Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(security): sign connectors.json and set aside one changed while closed

Alan Buscaglia9925c39f9ee2
diff --git a/README.md b/README.md
index aa3fed2..90de334 100644
--- a/README.md
+++ b/README.md
@@ -136,7 +136,7 @@ A small Node daemon starts the agent engine (Gentle Shell, `gentle-shell --mode
- **Your data:** `~/.gentle-dot` (mode 0700): sessions, settings, the access key (`token`), and the engine's own home and workspace. Point the assistant at a folder of yours with `GENTLE_DOT_WORKSPACE` or `"workspace"` in `~/.gentle-dot/config.json`.
- **Memory:** your global Engram (`~/.engram`, port 7437), project `gentle-dot`; `GENTLE_DOT_ENGRAM=private` gives the assistant a memory of its own.
-- **Connectors:** the daemon alone writes `~/.gentle-dot/connectors.json` and the engine's `mcp.json`, and puts them back if anything else changes them.
+- **Connectors:** the daemon alone writes `~/.gentle-dot/connectors.json` and the engine's `mcp.json`, and puts them back if anything else changes them. `connectors.json` is signed with a key kept in the Keychain; if it was changed while Gentle Dot was closed, it is set aside and you are told.
- **Screenshots:** each model call carries only the latest one; earlier ones become one-line log entries, which keeps long control sessions fast.
<div align="right"><a href="#top">Back to top</a></div>
@@ -145,9 +145,9 @@ A small Node daemon starts the agent engine (Gentle Shell, `gentle-shell --mode
## Security status
-What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow. Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat. On macOS, connector tokens, client secrets, and sign-ins live in the Keychain, in items the signed app creates, and reach the assistant only in memory over that private channel; they are never written to a file, and tokens from older versions move there once. Without the app, connectors that need a token stop working instead of falling back to a file.
+What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow. Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat. On macOS, connector tokens, client secrets, and sign-ins live in the Keychain, in items the signed app creates, and reach the assistant only in memory over that private channel; they are never written to a file, and tokens from older versions move there once. Without the app, connectors that need a token stop working instead of falling back to a file. The connector settings file is signed with a key kept in the Keychain: if anything changes it while Gentle Dot is closed, the app sets it aside at the next start, starts with no connectors, and tells you.
-What does not yet: the agent has a shell, and its shell commands are checked on a best-effort basis only. The connector settings file is trusted when the assistant starts, and the app cannot yet tell its own Keychain items from ones another program of yours planted. Protecting the connector settings file is the next step before a stable release. On Linux, tokens go to the system keyring, which any program of yours can read while it is unlocked, and that path is not yet verified on a Linux desktop.
+What does not yet: the agent has a shell, and its shell commands are checked on a best-effort basis only. Started without the app (from a terminal, or in the browser-only setup), the assistant cannot check that signature and loads the settings as they are, with token-based connectors locked. The app cannot yet tell its own Keychain items from ones another program of yours planted. On Linux, tokens go to the system keyring, which any program of yours can read while it is unlocked, and that path is not yet verified on a Linux desktop.
<div align="right"><a href="#top">Back to top</a></div>
diff --git a/docs/design.md b/docs/design.md
index d22b6cf..37ef2fe 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -138,19 +138,20 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete
- Slack: the official `https://mcp.slack.com/mcp` (no dynamic client registration) with the user's own Slack app: `oauth.clientId`, an optional `oauth.clientSecret`, and the fixed redirect `http://localhost:38417/callback` (`oauth.callbackUrl`, sent exactly as written). Slack accepts a loopback redirect only with PKCE turned on, which makes the app a public client (refresh tokens last 30 days), so the secret may be left empty; the guide lists the user token scopes.
- Gmail: the official `https://gmailmcp.googleapis.com/mcp/v1` (Developer Preview) with the user's own Google Cloud project: the Gmail API and Gmail MCP API enabled, the consent screen in testing (refresh tokens last 7 days), and a Web application client with the redirect `http://localhost:38418/callback`; `oauth.scope` asks for `gmail.readonly` and `gmail.compose`. `gmail.compose` can also send mail, so the copy says so: drafting and sending ask for approval each time, and read only hides them. Each guided connector's copy describes only what its guide's permissions allow (Slack: send and schedule messages with `chat:write`; Discord: send messages and reactions).
- Typed values (S18, S19): a connector's `fields` are asked one at a time with sign-in prompts (`auth_prompt` `secret` or `text`, flow id `connector-setup-*`, `optional` when the answer may be empty), in the window that started them. A catalog connector is added only when every required value is there (cancel changes nothing); an approved draft or an import is added first and stays `needs_setup` until its values are typed. A secret value (a field marked `secret`) goes to the app's secure store (below, Secrets) and only its reference stays in memory and `connectors.json`; other values (a client id) stay in `connectors.json` (protected). Values fill the real server in the daemon's memory in place of `${input:<key>}` placeholders (never the engine's `mcp.json`) and are never sent to a window or logged. Env values, headers, and `oauth.clientSecret` follow the engine's syntax (a leading `!` runs a shell command and `$NAME` expands), so typed and imported literals are escaped (`$` → `$$`, `!` → `$!`); the proxy resolves them the same way before it sends them upstream, so a typed value arrives exactly as typed. `clientId`, the command, its arguments, and URLs are used as written. `connector_setup` asks again (a new token). A connector whose value is missing is `needs_setup` and is left out of `mcp.json`.
-- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). A typed value (`${input:NAME}`) may only stand for an env value (or an http server's header): anywhere else (the command, its arguments, the URL) it would put the secret into the command line or an address the model chose, so the guard answers the model "Secrets can only go into environment variables." and sends nothing, and the daemon refuses such a draft as well. The daemon checks it (lengths, `https` or loopback URLs, env names, typed values), keeps the newest five (`MAX_CONNECTOR_DRAFTS`; the windows keep the same five and take the waiting list again after each `ready`), and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (no curated list, so the proxy shows none, and in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. Residual, as for the rest of the state (S25): `connectors.json` edited while the daemon is not running is loaded at its next start, and it can now hold a server of the user's own (a command).
+- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). A typed value (`${input:NAME}`) may only stand for an env value (or an http server's header): anywhere else (the command, its arguments, the URL) it would put the secret into the command line or an address the model chose, so the guard answers the model "Secrets can only go into environment variables." and sends nothing, and the daemon refuses such a draft as well. The daemon checks it (lengths, `https` or loopback URLs, env names, typed values), keeps the newest five (`MAX_CONNECTOR_DRAFTS`; the windows keep the same five and take the waiting list again after each `ready`), and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (no curated list, so the proxy shows none, and in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. `connectors.json` can hold a server of the user's own (a command), so it is signed (Integrity, below): with the app, a file edited while the daemon is not running is set aside instead of loaded.
- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address (`summary`), and env and header names only; values stay in the daemon. The summary, also shown for a custom connector in the Connectors list, is masked by structure, not by a word list: an address (an argument or the server URL, any scheme) keeps its scheme, host, and path, loses its user and password and its fragment, shows its query keys with every value as `•••`, and masks long opaque path segments (20 or more letters, digits, `_`, or `-`, mixing digits or cases); the argument after `--header`/`-H`, the value of `--header=`, and any `Name: value` argument whose name looks like a credential (Authorization, Cookie, `*key*`, `*token*`, `*secret*`, and so on) keep only the name; the argument after a flag named like a credential (`/token|secret|key|pass|auth|cred|bearer/i`) and the value of `name=value` forms of the same are masked; known token prefixes (`ghp_`, `sk-`, `xoxb-`, `AKIA`, `glpat-`, and others) and long opaque words are masked. Values the engine resolves at start are noted before the import (`notes`): "Runs a command on your computer to get this value." for a leading `!` (the command is not shown), and "Reads the environment variable NAME." for `$NAME`/`${NAME}`. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries, read only with every tool hidden, and never touches the source files; their header and environment values go to the app's secure store (below, Secrets), with references in `connectors.json`. A credential inside an imported address or command-line argument stays where it is (masked when shown; a documented limit).
-- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600; neither holds a secret. The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above).
+- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600; neither holds a secret. The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." A change made to `connectors.json` while the daemon is not running is caught by its signature at the next start with the app (Integrity, below); `mcp.json` is always rewritten from memory. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above).
- MCP proxy (S25.4, `packages/daemon/src/mcp-proxy.ts`): the engine's `<agentHome>/mcp.json` lists every connector as `{url: "http://127.0.0.1:<port>/mcp/<id>", headers: {Authorization: "Bearer <proxy key>"}, exposure: "direct", timeout: 300}` (plus `enabled: false` when turned off) and nothing else: no real address, token, environment, or command. The key is random, kept only in memory, and new for every engine launch; the proxy accepts it only in the `Authorization` header (401 otherwise, never from the address) and refuses any request with an `Origin`. It answers JSON-RPC 2.0 as plain `application/json` over POST, like the computer helper (GET is 405, notifications 202): `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, and `prompts/get`. Upstream, the daemon keeps one pi-mcp `McpClient` per connector, connected on first use: streamable HTTP for a remote server, with its headers and the stored sign-in (sent as a bearer token and refreshed after a 401 with the stored refresh token, never a new browser sign-in), or stdio for a server the daemon runs itself, with the engine's environment plus the server's values. A dropped connection is made again on the next request; turning a connector off, removing it, or changing its server or values closes it, and so does the daemon's shutdown. Every request reads the connector's state from the daemon's memory, so a mode change applies at once, without an engine restart (the engine still restarts to list newly allowed tools). Policy: `tools/list` shows in read only only the tools that declare `readOnlyHint: true` AND are on the curated list (the same `isReadOnlyTool` rule the guard uses), and every tool in "Read and send"; `tools/call` refuses a hidden or unknown tool with a JSON-RPC error however it is called, taking the annotations from the server's own list, never the caller; a sending action (any tool that is not read-only) is forwarded only after the user approves its preview (connector, action, and every argument, key fields first) in the desktop app's native dialog, asked over the app channel (below; `DotBridge.askInApp`); windows only show an informational card. Declining, no answer (the app declines after 120 s, the daemon gives up at 130 s), no app to ask, the app quitting while it asks, an answer that is stopped, or a connector changed while it was asked refuses it with a JSON-RPC error that says nothing was sent. Resources and prompts are reads: they are shown in "Read and send", and in read only only for a connector with a curated read-only list (the catalog's); a server of the user's own in read only exposes no resources or prompts, like its tools. Errors from the server are passed on with their code and message; a refused sign-in says to sign in again in Connectors; anything else says the connector could not be reached (the log masks addresses).
- Secrets (S25.5, `packages/daemon/src/secret-source.ts`): bot tokens, client secrets, imported header and environment values, and OAuth sign-ins live in the desktop app's secure store (macOS: Keychain items the signed app creates, service `dev.gentleman.gentle-dot.connectors`; `apps/desktop/src-tauri/src/secure_store`). The daemon asks for them over the app channel (`secret_get`, `secret_put`, `secret_delete`, `secret_list`, below) and keeps them in memory only, until the channel closes; no secret is written to a file or a log. `connectors.json` holds `{"secretRef": "<id>"}` in each secret's place, with ids `connector/<id>/value/<key>`, `connector/<id>/env/<NAME>`, `connector/<id>/header/<Name>`, `connector/<id>/client-secret`, and `connector/<id>/signin` (pi-mcp's OAuth state as JSON). In a server of the user's own, every environment value, header, and `oauth.clientSecret` is treated as a secret unless it only names a typed field. Before the proxy uses a connector it reads the secrets it refers to; the daemon only reads ids it recorded after its own `put`. Without the app (a daemon it only attached to, `pnpm dev`, the web), a connector that needs a secret fails closed with "Open the Gentle Dot app to use this connector." (the proxy answers it to every request), and a connector without secrets keeps working; there is no file fallback. Removing a connector deletes its items.
-- Migration (once, when the app's channel is there): text secrets still in `connectors.json`, then the sign-ins of the old sign-in home (`<data>/connector-signin/mcp-auth.json`, the daemon's own, which win) and of the engine's old `<agentHome>/mcp-auth.json` (keyed `mcp__<id>|<url>`), are stored, read back, and compared before they leave the files; if one fails, the files stay as they were and the next start tries again. A sign-in for a connector that is no longer added is dropped (counted in the log). The old sign-in home (its `mcp.json` held the real servers) is removed. A 0-byte sign-in file is removed and an unreadable one is left alone and reported; neither blocks the rest. `connectors.json` then says `version: 2`, and a sign-in file that appears afterwards is reported once and left alone, never imported (L114 N1). Until a text secret has moved it stays in the file and is not used. Nothing secret is logged.
+- Migration (once, when the app's channel is there): text secrets still in `connectors.json`, then the sign-ins of the old sign-in home (`<data>/connector-signin/mcp-auth.json`, the daemon's own, which win) and of the engine's old `<agentHome>/mcp-auth.json` (keyed `mcp__<id>|<url>`), are stored, read back, and compared before they leave the files; if one fails, the files stay as they were and the next start tries again. A sign-in for a connector that is no longer added is dropped (counted in the log). The old sign-in home (its `mcp.json` held the real servers) is removed. A 0-byte sign-in file holds nothing: it is removed and the removal is logged. One that cannot be read or is not a list of sign-ins may hold secrets: it is left as it is and reported, the other files still move, and the migration is not marked done, so the next start tries again (L117 A2). `connectors.json` then says `version: 2`, and a sign-in file that appears afterwards is reported once and left alone, never imported (L114 N1). Until a text secret has moved it stays in the file and is not used. Nothing secret is logged.
+- Integrity (S25.6, `packages/daemon/src/connector-integrity.ts`): every write of `connectors.json` (a change, a migration, a put-back) carries `mac`, the lowercase hex HMAC-SHA256 of the text `gentle-dot/connectors.json/v1\n` followed by the record without `mac` in canonical JSON (no whitespace; every object's keys sorted by UTF-16 code unit; arrays in order; strings, numbers, booleans, and null as `JSON.stringify` writes them). The key is 32 random bytes, kept as hex in the app's secure store under `integrity/connectors`, created on the first start with the app, and held only in memory; it is never written to a file or logged. At start the daemon listens (so the app's health check answers), then checks the file as it was read before anything rewrites it, watches it, migrates secrets, answers the app, or starts the engine. With the app: a file that was signed before (it has a `mac`, or the key already existed) whose `mac` is missing or wrong was changed while Gentle Dot was closed; it is moved to `<data>/connectors.rejected-<UTC time>.json` (0600; a planted link is moved as a link), the daemon starts with no connectors and a fresh signed record, the log says so once, and every window of that run gets the warning toast "Connectors were changed while Gentle Dot was closed, so they were set aside. Review them in Connectors." The Keychain items are not touched (a reference in the set-aside file is never read). The first start after T23e (an unsigned file and no key) creates the key and signs the file without refusing it. Without the app (or when the key cannot be read or stored), the file cannot be checked: it is loaded as it is, the log says it was not verified, connectors that need a secret stay locked, and a signed file is put back byte for byte so its signature survives until a daemon the app launches checks it. While running, a change is put back as before, signed. Limits: a `connectors.json` written without the app (a migration rename of a `computer` entry) is unsigned and is refused at the next start with the app once the key exists; the key's Keychain item has the same limits as any other (§8).
- Sign-in (S25.5, `packages/daemon/src/connector-oauth.ts`) runs in the daemon with pi-mcp's OAuth, as the engine's `mcp login` did (the CLI is no longer run): a stored refresh token signs in again without the browser; otherwise the authorization code flow (PKCE, dynamic client registration or the user's own client) against a loopback callback (`127.0.0.1`, a random port, or the connector's fixed redirect such as Slack's `http://localhost:38417/callback`). The whole flow keeps its state in memory; only the result is stored, once, with `secret_put`, and a refresh after a 401 stores the new tokens the same way. The daemon relays the authorization URL to the window that started it (`auth_event` `auth_url`, which opens the browser) and offers a `manual_code` prompt: when the browser cannot reach the loopback callback, the user pastes the address it ended on, and the daemon takes the code from it only when it is this sign-in's loopback address (port and path) with its `state`; nothing is fetched. Cancel closes the callback. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed text and codes are never logged (URLs are masked).
- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when the connector refers to a stored sign-in with tokens and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.
- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`, and the secret requests `secret_get {id}` (`{secret}` or `null`), `secret_put {id, secret}`, `secret_delete {id}` (`{deleted}`), and `secret_list` (`{ids}`). The app answers on worker threads: approvals with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout), secrets from `secure_store` with ids checked (`check_id`), refusals that never repeat a value, and nothing logged; a malformed request, a dialog that fails, or the channel closing refuses.
- Privileged messages (S25.2, `APP_COMMANDS` in the protocol): `connector_connect`, `connector_signin`, `connector_setup`, `connector_disconnect`, `connector_remove`, `connector_mode`, `connector_draft_reply` approving, `connector_import`, `computer_register`, and `computer_unregister` are refused on the WebSocket (`error app_required`, "Open the Gentle Dot app to change connectors.") whoever sends them, the access key notwithstanding (L49). The desktop panel sends them with the `connector_command` Tauri command, which the app forwards over the channel with the panel's `clientId` (from `ready`; it only routes the sign-in steps and refusals to that window and authorizes nothing by itself). Every other message stays on the WebSocket: chat, history, accounts, profiles, models, uploads, `connectors_list`, `connectors_scan`, sign-in answers (`auth_reply`, owner-checked), and declining a draft. Changes that widen access are confirmed natively even though the app sent them: switching to "Read and send", connecting or setting up a connector that is off, approving a draft, and importing (each with what it adds); declining sends the window `error declined` and changes nothing. Narrowing (read only, disconnecting, removing) and signing in again need no dialog. Without a channel (an attached daemon, `pnpm dev`, the web, a VPS until T23h) these messages and every approval fail closed. Approvals the daemon asks show in every window as an `ask` with `method: "app"` ("Waiting for your answer in the Gentle Dot app."); `ui_response` to it is refused.
- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): the tools of a connector the proxy fronts (`proxied` in the policy: turned on and set up) pass, since the proxy filters them and asks itself; a card here would ask twice. A turned-off connector is not in `proxied` or the approved list, so its tools stay blocked here as well. For any other connector tool: it runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.
- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the old sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json` (gone after the migration, still protected in case they appear again), `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.
-- Stage 2 integrity (S25) must cover the user's own servers too. Today `connectors.json` is trusted when the daemon starts, so a file edited while the daemon is not running can add a custom or imported server that runs an arbitrary command, turn it on, claim any `origin` ("Imported from …", "Drafted by the assistant"), and carry env or header values that are not escaped (`!command`, `$NAME`), which the engine runs or expands at the next start. S25's integrity check (state the agent cannot write, or a signature it cannot forge) must cover every field of those entries: command, arguments, URL, env, headers, `enabled`, `mode`, and `origin`.
+- Stage 2 integrity (S25.6, Integrity above) covers the user's own servers too: the signature is over the whole record, so a file edited while the daemon is not running cannot add a server that runs a command, turn it on, claim an `origin`, change its command, arguments, URL, env, headers, `enabled`, or `mode`, or plant a secret reference (L117 A1) without being set aside at the next start with the app. Without the app it is still loaded, but connectors that need a secret are locked there.
- Subagents are off in the assistant's engine (`GENTLE_PI_AGENTS=0`, §3): Gentle Shell's subagent child engines get only its own child extensions, not the approval guard, so a child could run connector tools or read credentials unchecked. Turning them back on needs S25 (enforcement in the daemon) or forwarding the guard to child engines. With the proxy (S25.4) a child's connector calls are filtered and approved by the daemon too; subagents stay off until T23f checks the rest (credential reads, a real-engine probe).
### Switching and history races (S21)
@@ -286,7 +287,7 @@ The user changes the main assistant's model from the chat, in the panel and the
- The daemon binds `127.0.0.1` only. A random 256-bit token is stored in `~/.gentle-dot/token` (mode 0600). The desktop app reads it; the browser receives it once by URL fragment.
- WebSocket upgrades check `Origin` against an allowlist (`http://127.0.0.1:4317`, `tauri://localhost`).
- The VPS guide requires HTTPS, a reverse proxy with authentication, and a dedicated Docker container with no access to personal machines.
-- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Connector secrets (tokens, client secrets, imported headers, sign-ins) are in Keychain items the signed app creates and reach the daemon only in memory over that channel (S25.5, §4 Secrets); without the app, connectors that need one fail closed. What the Keychain cannot check: `security-framework` exposes no item access list, so the app cannot tell an item it created from one a same-user process planted (before the first `put`, or after deleting the app's); the daemon only reads ids it recorded, and every `put` replaces the item. Still open: `connectors.json` (with its references) is trusted at start until T23e signs it, Linux children could inherit the channel if libuv there does not close it (the daemon then refuses it; T23g), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.
+- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Connector secrets (tokens, client secrets, imported headers, sign-ins) are in Keychain items the signed app creates and reach the daemon only in memory over that channel (S25.5, §4 Secrets); without the app, connectors that need one fail closed. What the Keychain cannot check: `security-framework` exposes no item access list, so the app cannot tell an item it created from one a same-user process planted (before the first `put`, or after deleting the app's); the daemon only reads ids it recorded, and every `put` replaces the item. `connectors.json` is signed with a key in the Keychain, and a file changed while Gentle Dot was closed is set aside at the next start with the app (S25.6, §4 Integrity); without the app it is loaded unverified. Still open: Linux children could inherit the channel if libuv there does not close it (the daemon then refuses it; T23g), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.
## 9. Desktop shell contract (Tauri 2 <-> UI)
diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.ts
index 0325214..ab7c926 100644
--- a/packages/daemon/src/bridge.ts
+++ b/packages/daemon/src/bridge.ts
@@ -117,6 +117,8 @@ export class DotBridge {
/** Each window's id, for the app's commands on its behalf. */
private readonly clientIds = new Map<string, BridgeClient>();
private readonly asks = new Map<string, PendingAsk>();
+ /** Told to every window that connects during this run (a connectors file set aside at start). */
+ private readonly notices: ServerPayload[] = [];
private readonly runningTools = new Set<string>();
private readonly seenRequestIds: string[] = [];
private readonly sessionDir: string;
@@ -160,6 +162,7 @@ export class DotBridge {
if (options.connectors) {
options.connectors.onChanged = (restart) => this.afterConnectorsChange(restart);
options.connectors.onBlocked = () => this.connectorChangeBlocked();
+ options.connectors.onSetAside = (notice) => this.connectorsSetAside(notice);
options.connectors.imagesSupported = () => supervisor.modelImages;
}
this.state = this.deriveState();
@@ -208,6 +211,7 @@ export class DotBridge {
for (const draft of this.options.connectors?.drafts() ?? [])
this.deliver(client, { type: "connector_draft", draft });
if (this.interrupted) this.deliver(client, { type: "interrupted" });
+ for (const notice of this.notices) this.deliver(client, notice);
return () => {
this.clients.delete(client);
this.clientIds.delete(clientId);
@@ -707,6 +711,17 @@ export class DotBridge {
this.broadcast({ type: "connector_draft", draft });
}
+ /**
+ * A `connectors.json` changed while the daemon was down was set aside (S25.6), usually before any
+ * window is open: every window of this run is told once, when it connects.
+ */
+ private connectorsSetAside(message: string): void {
+ const notice: ServerPayload = { type: "toast", level: "warning", message };
+ this.notices.push(notice);
+ this.broadcast(notice);
+ this.broadcast({ type: "connectors", connectors: this.requireConnectors().list() });
+ }
+
/** The connector files were changed outside the Connectors screen and put back. */
private connectorChangeBlocked(): void {
this.broadcast({ type: "toast", level: "warning", message: "A change to your connectors was blocked." });
diff --git a/packages/daemon/src/connector-integrity.ts b/packages/daemon/src/connector-integrity.ts
new file mode 100644
index 0000000..4494390
--- /dev/null
+++ b/packages/daemon/src/connector-integrity.ts
@@ -0,0 +1,57 @@
+/**
+ * The signature on `connectors.json` (S25.6, docs/design.md "Security"). The daemon signs every
+ * write with HMAC-SHA256 under a random 32-byte key kept in the desktop app's secure store (id
+ * {@link INTEGRITY_KEY_ID}), and at start, with the app, refuses a file whose signature does not
+ * match: it was changed while Gentle Dot was closed. The key reaches the daemon over the app's
+ * channel and stays in memory; it is never written to a file or a log.
+ *
+ * What is signed: the UTF-8 bytes of {@link MAC_DOMAIN} followed by the record without its `mac`
+ * field in canonical JSON: no whitespace, every object's keys sorted by UTF-16 code unit (the
+ * default `Array.prototype.sort`), arrays in their order, and strings, numbers, booleans, and null
+ * as `JSON.stringify` writes them. The `mac` field is the lowercase hex digest.
+ */
+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
+
+/** The secret id of the signing key in the app's store. */
+export const INTEGRITY_KEY_ID = "integrity/connectors";
+
+/** What every signed text starts with, so the key signs nothing else by accident. */
+export const MAC_DOMAIN = "gentle-dot/connectors.json/v1\n";
+
+const KEY_HEX = /^[0-9a-f]{64}$/;
+
+/** A new signing key, as the hex text the app's store keeps. */
+export function newIntegrityKey(): string {
+ return randomBytes(32).toString("hex");
+}
+
+/** The key's bytes, or undefined when the stored text is not a key this daemon made. */
+export function parseIntegrityKey(text: string | undefined): Buffer | undefined {
+ return text !== undefined && KEY_HEX.test(text) ? Buffer.from(text, "hex") : undefined;
+}
+
+/** `value` as canonical JSON (see the module comment). */
+export function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item ?? null)).join(",")}]`;
+ if (value !== null && typeof value === "object") {
+ const record = value as Record<string, unknown>;
+ const keys = Object.keys(record)
+ .filter((key) => record[key] !== undefined)
+ .sort();
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
+ }
+ return JSON.stringify(value) ?? "null";
+}
+
+/** The MAC of a record (its own `mac` field, if any, is left out). */
+export function recordMac(key: Buffer, record: Record<string, unknown>): string {
+ const { mac: _mac, ...rest } = record;
+ return createHmac("sha256", key).update(MAC_DOMAIN).update(canonicalJson(rest)).digest("hex");
+}
+
+/** True when `record.mac` is the MAC of the rest under `key`; compared in constant time. */
+export function macMatches(key: Buffer, record: Record<string, unknown>): boolean {
+ const { mac } = record;
+ if (typeof mac !== "string" || !/^[0-9a-f]{64}$/.test(mac)) return false;
+ return timingSafeEqual(Buffer.from(mac, "hex"), Buffer.from(recordMac(key, record), "hex"));
+}
diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.ts
index 7e93918..01e4224 100644
--- a/packages/daemon/src/connectors.ts
+++ b/packages/daemon/src/connectors.ts
@@ -1,5 +1,6 @@
import { createHash, randomUUID } from "node:crypto";
import {
+ chmodSync,
existsSync,
type FSWatcher,
lstatSync,
@@ -28,12 +29,25 @@ import type {
import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";
import { resolveRecord, resolveValue, storedSignIn } from "./connector-credentials.ts";
import { type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";
+import {
+ INTEGRITY_KEY_ID,
+ macMatches,
+ newIntegrityKey,
+ parseIntegrityKey,
+ recordMac,
+} from "./connector-integrity.ts";
import { type OAuthSettings, type SignIn, SignInCancelledError, startSignIn } from "./connector-oauth.ts";
import { type ConnectorPolicy, draftSecretProblem, POLICY_ENV } from "./extensions/approval-guard.ts";
import type { ProxiedConnector, UpstreamCredentials } from "./mcp-proxy.ts";
import { runtimeDir, runtimeModules } from "./runtime.ts";
import { NO_APP, type SecretSource, SecretsUnavailableError } from "./secret-source.ts";
+export { INTEGRITY_KEY_ID } from "./connector-integrity.ts";
+
+/** What windows are told once after a changed `connectors.json` was set aside (S25.6). */
+export const SET_ASIDE_NOTICE =
+ "Connectors were changed while Gentle Dot was closed, so they were set aside. Review them in Connectors.";
+
/** A value the user types in the app (a token, client credentials); kept only in the assistant's private state. */
export interface SetupField {
key: string;
@@ -621,7 +635,8 @@ export interface SignInTarget {
* screen. The files (`connectors.json` and the engine's `mcp.json`) are written from memory; a change
* made by anything else (the assistant has a shell) is put back, and a project `.pi/mcp.json` in the
* workspace is removed. Checked on every file event, before every engine start, and after every
- * run. A change made while the daemon is not running is loaded at its next start (S25.6).
+ * run. Every write of `connectors.json` is signed (S25.6, {@link checkIntegrity}): with the app, a
+ * file changed while the daemon was not running is set aside at the next start instead of loaded.
*
* Secrets (S25.5) are never in a file: `connectors.json` holds `{"secretRef": "<id>"}` in their
* place, the values live in the desktop app's secure store, and the daemon keeps the ones it read
@@ -643,7 +658,15 @@ export class ConnectorStore {
onReverted: () => void = () => {};
/** Called after every change to the state (the proxy closes what it no longer may use). */
onUpdated: () => void = () => {};
+ /** Called once when a changed `connectors.json` was set aside at start; `notice` is for the user. */
+ onSetAside: (notice: string) => void = () => {};
private saved: ConnectorsState;
+ /** `connectors.json` as it was read at start: its text, and the record when it was a JSON object. */
+ private loaded: { text: string; record?: Record<string, unknown> } | undefined;
+ /** The signing key from the app's store, once {@link checkIntegrity} read it; only in memory. */
+ private integrityKey: Buffer | undefined;
+ /** True once the record differs from what was read at start (a change, a move, a migration). */
+ private edited = false;
/** The desktop app's helper while a window has it registered; only in memory and `mcp.json`. */
private computer: ComputerEndpoint | undefined;
/** The daemon's proxy for the running engine; only in memory and `mcp.json`. */
@@ -675,7 +698,10 @@ export class ConnectorStore {
// A new install has nothing to move.
this.migrated =
version >= 2 || (version === 0 && ![this.authFile, this.legacyAuthFile].some((f) => existsSync(f)));
- if (renamed) writePrivate(this.file, this.recordText());
+ if (renamed) {
+ this.edited = true;
+ writePrivate(this.file, this.recordText());
+ }
}
get agentHome(): string {
@@ -699,12 +725,70 @@ export class ConnectorStore {
refId(text) !== undefined ? text : this.seal(secretId, text),
);
this.saved = state;
+ this.edited = true;
mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });
writePrivate(this.file, this.recordText());
writePrivate(this.mcpFile, this.engineMcpText());
this.onUpdated();
}
+ /**
+ * Checks the signature of `connectors.json` as it was read at start (S25.6); the daemon awaits it
+ * before it watches the files or starts the engine. With the app's store: the signing key is read,
+ * or created on the first start with the app (and the current file signed: the first start after
+ * T23e). A file that was signed before (it has a `mac`, or the key already existed) whose `mac` is
+ * missing or wrong was changed while the daemon was down: it is moved to
+ * `connectors.rejected-<UTC time>.json` (0600), the daemon starts with no connectors, and
+ * {@link onSetAside} tells the user once; the secrets in the app's store are left alone. Without
+ * the app (or when the key cannot be read) the file cannot be checked: it stays loaded as it is,
+ * that is logged, and it is put back byte for byte, so its signature survives until a daemon the
+ * app launches checks it.
+ */
+ async checkIntegrity(): Promise<void> {
+ const source = this.options.secrets;
+ const present = this.loaded !== undefined;
+ const notVerified = (why: string) => {
+ if (present)
+ this.log(
+ `connectors.json was not verified: ${why}; it is used as it is, and connectors that need a secret stay locked without the app`,
+ );
+ };
+ if (!source?.available) {
+ notVerified("the desktop app is not connected");
+ return;
+ }
+ let stored: string | undefined;
+ try {
+ stored = await source.get(INTEGRITY_KEY_ID);
+ } catch (error) {
+ notVerified(`its key could not be read (${(error as Error).message})`);
+ return;
+ }
+ let key = parseIntegrityKey(stored);
+ if (!key) {
+ const created = newIntegrityKey();
+ try {
+ await this.verifiedPut(source, INTEGRITY_KEY_ID, created);
+ } catch (error) {
+ notVerified(`its key could not be stored (${(error as Error).message})`);
+ return;
+ }
+ key = Buffer.from(created, "hex");
+ }
+ this.integrityKey = key;
+ if (!this.loaded) return;
+ const record = this.loaded.record;
+ const signedBefore = stored !== undefined || (record !== undefined && "mac" in record);
+ if (!signedBefore) {
+ this.edited = true;
+ writePrivate(this.file, this.recordText());
+ this.log("signed connectors.json for the first time");
+ return;
+ }
+ if (record && macMatches(key, record)) return;
+ this.setAside();
+ }
+
/** Waits for the secrets {@link update} is still storing. */
async settled(): Promise<void> {
while (this.writes.size > 0) await Promise.allSettled([...this.writes]);
@@ -889,8 +973,9 @@ export class ConnectorStore {
* Moves the secrets files still hold into the app's store, once the app is there (S25.5): text
* secrets in `connectors.json`, then the sign-ins of the old sign-in home and of the engine's old
* `mcp-auth.json` (the daemon's own win). Each one is stored, read back, and compared before the
- * file loses it; when one fails, the files stay as they were and the next start tries again. A
- * file that is empty or cannot be read is skipped and does not stop the rest. Afterwards
+ * file loses it; when one fails, the files stay as they were and the next start tries again. An
+ * empty sign-in file is removed (logged); one that cannot be read or parsed is reported and left
+ * as it is, the rest still move, and the move is not marked done until it can be read. Afterwards
* `connectors.json` says so (`version: 2`), and sign-in files that appear later are reported once
* and left alone, never imported. Nothing secret is logged.
*/
@@ -1135,16 +1220,20 @@ export class ConnectorStore {
const moved = this.pending.size;
for (const [id, secret] of this.pending) this.cache.set(id, secret);
this.pending.clear();
+ this.edited = true;
writePrivate(this.file, this.recordText());
this.log(`moved ${moved} connector secrets from connectors.json into the app's secure store`);
}
if (!this.migrated) {
let moved = 0;
let dropped = 0;
+ // A file that could not be read may hold secrets: the move is not done until it is.
+ let unread = false;
// The daemon's own sign-ins first: they win over the engine's older ones.
for (const file of [this.authFile, this.legacyAuthFile]) {
const states = this.readSignIns(file);
- if (!states) continue;
+ if (states === "unread") unread = true;
+ if (!states || states === "unread") continue;
const refs: Record<string, string> = {};
try {
for (const [key, state] of Object.entries(states)) {
@@ -1171,18 +1260,20 @@ export class ConnectorStore {
this.applySignIns(refs);
unlinkSync(file);
}
+ if (moved > 0) this.log(`moved ${moved} connector sign-ins into the app's secure store`);
+ if (dropped > 0)
+ this.log(
+ `dropped ${dropped} sign-in${dropped === 1 ? "" : "s"} for a connector that is no longer added`,
+ );
+ if (unread) return;
if (existsSync(this.signinMcpFile)) unlinkSync(this.signinMcpFile);
try {
if (readdirSync(this.signinHome).length === 0) rmdirSync(this.signinHome);
} catch {}
this.migrated = true;
+ this.edited = true;
mkdirSync(this.options.dataDir, { recursive: true, mode: 0o700 });
writePrivate(this.file, this.recordText());
- if (moved > 0) this.log(`moved ${moved} connector sign-ins into the app's secure store`);
- if (dropped > 0)
- this.log(
- `dropped ${dropped} sign-in${dropped === 1 ? "" : "s"} for a connector that is no longer added`,
- );
}
this.reportPlanted();
}
@@ -1193,23 +1284,31 @@ export class ConnectorStore {
if ((await source.get(id)) !== secret) throw new Error("a secret did not read back the same");
}
- /** The sign-ins of an old file, by key; undefined when there is none, it is empty, or it cannot be read. */
- private readSignIns(file: string): Record<string, unknown> | undefined {
+ /**
+ * The sign-ins of an old file, by key; undefined when there is none or it is empty (an empty one
+ * holds nothing: it is removed, and that is logged). `"unread"` when it cannot be read or is not a
+ * list of sign-ins: it may hold secrets, so it is left as it is, reported, and tried again later.
+ */
+ private readSignIns(file: string): Record<string, unknown> | "unread" | undefined {
+ const unread = (why: string) => {
+ this.log(
+ `${file} ${why}; it may hold connector secrets and stays on disk as it is. The move into the app's secure store will be tried again at the next start; fix or remove the file`,
+ );
+ return "unread" as const;
+ };
let text: string;
try {
text = readFileSync(file, "utf8");
} catch (error) {
- if ((error as NodeJS.ErrnoException).code !== "ENOENT")
- this.log(`could not read ${file}; it was left as it is`);
- return undefined;
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
+ return unread("could not be read");
}
if (text.trim() === "") {
unlinkSync(file);
+ this.log(`removed ${file}: it was empty and held no sign-ins`);
return undefined;
}
- const states = signInStates(text);
- if (!states) this.log(`${file} is not a list of sign-ins; it was left as it is`);
- return states;
+ return signInStates(text) ?? unread("is not a list of sign-ins");
}
/** The added connector whose remote server an old sign-in key names (`mcp__<server>|<url>`). */
@@ -1247,6 +1346,36 @@ export class ConnectorStore {
return renderMcpJson(this.saved, this.computer, this.proxy);
}
+ /** Moves a changed `connectors.json` aside (private), and starts over with no connectors, signed. */
+ private setAside(): void {
+ const stamp = new Date().toISOString().replace(/[-:.]/g, "");
+ let target = join(this.options.dataDir, `connectors.rejected-${stamp}.json`);
+ for (let n = 2; existsSync(target); n++)
+ target = join(this.options.dataDir, `connectors.rejected-${stamp}-${n}.json`);
+ let moved = false;
+ try {
+ renameSync(this.file, target);
+ moved = true;
+ // A planted link is moved as a link; what it points to is never touched.
+ if (lstatSync(target).isFile()) chmodSync(target, 0o600);
+ } catch (error) {
+ this.log(`could not move connectors.json aside (${(error as Error).message}); it is replaced`);
+ }
+ this.saved = { connectors: {} };
+ this.pending.clear();
+ this.cache.clear();
+ // Nothing from the changed file is trusted: old sign-in files are reported, never imported.
+ this.migrated = true;
+ this.edited = true;
+ mkdirSync(this.options.dataDir, { recursive: true, mode: 0o700 });
+ writePrivate(this.file, this.recordText());
+ this.log(
+ `connectors.json was changed while Gentle Dot was closed (its signature does not match)${moved ? `; moved it to ${target}` : ""} and started with no connectors; the secrets in the app's secure store were not touched`,
+ );
+ this.onUpdated();
+ this.onSetAside(SET_ASIDE_NOTICE);
+ }
+
private log(line: string): void {
this.options.log?.(line);
}
@@ -1289,17 +1418,25 @@ export class ConnectorStore {
return true;
}
- /** `connectors.json`: each secret as `{"secretRef": "<id>"}`, or as the text it still was until it moves. */
+ /**
+ * `connectors.json`: each secret as `{"secretRef": "<id>"}`, or as the text it still was until it
+ * moves, and `mac`, its signature (S25.6). Without the key the daemon cannot sign: a signed record
+ * as it was read is kept byte for byte while nothing changed it, so its signature is never lost.
+ */
private recordText(): string {
- const record = { version: this.migrated ? 2 : 1, connectors: this.saved.connectors };
- return `${JSON.stringify(
- record,
- (_key, value: unknown) => {
- const ref = typeof value === "string" ? refId(value) : undefined;
- return ref === undefined ? value : (this.pending.get(ref) ?? { secretRef: ref });
- },
- 2,
- )}\n`;
+ const signedAtStart = this.loaded?.record !== undefined && "mac" in this.loaded.record;
+ if (!this.integrityKey && !this.edited && signedAtStart && this.loaded) return this.loaded.text;
+ const record = JSON.parse(
+ JSON.stringify(
+ { version: this.migrated ? 2 : 1, connectors: this.saved.connectors },
+ (_key, value: unknown) => {
+ const ref = typeof value === "string" ? refId(value) : undefined;
+ return ref === undefined ? value : (this.pending.get(ref) ?? { secretRef: ref });
+ },
+ ),
+ ) as Record<string, unknown>;
+ const signed = this.integrityKey ? { ...record, mac: recordMac(this.integrityKey, record) } : record;
+ return `${JSON.stringify(signed, null, 2)}\n`;
}
/**
@@ -1309,7 +1446,12 @@ export class ConnectorStore {
private load(): { state: ConnectorsState; renamed: boolean; version: number } {
let saved: { version?: unknown; connectors?: Record<string, Record<string, unknown> | undefined> };
try {
- saved = JSON.parse(readFileSync(this.file, "utf8"), (_key, value: unknown) => {
+ const text = readFileSync(this.file, "utf8");
+ this.loaded = { text };
+ const raw = JSON.parse(text) as unknown;
+ if (typeof raw === "object" && raw !== null && !Array.isArray(raw))
+ this.loaded.record = raw as Record<string, unknown>;
+ saved = JSON.parse(text, (_key, value: unknown) => {
const ref = (value as { secretRef?: unknown } | null)?.secretRef;
return typeof value === "object" && typeof ref === "string" && SECRET_ID.test(ref)
? secretRef(ref)
@@ -1547,6 +1689,8 @@ export class ConnectorManager {
onChanged: (restart: boolean) => void = () => {};
/** A change to the connector files made outside the Connectors screen was put back. */
onBlocked: () => void = () => {};
+ /** A `connectors.json` changed while the daemon was down was set aside; `notice` is for the user. */
+ onSetAside: (notice: string) => void = () => {};
/** Whether the current model accepts images; undefined when that is not known. */
imagesSupported: () => boolean | undefined = () => undefined;
private flow: Flow | undefined;
@@ -1561,6 +1705,7 @@ export class ConnectorManager {
constructor(options: ConnectorManagerOptions) {
this.options = options;
options.store.onReverted = () => this.onBlocked();
+ options.store.onSetAside = (notice) => this.onSetAside(notice);
}
/** Puts back connector files changed outside the Connectors screen (for example after a run). */
diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.ts
index fed053e..16a804c 100644
--- a/packages/daemon/src/daemon.ts
+++ b/packages/daemon/src/daemon.ts
@@ -254,8 +254,17 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),
});
+ // connectors.json as read at start is checked against its signature before anything rewrites it,
+ // watches it, or starts the engine (S25.6).
+ const integrity = connectorStore
+ .checkIntegrity()
+ .catch((error: Error) => log(`could not check connectors.json: ${error.message}`));
if (app) {
- app.handler = (method, params) => appRequest(method, params, bridge, connectors, app);
+ // Nothing the app asks changes connectors before connectors.json was checked (S25.6).
+ app.handler = async (method, params) => {
+ await integrity;
+ return appRequest(method, params, bridge, connectors, app);
+ };
// The computer helper belongs to the app that registered it (S24.7).
app.onClose(() => {
log("the desktop app's channel closed");
@@ -263,19 +272,11 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
// Secrets read from the app are forgotten; connectors that need one fail closed until it is back.
connectorStore.lock();
});
- // Secrets that files still hold move into the app's store, once.
- void connectorStore
- .migrate()
- .catch((error: Error) => log(`connector secrets were not moved: ${error.message}`));
} else
log(
"no desktop app channel: connector changes and approvals are refused, and connectors that need a secret fail closed",
);
- // The files as the daemon writes them (an older version kept a hash), then watched.
- connectorStore.enforce(false);
- connectorStore.watch();
-
const server = createServer((req, res) => {
const { pathname } = new URL(req.url ?? "/", "http://localhost");
if (pathname === "/upload") {
@@ -306,6 +307,17 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
});
port = (server.address() as AddressInfo).port;
+ // Listening first keeps the app's health check answered while its store is asked for the key.
+ await integrity;
+ // Secrets that files still hold move into the app's store, once.
+ if (app)
+ void connectorStore
+ .migrate()
+ .catch((error: Error) => log(`connector secrets were not moved: ${error.message}`));
+ // The files as the daemon writes them (an older version kept a hash), then watched.
+ connectorStore.enforce(false);
+ connectorStore.watch();
+
await supervisor.start().catch((error: Error) => log(`agent failed to start: ${error.message}; retrying`));
return {
diff --git a/packages/daemon/test/connector-integrity.test.ts b/packages/daemon/test/connector-integrity.test.ts
new file mode 100644
index 0000000..23d0bc9
--- /dev/null
+++ b/packages/daemon/test/connector-integrity.test.ts
@@ -0,0 +1,528 @@
+// connectors.json integrity (S25.6, T23e): every write carries an HMAC whose key lives only in the
+// desktop app's secure store; a file changed while the daemon was down is set aside (private), the
+// daemon starts with no connectors, and the user is told once; the first start after T23e signs the
+// current file; without the app the file is loaded unverified, and a write never breaks a signature.
+import { createHmac } from "node:crypto";
+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import type { ServerMessage, ServerPayload } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import WebSocket from "ws";
+import {
+ ConnectorManager,
+ ConnectorStore,
+ type CustomConnector,
+ INTEGRITY_KEY_ID,
+ SET_ASIDE_NOTICE,
+ secretRef,
+} from "../src/connectors.ts";
+import { type DotDaemon, startDaemon } from "../src/daemon.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
+import { fakeApp } from "./fake-app.ts";
+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
+
+const TOKEN = "discord-bot-token-5e1d7a90";
+const NOTION_TOKENS = "notion-signin-tokens-secret";
+
+const stores: ConnectorStore[] = [];
+const managers: ConnectorManager[] = [];
+const daemons: DotDaemon[] = [];
+const sockets: WebSocket[] = [];
+afterEach(async () => {
+ for (const manager of managers.splice(0)) manager.cancelAll();
+ for (const store of stores.splice(0)) store.close();
+ for (const ws of sockets.splice(0)) ws.close();
+ await Promise.all(daemons.splice(0).map((d) => d.close()));
+});
+
+/** The documented canonical form (docs/design.md "Security"): sorted keys, no whitespace. */
+function canonical(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
+ if (value !== null && typeof value === "object")
+ return `{${Object.keys(value)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`)
+ .join(",")}}`;
+ return JSON.stringify(value);
+}
+
+/** The MAC a record should carry under `keyHex`, computed independently of the daemon. */
+function expectedMac(keyHex: string, record: Record<string, unknown>): string {
+ const { mac: _mac, ...rest } = record;
+ return createHmac("sha256", Buffer.from(keyHex, "hex"))
+ .update(`gentle-dot/connectors.json/v1\n${canonical(rest)}`)
+ .digest("hex");
+}
+
+const readRecord = (dataDir: string) =>
+ JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8")) as Record<string, unknown> & {
+ connectors: Record<string, Record<string, unknown>>;
+ mac?: string;
+ };
+
+/** True when connectors.json carries a valid MAC under the key in `secrets`. */
+function validlySigned(dataDir: string, secrets: Map<string, string>): boolean {
+ const key = secrets.get(INTEGRITY_KEY_ID);
+ const record = readRecord(dataDir);
+ return key !== undefined && typeof record.mac === "string" && record.mac === expectedMac(key, record);
+}
+
+const rejectedFiles = (dataDir: string) =>
+ readdirSync(dataDir).filter((name) => /^connectors\.rejected-.+\.json$/.test(name));
+
+/** Every file below `dir` whose bytes contain `needle`. */
+function filesContaining(dir: string, needle: string): string[] {
+ const found: string[] = [];
+ const walk = (folder: string) => {
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
+ const path = join(folder, entry.name);
+ if (entry.isDirectory()) walk(path);
+ else if (entry.isFile() && readFileSync(path).includes(needle)) found.push(path);
+ }
+ };
+ walk(dir);
+ return found;
+}
+
+function storeWith(dataDir: string, secrets?: MemorySecretSource, logs: string[] = []) {
+ const store = new ConnectorStore({
+ dataDir,
+ agentHome: join(dataDir, "agent"),
+ ...(secrets ? { secrets } : {}),
+ log: (line) => logs.push(line),
+ });
+ stores.push(store);
+ const notices: string[] = [];
+ store.onSetAside = (notice) => notices.push(notice);
+ return { store, notices };
+}
+
+/** A daemon start as far as the connectors go: load, verify, then put the files back as written. */
+async function started(dataDir: string, secrets?: MemorySecretSource, logs: string[] = []) {
+ const opened = storeWith(dataDir, secrets, logs);
+ await opened.store.checkIntegrity();
+ opened.store.enforce(false);
+ return opened;
+}
+
+const PLAIN: CustomConnector = {
+ name: "Plain",
+ description: "",
+ origin: "Drafted by the assistant",
+ server: { command: "plain-mcp", args: ["--stdio"] },
+ fields: [],
+ oauth: false,
+};
+
+/** A signed install: Discord with a token in the app's store, and a plain connector. */
+async function signedInstall() {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ const { store } = await started(dataDir, source);
+ await store.keepValues("discord", { token: TOKEN });
+ store.update((state) => {
+ state.connectors.discord = { ...state.connectors.discord, enabled: true, mode: "read_only" };
+ state.connectors.plain = { enabled: true, mode: "read_only", custom: PLAIN };
+ });
+ store.close();
+ return { dataDir, source };
+}
+
+describe("connectors.json is signed on every write (S25.6)", () => {
+ it("carries a valid MAC whose key is only in the app's store, never in a file or a log", async () => {
+ const logs: string[] = [];
+ const { dataDir, source } = await signedInstall();
+ const key = source.values.get(INTEGRITY_KEY_ID) ?? "";
+ expect(key).toMatch(/^[0-9a-f]{64}$/);
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ expect(readRecord(dataDir).connectors.discord?.values).toEqual({
+ token: { secretRef: "connector/discord/value/token" },
+ });
+ expect(statSync(join(dataDir, "connectors.json")).mode & 0o777).toBe(0o600);
+ const { store } = await started(dataDir, source, logs);
+ expect(Object.keys(store.state().connectors).sort()).toEqual(["discord", "plain"]);
+ expect(rejectedFiles(dataDir)).toEqual([]);
+ expect(filesContaining(dataDir, key)).toEqual([]);
+ expect(filesContaining(dataDir, TOKEN)).toEqual([]);
+ expect(logs.join("\n")).not.toContain(key);
+ });
+});
+
+describe("a file changed while the daemon was down is set aside", () => {
+ const tamperings: [string, (record: ReturnType<typeof readRecord>) => void][] = [
+ [
+ "an edited value",
+ (record) => {
+ record.connectors.discord = { ...record.connectors.discord, mode: "read_write" };
+ },
+ ],
+ [
+ "an added connector",
+ (record) => {
+ record.connectors.extra = { enabled: true, mode: "read_write", custom: PLAIN };
+ },
+ ],
+ [
+ "a removed mac",
+ (record) => {
+ delete record.mac;
+ },
+ ],
+ [
+ "a mac from another key",
+ (record) => {
+ record.connectors.plain = { enabled: false, mode: "read_only", custom: PLAIN };
+ record.mac = expectedMac("ab".repeat(32), record);
+ },
+ ],
+ ];
+ for (const [name, tamper] of tamperings)
+ it(`refuses ${name}: moved aside privately, no connectors loaded, the user told once`, async () => {
+ const { dataDir, source } = await signedInstall();
+ const record = readRecord(dataDir);
+ tamper(record);
+ const tampered = JSON.stringify(record);
+ writeFileSync(join(dataDir, "connectors.json"), tampered);
+ const logs: string[] = [];
+ const { store, notices } = await started(dataDir, source, logs);
+ const [aside, ...more] = rejectedFiles(dataDir);
+ expect(more).toEqual([]);
+ expect(aside).toMatch(/^connectors\.rejected-\d{8}T\d{6}(\d{3})?Z(-\d+)?\.json$/);
+ expect(readFileSync(join(dataDir, aside ?? ""), "utf8")).toBe(tampered);
+ expect(statSync(join(dataDir, aside ?? "")).mode & 0o777).toBe(0o600);
+ expect(store.state().connectors).toEqual({});
+ expect(readRecord(dataDir).connectors).toEqual({});
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ expect(notices).toEqual([SET_ASIDE_NOTICE]);
+ expect(logs.filter((line) => line.includes("changed while Gentle Dot was closed"))).toHaveLength(1);
+ // The secrets in the app's store are not touched.
+ expect(source.values.get("connector/discord/value/token")).toBe(TOKEN);
+ store.enforce();
+ expect(notices).toHaveLength(1);
+ });
+
+ it("keeps working after a restart: a fresh signed record, nothing set aside again", async () => {
+ const { dataDir, source } = await signedInstall();
+ writeFileSync(join(dataDir, "connectors.json"), JSON.stringify({ version: 2, connectors: {} }));
+ (await started(dataDir, source)).store.close();
+ expect(rejectedFiles(dataDir)).toHaveLength(1);
+ const { store, notices } = await started(dataDir, source);
+ store.update((state) => {
+ state.connectors.plain = { enabled: true, mode: "read_only", custom: PLAIN };
+ });
+ store.close();
+ const again = await started(dataDir, source);
+ expect(notices).toEqual([]);
+ expect(again.notices).toEqual([]);
+ expect(rejectedFiles(dataDir)).toHaveLength(1);
+ expect(Object.keys(again.store.state().connectors)).toEqual(["plain"]);
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ });
+
+ it("refuses the planted-reference attack from L117 before any secret is read", async () => {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ const { store } = await started(dataDir, source);
+ source.values.set("connector/notion/signin", NOTION_TOKENS);
+ store.update((state) => {
+ state.connectors.notion = {
+ enabled: true,
+ mode: "read_only",
+ signIn: secretRef("connector/notion/signin"),
+ };
+ });
+ store.close();
+ const record = readRecord(dataDir);
+ record.connectors.evil = {
+ enabled: true,
+ mode: "read_only",
+ custom: {
+ ...PLAIN,
+ name: "Evil",
+ server: { command: "/bin/sh", env: { X: { secretRef: "connector/notion/signin" } } },
+ },
+ signIn: { secretRef: "connector/notion/signin" },
+ };
+ writeFileSync(join(dataDir, "connectors.json"), JSON.stringify(record));
+ const reads: string[] = [];
+ const get = source.get.bind(source);
+ source.get = async (id: string) => {
+ reads.push(id);
+ return get(id);
+ };
+ const { store: restarted, notices } = await started(dataDir, source);
+ expect(notices).toEqual([SET_ASIDE_NOTICE]);
+ expect(restarted.state().connectors).toEqual({});
+ await expect(restarted.credentials("evil")).rejects.toThrow();
+ expect(reads.filter((id) => id.startsWith("connector/"))).toEqual([]);
+ });
+});
+
+describe("first start after T23e", () => {
+ it("signs an unsigned file without refusing it, and creates the key", async () => {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 2,
+ connectors: { plain: { enabled: true, mode: "read_only", custom: PLAIN } },
+ }),
+ );
+ const logs: string[] = [];
+ const { store, notices } = await started(dataDir, source, logs);
+ expect(notices).toEqual([]);
+ expect(rejectedFiles(dataDir)).toEqual([]);
+ expect(Object.keys(store.state().connectors)).toEqual(["plain"]);
+ expect(source.values.get(INTEGRITY_KEY_ID)).toMatch(/^[0-9a-f]{64}$/);
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ store.close();
+ expect((await started(dataDir, source)).notices).toEqual([]);
+ });
+
+ it("an unsigned file once the key exists is refused (it was signed before)", async () => {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ (await started(dataDir, source)).store.close();
+ expect(source.values.has(INTEGRITY_KEY_ID)).toBe(true);
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 2,
+ connectors: { plain: { enabled: true, mode: "read_write", custom: PLAIN } },
+ }),
+ );
+ const { store, notices } = await started(dataDir, source);
+ expect(notices).toEqual([SET_ASIDE_NOTICE]);
+ expect(store.state().connectors).toEqual({});
+ });
+});
+
+describe("without the app", () => {
+ it("loads the file unverified, says so, and never breaks its signature; the next start with the app verifies it", async () => {
+ const { dataDir, source } = await signedInstall();
+ const signed = readFileSync(join(dataDir, "connectors.json"), "utf8");
+ const logs: string[] = [];
+ const { store } = await started(dataDir, undefined, logs);
+ expect(Object.keys(store.state().connectors).sort()).toEqual(["discord", "plain"]);
+ expect(logs.some((line) => /connectors\.json was not verified/.test(line))).toBe(true);
+ // Changed while running: put back byte for byte, still signed.
+ writeFileSync(join(dataDir, "connectors.json"), "{}");
+ expect(store.enforce()).toBe(true);
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toBe(signed);
+ store.close();
+ const withApp = await started(dataDir, source);
+ expect(withApp.notices).toEqual([]);
+ expect(Object.keys(withApp.store.state().connectors).sort()).toEqual(["discord", "plain"]);
+ });
+
+ it("a file changed while down is loaded as today, then refused once the app is there", async () => {
+ const { dataDir, source } = await signedInstall();
+ const record = readRecord(dataDir);
+ (record.connectors.plain ?? {}).mode = "read_write";
+ writeFileSync(join(dataDir, "connectors.json"), JSON.stringify(record));
+ const { store } = await started(dataDir);
+ expect(store.state().connectors.plain?.mode).toBe("read_write");
+ store.close();
+ const withApp = await started(dataDir, source);
+ expect(withApp.notices).toEqual([SET_ASIDE_NOTICE]);
+ expect(withApp.store.state().connectors).toEqual({});
+ });
+});
+
+describe("normal connector flows keep a valid signature across restarts (regression)", () => {
+ it("connect, mode change, and remove", async () => {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ const open = async () => {
+ const { store, notices } = await started(dataDir, source);
+ const manager = new ConnectorManager({ store });
+ managers.push(manager);
+ return { store, notices, manager };
+ };
+ const first = await open();
+ const sent: ServerPayload[] = [];
+ const owner = {};
+ first.manager.connect(owner, "discord", (payload) => sent.push(payload));
+ const prompt = await waitFor(() => sent.find((m) => m.type === "auth_prompt"));
+ if (prompt.type !== "auth_prompt") throw new Error("no prompt");
+ first.manager.reply(owner, prompt.prompt.flowId, { value: TOKEN });
+ await waitFor(() => sent.find((m) => m.type === "auth_done"));
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ first.store.close();
+
+ const second = await open();
+ expect(second.notices).toEqual([]);
+ expect(second.manager.setMode("discord", "read_write")).toBeUndefined();
+ expect(readRecord(dataDir).connectors.discord?.mode).toBe("read_write");
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ second.store.close();
+
+ const third = await open();
+ expect(third.notices).toEqual([]);
+ expect(third.store.state().connectors.discord?.mode).toBe("read_write");
+ expect(await third.manager.remove("discord")).toBeUndefined();
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ third.store.close();
+
+ const fourth = await open();
+ expect(fourth.notices).toEqual([]);
+ expect(fourth.store.state().connectors).toEqual({});
+ expect(rejectedFiles(dataDir)).toEqual([]);
+ });
+});
+
+describe("legacy sign-in files the migration cannot read (A2, L117)", () => {
+ it("an unparsable mcp-auth.json is reported and retried, never marked as moved", async () => {
+ const dataDir = tempDir();
+ const agentHome = join(dataDir, "agent");
+ mkdirSync(agentHome, { recursive: true });
+ writeFileSync(join(dataDir, "connectors.json"), JSON.stringify({ version: 1, connectors: {} }));
+ const legacy = join(agentHome, "mcp-auth.json");
+ writeFileSync(legacy, '{"mcp__notion|https://mcp.notion.com/mcp": {"tokens": {"access_token": "half');
+ const source = new MemorySecretSource();
+ const logs: string[] = [];
+ const { store } = await started(dataDir, source, logs);
+ await store.migrate();
+ expect(existsSync(legacy)).toBe(true);
+ expect(readRecord(dataDir).version).toBe(1);
+ const reports = () => logs.filter((line) => line.includes(legacy) && /will be tried again/.test(line));
+ expect(reports()).toHaveLength(1);
+ expect(logs.join("\n")).not.toContain("half");
+ store.close();
+ const next = await started(dataDir, source, logs);
+ await next.store.migrate();
+ expect(reports()).toHaveLength(2);
+ expect(readRecord(dataDir).version).toBe(1);
+ writeFileSync(legacy, "{}");
+ await next.store.migrate();
+ expect(existsSync(legacy)).toBe(false);
+ expect(readRecord(dataDir).version).toBe(2);
+ expect(validlySigned(dataDir, source.values)).toBe(true);
+ });
+
+ it("a 0-byte mcp-auth.json is removed and reported, not silently", async () => {
+ const dataDir = tempDir();
+ const agentHome = join(dataDir, "agent");
+ mkdirSync(agentHome, { recursive: true });
+ writeFileSync(join(dataDir, "connectors.json"), JSON.stringify({ version: 1, connectors: {} }));
+ const legacy = join(agentHome, "mcp-auth.json");
+ writeFileSync(legacy, "");
+ const logs: string[] = [];
+ const { store } = await started(dataDir, new MemorySecretSource(), logs);
+ await store.migrate();
+ expect(existsSync(legacy)).toBe(false);
+ expect(logs.some((line) => line.includes(legacy) && /empty/.test(line))).toBe(true);
+ expect(readRecord(dataDir).version).toBe(2);
+ });
+});
+
+/** A daemon with the fake app (or none) and a window connected over the WebSocket. */
+async function daemonWith(dataDir: string, app?: ReturnType<typeof fakeApp>, logs: string[] = []) {
+ const d = await startDaemon({
+ port: 0,
+ host: "127.0.0.1",
+ dataDir,
+ workspace: join(dataDir, "workspace"),
+ uiDir: dataDir,
+ agentCommand: process.execPath,
+ agentArgs: [FAKE_AGENT],
+ agentHome: join(dataDir, "agent"),
+ backoffMs: [50],
+ authRuntime: async () => fakeAuthRuntime().runtime,
+ ...(app ? { appChannel: app.daemonEnd } : {}),
+ log: (line) => logs.push(line),
+ });
+ daemons.push(d);
+ return d;
+}
+
+async function window(d: DotDaemon) {
+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);
+ sockets.push(ws);
+ const messages: ServerMessage[] = [];
+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));
+ await new Promise((resolve) => ws.on("open", resolve));
+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));
+ await waitFor(() => messages.find((m) => m.type === "ready"));
+ return messages;
+}
+
+const setAsideToasts = (messages: ServerMessage[]) =>
+ messages.filter((m) => m.type === "toast" && m.message === SET_ASIDE_NOTICE);
+
+describe("the daemon checks connectors.json with the app (S25.6)", () => {
+ it("sets a changed file aside at start and tells the window; a restart starts clean", async () => {
+ const dataDir = tempDir();
+ const app = fakeApp();
+ app.secrets.set(INTEGRITY_KEY_ID, "cd".repeat(32));
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 2,
+ connectors: { plain: { enabled: true, mode: "read_write", custom: PLAIN } },
+ }),
+ );
+ const logs: string[] = [];
+ const d = await daemonWith(dataDir, app, logs);
+ const messages = await window(d);
+ await waitFor(() => setAsideToasts(messages).length > 0);
+ expect(setAsideToasts(messages)).toHaveLength(1);
+ expect(setAsideToasts(messages)[0]).toMatchObject({ level: "warning" });
+ expect(rejectedFiles(dataDir)).toHaveLength(1);
+ expect(logs.filter((line) => line.includes("changed while Gentle Dot was closed"))).toHaveLength(1);
+ const mcp = JSON.parse(readFileSync(join(dataDir, "agent", "mcp.json"), "utf8"));
+ expect(Object.keys(mcp.mcpServers ?? {})).not.toContain("plain");
+ await d.close();
+ daemons.splice(daemons.indexOf(d), 1);
+
+ // The app launches a new daemon: a new channel, the same Keychain.
+ const relaunched = fakeApp();
+ for (const [id, secret] of app.secrets) relaunched.secrets.set(id, secret);
+ const again = await daemonWith(dataDir, relaunched, logs);
+ const later = await window(again);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect(setAsideToasts(later)).toEqual([]);
+ expect(rejectedFiles(dataDir)).toHaveLength(1);
+ expect(validlySigned(dataDir, relaunched.secrets)).toBe(true);
+ });
+
+ it("puts back a change made while running, still signed", async () => {
+ const dataDir = tempDir();
+ const app = fakeApp();
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 2,
+ connectors: { plain: { enabled: true, mode: "read_only", custom: PLAIN } },
+ }),
+ );
+ const d = await daemonWith(dataDir, app);
+ expect(validlySigned(dataDir, app.secrets)).toBe(true);
+ const signed = readFileSync(join(dataDir, "connectors.json"), "utf8");
+ const record = readRecord(dataDir);
+ (record.connectors.plain ?? {}).mode = "read_write";
+ writeFileSync(join(dataDir, "connectors.json"), JSON.stringify(record));
+ await waitFor(() => readFileSync(join(dataDir, "connectors.json"), "utf8") === signed);
+ expect(validlySigned(dataDir, app.secrets)).toBe(true);
+ expect(rejectedFiles(dataDir)).toEqual([]);
+ expect(d.supervisor.state).not.toBe("error");
+ });
+
+ it("without the app, loads the file unverified and logs it", async () => {
+ const dataDir = tempDir();
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 2,
+ connectors: { plain: { enabled: true, mode: "read_only", custom: PLAIN } },
+ }),
+ );
+ const logs: string[] = [];
+ await daemonWith(dataDir, undefined, logs);
+ expect(logs.some((line) => /connectors\.json was not verified/.test(line))).toBe(true);
+ expect(rejectedFiles(dataDir)).toEqual([]);
+ expect(readRecord(dataDir).mac).toBeUndefined();
+ });
+});