Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(auth): route OAuth wire handling by stored credentials
thinhlpgf85bdcb6beeb
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex b19784f92..75d25e243 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -418,9 +418,15 @@ pub(crate) async fn resolve_api_type_for_model(drop(pc);let api_type = cfg.as_ref().and_then(|c| c.api_type.clone())?;+ // OAuth account login is a `cli` feature; resolve the auth scheme from+ // the stored credential so a plain API key stays on its key scheme.+ #[cfg(feature = "cli")]let oauth = cfg- .map(|c| matches!(c.provider.as_str(), "openai" | "anthropic"))+ .as_ref()+ .map(|c| crate::core::cli::auth::account::has_oauth_credential(&c.provider)).unwrap_or(false);+ #[cfg(not(feature = "cli"))]+ let oauth = false;Some((api_type, oauth))}diff --git a/src-tauri/src/core/cli/auth/account.rs b/src-tauri/src/core/cli/auth/account.rsindex 825323e29..58e1b5b5f 100644--- a/src-tauri/src/core/cli/auth/account.rs+++ b/src-tauri/src/core/cli/auth/account.rs@@ -243,7 +243,7 @@ pub fn parse_manual_callback(raw: &str, expected_state: &str) -> Result<String,Ok(code.to_string())}-pub async fn accept_callback(+async fn accept_callback(listener: tokio::net::TcpListener,login: &AccountLogin,) -> Result<String, String> {@@ -272,7 +272,7 @@ pub async fn accept_callback(let response = if result.is_ok() {"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 71\r\nConnection: close\r\n\r\n<html><body>Sign-in completed. You can close this window.</body></html>"} else {- "HTTP/1.1 400 Bad Request\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 57\r\nConnection: close\r\n\r\n<html><body>Sign-in could not be verified.</body></html>"+ "HTTP/1.1 400 Bad Request\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 56\r\nConnection: close\r\n\r\n<html><body>Sign-in could not be verified.</body></html>"};let _ = stream.write_all(response.as_bytes()).await;result@@ -289,10 +289,6 @@ pub async fn bind_callback(login: &AccountLogin) -> Result<tokio::net::TcpListen.map_err(|_| "could not start the local sign-in callback".to_string())}-pub async fn wait_for_browser_callback(login: &AccountLogin) -> Result<String, String> {- let listener = bind_callback(login).await?;- accept_callback(listener, login).await-}fn token_request_body(login: &AccountLogin,@@ -335,7 +331,7 @@ fn refresh_request_body(.collect())}-pub async fn exchange(login: &AccountLogin, code: &str) -> Result<OAuthToken, String> {+async fn exchange(login: &AccountLogin, code: &str) -> Result<OAuthToken, String> {#[derive(serde::Deserialize)]struct TokenResponse {access_token: String,@@ -676,8 +672,10 @@ pub async fn access_token(provider: &str) -> Result<Option<String>, String> {return Ok(None);};let stored = CredentialStore::load(provider)?;- let Some(Credential::OAuthToken(token)) = stored else {- // No Jan-owned credential: alias Claude Code's token (Claude only).+ let Some(stored) = stored else {+ // No Jan-owned credential at all: alias Claude Code's token (Claude+ // only). A stored API key is a deliberate user choice and must not be+ // overridden by the Claude Code keychain token.if provider_kind == AccountProvider::Claude {if let Some(access) = claude_code_access_token().await {return Ok(Some(access));@@ -685,6 +683,10 @@ pub async fn access_token(provider: &str) -> Result<Option<String>, String> {}return Ok(None);};+ let Credential::OAuthToken(token) = stored else {+ // A stored API key is a deliberate choice; never substitute a token.+ return Ok(None);+ };let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|_| "could not read the system clock".to_string())?@@ -696,6 +698,20 @@ pub async fn access_token(provider: &str) -> Result<Option<String>, String> {}Ok(Some(token.access_token))}+/// Whether `provider` is authenticated with an OAuth account token rather+/// than a plain API key. This is the discriminator for selecting the OAuth+/// upstream wire scheme (Bearer + Code `?beta=true` headers): it must reflect+/// the stored credential, not merely that the provider supports account+/// login. `openai`/`anthropic` are also first-class API-key providers, so a+/// provider name alone is not enough to pick the OAuth scheme (a plain+/// `sk-ant-…` key must stay on `x-api-key` + `/messages`).+pub fn has_oauth_credential(provider: &str) -> bool {+ let Ok(Some(Credential::OAuthToken(_))) = CredentialStore::load(provider) else {+ return false;+ };+ true+}+pub fn store(provider: AccountProvider, token: &OAuthToken) -> Result<(), String> {CredentialStore::store(@@ -796,19 +812,6 @@ fn claude_plan_message(heavy_ok: bool, tier: Option<&str>) -> String {}-pub async fn complete_browser_login(login: AccountLogin) -> Result<AccountProvider, String> {- let listener = bind_callback(&login).await?;- complete_callback_login(listener, login).await-}--pub async fn complete_callback_login(- listener: tokio::net::TcpListener,- login: AccountLogin,-) -> Result<AccountProvider, String> {- let code = accept_callback(listener, &login).await?;- complete_code_login(login, code).await-}-pub async fn complete_callback_login_with_manual(listener: tokio::net::TcpListener,login: AccountLogin,@@ -1100,7 +1103,8 @@ mod tests {.await.unwrap();});- let result = complete_callback_login(listener, login).await;+ let code = accept_callback(listener, &login).await?;+ let result = complete_code_login(login, code).await;client.await.unwrap();result})@@ -1132,7 +1136,8 @@ mod tests {.await.unwrap();});- let result = complete_callback_login(listener, login).await;+ let code = accept_callback(listener, &login).await?;+ let result = complete_code_login(login, code).await;client.await.unwrap();result})diff --git a/src-tauri/src/core/cli/auth/mod.rs b/src-tauri/src/core/cli/auth/mod.rsindex 5eeeac65d..9bf7e730d 100644--- a/src-tauri/src/core/cli/auth/mod.rs+++ b/src-tauri/src/core/cli/auth/mod.rs@@ -34,27 +34,6 @@ pub struct ApiKeyMetadata {pub open_in_browser: bool,}-/// Grant type an issued Jan OAuth registration permits.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum OAuthGrant {- AuthorizationCodePkce,- DeviceCode,-}--/// Optional catalog metadata for a Jan-owned, provider-issued OAuth-/// registration. Account-login availability is intentionally mapped in-/// [`account::AccountProvider`]; do not infer login UI capabilities from this-/// placeholder metadata.-#[derive(Debug, Clone)]-pub struct OAuthRegistration {- pub client_id: &'static str,- pub authorization_url: &'static str,- pub token_url: &'static str,- pub scopes: &'static [&'static str],- pub grant: OAuthGrant,-}--/// Non-secret, typed description of one sign-in-able provider.#[derive(Debug, Clone)]pub struct ProviderDefinition {/// Provider id used in `~/.jan/config.toml` and in `<id>/<model>` ids.@@ -65,9 +44,6 @@ pub struct ProviderDefinition {pub default_base_url: String,pub transport: Transport,pub api_key: ApiKeyMetadata,- /// Optional non-secret OAuth metadata. This is not an account-login- /// capability switch; see [`account::AccountProvider`].- pub oauth: Option<OAuthRegistration>,}@@ -84,7 +60,6 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {hint: "get a key at platform.openai.com/account/api-keys",open_in_browser: false,},- oauth: None,},ProviderDefinition {id: "anthropic",@@ -96,7 +71,6 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {hint: "get a key at console.anthropic.com/settings/keys",open_in_browser: false,},- oauth: None,},ProviderDefinition {id: "opencode",@@ -108,7 +82,6 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {hint: "sign in at opencode.ai/auth to copy your OpenCode API key",open_in_browser: true,},- oauth: None,},ProviderDefinition {id: "deepseek",@@ -120,7 +93,6 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {hint: "get a key at platform.deepseek.com/api_keys",open_in_browser: false,},- oauth: None,},ProviderDefinition {id: "tokamak",@@ -132,7 +104,6 @@ pub fn provider_catalog() -> Vec<ProviderDefinition> {hint: "get a key at tokamak.sh/settings/api-keys",open_in_browser: false,},- oauth: None,},];catalog@@ -179,13 +150,6 @@ pub enum LoginError {mod tests {use super::*;- #[test]- fn catalog_has_no_oauth_registration_metadata_until_issued() {- for provider in provider_catalog() {- assert!(provider.oauth.is_none(), "{} must not invent OAuth metadata", provider.id);- }- }-#[test]fn catalog_lists_the_five_providers_in_picker_order() {let ids: Vec<&str> = provider_catalog().iter().map(|p| p.id).collect();diff --git a/src-tauri/src/core/cli/auth/providers.rs b/src-tauri/src/core/cli/auth/providers.rsindex 91f1d0fb6..e0f8dbb9b 100644--- a/src-tauri/src/core/cli/auth/providers.rs+++ b/src-tauri/src/core/cli/auth/providers.rs@@ -16,49 +16,42 @@ use super::{Credential, CredentialStore, LoginError, LoginResult, ProviderDefiniconst VERIFY_TIMEOUT: Duration = Duration::from_secs(20);-/// Validates and persists provider sign-ins. Stateless: callers construct one-/// per flow and share it across attempts.-pub struct LoginService;--impl LoginService {- /// Trim and reject a key before any I/O. A key with interior whitespace is- /// a mis-paste (partial selection, wrapped line) that would otherwise fail- /// as a confusing 401.- pub fn sanitize_key(raw: &str) -> Result<String, String> {- let key = raw.trim();- if key.is_empty() {- return Err("no API key entered".to_string());- }- if key.chars().any(char::is_whitespace) {- return Err("that key contains spaces or line breaks - copy it again".to_string());- }- Ok(key.to_string())+/// Trim and reject a key before any I/O. A key with interior whitespace is+/// a mis-paste (partial selection, wrapped line) that would otherwise fail+/// as a confusing 401.+pub fn sanitize_key(raw: &str) -> Result<String, String> {+ let key = raw.trim();+ if key.is_empty() {+ return Err("no API key entered".to_string());}-- /// Validate `raw_key` against the provider's model endpoint, then persist- /// the credential (secret store) and non-secret provider configuration.- /// Nothing is written when validation fails.- pub async fn login_with_api_key(- &self,- definition: &ProviderDefinition,- raw_key: &str,- ) -> Result<LoginResult, LoginError> {- let key = Self::sanitize_key(raw_key).map_err(LoginError::InvalidKey)?;- let models = discover_models(definition, &key, false).await?;- persist(definition, &key, &models)+ if key.chars().any(char::is_whitespace) {+ return Err("that key contains spaces or line breaks - copy it again".to_string());}+ Ok(key.to_string())+}- /// Remove the stored credential and the provider's non-secret- /// configuration entry. Missing entries are not an error.- pub fn logout(&self, provider: &str) -> Result<(), LoginError> {- CredentialStore::delete(provider).map_err(|e| {- LoginError::Persist(format!("could not clear the stored credential: {e}"))- })?;- remove_provider(provider).map_err(|e| {- LoginError::Persist(format!("could not clear the provider configuration: {e}"))- })?;- Ok(())- }+/// Validate `raw_key` against the provider's model endpoint, then persist+/// the credential (secret store) and non-secret provider configuration.+/// Nothing is written when validation fails.+pub async fn login_with_api_key(+ definition: &ProviderDefinition,+ raw_key: &str,+) -> Result<LoginResult, LoginError> {+ let key = sanitize_key(raw_key).map_err(LoginError::InvalidKey)?;+ let models = discover_models(definition, &key, false).await?;+ persist(definition, &key, &models)+}++/// Remove the stored credential and the provider's non-secret+/// configuration entry. Missing entries are not an error.+pub fn logout(provider: &str) -> Result<(), LoginError> {+ CredentialStore::delete(provider).map_err(|e| {+ LoginError::Persist(format!("could not clear the stored credential: {e}"))+ })?;+ remove_provider(provider).map_err(|e| {+ LoginError::Persist(format!("could not clear the provider configuration: {e}"))+ })?;+ Ok(())}pub(crate) async fn discover_models(@@ -423,7 +416,7 @@ mod tests {std::thread::spawn(move || {tokio::runtime::Runtime::new().unwrap()- .block_on(LoginService.login_with_api_key(&definition, &key))+ .block_on(login_with_api_key(&definition, &key))}).join().expect("verification thread must not panic")@@ -431,11 +424,11 @@ mod tests {#[test]fn sanitize_trims_and_rejects_unusable_input() {- assert_eq!(LoginService::sanitize_key(" sk-abc\n").unwrap(), "sk-abc");- assert!(LoginService::sanitize_key(" ").is_err());- assert!(LoginService::sanitize_key("").is_err());- assert!(LoginService::sanitize_key("sk-abc def").is_err());- assert!(LoginService::sanitize_key("sk-abc\ndef").is_err());+ assert_eq!(sanitize_key(" sk-abc\n").unwrap(), "sk-abc");+ assert!(sanitize_key(" ").is_err());+ assert!(sanitize_key("").is_err());+ assert!(sanitize_key("sk-abc def").is_err());+ assert!(sanitize_key("sk-abc\ndef").is_err());}#[test]@@ -508,9 +501,7 @@ mod tests {async fn rate_limited_key_maps_to_rate_limited_error() {let _tmp = TempSecrets::new();let endpoint = mock_server("429 Too Many Requests", "{}");- let result = LoginService- .login_with_api_key(&deepseek_at(endpoint), "sk-busy")- .await;+ let result = login_with_api_key(&deepseek_at(endpoint), "sk-busy").await;assert!(matches!(result, Err(LoginError::RateLimited)));}@@ -519,7 +510,7 @@ mod tests {let _tmp = TempSecrets::new();// Nothing listens on this port: connection refused.let def = deepseek_at("http://127.0.0.1:9/v1".to_string());- let result = LoginService.login_with_api_key(&def, "sk-x").await;+ let result = login_with_api_key(&def, "sk-x").await;assert!(matches!(result, Err(LoginError::Unavailable(_))));}@@ -568,11 +559,11 @@ mod tests {assert!(CredentialStore::load("deepseek").unwrap().is_some());assert!(load_global_config().unwrap().contains_key("deepseek"));- LoginService.logout("deepseek").unwrap();+ logout("deepseek").unwrap();assert!(CredentialStore::load("deepseek").unwrap().is_none());assert!(!load_global_config().unwrap().contains_key("deepseek"));// Logging out again is a no-op, not an error.- LoginService.logout("deepseek").unwrap();+ logout("deepseek").unwrap();});}diff --git a/src-tauri/src/core/cli/tokamak.rs b/src-tauri/src/core/cli/tokamak.rsindex fe5a4dda8..e1f719c2e 100644--- a/src-tauri/src/core/cli/tokamak.rs+++ b/src-tauri/src/core/cli/tokamak.rs@@ -40,7 +40,7 @@ pub struct Login {/// with interior whitespace is a mis-paste (partial selection, wrapped line)/// that would otherwise fail as a confusing 401.pub fn sanitize_key(raw: &str) -> Result<String, String> {- super::auth::providers::LoginService::sanitize_key(raw)+ super::auth::providers::sanitize_key(raw)}/// Verify `api_key` against Tokamak and return the model ids it grants accessdiff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex a87d1116a..64340fc61 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -6291,8 +6291,7 @@ async fn chat_loop<B: Backend>("selected provider is unavailable".to_string(),)})?;- crate::core::cli::auth::providers::LoginService- .login_with_api_key(&definition, &key)+ crate::core::cli::auth::providers::login_with_api_key(&definition, &key).await}));}@@ -6960,7 +6959,7 @@ fn handle_login_key(app: &mut App, key: KeyEvent, ctrl: bool) {}match key.code {KeyCode::Enter => {- match crate::core::cli::auth::providers::LoginService::sanitize_key(&prompt.input) {+ match crate::core::cli::auth::providers::sanitize_key(&prompt.input) {Ok(key) => {prompt.verifying = true;prompt.error = None;@@ -9933,7 +9932,7 @@ fn logout_command(app: &mut App, provider: &str) {.ok().and_then(|configs| configs.get(provider).cloned()).is_some_and(|config| config.models.iter().any(|model| model == &app.model));- match crate::core::cli::auth::providers::LoginService.logout(provider) {+ match crate::core::cli::auth::providers::logout(provider) {Ok(()) => {if owned_model {app.set_model(String::new());@@ -11547,7 +11546,11 @@ fn draw_login(f: &mut Frame, area: ratatui::layout::Rect, prompt: &LoginPrompt).borders(Borders::ALL).border_style(Style::new().cyan()).title(Span::styled(- " tokamak sign-in ",+ format!(+ " {} sign-in ",+ crate::core::cli::auth::provider_by_id(&prompt.provider)+ .map_or("provider", |definition| definition.name)+ ),Style::new().on_cyan().black().bold(),));@@ -13894,6 +13897,7 @@ mod tests {let error = "verification failed: the upstream returned 502 Bad Gateway \from https://api.tokamak.sh/v1/models after three attempts";app.login = Some(super::LoginPrompt {+ provider: "tokamak".to_string(),input: String::new(),error: Some(error.to_string()),verifying: false,diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rsindex de1643551..5095302c6 100644--- a/src-tauri/src/core/server/proxy.rs+++ b/src-tauri/src/core/server/proxy.rs@@ -1589,15 +1589,22 @@ async fn proxy_request(if let Some(provider_cfg) = provider_config {// A converter only applies to chat/completions; other- // paths keep verbatim forwarding. The credential is- // an OAuth account token when the provider is one of- // Jan's account credential providers (openai/anthropic),- // which selects the Anthropic OAuth auth scheme.+ // paths keep verbatim forwarding. The OAuth auth+ // scheme applies only when the provider is actually+ // authenticated with an OAuth account token, not+ // merely because openai/anthropic also support+ // account login (an API-key sign-in must stay on+ // its plain key scheme).let converter = if destination_path == "/chat/completions" {- let oauth = matches!(- provider_cfg.provider.as_str(),- "openai" | "anthropic"- );+ // OAuth account login is a `cli` feature; the+ // desktop has no OAuth account token here, so it+ // must keep the plain API-key scheme rather than+ // treat every anthropic provider as an account.+ #[cfg(feature = "cli")]+ let oauth = crate::core::cli::auth::account::+ has_oauth_credential(&provider_cfg.provider);+ #[cfg(not(feature = "cli"))]+ let oauth = false;converter_for(provider_cfg.api_type.as_deref(), oauth)} else {None