Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-cli): add secure login credentials
thinhlpg1a5a97e5bdee
diff --git a/src-tauri/src/core/cli/auth/credentials.rs b/src-tauri/src/core/cli/auth/credentials.rsnew file mode 100644index 000000000..2910731fa--- /dev/null+++ b/src-tauri/src/core/cli/auth/credentials.rs@@ -0,0 +1,198 @@+//! Versioned credential records persisted through the shared secret store+//! (`provider_secrets`: OS keyring first, encrypted permission-restricted file+//! fallback). A credential is the only thing that knows a key or token; the+//! provider catalog and provider configuration never do.++use serde::{Deserialize, Serialize};++use crate::core::server::provider_secrets;++/// Credential record format version; bump on any breaking shape change.+const CREDENTIAL_VERSION: u32 = 1;++/// What a provider account is authenticated with. Stored only as a versioned+/// record under `auth:<provider>`; never in config, logs, or transcripts.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", content = "value", rename_all = "snake_case")]+pub enum Credential {+ ApiKey(String),+ OAuthToken(OAuthToken),+}++impl Credential {+ /// The API key, when this credential is a plain key.+ pub fn as_api_key(&self) -> Option<&str> {+ match self {+ Credential::ApiKey(key) => Some(key.as_str()),+ Credential::OAuthToken(_) => None,+ }+ }++ /// The OAuth token bundle, when this credential is an account login.+ pub fn as_oauth(&self) -> Option<&OAuthToken> {+ match self {+ Credential::ApiKey(_) => None,+ Credential::OAuthToken(token) => Some(token),+ }+ }+}++/// An OAuth access token plus the fields needed to refresh it.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct OAuthToken {+ pub access_token: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub refresh_token: Option<String>,+ /// Unix seconds at which the access token expires; `None` when unknown.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub expires_at: Option<i64>,+ pub token_type: String,+ #[serde(default)]+ pub scopes: Vec<String>,+}++/// Read/write versioned credential records under `auth:<provider>` in the+/// shared secret store. Has no TUI or HTTP dependency, so any caller can use+/// it without pulling in presentation concerns.+pub struct CredentialStore;++impl CredentialStore {+ /// Replace the stored credential for `provider`. An empty record never+ /// exists: `store` with a value that serializes to nothing is rejected.+ pub fn store(provider: &str, credential: &Credential) -> Result<(), String> {+ let record = serde_json::json!({+ "version": CREDENTIAL_VERSION,+ "credential": credential,+ });+ let raw = record.to_string();+ if raw.is_empty() {+ return Err("credential record serialized to nothing".to_string());+ }+ provider_secrets::store_secret_record(&secret_key(provider), &raw)+ }++ /// The stored credential for `provider`, or `None`. A record with an+ /// unknown version or an unparsable body is treated as absent rather than+ /// surfaced, so a future format change degrades to "please sign in again".+ pub fn load(provider: &str) -> Result<Option<Credential>, String> {+ let Some(raw) = provider_secrets::load_secret_record(&secret_key(provider)) else {+ return Ok(None);+ };+ let parsed: serde_json::Value =+ serde_json::from_str(&raw).map_err(|e| format!("stored credential is unreadable: {e}"))?;+ if parsed.get("version").and_then(|v| v.as_u64()) != Some(CREDENTIAL_VERSION as u64) {+ return Ok(None);+ }+ let body = parsed.get("credential").cloned().unwrap_or(serde_json::Value::Null);+ serde_json::from_value(body)+ .map(Some)+ .map_err(|e| format!("stored credential is unreadable: {e}"))+ }++ /// Remove the stored credential for `provider`. Missing entries are not an+ /// error.+ pub fn delete(provider: &str) -> Result<(), String> {+ provider_secrets::delete_secret_record(&secret_key(provider))+ }+}++fn secret_key(provider: &str) -> String {+ format!("auth:{provider}")+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::Mutex;++ /// `provider_secrets` reads process-wide env and a latched keyring flag, so+ /// tests that redirect them must not run concurrently.+ static ENV_LOCK: Mutex<()> = Mutex::new(());++ struct TempSecrets {+ _guard: std::sync::MutexGuard<'static, ()>,+ prev_data_folder: Option<String>,+ _dir: tempfile::TempDir,+ }++ impl TempSecrets {+ fn new() -> Self {+ let guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let dir = tempfile::tempdir().unwrap();+ let prev_data_folder = std::env::var("JAN_DATA_FOLDER").ok();+ std::env::set_var("JAN_DATA_FOLDER", dir.path());+ crate::core::server::provider_secrets::force_file_secrets();+ Self {+ _guard: guard,+ prev_data_folder,+ _dir: dir,+ }+ }+ }++ impl Drop for TempSecrets {+ fn drop(&mut self) {+ match &self.prev_data_folder {+ Some(v) => std::env::set_var("JAN_DATA_FOLDER", v),+ None => std::env::remove_var("JAN_DATA_FOLDER"),+ }+ }+ }++ fn oauth_credential() -> Credential {+ Credential::OAuthToken(OAuthToken {+ access_token: "access".into(),+ refresh_token: Some("refresh".into()),+ expires_at: Some(1_800_000_000),+ token_type: "Bearer".into(),+ scopes: vec!["model.read".into()],+ })+ }++ #[test]+ fn credential_store_roundtrips_oauth_without_provider_config() {+ let _tmp = TempSecrets::new();+ let credential = oauth_credential();+ CredentialStore::store("openai", &credential).unwrap();+ assert_eq!(CredentialStore::load("openai").unwrap(), Some(credential));+ }++ #[test]+ fn credential_store_roundtrips_and_deletes_api_key() {+ let _tmp = TempSecrets::new();+ let credential = Credential::ApiKey("sk-live".into());+ CredentialStore::store("deepseek", &credential).unwrap();+ assert_eq!(CredentialStore::load("deepseek").unwrap(), Some(credential));++ CredentialStore::delete("deepseek").unwrap();+ assert_eq!(CredentialStore::load("deepseek").unwrap(), None);+ // Deleting one provider never touches another's record.+ assert_eq!(CredentialStore::load("openai").unwrap(), None);+ }++ #[test]+ fn load_missing_provider_is_none_and_delete_is_idempotent() {+ let _tmp = TempSecrets::new();+ assert_eq!(CredentialStore::load("anthropic").unwrap(), None);+ assert!(CredentialStore::delete("anthropic").is_ok());+ }++ #[test]+ fn provider_records_are_namespaced_away_from_key_chains() {+ let _tmp = TempSecrets::new();+ // A legacy provider key chain and a login credential share a provider+ // name but must not collide on storage.+ crate::core::server::provider_secrets::store_provider_keys(+ "openai",+ &["sk-legacy".to_string()],+ )+ .unwrap();+ let credential = Credential::ApiKey("sk-login".into());+ CredentialStore::store("openai", &credential).unwrap();+ assert_eq!(CredentialStore::load("openai").unwrap(), Some(credential));+ assert_eq!(+ crate::core::server::provider_secrets::load_provider_keys("openai"),+ vec!["sk-legacy".to_string()]+ );+ }+}diff --git a/src-tauri/src/core/cli/auth/mod.rs b/src-tauri/src/core/cli/auth/mod.rsnew file mode 100644index 000000000..8afa6f5cc--- /dev/null+++ b/src-tauri/src/core/cli/auth/mod.rs@@ -0,0 +1,229 @@+//! Provider authentication for the CLI: a typed capability catalog, credential+//! contracts, and (in submodules) API-key validation, registered OAuth flows,+//! and secure persistence. This module is the security boundary between what a+//! user can sign in with and what the agent runtime trusts.+//!+//! Capability metadata is non-secret by construction: keys, tokens, and+//! verifier/state values never live here. They move through+//! [`crate::core::server::provider_secrets`] only.++pub mod credentials;++use std::path::PathBuf;++pub use credentials::{Credential, CredentialStore, OAuthToken};++/// Wire transport a provider speaks, chosen at credential resolution.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Transport {+ OpenAi,+ Anthropic,+}++/// How a user can authenticate with a provider.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AuthMethod {+ ApiKey,+ AccountOAuth,+}++/// Non-secret guidance for minting an API key.+#[derive(Debug, Clone)]+pub struct ApiKeyMetadata {+ /// Human-facing page where the user creates/views keys.+ pub keys_url: &'static str,+ /// Short hint shown above the masked input.+ pub hint: &'static str,+}++/// Grant type an issued Jan OAuth registration permits.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OAuthGrant {+ AuthorizationCodePkce,+ DeviceCode,+}++/// A Jan-owned, provider-issued OAuth registration. `provider_catalog()` keeps+/// this `None` for every provider until Jan actually holds an issued+/// registration with an approved redirect URI and permitted scopes; that is+/// the single gate deciding whether "Sign in with account" is offered.+#[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.+ pub id: &'static str,+ /// Display name shown in pickers.+ pub name: &'static str,+ /// Default API endpoint (an OpenAI-compatible root or the Anthropic `/v1`).+ pub default_base_url: &'static str,+ pub transport: Transport,+ pub api_key: ApiKeyMetadata,+ /// `None` means account login is NOT offered. This is a security boundary,+ /// not a disabled control: a missing registration hides the method.+ pub oauth: Option<OAuthRegistration>,+}++impl ProviderDefinition {+ /// The authentication methods this provider may offer, in display order.+ /// Account login appears only when an issued Jan registration exists.+ pub fn available_methods(&self) -> Vec<AuthMethod> {+ let mut methods = vec![AuthMethod::ApiKey];+ if self.oauth.is_some() {+ methods.push(AuthMethod::AccountOAuth);+ }+ methods+ }+}++/// The providers the TUI `/login` flow offers, in picker order.+pub fn provider_catalog() -> &'static [ProviderDefinition] {+ &CATALOG+}++static CATALOG: [ProviderDefinition; 5] = [+ ProviderDefinition {+ id: "openai",+ name: "Codex",+ default_base_url: "https://api.openai.com/v1",+ transport: Transport::OpenAi,+ api_key: ApiKeyMetadata {+ keys_url: "https://platform.openai.com/account/api-keys",+ hint: "get a key at platform.openai.com/account/api-keys",+ },+ oauth: None,+ },+ ProviderDefinition {+ id: "anthropic",+ name: "Claude",+ default_base_url: "https://api.anthropic.com/v1",+ transport: Transport::Anthropic,+ api_key: ApiKeyMetadata {+ keys_url: "https://console.anthropic.com/settings/keys",+ hint: "get a key at console.anthropic.com/settings/keys",+ },+ oauth: None,+ },+ ProviderDefinition {+ id: "opencode",+ name: "OpenCode",+ default_base_url: "https://opencode.ai/zen/v1",+ transport: Transport::OpenAi,+ api_key: ApiKeyMetadata {+ keys_url: "https://opencode.ai/docs",+ hint: "see opencode.ai/docs for how to get a key",+ },+ oauth: None,+ },+ ProviderDefinition {+ id: "deepseek",+ name: "DeepSeek",+ default_base_url: "https://api.deepseek.com/v1",+ transport: Transport::OpenAi,+ api_key: ApiKeyMetadata {+ keys_url: "https://platform.deepseek.com/api_keys",+ hint: "get a key at platform.deepseek.com/api_keys",+ },+ oauth: None,+ },+ ProviderDefinition {+ id: "tokamak",+ name: "Tokamak",+ default_base_url: "https://api.tokamak.sh/v1",+ transport: Transport::OpenAi,+ api_key: ApiKeyMetadata {+ keys_url: "https://tokamak.sh/settings/api-keys",+ hint: "get a key at tokamak.sh/settings/api-keys",+ },+ oauth: None,+ },+];++/// The catalog entry for `id`, if any.+pub fn provider_by_id(id: &str) -> Option<&'static ProviderDefinition> {+ provider_catalog().iter().find(|p| p.id == id)+}++/// Non-secret outcome of a successful login, safe to render and report.+#[derive(Debug, Clone, PartialEq)]+pub struct LoginResult {+ pub provider: String,+ pub models: Vec<String>,+ /// Where the non-secret provider configuration was written.+ pub config_path: PathBuf,+ /// The model adopted as `default_model`, or `None` when the user already+ /// had one (or the account has no models).+ pub default_model: Option<String>,+}++/// Why a login attempt failed. Every variant carries only safe, non-secret+/// text; errors never include the credential.+#[derive(Debug, Clone, PartialEq)]+pub enum LoginError {+ /// The entered key is empty or malformed; retryable without I/O.+ InvalidKey(String),+ /// The provider rejected the credential (HTTP 401/403).+ Unauthorized,+ /// The provider is rate limiting this credential (HTTP 429).+ RateLimited,+ /// Network, protocol, or provider 5xx failure, with a safe message.+ Unavailable(String),+ /// A validated credential could not be persisted; nothing was changed.+ Persist(String),+ /// The OAuth interaction failed; no credential was persisted.+ OAuth(String),+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn catalog_hides_account_login_without_an_issued_registration() {+ let catalog = provider_catalog();+ let claude = catalog.iter().find(|p| p.id == "anthropic").unwrap();+ assert_eq!(claude.available_methods(), vec![AuthMethod::ApiKey]);+ // No production entry carries a registration until Jan holds one.+ for provider in catalog {+ assert!(provider.oauth.is_none(), "{} must not offer OAuth", provider.id);+ assert_eq!(+ provider.available_methods(),+ vec![AuthMethod::ApiKey],+ "{} must offer API key only",+ provider.id+ );+ }+ }++ #[test]+ fn catalog_lists_the_five_providers_in_picker_order() {+ let ids: Vec<&str> = provider_catalog().iter().map(|p| p.id).collect();+ assert_eq!(+ ids,+ vec!["openai", "anthropic", "opencode", "deepseek", "tokamak"]+ );+ assert_eq!(provider_by_id("deepseek").unwrap().name, "DeepSeek");+ assert!(provider_by_id("nope").is_none());+ }++ #[test]+ fn available_methods_includes_account_login_when_registered() {+ let mut provider = provider_catalog()[0].clone();+ provider.oauth = Some(OAuthRegistration {+ client_id: "jan-test",+ authorization_url: "https://auth.example.com/authorize",+ token_url: "https://auth.example.com/token",+ scopes: &["model.read"],+ grant: OAuthGrant::AuthorizationCodePkce,+ });+ assert_eq!(provider.available_methods(), vec![AuthMethod::ApiKey, AuthMethod::AccountOAuth]);+ }+}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 31f51ebb8..d72cfc383 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -2,6 +2,7 @@//!//! This module is only compiled when the `cli` feature is enabled.+pub mod auth;pub mod brand;pub mod journal;pub mod login;diff --git a/src-tauri/src/core/server/provider_secrets.rs b/src-tauri/src/core/server/provider_secrets.rsindex 5d2f1b9bd..ba0a87386 100644--- a/src-tauri/src/core/server/provider_secrets.rs+++ b/src-tauri/src/core/server/provider_secrets.rs@@ -232,6 +232,32 @@ pub async fn set_secret(key: String, value: String) -> Result<(), String> {.map_err(|e| e.to_string())?}+/// Store (or replace) one opaque secret record under `key` (namespaced+/// `auth:<key>` so it can never collide with a provider key chain). Used for+/// versioned login credential bundles; empty values delete the entry.+pub fn store_secret_record(key: &str, value: &str) -> Result<(), String> {+ store_provider_keys(&format!("auth:{key}"), &[value.to_string()])+}++/// Read a secret record stored via [`store_secret_record`]. `None` when absent.+pub fn load_secret_record(key: &str) -> Option<String> {+ load_provider_keys(&format!("auth:{key}")).into_iter().next()+}++/// Remove a secret record stored via [`store_secret_record`]. Missing entries+/// are not an error.+pub fn delete_secret_record(key: &str) -> Result<(), String> {+ delete_provider_keys(&format!("auth:{key}"))+}++/// Force the encrypted-file fallback for the rest of the process. Test-only:+/// lets unit tests exercise the file path without touching the developer's+/// keychain.+#[cfg(test)]+pub(crate) fn force_file_secrets() {+ KEYRING_DOWN.store(true, Ordering::Relaxed);+}+/// Read a single generic secret stored via `set_secret`. None when absent.#[cfg(not(feature = "cli"))]#[tauri::command]