From 9b9718e22e26cd008cf31a4b70232846166a4da8 Mon Sep 17 00:00:00 2001 From: hermes Date: Wed, 7 Oct 2026 10:30:18 +0000 Subject: [PATCH] hx login custom: store OpenAI-compat API key in auth.json --- crates/hx-ai/src/auth.rs | 43 ++++++++++++++++++++++-- crates/hx-ai/src/openai_compat.rs | 54 +++++++++++++++++++++++-------- crates/hx-cli/src/main.rs | 4 +-- 3 files changed, 83 insertions(+), 18 deletions(-) diff --git a/crates/hx-ai/src/auth.rs b/crates/hx-ai/src/auth.rs index a409823..b5b42f5 100644 --- a/crates/hx-ai/src/auth.rs +++ b/crates/hx-ai/src/auth.rs @@ -389,9 +389,15 @@ pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String { /// Interactive browser login. Prints the URL to stderr. pub async fn login(k: Kind) -> Result { if k == Kind::Custom { - return Err(Error::Http( - "custom provider has no login: set [openai_compat] in config.toml".into(), - )); + let key = read_secret("API key for [openai_compat]: ")?; + 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 (verifier, challenge) = pkce(); @@ -428,6 +434,37 @@ pub async fn login(k: Kind) -> Result { Ok(cred) } +/// One line from stdin, echo off when stdin is a terminal. +fn read_secret(prompt: &str) -> Result { + 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 { + load_store().remove(&Kind::Custom).map(|c| c.access) +} + pub fn logout(k: Kind) -> Result<()> { save_at(&store_path(), k, None) } diff --git a/crates/hx-ai/src/openai_compat.rs b/crates/hx-ai/src/openai_compat.rs index 67ab84c..cd4a4c6 100644 --- a/crates/hx-ai/src/openai_compat.rs +++ b/crates/hx-ai/src/openai_compat.rs @@ -1,7 +1,7 @@ //! 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 -//! 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::models::ModelInfo; @@ -36,17 +36,18 @@ pub struct OpenAiCompat { } impl OpenAiCompat { - pub fn new(cfg: Config) -> Result { + /// Key: the `api_key_env` variable if set, else `stored` (from `hx login custom`), else none. + pub fn new(cfg: Config, stored: Option) -> Result { if cfg.base_url.is_empty() { return Err(Error::Http("[openai_compat] needs base_url".into())); } - let key = match &cfg.api_key_env { - Some(n) => Some( - std::env::var(n) - .map_err(|_| Error::Http(format!("env var {n} (api_key_env) is not set")))?, - ), - None => None, - }; + let env = cfg.api_key_env.as_ref().and_then(|n| std::env::var(n).ok()); + if let (None, None, Some(n)) = (&env, &stored, &cfg.api_key_env) { + return Err(Error::Http(format!( + "env var {n} (api_key_env) is not set; or run `hx login custom`" + ))); + } + let key = env.or(stored); Ok(Self { cfg, key, @@ -524,10 +525,13 @@ mod tests { s.write_all(r.as_bytes()).await.unwrap(); } }); - let p = OpenAiCompat::new(Config { - base_url: format!("http://127.0.0.1:{port}/v1/"), - ..Default::default() - }) + let p = OpenAiCompat::new( + Config { + base_url: format!("http://127.0.0.1:{port}/v1/"), + ..Default::default() + }, + None, + ) .unwrap(); let ms = p.models().await.unwrap(); 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] fn parses_models() { let v = json!({"data": [ diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index b91fcff..aad761c 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -53,7 +53,7 @@ enum Mode { #[derive(Subcommand)] 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 }, /// Remove stored credentials for a provider. Logout { provider: Kind }, @@ -290,7 +290,7 @@ fn provider(k: Kind) -> hx_ai::Result> { .get() .cloned() .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") { Ok(u) => c.with_base_url(u), Err(_) => c, -- 2.54.1