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(agent): Hide Secrets - keep credentials out of model requests (#9107)

thinhlpg9a3f29611efc
diff --git a/docs/src/pages/docs/agent/_meta.json b/docs/src/pages/docs/agent/_meta.json
index 1c12ff4ae..43de05bb4 100644
--- a/docs/src/pages/docs/agent/_meta.json
+++ b/docs/src/pages/docs/agent/_meta.json
@@ -25,6 +25,7 @@
"permissions": "Tool Permissions",
"hooks": "Hooks",
"mcp": "MCP",
+ "hide-secrets": "Hide Secrets",
"telemetry": "Telemetry (OpenTelemetry)",
"embedding-separator": { "title": "Embedding", "type": "separator" },
"adk": "Jan ADK",
diff --git a/docs/src/pages/docs/agent/hide-secrets.mdx b/docs/src/pages/docs/agent/hide-secrets.mdx
new file mode 100644
index 000000000..2c0caa01d
--- /dev/null
+++ b/docs/src/pages/docs/agent/hide-secrets.mdx
@@ -0,0 +1,65 @@
+---
+title: Hide Secrets
+description: Keep API keys, tokens and passwords out of the requests Jan Agent sends to a model provider, while tools still run with the real values.
+keywords: [Jan, Jan Agent, secrets, privacy, redaction, API key, token, credentials]
+---
+
+import { Callout } from 'nextra/components'
+
+# Hide Secrets
+
+Everything the agent reads is sent to your model provider: file contents, shell output, an
+environment dump, pasted text. With **Hide Secrets** on, Jan replaces credentials with placeholders
+just before a request leaves your machine, and puts the real value back when the model asks a tool
+to use one.
+
+<Callout type="info">
+Hide Secrets is **off by default**, so existing prompts and provider caches are unchanged.
+</Callout>
+
+## Turn it on
+
+In `/settings`, open **hide_secrets** (Privacy), or set it in `~/.jan/config.toml`:
+
+```toml
+hide_secrets = true
+```
+
+`JAN_HIDE_SECRETS=1` (or `0`) overrides the file. The setting is read when a session starts, so a
+change takes effect on the next session.
+
+## What is hidden
+
+| Source | Example |
+| --- | --- |
+| Values of environment variables whose name has a `KEY`, `SECRET`, `TOKEN`, `PASSWORD`, `PASS`, `AUTH`, `CREDENTIAL`, `PRIVATE` or `OAUTH` part, when the value is 8+ characters | `OPENAI_API_KEY` |
+| A password inside a URL, whatever the variable is called | `postgres://app:hunter2@db/x` |
+| GitHub, GitLab, OpenAI and Anthropic keys | `ghp_…`, `glpat-…`, `sk-…`, `sk-ant-…` |
+| AWS access keys, Google API keys, Slack, npm, Stripe, Hugging Face and SendGrid tokens | `AKIA…`, `AIza…`, `xoxb-…` |
+| JWTs, `Bearer` header tokens, PEM private key blocks | `eyJ…`, `Bearer …` |
+
+The pass covers message text, tool results, and the arguments of earlier tool calls. Images, tool
+schemas and ids are left alone. It applies to the main run, subagents and compaction.
+
+## How it works
+
+```text
+tool output "token=ghp_abc…" -> provider sees "token=$$GITHUBTOKEN_3P8W5JH1TK2Q$$"
+model calls bash("curl -H $$GITHUBTOKEN_3P8W5JH1TK2Q$$") -> bash runs with the real token
+```
+
+- A placeholder is derived from the secret and a random key kept in `~/.jan/secret-placeholder.key`
+ (mode `0600`, never sent anywhere). A transcript reader cannot hash a placeholder back to its
+ secret, and the same secret always becomes the same placeholder.
+- Saved threads keep the real text, and each request is filtered again, so `/resume` and fork behave
+ the same.
+- **Prompt cache:** the same text always yields the same bytes, an earlier message is never rewritten
+ differently on a later request, and nothing is added to the system prompt.
+
+## Limits
+
+- Detection is by name and shape. A secret that has neither (a short or unusual value in a variable
+ with a plain name) is not hidden.
+- Values under 8 characters are left alone, so ordinary words survive.
+- Encrypted or opaque provider replay fields cannot be filtered.
+- Telemetry has its own redaction (see [Telemetry](/docs/agent/telemetry)).
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index f5ab526d2..31134f3f9 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -47,6 +47,12 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# # On by default
# claude_code_alias = false # allow Jan to reuse Claude Code's
# # keychain login; on by default
+# hide_secrets = true # replace secret-named env values, URL
+# # passwords and credential-shaped tokens
+# # with placeholders before a request goes
+# # to a model; tool calls get the real
+# # value back. Off by default;
+# # JAN_HIDE_SECRETS=1|0 overrides it
# memory_cross_project = false # hide other projects' memory from the
# # agent (the root ~/.jan/MEMORY.md lists
# # them by default)
@@ -131,6 +137,10 @@ struct GlobalConfigToml {
/// on; set false to keep Jan from reading or refreshing that credential.
#[serde(default, skip_serializing_if = "Option::is_none")]
claude_code_alias: Option<bool>,
+ /// Hide secrets from model requests (`core::agent::secrets`). `None` = the
+ /// default, off.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ hide_secrets: Option<bool>,
/// List other projects' memory in the prompt and let the agent read it as
/// `project:<slug>`. `None` = the default, on. Off keeps each project's
/// memory to itself (user-wide `user:` notes still apply everywhere).
@@ -333,6 +343,12 @@ pub(crate) fn telemetry_setting() -> Option<bool> {
load_raw().ok().and_then(|config| config.telemetry.enabled)
}
+/// `hide_secrets` in `~/.jan/config.toml`; `None` when unset. Fails open to
+/// "unset" (off): a preference file must never stop a session from starting.
+pub(crate) fn hide_secrets_setting() -> Option<bool> {
+ load_raw().ok().and_then(|config| config.hide_secrets)
+}
+
/// Whether the TUI should track the mouse (`mouse` in `~/.jan/config.toml`),
/// defaulting to on. A display preference must never block startup, so an
/// unreadable or malformed config yields the default rather than an error.
@@ -871,6 +887,21 @@ mod tests {
});
}
+ #[test]
+ fn hide_secrets_is_unset_by_default_and_reads_its_key() {
+ with_temp_home(|home| {
+ assert_eq!(hide_secrets_setting(), None, "missing file");
+ let path = home.join(".jan").join("config.toml");
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, "hide_secrets = true\n").unwrap();
+ assert_eq!(hide_secrets_setting(), Some(true));
+ std::fs::write(&path, "hide_secrets = false\n").unwrap();
+ assert_eq!(hide_secrets_setting(), Some(false));
+ std::fs::write(&path, "hide_secrets = [").unwrap();
+ assert_eq!(hide_secrets_setting(), None, "fails open to unset");
+ });
+ }
+
#[test]
fn telemetry_is_unset_by_default_and_reads_its_table() {
with_temp_home(|_| {
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 39e129516..4796e6d0f 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -355,6 +355,10 @@ struct HttpModelInvoker {
/// to carry it (a `/compact` or `/goal` evaluation started between turns,
/// the API-server proxy that discards its events).
provenance_events: Option<mpsc::UnboundedSender<StreamEvent>>,
+ /// Hide Secrets, when it is on for this process: every request is filtered
+ /// just before it leaves, and the completion is mapped back. `None` = off,
+ /// and then nothing in the request or the reply changes.
+ secrets: Option<Arc<crate::core::agent::secrets::SecretFilter>>,
}
/// [`crate::core::agent::provenance::RequestIdentity`] as the invoker stores it:
@@ -431,7 +435,10 @@ impl ModelInvoker for HttpModelInvoker {
// URL + credential have already been resolved from that qualifier, so
// the body must carry the bare model id - providers like OpenCode GO
// reject a provider-qualified id with "model not supported".
- let mut normalized = request.clone();
+ let mut normalized = match &self.secrets {
+ Some(filter) => filter.filter_request(request),
+ None => request.clone(),
+ };
if let Some(model) = normalized.get("model").and_then(|m| m.as_str()) {
let pc = self.provider_configs.lock().await;
let bare = crate::core::agent::upstream::strip_provider_prefix(model, &pc);
@@ -452,7 +459,7 @@ impl ModelInvoker for HttpModelInvoker {
&normalized,
self.provenance.as_identity(self.session_id.as_deref()),
));
- if let Some(converter) = &self.converter {
+ let completion = if let Some(converter) = &self.converter {
crate::core::agent::upstream::stream_converted_chat_completions(
&self.converter_client,
&self.upstream_url,
@@ -475,7 +482,16 @@ impl ModelInvoker for HttpModelInvoker {
self.client_request_id.as_deref(),
)
.await
+ };
+ if self.secrets.is_some() {
+ // The model saw placeholders; the tool and the saved thread get the
+ // real values back. The next request hides them again.
+ return completion.map(|mut c| {
+ crate::core::agent::secrets::restore_completion(&mut c);
+ c
+ });
}
+ completion
}
}
@@ -3298,6 +3314,7 @@ async fn orchestrate_inner(
session_id: args.session_id.clone(),
provenance,
provenance_events: Some(events.clone()),
+ secrets: crate::core::agent::secrets::for_run(),
};
let mcp_tools = McpToolInvoker {
tool_to_server,
@@ -3765,6 +3782,7 @@ pub(crate) async fn compact_history(
// to carry the record, so this request is reported nowhere rather than
// somewhere a client cannot read.
provenance_events: None,
+ secrets: crate::core::agent::secrets::for_run(),
};
crate::core::agent::compaction::compact_conversation(messages, model_id, &model, keep_recent)
.await
@@ -3847,6 +3865,7 @@ async fn side_call_invoker(
provenance,
// Between turns, like `/compact`: no run stream exists to carry it.
provenance_events: None,
+ secrets: crate::core::agent::secrets::for_run(),
};
Ok(model)
}
@@ -5182,6 +5201,7 @@ mod tests {
oauth: false,
},
provenance_events: Some(run),
+ secrets: None,
};
let request =
@@ -5209,6 +5229,88 @@ mod tests {
);
}
+ /// Hide Secrets, end to end through the invoker: the body a provider
+ /// receives holds a placeholder and never the secret, and a tool call the
+ /// model writes with that placeholder comes back holding the real value.
+ #[tokio::test]
+ async fn hide_secrets_filters_the_wire_body_and_restores_the_tool_call() {
+ use std::io::{BufRead, BufReader, Read, Write};
+
+ const SECRET: &str = "live-value-1234567890";
+ let filter = Arc::new(crate::core::agent::secrets::SecretFilter::for_tests(&[(
+ "OPENAI_API_KEY",
+ SECRET,
+ )]));
+ let placeholder = filter.hide(SECRET);
+ assert!(placeholder.starts_with("$$OPENAI_API_KEY_"), "{placeholder}");
+
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}/v1/chat/completions", listener.local_addr().unwrap());
+ let (seen_tx, seen_rx) = std::sync::mpsc::channel::<String>();
+ let reply_args = serde_json::json!({ "command": format!("login {placeholder}") })
+ .to_string();
+ std::thread::spawn(move || {
+ let Some(Ok(mut stream)) = listener.incoming().next() else { return };
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut length = 0usize;
+ loop {
+ let mut line = String::new();
+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
+ break;
+ }
+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {
+ length = n.trim().parse().unwrap_or(0);
+ }
+ }
+ let mut body = vec![0; length];
+ let _ = reader.read_exact(&mut body);
+ let _ = seen_tx.send(String::from_utf8_lossy(&body).into_owned());
+ let chunk = serde_json::json!({"id":"s","object":"chat.completion.chunk","created":1,"model":"m",
+ "choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[
+ {"index":0,"id":"c1","type":"function","function":{"name":"bash","arguments":reply_args}}]},
+ "finish_reason":null}]});
+ let done = serde_json::json!({"id":"s","object":"chat.completion.chunk","created":1,"model":"m",
+ "choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],
+ "usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}});
+ let answer = format!("data: {chunk}\n\ndata: {done}\n\ndata: [DONE]\n\n");
+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len()).unwrap();
+ });
+
+ let (events, _rx) = mpsc::unbounded_channel();
+ let invoker = HttpModelInvoker {
+ client: crate::core::agent::upstream::agent_http_client(),
+ upstream_url: url,
+ api_keys: Vec::new(),
+ provider_configs: Arc::new(Mutex::new(HashMap::new())),
+ converter: None,
+ converter_client: converter_http_client(),
+ client_request_id: None,
+ session_id: None,
+ provenance: RequestIdentityOwned {
+ run_id: None,
+ provider: Some("stub".to_string()),
+ api_type: None,
+ oauth: false,
+ },
+ provenance_events: None,
+ secrets: Some(filter),
+ };
+ let request = json!({"model":"m","messages":[
+ {"role":"user","content":format!("my key is {SECRET}")}]});
+ let completion = invoker.invoke(&request, &events).await.expect("the stub answers");
+
+ let wire = seen_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("a request");
+ assert!(!wire.contains(SECRET), "the secret reached the provider: {wire}");
+ assert!(wire.contains(&placeholder), "the placeholder is what it saw: {wire}");
+
+ let args = completion["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"]
+ .as_str()
+ .expect("a tool call came back");
+ let parsed: serde_json::Value = serde_json::from_str(args).unwrap();
+ assert_eq!(parsed["command"], format!("login {SECRET}"), "the tool gets the real value");
+ assert_eq!(request["messages"][0]["content"], format!("my key is {SECRET}"), "the caller's history is untouched");
+ }
+
#[derive(Default)]
struct MockTool {
calls: StdMutex<Vec<Vec<serde_json::Value>>>,
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 2040a88d2..03f76318f 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -46,6 +46,7 @@ pub mod project;
pub mod prompt;
pub mod provenance;
pub mod reminder;
+pub mod secrets;
pub mod session;
pub mod skill_hub;
pub mod skills;
diff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rs
index 722525dd2..8b886c7fc 100644
--- a/src-tauri/src/core/agent/prefix_stability.rs
+++ b/src-tauri/src/core/agent/prefix_stability.rs
@@ -789,3 +789,45 @@ fn the_default_policy_places_exactly_the_permitted_contributors_in_the_prefix()
"the default policy's prefix contributors have to be the permitted list, in registry order"
);
}
+
+/// Hide Secrets rewrites the request just before it leaves. It must not move the
+/// cache line: a request that extends an earlier one has to keep the earlier
+/// one's bytes, secret or not, and the system prompt must come through unchanged.
+#[test]
+fn hide_secrets_keeps_the_filtered_prefix_stable_from_turn_to_turn() {
+ const SECRET: &str = "live-value-1234567890";
+ let filter = crate::core::agent::secrets::SecretFilter::for_tests(&[(
+ "OPENAI_API_KEY",
+ SECRET,
+ )]);
+ let project = Project::new("hide-secrets");
+ let tools = advertised(&["read_file"]);
+
+ let first = turn(
+ project.root(),
+ &[user(&format!("my key is {SECRET}"))],
+ DAY,
+ &tools,
+ );
+ let mut history = first.messages.clone();
+ history.push(assistant("noted"));
+ history.push(user(&format!("again: {SECRET}")));
+ let second = turn(project.root(), &history, DAY, &tools);
+
+ let filtered = |request: &Request| -> Request {
+ let body: Value = serde_json::from_str(&request.body).unwrap();
+ let body = filter.filter_request(&body);
+ Request {
+ messages: body["messages"].as_array().unwrap().clone(),
+ body: serde_json::to_string(&body).unwrap(),
+ }
+ };
+ let (a, b) = (filtered(&first), filtered(&second));
+
+ assert!(!a.body.contains(SECRET) && !b.body.contains(SECRET), "the key leaked");
+ assert_eq!(
+ a.messages[0], first.messages[0],
+ "the system prompt is not part of the secret pass unless it holds one"
+ );
+ a.assert_extended_by("turn two after Hide Secrets", &b);
+}
diff --git a/src-tauri/src/core/agent/secrets.rs b/src-tauri/src/core/agent/secrets.rs
new file mode 100644
index 000000000..9247ea31e
--- /dev/null
+++ b/src-tauri/src/core/agent/secrets.rs
@@ -0,0 +1,575 @@
+//! Hide Secrets: keep credentials out of the requests sent to a model provider.
+//!
+//! Off by default. When on, every outbound request body is rewritten just
+//! before it leaves the process (`HttpModelInvoker::invoke`, which the main
+//! run, every subagent and compaction all go through):
+//!
+//! * the values of secret-named environment variables,
+//! * passwords inside `scheme://user:password@host` URLs, and
+//! * credential-shaped tokens (GitHub, OpenAI/Anthropic, AWS, JWTs, `Bearer`
+//! headers, PEM private keys, ...)
+//!
+//! become reversible placeholders such as `$$GITHUBTOKEN_3P8W5JH1TK2Q$$`. The
+//! model's completion is mapped back on the way in, so a tool call that uses a
+//! placeholder runs with the real value, and the saved thread stays readable.
+//!
+//! **Prompt cache.** A placeholder is a function of the secret and a private
+//! per-install key, so the same text always yields the same bytes, and the
+//! filter never touches an earlier message differently from one request to the
+//! next. It adds nothing to the system prompt. `prefix_stability` pins this.
+//!
+//! The 12-hex-character id is an HMAC of the value under a random key kept in
+//! `~/.jan/secret-placeholder.key` (mode 0600, never sent anywhere), so a reader
+//! of a transcript cannot dictionary-hash a placeholder back to its secret.
+
+use std::collections::HashMap;
+use std::sync::{Arc, LazyLock, Mutex};
+
+use hmac::{Hmac, Mac};
+use rand::RngCore;
+use regex::Regex;
+use serde_json::Value;
+use sha2::Sha256;
+
+/// Env var that overrides the config key: `1`/`true`/`on` or `0`/`false`/`off`.
+pub(crate) const ENV: &str = "JAN_HIDE_SECRETS";
+
+/// Values shorter than this are left alone, so ordinary short words survive.
+const MIN_SECRET_LEN: usize = 8;
+
+/// Name tokens (split on `_`, `-`, `.`) that mark an environment variable as
+/// holding a secret.
+const SECRET_NAME_TOKENS: &[&str] = &[
+ "KEY",
+ "SECRET",
+ "TOKEN",
+ "PASSWORD",
+ "PASSWD",
+ "PASS",
+ "AUTH",
+ "CREDENTIAL",
+ "CREDENTIALS",
+ "PRIVATE",
+ "OAUTH",
+];
+
+/// Names that match the rule above but hold a path or a socket, not a secret.
+const NOT_SECRETS: &[&str] = &["SSH_AUTH_SOCK", "GPG_AGENT_INFO"];
+
+/// placeholder text -> the secret it stands for. Shared by every filter in the
+/// process, so a subagent's or a compaction's completion restores what the main
+/// run hid. A placeholder is deterministic, so a restart rebuilds the same ones.
+static REVERSE: LazyLock<Mutex<HashMap<String, String>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+/// One built-in credential shape. `group` is the capture group to hide (`0` =
+/// the whole match).
+struct Shape {
+ label: &'static str,
+ re: Regex,
+ group: usize,
+}
+
+static SHAPES: LazyLock<Vec<Shape>> = LazyLock::new(|| {
+ let table: &[(&str, &str, usize)] = &[
+ ("PRIVATEKEY", r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----", 0),
+ ("GITHUBTOKEN", r"\bgh[pousr]_[A-Za-z0-9]{20,}", 0),
+ ("GITHUBTOKEN", r"\bgithub_pat_[A-Za-z0-9_]{20,}", 0),
+ ("GITLABTOKEN", r"\bglpat-[A-Za-z0-9_-]{20,}", 0),
+ ("APIKEY", r"\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}", 0),
+ ("AWSKEY", r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b", 0),
+ ("GOOGLEKEY", r"\bAIza[0-9A-Za-z_-]{30,}", 0),
+ ("SLACKTOKEN", r"\bxox[abprs]-[A-Za-z0-9-]{10,}", 0),
+ ("NPMTOKEN", r"\bnpm_[A-Za-z0-9]{30,}", 0),
+ ("STRIPEKEY", r"\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}", 0),
+ ("STRIPEKEY", r"\bwhsec_[A-Za-z0-9]{16,}", 0),
+ ("HFTOKEN", r"\bhf_[A-Za-z0-9]{30,}", 0),
+ ("SENDGRIDKEY", r"\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}", 0),
+ ("JWT", r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}", 0),
+ ("BEARER", r"(?i)\bbearer\s+([A-Za-z0-9._~+/=-]{16,})", 1),
+ ("URLPASSWORD", r"://[^\s:/@]+:([^\s@/]{3,})@", 1),
+ ];
+ table
+ .iter()
+ .map(|(label, pattern, group)| Shape {
+ label,
+ re: Regex::new(pattern).expect("valid secret pattern"),
+ group: *group,
+ })
+ .collect()
+});
+
+static PLACEHOLDER: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"\$\$(?:[A-Z0-9_]+_)?[0-9A-F]{12}\$\$").expect("valid placeholder pattern"));
+
+/// What one run hides. Cheap to build; holds the literal secrets found in the
+/// environment when it was made.
+pub(crate) struct SecretFilter {
+ key: [u8; 32],
+ /// `(label, value)`, longest value first, so a secret that contains another
+ /// is replaced whole.
+ literals: Vec<(String, String)>,
+}
+
+/// `Some` when Hide Secrets is on for this process, `None` when it is off.
+/// `JAN_HIDE_SECRETS` wins over `hide_secrets` in `~/.jan/config.toml`.
+pub(crate) fn for_run() -> Option<Arc<SecretFilter>> {
+ let env = std::env::var(ENV).ok();
+ let setting = crate::core::agent::global_config::hide_secrets_setting();
+ if !enabled(env.as_deref(), setting) {
+ return None;
+ }
+ let vars: Vec<(String, String)> = std::env::vars().collect();
+ Some(Arc::new(SecretFilter::new(load_key(), &vars)))
+}
+
+fn enabled(env: Option<&str>, setting: Option<bool>) -> bool {
+ match env.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
+ Some("1" | "true" | "on" | "yes") => true,
+ Some("0" | "false" | "off" | "no") => false,
+ _ => setting.unwrap_or(false),
+ }
+}
+
+/// The per-install key, created on first use. If it cannot be written the run
+/// still works: the key is ephemeral, so placeholders are stable within the
+/// process but not across restarts.
+fn load_key() -> [u8; 32] {
+ let path = crate::core::agent::global_config::global_jan_dir()
+ .ok()
+ .map(|dir| dir.join("secret-placeholder.key"));
+ if let Some(path) = &path {
+ if let Ok(text) = std::fs::read_to_string(path) {
+ if let Ok(bytes) = hex::decode(text.trim()) {
+ if let Ok(key) = <[u8; 32]>::try_from(bytes.as_slice()) {
+ return key;
+ }
+ }
+ }
+ }
+ let mut key = [0u8; 32];
+ rand::thread_rng().fill_bytes(&mut key);
+ if let Some(path) = &path {
+ let written = path
+ .parent()
+ .map(std::fs::create_dir_all)
+ .transpose()
+ .and_then(|_| std::fs::write(path, hex::encode(key)));
+ match written {
+ Ok(()) => restrict(path),
+ Err(e) => log::warn!(
+ "hide_secrets: could not save {}: {e}; placeholders will change on restart",
+ path.display()
+ ),
+ }
+ }
+ key
+}
+
+#[cfg(unix)]
+fn restrict(path: &std::path::Path) {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
+}
+
+#[cfg(not(unix))]
+fn restrict(_path: &std::path::Path) {}
+
+fn is_secret_name(name: &str) -> bool {
+ let upper = name.to_ascii_uppercase();
+ if NOT_SECRETS.contains(&upper.as_str()) {
+ return false;
+ }
+ upper
+ .split(['_', '-', '.'])
+ .any(|token| SECRET_NAME_TOKENS.contains(&token))
+}
+
+/// Keep a name's letters and digits only, for a model-visible label.
+fn label_of(name: &str) -> String {
+ let label: String = name
+ .chars()
+ .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
+ .map(|c| c.to_ascii_uppercase())
+ .take(32)
+ .collect();
+ label.trim_matches('_').to_string()
+}
+
+impl SecretFilter {
+ fn new(key: [u8; 32], vars: &[(String, String)]) -> Self {
+ let mut literals: Vec<(String, String)> = Vec::new();
+ let mut push = |label: String, value: &str| {
+ if value.len() >= MIN_SECRET_LEN
+ && !literals.iter().any(|(_, existing)| existing == value)
+ {
+ literals.push((label, value.to_string()));
+ }
+ };
+ for (name, value) in vars {
+ if is_secret_name(name) && !value.starts_with('/') {
+ push(label_of(name), value);
+ }
+ }
+ // A password inside a URL-shaped value is a secret whatever the
+ // variable is called (`DATABASE_URL`).
+ let url_password = &SHAPES
+ .iter()
+ .find(|s| s.label == "URLPASSWORD")
+ .expect("url shape exists")
+ .re;
+ for (name, value) in vars {
+ for caps in url_password.captures_iter(value) {
+ if let Some(m) = caps.get(1) {
+ push(label_of(name), m.as_str());
+ }
+ }
+ }
+ literals.sort_by_key(|(_, value)| std::cmp::Reverse(value.len()));
+ Self { key, literals }
+ }
+
+ /// A filter over fixed variables and a fixed key, for tests in other modules.
+ #[cfg(test)]
+ pub(crate) fn for_tests(vars: &[(&str, &str)]) -> Self {
+ let vars: Vec<(String, String)> = vars
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ Self::new([7; 32], &vars)
+ }
+
+ /// The placeholder for `value`, remembered so a completion can be restored.
+ fn placeholder(&self, label: &str, value: &str) -> String {
+ let mut mac = Hmac::<Sha256>::new_from_slice(&self.key).expect("hmac takes any key length");
+ mac.update(value.as_bytes());
+ let id = hex::encode_upper(&mac.finalize().into_bytes()[..6]);
+ let text = if label.is_empty() {
+ format!("$${id}$$")
+ } else {
+ format!("$${label}_{id}$$")
+ };
+ REVERSE
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .entry(text.clone())
+ .or_insert_with(|| value.to_string());
+ text
+ }
+
+ /// `text` with every secret replaced by its placeholder. Text that holds no
+ /// secret comes back unchanged, and a placeholder is never rewritten.
+ pub(crate) fn hide(&self, text: &str) -> String {
+ let mut out = text.to_string();
+ for (label, value) in &self.literals {
+ if out.contains(value.as_str()) {
+ out = out.replace(value.as_str(), &self.placeholder(label, value));
+ }
+ }
+ for shape in SHAPES.iter() {
+ if !shape.re.is_match(&out) {
+ continue;
+ }
+ out = shape
+ .re
+ .replace_all(&out, |caps: &regex::Captures| {
+ let whole = caps.get(0).expect("group 0").as_str();
+ match caps.get(shape.group) {
+ Some(hidden) => {
+ let placeholder = self.placeholder(shape.label, hidden.as_str());
+ // Keep the text around the hidden group (`://user:`).
+ whole.replacen(hidden.as_str(), &placeholder, 1)
+ }
+ None => whole.to_string(),
+ }
+ })
+ .into_owned();
+ }
+ out
+ }
+
+ /// A copy of a chat/completions request with every provider-visible string
+ /// run through [`hide`](Self::hide): message text, tool results, and the
+ /// arguments of earlier tool calls. Images, tool schemas and ids are left.
+ pub(crate) fn filter_request(&self, request: &Value) -> Value {
+ let mut out = request.clone();
+ let Some(messages) = out.get_mut("messages").and_then(Value::as_array_mut) else {
+ return out;
+ };
+ for message in messages {
+ for field in ["content", "reasoning_content"] {
+ if let Some(value) = message.get_mut(field) {
+ self.hide_in_content(value);
+ }
+ }
+ if let Some(calls) = message.get_mut("tool_calls").and_then(Value::as_array_mut) {
+ for call in calls {
+ if let Some(args) = call.pointer_mut("/function/arguments") {
+ self.hide_in_content(args);
+ }
+ }
+ }
+ }
+ out
+ }
+
+ fn hide_in_content(&self, value: &mut Value) {
+ match value {
+ Value::String(text) => {
+ let hidden = self.hide(text);
+ if hidden != *text {
+ *text = hidden;
+ }
+ }
+ Value::Array(parts) => {
+ for part in parts {
+ if let Some(text) = part.get_mut("text") {
+ self.hide_in_content(text);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+/// `text` with every placeholder this process knows put back to its secret.
+/// An unknown placeholder is left as it is.
+pub(crate) fn restore(text: &str) -> String {
+ if !text.contains("$$") {
+ return text.to_string();
+ }
+ let reverse = REVERSE.lock().unwrap_or_else(|e| e.into_inner());
+ PLACEHOLDER
+ .replace_all(text, |caps: &regex::Captures| {
+ let found = caps.get(0).expect("group 0").as_str();
+ reverse.get(found).cloned().unwrap_or_else(|| found.to_string())
+ })
+ .into_owned()
+}
+
+/// Restore placeholders in the strings of a JSON value, so a secret containing
+/// a quote or a backslash is escaped by the serializer, not by this function.
+fn restore_json(value: &mut Value) {
+ match value {
+ Value::String(text) => *text = restore(text),
+ Value::Array(items) => items.iter_mut().for_each(restore_json),
+ Value::Object(map) => map.values_mut().for_each(restore_json),
+ _ => {}
+ }
+}
+
+/// Put real values back into a completion: the answer text, the reasoning, and
+/// the arguments of every tool call, so the tool runs with the real value and
+/// the saved thread reads normally. The next request hides them again.
+pub(crate) fn restore_completion(completion: &mut Value) {
+ let Some(choices) = completion.get_mut("choices").and_then(Value::as_array_mut) else {
+ return;
+ };
+ for choice in choices {
+ let Some(message) = choice.get_mut("message") else { continue };
+ for field in ["content", "reasoning_content"] {
+ if let Some(Value::String(text)) = message.get_mut(field) {
+ *text = restore(text);
+ }
+ }
+ let Some(calls) = message.get_mut("tool_calls").and_then(Value::as_array_mut) else {
+ continue;
+ };
+ for call in calls {
+ let Some(Value::String(args)) = call.pointer_mut("/function/arguments") else {
+ continue;
+ };
+ if !args.contains("$$") {
+ continue;
+ }
+ *args = match serde_json::from_str::<Value>(args) {
+ Ok(mut parsed) => {
+ restore_json(&mut parsed);
+ parsed.to_string()
+ }
+ Err(_) => restore(args),
+ };
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ const KEY: [u8; 32] = [7; 32];
+
+ fn filter(vars: &[(&str, &str)]) -> SecretFilter {
+ let vars: Vec<(String, String)> = vars
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ SecretFilter::new(KEY, &vars)
+ }
+
+ #[test]
+ fn the_switch_is_off_unless_asked_for_and_the_env_wins() {
+ assert!(!enabled(None, None));
+ assert!(enabled(None, Some(true)));
+ assert!(!enabled(None, Some(false)));
+ assert!(enabled(Some("1"), None));
+ assert!(enabled(Some("TRUE"), Some(false)));
+ assert!(!enabled(Some("0"), Some(true)), "=0 turns it off");
+ assert!(enabled(Some("maybe"), Some(true)), "unknown value defers to the config");
+ }
+
+ #[test]
+ fn secret_names_are_matched_by_token_not_substring() {
+ for yes in ["OPENAI_API_KEY", "GITHUB_TOKEN", "DB_PASSWORD", "AWS_SECRET_ACCESS_KEY", "AUTH"] {
+ assert!(is_secret_name(yes), "{yes}");
+ }
+ for no in ["PATH", "GIT_AUTHOR_NAME", "KEYBOARD_LAYOUT", "SSH_AUTH_SOCK", "HOME"] {
+ assert!(!is_secret_name(no), "{no}");
+ }
+ }
+
+ #[test]
+ fn an_env_secret_is_hidden_and_a_short_value_or_plain_word_is_not() {
+ let f = filter(&[
+ ("OPENAI_API_KEY", "live-value-1234567890"),
+ ("SHORT_TOKEN", "abc123"),
+ ("EDITOR", "vim-the-editor"),
+ ]);
+ let out = f.hide("export OPENAI_API_KEY=live-value-1234567890 abc123 vim-the-editor");
+ assert!(!out.contains("live-value-1234567890"), "{out}");
+ assert!(out.contains("$$OPENAI_API_KEY_"), "{out}");
+ assert!(out.contains("abc123"), "short values are not hidden");
+ assert!(out.contains("vim-the-editor"), "non-secret names are not hidden");
+ }
+
+ #[test]
+ fn built_in_token_shapes_are_hidden() {
+ let f = filter(&[]);
+ let samples = [
+ "ghp_abcdefghijklmnopqrstuvwxyz0123456789",
+ "sk-proj-abcdefghijklmnopqrstuvwx",
+ "sk-ant-abcdefghijklmnopqrstuvwxyz0123",
+ "AKIAABCDEFGHIJKLMNOP",
+ "xoxb-1234567890-abcdefghij",
+ "hf_abcdefghijklmnopqrstuvwxyz012345",
+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnop",
+ "-----BEGIN RSA PRIVATE KEY-----\nMIIEabc\n-----END RSA PRIVATE KEY-----",
+ ];
+ for sample in samples {
+ let out = f.hide(&format!("token is {sample} ok"));
+ assert!(!out.contains(sample), "{sample} leaked: {out}");
+ assert!(out.starts_with("token is $$") && out.ends_with("$$ ok"), "{out}");
+ }
+ let bearer = f.hide("Authorization: Bearer abcdefghijklmnop1234");
+ assert!(bearer.starts_with("Authorization: Bearer $$BEARER_"), "{bearer}");
+ }
+
+ #[test]
+ fn a_url_password_is_hidden_and_the_rest_of_the_url_stays() {
+ let f = filter(&[("DATABASE_URL", "postgres://app:[email protected]:5432/x")]);
+ let out = f.hide("postgres://app:[email protected]:5432/x and postgres://u:otherpass@h/y");
+ assert!(!out.contains("hunter2hunter2") && !out.contains("otherpass"), "{out}");
+ assert!(out.contains("postgres://app:$$") && out.contains("@db.local:5432/x"), "{out}");
+ }
+
+ #[test]
+ fn hiding_is_deterministic_idempotent_and_leaves_clean_text_alone() {
+ let f = filter(&[("MY_SECRET", "s3cr3t-value-xyz")]);
+ let once = f.hide("a s3cr3t-value-xyz b");
+ assert_eq!(once, f.hide("a s3cr3t-value-xyz b"), "same input, same bytes");
+ assert_eq!(once, f.hide(&once), "a placeholder is not rewritten");
+ assert_eq!(f.hide("nothing to see"), "nothing to see");
+ let other = SecretFilter::new([9; 32], &[("MY_SECRET".into(), "s3cr3t-value-xyz".into())]);
+ assert_ne!(once, other.hide("a s3cr3t-value-xyz b"), "the id depends on the key");
+ }
+
+ #[test]
+ fn a_tool_call_with_a_placeholder_runs_with_the_real_value() {
+ let f = filter(&[("MY_SECRET", "p@ss\"word\\value1")]);
+ let hidden = f.hide("p@ss\"word\\value1");
+ let args = json!({ "command": format!("login {hidden}") }).to_string();
+ let mut completion = json!({"choices":[{"message":{
+ "content": format!("using {hidden}"),
+ "tool_calls":[{"id":"c1","type":"function","function":{"name":"bash","arguments": args}}]
+ }}]});
+ restore_completion(&mut completion);
+ assert_eq!(completion["choices"][0]["message"]["content"], "using p@ss\"word\\value1");
+ let args = completion["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"]
+ .as_str()
+ .unwrap();
+ let parsed: Value = serde_json::from_str(args).expect("still valid JSON");
+ assert_eq!(parsed["command"], "login p@ss\"word\\value1");
+ }
+
+ #[test]
+ fn an_unknown_placeholder_is_left_alone() {
+ let text = "$$NOPE_0123456789AB$$";
+ assert_eq!(restore(text), text);
+ }
+
+ #[test]
+ fn a_request_is_filtered_everywhere_the_provider_reads_text() {
+ let f = filter(&[("MY_TOKEN", "tok-1234567890abc")]);
+ let request = json!({
+ "model": "m",
+ "tools": [{"type":"function","function":{"name":"bash","description":"tok-1234567890abc"}}],
+ "messages": [
+ {"role":"system","content":"you are Jan"},
+ {"role":"user","content":[{"type":"text","text":"use tok-1234567890abc"},
+ {"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]},
+ {"role":"assistant","content":null,"tool_calls":[
+ {"id":"c1","type":"function","function":{"name":"bash","arguments":"{\"c\":\"echo tok-1234567890abc\"}"}}]},
+ {"role":"tool","tool_call_id":"c1","content":"tok-1234567890abc"}
+ ]
+ });
+ let out = f.filter_request(&request);
+ let text = out["messages"].to_string();
+ assert!(!text.contains("tok-1234567890abc"), "{text}");
+ assert!(text.contains("data:image/png;base64,AAAA"), "images are untouched");
+ assert_eq!(out["messages"][2]["content"], Value::Null);
+ assert_eq!(out["tools"], request["tools"], "tool schemas are not part of the pass");
+ assert_eq!(request["messages"][3]["content"], "tok-1234567890abc", "the input is not mutated");
+ }
+
+ /// The cache rule: a request that extends an earlier one keeps the earlier
+ /// bytes exactly.
+ #[test]
+ fn a_longer_request_keeps_the_filtered_prefix_byte_identical() {
+ let f = filter(&[("MY_TOKEN", "tok-1234567890abc")]);
+ let first = json!({"model":"m","messages":[
+ {"role":"system","content":"sys"},
+ {"role":"user","content":"key is tok-1234567890abc"}]});
+ let mut second = first.clone();
+ second["messages"].as_array_mut().unwrap().extend([
+ json!({"role":"assistant","content":"ok"}),
+ json!({"role":"user","content":"again ghp_abcdefghijklmnopqrstuvwxyz0123456789"}),
+ ]);
+ let a = f.filter_request(&first)["messages"].as_array().unwrap().clone();
+ let b = f.filter_request(&second)["messages"].as_array().unwrap().clone();
+ for (i, message) in a.iter().enumerate() {
+ assert_eq!(
+ serde_json::to_string(message).unwrap(),
+ serde_json::to_string(&b[i]).unwrap(),
+ "message {i} moved"
+ );
+ }
+ }
+
+ #[test]
+ fn the_key_is_created_once_private_and_reused() {
+ crate::core::agent::global_config::with_temp_home(|home| {
+ let first = load_key();
+ let path = home.join(".jan").join("secret-placeholder.key");
+ assert!(path.exists(), "{}", path.display());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ }
+ assert_eq!(first, load_key(), "the same key on the next call");
+ });
+ }
+}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index e3b03ad3e..815a09b4a 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -13856,6 +13856,13 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[
kind: AgentSettingKind::Bool { default: true },
scope: SettingScope::Global,
},
+ AgentSettingDef {
+ key: "hide_secrets",
+ label: "hide_secrets",
+ desc: "Privacy: obfuscate secret env values and redact credential-shaped tokens before sending to AI providers",
+ kind: AgentSettingKind::Bool { default: false },
+ scope: SettingScope::Global,
+ },
AgentSettingDef {
key: "wave",
label: "wave",