Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cli): browser-approval sign-in for jan login and /login (#8761)

Akarshan Biswasda638d64c646
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index ffa996787..fbf799b8c 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -10,8 +10,8 @@ use console::Style;
// Import the library crate so we can access core modules.
// The lib target is named "app_lib" (see [lib] section in Cargo.toml).
use app_lib::core::agent::plugins::InstalledPlugin;
-use app_lib::core::cli::providers::{load_provider_configs, ProviderOverrides};
use app_lib::core::cli::mcp::{self, split_kv, McpServerEntry};
+use app_lib::core::cli::providers::{load_provider_configs, ProviderOverrides};
use app_lib::core::cli::run_report::OutputFormat;
use app_lib::core::cli::{
cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,
@@ -158,21 +158,31 @@ enum Commands {
},
/// Sign in to Tokamak and save the API key to ~/.jan/config.toml
#[command(display_order = 2)]
- Login,
- /// Manage provider credentials in ~/.jan/config.toml (used by the TUI and CLI)
+ Login {
+ /// Skip the browser approval and paste an API key instead (the legacy flow)
+ #[arg(long)]
+ paste_token: bool,
+ },
+ /// Show or manage the Tokamak sign-in
#[command(display_order = 3)]
+ Auth {
+ #[command(subcommand)]
+ cmd: AuthCommands,
+ },
+ /// Manage provider credentials in ~/.jan/config.toml (used by the TUI and CLI)
+ #[command(display_order = 4)]
Config {
#[command(subcommand)]
cmd: AgentConfigCommands,
},
/// Manage project-local plugins and their skills
- #[command(display_order = 4)]
+ #[command(display_order = 5)]
Plugin {
#[command(subcommand)]
cmd: PluginCommands,
},
/// Update this binary to the latest build of the channel it was built for
- #[command(display_order = 5)]
+ #[command(display_order = 6)]
Update {
/// Report whether an update exists without installing it
#[arg(long)]
@@ -183,6 +193,16 @@ enum Commands {
},
}
+/// Tokamak sign-in inspection and control.
+#[derive(Subcommand)]
+enum AuthCommands {
+ /// Show the current sign-in: account, endpoint, key id and expiry, plus a
+ /// live validity check against the upstream
+ Status,
+ /// Sign out: revoke the stored key server-side and clear the local entry.
+ Logout,
+}
+
#[derive(Subcommand)]
enum PluginCommands {
/// List plugins installed in a project
@@ -539,8 +559,14 @@ async fn main() {
match command {
Commands::Cli { cmd } => handle_cli(cmd).await,
- Commands::Login => {
- if let Err(e) = app_lib::core::cli::login::run_login().await {
+ Commands::Login { paste_token } => {
+ if let Err(e) = app_lib::core::cli::login::run_login(paste_token).await {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ }
+ Commands::Auth { cmd } => {
+ if let Err(e) = handle_auth(cmd).await {
eprintln!("Error: {e}");
std::process::exit(1);
}
@@ -590,34 +616,35 @@ async fn handle_update(check: bool, force: bool) {
}
async fn handle_plugin(cmd: PluginCommands) {
- let result = match cmd {
- PluginCommands::List { project, json } => {
- let plugins = cli_plugin_list(&project);
- if json {
- println!("{}", serde_json::to_string_pretty(&plugins).unwrap());
- } else {
- print!("{}", format_plugin_list(&plugins));
+ let result =
+ match cmd {
+ PluginCommands::List { project, json } => {
+ let plugins = cli_plugin_list(&project);
+ if json {
+ println!("{}", serde_json::to_string_pretty(&plugins).unwrap());
+ } else {
+ print!("{}", format_plugin_list(&plugins));
+ }
+ Ok(())
}
- Ok(())
- }
- PluginCommands::Install { spec, project } => cli_plugin_install(&project, &spec)
- .await
- .map(|plugins| match plugins.as_slice() {
- // A single install keeps the original JSON-object output so
- // existing scripts parsing it are unaffected; a batch install
- // (plugin collection) prints the JSON array.
- [plugin] => println!("{}", serde_json::to_string_pretty(plugin).unwrap()),
- many => println!("{}", serde_json::to_string_pretty(many).unwrap()),
- }),
- PluginCommands::Remove { name, project } => {
- cli_plugin_remove(&project, &name).map(|()| println!("Removed plugin '{name}'"))
- }
- PluginCommands::Search { query, project } => {
- cli_plugin_search(&project, query.as_deref().unwrap_or(""))
+ PluginCommands::Install { spec, project } => cli_plugin_install(&project, &spec)
.await
- .map(|entries| println!("{}", serde_json::to_string_pretty(&entries).unwrap()))
- }
- };
+ .map(|plugins| match plugins.as_slice() {
+ // A single install keeps the original JSON-object output so
+ // existing scripts parsing it are unaffected; a batch install
+ // (plugin collection) prints the JSON array.
+ [plugin] => println!("{}", serde_json::to_string_pretty(plugin).unwrap()),
+ many => println!("{}", serde_json::to_string_pretty(many).unwrap()),
+ }),
+ PluginCommands::Remove { name, project } => {
+ cli_plugin_remove(&project, &name).map(|()| println!("Removed plugin '{name}'"))
+ }
+ PluginCommands::Search { query, project } => {
+ cli_plugin_search(&project, query.as_deref().unwrap_or(""))
+ .await
+ .map(|entries| println!("{}", serde_json::to_string_pretty(&entries).unwrap()))
+ }
+ };
if let Err(e) = result {
eprintln!("Error: {e}");
std::process::exit(1);
@@ -760,6 +787,70 @@ async fn handle_agent(cmd: AgentCommands) {
}
}
+/// `jan auth` handler: report sign-in state or sign out.
+async fn handle_auth(cmd: AuthCommands) -> Result<(), String> {
+ use app_lib::core::cli::tokamak;
+ match cmd {
+ AuthCommands::Status => {
+ let status = tokamak::auth_status();
+ if !status.signed_in {
+ println!("Not signed in to Tokamak. Run `jan login`.");
+ return Ok(());
+ }
+ println!("Signed in to Tokamak");
+ match &status.account {
+ Some(account) => println!(" account: {account}"),
+ // A legacy paste login never learns the account; that is not the
+ // same as failing to look one up.
+ None => println!(" account: not recorded"),
+ }
+ println!(" endpoint: {}", status.endpoint);
+ if let Some(key_id) = &status.key_id {
+ println!(" key id: {key_id}");
+ }
+ match status.key_expires_at {
+ Some(ts) if ts != 0 => println!(" key expires: {}", format_ts(ts)),
+ // A legacy paste login records no expiry; that is not the same
+ // as a key that never expires, so don't claim it does.
+ _ => println!(" key expires: not recorded"),
+ }
+ match tokamak::live_valid().await {
+ Some(true) => println!(" valid: yes"),
+ Some(false) => println!(" valid: no (re-run `jan login`)"),
+ None => println!(" valid: could not reach upstream"),
+ }
+ if let Some(warning) = tokamak::expiry_warning() {
+ println!();
+ println!("Warning: {warning}");
+ }
+ Ok(())
+ }
+ AuthCommands::Logout => {
+ match tokamak::logout().await? {
+ tokamak::Logout::ClearedAndRevoked => {
+ println!("Signed out of Tokamak (key revoked).")
+ }
+ tokamak::Logout::ClearedOnly => println!(
+ "Signed out of Tokamak locally. The key could not be revoked upstream - \
+ remove it at {}",
+ tokamak::API_KEYS_URL
+ ),
+ tokamak::Logout::NothingToDo => println!("Not signed in to Tokamak."),
+ }
+ Ok(())
+ }
+ }
+}
+
+/// Render a unix timestamp as a UTC date/time for `auth status`.
+fn format_ts(ts: u64) -> String {
+ let secs = i64::try_from(ts).unwrap_or(0);
+ match chrono::DateTime::from_timestamp(secs, 0) {
+ Some(dt) => dt.format("%Y-%m-%d %H:%M UTC").to_string(),
+ None => format!("unix {ts}"),
+ }
+}
+
fn handle_agent_config(cmd: AgentConfigCommands) -> Result<(), String> {
match cmd {
AgentConfigCommands::Set {
@@ -890,10 +981,8 @@ fn mcp_list_entry(entry: &McpServerEntry, show_secrets: bool) -> serde_json::Val
let redact_map = |m: Option<&serde_json::Map<String, serde_json::Value>>| -> serde_json::Value {
match m {
Some(map) => {
- let out: serde_json::Map<String, serde_json::Value> = map
- .iter()
- .map(|(k, v)| (k.clone(), redact(v)))
- .collect();
+ let out: serde_json::Map<String, serde_json::Value> =
+ map.iter().map(|(k, v)| (k.clone(), redact(v))).collect();
serde_json::Value::Object(out)
}
None => serde_json::json!({}),
@@ -1083,16 +1172,48 @@ mod tests {
#[test]
fn login_command_parses_and_takes_no_args() {
let cli = Cli::parse_from(["jan", "login"]);
- assert!(matches!(cli.command, Some(Commands::Login)));
+ assert!(matches!(
+ cli.command,
+ Some(Commands::Login { paste_token: false })
+ ));
assert!(Cli::try_parse_from(["jan", "login", "sk-key"]).is_err());
}
+ #[test]
+ fn login_command_accepts_paste_token_flag() {
+ let cli = Cli::parse_from(["jan", "login", "--paste-token"]);
+ assert!(matches!(
+ cli.command,
+ Some(Commands::Login { paste_token: true })
+ ));
+ }
+
+ #[test]
+ fn auth_subcommands_parse() {
+ let cli = Cli::parse_from(["jan", "auth", "status"]);
+ assert!(matches!(
+ cli.command,
+ Some(Commands::Auth {
+ cmd: AuthCommands::Status
+ })
+ ));
+ let cli = Cli::parse_from(["jan", "auth", "logout"]);
+ assert!(matches!(
+ cli.command,
+ Some(Commands::Auth {
+ cmd: AuthCommands::Logout
+ })
+ ));
+ }
+
/// Parse a `jan cli mcp <cmd> <extra...>` argv and pull out the subcommand.
fn parsed_mcp(extra: &[&str]) -> McpCommands {
let mut argv = vec!["jan", "cli", "mcp"];
argv.extend_from_slice(extra);
match Cli::parse_from(argv).command {
- Some(Commands::Cli { cmd: CliCommands::Mcp { cmd } }) => cmd,
+ Some(Commands::Cli {
+ cmd: CliCommands::Mcp { cmd },
+ }) => cmd,
_ => panic!("expected `cli mcp`"),
}
}
@@ -1100,7 +1221,12 @@ mod tests {
#[test]
fn mcp_list_parses_and_redacts_by_default() {
let cmd = parsed_mcp(&["list"]);
- assert!(matches!(cmd, McpCommands::List { show_secrets: false }));
+ assert!(matches!(
+ cmd,
+ McpCommands::List {
+ show_secrets: false
+ }
+ ));
let cmd = parsed_mcp(&["list", "--show-secrets"]);
assert!(matches!(cmd, McpCommands::List { show_secrets: true }));
}
@@ -1187,11 +1313,14 @@ mod tests {
cmd: PluginCommands::List { json, .. }
}) if json
));
-}
+ }
#[test]
fn split_kv_rejects_without_separator() {
- assert_eq!(split_kv("K=V", "env").unwrap(), ("K".to_string(), "V".to_string()));
+ assert_eq!(
+ split_kv("K=V", "env").unwrap(),
+ ("K".to_string(), "V".to_string())
+ );
assert!(split_kv("novalue", "env").is_err());
assert!(split_kv("=V", "header").is_err());
}
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index e40f96866..9b93117b2 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -105,6 +105,19 @@ struct GlobalProviderEntry {
models: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
api_type: Option<String>,
+ /// Server-assigned id of the key, so a logout can revoke the exact key the
+ /// CLI holds rather than a user's other keys.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ key_id: Option<String>,
+ /// Unix seconds the key expires at, when the server says. Lets the CLI warn
+ /// (and show auth status) without a 401 first.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ key_expires_at: Option<u64>,
+ /// Who the key belongs to, as reported when it was minted. Recorded so
+ /// `auth status` can name the account without a round trip (and without
+ /// guessing an identity endpoint's response shape).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ account: Option<String>,
}
/// Fields to update on a provider entry via [`set_provider`]. `None` leaves the
@@ -118,6 +131,14 @@ pub(crate) struct ProviderUpdate {
/// `Some(vec)` replaces the model list; `Some(empty)` clears it.
pub models: Option<Vec<String>>,
pub api_type: Option<String>,
+ /// Server-assigned key metadata a browser sign-in gets back. Doubly
+ /// optional on purpose: `None` leaves whatever is stored alone (the merge
+ /// semantics above), while `Some(None)` clears it -- which is what a login
+ /// that learned no metadata has to do, so a stale id from a previous key
+ /// cannot outlive it.
+ pub key_id: Option<Option<String>>,
+ pub key_expires_at: Option<Option<u64>>,
+ pub account: Option<Option<String>>,
}
/// `~/.jan`, the user-wide config directory.
@@ -273,9 +294,8 @@ pub(crate) fn wave_len(glyph: &str) -> usize {
/// key being absent, which takes the default.
pub(crate) fn wave_error(glyph: &str) -> Option<String> {
let len = wave_len(glyph);
- (len > WAVE_MAX_GRAPHEMES).then(|| {
- format!("at most {WAVE_MAX_GRAPHEMES} characters (got {len})")
- })
+ (len > WAVE_MAX_GRAPHEMES)
+ .then(|| format!("at most {WAVE_MAX_GRAPHEMES} characters (got {len})"))
}
/// The glyph to sweep along the working row (`wave` in `~/.jan/config.toml`).
@@ -324,9 +344,11 @@ fn load_raw() -> Result<GlobalConfigToml, String> {
/// since it holds API keys.
fn write_raw(config: &GlobalConfigToml) -> Result<PathBuf, String> {
let dir = global_jan_dir()?;
- std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create {}: {e}", dir.display()))?;
+ std::fs::create_dir_all(&dir)
+ .map_err(|e| format!("Failed to create {}: {e}", dir.display()))?;
let path = dir.join("config.toml");
- let body = toml::to_string_pretty(config).map_err(|e| format!("Failed to serialize config: {e}"))?;
+ let body =
+ toml::to_string_pretty(config).map_err(|e| format!("Failed to serialize config: {e}"))?;
std::fs::write(&path, &body).map_err(|e| format!("Failed to write {}: {e}", path.display()))?;
restrict_permissions(&path);
Ok(path)
@@ -364,6 +386,15 @@ pub(crate) fn set_provider(name: &str, update: ProviderUpdate) -> Result<PathBuf
if let Some(api_type) = update.api_type {
entry.api_type = Some(api_type);
}
+ if let Some(key_id) = update.key_id {
+ entry.key_id = key_id.filter(|k| !k.is_empty());
+ }
+ if let Some(key_expires_at) = update.key_expires_at {
+ entry.key_expires_at = key_expires_at;
+ }
+ if let Some(account) = update.account {
+ entry.account = account.filter(|a| !a.is_empty());
+ }
write_raw(&config)
}
@@ -388,6 +419,30 @@ pub(crate) fn set_default_model_if_unset(model: &str) -> Result<bool, String> {
Ok(true)
}
+/// Server-assigned metadata for a provider's stored key, when a v5 device-flow
+/// login recorded any. Used by `jan auth status` / the expiry warning and by
+/// `jan auth logout` to revoke the exact key.
+#[derive(Debug, Clone, Default)]
+pub(crate) struct StoredKeyMeta {
+ pub key_id: Option<String>,
+ pub key_expires_at: Option<u64>,
+ pub account: Option<String>,
+}
+
+/// Read `key_id`/`key_expires_at` for a provider, if stored. Missing config or
+/// provider reads as `None` fields -- the legacy login records neither.
+pub(crate) fn provider_key_meta(name: &str) -> Result<StoredKeyMeta, String> {
+ let config = load_raw()?;
+ Ok(match config.providers.get(name) {
+ Some(entry) => StoredKeyMeta {
+ key_id: entry.key_id.clone(),
+ key_expires_at: entry.key_expires_at,
+ account: entry.account.clone(),
+ },
+ None => StoredKeyMeta::default(),
+ })
+}
+
/// Remove a provider entry from `~/.jan/config.toml`. Returns `true` if the
/// provider existed and was removed, `false` if it was already absent.
pub(crate) fn remove_provider(name: &str) -> Result<bool, String> {
@@ -455,7 +510,8 @@ pub(crate) fn set_global_key(key: &str, value: Option<toml_edit::Item>) -> Resul
/// yet. Idempotent and clobber-safe: never overwrites an existing file.
pub(crate) fn ensure_global_config() -> Result<PathBuf, String> {
let dir = global_jan_dir()?;
- std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create {}: {e}", dir.display()))?;
+ std::fs::create_dir_all(&dir)
+ .map_err(|e| format!("Failed to create {}: {e}", dir.display()))?;
let path = dir.join("config.toml");
if !path.exists() {
std::fs::write(&path, GLOBAL_CONFIG_TEMPLATE)
@@ -552,7 +608,10 @@ mod tests {
assert!(think_tags_enabled());
std::fs::write(&path, "not valid toml [[[").unwrap();
- assert!(think_tags_enabled(), "an unreadable config keeps the default");
+ assert!(
+ think_tags_enabled(),
+ "an unreadable config keeps the default"
+ );
});
}
@@ -622,11 +681,17 @@ mod tests {
assert_eq!(wave_len("πŸ‘¨β€πŸ‘©β€πŸ‘§"), 1, "ZWJ family is one cluster");
assert_eq!(wave_len("πŸ‘οΈπŸ‘„πŸ‘οΈ"), 3, "5 chars, 3 clusters");
- assert!(wave_error("").is_none(), "empty is the off switch, not an error");
+ assert!(
+ wave_error("").is_none(),
+ "empty is the off switch, not an error"
+ );
assert!(wave_error("πŸ‘οΈπŸ‘„πŸ‘οΈ").is_none(), "exactly at the cap");
assert!(wave_error("<o>").is_none());
let err = wave_error("abcd").expect("over the cap");
- assert!(err.contains('3') && err.contains('4'), "names cap and actual: {err}");
+ assert!(
+ err.contains('3') && err.contains('4'),
+ "names cap and actual: {err}"
+ );
}
/// The `/settings` write path. Two properties matter and neither is
@@ -638,15 +703,14 @@ mod tests {
fn set_global_key_preserves_comments_and_stays_out_of_provider_tables() {
with_temp_home(|_| {
let path = ensure_global_config().expect("ensure");
- std::fs::write(
- &path,
- "# keep me\n[providers.openai]\napi_key = \"sk-x\"\n",
- )
- .unwrap();
+ std::fs::write(&path, "# keep me\n[providers.openai]\napi_key = \"sk-x\"\n").unwrap();
set_global_key("wave", Some(toml_edit::value("🍌"))).expect("set");
let raw = std::fs::read_to_string(&path).unwrap();
- assert!(raw.contains("# keep me"), "comment survives the write: {raw}");
+ assert!(
+ raw.contains("# keep me"),
+ "comment survives the write: {raw}"
+ );
assert!(raw.contains("sk-x"), "provider survives the write: {raw}");
assert_eq!(
wave_glyph().as_deref(),
@@ -687,7 +751,10 @@ mod tests {
with_temp_home(|_| {
assert!(stream_reasoning_enabled(), "missing file -> streaming on");
let path = ensure_global_config().expect("ensure");
- assert!(stream_reasoning_enabled(), "scaffolded file -> streaming on");
+ assert!(
+ stream_reasoning_enabled(),
+ "scaffolded file -> streaming on"
+ );
std::fs::write(&path, "stream_reasoning = false\n").unwrap();
assert!(!stream_reasoning_enabled());
@@ -734,7 +801,10 @@ models = ["gpt-4o"]
let configs = load_global_config().expect("load");
let openai = configs.get("openai").expect("openai present");
assert_eq!(openai.api_key.as_deref(), Some("sk-abc"));
- assert_eq!(openai.base_url.as_deref(), Some("https://api.openai.com/v1"));
+ assert_eq!(
+ openai.base_url.as_deref(),
+ Some("https://api.openai.com/v1")
+ );
assert_eq!(openai.models, vec!["gpt-4o".to_string()]);
});
}
@@ -758,13 +828,17 @@ models = ["gpt-4o"]
base_url: Some("https://api.openai.com/v1".into()),
models: Some(vec!["gpt-4o".into()]),
api_type: None,
+ ..Default::default()
},
)
.expect("set");
let configs = load_global_config().expect("load");
let openai = configs.get("openai").expect("present");
assert_eq!(openai.api_key.as_deref(), Some("sk-1"));
- assert_eq!(openai.base_url.as_deref(), Some("https://api.openai.com/v1"));
+ assert_eq!(
+ openai.base_url.as_deref(),
+ Some("https://api.openai.com/v1")
+ );
assert_eq!(openai.models, vec!["gpt-4o".to_string()]);
});
}
@@ -779,19 +853,37 @@ models = ["gpt-4o"]
base_url: Some("https://a".into()),
models: Some(vec!["gpt-4o".into()]),
api_type: None,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ set_provider(
+ "anthropic",
+ ProviderUpdate {
+ api_key: Some("sk-ant".into()),
+ ..Default::default()
},
)
.unwrap();
- set_provider("anthropic", ProviderUpdate { api_key: Some("sk-ant".into()), ..Default::default() }).unwrap();
// Update only the openai key; base_url + models must survive.
- set_provider("openai", ProviderUpdate { api_key: Some("sk-2".into()), ..Default::default() }).unwrap();
+ set_provider(
+ "openai",
+ ProviderUpdate {
+ api_key: Some("sk-2".into()),
+ ..Default::default()
+ },
+ )
+ .unwrap();
let configs = load_global_config().expect("load");
let openai = configs.get("openai").unwrap();
assert_eq!(openai.api_key.as_deref(), Some("sk-2"));
assert_eq!(openai.base_url.as_deref(), Some("https://a"));
assert_eq!(openai.models, vec!["gpt-4o".to_string()]);
- assert_eq!(configs.get("anthropic").unwrap().api_key.as_deref(), Some("sk-ant"));
+ assert_eq!(
+ configs.get("anthropic").unwrap().api_key.as_deref(),
+ Some("sk-ant")
+ );
});
}
@@ -811,11 +903,23 @@ models = ["gpt-4o"]
.unwrap();
set_provider("local", ProviderUpdate::default()).unwrap();
assert_eq!(
- load_global_config().unwrap().get("local").unwrap().api_key.as_deref(),
+ load_global_config()
+ .unwrap()
+ .get("local")
+ .unwrap()
+ .api_key
+ .as_deref(),
Some("sk-1"),
"None merges: key kept"
);
- set_provider("local", ProviderUpdate { api_key: Some(String::new()), ..Default::default() }).unwrap();
+ set_provider(
+ "local",
+ ProviderUpdate {
+ api_key: Some(String::new()),
+ ..Default::default()
+ },
+ )
+ .unwrap();
assert_eq!(
load_global_config().unwrap().get("local").unwrap().api_key,
None,
@@ -841,7 +945,14 @@ models = ["gpt-4o"]
#[test]
fn default_model_derives_from_first_provider_model() {
with_temp_home(|_| {
- set_provider("openai", ProviderUpdate { models: Some(vec!["gpt-4o".into()]), ..Default::default() }).unwrap();
+ set_provider(
+ "openai",
+ ProviderUpdate {
+ models: Some(vec!["gpt-4o".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
assert_eq!(default_model().expect("default").as_deref(), Some("gpt-4o"));
});
}
@@ -856,16 +967,36 @@ models = ["gpt-4o"]
"default_model = \"claude-sonnet-5\"\n[providers.openai]\nmodels = [\"gpt-4o\"]\n",
)
.unwrap();
- assert_eq!(default_model().expect("default").as_deref(), Some("claude-sonnet-5"));
+ assert_eq!(
+ default_model().expect("default").as_deref(),
+ Some("claude-sonnet-5")
+ );
});
}
#[test]
fn default_model_derivation_is_deterministic_by_provider_name() {
with_temp_home(|_| {
- set_provider("zeta", ProviderUpdate { models: Some(vec!["z-model".into()]), ..Default::default() }).unwrap();
- set_provider("alpha", ProviderUpdate { models: Some(vec!["a-model".into()]), ..Default::default() }).unwrap();
- assert_eq!(default_model().expect("default").as_deref(), Some("a-model"));
+ set_provider(
+ "zeta",
+ ProviderUpdate {
+ models: Some(vec!["z-model".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ set_provider(
+ "alpha",
+ ProviderUpdate {
+ models: Some(vec!["a-model".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ default_model().expect("default").as_deref(),
+ Some("a-model")
+ );
});
}
@@ -875,7 +1006,14 @@ models = ["gpt-4o"]
let path = global_config_path().unwrap();
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "default_model = \"m1\"\n").unwrap();
- set_provider("openai", ProviderUpdate { api_key: Some("sk".into()), ..Default::default() }).unwrap();
+ set_provider(
+ "openai",
+ ProviderUpdate {
+ api_key: Some("sk".into()),
+ ..Default::default()
+ },
+ )
+ .unwrap();
assert_eq!(default_model().expect("default").as_deref(), Some("m1"));
});
}
@@ -895,20 +1033,33 @@ models = ["gpt-4o"]
with_temp_home(|_| {
set_provider(
"tokamak",
- ProviderUpdate { api_key: Some("tk".into()), ..Default::default() },
+ ProviderUpdate {
+ api_key: Some("tk".into()),
+ ..Default::default()
+ },
)
.unwrap();
assert!(!set_default_model_if_unset(" ").expect("blank"));
assert!(set_default_model_if_unset("m1").expect("set"));
let configs = load_global_config().expect("load");
- assert_eq!(configs.get("tokamak").unwrap().api_key.as_deref(), Some("tk"));
+ assert_eq!(
+ configs.get("tokamak").unwrap().api_key.as_deref(),
+ Some("tk")
+ );
});
}
#[test]
fn remove_provider_reports_presence() {
with_temp_home(|_| {
- set_provider("openai", ProviderUpdate { api_key: Some("sk-1".into()), ..Default::default() }).unwrap();
+ set_provider(
+ "openai",
+ ProviderUpdate {
+ api_key: Some("sk-1".into()),
+ ..Default::default()
+ },
+ )
+ .unwrap();
assert!(remove_provider("openai").expect("remove"));
assert!(!remove_provider("openai").expect("remove again"));
assert!(!load_global_config().unwrap().contains_key("openai"));
@@ -923,10 +1074,20 @@ models = ["gpt-4o"]
let path = global_config_path().unwrap();
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "[providers.groq]\napi_key = \"gk\"\n").unwrap();
- set_provider("openai", ProviderUpdate { api_key: Some("sk".into()), ..Default::default() }).unwrap();
+ set_provider(
+ "openai",
+ ProviderUpdate {
+ api_key: Some("sk".into()),
+ ..Default::default()
+ },
+ )
+ .unwrap();
let configs = load_global_config().unwrap();
assert_eq!(configs.get("groq").unwrap().api_key.as_deref(), Some("gk"));
- assert_eq!(configs.get("openai").unwrap().api_key.as_deref(), Some("sk"));
+ assert_eq!(
+ configs.get("openai").unwrap().api_key.as_deref(),
+ Some("sk")
+ );
});
}
}
diff --git a/src-tauri/src/core/cli/device_auth.rs b/src-tauri/src/core/cli/device_auth.rs
new file mode 100644
index 000000000..63d8246bb
--- /dev/null
+++ b/src-tauri/src/core/cli/device_auth.rs
@@ -0,0 +1,1174 @@
+//! Browser-approval sign-in for Tokamak, the counterpart to `codex login
+//! --device-auth` and Claude Code's OAuth login. Ported from the tokamak CLI's
+//! `cli-login.ts`; the wire format below is that client's, not an invention.
+//!
+//! Where the legacy flow makes the user paste a minted `sk_live_*` key, this
+//! flow leans on a browser approval that can happen on *any* device:
+//!
+//! 1. `POST {api}/auth/cli/sessions` with `{code_challenge, client_name}`
+//! returns `session_id`, `user_code` (`ABCD-2345`), `expires_in` and a
+//! suggested poll `interval`.
+//! 2. The CLI opens `{web}/cli/authorize?code=ABCD-2345` so the user can
+//! confirm the code matches and click Approve (a phone works too; the poll
+//! below still finishes the login).
+//! 3. The CLI polls `POST {api}/auth/cli/sessions/token` with
+//! `{session_id, code_verifier}` until the reply's `status` settles on
+//! `approved` (carrying the minted `api_key`), `denied`, or `expired`.
+//!
+//! These endpoints ride the gateway's unauthenticated `/auth/*` pass-through,
+//! so they hang off the API *origin* -- not off the OpenAI-compatible `/v1`
+//! base, which rejects everything unauthenticated. A server predating the flow
+//! answers 404/405 there, which the caller turns into the legacy paste flow.
+//!
+//! Only the PKCE verifier proves the claim: revealing it at claim time is what
+//! shows this process -- not someone who merely saw the session id -- is the
+//! requester. No token or key ever rides a URL, and the browser's Keycloak
+//! token never reaches the CLI.
+//!
+//! A 127.0.0.1-only ephemeral wake listener makes desktop logins complete the
+//! instant the user clicks Approve, instead of waiting for the next poll tick.
+//! Headless/SSH machines need nothing: approve from a phone and the poll picks
+//! it up.
+//!
+//! Tauri-free and UI-free: presentation lives in the callers ([`super::login`]
+//! for the plain terminal).
+
+use std::net::{Ipv4Addr, SocketAddr};
+use std::time::Duration;
+
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
+use base64::Engine as _;
+use rand::RngCore;
+use serde::Deserialize;
+use sha2::{Digest, Sha256};
+use url::Url;
+
+/// Endpoint prefix for the CLI-login session API, relative to the API origin.
+pub(crate) const SESSIONS_PATH: &str = "/auth/cli/sessions";
+
+/// Identifies this client in the approve page ("… is requesting access").
+const CLIENT_NAME: &str = "Jan CLI";
+
+/// Fallbacks for a server that omits them, matching the reference client.
+const DEFAULT_EXPIRES_IN: u64 = 600;
+const DEFAULT_INTERVAL: u64 = 5;
+
+/// Clamp for the server-suggested poll interval, so neither a zero nor an absurd
+/// value turns the loop into a busy spin or a stall.
+const MIN_INTERVAL: u64 = 1;
+const MAX_INTERVAL: u64 = 30;
+
+/// How long a single HTTP call waits before failing, so a hung server cannot
+/// stall the poll loop past one tick's worth of patience.
+const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// A fresh, unapproved sign-in as returned by the create endpoint.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Session {
+ pub session_id: String,
+ /// The human-readable code the user must match in the authorize page
+ /// (e.g. `ABCD-2345`).
+ pub user_code: String,
+ /// Where to ask the user to go, e.g.
+ /// `https://tokamak.sh/cli/authorize?code=ABCD-2345`.
+ pub authorize_url: String,
+ /// Seconds the session lives before it expires -- the poll deadline.
+ pub expires_in: u64,
+ /// Seconds the server asks us to wait between polls.
+ pub interval: u64,
+}
+
+/// State held between `begin` and `claim`, so a long approval window keeps the
+/// verifier (and the wake listener) on one struct.
+pub(crate) struct PendingAuth {
+ api_root: String,
+ session: Session,
+ verifier: String,
+ /// Bound in `begin` so its port and state can ride the authorize page and
+ /// an Approve click can wake the poll immediately. `None` when binding
+ /// failed -- the poll interval is the floor then.
+ wake: Option<WakeServer>,
+}
+
+/// The key minted by a successful claim, before it is persisted.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct Minted {
+ pub api_key: String,
+ /// Server-assigned key id, needed to revoke this exact key on logout.
+ pub key_id: Option<String>,
+ /// Unix seconds, parsed from the server's RFC 3339 `expires_at`.
+ pub key_expires_at: Option<u64>,
+ /// Who the server says signed in, for the sign-in report.
+ pub account: Option<String>,
+}
+
+/// Why [`begin`] gave up. Split from a plain string so the caller can act on
+/// "this server predates the flow" without matching on prose.
+#[derive(Debug)]
+pub(crate) enum BeginError {
+ /// 404/405 from the auth pass-through: fall back to the legacy paste flow.
+ Unsupported,
+ Failed(String),
+}
+
+impl BeginError {
+ pub(crate) fn message(&self, host: &str) -> String {
+ match self {
+ Self::Unsupported => format!(
+ "the server at {host} does not support browser sign-in; falling back to pasting \
+ an API key"
+ ),
+ Self::Failed(e) => e.clone(),
+ }
+ }
+}
+
+fn http() -> reqwest::Client {
+ reqwest::Client::builder()
+ .timeout(HTTP_TIMEOUT)
+ .build()
+ .unwrap_or_else(|_| reqwest::Client::new())
+}
+
+/// Base64url (no padding) SHA-256 of `input` -- the S256 PKCE derivation.
+fn pkce_code_challenge(verifier: &str) -> String {
+ let digest = Sha256::digest(verifier.as_bytes());
+ URL_SAFE_NO_PAD.encode(digest)
+}
+
+fn random_b64(bytes: usize) -> String {
+ let mut buf = vec![0u8; bytes];
+ rand::thread_rng().fill_bytes(&mut buf);
+ URL_SAFE_NO_PAD.encode(buf)
+}
+
+/// A random verifier string. 43-128 chars of unreserved base64url -- 32 random
+/// bytes is 43 characters, comfortably inside the codex/Claude range.
+fn random_verifier() -> String {
+ random_b64(32)
+}
+
+/// Guards the loopback wake endpoint, so only the browser we sent to the
+/// approve page can ring it.
+fn random_state() -> String {
+ random_b64(16)
+}
+
+/// Scheme + host + port of `base_url`, with no trailing slash. The session
+/// endpoints live at the API origin, not under the `/v1` OpenAI-compatible
+/// prefix that `base_url` points at.
+pub(crate) fn api_root(base_url: &str) -> String {
+ match origin_of(base_url) {
+ Some(url) => url.as_str().trim_end_matches('/').to_string(),
+ None => base_url.trim_end_matches('/').to_string(),
+ }
+}
+
+/// Origin of the *web* app, which serves the authorize page. Tokamak splits the
+/// two (API at `api.tokamak.sh`, web at `tokamak.sh`), so a plain `api.`
+/// subdomain is dropped; anything else is assumed to serve both.
+fn web_root(base_url: &str) -> String {
+ let Some(mut url) = origin_of(base_url) else {
+ return base_url.trim_end_matches('/').to_string();
+ };
+ if let Some(host) = url.host_str().and_then(|h| h.strip_prefix("api.")) {
+ let host = host.to_string();
+ if url.set_host(Some(&host)).is_err() {
+ return url.as_str().trim_end_matches('/').to_string();
+ }
+ }
+ url.as_str().trim_end_matches('/').to_string()
+}
+
+fn origin_of(base_url: &str) -> Option<Url> {
+ let mut url = Url::parse(base_url).ok()?;
+ url.set_path("");
+ url.set_query(None);
+ url.set_fragment(None);
+ Some(url)
+}
+
+/// The browser approval URL. When a wake listener is running, its loopback
+/// address and a random state ride along so the approve page can bounce the
+/// browser back and finish the terminal instantly -- the params carry no
+/// secrets, and losing them only costs one poll tick.
+fn build_authorize_url(web_root: &str, user_code: &str, wake: Option<(u16, &str)>) -> String {
+ let joined = Url::parse(web_root).and_then(|base| base.join("/cli/authorize"));
+ let Ok(mut url) = joined else {
+ return format!("{web_root}/cli/authorize?code={user_code}");
+ };
+ {
+ let mut query = url.query_pairs_mut();
+ query.append_pair("code", user_code);
+ if let Some((port, state)) = wake {
+ query.append_pair("redirect", &format!("http://127.0.0.1:{port}/done"));
+ query.append_pair("state", state);
+ }
+ }
+ url.to_string()
+}
+
+fn clamp_interval(seconds: Option<u64>) -> u64 {
+ seconds
+ .filter(|s| *s > 0)
+ .unwrap_or(DEFAULT_INTERVAL)
+ .clamp(MIN_INTERVAL, MAX_INTERVAL)
+}
+
+/// Start a sign-in: create a session on the server (PKCE S256 challenge,
+/// unauthenticated) for the deployment `base_url` points at. `base_url` is the
+/// OpenAI-compatible base (e.g. `https://api.tokamak.sh/v1`); both the API
+/// origin and the authorize page host are derived from it.
+pub(crate) async fn begin(base_url: &str) -> Result<PendingAuth, BeginError> {
+ let verifier = random_verifier();
+ let challenge = pkce_code_challenge(&verifier);
+ let api_root = api_root(base_url);
+
+ let body = serde_json::json!({ "code_challenge": challenge, "client_name": CLIENT_NAME });
+ let response = http()
+ .post(format!("{api_root}{SESSIONS_PATH}"))
+ .json(&body)
+ .send()
+ .await
+ .map_err(|e| BeginError::Failed(format!("could not reach {api_root}: {e}")))?;
+
+ let status = response.status().as_u16();
+ // No route here means the deployment predates the flow.
+ if status == 404 || status == 405 {
+ return Err(BeginError::Unsupported);
+ }
+ let payload: SessionPayload = response.json().await.unwrap_or_default();
+ let (Some(session_id), Some(user_code)) = (payload.session_id, payload.user_code) else {
+ return Err(BeginError::Failed(describe_create_failure(
+ status,
+ payload.error.as_deref(),
+ )));
+ };
+ if !(200..300).contains(&status) {
+ return Err(BeginError::Failed(describe_create_failure(
+ status,
+ payload.error.as_deref(),
+ )));
+ }
+
+ // Best-effort: a machine with no browser has nothing to hit the listener,
+ // so a bind failure just means the poll interval is the floor.
+ let state = random_state();
+ let wake = WakeServer::bind(state.clone()).await.ok();
+ let authorize_url = build_authorize_url(
+ &web_root(base_url),
+ &user_code,
+ wake.as_ref().map(|w| (w.port, state.as_str())),
+ );
+
+ Ok(PendingAuth {
+ api_root,
+ session: Session {
+ session_id,
+ user_code,
+ authorize_url,
+ expires_in: payload
+ .expires_in
+ .filter(|s| *s > 0)
+ .unwrap_or(DEFAULT_EXPIRES_IN),
+ interval: clamp_interval(payload.interval),
+ },
+ verifier,
+ wake,
+ })
+}
+
+fn describe_create_failure(status: u16, error: Option<&str>) -> String {
+ match status {
+ 401 | 403 => format!(
+ "Tokamak refused to start a sign-in session (HTTP {status}). The sign-in endpoints \
+ should not require auth, so this is likely the wrong endpoint for this deployment."
+ ),
+ 429 => "too many sign-in attempts - wait a minute and try again.".to_string(),
+ 500..=599 => format!("Tokamak is unavailable right now (HTTP {status})."),
+ _ => match error {
+ Some(e) if !e.is_empty() => {
+ format!("Tokamak could not start a sign-in session (HTTP {status}): {e}")
+ }
+ _ => format!("Tokamak could not start a sign-in session (HTTP {status})."),
+ },
+ }
+}
+
+impl PendingAuth {
+ /// The session + authorize URL, for the caller to display before claiming.
+ pub fn session(&self) -> &Session {
+ &self.session
+ }
+
+ /// Point of no return for the poll loop: wait until the session settles,
+ /// then hand back the minted key. Wakes early when the browser pings the
+ /// loopback listener, otherwise sleeps the server-suggested interval.
+ pub async fn claim(self) -> Result<Minted, String> {
+ let PendingAuth {
+ api_root,
+ session,
+ verifier,
+ mut wake,
+ } = self;
+
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(session.expires_in);
+ let mut interval = Duration::from_secs(session.interval);
+ // The last reachability blip, and whether it landed on the final poll:
+ // then it, not the clock, is why the sign-in is being abandoned.
+ let mut last_transient: Option<(String, bool)> = None;
+ loop {
+ // The local deadline is only a bound on waiting: one last poll runs
+ // on the way out so the server's own `expired`/`approved` gets the
+ // final word rather than the generic timeout below.
+ let last_round = tokio::time::Instant::now() >= deadline;
+ if !last_round {
+ // Wait before the first poll: the session was created a moment
+ // ago, so an immediate poll can only come back pending. The wake
+ // is one-shot -- once it fires, later ticks are plain sleeps,
+ // else an already-signalled listener would spin the loop.
+ match wake.take() {
+ Some(listener) => {
+ if !listener.wait(interval).await {
+ wake = Some(listener);
+ }
+ }
+ None => tokio::time::sleep(interval).await,
+ }
+ }
+ match poll_once(&api_root, &session.session_id, &verifier).await {
+ Ok(Poll::Approved(minted)) => return Ok(*minted),
+ Ok(Poll::Pending(next)) => {
+ interval = next;
+ // A live tick clears any earlier blip from the timeout message.
+ last_transient.take();
+ }
+ Ok(Poll::Denied) => {
+ return Err("the sign-in was denied in the browser.".to_string())
+ }
+ Ok(Poll::Expired) => {
+ return Err(
+ "the sign-in expired before it was approved. Run `jan login` again."
+ .to_string(),
+ )
+ }
+ // A reachability blip is one bad tick, not the session settling:
+ // the user may have just approved and the key is live server
+ // side. Keep polling and let the deadline bound the wait.
+ Err(e) if e.retryable => last_transient = Some((e.message, last_round)),
+ Err(e) => return Err(e.message),
+ }
+ if last_round {
+ break;
+ }
+ }
+ Err(match last_transient {
+ // The last word came from a failed poll, not from the clock running
+ // out on a silent server -- saying "timed out" would contradict a
+ // reason like "approved but no API key".
+ Some((e, true)) => format!(
+ "could not confirm the sign-in before the window closed: {e} Run `jan login` again."
+ ),
+ Some((e, _)) => format!(
+ "timed out waiting for browser approval (last poll error: {e}). Run `jan login` \
+ again."
+ ),
+ None => "timed out waiting for browser approval. Run `jan login` again.".to_string(),
+ })
+ }
+}
+
+/// How a single poll settled.
+enum Poll {
+ Pending(Duration),
+ Denied,
+ Expired,
+ Approved(Box<Minted>),
+}
+
+/// Why a single poll failed. `retryable` marks the failures that say nothing
+/// about the session itself -- the loop spends a tick on those instead of
+/// abandoning a sign-in the user may have just approved.
+struct PollError {
+ message: String,
+ retryable: bool,
+}
+
+impl PollError {
+ fn transient(message: String) -> Self {
+ Self {
+ message,
+ retryable: true,
+ }
+ }
+
+ fn terminal(message: String) -> Self {
+ Self {
+ message,
+ retryable: false,
+ }
+ }
+}
+
+/// A status the session cannot recover from: the server has judged this exact
+/// session id or verifier, so re-polling it will keep failing.
+fn poll_status_is_terminal(status: u16) -> bool {
+ !matches!(status, 408 | 425 | 429 | 500..=599)
+}
+
+/// One poll of the token endpoint. `Err` is a transport or protocol failure;
+/// everything the server models as an outcome comes back as a [`Poll`].
+async fn poll_once(api_root: &str, session_id: &str, verifier: &str) -> Result<Poll, PollError> {
+ let body = serde_json::json!({ "session_id": session_id, "code_verifier": verifier });
+ let response = http()
+ .post(format!("{api_root}{SESSIONS_PATH}/token"))
+ .json(&body)
+ .send()
+ .await
+ .map_err(|e| PollError::transient(format!("could not reach {api_root}: {e}")))?;
+
+ let status = response.status().as_u16();
+ let payload: PollPayload = response.json().await.unwrap_or_default();
+ if !(200..300).contains(&status) {
+ let message = describe_poll_failure(status, payload.error.as_deref());
+ return Err(if poll_status_is_terminal(status) {
+ PollError::terminal(message)
+ } else {
+ PollError::transient(message)
+ });
+ }
+
+ Ok(match payload.status.as_deref() {
+ Some("approved") => {
+ let key = payload
+ .api_key
+ .filter(|k| !k.key.is_empty())
+ .ok_or_else(|| {
+ // Approved without a key is a malformed body, not a verdict:
+ // the next poll of the same approved session should carry it.
+ PollError::transient(
+ "the sign-in was approved but Tokamak returned no API key.".to_string(),
+ )
+ })?;
+ Poll::Approved(Box::new(Minted {
+ api_key: key.key,
+ key_id: key.id.filter(|id| !id.is_empty()),
+ key_expires_at: key.expires_at.as_deref().and_then(parse_expires_at),
+ account: payload.user.and_then(|u| u.email.or(u.name)),
+ }))
+ }
+ Some("denied") => Poll::Denied,
+ Some("expired") => Poll::Expired,
+ // An unrecognised status is not a terminal outcome: a newer server may
+ // add intermediate states, and treating them as expired would abort a
+ // live sign-in. Keep polling; the deadline still bounds the wait.
+ _ => Poll::Pending(Duration::from_secs(clamp_interval(payload.interval))),
+ })
+}
+
+fn describe_poll_failure(status: u16, error: Option<&str>) -> String {
+ match status {
+ 401 | 403 => "the sign-in session could not be verified - re-run `jan login`.".to_string(),
+ 429 => "Tokamak is rate limiting - wait a moment and try again.".to_string(),
+ 500..=599 => format!("Tokamak is unavailable right now (HTTP {status})."),
+ _ => match error {
+ Some(e) if !e.is_empty() => {
+ format!("Tokamak could not finish the sign-in (HTTP {status}): {e}")
+ }
+ _ => format!("Tokamak could not finish the sign-in (HTTP {status})."),
+ },
+ }
+}
+
+/// The server dates the key in RFC 3339; the config stores unix seconds.
+fn parse_expires_at(raw: &str) -> Option<u64> {
+ let parsed = chrono::DateTime::parse_from_rfc3339(raw).ok()?;
+ u64::try_from(parsed.timestamp()).ok()
+}
+
+/// Payload of `POST /auth/cli/sessions`.
+#[derive(Deserialize, Default)]
+struct SessionPayload {
+ #[serde(default)]
+ session_id: Option<String>,
+ #[serde(default)]
+ user_code: Option<String>,
+ #[serde(default)]
+ expires_in: Option<u64>,
+ #[serde(default)]
+ interval: Option<u64>,
+ #[serde(default)]
+ error: Option<String>,
+}
+
+/// Payload of `POST /auth/cli/sessions/token`.
+#[derive(Deserialize, Default)]
+struct PollPayload {
+ #[serde(default)]
+ status: Option<String>,
+ #[serde(default)]
+ interval: Option<u64>,
+ #[serde(default)]
+ api_key: Option<ApiKeyPayload>,
+ #[serde(default)]
+ user: Option<UserPayload>,
+ #[serde(default)]
+ error: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct ApiKeyPayload {
+ key: String,
+ #[serde(default)]
+ id: Option<String>,
+ #[serde(default)]
+ expires_at: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct UserPayload {
+ #[serde(default)]
+ email: Option<String>,
+ #[serde(default)]
+ name: Option<String>,
+}
+
+const WAKE_PAGE: &str = "<!doctype html><html><head><meta charset=\"utf-8\"><title>Jan CLI</title>\
+</head><body style=\"font-family:system-ui,sans-serif;display:flex;align-items:center;\
+justify-content:center;height:100vh;margin:0\"><div style=\"text-align:center\">\
+<div style=\"font-size:2rem;margin-bottom:.5rem\">&#10003;</div>\
+<h1 style=\"font-size:1.3rem;font-weight:500;margin:0 0 .4rem\">Jan CLI authorized</h1>\
+<p style=\"opacity:.6;margin:0\">Return to your terminal. You can close this tab.</p>\
+</div></body></html>";
+
+/// A 127.0.0.1-only ephemeral listener that turns an approve click into an
+/// immediate poll, instead of waiting for the next tick.
+struct WakeServer {
+ listener: tokio::net::TcpListener,
+ port: u16,
+ /// Guards the endpoint: the approve page echoes back the state we sent it.
+ state: String,
+}
+
+/// What a request to the wake listener was asking for.
+enum WakeRequest {
+ /// Chrome's Private Network Access preflight, which must be answered before
+ /// the approve page is allowed to ping loopback at all.
+ Preflight,
+ Woken,
+ Other,
+}
+
+impl WakeServer {
+ async fn bind(state: String) -> Result<Self, std::io::Error> {
+ let listener =
+ tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).await?;
+ let port = listener.local_addr()?.port();
+ Ok(Self {
+ listener,
+ port,
+ state,
+ })
+ }
+
+ /// Wait up to `timeout` for the browser to ping us. `true` means woken;
+ /// `false` means the caller should just poll. The wake is only a heads-up
+ /// that the poll should run now, never a trust boundary.
+ async fn wait(&self, timeout: Duration) -> bool {
+ use tokio::io::AsyncReadExt as _;
+ let deadline = tokio::time::Instant::now() + timeout;
+ let mut buf = [0u8; 1024];
+ loop {
+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
+ if remaining.is_zero() {
+ return false;
+ }
+ let Ok(Ok((mut stream, _))) =
+ tokio::time::timeout(remaining, self.listener.accept()).await
+ else {
+ return false;
+ };
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let request = String::from_utf8_lossy(&buf[..n]);
+ match classify_wake(&request, &self.state) {
+ WakeRequest::Preflight => {
+ let _ = write_preflight(&mut stream).await;
+ }
+ WakeRequest::Woken => {
+ let _ = write_wake_page(&mut stream).await;
+ return true;
+ }
+ WakeRequest::Other => {
+ let _ = write_not_found(&mut stream).await;
+ }
+ }
+ }
+ }
+}
+
+fn classify_wake(request: &str, state: &str) -> WakeRequest {
+ let mut line = request
+ .lines()
+ .next()
+ .unwrap_or_default()
+ .split_whitespace();
+ let method = line.next().unwrap_or_default();
+ let target = line.next().unwrap_or_default();
+ if method == "OPTIONS" {
+ return WakeRequest::Preflight;
+ }
+ if method != "GET" {
+ return WakeRequest::Other;
+ }
+ let Ok(url) = Url::parse("http://127.0.0.1").and_then(|base| base.join(target)) else {
+ return WakeRequest::Other;
+ };
+ if url.path() != "/done" {
+ return WakeRequest::Other;
+ }
+ match url.query_pairs().any(|(k, v)| k == "state" && v == state) {
+ true => WakeRequest::Woken,
+ false => WakeRequest::Other,
+ }
+}
+
+async fn write_all(stream: &mut tokio::net::TcpStream, response: &str) -> std::io::Result<()> {
+ use tokio::io::AsyncWriteExt as _;
+ stream.write_all(response.as_bytes()).await
+}
+
+async fn write_preflight(stream: &mut tokio::net::TcpStream) -> std::io::Result<()> {
+ write_all(
+ stream,
+ "HTTP/1.1 204 No Content\r\naccess-control-allow-origin: *\r\n\
+ access-control-allow-methods: GET, OPTIONS\r\n\
+ access-control-allow-private-network: true\r\nconnection: close\r\n\r\n",
+ )
+ .await
+}
+
+async fn write_wake_page(stream: &mut tokio::net::TcpStream) -> std::io::Result<()> {
+ let response = format!(
+ "HTTP/1.1 200 OK\r\ncontent-length: {}\r\ncontent-type: text/html; charset=utf-8\r\n\
+ access-control-allow-origin: *\r\nconnection: close\r\n\r\n{WAKE_PAGE}",
+ WAKE_PAGE.len()
+ );
+ write_all(stream, &response).await
+}
+
+async fn write_not_found(stream: &mut tokio::net::TcpStream) -> std::io::Result<()> {
+ write_all(
+ stream,
+ "HTTP/1.1 404 Not Found\r\ncontent-length: 9\r\ncontent-type: text/plain\r\n\
+ connection: close\r\n\r\nnot found",
+ )
+ .await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pkce_challenge_is_stable_and_url_safe() {
+ let verifier = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
+ let challenge = pkce_code_challenge(verifier);
+ assert_eq!(challenge.len(), 43);
+ assert!(!challenge.contains('='));
+ assert!(!challenge.contains('+'));
+ assert!(!challenge.contains('/'));
+ assert_eq!(challenge, pkce_code_challenge(verifier));
+ }
+
+ /// The S256 derivation must match the reference client's
+ /// `sha256(verifier).base64url`, or the server rejects every claim.
+ #[test]
+ fn pkce_challenge_matches_the_reference_vector() {
+ // RFC 7636 appendix B.
+ assert_eq!(
+ pkce_code_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
+ );
+ }
+
+ #[test]
+ fn verifier_is_url_safe_and_random() {
+ let a = random_verifier();
+ let b = random_verifier();
+ assert_ne!(a, b);
+ for v in [&a, &b] {
+ assert!((43..=128).contains(&v.len()));
+ for c in v.chars() {
+ assert!(
+ c.is_ascii_alphanumeric() || c == '-' || c == '_',
+ "unexpected char in verifier: {c}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn state_is_random_and_url_safe() {
+ let a = random_state();
+ assert_ne!(a, random_state());
+ assert!(a
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
+ }
+
+ /// The session endpoints ride the API origin, never the `/v1` prefix -- the
+ /// gateway 401s everything under `/v1` that has no bearer key.
+ #[test]
+ fn api_root_drops_the_v1_prefix() {
+ assert_eq!(
+ api_root("https://api.tokamak.sh/v1"),
+ "https://api.tokamak.sh"
+ );
+ assert_eq!(
+ api_root("https://api.tokamak.sh/v1/"),
+ "https://api.tokamak.sh"
+ );
+ assert_eq!(
+ api_root("http://localhost:8080/v1"),
+ "http://localhost:8080"
+ );
+ assert_eq!(
+ format!("{}{SESSIONS_PATH}", api_root("https://api.tokamak.sh/v1")),
+ "https://api.tokamak.sh/auth/cli/sessions"
+ );
+ }
+
+ /// The authorize page is on the web host, and carries no path from the API
+ /// base -- `tokamak.sh/cli/authorize`, never `tokamak.sh/v1/cli/authorize`.
+ #[test]
+ fn web_root_drops_the_api_subdomain_and_the_path() {
+ assert_eq!(web_root("https://api.tokamak.sh/v1"), "https://tokamak.sh");
+ assert_eq!(web_root("https://tokamak.sh/v1"), "https://tokamak.sh");
+ assert_eq!(
+ web_root("http://localhost:8080/v1"),
+ "http://localhost:8080"
+ );
+ }
+
+ #[test]
+ fn authorize_url_matches_the_reference_shape() {
+ let url = build_authorize_url("https://tokamak.sh", "ABCD-2345", None);
+ assert_eq!(url, "https://tokamak.sh/cli/authorize?code=ABCD-2345");
+ }
+
+ /// With a wake listener the redirect + state ride along, percent-encoded,
+ /// and still carry no secret.
+ #[test]
+ fn authorize_url_carries_an_encoded_wake_redirect() {
+ let url = build_authorize_url("https://tokamak.sh", "ABCD-2345", Some((54321, "st-1")));
+ assert_eq!(
+ url,
+ "https://tokamak.sh/cli/authorize?code=ABCD-2345\
+ &redirect=http%3A%2F%2F127.0.0.1%3A54321%2Fdone&state=st-1"
+ );
+ assert!(!url.contains("sk_live"));
+ assert!(!url.contains("verifier"));
+ }
+
+ #[test]
+ fn interval_is_clamped_and_defaulted() {
+ assert_eq!(clamp_interval(None), DEFAULT_INTERVAL);
+ assert_eq!(clamp_interval(Some(0)), DEFAULT_INTERVAL);
+ assert_eq!(clamp_interval(Some(2)), 2);
+ assert_eq!(clamp_interval(Some(9999)), MAX_INTERVAL);
+ }
+
+ #[test]
+ fn expires_at_parses_rfc3339_into_unix_seconds() {
+ assert_eq!(parse_expires_at("2023-11-14T22:13:20Z"), Some(1700000000));
+ assert_eq!(
+ parse_expires_at("2023-11-14T22:13:20+00:00"),
+ Some(1700000000)
+ );
+ assert_eq!(parse_expires_at("not a date"), None);
+ assert_eq!(parse_expires_at("1700000000"), None);
+ }
+
+ #[test]
+ fn wake_requests_are_classified_by_path_and_state() {
+ let woken = "GET /done?state=st-1 HTTP/1.1\r\nhost: 127.0.0.1\r\n\r\n";
+ assert!(matches!(classify_wake(woken, "st-1"), WakeRequest::Woken));
+ // A wrong or missing state is not a wake.
+ assert!(matches!(classify_wake(woken, "other"), WakeRequest::Other));
+ assert!(matches!(
+ classify_wake("GET /done HTTP/1.1\r\n\r\n", "st-1"),
+ WakeRequest::Other
+ ));
+ // Another path on the same port is not a wake.
+ assert!(matches!(
+ classify_wake("GET /?state=st-1 HTTP/1.1\r\n\r\n", "st-1"),
+ WakeRequest::Other
+ ));
+ // Chrome's private-network preflight must be recognised, or the ping
+ // never arrives.
+ assert!(matches!(
+ classify_wake("OPTIONS /done HTTP/1.1\r\n\r\n", "st-1"),
+ WakeRequest::Preflight
+ ));
+ assert!(matches!(classify_wake("", "st-1"), WakeRequest::Other));
+ }
+
+ /// A create reply the server rejects, or one missing the ids, must not read
+ /// as a session.
+ #[test]
+ fn create_failures_are_described_with_the_server_reason() {
+ assert!(describe_create_failure(429, None).contains("too many sign-in attempts"));
+ assert!(describe_create_failure(503, None).contains("unavailable"));
+ assert!(describe_create_failure(400, Some("bad challenge")).contains("bad challenge"));
+ // A 401 here means the wrong endpoint, not a bad credential.
+ assert!(describe_create_failure(401, None).contains("should not require auth"));
+ }
+
+ /// Spin up a mock of the two endpoints and drive the whole flow: create,
+ /// one `pending` poll, then `approved`. Asserts the request bodies match the
+ /// reference client's field names -- the thing a mock-only test can still
+ /// get wrong is exactly what this pins.
+ #[test]
+ fn create_poll_and_claim_use_the_reference_wire_format() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let (host, requests) = mock_server(vec![
+ (
+ 200,
+ r#"{"session_id":"sess-1","user_code":"ABCD-2345","expires_in":300,"interval":1}"#,
+ ),
+ (200, r#"{"status":"pending","interval":1}"#),
+ (
+ 200,
+ r#"{"status":"approved","api_key":{"id":"k-1","key":"sk_live_x","expires_at":"2023-11-14T22:13:20Z"},"user":{"email":"[email protected]"}}"#,
+ ),
+ ])
+ .await;
+
+ let pending = begin(&format!("{host}/v1")).await.expect("begin");
+ assert_eq!(pending.session().user_code, "ABCD-2345");
+ assert_eq!(pending.session().expires_in, 300);
+ assert_eq!(pending.session().interval, 1);
+
+ let minted = pending.claim().await.expect("claim");
+ assert_eq!(minted.api_key, "sk_live_x");
+ assert_eq!(minted.key_id.as_deref(), Some("k-1"));
+ assert_eq!(minted.key_expires_at, Some(1700000000));
+ assert_eq!(minted.account.as_deref(), Some("[email protected]"));
+
+ let seen = requests.lock().unwrap();
+ assert_eq!(seen.len(), 3, "create + pending poll + approved poll");
+ // Create: the session path hangs off the origin, not /v1, and sends
+ // the challenge plus a client name.
+ assert!(
+ seen[0].starts_with("POST /auth/cli/sessions HTTP"),
+ "{}",
+ seen[0]
+ );
+ assert!(seen[0].contains("code_challenge"), "{}", seen[0]);
+ assert!(seen[0].contains("client_name"), "{}", seen[0]);
+ // Poll: the session id and the verifier, under the reference's
+ // field names.
+ for poll in &seen[1..] {
+ assert!(poll.starts_with("POST /auth/cli/sessions/token HTTP"), "{poll}");
+ assert!(poll.contains("\"session_id\":\"sess-1\""), "{poll}");
+ assert!(poll.contains("code_verifier"), "{poll}");
+ assert!(!poll.contains("sk_live"), "no key on the wire: {poll}");
+ }
+ });
+ }
+
+ /// `denied` and `expired` are outcomes, not "keep waiting" -- a user who
+ /// clicks Deny must not sit through the whole poll window.
+ #[test]
+ fn a_denied_session_fails_immediately() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let (host, _) = mock_server(vec![
+ (
+ 200,
+ r#"{"session_id":"s","user_code":"A-1","expires_in":300,"interval":1}"#,
+ ),
+ (200, r#"{"status":"denied"}"#),
+ ])
+ .await;
+ let pending = begin(&format!("{host}/v1")).await.expect("begin");
+ let err = pending.claim().await.expect_err("denied must fail");
+ assert!(err.contains("denied in the browser"), "{err}");
+ });
+ }
+
+ /// A gateway blip mid-poll must cost one tick, not the whole sign-in: the
+ /// approval may already have happened server side.
+ #[test]
+ fn a_transient_poll_failure_keeps_polling() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let (host, requests) = mock_server(vec![
+ (
+ 200,
+ r#"{"session_id":"s","user_code":"A-1","expires_in":300,"interval":1}"#,
+ ),
+ (502, r#"{"error":"bad gateway"}"#),
+ (
+ 200,
+ r#"{"status":"approved","api_key":{"key":"sk_live_x"}}"#,
+ ),
+ ])
+ .await;
+ let pending = begin(&format!("{host}/v1")).await.expect("begin");
+ let minted = pending.claim().await.expect("claim survives one bad tick");
+ assert_eq!(minted.api_key, "sk_live_x");
+ assert_eq!(requests.lock().unwrap().len(), 3);
+ });
+ }
+
+ /// The deadline only bounds waiting: one last poll runs on the way out, and
+ /// a server that is still `pending` then yields the timeout message.
+ #[test]
+ fn a_session_that_is_never_approved_times_out_after_a_final_poll() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let (host, requests) = mock_server(vec![
+ (
+ 200,
+ r#"{"session_id":"s","user_code":"A-1","expires_in":1,"interval":1}"#,
+ ),
+ (200, r#"{"status":"pending","interval":1}"#),
+ (200, r#"{"status":"pending","interval":1}"#),
+ ])
+ .await;
+ let pending = begin(&format!("{host}/v1")).await.expect("begin");
+ let err = pending
+ .claim()
+ .await
+ .expect_err("an unapproved session times out");
+ assert_eq!(
+ err,
+ "timed out waiting for browser approval. Run `jan login` again."
+ );
+ assert_eq!(
+ requests.lock().unwrap().len(),
+ 3,
+ "create + one tick + the final poll after the deadline"
+ );
+ });
+ }
+
+ /// When the final poll is the one that fails, the reason is that failure --
+ /// "timed out ... (approved but no API key)" would contradict itself.
+ #[test]
+ fn a_blip_on_the_final_poll_is_reported_instead_of_a_timeout() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let (host, _) = mock_server(vec![
+ (
+ 200,
+ r#"{"session_id":"s","user_code":"A-1","expires_in":1,"interval":1}"#,
+ ),
+ (200, r#"{"status":"approved"}"#),
+ (200, r#"{"status":"approved"}"#),
+ ])
+ .await;
+ let pending = begin(&format!("{host}/v1")).await.expect("begin");
+ let err = pending.claim().await.expect_err("no key is not a claim");
+ assert_eq!(
+ err,
+ "could not confirm the sign-in before the window closed: the sign-in was approved \
+ but Tokamak returned no API key. Run `jan login` again."
+ );
+ });
+ }
+
+ /// A rejected verifier is the server judging this session, so re-polling it
+ /// can only fail the same way -- fail now instead of at the deadline.
+ #[test]
+ fn a_rejected_session_fails_without_retrying() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let (host, requests) = mock_server(vec![
+ (
+ 200,
+ r#"{"session_id":"s","user_code":"A-1","expires_in":300,"interval":1}"#,
+ ),
+ (401, r#"{"error":"bad verifier"}"#),
+ (
+ 200,
+ r#"{"status":"approved","api_key":{"key":"sk_live_x"}}"#,
+ ),
+ ])
+ .await;
+ let pending = begin(&format!("{host}/v1")).await.expect("begin");
+ let err = pending.claim().await.expect_err("401 must fail");
+ assert!(err.contains("could not be verified"), "{err}");
+ assert_eq!(requests.lock().unwrap().len(), 2, "no poll after the 401");
+ });
+ }
+
+ /// A server that predates the flow answers 404 (405 on some proxies); both
+ /// are the signal to fall back to the paste flow, and neither is an error
+ /// the user should see.
+ #[test]
+ fn a_legacy_server_reports_unsupported() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ for status in [404, 405] {
+ let (host, _) =
+ mock_server(vec![(status, r#"{"error":"auth route not found"}"#)]).await;
+ match begin(&format!("{host}/v1")).await {
+ Err(BeginError::Unsupported) => {}
+ Err(BeginError::Failed(e)) => panic!("HTTP {status} must be Unsupported: {e}"),
+ Ok(_) => panic!("HTTP {status} must not yield a session"),
+ }
+ }
+ });
+ }
+
+ /// The `/v1` gate answers 401 for paths it does not know, so a 401 must not
+ /// be mistaken for "unsupported" -- it means we asked the wrong host.
+ #[test]
+ fn a_401_is_a_failure_not_a_fallback() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let (host, _) =
+ mock_server(vec![(401, r#"{"error":"authentication required"}"#)]).await;
+ match begin(&format!("{host}/v1")).await {
+ Err(BeginError::Failed(e)) => assert!(e.contains("should not require auth"), "{e}"),
+ Err(BeginError::Unsupported) => panic!("401 must not read as unsupported"),
+ Ok(_) => panic!("401 must not yield a session"),
+ }
+ });
+ }
+
+ #[test]
+ fn unsupported_message_names_the_fallback() {
+ let msg = BeginError::Unsupported.message("https://api.tokamak.sh");
+ assert!(msg.contains("does not support browser sign-in"), "{msg}");
+ assert!(msg.contains("pasting an API key"), "{msg}");
+ }
+
+ /// A wake ping completes the wait; a wrong state does not.
+ #[test]
+ fn the_wake_listener_answers_only_its_own_state() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let wake = WakeServer::bind("st-1".to_string()).await.expect("bind");
+ let port = wake.port;
+
+ let ping = tokio::spawn(async move {
+ let client = reqwest::Client::new();
+ // A wrong state is refused...
+ let bad = client
+ .get(format!("http://127.0.0.1:{port}/done?state=nope"))
+ .send()
+ .await
+ .expect("bad ping");
+ assert_eq!(bad.status().as_u16(), 404);
+ // ...and the right one is accepted, with CORS on the reply.
+ let ok = client
+ .get(format!("http://127.0.0.1:{port}/done?state=st-1"))
+ .send()
+ .await
+ .expect("good ping");
+ assert_eq!(ok.status().as_u16(), 200);
+ assert_eq!(ok.headers()["access-control-allow-origin"], "*");
+ });
+
+ assert!(
+ wake.wait(Duration::from_secs(5)).await,
+ "the matching ping must wake the poll"
+ );
+ ping.await.unwrap();
+ });
+ }
+
+ #[test]
+ fn the_wake_listener_times_out_without_a_ping() {
+ let rt = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let wake = WakeServer::bind("st-1".to_string()).await.expect("bind");
+ assert!(!wake.wait(Duration::from_millis(50)).await);
+ });
+ }
+
+ /// Serve `replies` in order, recording each request. Returns the origin to
+ /// point a client at plus the recorded requests.
+ async fn mock_server(
+ replies: Vec<(u16, &'static str)>,
+ ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
+ .await
+ .unwrap();
+ let host = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
+ let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let recorded = requests.clone();
+
+ tokio::spawn(async move {
+ for (status, body) in replies {
+ let Ok((mut sock, _)) = listener.accept().await else {
+ return;
+ };
+ let mut buf = vec![0u8; 4096];
+ let n = sock.read(&mut buf).await.unwrap_or(0);
+ recorded
+ .lock()
+ .unwrap()
+ .push(String::from_utf8_lossy(&buf[..n]).to_string());
+ let reason = if (200..300).contains(&status) {
+ "OK"
+ } else {
+ "Error"
+ };
+ let response = format!(
+ "HTTP/1.1 {status} {reason}\r\ncontent-length: {}\r\n\
+ content-type: application/json\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = sock.write_all(response.as_bytes()).await;
+ }
+ });
+
+ (host, requests)
+ }
+}
diff --git a/src-tauri/src/core/cli/login.rs b/src-tauri/src/core/cli/login.rs
index 2a6cd484e..1f554e3ec 100644
--- a/src-tauri/src/core/cli/login.rs
+++ b/src-tauri/src/core/cli/login.rs
@@ -20,7 +20,9 @@ const KEY_PROMPT: &str = "Paste your Tokamak API key: ";
/// to show the sign-in notice in and nobody to act on it. No-op otherwise --
/// an interactive run with no provider proceeds and the TUI shows its own
/// notice instead of forcing a login flow here.
-pub fn reject_headless_without_provider(project_root: Option<&std::path::Path>) -> Result<(), String> {
+pub fn reject_headless_without_provider(
+ project_root: Option<&std::path::Path>,
+) -> Result<(), String> {
if super::providers::has_usable_provider(project_root) {
return Ok(());
}
@@ -30,16 +32,72 @@ pub fn reject_headless_without_provider(project_root: Option<&std::path::Path>)
Ok(())
}
-/// Sign in to Tokamak from a plain terminal: point the user at the API-keys
-/// page, read the key they paste (hidden), verify it, and persist it.
+/// Sign in to Tokamak from a plain terminal.
///
-/// A piped stdin (`echo $KEY | jan login`) is verified directly instead: there
-/// is no browser to open and no prompt to answer, so scripting it is the only
-/// sensible reading.
-pub async fn run_login() -> Result<(), String> {
+/// The default flow is browser-approval: the CLI creates a sign-in session,
+/// opens the authorize page (any device can approve), and polls for the minted
+/// key. When the server predates the `/auth/cli/sessions` endpoints (404/405 on
+/// create), it falls back to the legacy paste-a-key flow automatically; a piped
+/// stdin (`echo $KEY | jan login`) and `--paste-token` force the paste flow.
+pub async fn run_login(paste_token: bool) -> Result<(), String> {
if !std::io::stdin().is_terminal() {
return login_from_stdin().await;
}
+ if paste_token {
+ return login_by_paste().await;
+ }
+ match device_login_interactive().await {
+ // A deployment that predates the flow is not an error, but say which
+ // flow you ended up in -- otherwise a paste prompt looks like the
+ // browser sign-in silently failing.
+ Err(DeviceLogin::Unsupported) => {
+ println!();
+ println!("This Tokamak deployment does not support browser sign-in yet.");
+ login_by_paste().await
+ }
+ Err(DeviceLogin::Failed(e)) => Err(e),
+ Ok(()) => Ok(()),
+ }
+}
+
+/// Why the browser flow did not complete, split so `run_login` can fall back on
+/// "this server is too old" without inspecting prose.
+enum DeviceLogin {
+ Unsupported,
+ Failed(String),
+}
+
+/// The device (browser-approval) login, interactive.
+async fn device_login_interactive() -> Result<(), DeviceLogin> {
+ use super::device_auth::{self, BeginError};
+
+ let base = tokamak::base_url();
+ let pending = match device_auth::begin(&base).await {
+ Ok(pending) => pending,
+ Err(BeginError::Unsupported) => return Err(DeviceLogin::Unsupported),
+ Err(e) => return Err(DeviceLogin::Failed(e.message(&base))),
+ };
+
+ println!();
+ println!("Sign in to Tokamak in your browser.");
+ let session = pending.session();
+ println!(" confirm this code matches: {}", session.user_code);
+ println!(" {}", session.authorize_url);
+ match super::browser::open(&session.authorize_url) {
+ Ok(()) => println!(" (opening that page in your browser)"),
+ Err(e) => println!(" (open that URL yourself: {e})"),
+ }
+ println!(" waiting for approval... (approve from any device, Ctrl-C to cancel)");
+
+ let login = tokamak::device_login(pending)
+ .await
+ .map_err(DeviceLogin::Failed)?;
+ report(&login);
+ Ok(())
+}
+
+/// The legacy paste-a-key login, interactive.
+async fn login_by_paste() -> Result<(), String> {
println!();
println!("Sign in to Tokamak and create an API key:");
println!(" {}", tokamak::API_KEYS_URL);
@@ -122,7 +180,7 @@ fn piped_empty_message() -> String {
$TOKAMAK_API_KEY | jan login\nor set it directly:\n jan config set --provider {} \
--api-key <key> --base-url {}",
tokamak::PROVIDER,
- tokamak::BASE_URL
+ tokamak::base_url()
)
}
@@ -143,6 +201,9 @@ fn report(login: &tokamak::Login) {
1 => println!("Signed in to Tokamak - 1 model available."),
n => println!("Signed in to Tokamak - {n} models available."),
}
+ if let Some(account) = &login.account {
+ println!(" account: {account}");
+ }
println!(" key saved to {}", login.config_path.display());
if let Some(model) = &login.default_model {
println!(" default model: {model}");
@@ -171,12 +232,19 @@ mod tests {
#[test]
fn report_survives_every_model_count() {
- for models in [Vec::new(), vec!["m".to_string()], vec!["a".into(), "b".into()]] {
- report(&tokamak::Login {
- models,
- config_path: std::path::PathBuf::from("/tmp/config.toml"),
- default_model: Some("a".to_string()),
- });
+ for models in [
+ Vec::new(),
+ vec!["m".to_string()],
+ vec!["a".into(), "b".into()],
+ ] {
+ for account in [None, Some("[email protected]".to_string())] {
+ report(&tokamak::Login {
+ models: models.clone(),
+ config_path: std::path::PathBuf::from("/tmp/config.toml"),
+ default_model: Some("a".to_string()),
+ account,
+ });
+ }
}
}
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 9c61a8add..bb50297d2 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -4,6 +4,7 @@
pub mod brand;
pub mod browser;
+pub mod device_auth;
pub mod journal;
pub mod login;
pub mod mcp;
@@ -567,6 +568,7 @@ pub fn cli_agent_config_set(
base_url,
models,
api_type,
+ ..Default::default()
},
)
}
@@ -1801,6 +1803,7 @@ mod tests {
base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),
models: Some(vec!["tokamak-1-preview".into()]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rs
index 02d7a78ae..c267a0155 100644
--- a/src-tauri/src/core/cli/providers.rs
+++ b/src-tauri/src/core/cli/providers.rs
@@ -295,6 +295,7 @@ pub async fn fetch_missing_models(
base_url: None,
models: Some(models),
api_type: None,
+ ..Default::default()
},
)?;
populated = true;
@@ -922,6 +923,7 @@ mod tests {
base_url: Some(format!("http://{addr}/v1")),
models: Some(vec![]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -949,6 +951,7 @@ mod tests {
base_url: Some("http://127.0.0.1:9/v1".into()), // would refuse
models: Some(vec!["my-model".into()]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -977,6 +980,7 @@ mod tests {
base_url: Some(format!("http://{addr}/v1")),
models: Some(vec![]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -1026,6 +1030,7 @@ mod tests {
base_url: Some(format!("http://{addr}/v1")),
models: Some(vec![]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -1053,6 +1058,7 @@ mod tests {
base_url: Some("http://127.0.0.1:9/v1".into()), // refuses instantly
models: Some(vec![]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
diff --git a/src-tauri/src/core/cli/tokamak.rs b/src-tauri/src/core/cli/tokamak.rs
index 58f7aef5a..c9b03479e 100644
--- a/src-tauri/src/core/cli/tokamak.rs
+++ b/src-tauri/src/core/cli/tokamak.rs
@@ -1,15 +1,23 @@
//! Tokamak sign-in for the headless CLI.
//!
//! Tokamak is an ordinary OpenAI-compatible upstream as far as the agent is
-//! concerned (Bearer key + `{base_url}/chat/completions`), so "login" is just:
-//! send the user to the web UI to mint an API key, verify what they paste
-//! against `GET /v1/models`, and persist it as a provider entry in
+//! concerned (Bearer key + `{base_url}/chat/completions`), so historically
+//! "login" was just: send the user to the web UI to mint an API key, verify what
+//! they paste against `GET /v1/models`, and persist it as a provider entry in
//! `~/.jan/config.toml`. No OAuth, no callback server, no browser required --
-//! the key can always be pasted from another machine.
+//! the key could always be pasted from another machine.
//!
-//! Presentation lives in the callers ([`super::mod`] for the fresh-install
-//! prompt, [`super::tui`] for `/login`); this module is UI-free so both share
-//! one implementation.
+//! The default flow is now the browser-approval device flow
+//! ([`device_login`] / [`super::device_auth`]): the server mints a fresh
+//! `sk_live_*` key after the user approves in a browser on any device, and only
+//! the PKCE verifier ever rides the network -- never the key. The legacy
+//! paste-a-key flow ([`login`]) remains for deployments that predate the
+//! `/auth/cli/sessions` endpoints (404/405 on create -- the caller falls back to
+//! it automatically) and for `--paste-token`.
+//!
+//! Presentation lives in the callers ([`super::login`] for the plain terminal,
+//! [`super::tui`] for `/login`); this module is UI-free so both share one
+//! implementation.
use std::path::PathBuf;
use std::time::Duration;
@@ -18,9 +26,31 @@ use crate::core::agent::global_config::{set_default_model_if_unset, set_provider
/// Provider id this login writes to in `~/.jan/config.toml`.
pub const PROVIDER: &str = "tokamak";
-/// OpenAI-compatible API root. Persisted (not hardcoded at call sites) so a user
-/// can retarget it by editing the config afterwards.
+/// Default OpenAI-compatible API root. Read through [`base_url`] rather than
+/// directly, so a dev or self-hosted deployment can be targeted without a
+/// rebuild; persisted into the config so a user can also retarget it by hand
+/// afterwards.
pub const BASE_URL: &str = "https://api.tokamak.sh/v1";
+
+/// Env var selecting a non-production deployment, matching the name the tokamak
+/// CLI already uses. Without it there is no way to exercise the browser sign-in
+/// against a dev stack before it reaches production.
+pub const BASE_URL_ENV: &str = "TOKAMAK_BASE_URL";
+
+/// The API root this run talks to: `$TOKAMAK_BASE_URL` when set, else
+/// [`BASE_URL`].
+pub fn base_url() -> String {
+ resolve_base_url(std::env::var(BASE_URL_ENV).ok().as_deref())
+}
+
+/// Split from [`base_url`] so the precedence is testable without mutating the
+/// process environment (which every other test in this binary shares).
+fn resolve_base_url(from_env: Option<&str>) -> String {
+ from_env
+ .map(|v| v.trim().trim_end_matches('/'))
+ .filter(|v| !v.is_empty())
+ .map_or_else(|| BASE_URL.to_string(), str::to_string)
+}
/// Where the user signs in and mints a key.
pub const API_KEYS_URL: &str = "https://tokamak.sh/settings/api-keys";
@@ -33,6 +63,9 @@ pub struct Login {
pub config_path: PathBuf,
/// The model written to `default_model`, or `None` when the user already had one.
pub default_model: Option<String>,
+ /// Who the server says signed in. Only the browser flow reports one; the
+ /// paste flow never learns it.
+ pub account: Option<String>,
}
/// Trim a pasted key and reject anything that isn't plausibly one. Terminals and
@@ -58,12 +91,13 @@ async fn verify_key(api_key: &str) -> Result<Vec<String>, String> {
.timeout(VERIFY_TIMEOUT)
.build()
.map_err(|e| e.to_string())?;
+ let root = base_url();
let response = client
- .get(format!("{BASE_URL}/models"))
+ .get(format!("{root}/models"))
.header("Authorization", format!("Bearer {api_key}"))
.send()
.await
- .map_err(|e| format!("could not reach {BASE_URL}: {e}"))?;
+ .map_err(|e| format!("could not reach {root}: {e}"))?;
let status = response.status();
let body = response.text().await.unwrap_or_default();
@@ -91,9 +125,14 @@ fn persist(api_key: &str, models: Vec<String>) -> Result<Login, String> {
PROVIDER,
ProviderUpdate {
api_key: Some(api_key.to_string()),
- base_url: Some(BASE_URL.to_string()),
+ base_url: Some(base_url()),
models: Some(models.clone()),
api_type: None,
+ // A pasted key carries no metadata, and any left over from a
+ // previous browser login belongs to a key this one replaces.
+ key_id: Some(None),
+ key_expires_at: Some(None),
+ account: Some(None),
},
)?;
let default_model = match models.first() {
@@ -104,9 +143,225 @@ fn persist(api_key: &str, models: Vec<String>) -> Result<Login, String> {
models,
config_path,
default_model,
+ // The paste flow verifies a key against `/v1/models`; it never learns
+ // who the key belongs to.
+ account: None,
+ })
+}
+
+/// Run the device (browser-approval) login to completion and persist the
+/// minted key. `pending` comes from [`super::device_auth::begin`].
+///
+/// The claim reply carries the key and its metadata but no model list, so the
+/// models are resolved the same way the paste flow resolves them -- a
+/// `GET /v1/models` with the fresh key. That doubles as a check that the minted
+/// key actually works before anything is written.
+pub(crate) async fn device_login(
+ pending: super::device_auth::PendingAuth,
+) -> Result<Login, String> {
+ let minted = pending.claim().await?;
+ let models = verify_key(&minted.api_key).await?;
+ persist_minted(&minted, models)
+}
+
+/// Persist a verified key plus the server-assigned key metadata (`key_id`/
+/// `key_expires_at`, so `auth status` can show the expiry and logout can revoke
+/// this exact key), adopting the first model as `default_model` when the user
+/// has none.
+fn persist_minted(
+ minted: &super::device_auth::Minted,
+ models: Vec<String>,
+) -> Result<Login, String> {
+ let config_path = set_provider(
+ PROVIDER,
+ ProviderUpdate {
+ api_key: Some(minted.api_key.clone()),
+ base_url: Some(base_url()),
+ models: Some(models.clone()),
+ api_type: None,
+ // Written even when the server sent nothing, so a re-login cannot
+ // leave the previous key's id behind to be revoked by mistake.
+ key_id: Some(minted.key_id.clone()),
+ key_expires_at: Some(minted.key_expires_at),
+ account: Some(minted.account.clone()),
+ },
+ )?;
+ let default_model = match models.first() {
+ Some(first) if set_default_model_if_unset(first)? => Some(first.clone()),
+ _ => None,
+ };
+ Ok(Login {
+ models,
+ config_path,
+ default_model,
+ account: minted.account.clone(),
+ })
+}
+
+/// What a sign-out actually did, so the caller does not claim a revocation that
+/// never happened.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Logout {
+ /// Nothing was configured.
+ NothingToDo,
+ /// The local entry is gone and the server confirmed the key is revoked.
+ ClearedAndRevoked,
+ /// The local entry is gone, but the key was not revoked upstream -- no
+ /// `key_id` was recorded (a legacy paste login) or the call did not land.
+ ClearedOnly,
+}
+
+/// Sign out: revoke the stored key server-side (best-effort) and clear the
+/// `tokamak` provider entry. Local sign-out always happens even if the
+/// revocation call fails, so a network problem cannot strand the user signed in
+/// locally -- but the result says which of the two happened.
+pub async fn logout() -> Result<Logout, String> {
+ use crate::core::agent::global_config::{provider_key_meta, remove_provider};
+
+ let meta = provider_key_meta(PROVIDER).unwrap_or_default();
+ let key = stored_api_key();
+ if meta.key_id.is_none() && key.is_none() {
+ return Ok(Logout::NothingToDo);
+ }
+
+ // Revoking needs both the server-side id and the key itself to authenticate
+ // the call; a legacy paste login recorded no id, so it can only clear local.
+ let revoked = match (&meta.key_id, &key) {
+ (Some(key_id), Some(key)) => revoke_key(key_id, key).await,
+ _ => false,
+ };
+
+ remove_provider(PROVIDER)?;
+ Ok(match revoked {
+ true => Logout::ClearedAndRevoked,
+ false => Logout::ClearedOnly,
})
}
+fn stored_api_key() -> Option<String> {
+ use crate::core::agent::global_config::load_global_config;
+ load_global_config()
+ .ok()?
+ .get(PROVIDER)
+ .and_then(|c| c.api_key.clone())
+ .filter(|k| !k.is_empty())
+}
+
+/// Revoke `key_id` server-side, authenticating with the key itself. Best-effort
+/// by contract -- logout must never be blocked by this call -- so the result is
+/// a plain "did it land", never an error.
+///
+/// `DELETE /auth/api-keys/{id}` is the real route: unauthenticated it answers
+/// `401 user context missing`, while `DELETE /auth/api-keys` (no id) and
+/// `GET /auth/api-keys/{id}` both answer `404 auth route not found`.
+async fn revoke_key(key_id: &str, api_key: &str) -> bool {
+ let Ok(client) = reqwest::Client::builder().timeout(VERIFY_TIMEOUT).build() else {
+ return false;
+ };
+ let root = super::device_auth::api_root(&base_url());
+ client
+ .delete(format!("{root}/auth/api-keys/{key_id}"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .is_ok_and(|r| r.status().is_success())
+}
+
+/// What `jan auth status` reports, without touching the network.
+#[derive(Debug, Clone, Default, serde::Serialize)]
+pub struct AuthStatus {
+ pub signed_in: bool,
+ pub endpoint: String,
+ pub account: Option<String>,
+ pub key_id: Option<String>,
+ pub key_expires_at: Option<u64>,
+}
+
+/// Read the local auth state for Tokamak.
+pub fn auth_status() -> AuthStatus {
+ use crate::core::agent::global_config::provider_key_meta;
+
+ let meta = provider_key_meta(PROVIDER).unwrap_or_default();
+ AuthStatus {
+ signed_in: stored_api_key().is_some(),
+ endpoint: base_url(),
+ account: meta.account,
+ key_id: meta.key_id,
+ key_expires_at: meta.key_expires_at,
+ }
+}
+
+/// How close to expiry a stored key has to be before the CLI says so unprompted,
+/// rather than letting the user discover it as a 401 mid-run.
+pub const EXPIRY_WARNING_WINDOW: Duration = Duration::from_secs(7 * 24 * 60 * 60);
+
+/// A one-line warning when the stored key is expired or about to be. `None` when
+/// there is no key, no recorded expiry (a legacy paste login records none), or
+/// the expiry is comfortably far off.
+pub fn expiry_warning() -> Option<String> {
+ let expires_at = auth_status().key_expires_at?;
+ describe_expiry(expires_at, unix_now())
+}
+
+fn unix_now() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+/// Split from [`expiry_warning`] so the wording can be tested without pinning
+/// the wall clock.
+fn describe_expiry(expires_at: u64, now: u64) -> Option<String> {
+ if expires_at == 0 {
+ return None;
+ }
+ let Some(remaining) = expires_at.checked_sub(now) else {
+ return Some(
+ "your Tokamak key has expired - run `jan login` to sign in again.".to_string(),
+ );
+ };
+ if remaining > EXPIRY_WARNING_WINDOW.as_secs() {
+ return None;
+ }
+ let days = remaining / (24 * 60 * 60);
+ Some(match days {
+ 0 => "your Tokamak key expires within a day - run `jan login` to renew it.".to_string(),
+ 1 => "your Tokamak key expires in 1 day - run `jan login` to renew it.".to_string(),
+ n => format!("your Tokamak key expires in {n} days - run `jan login` to renew it."),
+ })
+}
+
+/// Who the stored key belongs to, as recorded when it was minted. Read from the
+/// config rather than looked up: the browser flow's claim reply already names
+/// the account, so there is no round trip and no identity-endpoint response
+/// shape to guess. `None` after a legacy paste login, which never learns it.
+pub fn account() -> Option<String> {
+ use crate::core::agent::global_config::provider_key_meta;
+ provider_key_meta(PROVIDER).ok()?.account
+}
+
+/// Whether the stored key is currently accepted by the upstream: a live check
+/// against `GET /v1/models`. `None` when there is no key to check (not signed
+/// in), otherwise the pass/fail. A network the CLI cannot reach is reported as
+/// `None` so a blip does not read as an invalid key.
+pub async fn live_valid() -> Option<bool> {
+ use crate::core::agent::global_config::load_global_config;
+ let key = load_global_config()
+ .ok()
+ .and_then(|c| c.get(PROVIDER).cloned())
+ .and_then(|c| c.api_key)?;
+ if key.is_empty() {
+ return Some(false);
+ }
+ match verify_key(&key).await {
+ // A 401/403 is an invalid key; a network blip should not read as one.
+ Ok(_) => Some(true),
+ Err(e) if e.contains("could not reach") => None,
+ Err(_) => Some(false),
+ }
+}
+
/// Human-readable reason a verification request was rejected.
fn describe_failure(status: u16, body: &str) -> String {
match status {
@@ -279,4 +534,188 @@ mod tests {
assert_eq!(cfg.models, vec!["m-c".to_string()]);
});
}
+
+ /// Build a claim result the way `device_auth` hands one over.
+ fn minted(key_id: Option<&str>, expires_at: Option<u64>) -> super::super::device_auth::Minted {
+ super::super::device_auth::Minted {
+ api_key: "sk_live_x".to_string(),
+ key_id: key_id.map(str::to_string),
+ key_expires_at: expires_at,
+ account: Some("[email protected]".to_string()),
+ }
+ }
+
+ /// A browser-flow mint records `key_id`/`key_expires_at`, so `auth status`
+ /// can show the expiry and logout can revoke that exact key.
+ #[test]
+ fn persist_minted_records_the_server_key_metadata() {
+ with_temp_home(|_| {
+ use crate::core::agent::global_config::provider_key_meta;
+ let login = persist_minted(&minted(Some("k-1"), Some(1700000000)), vec!["m-a".into()])
+ .expect("persist");
+ assert_eq!(login.default_model.as_deref(), Some("m-a"));
+ assert_eq!(login.account.as_deref(), Some("[email protected]"));
+
+ let configs = load_global_config().expect("load");
+ let cfg = configs.get(PROVIDER).unwrap();
+ assert_eq!(cfg.api_key.as_deref(), Some("sk_live_x"));
+
+ let meta = provider_key_meta(PROVIDER).expect("meta");
+ assert_eq!(meta.key_id.as_deref(), Some("k-1"));
+ assert_eq!(meta.key_expires_at, Some(1700000000));
+ });
+ }
+
+ /// A legacy paste login writes no key metadata, so auth status falls back to
+ /// the key-only shape rather than erroring.
+ #[test]
+ fn legacy_persist_writes_no_key_metadata() {
+ with_temp_home(|_| {
+ persist("tk-1", vec![]).expect("persist");
+ use crate::core::agent::global_config::provider_key_meta;
+ let meta = provider_key_meta(PROVIDER).expect("meta");
+ assert!(meta.key_id.is_none());
+ assert!(meta.key_expires_at.is_none());
+ });
+ }
+
+ /// The account rides the mint, so `auth status` can name it with no round
+ /// trip -- and a paste login that never learns one must not inherit a stale
+ /// account from the key it replaced.
+ #[test]
+ fn the_account_is_recorded_by_the_mint_and_cleared_by_a_paste() {
+ with_temp_home(|_| {
+ persist_minted(&minted(Some("k-1"), None), vec![]).expect("persist");
+ assert_eq!(account().as_deref(), Some("[email protected]"));
+ assert_eq!(auth_status().account.as_deref(), Some("[email protected]"));
+
+ persist("tk-pasted", vec![]).expect("persist paste");
+ assert_eq!(
+ account(),
+ None,
+ "a paste login must not keep the old account"
+ );
+ assert_eq!(auth_status().account, None);
+ });
+ }
+
+ #[test]
+ fn auth_status_reflects_signed_in_state_and_metadata() {
+ with_temp_home(|_| {
+ assert!(!auth_status().signed_in);
+ persist_minted(&minted(Some("k-1"), Some(1700000000)), vec![]).expect("persist");
+ let status = auth_status();
+ assert!(status.signed_in);
+ assert_eq!(status.endpoint, BASE_URL);
+ assert_eq!(status.key_id.as_deref(), Some("k-1"));
+ assert_eq!(status.key_expires_at, Some(1700000000));
+ });
+ }
+
+ /// A dev or self-hosted deployment must be reachable without a rebuild, and
+ /// an unset/blank var must not produce an empty base url.
+ #[test]
+ fn base_url_prefers_the_env_override() {
+ assert_eq!(resolve_base_url(None), BASE_URL);
+ assert_eq!(resolve_base_url(Some("")), BASE_URL);
+ assert_eq!(resolve_base_url(Some(" ")), BASE_URL);
+ assert_eq!(
+ resolve_base_url(Some("https://api.dev.tokamak.sh/v1")),
+ "https://api.dev.tokamak.sh/v1"
+ );
+ // A trailing slash would double up in `{base}/models`.
+ assert_eq!(
+ resolve_base_url(Some(" http://localhost:8080/v1/ ")),
+ "http://localhost:8080/v1"
+ );
+ }
+
+ /// The warning window is the point of storing `key_expires_at` at all: a
+ /// key must announce itself before it 401s mid-run.
+ #[test]
+ fn expiry_is_only_described_inside_the_warning_window() {
+ const DAY: u64 = 24 * 60 * 60;
+ let now = 1_700_000_000;
+ // Comfortably far off: nothing to say.
+ assert_eq!(describe_expiry(now + 30 * DAY, now), None);
+ assert_eq!(describe_expiry(now + 8 * DAY, now), None);
+ // An unrecorded expiry is not an expired key.
+ assert_eq!(describe_expiry(0, now), None);
+
+ let soon = describe_expiry(now + 6 * DAY, now).expect("inside the window");
+ assert!(soon.contains("6 days"), "{soon}");
+ assert!(soon.contains("jan login"), "{soon}");
+
+ assert!(describe_expiry(now + DAY + 60, now)
+ .expect("1 day")
+ .contains("in 1 day"));
+ assert!(describe_expiry(now + 600, now)
+ .expect("today")
+ .contains("within a day"));
+ // Already gone -- and subtraction must not wrap.
+ let gone = describe_expiry(now - DAY, now).expect("expired");
+ assert!(gone.contains("has expired"), "{gone}");
+ }
+
+ /// A legacy paste login records no expiry, so the warning must stay quiet
+ /// rather than inventing one.
+ #[test]
+ fn expiry_warning_is_quiet_without_a_recorded_expiry() {
+ with_temp_home(|_| {
+ persist("tk-1", vec![]).expect("persist");
+ assert_eq!(expiry_warning(), None);
+ });
+ }
+
+ #[test]
+ fn expiry_warning_fires_for_a_key_that_is_about_to_lapse() {
+ with_temp_home(|_| {
+ let soon = unix_now() + 2 * 24 * 60 * 60;
+ persist_minted(&minted(Some("k-1"), Some(soon)), vec![]).expect("persist");
+ let warning = expiry_warning().expect("a key expiring in 2 days must warn");
+ assert!(warning.contains("2 days"), "{warning}");
+ });
+ }
+
+ fn run_logout() -> Logout {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(logout())
+ .expect("logout")
+ }
+
+ #[test]
+ fn logout_with_nothing_configured_is_a_no_op() {
+ with_temp_home(|_| assert_eq!(run_logout(), Logout::NothingToDo));
+ }
+
+ /// Without a recorded `key_id` there is nothing to revoke, so logout must
+ /// still clear the local entry -- and must not claim a revocation.
+ #[test]
+ fn logout_without_a_key_id_clears_locally_only() {
+ with_temp_home(|_| {
+ persist_minted(&minted(None, None), vec!["m-a".into()]).expect("persist");
+ assert!(auth_status().signed_in);
+
+ assert_eq!(run_logout(), Logout::ClearedOnly);
+ assert!(!auth_status().signed_in);
+
+ // The provider entry is fully gone.
+ let configs = load_global_config().expect("load");
+ assert!(!configs.contains_key(PROVIDER));
+ });
+ }
+
+ /// A revoke call that cannot land (no server here) must not strand the user
+ /// signed in locally, and must report that the key survives upstream.
+ #[test]
+ fn logout_clears_locally_even_when_revocation_fails() {
+ with_temp_home(|_| {
+ persist_minted(&minted(Some("k-1"), None), vec!["m-a".into()]).expect("persist");
+ assert_eq!(run_logout(), Logout::ClearedOnly);
+ assert!(!auth_status().signed_in);
+ });
+ }
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index b23bdc7dc..d6c9ad5e6 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -529,15 +529,75 @@ enum McpJobDone {
},
}
-/// `/login` key entry: a docked prompt that collects a Tokamak API key without
-/// echoing it. Verification runs off the render loop (see `login_task` in
-/// `chat_loop`), so `verifying` marks the window where the prompt is read-only.
+/// A browser launch held back for confirmation, for flows with no dock of their
+/// own to ask in (currently `/mcp` authorization).
+struct BrowserConfirm {
+ url: String,
+ /// What the page is for, e.g. `authorize 'github'`.
+ purpose: String,
+}
+
+/// Which sign-in the `/login` dock is running. The browser flow is the default;
+/// the paste field is what a server predating it (or a failure) falls back to.
+enum LoginStage {
+ /// Creating the session -- one round trip before there is a code to show.
+ Connecting,
+ /// Waiting on the browser. The code is displayed so the user can check it
+ /// against the approve page before clicking Approve.
+ ///
+ /// While `confirm_open` is set the user has not yet said whether to launch a
+ /// browser here. The poll runs regardless, so approving from a phone still
+ /// completes the sign-in without ever answering.
+ Approving {
+ user_code: String,
+ authorize_url: String,
+ confirm_open: bool,
+ },
+ /// Legacy paste-a-key entry. `confirm_open` gates sending the user to the
+ /// API-keys page; the field only accepts a key once that is answered.
+ Paste { confirm_open: bool },
+}
+
+impl LoginStage {
+ /// The page this stage would send the user to, while that is still unasked.
+ fn unconfirmed_url(&self) -> Option<&str> {
+ match self {
+ Self::Approving {
+ authorize_url,
+ confirm_open: true,
+ ..
+ } => Some(authorize_url),
+ Self::Paste { confirm_open: true } => Some(super::tokamak::API_KEYS_URL),
+ _ => None,
+ }
+ }
+
+ /// Mark the browser question answered, whichever stage asked it.
+ fn mark_confirmed(&mut self) {
+ match self {
+ Self::Approving { confirm_open, .. } | Self::Paste { confirm_open } => {
+ *confirm_open = false
+ }
+ Self::Connecting => {}
+ }
+ }
+}
+
+/// `/login`: a docked prompt that runs the browser-approval sign-in and, when
+/// that is unavailable, collects a Tokamak API key without echoing it. The
+/// network work runs off the render loop (see `login_*_task` in `chat_loop`), so
+/// `verifying` marks the window where the paste field is read-only.
+///
+/// The dock stays open for the whole flow, which is also what makes Esc a
+/// reliable cancel: `chat_loop` drops every in-flight sign-in task the moment
+/// `app.login` goes to `None`.
struct LoginPrompt {
/// The key as typed/pasted. Never rendered verbatim -- see `masked`.
input: String,
/// Why the previous attempt failed, shown above the field.
error: Option<String>,
verifying: bool,
+ stage: LoginStage,
}
impl LoginPrompt {
@@ -546,15 +606,30 @@ impl LoginPrompt {
input: String::new(),
error: None,
verifying: false,
+ stage: LoginStage::Paste { confirm_open: true },
}
}
+ /// The dock as `/login` opens it, before the session exists.
+ fn connecting() -> Self {
+ Self {
+ stage: LoginStage::Connecting,
+ ..Self::new()
+ }
+ }
+
+ /// Only the paste field accepts input, and only once the browser question is
+ /// answered; the approval stages are display-only throughout.
+ fn editable(&self) -> bool {
+ matches!(self.stage, LoginStage::Paste { confirm_open: false }) && !self.verifying
+ }
+
fn masked(&self) -> String {
super::secret_input::mask(self.input.chars().count())
}
fn paste(&mut self, text: &str) {
- if !self.verifying {
+ if self.editable() {
self.input.push_str(super::secret_input::pasted(text));
}
}
@@ -1480,6 +1555,12 @@ struct App {
probed_models: std::collections::HashSet<String>,
/// Key handed off to the loop to verify off the render loop. Taken once.
login_submit: Option<String>,
+ /// `/login` asked for the browser flow: `chat_loop` creates the session.
+ login_device_request: bool,
+ /// A `/mcp` authorization waiting on the user's yes/no before a browser is
+ /// launched. Holds only the URL and what it is for -- never the bound
+ /// loopback listener, which stays on the task awaiting the redirect.
+ browser_confirm: Option<BrowserConfirm>,
/// `/update` handed off to the loop, which spawns the install. Taken once.
update_requested: bool,
/// `/plugin install` handed off to the loop, which runs the git clone off
@@ -1935,6 +2016,8 @@ impl App {
provider_prompt: None,
probed_models: std::collections::HashSet::new(),
login_submit: None,
+ login_device_request: false,
+ browser_confirm: None,
update_requested: false,
plugin_install_request: None,
plugin_select_request: None,
@@ -2481,6 +2564,26 @@ impl App {
&& self.reasoning_open()
}
+ /// The open dock that owns the keyboard, phrased as what the user has to do
+ /// in it. `None` when the composer is live.
+ ///
+ /// Must mirror the guard list at the top of `handle_key`: a dock that takes
+ /// every keystroke but leaves a cursor blinking in the composer promises a
+ /// field that is not there.
+ fn blocking_dock(&self) -> Option<&'static str> {
+ if self.login.is_some() {
+ Some("sign in in the dock above")
+ } else if self.browser_confirm.is_some() {
+ Some("answer the question above")
+ } else if self.settings_prompt.is_some() {
+ Some("edit the setting above")
+ } else if self.mcp_prompt.is_some() || self.provider_prompt.is_some() {
+ Some("finish the wizard above")
+ } else {
+ None
+ }
+ }
+
/// True while the model is mid-reasoning: either a `<think>` block is live
/// in the answer buffer (inline-tag providers) or the newest native segment
/// is still at the tail, i.e. no content token has arrived since
@@ -5920,6 +6023,28 @@ async fn await_login(
}
}
+/// Await the session-creation half of the browser sign-in, parking forever when
+/// none is running so this can sit in the loop's `select!` unconditionally.
+async fn await_login_begin(
+ task: &mut Option<
+ tokio::task::JoinHandle<
+ Result<super::device_auth::PendingAuth, super::device_auth::BeginError>,
+ >,
+ >,
+) -> Result<super::device_auth::PendingAuth, super::device_auth::BeginError> {
+ let joined = match task.as_mut() {
+ Some(h) => h.await,
+ None => return pending().await,
+ };
+ *task = None;
+ match joined {
+ Ok(inner) => inner,
+ Err(e) => Err(super::device_auth::BeginError::Failed(format!(
+ "sign-in task failed: {e}"
+ ))),
+ }
+}
+
/// How often the dock's branch indicator re-reads `HEAD`, so a checkout made
/// outside the TUI (another terminal, an editor) shows up without needing a
/// restart. Cheap (`rev-parse --abbrev-ref HEAD`) but still shells out, so this
@@ -6180,6 +6305,10 @@ pub async fn run(
app.push_session_banner(!seeded);
if app.model.is_empty() {
app.note("not signed in β€” run /login to sign in to Tokamak, or `jan config set` to configure a provider manually");
+ } else if let Some(warning) = super::tokamak::expiry_warning() {
+ // Say it at launch rather than letting the key expire into a 401 in the
+ // middle of a run.
+ app.note(&warning);
}
// Only when there is nothing to load: a project that already has JAN.md needs
// no invitation, and the splash hint covers re-running /init deliberately.
@@ -6366,6 +6495,18 @@ async fn chat_loop<B: Backend>(
tokio::task::JoinHandle<Result<super::tokamak::Login, String>>,
> = None;
+ // The browser-approval sign-in, in two off-loop halves: `begin` creates the
+ // session (one round trip), then the claim polls until the user approves --
+ // which can take minutes, so it must never touch the render loop.
+ let mut login_begin_task: Option<
+ tokio::task::JoinHandle<
+ Result<super::device_auth::PendingAuth, super::device_auth::BeginError>,
+ >,
+ > = None;
+ let mut login_claim_task: Option<
+ tokio::task::JoinHandle<Result<super::tokamak::Login, String>>,
+ > = None;
+
// `/mcp` work that must not run on the render loop: a tool listing is a
// round trip to the peer, and an authorization waits on a browser for up to
// five minutes. One at a time -- the detail screen only ever asks for one.
@@ -6427,12 +6568,23 @@ async fn chat_loop<B: Backend>(
}
}
- // Esc closed the prompt while a verification was in flight: drop it, so a
- // late reply can't report a sign-in the user walked away from.
+ // Esc closed the dock while sign-in work was in flight: drop all of it,
+ // so a late reply can't report a sign-in the user walked away from. The
+ // dock stays open for the whole flow, so this is the one cancel path.
if app.login.is_none() {
- if let Some(task) = login_task.take() {
+ for task in [
+ login_task.take(),
+ login_claim_task.take(),
+ ]
+ .into_iter()
+ .flatten()
+ {
task.abort();
}
+ if let Some(task) = login_begin_task.take() {
+ task.abort();
+ }
+ app.login_device_request = false;
}
// The detail screen asked for something off-loop. One job at a time, and
@@ -6460,6 +6612,20 @@ async fn chat_loop<B: Backend>(
}
}
+ // `/login` asked for the browser flow: create the session off-loop. Only
+ // when nothing else sign-in shaped is already running, so a repeated
+ // `/login` cannot open two sessions.
+ if app.login_device_request
+ && login_begin_task.is_none()
+ && login_claim_task.is_none()
+ && login_task.is_none()
+ {
+ app.login_device_request = false;
+ login_begin_task = Some(tokio::spawn(async move {
+ super::device_auth::begin(&super::tokamak::base_url()).await
+ }));
+ }
+
// `/update` was typed: install off-loop. The flag is only honored when
// no install is in flight, so a repeated request can't spawn a second
// process rewriting the same binary.
@@ -6631,6 +6797,35 @@ async fn chat_loop<B: Backend>(
reload_provider_configs(app).await;
}
}
+ begun = await_login_begin(&mut login_begin_task) => {
+ match begun {
+ Ok(pending) => {
+ show_login_approval(app, pending.session());
+ login_claim_task =
+ Some(tokio::spawn(super::tokamak::device_login(pending)));
+ }
+ // Not a failure, but say it: an unexplained paste field
+ // reads as the browser sign-in having silently broken.
+ Err(super::device_auth::BeginError::Unsupported) => {
+ app.note("this Tokamak deployment does not support browser sign-in yet");
+ open_login_prompt(app);
+ }
+ Err(e) => {
+ app.note(&format!(
+ "browser sign-in unavailable: {}",
+ e.message(&super::tokamak::base_url())
+ ));
+ open_login_prompt(app);
+ }
+ }
+ }
+ claimed = await_login(&mut login_claim_task) => {
+ let login_ok = claimed.is_ok();
+ finish_login(app, claimed);
+ if login_ok {
+ reload_provider_configs(app).await;
+ }
+ }
update = await_update_check(&mut update_task) => {
note_update(app, update);
}
@@ -6888,7 +7083,11 @@ async fn handle_ask_key(
key: KeyEvent,
registry: &crate::core::agent::interaction::AskRegistry,
) -> bool {
- if app.ask_queue.is_empty() {
+ // A docked prompt owns the keyboard, and `handle_ask_key` runs before
+ // `handle_key` -- without this an ask queued by the running agent would
+ // swallow the secret being typed into `/login` and echo it into a custom
+ // answer that is then submitted to the model.
+ if app.ask_queue.is_empty() || app.blocking_dock().is_some() {
return false;
}
if key.kind == KeyEventKind::Release {
@@ -6978,6 +7177,9 @@ async fn handle_ask_mouse(
mouse: MouseEvent,
registry: &crate::core::agent::interaction::AskRegistry,
) -> bool {
+ if app.blocking_dock().is_some() {
+ return false;
+ }
let Some(ask) = app.ask_queue.front_mut() else {
return false;
};
@@ -7021,9 +7223,32 @@ fn handle_login_key(app: &mut App, key: KeyEvent, ctrl: bool) {
app.note("sign-in cancelled (run /login again any time)");
return;
}
+ // The browser question owns the keyboard until it is answered, so a
+ // keystroke meant for it can never fall through into the key field.
+ if app
+ .login
+ .as_ref()
+ .is_some_and(|p| p.stage.unconfirmed_url().is_some())
+ {
+ if ctrl {
+ return;
+ }
+ match key.code {
+ KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
+ resolve_login_browser(app, true)
+ }
+ KeyCode::Char('n') | KeyCode::Char('N') => resolve_login_browser(app, false),
+ _ => {}
+ }
+ return;
+ }
+
// Ctrl-V: terminals deliver a normal paste as `Event::Paste`, but some send
// Ctrl-V through as a key, so read the clipboard directly for those.
if ctrl && key.code == KeyCode::Char('v') {
+ if !app.login.as_ref().is_some_and(LoginPrompt::editable) {
+ return;
+ }
match super::secret_input::clipboard_text() {
Ok(text) => {
if let Some(prompt) = app.login.as_mut() {
@@ -7042,7 +7267,9 @@ fn handle_login_key(app: &mut App, key: KeyEvent, ctrl: bool) {
let Some(prompt) = app.login.as_mut() else {
return;
};
- if prompt.verifying {
+ // The browser stages have no field to edit -- only Esc, handled above, does
+ // anything. Same for a paste being verified.
+ if !prompt.editable() {
return;
}
match key.code {
@@ -7093,6 +7320,23 @@ async fn handle_key(
return;
}
+ // A pending browser question owns the keyboard the same way, so a `y`/`n`
+ // meant for it can never reach the input box or a transcript shortcut.
+ if app.browser_confirm.is_some() {
+ if !ctrl {
+ match key.code {
+ KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
+ resolve_mcp_browser(app, true)
+ }
+ KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
+ resolve_mcp_browser(app, false)
+ }
+ _ => {}
+ }
+ }
+ return;
+ }
+
// The `/settings` edit dock owns the keyboard while open, same as `/login`.
if app.settings_prompt.is_some() {
handle_settings_key(app, key, ctrl);
@@ -7997,8 +8241,8 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
},
SlashCommand {
name: "/login",
- hint: "",
- description: "Sign in to Tokamak and save the API key",
+ hint: "[--paste-token]",
+ description: "Sign in to Tokamak in a browser, or --paste-token to paste an API key",
},
SlashCommand {
name: "/config",
@@ -8188,7 +8432,7 @@ async fn run_command(
}
"mcp" => open_mcp_picker(app, mcp_servers).await,
"plugin" => plugin_command(app, arg).await,
- "login" => open_login_prompt(app),
+ "login" => login_command(app, arg),
"update" => update_command(app),
"config" => open_config_screen(app),
"terminal-setup" => terminal_setup_command(app),
@@ -10398,21 +10642,106 @@ fn clamp_line(line: Line<'static>, width: u16) -> Line<'static> {
Line::from(spans)
}
-/// Open the `/login` prompt: send the user to Tokamak's API-keys page and wait
-/// for the key they paste back. The URL is always written to the transcript, not
-/// just handed to the browser, so a headless or remote session can still be
-/// completed by hand.
+/// `/login [--paste-token]`: the browser flow, or the legacy paste field when
+/// the user asks for it explicitly (the same escape hatch `jan login` has).
+fn login_command(app: &mut App, arg: &str) {
+ // One sign-in at a time: the dock is open for the whole flow, and switching
+ // it under an in-flight session would either drop the new request (the
+ // browser flow) or have the arriving session clobber the paste field.
+ if app.login.is_some() {
+ app.note("a sign-in is already in progress - press Esc to cancel it first");
+ return;
+ }
+ match arg.split_whitespace().next() {
+ Some("--paste-token" | "--paste") => open_login_prompt(app),
+ Some(other) => app.note(&format!("/login: unknown option {other} (try --paste-token)")),
+ None => open_login(app),
+ }
+}
+
+/// Start `/login`: the browser-approval flow. The dock opens immediately, so
+/// there is something to Esc out of while the session is being created, and
+/// `chat_loop` picks the request up off the render loop.
+fn open_login(app: &mut App) {
+ app.login = Some(LoginPrompt::connecting());
+ app.login_device_request = true;
+}
+
+/// The session exists: show the code to check and the page to approve on, and
+/// open the browser. The URL goes to the transcript as well as the dock, so a
+/// remote or headless session can still be finished by hand -- or from a phone.
+fn show_login_approval(app: &mut App, session: &super::device_auth::Session) {
+ app.note("sign in to Tokamak in your browser - confirm this code matches:");
+ app.system_detail(vec![Span::styled(
+ session.user_code.clone(),
+ Style::new().cyan().bold(),
+ )]);
+ app.system_detail(vec![Span::styled(
+ session.authorize_url.clone(),
+ Style::new().cyan(),
+ )]);
+ app.login = Some(LoginPrompt {
+ stage: LoginStage::Approving {
+ user_code: session.user_code.clone(),
+ authorize_url: session.authorize_url.clone(),
+ confirm_open: true,
+ },
+ ..LoginPrompt::new()
+ });
+}
+
+/// Act on an answered "open a browser?" question: launch it, or say we didn't.
+/// Either way the URL is already in the transcript, so declining is a valid way
+/// to finish the flow on another device rather than a way to abandon it. Shared
+/// by `/login` and `/mcp`, which ask the same question in different docks.
+fn open_browser_reporting(app: &mut App, url: &str, open: bool) {
+ if !open {
+ app.system_detail_text("not opening a browser - use the URL above on any device");
+ return;
+ }
+ match super::browser::open(url) {
+ Ok(()) => app.system_detail_text("opening that page in your browser"),
+ Err(e) => app.system_detail_text(&format!("could not open a browser ({e})")),
+ }
+}
+
+/// Answer the question the `/login` dock is holding. The dock moves on either
+/// way, so the sign-in is never blocked on a browser.
+fn resolve_login_browser(app: &mut App, open: bool) {
+ let Some(url) = app
+ .login
+ .as_ref()
+ .and_then(|p| p.stage.unconfirmed_url())
+ .map(str::to_string)
+ else {
+ return;
+ };
+ open_browser_reporting(app, &url, open);
+ if let Some(prompt) = app.login.as_mut() {
+ prompt.stage.mark_confirmed();
+ }
+}
+
+/// Answer the standalone `/mcp` question. The authorization is already waiting on
+/// its loopback listener, so declining just means the user opens the URL
+/// themselves -- the redirect still completes the sign-in.
+fn resolve_mcp_browser(app: &mut App, open: bool) {
+ let Some(confirm) = app.browser_confirm.take() else {
+ return;
+ };
+ open_browser_reporting(app, &confirm.url, open);
+}
+
+/// Fall back to the paste field: send the user to Tokamak's API-keys page and
+/// wait for the key they paste back. The URL is always written to the
+/// transcript, not just handed to the browser, so a headless or remote session
+/// can still be completed by hand.
fn open_login_prompt(app: &mut App) {
app.note("sign in to Tokamak and create an API key:");
app.system_detail(vec![Span::styled(
super::tokamak::API_KEYS_URL,
Style::new().cyan(),
)]);
- let browser = match super::tokamak::open_api_keys_page() {
- Ok(()) => "opening that page in your browser".to_string(),
- Err(e) => format!("open that URL yourself ({e})"),
- };
- app.system_detail_text(&browser);
app.login = Some(LoginPrompt::new());
}
@@ -10423,22 +10752,35 @@ fn finish_login(app: &mut App, result: Result<super::tokamak::Login, String>) {
match result {
Ok(login) => {
app.login = None;
+ let who = match &login.account {
+ Some(account) => format!(" as {account}"),
+ None => String::new(),
+ };
app.note(&format!(
- "signed in to Tokamak - {} model(s) available, key saved to {}",
+ "signed in to Tokamak{who} - {} model(s) available, key saved to {}",
login.models.len(),
login.config_path.display()
));
+ if let Some(warning) = super::tokamak::expiry_warning() {
+ app.note(&warning);
+ }
adopt_login_model(app, &login);
}
Err(e) => {
- // Keep the prompt open with the reason: a rejected key is usually a
- // partial paste, and reopening from scratch loses that context.
- if let Some(prompt) = app.login.as_mut() {
- prompt.verifying = false;
- prompt.input.clear();
- prompt.error = Some(e);
- } else {
- app.note(&format!("sign-in failed: {e}"));
+ // Keep the paste field open with the reason: a rejected key is
+ // usually a partial paste, and reopening from scratch loses that
+ // context. A browser approval that was denied or expired has no
+ // field to correct, so the dock closes and the reason is noted.
+ match app.login.as_mut() {
+ Some(prompt) if prompt.editable() || prompt.verifying => {
+ prompt.verifying = false;
+ prompt.input.clear();
+ prompt.error = Some(e);
+ }
+ _ => {
+ app.login = None;
+ app.note(&format!("sign-in failed: {e}"));
+ }
}
}
}
@@ -10446,7 +10788,10 @@ fn finish_login(app: &mut App, result: Result<super::tokamak::Login, String>) {
/// Point the session at a Tokamak model when the current one is not runnable.
/// A model that already resolves is left alone: `/login` is also used to refresh
-/// an expired key, which must not silently switch models.
+/// an expired key, which must not silently switch models. "Runnable" is the
+/// CLI's own reachability (`is_cli_reachable`), so a local-engine model -- which
+/// this build can never resolve an upstream for -- is adopted away from rather
+/// than left as a session that cannot answer.
fn adopt_login_model(app: &mut App, login: &super::tokamak::Login) {
let runnable = super::providers::list_provider_models(Some(&app.project_root));
if runnable.iter().any(|(_, m)| *m == app.model) {
@@ -10618,12 +10963,14 @@ async fn finish_mcp_job(
pending.authorization_url.clone(),
Style::new().cyan(),
)]);
- match super::browser::open(&pending.authorization_url) {
- Ok(()) => app.system_detail_text("opening that page in your browser"),
- Err(e) => {
- app.system_detail_text(&format!("open that URL yourself ({e})"))
- }
- }
+ // Ask before launching anything. The authorization is spawned
+ // regardless: its listener is already bound, so the redirect
+ // completes the sign-in whether the page is opened here or by
+ // hand somewhere else.
+ app.browser_confirm = Some(BrowserConfirm {
+ url: pending.authorization_url.clone(),
+ purpose: format!("authorize '{server}'"),
+ });
let servers = mcp_servers.clone();
*job = Some(tokio::spawn(run_mcp_job(
McpJob::Authorize { server, pending },
@@ -10634,6 +10981,8 @@ async fn finish_mcp_job(
},
McpJobDone::Authorized { server, result } => match result {
Ok(()) => {
+ // Answered or not, there is nothing left to open.
+ app.browser_confirm = None;
app.note(&format!("authorized '{server}' - reconnecting..."));
// The live connection (if any) predates the token, so it is
// replaced rather than left unauthorized.
@@ -10641,7 +10990,10 @@ async fn finish_mcp_job(
let servers = mcp_servers.clone();
*job = Some(tokio::spawn(run_mcp_job(McpJob::Connect(server), servers)));
}
- Err(e) => app.note(&format!("sign-in for '{server}' failed: {e}")),
+ Err(e) => {
+ app.browser_confirm = None;
+ app.note(&format!("sign-in for '{server}' failed: {e}"));
+ }
},
McpJobDone::Connected { server, result } => {
match result {
@@ -11789,7 +12141,10 @@ fn draw(f: &mut Frame, app: &mut App) {
app.row_index = row_index;
// Keep the cursor row visible when the input outgrows the box.
- let input_scroll = if app.status == Status::Idle && app.picker.is_none() {
+ let input_scroll = if app.status == Status::Idle
+ && app.picker.is_none()
+ && app.blocking_dock().is_none()
+ {
let visible = chunks[2].height.saturating_sub(1);
let total = Paragraph::new(input_content_lines(&app.input, app.cursor))
.wrap(Wrap { trim: false })
@@ -11819,6 +12174,18 @@ fn draw(f: &mut Frame, app: &mut App) {
height,
};
draw_login(f, rect, prompt);
+ } else if let Some(confirm) = &app.browser_confirm {
+ let height = (browser_confirm_lines(confirm, chunks[2].width.saturating_sub(2)).len() as u16
+ + 2)
+ .min(chunks[1].height);
+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);
+ let rect = ratatui::layout::Rect {
+ x: chunks[2].x,
+ y,
+ width: chunks[2].width,
+ height,
+ };
+ draw_browser_confirm(f, rect, confirm);
} else if let Some(prompt) = &app.settings_prompt {
let toml_path = app.agent_dir.join("agent.toml");
let height = (settings_prompt_lines(prompt, &toml_path, chunks[2].width.saturating_sub(2))
@@ -12020,16 +12387,29 @@ fn draw_ask(f: &mut Frame, area: Rect, ask: &mut PendingAsk, queue_len: usize) {
fn login_prompt_lines(prompt: &LoginPrompt, width: u16) -> Vec<Line<'static>> {
let dim = Style::new().dark_gray();
let max = width.max(1) as usize;
- let mut lines: Vec<Line<'static>> = wrap_spans_hard(
- vec![
+ let lead = match &prompt.stage {
+ LoginStage::Connecting => vec![Span::styled("starting browser sign-in...", dim)],
+ LoginStage::Approving { authorize_url, .. } => vec![
+ Span::styled("approve at ", dim),
+ Span::styled(authorize_url.clone(), Style::new().cyan()),
+ ],
+ LoginStage::Paste { .. } => vec![
Span::styled("get a key at ", dim),
Span::styled(super::tokamak::API_KEYS_URL, Style::new().cyan()),
],
- max,
- )
- .into_iter()
- .map(Line::from)
- .collect();
+ };
+ let mut lines: Vec<Line<'static>> = wrap_spans_hard(lead, max)
+ .into_iter()
+ .map(Line::from)
+ .collect();
+ // The code is the one thing the user must compare against the browser, so
+ // it gets its own bright line rather than riding the URL's wrap.
+ if let LoginStage::Approving { user_code, .. } = &prompt.stage {
+ lines.push(Line::from(vec![
+ Span::styled("code: ", dim),
+ Span::styled(user_code.clone(), Style::new().cyan().bold()),
+ ]));
+ }
if let Some(error) = &prompt.error {
lines.extend(
wrap_text(error, Style::new().red(), max)
@@ -12037,23 +12417,49 @@ fn login_prompt_lines(prompt: &LoginPrompt, width: u16) -> Vec<Line<'static>> {
.map(Line::from),
);
}
- if prompt.verifying {
+ // The browser question, whichever stage is asking it, reads the same.
+ if prompt.stage.unconfirmed_url().is_some() {
lines.push(Line::styled(
- "verifying...".to_string(),
+ "open this page in your browser?".to_string(),
Style::new().yellow(),
));
- lines.push(Line::styled("Esc cancel".to_string(), dim));
- } else {
- lines.extend(field_lines(
- vec![Span::styled("API key: ", Style::new().bold())],
- &prompt.masked(),
- Style::new(),
- max,
- ));
lines.push(Line::styled(
- "paste the key Β· Enter verify Β· Esc cancel".to_string(),
+ "Enter open Β· n skip Β· Esc cancel".to_string(),
dim,
));
+ return lines;
+ }
+ match &prompt.stage {
+ LoginStage::Connecting => lines.push(Line::styled("Esc cancel".to_string(), dim)),
+ LoginStage::Approving { .. } => {
+ lines.push(Line::styled(
+ "waiting for approval...".to_string(),
+ Style::new().yellow(),
+ ));
+ lines.push(Line::styled(
+ "approve from any device Β· Esc cancel".to_string(),
+ dim,
+ ));
+ }
+ LoginStage::Paste { .. } if prompt.verifying => {
+ lines.push(Line::styled(
+ "verifying...".to_string(),
+ Style::new().yellow(),
+ ));
+ lines.push(Line::styled("Esc cancel".to_string(), dim));
+ }
+ LoginStage::Paste { .. } => {
+ lines.extend(field_lines(
+ vec![Span::styled("API key: ", Style::new().bold())],
+ &prompt.masked(),
+ Style::new(),
+ max,
+ ));
+ lines.push(Line::styled(
+ "paste the key Β· Enter verify Β· Esc cancel".to_string(),
+ dim,
+ ));
+ }
}
lines
}
@@ -12077,6 +12483,57 @@ fn field_lines(
gutter_lines(rows, lead, vec![Span::raw(" ".repeat(lead_w))])
}
+/// The pending-browser box's contents at `width`, sized by the caller the same
+/// way as `login_prompt_lines` -- the URL is the long line that has to be
+/// readable, since declining means opening it by hand.
+fn browser_confirm_lines(confirm: &BrowserConfirm, width: u16) -> Vec<Line<'static>> {
+ let dim = Style::new().dark_gray();
+ let max = width.max(1) as usize;
+ let mut lines: Vec<Line<'static>> = wrap_spans_hard(
+ vec![
+ Span::styled(format!("{} at ", confirm.purpose), dim),
+ Span::styled(confirm.url.clone(), Style::new().cyan()),
+ ],
+ max,
+ )
+ .into_iter()
+ .map(Line::from)
+ .collect();
+ lines.push(Line::styled(
+ "open this page in your browser?".to_string(),
+ Style::new().yellow(),
+ ));
+ lines.push(Line::styled(
+ "Enter open Β· n skip Β· Esc skip".to_string(),
+ dim,
+ ));
+ lines
+}
+
+fn draw_browser_confirm(
+ f: &mut Frame,
+ area: ratatui::layout::Rect,
+ confirm: &BrowserConfirm,
+) {
+ use ratatui::widgets::Clear;
+
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::new().cyan())
+ .title(Span::styled(
+ " open a browser? ",
+ Style::new().on_cyan().black().bold(),
+ ));
+
+ f.render_widget(Clear, area);
+ let inner = block.inner(area);
+ f.render_widget(block, area);
+ f.render_widget(
+ Paragraph::new(browser_confirm_lines(confirm, inner.width)),
+ inner,
+ );
+}
+
fn draw_login(f: &mut Frame, area: ratatui::layout::Rect, prompt: &LoginPrompt) {
use ratatui::widgets::Clear;
@@ -12084,7 +12541,7 @@ 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 ",
+ " sign in to Jan ",
Style::new().on_cyan().black().bold(),
));
@@ -13193,7 +13650,10 @@ const MAX_INPUT_ROWS: u16 = 8;
/// editing, plus one row of air above the dock. The box is borderless, so the
/// two rows this used to add on top of its content were simply blank.
fn input_box_height(app: &App, width: u16) -> u16 {
- let content = if app.picker.is_none() && !(app.status == Status::Running && app.input.is_empty()) {
+ let content = if app.picker.is_none()
+ && app.blocking_dock().is_none()
+ && !(app.status == Status::Running && app.input.is_empty())
+ {
let inner = width.saturating_sub(2).max(1);
let rows = Paragraph::new(input_content_lines(&app.input, app.cursor))
.wrap(Wrap { trim: false })
@@ -13332,6 +13792,14 @@ fn input_box(app: &App) -> Paragraph<'static> {
]))
.block(block)
}
+ } else if let Some(what) = app.blocking_dock() {
+ // The dock owns the keyboard while it is open, so this field takes
+ // nothing: say so instead of showing a cursor that will never move.
+ Paragraph::new(Line::styled(
+ format!("{what} - the field is inactive"),
+ Style::new().dim().italic(),
+ ))
+ .block(block)
} else if app.input.is_empty() {
// Same `> ` prompt as the typing view, then a fixed (non-blinking)
// block cursor in front of the placeholder.
@@ -14253,9 +14721,8 @@ 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 {
- input: String::new(),
error: Some(error.to_string()),
- verifying: false,
+ ..super::LoginPrompt::new()
});
let rows = render_rows(&mut app, 56, 24);
let joined = rows.join(" ");
@@ -14600,7 +15067,7 @@ mod tests {
press_ask(&mut app, &registry, KeyCode::Down).await;
press_ask(&mut app, &registry, KeyCode::Enter).await;
assert!(app.ask_queue.front().unwrap().editing_custom);
- app.login = Some(super::LoginPrompt::new());
+ app.login = Some(confirmed_paste_prompt());
route_paste_event(&mut app, Event::Paste("tokamak-api-key".into()));
@@ -16348,8 +16815,8 @@ mod tests {
#[tokio::test]
async fn login_prompt_captures_keys_and_never_renders_the_key() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
- assert!(app.login.is_some(), "/login must open the prompt");
+ open_paste_field(&mut app).await;
+ assert!(app.login.is_some(), "the paste prompt must be open");
type_key_chars(&mut app, "tk-secret").await;
// Keystrokes are the key, not chat input.
@@ -16360,7 +16827,7 @@ mod tests {
let rows = render_rows(&mut app, 80, 24);
let screen = rows.join("\n");
- assert!(screen.contains("tokamak sign-in"), "{screen}");
+ assert!(screen.contains("sign in to Jan"), "{screen}");
assert!(
!screen.contains("tk-secret"),
"the key must never be rendered:\n{screen}"
@@ -16370,7 +16837,7 @@ mod tests {
#[tokio::test]
async fn login_enter_hands_a_trimmed_key_to_the_loop() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
+ open_paste_field(&mut app).await;
app.login.as_mut().unwrap().paste(" tk-abc\n");
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
@@ -16381,7 +16848,7 @@ mod tests {
#[tokio::test]
async fn login_rejects_a_mispasted_key_before_any_request() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
+ open_paste_field(&mut app).await;
type_key_chars(&mut app, "tk-abc def").await;
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
@@ -16399,7 +16866,7 @@ mod tests {
#[tokio::test]
async fn login_backspace_edits_and_esc_cancels() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
+ open_paste_field(&mut app).await;
type_key_chars(&mut app, "tk-ab").await;
press(&mut app, KeyCode::Backspace, KeyModifiers::NONE).await;
assert_eq!(app.login.as_ref().unwrap().input, "tk-a");
@@ -16412,7 +16879,7 @@ mod tests {
#[tokio::test]
async fn login_stays_cancellable_while_verifying() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
+ open_paste_field(&mut app).await;
app.login.as_mut().unwrap().paste("tk-abc");
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
app.login_submit.take();
@@ -16431,7 +16898,7 @@ mod tests {
#[tokio::test]
async fn failed_verification_keeps_the_prompt_open_with_the_reason() {
let mut app = test_app();
- run_command(&mut app, "login", &no_mcp()).await;
+ open_paste_field(&mut app).await;
app.login.as_mut().unwrap().paste("tk-abc");
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
app.login_submit.take();
@@ -16443,6 +16910,458 @@ mod tests {
assert_eq!(prompt.error.as_deref(), Some("Tokamak rejected that API key."));
}
+ /// `/login --paste-token` skips straight to the legacy field, the same
+ /// escape hatch `jan login --paste-token` gives, and never asks the loop for
+ /// a browser session.
+ #[tokio::test]
+ async fn login_paste_token_forces_the_legacy_field() {
+ let mut app = test_app();
+ run_command(&mut app, "login --paste-token", &no_mcp()).await;
+ let prompt = app.login.as_ref().expect("dock open");
+ assert!(matches!(
+ prompt.stage,
+ super::LoginStage::Paste { confirm_open: true }
+ ));
+ assert!(!app.login_device_request, "no browser session may be started");
+
+ // The field opens only once the browser question is answered.
+ assert!(!prompt.editable(), "no key entry before the browser question");
+ press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE).await;
+ assert!(app.login.as_ref().unwrap().editable());
+ }
+
+ /// Nothing may reach a browser until the user says so -- in either flow.
+ #[tokio::test]
+ async fn the_browser_is_never_opened_without_an_answer() {
+ // Paste fallback.
+ let mut app = test_app();
+ super::open_login_prompt(&mut app);
+ let prompt = app.login.as_ref().unwrap();
+ assert_eq!(
+ prompt.stage.unconfirmed_url(),
+ Some(crate::core::cli::tokamak::API_KEYS_URL)
+ );
+ let screen = render_rows(&mut app, 80, 24).join("\n");
+ assert!(screen.contains("open this page in your browser?"), "{screen}");
+
+ // Browser approval.
+ let mut app = test_app();
+ super::show_login_approval(&mut app, &test_session());
+ assert_eq!(
+ app.login.as_ref().unwrap().stage.unconfirmed_url(),
+ Some("https://tokamak.sh/cli/authorize?code=ABCD-2345")
+ );
+ let screen = render_rows(&mut app, 80, 24).join("\n");
+ assert!(screen.contains("open this page in your browser?"), "{screen}");
+ // The code is still shown while the question is up: the user may prefer
+ // to approve on a phone and never open a browser here at all.
+ assert!(screen.contains("ABCD-2345"), "{screen}");
+ }
+
+ /// Declining does not abandon the sign-in: the poll is already running, so
+ /// the dock moves on to waiting and a phone can still approve it.
+ #[tokio::test]
+ async fn declining_the_browser_still_waits_for_approval() {
+ let mut app = test_app();
+ super::show_login_approval(&mut app, &test_session());
+ press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE).await;
+
+ let prompt = app.login.as_ref().expect("dock stays open");
+ assert!(prompt.stage.unconfirmed_url().is_none(), "question answered");
+ assert!(matches!(
+ prompt.stage,
+ super::LoginStage::Approving {
+ confirm_open: false,
+ ..
+ }
+ ));
+ let screen = render_rows(&mut app, 80, 24).join("\n");
+ assert!(screen.contains("waiting for approval"), "{screen}");
+ }
+
+ /// Esc at the browser question cancels the whole sign-in rather than
+ /// answering it, so the question can never wedge the dock.
+ #[tokio::test]
+ async fn esc_at_the_browser_question_cancels() {
+ for open_paste in [true, false] {
+ let mut app = test_app();
+ if open_paste {
+ super::open_login_prompt(&mut app);
+ } else {
+ super::show_login_approval(&mut app, &test_session());
+ }
+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
+ assert!(app.login.is_none(), "Esc must close the dock");
+ }
+ }
+
+ fn pending_browser(app: &mut App) {
+ app.browser_confirm = Some(super::BrowserConfirm {
+ url: "https://github.com/login/oauth/authorize?client_id=x".into(),
+ purpose: "authorize 'github'".into(),
+ });
+ }
+
+ /// The `/mcp` question shows what it is for and the URL to open, so
+ /// declining still leaves a way to finish.
+ #[tokio::test]
+ async fn the_mcp_browser_question_shows_the_purpose_and_url() {
+ let mut app = test_app();
+ pending_browser(&mut app);
+ let screen = render_rows(&mut app, 90, 24).join("\n");
+ assert!(screen.contains("open a browser?"), "{screen}");
+ assert!(screen.contains("authorize 'github'"), "{screen}");
+ assert!(screen.contains("open this page in your browser?"), "{screen}");
+ assert!(screen.contains("github.com/login/oauth/authorize"), "{screen}");
+ }
+
+ /// Every answer dismisses the question. `browser::open` is disabled under
+ /// `cfg(test)`, so the accept path is exercised without a real browser.
+ #[tokio::test]
+ async fn every_answer_dismisses_the_mcp_browser_question() {
+ for key in [
+ KeyCode::Enter,
+ KeyCode::Char('y'),
+ KeyCode::Char('n'),
+ KeyCode::Esc,
+ ] {
+ let mut app = test_app();
+ pending_browser(&mut app);
+ press(&mut app, key, KeyModifiers::NONE).await;
+ assert!(
+ app.browser_confirm.is_none(),
+ "{key:?} must dismiss the question"
+ );
+ }
+ }
+
+ /// The question owns the keyboard while it is up: a keystroke meant for it
+ /// must not land in the chat input.
+ #[tokio::test]
+ async fn the_mcp_browser_question_owns_the_keyboard() {
+ let mut app = test_app();
+ pending_browser(&mut app);
+ type_key_chars(&mut app, "hello").await;
+ assert!(app.browser_confirm.is_some(), "stray keys are not answers");
+ assert!(app.input.is_empty(), "nothing may reach the chat input");
+ }
+
+ /// An authorization that settles before the user answers takes the stale
+ /// question away with it, rather than leaving a dock pointing at a spent URL.
+ #[tokio::test]
+ async fn a_settled_authorization_clears_a_pending_question() {
+ for result in [Ok(()), Err("nope".to_string())] {
+ let mut app = test_app();
+ pending_browser(&mut app);
+ let mut job = None;
+ super::finish_mcp_job(
+ &mut app,
+ super::McpJobDone::Authorized {
+ server: "github".into(),
+ result,
+ },
+ &no_mcp(),
+ &mut job,
+ )
+ .await;
+ assert!(app.browser_confirm.is_none(), "stale question must go");
+ }
+ }
+
+ /// The paste field with the browser question already answered -- what most
+ /// key-entry tests are actually about.
+ /// Accepting launches the opener and moves on. `browser::open` is disabled
+ /// under `cfg(test)`, so this exercises the accept path (and its "could not
+ /// open" reporting) without hijacking a real browser.
+ #[tokio::test]
+ async fn accepting_the_browser_question_moves_on_either_way() {
+ for accept in [KeyCode::Enter, KeyCode::Char('y')] {
+ let mut app = test_app();
+ super::show_login_approval(&mut app, &test_session());
+ press(&mut app, accept, KeyModifiers::NONE).await;
+
+ let prompt = app.login.as_ref().expect("dock stays open");
+ assert!(
+ prompt.stage.unconfirmed_url().is_none(),
+ "{accept:?} must answer the question"
+ );
+ let screen = render_rows(&mut app, 80, 24).join("\n");
+ assert!(screen.contains("waiting for approval"), "{screen}");
+ }
+
+ // Same for the paste fallback: accepting opens the field.
+ let mut app = test_app();
+ super::open_login_prompt(&mut app);
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ assert!(app.login.as_ref().unwrap().editable());
+ }
+
+ /// A keystroke that is neither an answer nor a cancel is swallowed, so it
+ /// cannot leak into the key field or the chat input.
+ #[tokio::test]
+ async fn stray_keys_at_the_browser_question_do_nothing() {
+ let mut app = test_app();
+ super::open_login_prompt(&mut app);
+ type_key_chars(&mut app, "tk-secret").await;
+
+ let prompt = app.login.as_ref().expect("dock stays open");
+ assert!(prompt.stage.unconfirmed_url().is_some(), "still unanswered");
+ assert!(prompt.input.is_empty(), "no key may be collected yet");
+ assert!(app.input.is_empty(), "and nothing may reach the chat input");
+ }
+
+ fn confirmed_paste_prompt() -> super::LoginPrompt {
+ super::LoginPrompt {
+ stage: super::LoginStage::Paste { confirm_open: false },
+ ..super::LoginPrompt::new()
+ }
+ }
+
+ /// Open the paste fallback and decline the browser, leaving an editable field.
+ async fn open_paste_field(app: &mut App) {
+ super::open_login_prompt(app);
+ press(app, KeyCode::Char('n'), KeyModifiers::NONE).await;
+ }
+
+ fn test_session() -> crate::core::cli::device_auth::Session {
+ crate::core::cli::device_auth::Session {
+ session_id: "sess-1".into(),
+ user_code: "ABCD-2345".into(),
+ authorize_url: "https://tokamak.sh/cli/authorize?code=ABCD-2345".into(),
+ expires_in: 300,
+ interval: 5,
+ }
+ }
+
+ #[tokio::test]
+ async fn login_rejects_an_unknown_option_without_opening_a_dock() {
+ let mut app = test_app();
+ run_command(&mut app, "login --nope", &no_mcp()).await;
+ assert!(app.login.is_none());
+ assert!(!app.login_device_request);
+ }
+
+ /// `/login` starts the browser flow: the dock opens straight away (so Esc
+ /// has something to cancel) and the loop is asked for a session.
+ #[tokio::test]
+ async fn login_starts_the_browser_flow_and_opens_the_dock() {
+ let mut app = test_app();
+ run_command(&mut app, "login", &no_mcp()).await;
+ let prompt = app.login.as_ref().expect("/login must open the dock");
+ assert!(matches!(prompt.stage, super::LoginStage::Connecting));
+ assert!(app.login_device_request, "the loop must be asked to begin");
+ // No field yet, so nothing may be typed into one.
+ assert!(!prompt.editable());
+ }
+
+ /// A second `/login` while a session is being created must not switch the
+ /// dock: the browser session would land on top of the new one.
+ #[tokio::test]
+ async fn login_refuses_while_a_sign_in_is_already_in_progress() {
+ let mut app = test_app();
+ run_command(&mut app, "login", &no_mcp()).await;
+ app.login_device_request = false;
+
+ run_command(&mut app, "login --paste-token", &no_mcp()).await;
+ let prompt = app.login.as_ref().expect("the first dock stays open");
+ assert!(matches!(prompt.stage, super::LoginStage::Connecting));
+ assert!(!app.login_device_request);
+ let transcript = transcript_text(&app);
+ assert!(transcript.contains("already in progress"), "{transcript}");
+ }
+
+ /// The ask layer is consulted before `handle_key`, so an ask queued by the
+ /// running agent must not swallow the secret being typed into `/login` --
+ /// a custom answer is submitted to the model.
+ #[tokio::test]
+ async fn a_queued_ask_never_captures_login_keystrokes() {
+ let mut app = test_app();
+ let registry = crate::core::agent::interaction::new_registry();
+ let (request_id, _receiver) = crate::core::agent::interaction::register(&registry).await;
+ open_paste_field(&mut app).await;
+ app.apply(StreamEvent::AskRequest {
+ request_id,
+ request: ask_request(false, false),
+ });
+ app.ask_queue.front_mut().unwrap().editing_custom = true;
+
+ for ch in "tk-secret".chars() {
+ let key = KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE);
+ assert!(
+ !handle_ask_key(&mut app, key, &registry).await,
+ "the login dock owns the keyboard"
+ );
+ press(&mut app, KeyCode::Char(ch), KeyModifiers::NONE).await;
+ }
+
+ assert_eq!(app.login.as_ref().unwrap().input, "tk-secret");
+ assert_eq!(app.ask_queue.front().unwrap().custom_input, "");
+ assert!(app.input.is_empty(), "the composer must not see the key");
+ }
+
+ fn blank_mcp_prompt() -> super::McpPrompt {
+ super::McpPrompt {
+ editing: None,
+ field: super::McpField::Name,
+ name: String::new(),
+ transport: "stdio".to_string(),
+ command: String::new(),
+ args: String::new(),
+ env: String::new(),
+ url: String::new(),
+ headers: String::new(),
+ active: false,
+ error: None,
+ }
+ }
+
+ /// A named way to open one keyboard-owning dock, for the table below.
+ type DockSetup = (&'static str, fn(&mut App));
+
+ /// Every dock that takes the keyboard in `handle_key` must also blank the
+ /// input row: a live cursor under a dock that swallows every keystroke
+ /// promises a field that is not there. One case per guard in that list, so
+ /// the next dock added cannot quietly regress only the rendering half.
+ #[test]
+ fn every_blocking_dock_marks_the_input_row_inactive() {
+ let setups: [DockSetup; 6] = [
+ ("login/connecting", |app| {
+ app.login = Some(super::LoginPrompt::connecting())
+ }),
+ ("login/paste", |app| {
+ app.login = Some(confirmed_paste_prompt())
+ }),
+ ("browser_confirm", |app| {
+ app.browser_confirm = Some(super::BrowserConfirm {
+ url: "https://example.com/authorize".into(),
+ purpose: "authorize 'github'".into(),
+ })
+ }),
+ ("settings_prompt", |app| {
+ let def = AGENT_SETTINGS
+ .iter()
+ .find(|d| d.key == "max_parallel_subagents")
+ .unwrap();
+ app.settings_prompt = Some(super::SettingsPrompt::new(def, None));
+ }),
+ ("mcp_prompt", |app| {
+ app.mcp_prompt = Some(blank_mcp_prompt())
+ }),
+ ("provider_prompt", |app| {
+ app.provider_prompt = Some(super::ProviderPrompt::new())
+ }),
+ ];
+ for (name, open) in setups {
+ let mut app = test_app();
+ open(&mut app);
+ assert!(app.blocking_dock().is_some(), "{name} must block the field");
+ let screen = render_rows(&mut app, 80, 24).join("\n");
+ assert!(
+ screen.contains("the field is inactive"),
+ "{name}: {screen}"
+ );
+ assert!(
+ !screen.contains("Type here to chat with agent"),
+ "{name}: a live field must not show while the dock is open: {screen}"
+ );
+ }
+ }
+
+ /// The composer is only dead while a dock is up -- an idle app with no dock
+ /// must still offer a field, or the guard above has over-reached.
+ #[test]
+ fn no_dock_leaves_the_input_row_live() {
+ let mut app = test_app();
+ assert!(app.blocking_dock().is_none());
+ let screen = render_rows(&mut app, 80, 24).join("\n");
+ assert!(screen.contains("Type here to chat with agent"), "{screen}");
+ assert!(!screen.contains("the field is inactive"), "{screen}");
+ }
+
+ /// The approval stage shows the code and the URL, and takes no input -- the
+ /// code is the one thing the user has to compare against the browser.
+ #[tokio::test]
+ async fn login_approval_stage_shows_the_code_and_ignores_typing() {
+ let mut app = test_app();
+ super::show_login_approval(
+ &mut app,
+ &crate::core::cli::device_auth::Session {
+ session_id: "sess-1".into(),
+ user_code: "ABCD-2345".into(),
+ authorize_url: "https://tokamak.sh/cli/authorize?code=ABCD-2345".into(),
+ expires_in: 300,
+ interval: 5,
+ },
+ );
+ let prompt = app.login.as_ref().expect("dock open");
+ assert!(matches!(prompt.stage, super::LoginStage::Approving { .. }));
+ assert!(!prompt.editable());
+
+ type_key_chars(&mut app, "xyz").await;
+ assert!(app.login.as_ref().unwrap().input.is_empty(), "no field to type into");
+ assert!(app.login_submit.is_none());
+
+ let screen = render_rows(&mut app, 80, 24).join("\n");
+ assert!(screen.contains("ABCD-2345"), "{screen}");
+ assert!(screen.contains("waiting for approval"), "{screen}");
+ }
+
+ /// Esc during a browser approval closes the dock, which is what makes
+ /// `chat_loop` drop the in-flight poll.
+ #[tokio::test]
+ async fn esc_cancels_a_browser_approval() {
+ let mut app = test_app();
+ run_command(&mut app, "login", &no_mcp()).await;
+ press(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
+ assert!(app.login.is_none(), "Esc must close the dock");
+ }
+
+ /// A denied or expired approval has no field to correct, so the dock closes
+ /// with the reason rather than sitting there uneditable.
+ #[tokio::test]
+ async fn a_failed_approval_closes_the_dock_with_the_reason() {
+ let mut app = test_app();
+ super::show_login_approval(
+ &mut app,
+ &crate::core::cli::device_auth::Session {
+ session_id: "s".into(),
+ user_code: "A-1".into(),
+ authorize_url: "https://tokamak.sh/cli/authorize?code=A-1".into(),
+ expires_in: 300,
+ interval: 5,
+ },
+ );
+ finish_login(&mut app, Err("the sign-in was denied in the browser.".to_string()));
+ assert!(app.login.is_none(), "an uneditable dock must not stay open");
+ let text: String = row_lines(&app.transcript)
+ .iter()
+ .flat_map(|l| l.spans.clone())
+ .map(|s| s.content.to_string())
+ .collect();
+ assert!(text.contains("denied in the browser"), "{text}");
+ }
+
+ /// A successful browser sign-in names the account it signed in as.
+ #[test]
+ fn a_browser_login_reports_the_account() {
+ let mut app = test_app();
+ finish_login(
+ &mut app,
+ Ok(crate::core::cli::tokamak::Login {
+ models: vec!["tokamak-1-preview".into()],
+ config_path: std::path::PathBuf::from("/tmp/config.toml"),
+ default_model: None,
+ account: Some("[email protected]".into()),
+ }),
+ );
+ let text: String = row_lines(&app.transcript)
+ .iter()
+ .flat_map(|l| l.spans.clone())
+ .map(|s| s.content.to_string())
+ .collect();
+ assert!(text.contains("as [email protected]"), "{text}");
+ }
+
#[test]
fn submit_user_with_no_model_notes_instead_of_starting_a_turn() {
let mut app = test_app();
@@ -16509,13 +17428,14 @@ mod tests {
fn successful_login_closes_the_prompt_and_adopts_a_runnable_model() {
crate::core::agent::global_config::with_temp_home(|_| {
let mut app = test_app();
- app.login = Some(super::LoginPrompt::new());
+ app.login = Some(confirmed_paste_prompt());
finish_login(
&mut app,
Ok(crate::core::cli::tokamak::Login {
models: vec!["tokamak-1-preview".into(), "tokamak-1-mini".into()],
config_path: std::path::PathBuf::from("/tmp/config.toml"),
default_model: Some("tokamak-1-preview".into()),
+ account: None,
}),
);
assert!(app.login.is_none());
@@ -16535,18 +17455,20 @@ mod tests {
base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),
models: Some(vec!["m".into()]),
api_type: None,
+ ..Default::default()
},
)
.expect("seed provider");
let mut app = test_app();
- app.login = Some(super::LoginPrompt::new());
+ app.login = Some(confirmed_paste_prompt());
finish_login(
&mut app,
Ok(crate::core::cli::tokamak::Login {
models: vec!["tokamak-1-preview".into()],
config_path: std::path::PathBuf::from("/tmp/config.toml"),
default_model: None,
+ account: None,
}),
);
assert_eq!(app.model, "m", "a working model must survive a re-login");
@@ -16568,6 +17490,7 @@ mod tests {
base_url: Some(crate::core::cli::tokamak::BASE_URL.into()),
models: Some(vec!["tokamak-1-preview".into()]),
api_type: None,
+ ..Default::default()
},
)
.expect("seed provider");
@@ -16630,7 +17553,7 @@ mod tests {
#[test]
fn masked_key_is_bounded() {
- let mut prompt = super::LoginPrompt::new();
+ let mut prompt = confirmed_paste_prompt();
prompt.paste(&"k".repeat(200));
assert_eq!(prompt.masked().chars().count(), 32);
prompt.verifying = true;
@@ -17547,6 +18470,7 @@ mod tests {
base_url: Some("https://api.example/v1".into()),
models: Some(vec!["m1".into()]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -17586,6 +18510,7 @@ mod tests {
base_url: Some("https://api.example/v1".into()),
models: Some(vec!["m1".into()]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -17743,6 +18668,7 @@ mod tests {
base_url: Some("https://my.example/v1".into()),
models: Some(vec!["m1".into()]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -17771,6 +18697,7 @@ mod tests {
base_url: Some("https://my.example/v1".into()),
models: Some(vec![]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -17828,6 +18755,7 @@ mod tests {
base_url: Some("https://my.example/v1".into()),
models: Some(vec![]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -17906,6 +18834,7 @@ mod tests {
base_url: Some("https://my.example/v1".into()),
models: Some(vec!["m1".into(), "m2".into()]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();
@@ -18023,6 +18952,7 @@ mod tests {
base_url: Some(format!("http://{addr}/v1")),
models: Some(vec![]), // no models configured
api_type: None,
+ ..Default::default()
},
)
.expect("seed provider");
@@ -18057,6 +18987,7 @@ mod tests {
base_url: Some("http://127.0.0.1:9/v1".into()),
models: Some(vec![]),
api_type: None,
+ ..Default::default()
},
)
.unwrap();