hx login custom: store OpenAI-compat API key in auth.json
This commit is contained in:
1 parent
1952cb41c3
commit
9b9718e22e
3 files changed
+83
-18
No files matched your search
@@ -389,9 +389,15 @@ pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String {
|
|||||||
/// Interactive browser login. Prints the URL to stderr.
|
/// Interactive browser login. Prints the URL to stderr.
|
||||||
pub async fn login(k: Kind) -> Result<Credential> {
|
pub async fn login(k: Kind) -> Result<Credential> {
|
||||||
if k == Kind::Custom {
|
if k == Kind::Custom {
|
||||||
return Err(Error::Http(
|
let key = read_secret("API key for [openai_compat]: ")?;
|
||||||
"custom provider has no login: set [openai_compat] in config.toml".into(),
|
let cred = Credential {
|
||||||
));
|
access: key,
|
||||||
|
refresh: String::new(),
|
||||||
|
expires: u64::MAX,
|
||||||
|
account_id: None,
|
||||||
|
};
|
||||||
|
save(k, &cred)?;
|
||||||
|
return Ok(cred);
|
||||||
}
|
}
|
||||||
let c = cfg(k);
|
let c = cfg(k);
|
||||||
let (verifier, challenge) = pkce();
|
let (verifier, challenge) = pkce();
|
||||||
@@ -428,6 +434,37 @@ pub async fn login(k: Kind) -> Result<Credential> {
|
|||||||
Ok(cred)
|
Ok(cred)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One line from stdin, echo off when stdin is a terminal.
|
||||||
|
fn read_secret(prompt: &str) -> Result<String> {
|
||||||
|
use std::io::{BufRead, IsTerminal, Write};
|
||||||
|
let tty = std::io::stdin().is_terminal();
|
||||||
|
let stty = |arg| {
|
||||||
|
let _ = std::process::Command::new("stty").arg(arg).status();
|
||||||
|
};
|
||||||
|
eprint!("{prompt}");
|
||||||
|
let _ = std::io::stderr().flush();
|
||||||
|
if tty {
|
||||||
|
stty("-echo");
|
||||||
|
}
|
||||||
|
let mut s = String::new();
|
||||||
|
let r = std::io::stdin().lock().read_line(&mut s);
|
||||||
|
if tty {
|
||||||
|
stty("echo");
|
||||||
|
eprintln!();
|
||||||
|
}
|
||||||
|
r.map_err(|e| Error::Http(e.to_string()))?;
|
||||||
|
let s = s.trim().to_string();
|
||||||
|
if s.is_empty() {
|
||||||
|
return Err(Error::Http("empty key".into()));
|
||||||
|
}
|
||||||
|
Ok(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// API key saved by `hx login custom`.
|
||||||
|
pub fn stored_key() -> Option<String> {
|
||||||
|
load_store().remove(&Kind::Custom).map(|c| c.access)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn logout(k: Kind) -> Result<()> {
|
pub fn logout(k: Kind) -> Result<()> {
|
||||||
save_at(&store_path(), k, None)
|
save_at(&store_path(), k, None)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! OpenAI-compatible Chat Completions (Ollama, vLLM, LM Studio, llama.cpp, OpenRouter, ...).
|
//! OpenAI-compatible Chat Completions (Ollama, vLLM, LM Studio, llama.cpp, OpenRouter, ...).
|
||||||
//!
|
//!
|
||||||
//! No OAuth: the endpoint comes from `[openai_compat]` in config.toml, an optional bearer key
|
//! No OAuth: the endpoint comes from `[openai_compat]` in config.toml, an optional bearer key
|
||||||
//! from the env var named by `api_key_env`.
|
//! from the env var named by `api_key_env`, else the key saved by `hx login custom`.
|
||||||
|
|
||||||
use crate::auth::Kind;
|
use crate::auth::Kind;
|
||||||
use crate::models::ModelInfo;
|
use crate::models::ModelInfo;
|
||||||
@@ -36,17 +36,18 @@ pub struct OpenAiCompat {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl OpenAiCompat {
|
impl OpenAiCompat {
|
||||||
pub fn new(cfg: Config) -> Result<Self> {
|
/// Key: the `api_key_env` variable if set, else `stored` (from `hx login custom`), else none.
|
||||||
|
pub fn new(cfg: Config, stored: Option<String>) -> Result<Self> {
|
||||||
if cfg.base_url.is_empty() {
|
if cfg.base_url.is_empty() {
|
||||||
return Err(Error::Http("[openai_compat] needs base_url".into()));
|
return Err(Error::Http("[openai_compat] needs base_url".into()));
|
||||||
}
|
}
|
||||||
let key = match &cfg.api_key_env {
|
let env = cfg.api_key_env.as_ref().and_then(|n| std::env::var(n).ok());
|
||||||
Some(n) => Some(
|
if let (None, None, Some(n)) = (&env, &stored, &cfg.api_key_env) {
|
||||||
std::env::var(n)
|
return Err(Error::Http(format!(
|
||||||
.map_err(|_| Error::Http(format!("env var {n} (api_key_env) is not set")))?,
|
"env var {n} (api_key_env) is not set; or run `hx login custom`"
|
||||||
),
|
)));
|
||||||
None => None,
|
}
|
||||||
};
|
let key = env.or(stored);
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
cfg,
|
cfg,
|
||||||
key,
|
key,
|
||||||
@@ -524,10 +525,13 @@ mod tests {
|
|||||||
s.write_all(r.as_bytes()).await.unwrap();
|
s.write_all(r.as_bytes()).await.unwrap();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let p = OpenAiCompat::new(Config {
|
let p = OpenAiCompat::new(
|
||||||
base_url: format!("http://127.0.0.1:{port}/v1/"),
|
Config {
|
||||||
..Default::default()
|
base_url: format!("http://127.0.0.1:{port}/v1/"),
|
||||||
})
|
..Default::default()
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let ms = p.models().await.unwrap();
|
let ms = p.models().await.unwrap();
|
||||||
assert_eq!((ms[0].id.as_str(), ms[0].context_window), ("m1", 4096));
|
assert_eq!((ms[0].id.as_str(), ms[0].context_window), ("m1", 4096));
|
||||||
@@ -538,6 +542,30 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn key_precedence() {
|
||||||
|
let cfg = |env: Option<&str>| Config {
|
||||||
|
base_url: "http://x".into(),
|
||||||
|
api_key_env: env.map(Into::into),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let key = |c, s: Option<&str>| OpenAiCompat::new(c, s.map(Into::into)).map(|p| p.key);
|
||||||
|
assert_eq!(key(cfg(None), None).unwrap(), None);
|
||||||
|
assert_eq!(key(cfg(None), Some("s")).unwrap().as_deref(), Some("s"));
|
||||||
|
assert_eq!(
|
||||||
|
key(cfg(Some("PATH")), Some("s")).unwrap().as_deref(),
|
||||||
|
Some(std::env::var("PATH").unwrap().as_str()),
|
||||||
|
"env wins"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
key(cfg(Some("HX_NOPE_UNSET")), Some("s"))
|
||||||
|
.unwrap()
|
||||||
|
.as_deref(),
|
||||||
|
Some("s")
|
||||||
|
);
|
||||||
|
assert!(key(cfg(Some("HX_NOPE_UNSET")), None).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_models() {
|
fn parses_models() {
|
||||||
let v = json!({"data": [
|
let v = json!({"data": [
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ enum Mode {
|
|||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
enum Cmd {
|
enum Cmd {
|
||||||
/// Log in with a Claude Pro/Max or ChatGPT Plus/Pro subscription.
|
/// Log in with a Claude Pro/Max or ChatGPT Plus/Pro subscription; `custom` asks for an API key.
|
||||||
Login { provider: Kind },
|
Login { provider: Kind },
|
||||||
/// Remove stored credentials for a provider.
|
/// Remove stored credentials for a provider.
|
||||||
Logout { provider: Kind },
|
Logout { provider: Kind },
|
||||||
@@ -290,7 +290,7 @@ fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
|
|||||||
.get()
|
.get()
|
||||||
.cloned()
|
.cloned()
|
||||||
.ok_or_else(|| hx_ai::Error::Http("no [openai_compat] in config.toml".into()))?;
|
.ok_or_else(|| hx_ai::Error::Http("no [openai_compat] in config.toml".into()))?;
|
||||||
let c = hx_ai::openai_compat::OpenAiCompat::new(cfg)?;
|
let c = hx_ai::openai_compat::OpenAiCompat::new(cfg, hx_ai::auth::stored_key())?;
|
||||||
Arc::new(match std::env::var("HX_BASE_URL") {
|
Arc::new(match std::env::var("HX_BASE_URL") {
|
||||||
Ok(u) => c.with_base_url(u),
|
Ok(u) => c.with_base_url(u),
|
||||||
Err(_) => c,
|
Err(_) => c,
|
||||||
|
|||||||
Reference in new issue
Block a user