Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cli): mask the API key as it is typed or pasted
Akarshan Biswas0d770ffbaf91
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex ad9c3f6e9..32dbe49a9 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -14,7 +14,6 @@ dependencies = ["clap","comfy-table","console",- "dialoguer","dirs","ed25519-dalek","env",@@ -1642,19 +1641,6 @@ dependencies = ["syn 2.0.118",]-[[package]]-name = "dialoguer"-version = "0.11.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "658bce805d770f407bc62102fca7c2c64ceef2fbcb2b8bd19d2765ce093980de"-dependencies = [- "console",- "shell-words",- "tempfile",- "thiserror 1.0.69",- "zeroize",-]-[[package]]name = "digest"version = "0.10.7"@@ -6414,12 +6400,6 @@ dependencies = ["windows-sys 0.60.2",]-[[package]]-name = "shell-words"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"-[[package]]name = "shlex"version = "2.0.1"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex d9585a5c8..cb77d309a 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -90,7 +90,7 @@ test-tauri = ["deep-link","hardware",]-cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:ratatui", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"]+cli = ["dep:env_logger", "dep:indicatif", "dep:console", "dep:ratatui", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"][build-dependencies]tauri-build = { version = "2.0.2", features = [], optional = true }@@ -177,7 +177,6 @@ glob = "0.3"regex = "1"ignore = "0.4"clap = { version = "4", features = ["derive"] }-dialoguer = { version = "0.11", optional = true }env_logger = { version = "0.11", optional = true }indicatif = { version = "0.17", optional = true }console = { version = "0.15", optional = true }diff --git a/src-tauri/src/core/cli/login.rs b/src-tauri/src/core/cli/login.rsindex 012381546..ce78dcad5 100644--- a/src-tauri/src/core/cli/login.rs+++ b/src-tauri/src/core/cli/login.rs@@ -8,12 +8,14 @@use std::io::IsTerminal;-use super::tokamak;+use super::{secret_input, tokamak};/// Max key prompts before giving up, so a wrong paste is retryable but a script/// piping garbage at us can't loop forever.const MAX_ATTEMPTS: usize = 3;+const KEY_PROMPT: &str = "Paste your Tokamak API key: ";+/// Guarantee a runnable provider before the agent starts, signing the user in if/// there is none. No-op when anything usable is already configured, so the/// startup cost on an existing install is one config read.@@ -51,6 +53,7 @@ pub async fn run_login() -> Result<(), String> {Err(e) => println!(" (open that URL yourself: {e})"),}println!();+ println!("The key is masked as you type or paste. Enter verifies, Esc cancels.");let mut last_error = None;for attempt in 1..=MAX_ATTEMPTS {@@ -99,28 +102,13 @@ async fn login_from_stdin() -> Result<(), String> {Ok(())}-/// Read the key with echo disabled. `None` means the user interrupted the-/// prompt. Runs on a blocking thread: `dialoguer` owns the terminal while it-/// waits, which must not stall the async runtime.+/// Read the key, echoing a mask so the user can see a paste land. `None` means+/// the user abandoned the prompt. Runs on a blocking thread: the prompt owns the+/// terminal while it waits, which must not stall the async runtime.async fn prompt_for_key() -> Result<Option<String>, String> {- tokio::task::spawn_blocking(|| {- match dialoguer::Password::new()- .with_prompt("Paste your Tokamak API key")- .allow_empty_password(true)- .interact()- {- Ok(key) => Ok(Some(key)),- Err(e) if is_interrupted(&e) => Ok(None),- Err(e) => Err(format!("could not read the API key: {e}")),- }- })- .await- .map_err(|e| format!("key prompt failed: {e}"))?-}--fn is_interrupted(e: &dialoguer::Error) -> bool {- let dialoguer::Error::IO(io) = e;- io.kind() == std::io::ErrorKind::Interrupted+ tokio::task::spawn_blocking(|| secret_input::read_masked_line(KEY_PROMPT))+ .await+ .map_err(|e| format!("key prompt failed: {e}"))?}/// Why we stopped when there is nobody at the keyboard to paste a key.diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 4830f412f..2a0e6488e 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -6,6 +6,7 @@ pub mod login;pub mod mcp;pub mod providers;mod path_refs;+mod secret_input;pub mod tokamak;mod tui;pub mod updater;diff --git a/src-tauri/src/core/cli/secret_input.rs b/src-tauri/src/core/cli/secret_input.rsnew file mode 100644index 000000000..8409a5028--- /dev/null+++ b/src-tauri/src/core/cli/secret_input.rs@@ -0,0 +1,222 @@+//! Masked secret entry shared by the two places that collect an API key: the+//! plain-terminal prompt in [`super::login`] and the TUI's `/login` overlay.+//!+//! The value is never echoed verbatim; callers render [`mask`] instead, so the+//! user gets proof that a keystroke or paste landed without the key reaching the+//! screen or the scrollback.++use std::io::Write;++use ratatui::crossterm::{+ event::{+ self, DisableBracketedPaste, EnableBracketedPaste, Event, KeyCode, KeyEventKind,+ KeyModifiers,+ },+ execute,+ terminal::{disable_raw_mode, enable_raw_mode, Clear, ClearType},+};++/// Longest run of mask characters rendered. Bounds the field so a long paste+/// cannot overflow a TUI box or wrap a terminal line, and hides the key's exact+/// length from anyone reading over a shoulder.+const MASK_MAX: usize = 32;++/// Bounded stand-in for a secret of `char_count` characters.+pub fn mask(char_count: usize) -> String {+ "*".repeat(char_count.min(MASK_MAX))+}++/// Plain text from the OS clipboard, for the Ctrl-V fallback below.+pub fn clipboard_text() -> Result<String, String> {+ arboard::Clipboard::new()+ .and_then(|mut clip| clip.get_text())+ .map_err(|e| e.to_string())+}++/// Whitespace terminals add around a paste is dropped; interior whitespace is+/// kept so `sanitize_key` can reject a mis-paste with a clear reason rather than+/// silently mangling the key.+pub fn pasted(text: &str) -> &str {+ text.trim()+}++/// What one input event does to a secret field.+#[derive(Debug, PartialEq, Eq)]+pub enum Action {+ Insert(String),+ Backspace,+ Clear,+ /// Ctrl-V arrived as a keystroke: read the clipboard ourselves.+ PasteClipboard,+ Submit,+ Cancel,+ Ignore,+}++/// Map a terminal event onto a field edit. Pure, so the key semantics both+/// front-ends rely on are testable without a terminal.+pub fn classify(event: &Event) -> Action {+ let key = match event {+ Event::Paste(text) => return Action::Insert(pasted(text).to_string()),+ Event::Key(key) if key.kind == KeyEventKind::Press => key,+ _ => return Action::Ignore,+ };+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ match key.code {+ KeyCode::Esc => Action::Cancel,+ KeyCode::Char('c' | 'd') if ctrl => Action::Cancel,+ KeyCode::Char('u') if ctrl => Action::Clear,+ KeyCode::Char('v') if ctrl => Action::PasteClipboard,+ KeyCode::Enter => Action::Submit,+ // Raw mode maps only CR to Enter; a bare LF reaches us as Ctrl-J, which+ // is how a redirected or line-translating tty delivers a submit.+ KeyCode::Char('j') if ctrl => Action::Submit,+ KeyCode::Backspace => Action::Backspace,+ KeyCode::Char(ch) if !ctrl => Action::Insert(ch.to_string()),+ _ => Action::Ignore,+ }+}++/// Restore the terminal on every exit path, including a panic mid-prompt.+struct RawGuard;++impl Drop for RawGuard {+ fn drop(&mut self) {+ let _ = execute!(std::io::stdout(), DisableBracketedPaste);+ let _ = disable_raw_mode();+ }+}++/// Read a secret from the terminal, echoing [`mask`] as it is typed or pasted.+/// `None` means the user cancelled (Esc, Ctrl-C, or Ctrl-D).+///+/// Raw mode is entered once for the whole read rather than per keystroke: a+/// paste arriving while the terminal was briefly back in canonical mode would be+/// echoed in plaintext by the tty driver.+pub fn read_masked_line(prompt: &str) -> Result<Option<String>, String> {+ let mut out = std::io::stdout();+ enable_raw_mode().map_err(|e| format!("could not read the API key: {e}"))?;+ let _guard = RawGuard;+ // Bracketed paste turns a paste into one event instead of a burst of+ // keystrokes, so a key with interior whitespace survives intact.+ let _ = execute!(out, EnableBracketedPaste);++ let mut input = String::new();+ let mut error: Option<String> = None;+ loop {+ redraw(&mut out, prompt, input.chars().count(), error.as_deref())+ .map_err(|e| format!("could not draw the API key prompt: {e}"))?;+ let event = event::read().map_err(|e| format!("could not read the API key: {e}"))?;+ error = None;+ match classify(&event) {+ Action::Insert(text) => input.push_str(&text),+ Action::Backspace => {+ input.pop();+ }+ Action::Clear => input.clear(),+ Action::PasteClipboard => match clipboard_text() {+ Ok(text) => input.push_str(pasted(&text)),+ Err(e) => error = Some(format!("could not read the clipboard: {e}")),+ },+ Action::Submit => {+ let _ = write!(out, "\r\n");+ let _ = out.flush();+ return Ok(Some(input));+ }+ Action::Cancel => {+ let _ = write!(out, "\r\n");+ let _ = out.flush();+ return Ok(None);+ }+ Action::Ignore => {}+ }+ }+}++fn redraw(+ out: &mut std::io::Stdout,+ prompt: &str,+ char_count: usize,+ error: Option<&str>,+) -> std::io::Result<()> {+ execute!(out, Clear(ClearType::CurrentLine))?;+ write!(out, "\r{prompt}{}", mask(char_count))?;+ if let Some(error) = error {+ write!(out, " ({error})")?;+ }+ out.flush()+}++#[cfg(test)]+mod tests {+ use super::*;+ use ratatui::crossterm::event::KeyEvent;++ fn key(code: KeyCode) -> Event {+ Event::Key(KeyEvent::new(code, KeyModifiers::NONE))+ }++ fn ctrl(ch: char) -> Event {+ Event::Key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL))+ }++ #[test]+ fn mask_is_one_star_per_char_up_to_the_cap() {+ assert_eq!(mask(0), "");+ assert_eq!(mask(9), "*********");+ assert_eq!(mask(MASK_MAX).chars().count(), MASK_MAX);+ // A long key must not leak its length or overflow the field.+ assert_eq!(mask(4096).chars().count(), MASK_MAX);+ }++ #[test]+ fn typing_and_pasting_both_reach_the_field() {+ assert_eq!(classify(&key(KeyCode::Char('a'))), Action::Insert("a".into()));+ assert_eq!(+ classify(&Event::Paste(" sk-abc \n".into())),+ Action::Insert("sk-abc".into())+ );+ }++ #[test]+ fn interior_whitespace_survives_a_paste_so_it_can_be_rejected() {+ assert_eq!(pasted(" sk-a b \n"), "sk-a b");+ }++ #[test]+ fn every_way_out_of_the_prompt_is_honoured() {+ assert_eq!(classify(&key(KeyCode::Enter)), Action::Submit);+ // Raw mode delivers a bare LF as Ctrl-J rather than Enter.+ assert_eq!(classify(&ctrl('j')), Action::Submit);+ assert_eq!(classify(&key(KeyCode::Esc)), Action::Cancel);+ assert_eq!(classify(&ctrl('c')), Action::Cancel);+ assert_eq!(classify(&ctrl('d')), Action::Cancel);+ }++ #[test]+ fn editing_keys_match_the_tui_overlay() {+ assert_eq!(classify(&key(KeyCode::Backspace)), Action::Backspace);+ assert_eq!(classify(&ctrl('u')), Action::Clear);+ assert_eq!(classify(&ctrl('v')), Action::PasteClipboard);+ }++ #[test]+ fn control_chords_never_land_in_the_key() {+ // A stray Ctrl-<x> must not become a character in the secret.+ for ch in ['a', 'z', 'w'] {+ assert_eq!(classify(&ctrl(ch)), Action::Ignore);+ }+ }++ #[test]+ fn non_press_and_navigation_events_are_ignored() {+ let release = Event::Key(KeyEvent::new_with_kind(+ KeyCode::Char('a'),+ KeyModifiers::NONE,+ KeyEventKind::Release,+ ));+ assert_eq!(classify(&release), Action::Ignore);+ assert_eq!(classify(&key(KeyCode::Left)), Action::Ignore);+ assert_eq!(classify(&Event::FocusGained), Action::Ignore);+ }+}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 481d2afb1..ffac05879 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -230,18 +230,13 @@ impl LoginPrompt {}}- /// Bounded stand-in for the key so a long paste can't overflow the box and a- /// shoulder-surfer learns nothing beyond "something was entered".fn masked(&self) -> String {- "*".repeat(self.input.chars().count().min(32))+ super::secret_input::mask(self.input.chars().count())}- /// Append pasted text, dropping the whitespace terminals add around a paste.- /// Interior whitespace is kept so `sanitize_key` can reject a mis-paste with- /// a clear reason rather than silently mangling the key.fn paste(&mut self, text: &str) {if !self.verifying {- self.input.push_str(text.trim());+ self.input.push_str(super::secret_input::pasted(text));}}}@@ -3809,9 +3804,7 @@ fn handle_login_key(app: &mut App, key: KeyEvent, ctrl: bool) {/// Plain text from the OS clipboard, for Ctrl-V in the `/login` prompt (the/// image path is `clipboard_image`).fn clipboard_text() -> Result<String, String> {- arboard::Clipboard::new()- .and_then(|mut clip| clip.get_text())- .map_err(|e| e.to_string())+ super::secret_input::clipboard_text()}async fn handle_key(