A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
fix(security): fail closed when connectors.json cannot be checked
Alan Buscaglia118b4ac8ce04
diff --git a/docs/design.md b/docs/design.mdindex 37ef2fe..6b3ff35 100644--- a/docs/design.md+++ b/docs/design.md@@ -144,7 +144,7 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete- 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 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).+- 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, 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. With the app but a key that cannot be read or stored, the check fails closed: the file stays as it is, no secret is read, and every window gets "Gentle Dot could not check your connectors, so the ones that need a secret stay locked. Restart Gentle Dot to try again." A signed file deleted while Gentle Dot was closed (the key exists, the file is gone) starts with no connectors and every window gets "Your connectors file was removed while Gentle Dot was closed. Add your connectors again in Connectors." While running, a change is put back as before, signed. Limits: the signature has no counter, so putting back an older signed version of the file (for example one with a connector the user removed since) is accepted; sending actions still need the user's native approval. A same-user process that deletes the key's Keychain item and also removes `mac` makes the next start sign the file as a first start. 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.diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex 01e4224..c66fc5b 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -47,6 +47,12 @@ 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.";+/** The app is there but the integrity key could not be read or stored: nothing that needs a secret runs (A1, L120). */+export const INTEGRITY_UNCHECKED =+ "Gentle Dot could not check your connectors, so the ones that need a secret stay locked. Restart Gentle Dot to try again.";+/** A signed `connectors.json` was deleted while Gentle Dot was closed (A3, L120). */+export const MISSING_NOTICE =+ "Your connectors file was removed while Gentle Dot was closed. Add your connectors again 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 {@@ -663,6 +669,8 @@ export class ConnectorStore {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;+ /** Set when the app is there but the file could not be checked: secrets stay locked until a start can (A1). */+ private unchecked = false;/** 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). */@@ -757,11 +765,18 @@ export class ConnectorStore {notVerified("the desktop app is not connected");return;}+ // With the app there, a check that cannot run fails closed: the file stays as it is and no+ // secret is read until a start that can check it (A1).+ const cannot = (why: string) => {+ this.unchecked = true;+ this.log(`connectors.json could not be checked: ${why}; connectors that need a secret stay locked`);+ this.onSetAside(INTEGRITY_UNCHECKED);+ };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})`);+ cannot(`its key could not be read (${(error as Error).message})`);return;}let key = parseIntegrityKey(stored);@@ -770,13 +785,20 @@ export class ConnectorStore {try {await this.verifiedPut(source, INTEGRITY_KEY_ID, created);} catch (error) {- notVerified(`its key could not be stored (${(error as Error).message})`);+ cannot(`its key could not be stored (${(error as Error).message})`);return;}key = Buffer.from(created, "hex");}this.integrityKey = key;- if (!this.loaded) return;+ if (!this.loaded) {+ // A file that was signed before is gone: say so instead of starting empty in silence (A3).+ if (stored !== undefined) {+ this.log("connectors.json was signed before and is missing; starting with no connectors");+ this.onSetAside(MISSING_NOTICE);+ }+ return;+ }const record = this.loaded.record;const signedBefore = stored !== undefined || (record !== undefined && "mac" in record);if (!signedBefore) {@@ -1098,6 +1120,7 @@ export class ConnectorStore {}private secrets(): SecretSource {+ if (this.unchecked) throw new SecretsUnavailableError(INTEGRITY_UNCHECKED);const source = this.options.secrets;if (!source?.available) throw new SecretsUnavailableError();return source;diff --git a/packages/daemon/test/connector-integrity.test.ts b/packages/daemon/test/connector-integrity.test.tsindex 23d0bc9..0348ec0 100644--- a/packages/daemon/test/connector-integrity.test.ts+++ b/packages/daemon/test/connector-integrity.test.ts@@ -3,7 +3,7 @@// 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 { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, 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";@@ -13,6 +13,8 @@ import {ConnectorStore,type CustomConnector,INTEGRITY_KEY_ID,+ INTEGRITY_UNCHECKED,+ MISSING_NOTICE,SET_ASIDE_NOTICE,secretRef,} from "../src/connectors.ts";@@ -259,6 +261,35 @@ describe("a file changed while the daemon was down is set aside", () => {});});+describe("when the check itself cannot run (A1, A3, L120)", () => {+ it("a key the app cannot read keeps the file as it is and every connector with a secret locked", async () => {+ const { dataDir, source } = await signedInstall();+ const before = readFileSync(join(dataDir, "connectors.json"), "utf8");+ const get = source.get.bind(source);+ source.get = async (id: string) => {+ if (id === INTEGRITY_KEY_ID) throw new Error("keychain unavailable");+ return get(id);+ };+ const { store, notices } = await started(dataDir, source);+ await expect(store.credentials("discord")).rejects.toThrow(INTEGRITY_UNCHECKED);+ expect(notices).toEqual([INTEGRITY_UNCHECKED]);+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toBe(before);+ // The next start that can read the key checks it and unlocks.+ source.get = get;+ store.close();+ const { store: next } = await started(dataDir, source);+ expect((await next.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });+ });++ it("a signed file deleted while Gentle Dot was closed is reported once", async () => {+ const { dataDir, source } = await signedInstall();+ rmSync(join(dataDir, "connectors.json"));+ const { store, notices } = await started(dataDir, source);+ expect(notices).toEqual([MISSING_NOTICE]);+ expect(store.state().connectors).toEqual({});+ });+});+describe("first start after T23e", () => {it("signs an unsigned file without refusing it, and creates the key", async () => {const dataDir = tempDir();