diff --git a/.changeset/export-import-and-remove-checks.md b/.changeset/export-import-and-remove-checks.md new file mode 100644 index 00000000..bbfaa04e --- /dev/null +++ b/.changeset/export-import-and-remove-checks.md @@ -0,0 +1,9 @@ +--- +"turno-browser": patch +--- + +Session export and import: import refuses a file whose IV is not 12 bytes or whose tag is not 16 bytes as damaged, before it derives a key, and opens the file with a 16-byte tag only, so a tag cut short no longer passes on Node 22 to 25. Any other problem while decrypting gives the one "wrong passphrase, or the file was changed" error. One `import` run derives the key once instead of twice. `export --force` writes a new file with mode 600 in place of the old one, so a replaced export no longer keeps the old file's mode, and a failed write leaves no temporary file. When the record of exports cannot be read, export keeps it as it is and says the new file is not in it (init does the same for its record of registrations). Import's help states the header check. + +`remove`: more of what it cannot check is listed under `left` with `"unchecked": true` instead of being passed over: a registrations record (`agents.json`) or an exports record that cannot be read or parsed (each kept, with the state folder that holds it), a half-written copy of the vault index or a recorded export that cannot be read (kept), an identities folder that cannot be listed (a secret another identity may use is then kept), a Codex config.toml that names the server in a form it does not read, and a registration recorded in a file the agent's own command does not change. Codex servers written with dotted keys or as inline tables are now found and removed, and one whose command or args cannot be read (an array over several lines) is listed as unchecked. When a process does not stop, the final check still runs. Under `--json`, and in the lines for people, the home folder is written as `~` in `command`, `reason` and `error` too. The help states the exit codes as they are (2 also for `--json` without `--yes`; 1 also for a no and an identity that does not exist) and that on Windows a turno-browser-mcp for the id other than the background server and the one that holds the identity is listed, not stopped. + +Flow recording: a named recording now reads the vault's values when it starts, as 0.14.3 said; the identity's own recording (`record.flows`) reads them before its first typed step is kept. A read of the secret store that fails (a locked store, a cancelled prompt) is no longer kept as "no values" until the recording ends: while it stands, no typed value keeps its default, and the store is asked again at the first step 30 seconds later, so a vault value typed by hand is known once the store answers. A machine without a secret store is not asked again. The docs and the `--record-screenshots` help now say what the code does: no screenshot is taken of a page a vault sign-in or a secret went into, until that page navigates away. diff --git a/SECURITY.md b/SECURITY.md index 1b81b46e..45350762 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -53,7 +53,7 @@ is what it stores, what it trusts, and what it does not protect against. | Master gateway token | `~/.local/state/turno/mcpd.token` | file mode 600; used by turno only, for mcpd's own endpoints; never written into an agent config | | Per-profile gateway tokens | nowhere for Claude Code and Codex (their configs run `turno mcp headers`, which derives the token when the agent connects); `~/.local/state/turno/mcpd-tokens/.token` for Copilot CLI and Cursor CLI profiles and for agents set up by hand from `turno mcp config` | file mode 600; each one holds that profile's own token, derived from the master token | | Browser identities | `~/.local/share/turno/browser/` | live cookies of the sites you signed into: treat as credentials. By default Chrome encrypts them with a fixed public key (`--use-mock-keychain`), so anyone who can read the folder can read them; `"keychain": "system"` in identity.json uses the OS keychain's key instead, so a copy of the folder (a backup, a synced disk) does not hand over the sessions; changing it signs the identity out, so export first and import after | -| Session exports (`turno browser export`) | the file you name, mode 600 | cookies, localStorage and IndexedDB of an identity, encrypted with your passphrase (scrypt, AES-256-GCM) and refused on import after their expiry (default 7 days); never the vault | +| Session exports (`turno-browser export`, or `turno browser export`) | the file you name, mode 600 (a file replaced with `--force` too) | cookies, localStorage and IndexedDB of an identity, and its settings (identity.json, which names secret store items but never holds them), encrypted with your passphrase (scrypt, AES-256-GCM); import refuses one past its expiry (default 7 days) and, before it derives a key, one whose header asks for other key derivation settings, IV or tag length than export writes; never the vault | | Browser vault credentials (username, password, TOTP secret per site) | the same secret store (on Windows, DPAPI-encrypted files in `%LOCALAPPDATA%\turno\secrets`), items `turno-browser/vault//` | never in a file, a log, a tool result or a snapshot; the index `.vault.json` (mode 600) holds only site names, origins and the submit policy | | Chrome profiles for `turno open` | `~/.local/share/turno/chrome/` | the claude.ai session of each profile | | Installed MCP servers | `~/.local/share/turno/servers//` | folders mode 700; exact versions, no install scripts unless `--allow-scripts` | diff --git a/apps/docs/components/browser-page/copy.ts b/apps/docs/components/browser-page/copy.ts index 4f75cdd4..f9f76175 100644 --- a/apps/docs/components/browser-page/copy.ts +++ b/apps/docs/components/browser-page/copy.ts @@ -423,7 +423,7 @@ const en: BrowserCopy = { id: "record", state: "default", title: "Recordings", - text: "Every session's actions saved as a flow, and a screenshot after each action, under a 200MB cap and never of a page that shows a vault value. Playwright traces are opt in: while tracing, Chrome loads no image or frame of another site.", + text: "Every session's actions saved as a flow, and a screenshot after each action, under a 200MB cap and none of a page a vault sign-in or a secret went into, until it navigates. Playwright traces are opt in: while tracing, Chrome loads no image or frame of another site.", run: CMD.record, more: { text: "Recordings and traces", href: `${DOCS}/flows#recordings-and-traces` }, }, diff --git a/apps/docs/content/docs/browser/flows.mdx b/apps/docs/content/docs/browser/flows.mdx index 89901f14..a69164f9 100644 --- a/apps/docs/content/docs/browser/flows.mdx +++ b/apps/docs/content/docs/browser/flows.mdx @@ -64,9 +64,12 @@ A refusal costs the agent one look at the page; a wrong element costs a wrong ac Text typed into a field becomes a parameter, with what was typed as its default. A sensitive one keeps no value: a password field, a one-time code or card field, a field named like `password`, `otp`, `pin`, `token` or `cardnumber`, a vault value typed by hand, or any parameter the agent -lists in `sensitive` when it stops. The vault's values are read before the first typed step is -kept and held in memory only; a vault user name counts as the whole typed value (case aside), a -vault password also inside other text when it has at least 4 characters. A vault user name typed +lists in `sensitive` when it stops. The vault's values are read when a named recording starts +(the identity's own recording reads them before its first typed step is kept) and held in +memory only. When the secret store cannot be read, no typed value keeps its default, and the +store is asked again 30 seconds later, at the next step. A vault user name counts as the whole +typed value (case aside), a vault password also inside other text when it has at least 4 +characters. A vault user name typed outside a sign-in only loses its default. A vault sign-in is a `browser_login` step with the site name only. A `browser_navigate` step keeps its address without query string or fragment (they can carry tokens). diff --git a/apps/docs/content/docs/browser/identities.mdx b/apps/docs/content/docs/browser/identities.mdx index ccb0162a..7231a25a 100644 --- a/apps/docs/content/docs/browser/identities.mdx +++ b/apps/docs/content/docs/browser/identities.mdx @@ -77,7 +77,7 @@ Every feature has a default that turno works out when Chrome starts, from what i | [Live view](/docs/browser/live-view) | on | every server with an identity; it opens only when you ask | | [Side panel](/docs/browser/live-view#the-side-panel-in-the-agents-window) | on | a Chrome with a window that turno starts, with the live view on; not headless, in attach mode or with another engine | | [Flows](/docs/browser/flows) | recorded | always | -| [Screenshots](/docs/browser/flows#recordings-and-traces) | after each action, under a disk cap | never of a page that shows a vault value; not in attach or read mode | +| [Screenshots](/docs/browser/flows#recordings-and-traces) | after each action, under a disk cap | none of a page a vault sign-in or a secret went into, until it navigates away; not in attach or read mode | | [Traces](/docs/browser/flows#recordings-and-traces) | off (not yet available: while tracing, Chrome loads no image or frame of another site) | `--record-traces true` turns them on | | `vision`, `pdf`, `devtools`, `network` tools | listed | `devtools` not in attach mode or with `record.traces: true`; `network` not in attach mode or when the policy turns it off | | [`storage` tools](/docs/browser/vault#cookies-and-stored-tokens) | listed, session values masked | not in attach mode or when the policy turns it off | diff --git a/apps/docs/content/docs/browser/moving-a-session.mdx b/apps/docs/content/docs/browser/moving-a-session.mdx index 69081081..712b6f13 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 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. +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 header is part of what is checked: import takes the scrypt parameters `r` 8 and `p` 1 as export writes them, `N` a power of 2 up to export's 2^17 (about 128 MiB of memory), a 12-byte IV and a 16-byte tag, and refuses any other header 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/policy.mdx b/apps/docs/content/docs/browser/policy.mdx index e9c1c99b..784fb2f1 100644 --- a/apps/docs/content/docs/browser/policy.mdx +++ b/apps/docs/content/docs/browser/policy.mdx @@ -102,6 +102,9 @@ A `browser_batch` is checked as a whole before any of its steps runs, and before ## What a policy does not cover -- **An agent that can write files, with a shell or a file-editing tool,** can change `identity.json` (by hand, or with `turno-browser set` from a shell) like any program of yours. The policy binds the MCP server; give such an agent no shell and no write access to turno's config folder, or run it as another user. +- **An agent that can write files, with a shell or a file-editing tool,** can change `identity.json` (by hand, or with `turno-browser set` from a shell) like any program of yours. The policy binds the MCP server. Give such an agent no shell and no write access to what decides how the server starts, or run it as another user: + - turno's data folder, which holds `identity.json` (`~/.local/share/turno/browser/identities/.json`, on Windows `%LOCALAPPDATA%\turno\data\browser\identities\.json`); + - turno's config folder, whose `mcp.toml` starts the server when turno runs it (`~/.config/turno/`, on Windows `%APPDATA%\turno\`); + - the agent's own MCP config, whose entry starts the server and can set `TURNO_DATA_DIR` to another data folder. - **Signing in by hand** (`turno-browser login`) opens the profile for you, without the policy. - **An older turno-browser** refuses an `identity.json` with a policy (format 13) instead of ignoring it. diff --git a/apps/docs/content/docs/browser/reference/cli.mdx b/apps/docs/content/docs/browser/reference/cli.mdx index b34af87b..58ca72a7 100644 --- a/apps/docs/content/docs/browser/reference/cli.mdx +++ b/apps/docs/content/docs/browser/reference/cli.mdx @@ -270,8 +270,9 @@ What turno-browser records for this identity (turno-browser record): --record-traces a Playwright trace of each browser session (turno-browser traces); off by default: while tracing, Chrome loads no image or frame of another site - --record-screenshots a screenshot after each action (on by default, never of a - page that shows a vault value; not with attach or Lightpanda) + --record-screenshots a screenshot after each action (on by default; none of a page + a vault sign-in or a secret went into, until it navigates; not + with attach or Lightpanda) --record-max-size cap of the traces and screenshots, "10MB" to "10GB" (default 200MB) Vault sign-ins and passwords never reach a flow, a trace or a screenshot. @@ -370,7 +371,9 @@ Usage: Deletes everything turno-browser keeps for the identity, after it shows the list and asks: - it stops the identity's background server, a Chrome on its profile and the - turno-browser-mcp processes started for it (nothing is deleted while one still runs) + turno-browser-mcp processes started for it (nothing is deleted while one still runs); on + Windows, where it cannot read a process's environment, a turno-browser-mcp for the id other + than the background server and the one that holds the identity is listed, not stopped - it takes the identity's MCP server out of each agent that has it, with the agent's own command (claude mcp remove --scope user browser-, codex mcp remove ...) - it deletes the vault's credentials and the keychain: items identity.json references from @@ -378,15 +381,20 @@ Deletes everything turno-browser keeps for the identity, after it shows the list - it deletes the profile, identity.json, the vault index, the state folder, saved flows and the session exports it wrote ---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. +--yes deletes without asking; it is required without a terminal and with --json. --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), the answer was no, or the +identity does not exist; 2 no --yes without a terminal or with --json. 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 +it cannot read or parse, or a Codex config.toml that names the server in a form it does not +read; a registration in a file the agent's command does not change; a file that names what +else to remove and cannot be read (identity.json, the vault index or a half-written copy of it, +and the records of agent registrations and session exports, kept with the state folder); an +identities folder it cannot list; a recorded session export it cannot read (kept); a secret +another identity or turno's mcp.toml may use when its file cannot be read or the identities +folder cannot be listed (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). @@ -596,6 +604,10 @@ lets the agent do more or shows you less of it (lastClick, proxy, act, live, rec sharing, and sidePanel or notify false, cursor off), even for a new identity; those values are shown whole. +Before it derives the key from the passphrase it checks the file's header: scrypt r 8 and p 1, +as export writes them, N a power of 2 up to export's 2^17, a 12-byte IV and a 16-byte tag. A +file that asks for anything else is refused as damaged. + Examples: $ turno-browser import school.session --as school-laptop ``` diff --git a/apps/docs/content/docs/browser/what-leaves-your-machine.mdx b/apps/docs/content/docs/browser/what-leaves-your-machine.mdx index e3644bf5..e145c1e6 100644 --- a/apps/docs/content/docs/browser/what-leaves-your-machine.mdx +++ b/apps/docs/content/docs/browser/what-leaves-your-machine.mdx @@ -43,7 +43,7 @@ Cookies and stored tokens the agent reads through the storage tools never leave: ## What never leaves -- **Recordings**: flows, traces and screenshots stay in the identity's state folder. Flows and screenshots are on by default, under a disk cap, never of a page that shows a vault value; traces are off unless identity.json turns them on. +- **Recordings**: flows, traces and screenshots stay in the identity's state folder. Flows and screenshots are on by default, under a disk cap, and no screenshot is taken of a page a vault sign-in or a secret went into, until it navigates away; traces are off unless identity.json turns them on. - **The reputation log**: challenges and captcha attempts are written locally, with the host name, never a token or a key. - **Session exports**: `turno-browser export` writes an encrypted file on your disk; it goes wherever you copy it, and never holds vault credentials. - **The live view**, on by default for a server with an identity, is served on `127.0.0.1` only, on a random port, to a browser that holds a random per-process cookie. The background server listens on a Unix socket in a folder only your user can enter, or on `127.0.0.1` with a per-server token. See [Security and privacy](/docs/security#the-browser-package). diff --git a/apps/docs/content/docs/reference/cli/browser.mdx b/apps/docs/content/docs/reference/cli/browser.mdx index 35431bcb..c696a570 100644 --- a/apps/docs/content/docs/reference/cli/browser.mdx +++ b/apps/docs/content/docs/reference/cli/browser.mdx @@ -333,8 +333,9 @@ What turno-browser records for this identity (turno browser record): --record-traces a Playwright trace of each browser session (turno browser traces); off by default: while tracing, Chrome loads no image or frame of another site - --record-screenshots a screenshot after each action (on by default, never of a - page that shows a vault value; not with attach or Lightpanda) + --record-screenshots a screenshot after each action (on by default; none of a page + a vault sign-in or a secret went into, until it navigates; not + with attach or Lightpanda) --record-max-size cap of the traces and screenshots, "10MB" to "10GB" (default 200MB) Vault sign-ins and passwords never reach a flow, a trace or a screenshot. @@ -690,6 +691,10 @@ lets the agent do more or shows you less of it (lastClick, proxy, act, live, rec sharing, and sidePanel or notify false, cursor off), even for a new identity; those values are shown whole. +Before it derives the key from the passphrase it checks the file's header: scrypt r 8 and p 1, +as export writes them, N a power of 2 up to export's 2^17, a 12-byte IV and a 16-byte tag. A +file that asks for anything else is refused as damaged. + Examples: $ turno browser import school.session --as school-laptop ``` @@ -703,7 +708,9 @@ Usage: Deletes everything turno-browser keeps for the identity, after it shows the list and asks: - it stops the identity's background server, a Chrome on its profile and the - turno-browser-mcp processes started for it (nothing is deleted while one still runs) + turno-browser-mcp processes started for it (nothing is deleted while one still runs); on + Windows, where it cannot read a process's environment, a turno-browser-mcp for the id other + than the background server and the one that holds the identity is listed, not stopped - it takes the identity's MCP server out of each agent that has it, with the agent's own command (claude mcp remove --scope user browser-, codex mcp remove ...) - it deletes the vault's credentials and the keychain: items identity.json references from @@ -711,15 +718,20 @@ Deletes everything turno-browser keeps for the identity, after it shows the list - it deletes the profile, identity.json, the vault index, the state folder, saved flows and the session exports it wrote ---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. +--yes deletes without asking; it is required without a terminal and with --json. --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), the answer was no, or the +identity does not exist; 2 no --yes without a terminal or with --json. 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 +it cannot read or parse, or a Codex config.toml that names the server in a form it does not +read; a registration in a file the agent's command does not change; a file that names what +else to remove and cannot be read (identity.json, the vault index or a half-written copy of it, +and the records of agent registrations and session exports, kept with the state folder); an +identities folder it cannot list; a recorded session export it cannot read (kept); a secret +another identity or turno's mcp.toml may use when its file cannot be read or the identities +folder cannot be listed (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). diff --git a/apps/docs/content/docs/reference/cli/identity.mdx b/apps/docs/content/docs/reference/cli/identity.mdx index 49859e88..a1faeb22 100644 --- a/apps/docs/content/docs/reference/cli/identity.mdx +++ b/apps/docs/content/docs/reference/cli/identity.mdx @@ -231,8 +231,9 @@ What turno-browser records for this identity (turno browser record): --record-traces a Playwright trace of each browser session (turno browser traces); off by default: while tracing, Chrome loads no image or frame of another site - --record-screenshots a screenshot after each action (on by default, never of a - page that shows a vault value; not with attach or Lightpanda) + --record-screenshots a screenshot after each action (on by default; none of a page + a vault sign-in or a secret went into, until it navigates; not + with attach or Lightpanda) --record-max-size cap of the traces and screenshots, "10MB" to "10GB" (default 200MB) Vault sign-ins and passwords never reach a flow, a trace or a screenshot. diff --git a/packages/browser/README.md b/packages/browser/README.md index 729c231f..62bd4bb0 100644 --- a/packages/browser/README.md +++ b/packages/browser/README.md @@ -79,7 +79,7 @@ and where it came from: | [Side panel](https://turno.wimo.dev/docs/browser/live-view#the-side-panel-in-the-agents-window) | in a Chrome with a window that turno starts, Chrome's side panel shows what the agent does next to the page: its steps, Pause and Hand back, and a card when it waits for you. A small extension with the `sidePanel` permission only (`--side-panel false` turns it off) | | [Live view and take-over](https://turno.wimo.dev/docs/browser/live-view) | `turno-browser live ` opens a panel on 127.0.0.1 to watch from another window: the agent's tab, with each kind of action drawn in its own color, next to a timeline of its steps. Click or type on it, or in the agent's Chrome, and the agent waits; the browser goes back to it 5 seconds after your last input, and it is told what changed | | [Several agents, one browser](https://turno.wimo.dev/docs/browser/sharing) | several agent sessions in one identity's Chrome, each in its own tabs (`--sharing session` for one at a time) | -| [Recordings](https://turno.wimo.dev/docs/browser/flows#recordings-and-traces) | every session as a flow and a screenshot per action, under a 200MB cap and never of a page with a vault value | +| [Recordings](https://turno.wimo.dev/docs/browser/flows#recordings-and-traces) | every session as a flow and a screenshot per action, under a 200MB cap and none of a page a vault sign-in or a secret went into, until it navigates | | [Human-like input](https://turno.wimo.dev/docs/browser/actions#human-like-input) | the pointer moves along a curve and text is typed key by key; by default the level follows the page | | [Cookies and storage](https://turno.wimo.dev/docs/browser/vault#cookies-and-stored-tokens) | the `storage` tools, with the values that keep you signed in read as `[masked]` | | [The agent cursor](https://turno.wimo.dev/docs/browser/agent-cursor) | when you can see the browser, Chrome itself highlights the element the agent acts on and shows its clicks, with nothing in the page; `cursor: on` draws a named cursor and a badge in the page | diff --git a/packages/browser/src/agent-mcp.ts b/packages/browser/src/agent-mcp.ts index 2ac7d30a..bfb400dc 100644 --- a/packages/browser/src/agent-mcp.ts +++ b/packages/browser/src/agent-mcp.ts @@ -111,6 +111,8 @@ export interface McpEntry { file: string; command?: string; args?: string[]; + /** A value that tells what it runs could not be read (a Codex array over several lines). */ + unread?: true; } /** The servers of one agent's config file; `error` when the file exists and cannot be read. */ @@ -181,23 +183,108 @@ function parseJsonc(text: string): unknown { return JSON.parse(out); } -/** The `[mcp_servers.]` tables of a Codex config.toml, with their command and args. */ -function tomlServers(text: string): Map> { +/** `text` cut at each `sep` that is outside quotes, brackets and braces. */ +function splitTop(text: string, sep: string): string[] { + const parts: string[] = []; + let depth = 0; + let quote: string | undefined; + let from = 0; + for (let i = 0; i < text.length; i++) { + const ch = text[i]!; + if (quote) { + if (ch === "\\" && quote === '"') i++; + else if (ch === quote) quote = undefined; + } else if (ch === '"' || ch === "'") quote = ch; + else if (ch === "[" || ch === "{") depth++; + else if (ch === "]" || ch === "}") depth--; + else if (ch === sep && depth === 0) { + parts.push(text.slice(from, i)); + from = i + 1; + } + } + parts.push(text.slice(from)); + return parts; +} + +/** The parts of a TOML key (`a."b.c".'d'` is a, b.c and d); undefined when it is not one. */ +function tomlKey(text: string): string[] | undefined { + const keys: string[] = []; + for (const part of splitTop(text, ".")) { + const t = part.trim(); + if (/^[A-Za-z0-9_-]+$/.test(t)) keys.push(t); + else if (/^'[^']*'$/.test(t)) keys.push(t.slice(1, -1)); + else if (/^"(?:[^"\\]|\\.)*"$/.test(t)) { + try { + keys.push(JSON.parse(t) as string); + } catch { + return undefined; + } + } else return undefined; + } + return keys; +} + +/** A `key = value` line split at its first `=` outside quotes. */ +function tomlPair(line: string): [string, string] | undefined { + const [key, ...rest] = splitTop(line, "="); + return rest.length ? [key!, rest.join("=")] : undefined; +} + +/** The keys of an inline table (`{ command = "x", args = ["y"] }`); undefined when it is not one on this line. */ +function tomlInline(text: string): Record | undefined { + const out: Record = {}; + const t = text.trim(); + if (!t.startsWith("{") || !t.endsWith("}")) return undefined; + for (const part of splitTop(t.slice(1, -1), ",")) { + const pair = tomlPair(part); + const key = pair && tomlKey(pair[0]); + if (key?.length === 1) out[key[0]!] = tomlValue(pair![1]); + } + return out; +} + +/** The keys of a server whose value tells what it runs. */ +const RUN_KEYS = ["command", "args"]; + +/** + * The servers under `mcp_servers` in a Codex config.toml, with their command and args, in each + * way TOML lets a file write them: `[mcp_servers.]` tables, dotted keys + * (`mcp_servers..command = ...`, or `.command` under `[mcp_servers]`) and inline + * tables (` = { command = ... }`). A `command` or `args` value not read here (an array + * spread over several lines) marks its server in `unread`. + */ +function tomlServers(text: string): { servers: Map>; unread: Set } { const out = new Map>(); - let current: Record | undefined; + const unread = new Set(); + const server = (name: string) => out.get(name) ?? out.set(name, {}).get(name)!; + let table: string[] | undefined = []; for (const raw of text.split(/\r?\n/)) { const line = raw.trim(); + if (!line || line.startsWith("#")) continue; if (line.startsWith("[")) { - const m = /^\[\s*mcp_servers\.(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))\s*\]$/.exec(line); - current = m ? {} : undefined; - if (m) out.set((m[1] ?? m[2] ?? m[3])!, current!); + // An array of tables ([[...]]) holds no server. + const m = /^\[([^[].*)\]\s*(?:#.*)?$/.exec(line); + table = m ? tomlKey(m[1]!) : undefined; + if (table?.[0] === "mcp_servers" && table.length >= 2) server(table[1]!); continue; } - if (!current) continue; - const kv = /^([A-Za-z0-9_-]+)\s*=\s*(.+)$/.exec(line); - if (kv) current[kv[1]!] = tomlValue(kv[2]!.replace(/\s+#.*$/, "")); + const pair = tomlPair(line); + const key = pair && tomlKey(pair[0]); + if (!table || !key) continue; + const path = [...table, ...key]; + if (path[0] !== "mcp_servers" || path.length < 2) continue; + const value = pair![1].replace(/\s+#.*$/, ""); + const entry = server(path[1]!); + if (path.length === 2) { + const inline = tomlInline(value); + if (!inline || RUN_KEYS.some((k) => k in inline && inline[k] === undefined)) unread.add(path[1]!); + Object.assign(entry, inline); + } else if (path.length === 3) { + entry[path[2]!] = tomlValue(value); + if (RUN_KEYS.includes(path[2]!) && entry[path[2]!] === undefined) unread.add(path[1]!); + } } - return out; + return { servers: out, unread }; } /** @@ -225,8 +312,17 @@ export function agentServers(agent: McpAgent, env: NodeJS.ProcessEnv, file = AGE ...(args ? { args } : {}), }; }; - if (info.format === "toml") - return { agent, file, entries: [...tomlServers(text)].map(([server, e]) => entry(server, e)) }; + if (info.format === "toml") { + const { servers, unread } = tomlServers(text); + return { + agent, + file, + entries: [...servers].map(([server, e]) => ({ + ...entry(server, e), + ...(unread.has(server) ? { unread: true as const } : {}), + })), + }; + } let v: unknown; try { v = parseJsonc(text); @@ -302,28 +398,56 @@ function registrationsPath(id: string, env: NodeJS.ProcessEnv): string { return join(identityStateDir(id, env), "agents.json"); } -/** The registrations recorded for the identity, oldest first; none when the file is missing or unreadable. */ -export function readRegistrations(id: string, env: NodeJS.ProcessEnv): Registration[] { +/** + * The registrations recorded for the identity, oldest first, and the record's file. `error` says + * why a record that is there could not be read or parsed; it then has none. + */ +export function registrationRecord( + id: string, + env: NodeJS.ProcessEnv, +): { file: string; registrations: Registration[]; error?: string } { + const file = registrationsPath(id, env); + let text: string; try { - const v = JSON.parse(readFileSync(registrationsPath(id, env), "utf8")) as unknown; - if (!isObject(v) || !Array.isArray(v.registrations)) return []; - return v.registrations.filter( - (r): r is Registration => - isObject(r) && - (MCP_AGENTS as readonly unknown[]).includes(r.agent) && - typeof r.server === "string" && - typeof r.file === "string" && - typeof r.at === "string", - ); - } catch { - return []; + text = readFileSync(file, "utf8"); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") return { file, registrations: [] }; + return { file, registrations: [], error: (err as Error).message }; } + let v: unknown; + try { + v = JSON.parse(text); + } catch (err) { + return { file, registrations: [], error: `not valid JSON (${(err as Error).message})` }; + } + if (!isObject(v) || !Array.isArray(v.registrations)) + return { file, registrations: [], error: "it has no list of registrations" }; + const registrations = v.registrations.filter( + (r): r is Registration => + isObject(r) && + (MCP_AGENTS as readonly unknown[]).includes(r.agent) && + typeof r.server === "string" && + typeof r.file === "string" && + typeof r.at === "string", + ); + return { file, registrations }; +} + +/** The registrations recorded for the identity, oldest first; none when the file is missing or unreadable. */ +export function readRegistrations(id: string, env: NodeJS.ProcessEnv): Registration[] { + return registrationRecord(id, env).registrations; } -/** Record that the agent has the identity's server (one record per agent and server). */ +/** + * Record that the agent has the identity's server (one record per agent and server). A record + * that is there and cannot be read is kept as it is (it names files remove needs): this throws. + */ export function recordRegistration(id: string, env: NodeJS.ProcessEnv, reg: Registration): void { - const kept = readRegistrations(id, env).filter((r) => !(r.agent === reg.agent && r.server === reg.server)); - const file = registrationsPath(id, env); + const record = registrationRecord(id, env); + if (record.error) throw new Error(`${record.file} could not be read (${record.error}); it was left as it is`); + const kept = record.registrations.filter((r) => !(r.agent === reg.agent && r.server === reg.server)); + const file = record.file; mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify({ version: 1, registrations: [...kept, reg] }, null, 2)}\n`, { mode: 0o600 }); diff --git a/packages/browser/src/cli/commands.ts b/packages/browser/src/cli/commands.ts index 359c8433..85155b44 100644 --- a/packages/browser/src/cli/commands.ts +++ b/packages/browser/src/cli/commands.ts @@ -17,7 +17,8 @@ import { str, style, } from "turno-core/cli"; -import { tildify } from "turno-core/paths"; +import { isAbsolute, parse } from "node:path"; +import { browserPaths, tildify } from "turno-core/paths"; import { execCommand } from "../agent-mcp.js"; import { type RemovalItem, type RemovalReport, planRemoval, runRemoval } from "../destroy.js"; import type { BrowserFunctions } from "../api.js"; @@ -250,11 +251,17 @@ new, and what it leaves out and why: It asks first (or needs --yes) when the identity exists, and when a change sends data elsewhere, lets the agent do more or shows you less of it (lastClick, proxy, act, live, record, policy, sharing, and sidePanel or notify false, cursor off), even for a new identity; those values are -shown whole.`; +shown whole. + +Before it derives the key from the passphrase it checks the file's header: scrypt r 8 and p 1, +as export writes them, N a power of 2 up to export's 2^17, a 12-byte IV and a 16-byte tag. A +file that asks for anything else is refused as damaged.`; const REMOVE_DETAILS = `Deletes everything turno-browser keeps for the identity, after it shows the list and asks: - it stops the identity's background server, a Chrome on its profile and the - turno-browser-mcp processes started for it (nothing is deleted while one still runs) + turno-browser-mcp processes started for it (nothing is deleted while one still runs); on + Windows, where it cannot read a process's environment, a turno-browser-mcp for the id other + than the background server and the one that holds the identity is listed, not stopped - it takes the identity's MCP server out of each agent that has it, with the agent's own command (claude mcp remove --scope user browser-, codex mcp remove ...) - it deletes the vault's credentials and the keychain: items identity.json references from @@ -262,18 +269,44 @@ const REMOVE_DETAILS = `Deletes everything turno-browser keeps for the identity, - it deletes the profile, identity.json, the vault index, the state folder, saved flows and the session exports it wrote ---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. +--yes deletes without asking; it is required without a terminal and with --json. --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), the answer was no, or the +identity does not exist; 2 no --yes without a terminal or with --json. 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 +it cannot read or parse, or a Codex config.toml that names the server in a form it does not +read; a registration in a file the agent's command does not change; a file that names what +else to remove and cannot be read (identity.json, the vault index or a half-written copy of it, +and the records of agent registrations and session exports, kept with the state folder); an +identities folder it cannot list; a recorded session export it cannot read (kept); a secret +another identity or turno's mcp.toml may use when its file cannot be read or the identities +folder cannot be listed (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).`; +/** `text` with the home folder written as ~ wherever a path in it starts with it. */ +function tildeIn(text: string, env: NodeJS.ProcessEnv): string { + const home = browserPaths(env).home.replace(/[\\/]+$/, ""); + if (!isAbsolute(home) || home === parse(home).root) return text; + const escaped = home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + // Only where the path goes on, or ends: /home/al is not the start of /home/alex. + return text.replace(new RegExp(`${escaped}(?=$|[\\\\/\\s"'),;:])`, "g"), "~"); +} + +/** The item as it is shown: paths, and the paths in its command, reason and error, with ~. */ +function shownItem(item: RemovalItem, env: NodeJS.ProcessEnv): RemovalItem { + return { + ...item, + ...(item.path ? { path: tildify(item.path, env) } : {}), + ...(item.file ? { file: tildify(item.file, env) } : {}), + ...(item.command ? { command: tildeIn(item.command, env) } : {}), + ...(item.reason ? { reason: tildeIn(item.reason, env) } : {}), + ...(item.error ? { error: tildeIn(item.error, env) } : {}), + }; +} + /** One line about a removal item, for people. */ function describeItem(item: RemovalItem, env: NodeJS.ProcessEnv): string { switch (item.kind) { @@ -290,11 +323,7 @@ function describeItem(item: RemovalItem, env: NodeJS.ProcessEnv): string { /** A removal item as `remove --json` prints it: paths with ~, nothing that is not set. */ function itemJson(item: RemovalItem, env: NodeJS.ProcessEnv): Record { - return { - ...item, - ...(item.path ? { path: tildify(item.path, env) } : {}), - ...(item.file ? { file: tildify(item.file, env) } : {}), - }; + return { ...shownItem(item, env) }; } async function remove(c: Ctx, args: string[], io: Io): Promise { @@ -320,13 +349,14 @@ async function remove(c: Ctx, args: string[], io: Io): Promise { const planLines = () => { const out = [`This deletes browser identity "${id}":`]; for (const item of plan.items) out.push(` ${describeItem(item, env)}`); - for (const item of plan.left) + for (const item of plan.left.map((i) => shownItem(i, env))) 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}`); + for (const item of plan.kept.map((i) => shownItem(i, env))) + out.push(` kept: ${describeItem(item, env)}, ${item.reason}`); return out; }; if (dry) { @@ -355,10 +385,11 @@ async function remove(c: Ctx, args: string[], io: Io): Promise { else { const s = style(io); for (const item of report.deleted) io.out(s.note("ok", `deleted ${describeItem(item, env)}`)); - for (const item of report.kept) io.out(s.note("info", `kept ${describeItem(item, env)}: ${item.reason}`)); - for (const item of report.failed) + const shown = (items: RemovalItem[]) => items.map((i) => shownItem(i, env)); + for (const item of shown(report.kept)) io.out(s.note("info", `kept ${describeItem(item, env)}: ${item.reason}`)); + for (const item of shown(report.failed)) io.out(s.note("err", `could not delete ${describeItem(item, env)}: ${item.error}`)); - for (const item of report.left) + for (const item of shown(report.left)) io.out( s.note( "warn", diff --git a/packages/browser/src/cli/identity.ts b/packages/browser/src/cli/identity.ts index 359a3a59..987275a5 100644 --- a/packages/browser/src/cli/identity.ts +++ b/packages/browser/src/cli/identity.ts @@ -947,8 +947,9 @@ What turno-browser records for this identity (${b} record): --record-traces a Playwright trace of each browser session (${b} traces); off by default: while tracing, Chrome loads no image or frame of another site - --record-screenshots a screenshot after each action (on by default, never of a - page that shows a vault value; not with attach or Lightpanda) + --record-screenshots a screenshot after each action (on by default; none of a page + a vault sign-in or a secret went into, until it navigates; not + with attach or Lightpanda) --record-max-size cap of the traces and screenshots, "10MB" to "10GB" (default 200MB) Vault sign-ins and passwords never reach a flow, a trace or a screenshot. diff --git a/packages/browser/src/cli/init.ts b/packages/browser/src/cli/init.ts index 223c58b5..464619b7 100644 --- a/packages/browser/src/cli/init.ts +++ b/packages/browser/src/cli/init.ts @@ -358,8 +358,9 @@ export async function init(c: Ctx, args: string[], io: Io, run: RunCommand = run file: info.file(io.env), at: new Date().toISOString(), }); - } catch { - /* only a hint for remove: it also reads the agent's own config */ + } catch (err) { + // Only a hint for remove, which also reads the agent's own config: say it, and go on. + io.err(`note: the registration was not recorded for remove: ${(err as Error).message}`); } }; const there = agent === "json" ? undefined : findEntry(agent, id, io.env); diff --git a/packages/browser/src/cli/session.ts b/packages/browser/src/cli/session.ts index a22c9c7c..dd976b22 100644 --- a/packages/browser/src/cli/session.ts +++ b/packages/browser/src/cli/session.ts @@ -1,7 +1,8 @@ -import { readFileSync, writeFileSync } from "node:fs"; +import { randomBytes } from "node:crypto"; +import { readFileSync, rmSync, writeFileSync } from "node:fs"; import { resolve } from "node:path"; import { DRY_RUN, type Io, bool, fail, needsAnswer, noInputReason, parseFlags, str, style } from "turno-core/cli"; -import { tildify } from "turno-core/paths"; +import { replaceFileSync, tildify } from "turno-core/paths"; import { MIN_PASSPHRASE } from "../sealed.js"; import { type SettingsPlan, importSettingsPlan, recordExportFile } from "../session-export.js"; import { optInNotes } from "./identity.js"; @@ -78,6 +79,26 @@ async function passphrase( return line; } +/** + * Write the export with mode 600. With `force` an existing file is replaced by a new one (a + * temporary file of its own name, renamed over it), so it never keeps the old file's mode; the + * temporary file is removed when anything fails. Without it, an existing file is refused (EEXIST). + */ +function writeSealed(file: string, sealed: string, force: boolean): void { + if (!force) { + writeFileSync(file, sealed, { mode: 0o600, flag: "wx" }); + return; + } + const tmp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`; + try { + writeFileSync(tmp, sealed, { mode: 0o600, flag: "wx" }); + replaceFileSync(tmp, file); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } +} + export async function exportSession(c: Ctx, args: string[], io: Io): Promise { const mod = c.api; const input = c.deps.input ?? terminalInput; @@ -93,16 +114,17 @@ export async function exportSession(c: Ctx, args: string[], io: Io): Promise { return out; } -/** The sites of the vault index, also from an index too broken to load: what its items are named after. */ -function vaultSites(id: string, env: NodeJS.ProcessEnv): string[] { - const files = [vaultPath(id, env), ...leftoverTemps(id, env).filter((f) => f.includes(".vault.json."))]; +/** + * The sites of the vault index and its half-written copies, also from an index too broken to + * load: what its items are named after. `unreadable` lists the copies that are there and cannot + * be read (the index itself is checked apart). + */ +function vaultSites(id: string, env: NodeJS.ProcessEnv): { sites: string[]; unreadable: [string, string][] } { + const files = [vaultPath(id, env), ...leftoverTemps(id, env).files.filter((f) => f.includes(".vault.json."))]; const sites = new Set(); + const unreadable: [string, string][] = []; for (const file of files) { const text = readText(file); - if (text === undefined) continue; + if (text === undefined) { + const error = readError(file); + if (error !== undefined && file !== vaultPath(id, env)) unreadable.push([file, error]); + continue; + } let parsed: unknown; try { parsed = JSON.parse(text); @@ -194,48 +215,55 @@ function vaultSites(id: string, env: NodeJS.ProcessEnv): string[] { : [...text.matchAll(/"([a-z0-9][a-z0-9._-]{0,62})"\s*:\s*\{\s*"origins"/g)].map((m) => m[1]!); for (const site of listed) if (/^[a-z0-9][a-z0-9._-]{0,62}$/.test(site)) sites.add(site); } - return [...sites].sort(); + return { sites: [...sites].sort(), unreadable }; } -/** Half-written `.json..tmp` and `.vault.json..tmp` files an interrupted write left. */ -function leftoverTemps(id: string, env: NodeJS.ProcessEnv): string[] { - const dir = browserPaths(env).identitiesDir; - const own = new RegExp(`^${escapeRegExp(id)}(\\.vault)?\\.json\\.\\d+\\.tmp$`); +/** The names in `dir`, none when it is not there; `error` when it is there and cannot be listed. */ +function listDir(dir: string): { names: string[]; error?: string } { try { - return readdirSync(dir) - .filter((f) => own.test(f)) - .map((f) => join(dir, f)); - } catch { - return []; + return { names: readdirSync(dir) }; + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + return code === "ENOENT" || code === "ENOTDIR" ? { names: [] } : { names: [], error: (err as Error).message }; } } +/** + * Half-written `.json..tmp` and `.vault.json..tmp` files an interrupted write + * left; `error` when the identities folder cannot be listed. + */ +function leftoverTemps(id: string, env: NodeJS.ProcessEnv): { files: string[]; error?: string } { + const dir = browserPaths(env).identitiesDir; + const own = new RegExp(`^${escapeRegExp(id)}(\\.vault)?\\.json\\.\\d+\\.tmp$`); + const { names: found, error } = listDir(dir); + return { files: found.filter((f) => own.test(f)).map((f) => join(dir, f)), ...(error ? { error } : {}) }; +} + /** * 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. + * names, each with why, the ones whose file is there and cannot be read, and other identities + * when their folder cannot be listed. */ 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 { - others = readdirSync(root) - .filter((f) => f.endsWith(".json") && !f.endsWith(".vault.json")) - .map((f) => f.slice(0, -".json".length)) - .filter((other) => other !== id && isValidIdentityId(other)); - } catch { - /* no identities */ - } + const listing = listDir(browserPaths(env).identitiesDir); + if (listing.error) unknown.push("another identity (the identities folder cannot be listed)"); + const others = listing.names + .filter((f) => f.endsWith(".json") && !f.endsWith(".vault.json")) + .map((f) => f.slice(0, -".json".length)) + .filter((other) => other !== id && isValidIdentityId(other)); for (const other of others.sort()) { const file = identitySettingsPath(other, env); const text = readText(file); - if (text === undefined && readError(file) !== undefined) unknown.push(`identity "${other}"`); + if (text === undefined && readError(file) !== undefined) + unknown.push(`identity "${other}" (its file cannot be read)`); else if (text && keychainRefs(text).includes(item)) users.push(`identity "${other}"`); } const manifestFile = join(turnoRoots(env).config, "mcp.toml"); const manifest = readText(manifestFile); - if (manifest === undefined && readError(manifestFile) !== undefined) unknown.push("turno's mcp.toml"); + if (manifest === undefined && readError(manifestFile) !== undefined) + unknown.push("turno's mcp.toml (it cannot be read)"); else if (manifest && new RegExp(`keychain:${escapeRegExp(item)}(?![A-Za-z0-9._/-])`).test(manifest)) users.push("turno's mcp.toml"); return { users, unknown }; @@ -359,7 +387,8 @@ function processItems( function mcpItems(id: string, env: NodeJS.ProcessEnv): { items: RemovalItem[]; left: RemovalItem[] } { const server = serverName(id); const files = new Map(); - for (const r of readRegistrations(id, env)) files.set(`${r.agent}\0${r.file}`, { agent: r.agent, file: r.file }); + for (const r of registrationRecord(id, env).registrations) + files.set(`${r.agent}\0${r.file}`, { agent: r.agent, file: r.file }); for (const agent of MCP_AGENTS) { const file = AGENTS[agent].file(env); files.set(`${agent}\0${file}`, { agent, file }); @@ -383,8 +412,30 @@ function mcpItems(id: string, env: NodeJS.ProcessEnv): { items: RemovalItem[]; l }); continue; } + if (!found.entries.some((e) => e.server === server)) { + // A config.toml names the server in a form not read here (an array over several lines, say). + const text = info.format === "toml" ? readText(file) : undefined; + if (text !== undefined && new RegExp(`(? e.server === server && isTurnoEntry(e))) continue; + if (!found.entries.some((e) => e.server === server && isTurnoEntry(e))) { + // What it runs could not be read, so it may be turno's. + if (found.entries.some((e) => e.server === server && e.unread)) + left.push({ + ...base, + command: byHand, + reason: `what ${server} runs could not be read; so it is not known whether it is turno's entry`, + unchecked: true, + }); + continue; + } const words = info.remove?.(server); const agentEnv = envForFile(agent, file, env); const prefix = !agentEnv || agentEnv === env || !info.homeEnv ? "" : `${info.homeEnv}=${agentEnv[info.homeEnv]} `; @@ -394,6 +445,7 @@ function mcpItems(id: string, env: NodeJS.ProcessEnv): { items: RemovalItem[]; l left.push({ ...item, reason: `${info.label}'s own command changes ${info.file(env)}, not this file, which init recorded`, + unchecked: true, }); else if (!agentReachable(agent, env)) left.push({ ...item, reason: `${info.program} is not on the PATH, so ${info.label} cannot be reached` }); @@ -417,30 +469,97 @@ export async function planRemoval(id: string, options: RemovalOptions): Promise< 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. + // The files that name what else to remove: one that is there and cannot be read is kept, + // since deleting it would lose the names of what it would have let remove find. The records in + // the state folder keep the state folder too. 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,"], + const state = identityStateDir(id, env); + const registrations = registrationRecord(id, env); + const exportsRecord = exportRecord(id, env); + const vault = vaultSites(id, env); + for (const [path, what, error, lost, keep] of [ + [ + identitySettingsPath(id, env), + "identity.json", + readError(identitySettingsPath(id, env)), + "the keychain: items it references could not be found; it is kept", + undefined, + ], + [ + vaultPath(id, env), + "vault index", + readError(vaultPath(id, env)), + "the vault's credentials, named after its sites, could not be found; it is kept", + undefined, + ], + ...vault.unreadable.map( + ([file, error]) => + [ + file, + "half-written vault index", + error, + "the vault's credentials it may name could not be found; it is kept", + undefined, + ] as const, + ), + [ + registrations.file, + "record of agent registrations (agents.json)", + registrations.error, + "the agent config files it names were not looked in; it is kept, with the state folder that holds it", + state, + ], + [ + exportsRecord.file, + "record of session exports (exports.json)", + exportsRecord.error, + "the session exports it names could not be found; it is kept, with the state folder that holds it", + state, + ], ] as const) { - const error = readError(path); if (error === undefined) continue; unreadable.add(path); + if (keep) unreadable.add(keep); left.push({ kind: "path", what, path, - reason: `it could not be read (${error}), so ${refs} could not be found; it is kept`, + reason: `it could not be read (${error}), so ${lost}`, command: `make ${path} readable, then run remove again`, unchecked: true, }); } + const exports = exportFiles(id, env); + for (const { file, error } of exports.unreadable) { + unreadable.add(file); + left.push({ + kind: "path", + what: "session export", + path: file, + reason: `it could not be read (${error}), so it is not known whether it still holds the session; it is kept`, + command: `delete ${file} if it is the export`, + unchecked: true, + }); + } + const temps = leftoverTemps(id, env); + const identities = browserPaths(env).identitiesDir; + // Not a sign that the identity exists: the folder holds every identity's files. + const unlisted: RemovalItem | undefined = temps.error + ? { + kind: "path", + what: "identities folder", + path: identities, + reason: `it could not be listed (${temps.error}), so half-written copies of identity.json and the vault index were not looked for`, + command: `make ${identities} readable, then run remove again`, + unchecked: true, + } + : undefined; + if (unlisted) left.push(unlisted); // 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(); - const secrets: RemovalItem[] = vaultSites(id, env).map((site) => ({ + const secrets: RemovalItem[] = vault.sites.map((site) => ({ kind: "keychain" as const, what: `vault credential of ${site}`, item: vaultItem(id, site), @@ -454,7 +573,7 @@ export async function planRemoval(id: string, options: RemovalOptions): Promise< kind: "keychain", what, item, - reason: `kept: could not check whether ${unknown.join(" or ")} uses it (its file cannot be read)`, + reason: `kept: could not check whether ${unknown.join(" or ")} uses it`, command: `${names().browser} secret remove ${item}, once nothing else uses it`, unchecked: true, }); @@ -493,14 +612,15 @@ export async function planRemoval(id: string, options: RemovalOptions): Promise< [vaultPath(id, env), "vault index"], [identityStateDir(id, env), "state folder (runtime state, recordings)"], [flowsDir(id, env), "saved flows"], - ...leftoverTemps(id, env).map((f): [string, string] => [f, "half-written settings file"]), - ...exportFiles(id, env).map((f): [string, string] => [f, "session export"]), + ...temps.files.map((f): [string, string] => [f, "half-written settings file"]), + ...exports.files.map((f): [string, string] => [f, "session export"]), ]; for (const [path, what] of paths) if (!unreadable.has(path) && pathRemains(path)) items.push({ kind: "path", what, path }); - // 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"); + // An agent file, a process or the identities folder remove cannot read is not a sign that the + // identity exists. + const found = left.some((l) => l !== unlisted && (!l.unchecked || l.kind === "path")); return { id, exists: items.length > 0 || found, items, kept, left }; } @@ -562,50 +682,51 @@ export async function runRemoval(plan: RemovalPlan, options: RemovalOptions): Pr broke(item, err); } } - if (failed.length) { + // When one did not stop, nothing else goes, and the check below still looks at what was done. + let store: SecretStore | null | undefined; + if (failed.length) for (const item of plan.items.filter((i) => i.kind !== "process")) left.push({ ...item, reason: "not removed: a process of the identity did not stop" }); - return { deleted, failed, left, kept, complete: false }; - } - - // 2. The agents' MCP entries, with each agent's own command. - for (const item of plan.items.filter((i) => i.kind === "mcp")) { - const agent = item.agent!; - 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 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)}` : ""}${ - after.error ? `; then the file could not be read (${after.error})` : "" - }`, - }); - } + else { + // 2. The agents' MCP entries, with each agent's own command. + for (const item of plan.items.filter((i) => i.kind === "mcp")) { + const agent = item.agent!; + 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 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)}` : ""}${ + after.error ? `; then the file could not be read (${after.error})` : "" + }`, + }); + } - // 3. Secret store items. - const secrets = plan.items.filter((i) => i.kind === "keychain"); - const store = secrets.length ? (options.store === undefined ? secretStore(env) : options.store) : undefined; - for (const item of secrets) { - try { - if (!store) throw new Error("no secret store"); - await store.remove(item.item!); - done(item); - } catch (err) { - broke(item, err); + // 3. Secret store items. + const secrets = plan.items.filter((i) => i.kind === "keychain"); + store = secrets.length ? (options.store === undefined ? secretStore(env) : options.store) : undefined; + for (const item of secrets) { + try { + if (!store) throw new Error("no secret store"); + await store.remove(item.item!); + done(item); + } catch (err) { + broke(item, err); + } } - } - // 4. Files. - for (const item of plan.items.filter((i) => i.kind === "path")) { - try { - rmSync(item.path!, { recursive: true, force: true }); - done(item); - } catch (err) { - broke(item, err); + // 4. Files. + for (const item of plan.items.filter((i) => i.kind === "path")) { + try { + rmSync(item.path!, { recursive: true, force: true }); + done(item); + } catch (err) { + broke(item, err); + } } } diff --git a/packages/browser/src/recorder.ts b/packages/browser/src/recorder.ts index 34e4d834..989aa40f 100644 --- a/packages/browser/src/recorder.ts +++ b/packages/browser/src/recorder.ts @@ -38,8 +38,10 @@ import { type ToolSchema, upstream } from "./upstream.js"; * - Typed text is always a parameter. It keeps what was typed as its default only when the * field is not sensitive: a password field, an `autocomplete` of a password, a one-time code * or a card, a field named like one (`password`, `otp`, `pin`, `cvv`, `token`, `cardnumber`...), - * or a value of the identity's vault. The vault's values are read from the secret store before - * the first typed step is kept, and held in memory only. The agent can mark more parameters + * or a value of the identity's vault. The vault's values are read from the secret store when a + * named recording starts (for the identity's own recording, before its first typed step is + * kept), and held in memory only. While a read that failed stands (30 seconds, then the next + * step reads again), every typed value keeps no default. The agent can mark more parameters * sensitive when it stops a named recording, which is held in memory until then. * - `browser_login` is recorded as its site name; the values are read from the vault again * at replay. @@ -329,14 +331,25 @@ export function plainUrl(url: string): string | undefined { } } +/** + * How long a read of the vault's values that failed (a locked store, a cancelled prompt) stands + * before the store is asked again: each read starts the store's program once per site. + */ +const VAULT_RETRY_MS = 30_000; + /** The recorder of one MCP session. */ export class FlowRecorder { private named: Draft | undefined; private overwrite = false; private auto: Draft | undefined; private suspended = 0; - /** The vault's values, read once per named recording (and once for the identity's own). */ + /** + * The vault's values, read once per named recording (and once for the identity's own). A read + * that failed stands for `VAULT_RETRY_MS`, then the next step reads again. + */ private vaultLoad: Promise | undefined; + /** When the read in `vaultLoad` was found to have failed. */ + private vaultFailedAt: number | undefined; /** The fingerprints of what the identity's actions worked on (`fingerprint.ts`). */ readonly cache: ActionCache; @@ -348,6 +361,8 @@ export class FlowRecorder { private readonly autoFlows: () => boolean, /** The secret store the vault's values are read from (tests pass one); default: this machine's. */ private readonly store?: SecretStore, + /** The clock that times a retry of a failed vault read (tests pass one). */ + private readonly now: () => number = Date.now, ) { this.cache = ActionCache.for(actionCachePath(identity.id, identity.env), redactor); } @@ -371,22 +386,55 @@ export class FlowRecorder { throw new FlowError(`flow "${name}" exists; pass overwrite: true to replace it, or pick another name`); this.named = new Draft(name, description); this.overwrite = overwrite; - // Read again for this recording: a site added to the vault since counts. - this.vaultLoad = undefined; + // Read again for this recording, from its start: a site added to the vault since counts. + void this.loadVault(); } - /** The vault's values; none when the vault is empty or its store cannot be read. */ + /** + * The vault's values; none when the vault is empty or the machine has no secret store. A read + * that could not reach the store (for every site or some) is not `complete`; it stands for + * `VAULT_RETRY_MS`, so the steps meanwhile (and the host's check in the same step) share it, + * then the next step reads again. + */ vaultValues(): Promise { - this.vaultLoad ??= vaultValues(this.identity.id, { + const stale = this.vaultFailedAt !== undefined && this.now() - this.vaultFailedAt >= VAULT_RETRY_MS; + return this.vaultLoad && !stale ? this.vaultLoad : this.loadVault(); + } + + private loadVault(): Promise { + this.vaultFailedAt = undefined; + const failed = () => { + if (this.vaultLoad === load) this.vaultFailedAt = this.now(); + }; + const load: Promise = vaultValues(this.identity.id, { env: this.identity.env, ...(this.store ? { store: this.store } : {}), - }).catch(() => VaultValues.none); - return this.vaultLoad; + }).then( + (values) => { + if (!values.complete) failed(); + return values; + }, + () => { + failed(); + return new VaultValues([], false); + }, + ); + this.vaultLoad = load; + return load; + } + + /** Forget the vault's values: the next recording reads them again. */ + private dropVault(): void { + this.vaultLoad = undefined; + this.vaultFailedAt = undefined; } - /** True when a typed value must keep no default: a vault value, or one the redactor hides. */ + /** + * True when a typed value must keep no default: a vault value, one the redactor hides, or any + * value while the vault's values could not all be read (it may be one of them). + */ private secretValue(value: string, vault: VaultValues): boolean { - return value !== "" && (vault.holds(value) || this.redactor.covers(value)); + return value !== "" && (vault.holds(value) || !vault.complete || this.redactor.covers(value)); } /** Saves the named flow, with `sensitive` parameters' values dropped. */ @@ -412,14 +460,14 @@ export class FlowRecorder { const file = writeFlow(this.identity.id, flow, this.identity.env); this.named = undefined; // Not held past the recording: the next one (or the identity's own) reads them again. - this.vaultLoad = undefined; + this.dropVault(); return { flow, file }; } cancel(): boolean { const had = this.named !== undefined; this.named = undefined; - this.vaultLoad = undefined; + this.dropVault(); return had; } diff --git a/packages/browser/src/sealed.ts b/packages/browser/src/sealed.ts index b5791da3..11996843 100644 --- a/packages/browser/src/sealed.ts +++ b/packages/browser/src/sealed.ts @@ -25,6 +25,9 @@ const KDF = { N: 2 ** 17, r: 8, p: 1 } as const; * 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 GCM IV and tag export writes; any other length is refused before a key is derived. */ +const IV_BYTES = 12; +const TAG_BYTES = 16; /** The shortest passphrase an export takes; the export prompt says it up front. */ export const MIN_PASSPHRASE = 12; @@ -70,7 +73,7 @@ export async function seal(payload: unknown, passphrase: string): Promise { const env = parseEnvelope(text); - const decipher = createDecipheriv("aes-256-gcm", await key(passphrase, env.kdf), Buffer.from(env.iv, "base64")); - decipher.setAAD(aad(env)); - decipher.setAuthTag(Buffer.from(env.tag, "base64")); + const derived = await key(passphrase, env.kdf); let plain: Buffer; try { + const decipher = createDecipheriv("aes-256-gcm", derived, Buffer.from(env.iv, "base64"), { + authTagLength: TAG_BYTES, + }); + decipher.setAAD(aad(env)); + decipher.setAuthTag(Buffer.from(env.tag, "base64")); plain = Buffer.concat([decipher.update(Buffer.from(env.data, "base64")), decipher.final()]); } catch { throw new SealError("wrong passphrase, or the file was changed"); diff --git a/packages/browser/src/session-export.ts b/packages/browser/src/session-export.ts index 4e16f0cb..320aeb31 100644 --- a/packages/browser/src/session-export.ts +++ b/packages/browser/src/session-export.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { replaceFileSync } from "turno-core/paths"; import type { BrowserContext } from "patchright-core"; @@ -243,17 +243,26 @@ function isPayload(v: unknown): v is Payload { return isObject(s) && Array.isArray(s.cookies) && Array.isArray(s.origins); } +function checkPayload(v: unknown, now: Date): Payload { + if (!isPayload(v)) throw new SealError("this session export is damaged (its content is not a session)"); + if (now.getTime() > Date.parse(v.expiresAt)) + throw new SealError(`this session export expired on ${v.expiresAt}; export it again`); + return v; +} + +/** What `readSessionExport` returned, with the text it read: `importSession` takes it only for that text. */ +const opened = new WeakMap(); + /** Decrypt and check an export without touching any identity: what `import --dry-run` shows. */ export async function readSessionExport( text: string, passphrase: string, now: Date = new Date(), ): Promise<{ payload: Payload; summary: SessionSummary }> { - const v = await unseal(text, passphrase); - if (!isPayload(v)) throw new SealError("this session export is damaged (its content is not a session)"); - if (now.getTime() > Date.parse(v.expiresAt)) - throw new SealError(`this session export expired on ${v.expiresAt}; export it again`); - return { payload: v, summary: summary(v) }; + const payload = checkPayload(await unseal(text, passphrase), now); + const result = { payload, summary: summary(payload) }; + opened.set(result, text); + return result; } export interface ImportOptions { @@ -267,6 +276,11 @@ export interface ImportOptions { * changing anything when the plan it works out now differs from it. */ settingsPlan?: SettingsPlan; + /** + * What `readSessionExport` returned for this same text: import takes the session from it + * instead of deriving the key again (the expiry is checked again). Anything else is ignored. + */ + opened?: Awaited>; env?: NodeJS.ProcessEnv; now?: Date; } @@ -409,7 +423,11 @@ export async function importSession( options: ImportOptions, ): Promise { const env = options.env ?? process.env; - const { payload, summary: s } = await readSessionExport(text, options.passphrase, options.now); + const reuse = options.opened !== undefined && opened.get(options.opened) === text ? options.opened : undefined; + const payload = reuse + ? checkPayload(reuse.payload, options.now ?? new Date()) + : (await readSessionExport(text, options.passphrase, options.now)).payload; + const s = summary(payload); const id = options.as ?? payload.identity; assertIdentityId(id); const settingsPlan = payload.settings @@ -433,19 +451,38 @@ function exportsRecordPath(id: string, env: NodeJS.ProcessEnv): string { return join(identityStateDir(id, env), "exports.json"); } -function recordedExports(id: string, env: NodeJS.ProcessEnv): string[] { +/** + * The files recorded for the identity, and the record's file. `error` says why a record that is + * there could not be read or parsed; it then has none. + */ +export function exportRecord(id: string, env: NodeJS.ProcessEnv): { file: string; files: string[]; error?: string } { + const file = exportsRecordPath(id, env); + let text: string; try { - const v = JSON.parse(readFileSync(exportsRecordPath(id, env), "utf8")) as { files?: unknown }; - return Array.isArray(v.files) ? v.files.filter((f): f is string => typeof f === "string") : []; - } catch { - return []; + text = readFileSync(file, "utf8"); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") return { file, files: [] }; + return { file, files: [], error: (err as Error).message }; + } + try { + const v = JSON.parse(text) as { files?: unknown }; + if (!Array.isArray(v?.files)) return { file, files: [], error: "it has no list of files" }; + return { file, files: v.files.filter((f): f is string => typeof f === "string") }; + } catch (err) { + return { file, files: [], error: `not valid JSON (${(err as Error).message})` }; } } -/** Remember a file `export` wrote for the identity (an absolute path), so `remove` can delete it. */ +/** + * Remember a file `export` wrote for the identity (an absolute path), so `remove` can delete it. + * A record that is there and cannot be read is kept as it is (it names other exports): this throws. + */ export function recordExportFile(id: string, file: string, env: NodeJS.ProcessEnv = process.env): void { - const files = [...new Set([...recordedExports(id, env), file])]; - const record = exportsRecordPath(id, env); + const current = exportRecord(id, env); + if (current.error) throw new Error(`${current.file} could not be read (${current.error}); it was left as it is`); + const files = [...new Set([...current.files, file])]; + const record = current.file; mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 }); const tmp = `${record}.${process.pid}.tmp`; writeFileSync(tmp, `${JSON.stringify({ version: 1, files }, null, 2)}\n`, { mode: 0o600 }); @@ -454,15 +491,29 @@ export function recordExportFile(id: string, file: string, env: NodeJS.ProcessEn /** * The exports of the identity that are still where `export` wrote them and still hold a sealed - * session: a file replaced by something else since is not one of them. + * session: a file replaced by something else since is not one of them. `unreadable` lists the + * recorded files that are there and cannot be read, so it is not known whether they still are. */ -export function exportFiles(id: string, env: NodeJS.ProcessEnv = process.env): string[] { - return recordedExports(id, env).filter((file) => { - if (!existsSync(file)) return false; +export function exportFiles( + id: string, + env: NodeJS.ProcessEnv = process.env, +): { files: string[]; unreadable: { file: string; error: string }[] } { + const files: string[] = []; + const unreadable: { file: string; error: string }[] = []; + for (const file of exportRecord(id, env).files) { + let text: string; + try { + text = readFileSync(file, "utf8"); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code !== "ENOENT" && code !== "ENOTDIR") unreadable.push({ file, error: (err as Error).message }); + continue; + } try { - return (JSON.parse(readFileSync(file, "utf8")) as { format?: unknown }).format === SEALED_FORMAT; + if ((JSON.parse(text) as { format?: unknown }).format === SEALED_FORMAT) files.push(file); } catch { - return false; + /* not a sealed session: something else is there now */ } - }); + } + return { files, unreadable }; } diff --git a/packages/browser/src/vault.ts b/packages/browser/src/vault.ts index 4512bbcc..29434380 100644 --- a/packages/browser/src/vault.ts +++ b/packages/browser/src/vault.ts @@ -342,17 +342,25 @@ export async function readCredential(id: string, site: string, options: VaultOpt throw new VaultError( `the credentials of "${site}" are missing from the secret store; add them again with ${names().browser} vault add ${id} ${site}`, ); + const credential = credentialOf(raw); + if (!credential) + throw new VaultError( + `the secret store item of "${site}" is not a turno-browser credential; add it again with ${names().browser} vault add ${id} ${site}`, + ); + return credential; +} + +/** The credential a secret store item holds; undefined when it is not one. */ +function credentialOf(raw: string): Credential | undefined { let v: unknown; try { v = JSON.parse(raw); } catch { - v = undefined; + return undefined; } - if (!isCredential(v)) - throw new VaultError( - `the secret store item of "${site}" is not a turno-browser credential; add it again with ${names().browser} vault add ${id} ${site}`, - ); - return { username: v.username, password: v.password, ...(v.totp ? { totp: v.totp } : {}) }; + return isCredential(v) + ? { username: v.username, password: v.password, ...(v.totp ? { totp: v.totp } : {}) } + : undefined; } /** True when the identity's vault lists any site (an unreadable index counts as yes). */ @@ -439,7 +447,14 @@ export class VaultValues { /** Each user name in the forms a page gives it, lowercased: a page may show it in any case. */ private readonly names: { variants: string[]; mark: string }[] = []; - constructor(sites: readonly SiteValues[]) { + /** + * @param complete false when the secret store could not be read for some site (an error, not a + * missing item): a later read may find more, so a caller does not keep these for good. + */ + constructor( + sites: readonly SiteValues[], + readonly complete = true, + ) { this.usernames = [...new Set(sites.map((s) => s.username.trim().toLowerCase()).filter(Boolean))]; this.passwords = [...new Set(sites.map((s) => s.password).filter(Boolean))]; for (const s of sites) { @@ -481,16 +496,31 @@ export class VaultValues { /** * The vault values of every site of the identity, read from the secret store once. A site whose - * item cannot be read is left out; no vault, an unreadable index or no store gives none. + * item is missing or not a credential is left out; one whose read fails is left out too, and the + * result is then not `complete`. No vault, an unreadable index or no secret store gives none. */ export async function vaultValues(id: string, options: VaultOptions = {}): Promise { const env = options.env ?? process.env; const sites = vaultSummary(id, env)?.sites ?? []; if (!sites.length) return VaultValues.none; + let store: SecretStore; + try { + store = storeOf(options); + } catch { + return VaultValues.none; // no secret store on this machine: asking again finds none either + } const values: SiteValues[] = []; + let complete = true; for (const site of sites) { - const credential = await readCredential(id, site, options).catch(() => undefined); + let raw: string | undefined; + try { + raw = await store.get(vaultItem(id, site)); + } catch { + complete = false; + continue; + } + const credential = raw === undefined ? undefined : credentialOf(raw); if (credential) values.push({ site, username: credential.username, password: credential.password }); } - return new VaultValues(values); + return new VaultValues(values, complete); } diff --git a/packages/browser/test/cli/remove.test.ts b/packages/browser/test/cli/remove.test.ts index 2a937b8a..9a1b35bd 100644 --- a/packages/browser/test/cli/remove.test.ts +++ b/packages/browser/test/cli/remove.test.ts @@ -182,13 +182,20 @@ describe("turno-browser remove", () => { ); const r = json(io); expect(r.complete).toBe(false); - expect(r.left.map((l: { file?: string }) => ({ ...l, file: slashes(l.file ?? "") }))).toEqual( + // Paths with ~, also inside the step by hand. + expect( + r.left.map((l: { file?: string; command?: string }) => ({ + ...l, + file: slashes(l.file ?? ""), + command: slashes(l.command ?? ""), + })), + ).toEqual( expect.arrayContaining([ expect.objectContaining({ kind: "mcp", agent: "cursor", file: "~/.cursor/mcp.json", - command: `delete the "browser-school" entry from ${join(sb.home, ".cursor", "mcp.json")}`, + command: 'delete the "browser-school" entry from ~/.cursor/mcp.json', }), expect.objectContaining({ kind: "mcp", @@ -356,7 +363,7 @@ describe("turno-browser remove", () => { 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 () => { + it("lists a recorded registration in a file the agent's own command does not change as not checked", async () => { api.addIdentity("school", sb.env); const file = join(sb.home, "elsewhere", ".gemini", "settings.json"); mkdirSync(join(file, ".."), { recursive: true }); @@ -376,12 +383,13 @@ describe("turno-browser remove", () => { 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(json(io).left.map((l: { command: string }) => ({ ...l, command: slashes(l.command) }))).toEqual([ expect.objectContaining({ kind: "mcp", agent: "gemini", - command: `delete the "browser-school" entry from ${file}`, + command: 'delete the "browser-school" entry from ~/elsewhere/.gemini/settings.json', reason: expect.stringMatching(/own command changes/), + unchecked: true, }), ]); }); @@ -449,4 +457,129 @@ describe("turno-browser remove", () => { expect(report).toMatchObject({ complete: true, failed: [], left: [], deleted: [{ kind: "keychain", item: "x" }] }); expect(report.deleted[0]!.error).toBeUndefined(); }); + it("keeps a registrations or exports record it cannot parse, with the state folder, as not checked", async () => { + api.addIdentity("school", sb.env); + const state = identityStateDir("school", sb.env); + mkdirSync(state, { recursive: true }); + for (const f of ["agents.json", "exports.json"]) writeFileSync(join(state, f), '{"version":1,'); + // Recording another registration or export does not rewrite them. + const reg = { agent: "codex" as const, server: "browser-school", file: "x", at: "2026-12-01T00:00:00.000Z" }; + expect(() => recordRegistration("school", sb.env, reg)).toThrow(/left as it is/); + expect(() => recordExportFile("school", join(sb.home, "x.session"), sb.env)).toThrow(/left as it is/); + for (const f of ["agents.json", "exports.json"]) expect(readFileSync(join(state, f), "utf8")).toBe('{"version":1,'); + 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: expect.stringMatching(/agent registrations/), unchecked: true }), + expect.objectContaining({ kind: "path", what: expect.stringMatching(/session exports/), unchecked: true }), + ]); + for (const f of ["agents.json", "exports.json"]) expect(existsSync(join(state, f))).toBe(true); + expect(existsSync(identityDir("school", sb.env))).toBe(false); + }); + + it("reads Codex servers written with dotted keys or inline tables, and lists one in another form as not checked", async () => { + installed("codex"); + const config = join(sb.home, ".codex", "config.toml"); + mkdirSync(join(config, ".."), { recursive: true }); + const forms = [ + 'mcp_servers.browser-school = { command = "turno-browser-mcp", args = ["--identity", "school"] }', + '[mcp_servers]\n"browser-school".command = "turno-browser-mcp"\n"browser-school".args = ["--identity", "school"]', + 'mcp_servers."browser-school".command = "turno-browser-mcp" # turno', + '[mcp_servers.browser-school]\ncommand = "turno-browser-mcp"\n[mcp_servers.browser-school.env]\nA = "1"', + ]; + api.addIdentity("school", sb.env); + for (const form of forms) { + writeFileSync(config, `model = "x"\n${form}\n`); + const plan = await planRemoval("school", { env: sb.env, exec: fakeAgentCli(sb.env).exec, store: null }); + expect(plan.items.filter((i) => i.kind === "mcp")).toEqual([ + expect.objectContaining({ agent: "codex", command: "codex mcp remove browser-school" }), + ]); + expect(plan.left).toEqual([]); + } + // A form not read, and a server whose args are spread over several lines. + for (const form of [ + '[[mcp_servers]]\nname = "browser-school"\n', + '[mcp_servers.browser-school]\ncommand = "node"\nargs = [\n "turno-browser-mcp",\n "--identity",\n "school",\n]\n', + ]) { + writeFileSync(config, form); + const plan = await planRemoval("school", { env: sb.env, exec: fakeAgentCli(sb.env).exec, store: null }); + expect(plan.items.filter((i) => i.kind === "mcp")).toEqual([]); + expect(plan.left).toEqual([expect.objectContaining({ kind: "mcp", agent: "codex", unchecked: true })]); + } + }); + + it("checks what was done when a process does not stop", async () => { + api.addIdentity("school", sb.env); + const gone = 4_194_001; // no such process + const plan = { + id: "school", + exists: true, + // This test's own process stands for a server that does not stop. + items: [ + { kind: "process" as const, what: "background server", pid: process.pid }, + { kind: "path" as const, what: "profile", path: identityDir("school", sb.env) }, + ], + kept: [], + left: [ + { + kind: "process" as const, + what: "turno-browser-mcp started with the identity's id", + pid: gone, + unchecked: true, + }, + ], + }; + const report = await runRemoval(plan, { + env: sb.env, + exec: fakeAgentCli(sb.env).exec, + procTable: () => new Map(), + store: null, + }); + expect(report.complete).toBe(false); + expect(report.failed).toEqual([expect.objectContaining({ pid: process.pid })]); + // The check ran: the server it could not tell apart is gone, so it is no longer listed. + expect(report.left).toEqual([ + expect.objectContaining({ kind: "path", reason: "not removed: a process of the identity did not stop" }), + ]); + expect(existsSync(identityDir("school", sb.env))).toBe(true); + }); + + // Permission bits: POSIX, and not as root. + it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "lists an identities folder it cannot list, a half-written vault copy and an export it cannot read, and keeps them", + async () => { + const { exportFile } = await school(); + work(); + const copy = `${vaultPath("school", sb.env)}.123.tmp`; + writeFileSync(copy, "{}"); + chmodSync(copy, 0o000); + chmodSync(exportFile, 0o000); + const identities = join(identitySettingsPath("school", sb.env), ".."); + const options = { env: sb.env, exec: fakeAgentCli(sb.env).exec, store: null }; + try { + let plan = await planRemoval("school", options); + expect(plan.left.filter((l) => l.unchecked)).toEqual([ + expect.objectContaining({ kind: "path", path: copy, what: "half-written vault index", unchecked: true }), + expect.objectContaining({ kind: "path", path: exportFile, what: "session export", unchecked: true }), + ]); + expect(plan.items.map((i) => i.path)).not.toContain(copy); + expect(plan.items.map((i) => i.path)).not.toContain(exportFile); + // A folder it can enter but not list: the files it names still read. + chmodSync(identities, 0o300); + plan = await planRemoval("school", options); + expect(plan.left).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "path", what: "identities folder", unchecked: true }), + // Another identity may use it, as far as remove can tell. + expect.objectContaining({ kind: "keychain", item: "shared-user", unchecked: true }), + ]), + ); + expect(plan.kept).toEqual([]); + } finally { + chmodSync(identities, 0o700); + chmodSync(copy, 0o600); + chmodSync(exportFile, 0o600); + } + }, + ); }); diff --git a/packages/browser/test/cli/session.test.ts b/packages/browser/test/cli/session.test.ts index ad42765d..4a5e40cf 100644 --- a/packages/browser/test/cli/session.test.ts +++ b/packages/browser/test/cli/session.test.ts @@ -1,10 +1,11 @@ -import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { BrowserFunctions as BrowserApi } from "../../src/api.js"; import type { CliDeps, VaultInput } from "../../src/cli/context.js"; import * as session from "../../src/cli/session.js"; import { parseExpiry } from "../../src/cli/session.js"; +import { identityStateDir } from "../../src/ids.js"; import { importSettingsPlan } from "../../src/session-export.js"; import { readIdentitySettings, writeIdentitySettings } from "../../src/settings.js"; import { type Sandbox, sandbox, expectMode } from "../helpers/sandbox.js"; @@ -27,7 +28,8 @@ const SUMMARY = { interface Calls { exported: { id: string; options: { passphrase: string; expiresInMs?: number } }[]; - imported: { options: { passphrase: string; as?: string } }[]; + imported: { options: { passphrase: string; as?: string; opened?: unknown } }[]; + read?: unknown[]; } function fakeModule(calls: Calls, existing: string[] = ["work"]): BrowserApi { @@ -44,7 +46,9 @@ function fakeModule(calls: Calls, existing: string[] = ["work"]): BrowserApi { readSessionExport: async (_text: string, passphrase: string) => { if (passphrase !== PASS) throw Object.assign(new Error("wrong passphrase, or the file was changed"), { name: "SealError" }); - return { payload: {}, summary: SUMMARY }; + const opened = { payload: {}, summary: SUMMARY }; + calls.read?.push(opened); + return opened; }, importSession: async (_text: string, options: Calls["imported"][number]["options"]) => { calls.imported.push({ options }); @@ -94,7 +98,41 @@ describe("export", () => { expect(await run(exportSession(fakeModule(calls), ["work", "--out", out], fakeIo(sb.env), input()))).toMatch( /exists; pass --force/, ); + // --force replaces the file with a new one of mode 600, whatever mode the old one had. + chmodSync(out, 0o644); expect(await exportSession(fakeModule(calls), ["work", "--out", out, "--force"], fakeIo(sb.env), input())).toBe(0); + expectMode(out, 0o600); + expect(readdirSync(sb.home).filter((f) => f.endsWith(".tmp"))).toEqual([]); + }); + + it("--force is not stopped by a stale temporary file, and leaves none behind when it fails", async () => { + const calls: Calls = { exported: [], imported: [] }; + const out = join(sb.home, "work.session"); + writeFileSync(out, "old"); + const stale = `${out}.${process.pid}.tmp`; + writeFileSync(stale, "stale"); + expect(await exportSession(fakeModule(calls), ["work", "--out", out, "--force"], fakeIo(sb.env), input())).toBe(0); + expect(readFileSync(out, "utf8")).toContain("turno-browser-session"); + expect(readFileSync(stale, "utf8")).toBe("stale"); + // A folder where the file would go: the rename fails, and the temporary file goes too. + const folder = join(sb.home, "folder.session"); + mkdirSync(join(folder, "inside"), { recursive: true }); + const r = await run( + exportSession(fakeModule(calls), ["work", "--out", folder, "--force"], fakeIo(sb.env), input()), + ); + expect(r).not.toMatch(/pass --force/); + expect(readdirSync(sb.home).filter((f) => f.startsWith("folder.session."))).toEqual([]); + }); + + it("keeps an exports record it cannot read, and says the new export is not in it", async () => { + const calls: Calls = { exported: [], imported: [] }; + const record = join(identityStateDir("work", sb.env), "exports.json"); + mkdirSync(join(record, ".."), { recursive: true }); + writeFileSync(record, '{"files":'); + const io = fakeIo(sb.env); + expect(await exportSession(fakeModule(calls), ["work", "--out", join(sb.home, "w.session")], io, input())).toBe(0); + expect(readFileSync(record, "utf8")).toBe('{"files":'); + expect(io.errors.join("\n")).toMatch(/remove will not know of this export/); }); it("says the length rule in the first prompt and asks again after a short or differing passphrase", async () => { @@ -167,11 +205,14 @@ describe("import", () => { return f; }; - it("creates a new identity without asking", async () => { - const calls: Calls = { exported: [], imported: [] }; + it("creates a new identity without asking, from the export it read once", async () => { + const calls: Calls = { exported: [], imported: [], read: [] }; const io = fakeIo(sb.env); expect(await importSession(fakeModule(calls), [file(), "--as", "laptop"], io, deps(false, false), input())).toBe(0); expect(calls.imported[0]!.options.as).toBe("laptop"); + // The import takes what the first read opened, so the key is derived once. + expect(calls.read).toHaveLength(1); + expect(calls.imported[0]!.options.opened).toBe(calls.read![0]); expect(io.lines.join("\n")).toMatch(/created browser identity "laptop" with 3 cookies/); expect(io.lines.join("\n")).toMatch( /the export holds no settings \(an older turno-browser made it\): "laptop" keeps its own; change them with turno-browser set laptop/, diff --git a/packages/browser/test/recorder.test.ts b/packages/browser/test/recorder.test.ts index 31fd9ad3..c6743c55 100644 --- a/packages/browser/test/recorder.test.ts +++ b/packages/browser/test/recorder.test.ts @@ -252,6 +252,64 @@ describe("a named recording", () => { expect(readFileSync(file, "utf8")).not.toMatch(/Vault-pass-1|"ada"/); }); + it("reads the vault when a recording starts, keeps no default while a failed read stands, and retries after it", async () => { + addIdentity("work", sb.env); + const store = memorySecretStore(); + await vaultAdd( + "work", + "mail", + { urls: ["https://example.com/login"], username: "ada", password: "Vault-pass-1" }, + { env: sb.env, store }, + ); + const reads = { count: 0, fail: 1 }; + const flaky = { + ...store, + get: async (item: string) => { + reads.count++; + if (reads.fail-- > 0) throw new Error("the store timed out"); + return store.get(item); + }, + }; + const clock = { now: 1_000_000 }; + const r = new FlowRecorder( + { id: "work", env: sb.env }, + new Redactor(), + () => false, + flaky, + () => clock.now, + ); + r.start("flaky", undefined, false); + // The read starts with the recording, before any step. + expect(reads.count).toBe(1); + // While the failed read stands, any typed value may be a vault value: none keeps a default, + // and the steps (with the host's check in each) share that read. + for (const text of ["Canada", "Vault-pass-1"]) { + await act(r, "browser_type", { target: "e1", text }); + await r.vaultValues(); + } + expect(reads.count).toBe(1); + clock.now += 30_000; + await act(r, "browser_type", { target: "e1", text: "ada" }); + await act(r, "browser_type", { target: "e1", text: "Canada" }); + expect(reads.count).toBe(2); + const { flow } = r.stop(); + expect(flow.params.map((p) => [p.sensitive, p.default])).toEqual([ + [true, undefined], + [true, undefined], + [true, undefined], + [false, "Canada"], + ]); + // A store that keeps failing is asked at most once per 30 seconds, however many steps. + reads.fail = 100; + r.start("still-flaky", undefined, false); + for (let i = 0; i < 10; i++) { + await act(r, "browser_type", { target: "e1", text: `x${i}` }); + clock.now += 5_000; + } + expect(reads.count).toBe(3 + 1); + r.cancel(); + }); + it("refuses to replace a saved flow unless asked, and keeps auto- names for the identity", async () => { const r = recorder(); r.start("once", undefined, false); diff --git a/packages/browser/test/sealed.test.ts b/packages/browser/test/sealed.test.ts index fa8d8db7..c6290009 100644 --- a/packages/browser/test/sealed.test.ts +++ b/packages/browser/test/sealed.test.ts @@ -1,6 +1,21 @@ -import { describe, expect, it } from "vitest"; +import { createCipheriv, randomBytes, scryptSync } from "node:crypto"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { SEALED_FORMAT, SealError, seal, unseal } from "../src/sealed.js"; +// scrypt that counts its calls: the tests see whether a key was derived before a file was refused. +const derived = vi.hoisted(() => ({ count: 0 })); +vi.mock("node:crypto", async (importOriginal) => { + const actual = await importOriginal(); + const scrypt = (...args: Parameters) => { + derived.count++; + return actual.scrypt(...args); + }; + return { ...actual, scrypt }; +}); +beforeEach(() => { + derived.count = 0; +}); + const PASS = "correct horse battery staple"; const PAYLOAD = { kind: "test", cookies: [{ name: "sid", value: "session-value-1234" }] }; @@ -65,5 +80,48 @@ describe("the sealed session envelope (scrypt + AES-256-GCM)", () => { }; 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/); + expect(derived.count).toBe(0); }); + + it("refuses a tag cut short or an IV of another length as damaged, before deriving a key", async () => { + const env = JSON.parse(await seal(PAYLOAD, PASS)); + derived.count = 0; + const tag = Buffer.from(env.tag, "base64"); + for (const bytes of [12, 8, 4]) + await expect( + unseal(JSON.stringify({ ...env, tag: tag.subarray(0, bytes).toString("base64") }), PASS), + ).rejects.toThrow(/damaged/); + for (const bytes of [8, 16]) + await expect(unseal(JSON.stringify({ ...env, iv: randomBytes(bytes).toString("base64") }), PASS)).rejects.toThrow( + /damaged/, + ); + expect(derived.count).toBe(0); + }, 30_000); + + it("opens a file sealed with a lower N, which the header check allows, when its tag is valid", async () => { + // Sealed by hand the way seal does, with N 2^16 instead of export's 2^17. + const header = { + format: SEALED_FORMAT, + version: 1, + kdf: { name: "scrypt", N: 2 ** 16, r: 8, p: 1, salt: randomBytes(16).toString("base64") }, + cipher: "aes-256-gcm", + iv: randomBytes(12).toString("base64"), + }; + const key = scryptSync(PASS, Buffer.from(header.kdf.salt, "base64"), 32, { + N: 2 ** 16, + r: 8, + p: 1, + maxmem: 256 * 2 ** 16 * 8, + }); + const cipher = createCipheriv("aes-256-gcm", key, Buffer.from(header.iv, "base64")); + cipher.setAAD(Buffer.from(JSON.stringify(header))); + const data = Buffer.concat([cipher.update(JSON.stringify(PAYLOAD), "utf8"), cipher.final()]); + const text = JSON.stringify({ + ...header, + data: data.toString("base64"), + tag: cipher.getAuthTag().toString("base64"), + }); + expect(await unseal(text, PASS)).toEqual(PAYLOAD); + expect(derived.count).toBe(1); + }, 30_000); }); diff --git a/packages/browser/test/session-export.test.ts b/packages/browser/test/session-export.test.ts index c3cef1e0..a0473db2 100644 --- a/packages/browser/test/session-export.test.ts +++ b/packages/browser/test/session-export.test.ts @@ -1,7 +1,7 @@ import { type Server, createServer } from "node:http"; -import { afterEach, beforeEach, describe, expect, it, onTestFinished } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { addIdentity, identityExists } from "../src/identities.js"; -import { seal } from "../src/sealed.js"; +import { seal, unseal } from "../src/sealed.js"; import { exportSession, importSession, @@ -15,6 +15,12 @@ import { chromeUnavailable, stopSandboxProcesses } from "./helpers/chrome.js"; import { fakeSecretStore } from "./helpers/fake-secret-store.js"; import { type Sandbox, sandbox } from "./helpers/sandbox.js"; +// unseal as a spy: each call derives the key once. +vi.mock("../src/sealed.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, unseal: vi.fn(actual.unseal) }; +}); + const PASS = "a long enough passphrase"; const reason = chromeUnavailable(); @@ -160,6 +166,38 @@ describe("importing with a confirmed plan", () => { ).rejects.toThrow(/changed after import showed what it would change; nothing was imported/); expect(identityExists("copy", sb.env)).toBe(false); }, 30_000); + + it("takes the export it was given from readSessionExport for the same text, without deriving the key again", async () => { + const settings = { locale: "es-MX" }; + const payload = { + kind: "turno-browser-session", + identity: "work", + createdAt: "2026-11-01T00:00:00.000Z", + expiresAt: "2099-01-01T00:00:00.000Z", + storageState: state(1), + settings, + }; + const [text, other] = [await seal(payload, PASS), await seal(payload, PASS)]; + const confirmed = planSettings({ ...settings, locale: "fr-FR" }, undefined); + const opened = await readSessionExport(text, PASS); + vi.mocked(unseal).mockClear(); + const changed = /changed after import showed what it would change/; + await expect( + importSession(text, { passphrase: PASS, as: "copy", opened, settingsPlan: confirmed, env: sb.env }), + ).rejects.toThrow(changed); + expect(unseal).not.toHaveBeenCalled(); + // What was read from another text, or made by hand, is not taken: the key is derived. + for (const given of [{ ...opened }, opened]) + await expect( + importSession(other, { passphrase: PASS, as: "copy", opened: given, settingsPlan: confirmed, env: sb.env }), + ).rejects.toThrow(changed); + expect(unseal).toHaveBeenCalledTimes(2); + // The expiry is checked again. + await expect( + importSession(text, { passphrase: PASS, opened, now: new Date("2099-01-02T00:00:00Z"), env: sb.env }), + ).rejects.toThrow(/expired/); + expect(unseal).toHaveBeenCalledTimes(2); + }, 60_000); }); describe("the origins an export opens", () => {