diff --git a/.changeset/browser-import-cost-bound.md b/.changeset/browser-import-cost-bound.md new file mode 100644 index 00000000..88943e38 --- /dev/null +++ b/.changeset/browser-import-cost-bound.md @@ -0,0 +1,5 @@ +--- +"turno-browser": patch +--- + +`turno-browser import` takes only the key derivation parameters `export` writes: scrypt `r` 8 and `p` 1, and `N` at most 2^17, so reading a `.session` file never costs more memory than writing one (about 128 MiB). A header that asks for more is refused as damaged before any key is derived. Every export written so far uses exactly these values and still imports. diff --git a/.changeset/browser-remove-reports-unchecked.md b/.changeset/browser-remove-reports-unchecked.md new file mode 100644 index 00000000..5f86ce85 --- /dev/null +++ b/.changeset/browser-remove-reports-unchecked.md @@ -0,0 +1,5 @@ +--- +"turno-browser": patch +--- + +`turno-browser remove` no longer reports a complete removal (exit 0) while it could not check something. What it cannot check goes under `left` with `"unchecked": true` in `--json`, as "could not check" in the plan and "not checked" afterwards, and the exit code is 1: an agent config file it cannot read or parse, a registration `init` recorded in a file Cursor's, GitHub Copilot CLI's or Gemini CLI's own command does not change (now with the step to do by hand), an identity.json or vault index it cannot read (kept, since they name the secret store items, so a later run can find them), a secret another identity's identity.json or turno's mcp.toml may use when that file cannot be read (kept), and a turno-browser-mcp started with the identity's id whose environment cannot be read (with its stop command). Agent config files are read with comments and trailing commas allowed, as Gemini CLI's settings.json allows comments, and a file that does not parse is skipped only when no quoted key in it names the identity's server. An agent file that cannot be read after the agent's `mcp remove` counts as failed, not deleted. Planning and the final check read a path with `lstat`, so a broken link is planned and checked and a path it cannot look at is not taken for gone. The final check keeps a process the plan could not tell apart when the process table cannot be read, and checks failed items again: one that is gone after all is listed as deleted. The help and the reference state the limits: vault credentials are found through the sites the vault index names, and session exports through the record kept since 0.9.0. The `--json` fields are unchanged; `unchecked` is a new field on items. diff --git a/apps/docs/content/docs/browser/moving-a-session.mdx b/apps/docs/content/docs/browser/moving-a-session.mdx index 9cd3c0b6..69081081 100644 --- a/apps/docs/content/docs/browser/moving-a-session.mdx +++ b/apps/docs/content/docs/browser/moving-a-session.mdx @@ -8,7 +8,7 @@ turno-browser export school --out school.session --expires 2d turno-browser import school.session --as school-laptop ``` -The export holds the identity's cookies, localStorage and IndexedDB, and its settings (identity.json), encrypted with a passphrase of 12 characters or more that you type (asked twice, and asked again when it is too short or the two differ), or the first line of stdin. It is refused after its expiry (7 days by default, at most 90). It never holds vault credentials. Importing into an identity that exists replaces its session and settings, so turno asks first (or needs `--yes`). +The export holds the identity's cookies, localStorage and IndexedDB, and its settings (identity.json), encrypted with a passphrase of 12 characters or more that you type (asked twice, and asked again when it is too short or the two differ), or the first line of stdin. It is refused after its expiry (7 days by default, at most 90). It never holds vault credentials. Importing into an identity that exists replaces its session and settings, so turno asks first (or needs `--yes`). The file's key derivation settings are part of what is checked: import takes the scrypt parameters export writes (`r` 8, `p` 1, `N` at most 2^17, about 128 MiB of memory) and refuses a file that asks for more before it derives a key. Import restores the settings (locale, languages, region, time zone, humanize level, resources, sharing and the rest) and keeps the importing identity's own creation date. Before anything changes, it lists each setting it changes with the old and the new value, and what it leaves out and why; `--dry-run` shows the same list. It leaves out what belongs to the machine and keeps this identity's value of each: `browser` (a path, or a browser installed on the other machine), `attach` (a Chrome running there), `keychain` (each machine's secret store), and an `engine` other than `chrome` (the session is a Chrome profile). It also leaves out a setting that uses secret store items (`keychain:` references, such as a proxy password or a model key), since the export never holds them: store them on the new machine, then set it again. A value this release does not accept is left out alone. The identity keeps its own `policy` unless you pass `--take-policy`, and an export without a policy never removes it. A change to `lastClick`, `proxy`, `act`, `live`, `record`, `policy` or `sharing`, or `sidePanel` or `notify` set to `false` or `cursor` to `"off"`, sends data elsewhere, lets the agent do more or shows you less of what it does, so turno shows those values whole, with the same warnings as `set`, and asks first (or needs `--yes`) even for a new identity. An export made by an older release holds no settings; it still imports, and the identity keeps its own. The settings apply from the next start of the identity's server. diff --git a/apps/docs/content/docs/browser/reference/cli.mdx b/apps/docs/content/docs/browser/reference/cli.mdx index bc7fe603..b34af87b 100644 --- a/apps/docs/content/docs/browser/reference/cli.mdx +++ b/apps/docs/content/docs/browser/reference/cli.mdx @@ -382,6 +382,14 @@ Deletes everything turno-browser keeps for the identity, after it shows the list Afterwards it checks that nothing is left. Exit codes: 0 all gone, 1 something is left (--json lists it under left, with the step that removes it), 2 no terminal and no --yes. +What it cannot check counts as left, with "unchecked": true under --json: an agent config file +it cannot read or parse, a registration in a file the agent's command does not change, an +unreadable identity.json or vault index (kept, as they name the secret store items), a secret +another identity's identity.json or turno's mcp.toml may use when that file cannot be read +(kept), and a turno-browser-mcp for the id whose environment cannot be read. Its limits: vault credentials are +found by the sites the vault index names (the secret store has no listing by prefix), and +session exports by the record kept since 0.9.0 (one made before, or moved since, is not found). + Examples: $ turno-browser remove school --dry-run $ turno-browser remove school --yes --json diff --git a/apps/docs/content/docs/reference/cli/browser.mdx b/apps/docs/content/docs/reference/cli/browser.mdx index 7a6178ad..35431bcb 100644 --- a/apps/docs/content/docs/reference/cli/browser.mdx +++ b/apps/docs/content/docs/reference/cli/browser.mdx @@ -715,6 +715,14 @@ Deletes everything turno-browser keeps for the identity, after it shows the list Afterwards it checks that nothing is left. Exit codes: 0 all gone, 1 something is left (--json lists it under left, with the step that removes it), 2 no terminal and no --yes. +What it cannot check counts as left, with "unchecked": true under --json: an agent config file +it cannot read or parse, a registration in a file the agent's command does not change, an +unreadable identity.json or vault index (kept, as they name the secret store items), a secret +another identity's identity.json or turno's mcp.toml may use when that file cannot be read +(kept), and a turno-browser-mcp for the id whose environment cannot be read. Its limits: vault credentials are +found by the sites the vault index names (the secret store has no listing by prefix), and +session exports by the record kept since 0.9.0 (one made before, or moved since, is not found). + Examples: $ turno browser remove school --dry-run $ turno browser remove school --yes --json diff --git a/packages/browser/src/agent-mcp.ts b/packages/browser/src/agent-mcp.ts index d6d75212..2ac7d30a 100644 --- a/packages/browser/src/agent-mcp.ts +++ b/packages/browser/src/agent-mcp.ts @@ -145,6 +145,42 @@ function tomlValue(text: string): unknown { } } +/** + * JSON with comments and trailing commas taken out, outside strings. Gemini CLI reads its + * settings.json with comments (strip-json-comments); Claude Code, Cursor and GitHub Copilot CLI + * write plain JSON. Reading leniently only finds more of what is in a file, never less. + */ +function parseJsonc(text: string): unknown { + let out = ""; + for (let i = 0; i < text.length; i++) { + const ch = text[i]!; + if (ch === '"') { + const from = i; + for (i++; i < text.length && text[i] !== '"'; i++) if (text[i] === "\\") i++; + out += text.slice(from, i + 1); + } else if (ch === "/" && text[i + 1] === "/") { + while (i + 1 < text.length && text[i + 1] !== "\n") i++; + } else if (ch === "/" && text[i + 1] === "*") { + const close = text.indexOf("*/", i + 2); + i = close < 0 ? text.length : close + 1; + out += " "; + } else if (ch === ",") { + // A comma followed only by blanks and comments before } or ] is a trailing one. + let j = i + 1; + for (;;) { + while (j < text.length && /\s/.test(text[j]!)) j++; + if (text.startsWith("//", j)) while (j < text.length && text[j] !== "\n") j++; + else if (text.startsWith("/*", j)) { + const close = text.indexOf("*/", j + 2); + j = close < 0 ? text.length : close + 2; + } else break; + } + if (text[j] !== "}" && text[j] !== "]") out += ch; + } else out += ch; + } + return JSON.parse(out); +} + /** The `[mcp_servers.]` tables of a Codex config.toml, with their command and args. */ function tomlServers(text: string): Map> { const out = new Map>(); @@ -164,10 +200,12 @@ function tomlServers(text: string): Map> { return out; } -/** Every MCP server in the agent's config file (read only). A missing file has none. */ -export function agentServers(agent: McpAgent, env: NodeJS.ProcessEnv): AgentServers { +/** + * Every MCP server in the agent's config file (read only), or in `file` when given (a + * registration recorded in another file). A missing file has none. + */ +export function agentServers(agent: McpAgent, env: NodeJS.ProcessEnv, file = AGENTS[agent].file(env)): AgentServers { const info = AGENTS[agent]; - const file = info.file(env); let text: string; try { text = readFileSync(file, "utf8"); @@ -191,7 +229,7 @@ export function agentServers(agent: McpAgent, env: NodeJS.ProcessEnv): AgentServ return { agent, file, entries: [...tomlServers(text)].map(([server, e]) => entry(server, e)) }; let v: unknown; try { - v = JSON.parse(text); + v = parseJsonc(text); } catch (err) { return { agent, file, entries: [], error: `not valid JSON (${(err as Error).message})` }; } diff --git a/packages/browser/src/cli/commands.ts b/packages/browser/src/cli/commands.ts index a499d4a9..359c8433 100644 --- a/packages/browser/src/cli/commands.ts +++ b/packages/browser/src/cli/commands.ts @@ -264,7 +264,15 @@ const REMOVE_DETAILS = `Deletes everything turno-browser keeps for the identity, --yes deletes without asking; without a terminal it is required. --dry-run shows the list. Afterwards it checks that nothing is left. Exit codes: 0 all gone, 1 something is left (--json -lists it under left, with the step that removes it), 2 no terminal and no --yes.`; +lists it under left, with the step that removes it), 2 no terminal and no --yes. + +What it cannot check counts as left, with "unchecked": true under --json: an agent config file +it cannot read or parse, a registration in a file the agent's command does not change, an +unreadable identity.json or vault index (kept, as they name the secret store items), a secret +another identity's identity.json or turno's mcp.toml may use when that file cannot be read +(kept), and a turno-browser-mcp for the id whose environment cannot be read. Its limits: vault credentials are +found by the sites the vault index names (the secret store has no listing by prefix), and +session exports by the record kept since 0.9.0 (one made before, or moved since, is not found).`; /** One line about a removal item, for people. */ function describeItem(item: RemovalItem, env: NodeJS.ProcessEnv): string { @@ -313,7 +321,11 @@ async function remove(c: Ctx, args: string[], io: Io): Promise { const out = [`This deletes browser identity "${id}":`]; for (const item of plan.items) out.push(` ${describeItem(item, env)}`); for (const item of plan.left) - out.push(` ${describeItem(item, env)}: cannot be removed here (${item.reason}); by hand: ${item.command ?? ""}`); + out.push( + item.unchecked + ? ` could not check ${describeItem(item, env)}: ${item.reason}; by hand: ${item.command ?? ""}` + : ` ${describeItem(item, env)}: cannot be removed here (${item.reason}); by hand: ${item.command ?? ""}`, + ); for (const item of plan.kept) out.push(` kept: ${describeItem(item, env)}, ${item.reason}`); return out; }; @@ -350,7 +362,7 @@ async function remove(c: Ctx, args: string[], io: Io): Promise { io.out( s.note( "warn", - `left ${describeItem(item, env)}: ${item.reason}${item.command ? `; to remove it: ${item.command}` : ""}`, + `${item.unchecked ? "not checked" : "left"} ${describeItem(item, env)}: ${item.reason}${item.command ? `; to remove it: ${item.command}` : ""}`, ), ); if (report.complete) io.out(`removed identity "${id}" and its saved browser data`); diff --git a/packages/browser/src/destroy.ts b/packages/browser/src/destroy.ts index 82ee49b4..03bb0611 100644 --- a/packages/browser/src/destroy.ts +++ b/packages/browser/src/destroy.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { existsSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { lstatSync, readFileSync, readdirSync, rmSync } from "node:fs"; import { join } from "node:path"; import { browserPaths, turnoRoots } from "turno-core/paths"; import { type ProcTable, killTree, pidAlive, readProcTable, signalProcess } from "turno-core/process"; @@ -46,6 +46,16 @@ import { vaultItem, vaultPath } from "./vault.js"; * recordings, the Camoufox profile), saved flows, and the session exports it wrote that are * still where it wrote them. * + * What it cannot check is said, never skipped: an agent config file it cannot read or parse, a + * registration in a file the agent's own command does not change, a vault index or identity.json + * it cannot read (kept, since it names the secret store items), and a turno-browser-mcp for the + * identity whose environment cannot be read. Each goes under `left` with `unchecked`, so the + * removal is not complete and the exit code says so. + * + * Its limits: the vault's credentials are found by the sites the index names, since the secret + * store offers no listing by prefix, so a credential whose site no index names is not found; and + * the session exports are the ones recorded (since 0.9.0) and still where they were written. + * * Chrome's own cookie key ("Chrome Safe Storage", used with identity.json `"keychain": "system"`) * is shared by every Chrome profile of the machine, the person's own Chrome included, so it is * kept and said so. @@ -72,6 +82,8 @@ export interface RemovalItem { reason?: string; /** What went wrong while deleting it. */ error?: string; + /** In `left`: it may or may not be there, because remove could not read what would tell. */ + unchecked?: boolean; } export interface RemovalPlan { @@ -123,6 +135,28 @@ function readText(file: string): string | undefined { } } +/** Why a file that is there cannot be read; undefined when it reads or is not there. */ +function readError(file: string): string | undefined { + try { + readFileSync(file); + return undefined; + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + return code === "ENOENT" || code === "ENOTDIR" ? undefined : (err as Error).message; + } +} + +/** True unless the path is gone: an error other than "not there" counts as still there. */ +function pathRemains(path: string): boolean { + try { + lstatSync(path); + return true; + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + return code !== "ENOENT" && code !== "ENOTDIR"; + } +} + /** Which setting names each reference, for the plan: proxy.password, act.key... */ function refOwners(text: string): Map { const out = new Map(); @@ -176,9 +210,13 @@ function leftoverTemps(id: string, env: NodeJS.ProcessEnv): string[] { } } -/** Who else references a secret store item: other identities, and turno's mcp.toml. */ -function otherUsers(item: string, id: string, env: NodeJS.ProcessEnv): string[] { +/** + * Who else references a secret store item: other identities, and turno's mcp.toml; `unknown` + * names the ones whose file is there and cannot be read. + */ +function otherUsers(item: string, id: string, env: NodeJS.ProcessEnv): { users: string[]; unknown: string[] } { const users: string[] = []; + const unknown: string[] = []; const root = browserPaths(env).identitiesDir; let others: string[] = []; try { @@ -190,13 +228,17 @@ function otherUsers(item: string, id: string, env: NodeJS.ProcessEnv): string[] /* no identities */ } for (const other of others.sort()) { - const text = readText(identitySettingsPath(other, env)); - if (text && keychainRefs(text).includes(item)) users.push(`identity "${other}"`); + const file = identitySettingsPath(other, env); + const text = readText(file); + if (text === undefined && readError(file) !== undefined) unknown.push(`identity "${other}"`); + else if (text && keychainRefs(text).includes(item)) users.push(`identity "${other}"`); } - const manifest = readText(join(turnoRoots(env).config, "mcp.toml")); - if (manifest && new RegExp(`keychain:${escapeRegExp(item)}(?![A-Za-z0-9._/-])`).test(manifest)) + const manifestFile = join(turnoRoots(env).config, "mcp.toml"); + const manifest = readText(manifestFile); + if (manifest === undefined && readError(manifestFile) !== undefined) unknown.push("turno's mcp.toml"); + else if (manifest && new RegExp(`keychain:${escapeRegExp(item)}(?![A-Za-z0-9._/-])`).test(manifest)) users.push("turno's mcp.toml"); - return users; + return { users, unknown }; } /** @@ -233,12 +275,17 @@ function processDataEnv(pid: number): NodeJS.ProcessEnv | undefined { /** * The turno-browser-mcp processes started for the identity: `--identity ` on their command * line, and turno's data folder where this one's is (the same id under another HOME or - * TURNO_DATA_DIR is another identity). A process whose variables cannot be read is not counted. + * TURNO_DATA_DIR is another identity). One whose variables cannot be read is `unknown`. */ -function identityServers(table: ProcTable | undefined, id: string, env: NodeJS.ProcessEnv): number[] { - if (!table) return []; +function identityServers( + table: ProcTable | undefined, + id: string, + env: NodeJS.ProcessEnv, +): { pids: number[]; unknown: number[] } { + const pids: number[] = []; + const unknown: number[] = []; + if (!table) return { pids, unknown }; const ours = browserPaths(env).identitiesDir; - const out: number[] = []; for (const p of table.values()) { if (p.pid === process.pid) continue; // Windows separates with backslashes and quotes a path with a space in it. @@ -253,13 +300,31 @@ function identityServers(table: ProcTable | undefined, id: string, env: NodeJS.P const given = at >= 0 ? words[at + 1] : words.find((w) => w.startsWith("--identity="))?.slice(11); if (given !== id && given !== `browser:${id}`) continue; const theirs = processDataEnv(p.pid); - if (theirs && browserPaths(theirs).identitiesDir === ours) out.push(p.pid); + if (!theirs) unknown.push(p.pid); + else if (browserPaths(theirs).identitiesDir === ours) pids.push(p.pid); } - return out; + return { pids, unknown }; +} + +/** A turno-browser-mcp for the identity's id whose data folder cannot be told: left to the person. */ +function unknownServer(pid: number): RemovalItem { + return { + kind: "process", + what: "turno-browser-mcp started with the identity's id", + pid, + command: stopCommand(pid), + reason: + "its environment cannot be read, so it is not known whether it uses this identity or one of the same id in another data folder", + unchecked: true, + }; } /** The processes of the identity that run now: what has to stop before anything is deleted. */ -function processItems(id: string, env: NodeJS.ProcessEnv, table: ProcTable | undefined): RemovalItem[] { +function processItems( + id: string, + env: NodeJS.ProcessEnv, + table: ProcTable | undefined, +): { items: RemovalItem[]; left: RemovalItem[] } { const out: RemovalItem[] = []; const seen = new Set(); const add = (pid: number, what: string) => { @@ -281,11 +346,16 @@ function processItems(id: string, env: NodeJS.ProcessEnv, table: ProcTable | und } const chrome = findProfileChrome(identityDir(id, env), table ? { table } : {}); if (chrome) add(chrome.pid, "Chrome on the profile"); - for (const pid of identityServers(table, id, env)) add(pid, "turno-browser-mcp started for the identity"); - return out; + const servers = identityServers(table, id, env); + for (const pid of servers.pids) add(pid, "turno-browser-mcp started for the identity"); + return { items: out, left: servers.unknown.filter((pid) => !seen.has(pid)).map(unknownServer) }; } -/** Each agent with the identity's server: recorded by init, or found in the agent's file. */ +/** + * Each agent with the identity's server: recorded by init, or found in the agent's file. A file + * that cannot be read or parsed, unless its text shows the server's name is not in it, and an + * entry in a file the agent's own command does not change, go under `left`. + */ function mcpItems(id: string, env: NodeJS.ProcessEnv): { items: RemovalItem[]; left: RemovalItem[] } { const server = serverName(id); const files = new Map(); @@ -298,21 +368,33 @@ function mcpItems(id: string, env: NodeJS.ProcessEnv): { items: RemovalItem[]; l const left: RemovalItem[] = []; for (const { agent, file } of files.values()) { const info = AGENTS[agent]; - const agentEnv = envForFile(agent, file, env); - if (!agentEnv) continue; + const base: RemovalItem = { kind: "mcp", what: `${info.label}'s MCP server ${server}`, agent, server, file }; + const byHand = `delete the "${server}" entry from ${file}`; + const found = agentServers(agent, env, file); + if (found.error) { + // Only text that cannot hold the entry rules it out: no key quoted with the server's name. + const text = readText(file); + if (text !== undefined && !new RegExp(`["']${escapeRegExp(server)}["']`).test(text)) continue; + left.push({ + ...base, + command: byHand, + reason: `could not read the file: ${found.error}; so it is not known whether it has the entry`, + unchecked: true, + }); + continue; + } // Only turno's own entry: a server of the same name that runs something else is not removed. - if (!agentServers(agent, agentEnv).entries.some((e) => e.server === server && isTurnoEntry(e))) continue; + if (!found.entries.some((e) => e.server === server && isTurnoEntry(e))) continue; const words = info.remove?.(server); - const prefix = agentEnv === env || !info.homeEnv ? "" : `${info.homeEnv}=${agentEnv[info.homeEnv]} `; - const item: RemovalItem = { - kind: "mcp", - what: `${info.label}'s MCP server ${server}`, - agent, - server, - file, - command: words ? `${prefix}${words.join(" ")}` : `delete the "${server}" entry from ${file}`, - }; + const agentEnv = envForFile(agent, file, env); + const prefix = !agentEnv || agentEnv === env || !info.homeEnv ? "" : `${info.homeEnv}=${agentEnv[info.homeEnv]} `; + const item: RemovalItem = { ...base, command: words && agentEnv ? `${prefix}${words.join(" ")}` : byHand }; if (!words) left.push({ ...item, reason: `${info.label} has no command that removes it` }); + else if (!agentEnv) + left.push({ + ...item, + reason: `${info.label}'s own command changes ${info.file(env)}, not this file, which init recorded`, + }); else if (!agentReachable(agent, env)) left.push({ ...item, reason: `${info.program} is not on the PATH, so ${info.label} cannot be reached` }); else items.push(item); @@ -328,11 +410,33 @@ export async function planRemoval(id: string, options: RemovalOptions): Promise< const kept: RemovalItem[] = []; const left: RemovalItem[] = []; - items.push(...processItems(id, env, table)); + const processes = processItems(id, env, table); + items.push(...processes.items); + left.push(...processes.left); const mcp = mcpItems(id, env); items.push(...mcp.items); left.push(...mcp.left); + // The files that name the secret store items: one that is there and cannot be read is kept, + // since deleting it would lose the names of the items it would have let remove find. + const unreadable = new Set(); + for (const [path, what, refs] of [ + [identitySettingsPath(id, env), "identity.json", "the keychain: items it references"], + [vaultPath(id, env), "vault index", "the vault's credentials, named after its sites,"], + ] as const) { + const error = readError(path); + if (error === undefined) continue; + unreadable.add(path); + left.push({ + kind: "path", + what, + path, + reason: `it could not be read (${error}), so ${refs} could not be found; it is kept`, + command: `make ${path} readable, then run remove again`, + unchecked: true, + }); + } + // Secret store items: the vault's, then the ones identity.json references. const settingsText = readText(identitySettingsPath(id, env)); const owners = settingsText ? refOwners(settingsText) : new Map(); @@ -343,8 +447,17 @@ export async function planRemoval(id: string, options: RemovalOptions): Promise< })); for (const item of settingsText ? keychainRefs(settingsText) : []) { const what = `${owners.get(item) ?? "identity.json"} secret`; - const users = otherUsers(item, id, env); + const { users, unknown } = otherUsers(item, id, env); if (users.length) kept.push({ kind: "keychain", what, item, reason: `also used by ${users.join(", ")}` }); + else if (unknown.length) + left.push({ + kind: "keychain", + what, + item, + reason: `kept: could not check whether ${unknown.join(" or ")} uses it (its file cannot be read)`, + command: `${names().browser} secret remove ${item}, once nothing else uses it`, + unchecked: true, + }); else secrets.push({ kind: "keychain", what, item }); } if (secrets.length) { @@ -383,9 +496,12 @@ export async function planRemoval(id: string, options: RemovalOptions): Promise< ...leftoverTemps(id, env).map((f): [string, string] => [f, "half-written settings file"]), ...exportFiles(id, env).map((f): [string, string] => [f, "session export"]), ]; - for (const [path, what] of paths) if (existsSync(path)) items.push({ kind: "path", what, path }); + for (const [path, what] of paths) + if (!unreadable.has(path) && pathRemains(path)) items.push({ kind: "path", what, path }); - return { id, exists: items.length > 0 || left.length > 0, items, kept, left }; + // An agent file or a process remove cannot read is not a sign that the identity exists. + const found = left.some((l) => !l.unchecked || l.kind === "path"); + return { id, exists: items.length > 0 || found, items, kept, left }; } async function waitGone(pid: number, ms: number): Promise { @@ -431,6 +547,8 @@ export async function runRemoval(plan: RemovalPlan, options: RemovalOptions): Pr const failed: RemovalItem[] = []; const left: RemovalItem[] = [...plan.left]; const kept = [...plan.kept]; + // A process remove could not tell apart is looked for again by the check, which sees it if it still runs. + const unknownPlanned = (l: RemovalItem) => l.kind === "process" && l.unchecked; const done = (item: RemovalItem) => deleted.push(item); const broke = (item: RemovalItem, err: unknown) => failed.push({ ...item, error: (err as Error).message ?? String(err) }); @@ -456,12 +574,15 @@ export async function runRemoval(plan: RemovalPlan, options: RemovalOptions): Pr const agentEnv = envForFile(agent, item.file!, env) ?? env; const [bin, ...rest] = AGENTS[agent].remove!(item.server!); const result = await options.exec(bin!, rest, agentEnv); - const still = agentServers(agent, agentEnv).entries.some((e) => e.server === item.server); + const after = agentServers(agent, env, item.file!); + const still = after.error !== undefined || after.entries.some((e) => e.server === item.server); if (!still) done(item); else failed.push({ ...item, - error: `${bin} ended with code ${result.code}${result.output ? `: ${lastLine(result.output)}` : ""}`, + error: `${bin} ended with code ${result.code}${result.output ? `: ${lastLine(result.output)}` : ""}${ + after.error ? `; then the file could not be read (${after.error})` : "" + }`, }); } @@ -488,17 +609,18 @@ export async function runRemoval(plan: RemovalPlan, options: RemovalOptions): Pr } } - // The check: anything that is still there moves from deleted to left. + // The check: anything that is still there moves from deleted to left, and a failed item that + // is gone after all moves to deleted. What cannot be read counts as still there. const table = (options.procTable ?? readProcTable)(); const remains = async (item: RemovalItem): Promise => { switch (item.kind) { case "path": - return existsSync(item.path!); + return pathRemains(item.path!); case "process": return pidAlive(item.pid!); case "mcp": { - const agentEnv = envForFile(item.agent!, item.file!, env) ?? env; - return agentServers(item.agent!, agentEnv).entries.some((e) => e.server === item.server); + const found = agentServers(item.agent!, env, item.file!); + return found.error !== undefined || found.entries.some((e) => e.server === item.server); } case "keychain": return store ? await store.has(item.item!).catch(() => true) : true; @@ -509,21 +631,38 @@ export async function runRemoval(plan: RemovalPlan, options: RemovalOptions): Pr if (await remains(item)) left.push({ ...item, reason: "still there after it was deleted" }); else verified.push(item); } + const stillFailed: RemovalItem[] = []; + for (const item of failed) { + if (await remains(item)) stillFailed.push(item); + else { + const { error: _error, ...gone } = item; + verified.push(gone); + } + } const profile = identityDir(id, env); const servers = identityServers(table, id, env); + // Without a process table the check cannot look again, so what the plan could not tell apart stays. + const checked = table ? left.filter((l) => !unknownPlanned(l)) : [...left]; const stray = table ? [...table.values()].filter( - (p) => p.pid !== process.pid && (usesProfile(p.command, profile) || servers.includes(p.pid)), + (p) => p.pid !== process.pid && (usesProfile(p.command, profile) || servers.pids.includes(p.pid)), ) : []; for (const p of stray) - if (!left.some((l) => l.pid === p.pid)) - left.push({ + if (!checked.some((l) => l.pid === p.pid)) + checked.push({ kind: "process", what: "a process of the identity", pid: p.pid, reason: "still running", command: stopCommand(p.pid), }); - return { deleted: verified, failed, left, kept, complete: failed.length === 0 && left.length === 0 }; + for (const pid of servers.unknown) if (!checked.some((l) => l.pid === pid)) checked.push(unknownServer(pid)); + return { + deleted: verified, + failed: stillFailed, + left: checked, + kept, + complete: stillFailed.length === 0 && checked.length === 0, + }; } diff --git a/packages/browser/src/sealed.ts b/packages/browser/src/sealed.ts index dd91e115..b5791da3 100644 --- a/packages/browser/src/sealed.ts +++ b/packages/browser/src/sealed.ts @@ -19,8 +19,12 @@ export const SEALED_FORMAT = "turno-browser-session"; const VERSION = 1; /** scrypt cost: 2^17 (about 128 MiB and a few hundred ms), the OWASP floor for scrypt. */ const KDF = { N: 2 ** 17, r: 8, p: 1 } as const; -/** Ceiling on what a file may ask for, so a crafted header cannot make import allocate gigabytes. */ -const MAX_N = 2 ** 20; +/** + * What a file may ask for: export has always written exactly KDF, so import takes r and p as + * export writes them and N up to export's. The key derivation runs before the tag can be checked, + * so these bounds are what keeps import's cost at most export's (128 * N * r bytes, 128 MiB). + */ +const MAX_N = KDF.N; /** The shortest passphrase an export takes; the export prompt says it up front. */ export const MIN_PASSPHRASE = 12; @@ -91,11 +95,12 @@ function parseEnvelope(text: string): Envelope { if ( !isObject(kdf) || kdf.name !== "scrypt" || - ![kdf.N, kdf.r, kdf.p].every((n) => Number.isInteger(n) && (n as number) > 0) || + !Number.isInteger(kdf.N) || + (kdf.N as number) < 2 || (kdf.N as number) > MAX_N || ((kdf.N as number) & ((kdf.N as number) - 1)) !== 0 || - (kdf.r as number) > 32 || - (kdf.p as number) > 16 || + kdf.r !== KDF.r || + kdf.p !== KDF.p || typeof kdf.salt !== "string" || v.cipher !== "aes-256-gcm" || typeof v.iv !== "string" || diff --git a/packages/browser/test/cli/remove.test.ts b/packages/browser/test/cli/remove.test.ts index 4c207af3..2a937b8a 100644 --- a/packages/browser/test/cli/remove.test.ts +++ b/packages/browser/test/cli/remove.test.ts @@ -1,12 +1,14 @@ import { type ChildProcess, spawn } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; import { hostname } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { pidAlive, readProcTable } from "turno-core/process"; +import type { SecretStore } from "turno-core/secrets"; import { type ExecCommand, readRegistrations, recordRegistration } from "../../src/agent-mcp.js"; import type { BrowserFunctions } from "../../src/api.js"; import { backgroundStatePath } from "../../src/background-state.js"; +import { planRemoval, runRemoval } from "../../src/destroy.js"; import { identityDir, identityStateDir } from "../../src/ids.js"; import { runtimeLockPath } from "../../src/runtime-lock.js"; import { recordExportFile } from "../../src/session-export.js"; @@ -322,4 +324,129 @@ describe("turno-browser remove", () => { expect(seen).toEqual([profile.CLAUDE_CONFIG_DIR]); expect(JSON.parse(readFileSync(join(profile.CLAUDE_CONFIG_DIR!, ".claude.json"), "utf8")).mcpServers).toEqual({}); }); + it("reads agent files with comments, and lists one it cannot parse as not checked unless no key names the server", async () => { + api.addIdentity("school", sb.env); + writeFileSync(join(sb.home, ".claude.json"), '{"mcpServers":{"browser-school":{"command":"turno-browser-mcp",'); + mkdirSync(join(sb.home, ".gemini")); + writeFileSync(join(sb.home, ".gemini", "settings.json"), '{ "mcpServers": { "browser-school-laptop": {'); + mkdirSync(join(sb.home, ".cursor")); + writeFileSync( + join(sb.home, ".cursor", "mcp.json"), + '{\n // turno\n "mcpServers": { "browser-school": { "command": "turno-browser-mcp", /* id */ "args": ["--identity", "school",], }, },\n}', + ); + const dry = fakeIo(sb.env); + expect(await cli(api).run("remove", ["school", "--dry-run"], dry)).toBe(0); + expect(slashes(dry.lines.join("\n"))).toContain( + "could not check Claude Code's MCP server browser-school in ~/.claude.json: could not read the file: not valid JSON", + ); + const io = fakeIo(sb.env); + expect(await cli(api).run("remove", ["school", "--yes", "--json"], io)).toBe(1); + const r = json(io); + expect(r.complete).toBe(false); + expect(r.left).toEqual([ + expect.objectContaining({ + kind: "mcp", + agent: "claude-code", + unchecked: true, + reason: expect.stringMatching(/JSON/), + }), + expect.objectContaining({ kind: "mcp", agent: "cursor", reason: "Cursor has no command that removes it" }), + ]); + expect(r.left[1].unchecked).toBeUndefined(); + expect(api.identityExists("school", sb.env)).toBe(false); + }); + + it("lists a recorded registration in a file the agent's own command does not change", async () => { + api.addIdentity("school", sb.env); + const file = join(sb.home, "elsewhere", ".gemini", "settings.json"); + mkdirSync(join(file, ".."), { recursive: true }); + writeFileSync( + file, + JSON.stringify({ + mcpServers: { "browser-school": { command: "turno-browser-mcp", args: ["--identity", "school"] } }, + }), + ); + recordRegistration("school", sb.env, { + agent: "gemini", + server: "browser-school", + file, + at: "2026-11-20T00:00:00.000Z", + }); + const agent = fakeAgentCli(sb.env); + const io = fakeIo(sb.env); + expect(await cli(api, { exec: agent.exec }).run("remove", ["school", "--yes", "--json"], io)).toBe(1); + expect(agent.calls).toEqual([]); + expect(json(io).left).toEqual([ + expect.objectContaining({ + kind: "mcp", + agent: "gemini", + command: `delete the "browser-school" entry from ${file}`, + reason: expect.stringMatching(/own command changes/), + }), + ]); + }); + + it("lists a turno-browser-mcp for the id whose environment it cannot read, in the plan and the check", async () => { + api.addIdentity("school", sb.env); + const pid = 4_194_000; // no such process, so its environment cannot be read + const table = () => + new Map([[pid, { pid, ppid: 1, pgid: pid, command: "node /opt/turno-browser-mcp --identity school" }]]); + const options = { env: sb.env, exec: fakeAgentCli(sb.env).exec, procTable: table, store: null }; + const plan = await planRemoval("school", options); + expect(plan.left).toEqual([expect.objectContaining({ kind: "process", pid, unchecked: true })]); + const report = await runRemoval(plan, options); + expect(report.complete).toBe(false); + expect(report.left).toEqual([ + expect.objectContaining({ kind: "process", pid, unchecked: true, command: expect.stringContaining(String(pid)) }), + ]); + }); + + // Permission bits that make a file unreadable: POSIX, and not as root. + it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "keeps an identity.json and a vault index it cannot read, with the secrets they name, until a later run can read them", + async () => { + await school(); + const files = [identitySettingsPath("school", sb.env), vaultPath("school", sb.env)]; + for (const f of files) chmodSync(f, 0o000); + const io = fakeIo(sb.env); + expect(await cli(api).run("remove", ["school", "--yes", "--json"], io)).toBe(1); + expect(json(io).left).toEqual([ + expect.objectContaining({ kind: "path", what: "identity.json", unchecked: true }), + expect.objectContaining({ kind: "path", what: "vault index", unchecked: true }), + ]); + for (const f of files) expect(existsSync(f)).toBe(true); + expect(store.services()).toEqual(expect.arrayContaining(["school-proxy", "turno-browser/vault/school/mail"])); + for (const f of files) chmodSync(f, 0o600); + expect(await cli(api).run("remove", ["school", "--yes", "--json"], fakeIo(sb.env))).toBe(0); + expect(store.services()).toEqual([]); + }, + ); + + it("checks a failed item again, and lists it as deleted when it is gone after all", async () => { + const gone: SecretStore = { + kind: "keychain", + label: "test store", + get: async () => undefined, + has: async () => false, + set: async () => {}, + remove: async () => { + throw new Error("the store timed out"); + }, + }; + const plan = { + id: "school", + exists: true, + items: [{ kind: "keychain" as const, what: "x secret", item: "x" }], + kept: [], + left: [], + }; + const report = await runRemoval(plan, { + env: sb.env, + exec: fakeAgentCli(sb.env).exec, + procTable: () => new Map(), + store: gone, + }); + expect(report).toMatchObject({ complete: true, failed: [], left: [], deleted: [{ kind: "keychain", item: "x" }] }); + expect(report.deleted[0]!.error).toBeUndefined(); + }); }); diff --git a/packages/browser/test/sealed.test.ts b/packages/browser/test/sealed.test.ts index 841525e2..fa8d8db7 100644 --- a/packages/browser/test/sealed.test.ts +++ b/packages/browser/test/sealed.test.ts @@ -51,4 +51,19 @@ describe("the sealed session envelope (scrypt + AES-256-GCM)", () => { await expect(unseal(JSON.stringify({ ...env, kdf: { ...env.kdf, N: 2 ** 24 } }), PASS)).rejects.toThrow(/damaged/); await expect(unseal(JSON.stringify({ ...env, kdf: { ...env.kdf, N: 1000 } }), PASS)).rejects.toThrow(/damaged/); }, 30_000); + + it("takes no cost parameters past what export writes, and refuses them before deriving a key", async () => { + // A header written by hand: no export (and no key derivation) is needed to refuse it. + const env = { + format: SEALED_FORMAT, + version: 1, + kdf: { name: "scrypt", N: 2 ** 17, r: 8, p: 1, salt: "AAAAAAAAAAAAAAAAAAAAAA==" }, + cipher: "aes-256-gcm", + iv: "AAAAAAAAAAAAAAAA", + data: "", + tag: "AAAAAAAAAAAAAAAAAAAAAA==", + }; + for (const kdf of [{ N: 2 ** 18 }, { N: 2 ** 20 }, { r: 16 }, { r: 32 }, { r: 4 }, { p: 2 }, { N: 1 }]) + await expect(unseal(JSON.stringify({ ...env, kdf: { ...env.kdf, ...kdf } }), PASS)).rejects.toThrow(/damaged/); + }); });