Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(agent): secret paths are off limits for every agent tool, in every mode (C59 A5)

purpleeccf17efb581
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index b2054c1f..08f42a41 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -1163,6 +1163,12 @@ async fn handle_agent_tool(
}
};
+ // C59: secret paths are off limits for every remote tool call, before
+ // any permission or workspace logic runs (crate::secret_paths).
+ if let Some((path, why)) = crate::secret_paths::hit_in_args(&body.args) {
+ return graceful_error(&crate::secret_paths::refusal(&path, why));
+ }
+
let result: Result<serde_json::Value, String> = match tool_name.as_str() {
"file_read" => {
let path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 0661a099..a76bc4fd 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -18,6 +18,7 @@ mod android_entry;
#[cfg(target_os = "linux")]
mod linux_media;
mod app_identity;
+mod secret_paths;
// The chat's HTML preview server. A phone starts no server (mobile_guard.rs).
#[cfg(desktop)]
mod html_preview;
diff --git a/src-tauri/src/secret_paths.rs b/src-tauri/src/secret_paths.rs
new file mode 100644
index 00000000..01f1a63f
--- /dev/null
+++ b/src-tauri/src/secret_paths.rs
@@ -0,0 +1,146 @@
+//! Paths a remote agent never reads, lists, searches or runs a command on
+//! (C59). The desktop agents meet the same list in `src/lib/secret-paths.ts`
+//! at tool registration; the phone's tools run here in `remote.rs` and never
+//! pass that registry, so the list lives twice. `secret_paths_parity` in the
+//! TS tests holds the two against the same sample paths.
+//!
+//! Not a sandbox: a shell command can reach a file without naming it. This
+//! catches what a model writes, which is the name.
+
+fn segs(p: &str) -> Vec<&str> {
+ p.split('/').filter(|s| !s.is_empty()).collect()
+}
+
+fn ends_with_any(p: &str, names: &[&str]) -> bool {
+ let last = p.rsplit('/').next().unwrap_or("");
+ names.contains(&last)
+}
+
+/// `~`, `$HOME`, `${HOME}`, `%USERPROFILE%`, backslashes, quotes, `file://`.
+pub fn normalise(raw: &str) -> String {
+ let mut p = raw.trim().trim_matches(|c| c == '"' || c == '\'').replace('\\', "/");
+ if let Some(rest) = p.strip_prefix("file://") { p = rest.to_string(); }
+ for pre in ["${HOME}", "$HOME", "%USERPROFILE%"] {
+ if p.len() >= pre.len() && p[..pre.len()].eq_ignore_ascii_case(pre) {
+ let rest = &p[pre.len()..];
+ if rest.is_empty() || rest.starts_with('/') { p = format!("~{}", rest); }
+ break;
+ }
+ }
+ while p.contains("//") { p = p.replace("//", "/"); }
+ p.to_lowercase()
+}
+
+/// Why `path` is off limits, or None.
+pub fn reason(path: &str) -> Option<&'static str> {
+ let p = normalise(path);
+ if p.is_empty() { return None; }
+ let s = segs(&p);
+ let last = *s.last().unwrap_or(&"");
+ let joined = format!("/{}", s.join("/"));
+ if s.contains(&".ssh") { return Some("SSH keys"); }
+ if joined.ends_with("/huggingface/token") || joined.ends_with("/.huggingface/token")
+ || joined.ends_with("/.cache/huggingface/stored_tokens") { return Some("a Hugging Face access token"); }
+ if s.contains(&".aws") { return Some("AWS credentials"); }
+ if joined.contains("/.config/gcloud") { return Some("Google Cloud credentials"); }
+ if s.contains(&".azure") { return Some("Azure credentials"); }
+ if joined.ends_with("/.kube/config") { return Some("Kubernetes credentials"); }
+ if ends_with_any(&p, &[".netrc", "_netrc", ".git-credentials", ".pgpass", ".npmrc", ".pypirc"]) { return Some("stored passwords or tokens"); }
+ if joined.ends_with("/.docker/config.json") { return Some("Docker registry credentials"); }
+ if joined.ends_with("/.config/gh/hosts.yml") || joined.ends_with("/.config/gh/hosts.yaml") { return Some("the GitHub CLI token"); }
+ if s.contains(&".gnupg") { return Some("GPG keys"); }
+ if joined.contains("/library/keychains") || last.ends_with(".keychain") || last.ends_with(".keychain-db") { return Some("the system keychain"); }
+ for ext in [".pem", ".key", ".p12", ".pfx", ".jks", ".keystore", ".ppk"] {
+ if last.ends_with(ext) { return Some("a private key or certificate store"); }
+ }
+ for k in ["id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"] {
+ let base = last.trim_end_matches(".pub").trim_end_matches("_sk");
+ if base == k { return Some("an SSH key"); }
+ }
+ if last == ".env" || (last.starts_with(".env.") && !matches!(&last[5..], "example" | "sample" | "template" | "dist" | "defaults")) {
+ return Some("environment secrets (.env)");
+ }
+ if last == "secrets.json" || last == "secret.json" { return Some("stored API keys"); }
+ if joined.starts_with("/volumes/") && s.get(1).map(|v| v.contains("credential")).unwrap_or(false) { return Some("a credentials volume"); }
+ let browser_file = ["cookies", "login data", "web data", "logins.json", "key3.db", "key4.db", "cookies.sqlite"];
+ if browser_file.iter().any(|f| last == *f || last == format!("{}-journal", f))
+ || ["/library/application support/google/chrome", "/library/application support/bravesoftware",
+ "/library/application support/microsoft edge", "/library/application support/firefox",
+ "/library/application support/arc/user data", "/library/cookies"].iter().any(|d| joined.contains(d)) {
+ return Some("browser cookies or saved logins");
+ }
+ None
+}
+
+fn words(command: &str) -> Vec<String> {
+ command
+ .split(|c: char| c.is_whitespace() || ";|&<>()`".contains(c))
+ .flat_map(|w| w.split('=').map(|x| x.to_string()).collect::<Vec<_>>())
+ .map(|w| w.trim_matches(|c| c == '"' || c == '\'').to_string())
+ .filter(|w| w.len() > 1)
+ .collect()
+}
+
+/// The first secret path a remote tool call names: path-like arguments, and
+/// the words of a shell command or stdin script. Content to be written is not
+/// looked at.
+pub fn hit_in_args(args: &serde_json::Value) -> Option<(String, &'static str)> {
+ let strs = |v: Option<&serde_json::Value>| -> Vec<String> {
+ match v {
+ Some(serde_json::Value::String(s)) => vec![s.clone()],
+ Some(serde_json::Value::Array(a)) => a.iter().filter_map(|x| x.as_str().map(|s| s.to_string())).collect(),
+ _ => vec![],
+ }
+ };
+ for key in ["path", "paths", "cwd", "file", "files", "directory", "dir", "source", "destination", "target", "url", "args"] {
+ for s in strs(args.get(key)) {
+ if let Some(why) = reason(&s) { return Some((s, why)); }
+ }
+ }
+ for key in ["command", "stdin", "script"] {
+ for s in strs(args.get(key)) {
+ for w in words(&s) {
+ if let Some(why) = reason(&w) { return Some((w, why)); }
+ }
+ }
+ }
+ None
+}
+
+pub fn refusal(path: &str, why: &str) -> String {
+ format!("Refused: {} holds {}. LU never lets an agent read, list, search or run commands on secret files, in any mode. Nothing was read.", path, why)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn the_paths_from_the_list_are_refused() {
+ for p in [
+ "~/.huggingface/token", "~/.cache/huggingface/token", "/Users/x/.ssh/id_ed25519", "$HOME/.aws/credentials",
+ "~/.config/gcloud/application_default_credentials.json", "~/.netrc", "~/.git-credentials",
+ "~/.docker/config.json", "~/Library/Keychains/login.keychain-db", "certs/server.pem", "deploy.key",
+ "id_rsa", ".env", "app/.env.local", "secrets.json", "/Volumes/MyCredentials/x.txt",
+ "~/Library/Application Support/Google/Chrome/Default/Cookies", "C:\\Users\\x\\.ssh\\config",
+ ] {
+ assert!(reason(p).is_some(), "{p} should be refused");
+ }
+ }
+
+ #[test]
+ fn ordinary_files_pass() {
+ for p in ["notes.txt", "src/env.ts", ".env.example", "docs/keys.md", "README.md", "config.json", "src/secret_paths.rs"] {
+ assert!(reason(p).is_none(), "{p} should pass");
+ }
+ }
+
+ #[test]
+ fn a_shell_command_naming_one_is_refused() {
+ assert!(hit_in_args(&json!({ "command": "cat ~/.ssh/id_rsa" })).is_some());
+ assert!(hit_in_args(&json!({ "command": "grep TOKEN \"$HOME/.aws/credentials\"" })).is_some());
+ assert!(hit_in_args(&json!({ "command": "ls -la src" })).is_none());
+ assert!(hit_in_args(&json!({ "path": "notes.txt", "content": "see .env" })).is_none());
+ }
+}
diff --git a/src/api/mcp/__tests__/secret-paths-never-reach-the-backend.test.ts b/src/api/mcp/__tests__/secret-paths-never-reach-the-backend.test.ts
new file mode 100644
index 00000000..a0310377
--- /dev/null
+++ b/src/api/mcp/__tests__/secret-paths-never-reach-the-backend.test.ts
@@ -0,0 +1,76 @@
+/**
+ * C59, after C60's live run 1: a 9B tried `file_read ~/.huggingface/token`
+ * unasked. The read came back empty, but it must not get that far. Every
+ * built-in tool now refuses a secret path before the backend sees the call,
+ * in every mode (the guard sits at registration, Bypass has nothing to skip).
+ *
+ * Red without the guard: the backend records the read.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []
+
+vi.mock('../../backend', () => ({
+ backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {
+ backendCalls.push({ cmd, body })
+ if (cmd === 'shell_execute') return { stdout: 'ran', stderr: '', exitCode: 0 }
+ if (cmd === 'fs_read') return { content: 'hf_SECRET', encoding: 'utf8' }
+ if (cmd === 'fs_search') return { results: [] }
+ return { ok: true }
+ }),
+ fetchExternal: vi.fn(async () => ({ ok: true, status: 200, text: async () => '' })),
+}))
+vi.mock('../../agents/sub-agent', () => ({
+ DELEGATE_TASK_TOOL_DEF: { name: 'delegate_task', description: '', category: 'system', inputSchema: {} },
+ buildDelegateExecutor: () => async () => 'stub',
+}))
+vi.mock('../../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))
+
+import { registerBuiltinTools, runRetiredTool } from '../builtin-tools'
+import { ToolRegistry } from '../tool-registry'
+
+const registry = new ToolRegistry()
+registerBuiltinTools(registry)
+
+beforeEach(() => { backendCalls.length = 0 })
+
+const reaches = (cmd: string) => backendCalls.some((c) => c.cmd === cmd)
+
+describe('secret paths never reach the backend', () => {
+ it('file_read ~/.huggingface/token: refused, nothing read', async () => {
+ const out = await registry.execute('file_read', { path: '~/.huggingface/token' })
+ expect(out).toMatch(/^Error: Refused: ~\/\.huggingface\/token holds a Hugging Face access token/)
+ expect(reaches('fs_read')).toBe(false)
+ })
+
+ it('the same for the other tools and spellings', async () => {
+ const cases: Array<[string, Record<string, unknown>, string]> = [
+ ['file_read', { path: '/Users/x/.ssh/id_ed25519' }, 'fs_read'],
+ ['file_read', { path: '.env' }, 'fs_read'],
+ ['file_list', { path: '~/.aws' }, 'fs_list'],
+ ['file_search', { path: '~/.config/gcloud', pattern: 'token' }, 'fs_search'],
+ ['shell_execute', { command: 'cat ~/.ssh/id_rsa' }, 'shell_execute'],
+ ['shell_execute', { command: 'grep TOKEN "$HOME/.netrc"' }, 'shell_execute'],
+ ['shell_execute', { command: 'ls', cwd: '~/.ssh' }, 'shell_execute'],
+ ['shell_execute', { command: 'python3 -', stdin: 'print(open("/Users/x/.git-credentials").read())' }, 'shell_execute'],
+ ]
+ for (const [tool, args, cmd] of cases) {
+ const out = await registry.execute(tool, args)
+ expect(out, `${tool} ${JSON.stringify(args)}`).toMatch(/^Error: Refused:/)
+ expect(reaches(cmd), `${tool} reached ${cmd}`).toBe(false)
+ }
+ })
+
+ it('a retired tool name is no way around it', async () => {
+ const out = await runRetiredTool('code_execute', { language: 'bash', code: 'cat ~/.aws/credentials', stdin: 'cat ~/.aws/credentials' })
+ expect(out).toMatch(/Refused:/)
+ expect(reaches('shell_execute')).toBe(false)
+ })
+
+ it('ordinary paths still run', async () => {
+ await registry.execute('file_read', { path: 'notes.txt' })
+ expect(reaches('fs_read')).toBe(true)
+ await registry.execute('shell_execute', { command: 'ls -la src' })
+ expect(reaches('shell_execute')).toBe(true)
+ })
+})
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index b852a10b..7df57eb9 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -51,6 +51,7 @@ import { macEditSide } from '../../lib/image-engines'
import { aspectFrame, aspectRatioReject, parseAspectRatio } from '../../lib/aspect-frame'
import { CHARACTER_ARG_SCHEMA, characterImageArgs, characterVideoArgs, type CharacterChatDeps } from '../../lib/character-chat'
import { blockMessageFor, checkPromptSafety } from '../../lib/render/safety'
+import { dropSecretLines, secretAccessOf, secretRefusal } from '../../lib/secret-paths'
/**
* Helper: current chat id (+ folder workspace) as a fragment to spread into
@@ -2414,7 +2415,7 @@ export function registerBuiltinTools(registry: ToolRegistry) {
if (!toolExistsOnThisDevice(tool.name)) continue
const executor = EXECUTOR_MAP[tool.name]
if (executor) {
- registry.registerBuiltin(toolDefinitionForThisDevice(tool), executor)
+ registry.registerBuiltin(toolDefinitionForThisDevice(tool), guardSecrets(tool.name, executor))
}
}
// M7 / Audit W-T2: der Redirect für zurückgezogene Namen wird hier ANGEMELDET,
@@ -2500,14 +2501,33 @@ export const RETIRED_EXECUTOR_NAMES: ReadonlySet<string> = new Set(Object.keys(R
* never ours. The appended note is one line so the model learns the new way
* without the step being wasted.
*/
+type Executor = (args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal) => Promise<string>
+
+/**
+ * Every built-in tool goes through this: a call that names a secret path
+ * (lib/secret-paths.ts) is refused before anything runs, in every mode,
+ * Bypass included. It sits at registration, so both tabs, sub agents,
+ * workflows and the phone's dispatch meet the same floor. file_search over a
+ * folder also loses the lines that came from secret files.
+ */
+export function guardSecrets(name: string, executor: Executor): Executor {
+ return async (args, run, signal) => {
+ const hit = secretAccessOf(name, args as Record<string, unknown>)
+ if (hit) return secretRefusal(hit)
+ const out = await executor(args, run, signal)
+ return name === 'file_search' ? dropSecretLines(out) : out
+ }
+}
+
export async function runRetiredTool(
name: string,
args: ToolArgs,
run?: AgentRunContext,
signal?: AbortSignal,
): Promise<string | null> {
- const exec = RETIRED_EXECUTORS[name]
- if (!exec) return null
+ const raw = RETIRED_EXECUTORS[name]
+ if (!raw) return null
+ const exec = guardSecrets(name, raw)
// On a phone the old names must not be a back door to the shell: all but
// the clock answer as a name that was never ours.
if (!retiredToolRunsOnThisDevice(name)) return null
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index cac01983..816989d0 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -172,6 +172,7 @@ import type { ToolArgs } from '../api/mcp/types'
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
import { buildChatSystemPrompt } from '../lib/system-prompt'
import { agentProfileFor, resultCharsFor, COMPACT_MAX_TOOLS, COMPACT_PREFER } from '../lib/agent-profile'
+import { secretAccessOf, secretNotice } from '../lib/secret-paths'
import { TOOL_SEARCH, TOOL_SEARCH_DEF, briefFor, clearUnlockedTools, runToolSearch, withToolSearch } from '../lib/tool-search'
import { withChatPersona, samplingPresetFor, speakerCustomParams, speakerPersonaFor } from '../lib/chat-persona'
import { injectPersonaNote, noteTokens, personaNoteOf } from '../lib/persona-note'
@@ -2974,6 +2975,16 @@ export function useAgentChat() {
timestamp: Date.now(),
})
}
+ // C59: a call on a secret path is refused by the tool itself
+ // (builtin-tools guardSecrets); the user sees it here, not only the model.
+ for (const tc of toolCalls) {
+ const hit = secretAccessOf(tc.function?.name ?? '', tc.function?.arguments as Record<string, unknown>)
+ if (hit) {
+ addBlock(runState, convId!, assistantMessage.id, {
+ id: uuid(), phase: 'reflection', content: secretNotice(tc.function.name, hit), timestamp: Date.now(),
+ })
+ }
+ }
// Every call carries an id from here on. Only the NATIVE channel gives
// us one; a call lifted out of prose (parseLooseToolCalls) or
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index f9636033..f39bf73c 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -85,6 +85,7 @@ import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'
import { repairToolCall } from '../lib/loose-tool-parse'
import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools, isGatedTool, applyMaxTools } from '../lib/tool-selection'
import { agentProfileFor, resultCharsFor, COMPACT_MAX_TOOLS, COMPACT_PREFER } from '../lib/agent-profile'
+import { secretAccessOf, secretNotice } from '../lib/secret-paths'
import type { MCPToolDefinition } from '../api/mcp/types'
import { TOOL_SEARCH, TOOL_SEARCH_DEF, briefFor, clearUnlockedTools, runToolSearch, withToolSearch } from '../lib/tool-search'
import { reaRoutingText } from '../lib/plugins/rea-tools'
@@ -2277,6 +2278,12 @@ export function useCodex() {
timestamp: Date.now(),
})
}
+ // C59: a call on a secret path is refused by the tool itself
+ // (builtin-tools guardSecrets); the user sees it here, not only the model.
+ for (const tc of toolCalls) {
+ const hit = secretAccessOf(tc.function?.name ?? '', tc.function?.arguments as Record<string, unknown>)
+ if (hit) addBlock({ id: uuid(), phase: 'reflection', content: secretNotice(tc.function.name, hit), timestamp: Date.now() })
+ }
type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string; injectedArgs: ToolArgs }
const batch: BatchEntry[] = []
diff --git a/src/lib/__tests__/secret-paths.test.ts b/src/lib/__tests__/secret-paths.test.ts
new file mode 100644
index 00000000..da82d3cb
--- /dev/null
+++ b/src/lib/__tests__/secret-paths.test.ts
@@ -0,0 +1,57 @@
+/**
+ * The list of secret paths (C59). The phone's tools run in Rust
+ * (remote.rs) and use src-tauri/src/secret_paths.rs; the last test holds the
+ * two lists against the Rust test's own sample paths.
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { dropSecretLines, secretAccessOf, secretNotice, secretPathReason } from '../secret-paths'
+
+const SECRET = [
+ '~/.huggingface/token', '~/.cache/huggingface/token', '/Users/x/.ssh/id_ed25519', '$HOME/.aws/credentials',
+ '${HOME}/.aws/config', '~/.config/gcloud/application_default_credentials.json', '~/.netrc', '~/.git-credentials',
+ '~/.docker/config.json', '~/Library/Keychains/login.keychain-db', 'certs/server.pem', 'deploy.key', 'id_rsa',
+ '.env', 'app/.env.local', 'secrets.json', '/Volumes/MyCredentials/x.txt',
+ '~/Library/Application Support/Google/Chrome/Default/Cookies', 'C:\\Users\\x\\.ssh\\config', '%USERPROFILE%\\.aws\\credentials',
+ 'file:///Users/x/.ssh/id_rsa', '~/.gnupg/private-keys-v1.d/x.key', '~/.config/gh/hosts.yml',
+]
+const ORDINARY = ['notes.txt', 'src/env.ts', '.env.example', 'docs/keys.md', 'README.md', 'config.json', 'src/secret-paths.ts', 'environment.md']
+
+describe('secret paths', () => {
+ it('every path on the list is refused', () => {
+ for (const p of SECRET) expect(secretPathReason(p), p).toBeTruthy()
+ })
+ it('ordinary paths pass', () => {
+ for (const p of ORDINARY) expect(secretPathReason(p), p).toBeNull()
+ })
+ it('a tool call is checked on its path arguments and command words, not on what it writes', () => {
+ expect(secretAccessOf('file_read', { path: '~/.huggingface/token' })?.why).toMatch(/Hugging Face/)
+ expect(secretAccessOf('shell_execute', { command: 'cat ~/.ssh/id_rsa | base64' })?.path).toBe('~/.ssh/id_rsa')
+ expect(secretAccessOf('shell_execute', { command: 'export X=~/.aws/credentials' })).toBeTruthy()
+ expect(secretAccessOf('shell_execute', { command: 'npm test' })).toBeNull()
+ expect(secretAccessOf('file_write', { path: 'notes.md', content: 'cat ~/.ssh/id_rsa' })).toBeNull()
+ })
+ it('the user sees a notice that names the tool and the path', () => {
+ expect(secretNotice('file_read', { path: '~/.netrc', why: 'stored passwords or tokens' })).toBe('🔒 Blocked: the model tried file_read on ~/.netrc (stored passwords or tokens). Nothing was read.')
+ })
+ it('a folder search loses the lines from secret files', () => {
+ const out = dropSecretLines('src/a.ts:3: const t = 1\n.env:1: API_KEY=abc\napp/.env.local:2: X=y')
+ expect(out).toContain('src/a.ts:3')
+ expect(out).not.toContain('API_KEY')
+ expect(out).toMatch(/2 line\(s\) from secret files left out/)
+ })
+ it('the Rust list (phone tools) refuses and passes the same sample paths', () => {
+ const rs = readFileSync(resolve(__dirname, '../../../src-tauri/src/secret_paths.rs'), 'utf8')
+ const block = (fn: string) => {
+ const body = rs.slice(rs.indexOf(`fn ${fn}()`))
+ const list = body.slice(body.indexOf('for p in ['), body.indexOf(']', body.indexOf('for p in [')))
+ return [...list.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1].replace(/\\\\/g, '\\'))
+ }
+ const refused = block('the_paths_from_the_list_are_refused')
+ const passed = block('ordinary_files_pass')
+ expect(refused.length).toBeGreaterThan(10)
+ for (const p of refused) expect(secretPathReason(p), `Rust refuses ${p}, TS must too`).toBeTruthy()
+ for (const p of passed) expect(secretPathReason(p), `Rust passes ${p}, TS must too`).toBeNull()
+ })
+})
diff --git a/src/lib/secret-paths.ts b/src/lib/secret-paths.ts
new file mode 100644
index 00000000..4b7a9dac
--- /dev/null
+++ b/src/lib/secret-paths.ts
@@ -0,0 +1,160 @@
+/**
+ * Paths an agent never reads, lists, searches or runs a command on, in any
+ * mode, Bypass included (C59, after C60's live run 1: a 9B tried
+ * `file_read ~/.huggingface/token` unasked).
+ *
+ * What this is: a hard floor under every built-in tool. A call that names
+ * one of these paths is refused before anything runs, the model is told why,
+ * and the user sees a notice in the run.
+ *
+ * What this is not: a sandbox. A shell command can reach a file without
+ * spelling its name (`grep -r token ~`, a script, a variable). The list
+ * catches what a model actually writes, which is the name. The boundary for
+ * everything else is the approval mode the user chose.
+ */
+
+export interface SecretHit {
+ /** The path as the model wrote it. */
+ path: string
+ /** Why it is off limits, for the model and the notice. */
+ why: string
+}
+
+interface Rule { test: (p: string) => boolean; why: string }
+
+const seg = (p: string) => p.split('/').filter(Boolean)
+const has = (p: string, dir: string) => seg(p).includes(dir)
+
+/** Patterns over a normalised path: forward slashes, `~` for the home folder, lower case. */
+const RULES: Rule[] = [
+ { test: (p) => has(p, '.ssh'), why: 'SSH keys' },
+ { test: (p) => /(^|\/)\.?huggingface\/token$/.test(p) || /(^|\/)\.cache\/huggingface\/(token|stored_tokens)$/.test(p), why: 'a Hugging Face access token' },
+ { test: (p) => has(p, '.aws'), why: 'AWS credentials' },
+ { test: (p) => /(^|\/)\.config\/gcloud(\/|$)/.test(p), why: 'Google Cloud credentials' },
+ { test: (p) => /(^|\/)\.azure(\/|$)/.test(p), why: 'Azure credentials' },
+ { test: (p) => /(^|\/)\.kube\/config$/.test(p), why: 'Kubernetes credentials' },
+ { test: (p) => /(^|\/)(\.netrc|_netrc|\.git-credentials|\.pgpass|\.npmrc|\.pypirc)$/.test(p), why: 'stored passwords or tokens' },
+ { test: (p) => /(^|\/)\.docker\/config\.json$/.test(p), why: 'Docker registry credentials' },
+ { test: (p) => /(^|\/)\.config\/gh\/hosts\.ya?ml$/.test(p), why: 'the GitHub CLI token' },
+ { test: (p) => has(p, '.gnupg'), why: 'GPG keys' },
+ { test: (p) => /(^|\/)library\/keychains(\/|$)/.test(p) || /\.keychain(-db)?$/.test(p), why: 'the system keychain' },
+ { test: (p) => /\.(pem|key|p12|pfx|jks|keystore|ppk)$/.test(p), why: 'a private key or certificate store' },
+ { test: (p) => /(^|\/)id_(rsa|dsa|ecdsa|ed25519)(_sk)?(\.pub)?$/.test(p), why: 'an SSH key' },
+ {
+ // .env, .env.local, .env.production … but not the examples projects ship.
+ test: (p) => /(^|\/)\.env(\.[a-z0-9_-]+)*$/.test(p) && !/(^|\/)\.env\.(example|sample|template|dist|defaults)$/.test(p),
+ why: 'environment secrets (.env)',
+ },
+ { test: (p) => /(^|\/)secrets?\.json$/.test(p), why: 'stored API keys' },
+ { test: (p) => /^\/volumes\/[^/]*credential/.test(p), why: 'a credentials volume' },
+ {
+ // Browser profiles: cookies, saved logins, session stores.
+ test: (p) => /(^|\/)(cookies|login data|web data|logins\.json|key[34]\.db|cookies\.sqlite)(-journal)?$/.test(p)
+ || /(^|\/)library\/application support\/(google\/chrome|bravesoftware|microsoft edge|firefox|arc\/user data)(\/|$)/.test(p)
+ || /(^|\/)library\/cookies(\/|$)/.test(p)
+ || /(^|\/)appdata\/(local|roaming)\/(google\/chrome|microsoft\/edge|mozilla\/firefox)\/.*user data/.test(p),
+ why: 'browser cookies or saved logins',
+ },
+]
+
+/** `~`, `$HOME`, `${HOME}`, `%USERPROFILE%` and the real home all become `~`. */
+export function normaliseForSecrets(raw: string, home?: string): string {
+ let p = raw.trim().replace(/^["']|["']$/g, '').replace(/\\/g, '/')
+ p = p.replace(/^file:\/\//i, '')
+ p = p.replace(/^(\$\{?HOME\}?|%USERPROFILE%)(?=\/|$)/i, '~')
+ if (home) {
+ const h = home.replace(/\\/g, '/').replace(/\/+$/, '')
+ if (h && (p === h || p.startsWith(h + '/'))) p = '~' + p.slice(h.length)
+ }
+ // Collapse ./ and duplicate slashes; a `..` does not unlock anything, the
+ // rules match on segments wherever they stand.
+ p = p.replace(/\/{2,}/g, '/').replace(/(^|\/)\.\/(?=.)/g, '$1')
+ return p.toLowerCase()
+}
+
+/** Why `path` is off limits, or null. */
+export function secretPathReason(path: string, home?: string): string | null {
+ if (!path || typeof path !== 'string') return null
+ const p = normaliseForSecrets(path, home)
+ if (!p) return null
+ return RULES.find((r) => r.test(p))?.why ?? null
+}
+
+/**
+ * The words of a shell command that look like paths. Quote aware enough for
+ * the forms models write: `cat ~/.ssh/id_rsa`, `cat "$HOME/.aws/credentials"`,
+ * `grep x < .env`, `cp ~/.netrc /tmp/x`.
+ */
+function shellWords(command: string): string[] {
+ return command
+ .split(/[\s;|&<>()`]+|=(?=[~/$.])/)
+ .map((w) => w.replace(/^["']+|["']+$/g, ''))
+ .filter((w) => w.length > 1)
+}
+
+/** Argument names that hold a path or a command in the built-in tools. */
+const PATH_KEYS = ['path', 'paths', 'cwd', 'file', 'files', 'directory', 'dir', 'source', 'destination', 'target', 'url']
+const COMMAND_KEYS = ['command', 'stdin', 'script']
+
+function strings(v: unknown): string[] {
+ if (typeof v === 'string') return [v]
+ if (Array.isArray(v)) return v.filter((x): x is string => typeof x === 'string')
+ return []
+}
+
+/**
+ * The first secret path a tool call names, or null. Looks at the path-like
+ * arguments of any tool and at the words of a shell command or script. The
+ * content a tool writes is not looked at: a file that mentions `.env` is fine.
+ */
+export function secretAccessOf(toolName: string, args: Record<string, unknown> | undefined, home?: string): SecretHit | null {
+ if (!args || typeof args !== 'object') return null
+ for (const key of PATH_KEYS) {
+ for (const s of strings(args[key])) {
+ const why = secretPathReason(s, home)
+ if (why) return { path: s, why }
+ }
+ }
+ for (const key of COMMAND_KEYS) {
+ for (const s of strings(args[key])) {
+ for (const w of shellWords(s)) {
+ const why = secretPathReason(w, home)
+ if (why) return { path: w, why }
+ }
+ }
+ }
+ // Shell arguments passed as a list (`args: ["~/.ssh/id_rsa"]`).
+ if (/shell|exec|code/.test(toolName)) {
+ for (const s of strings(args.args)) {
+ const why = secretPathReason(s, home)
+ if (why) return { path: s, why }
+ }
+ }
+ return null
+}
+
+/** What the model reads back. Starts with "Error:" so every caller counts it as a failed call. */
+export function secretRefusal(hit: SecretHit): string {
+ return `Error: Refused: ${hit.path} holds ${hit.why}. LU never lets an agent read, list, search or run commands on secret files, in any mode. Nothing was read. Do the task without it; if you really need a value from it, ask the user to give it to you.`
+}
+
+/** The line the user sees in the run. */
+export function secretNotice(toolName: string, hit: SecretHit): string {
+ return `🔒 Blocked: the model tried ${toolName} on ${hit.path} (${hit.why}). Nothing was read.`
+}
+
+/**
+ * file_search over a folder reads every file in it, .env included. Drops the
+ * result lines whose file is a secret one, so a broad search cannot carry a
+ * token out. A line is `path:line: text` or a bare path.
+ */
+export function dropSecretLines(result: string, home?: string): string {
+ if (!result) return result
+ let dropped = 0
+ const kept = result.split('\n').filter((line) => {
+ const file = line.match(/^(.+?):\d+:/)?.[1] ?? line.trim()
+ if (file && secretPathReason(file, home)) { dropped++; return false }
+ return true
+ })
+ return dropped ? `${kept.join('\n')}\n(${dropped} line(s) from secret files left out.)` : result
+}