A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(vps): run the engine as another user, encrypt secrets, and require a web PIN
Alan Buscaglia35b942b934e5
diff --git a/Dockerfile b/Dockerfileindex 2b4b024..7c06d0f 100644--- a/Dockerfile+++ b/Dockerfile@@ -24,16 +24,23 @@ RUN apt-get update \# The engine's first-run setup needs `pi` on PATH; match the version the daemon bundles.&& PI_VERSION="$(node -p "require('/app/packages/daemon/node_modules/@earendil-works/pi-coding-agent/package.json').version")" \&& npm install -g "@earendil-works/pi-coding-agent@${PI_VERSION}" \+ # Server mode (S25.8): the daemon runs as root, the engine as dot, stdio connector servers as dotmcp.&& useradd --create-home dot \- # gentle-pi installs its gentle-ai binary with mode 0700 during the build (as root); the engine runs as dot.- && chown -R dot:dot /app+ && useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin dotmcp \+ # The daemon's code stays root's: readable and runnable by all, writable by no one else.+ # gentle-pi installs its gentle-ai binary with mode 0700 during the build; a+rX lets the engine run it.+ && chown -R root:root /app \+ && chmod -R a+rX,go-w /appCOPY --from=engram /go/bin/engram /usr/local/bin/engramCOPY docker/entrypoint.sh /usr/local/bin/gentle-dot-entrypoint-USER dotWORKDIR /home/dotENV GENTLE_DOT_HOST=0.0.0.0 \GENTLE_DOT_PORT=4317 \- GENTLE_DOT_DATA_DIR=/home/dot/.gentle-dot+ GENTLE_DOT_DATA_DIR=/home/dot/.gentle-dot \+ GENTLE_DOT_VPS=1 \+ GENTLE_DOT_ENGINE_USER=dot \+ GENTLE_DOT_CONNECTOR_USER=dotmcp \+ GENTLE_DOT_ENGRAM_DATA_DIR=/home/dot/.engramEXPOSE 4317HEALTHCHECK --interval=30s --timeout=5s CMD node -e "fetch('http://127.0.0.1:4317/health').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"ENTRYPOINT ["tini", "--", "gentle-dot-entrypoint"]diff --git a/README.md b/README.mdindex c2669ac..16acf82 100644--- a/README.md+++ b/README.md@@ -97,7 +97,7 @@ Attach files with the paperclip, drag and drop, or paste. Images go straight to| **Self-contained installers** | A macOS DMG and Linux `.deb` and Arch packages carry their own Node, engine, and Engram || **Stable signing** | A self-signed identity keeps macOS permissions across updates || **Isolated engine** | The assistant runs its own engine and home folder; it never touches your own agent setup |-| **Web and server** | The same interface in the browser, and a Docker setup for your own VPS behind HTTPS |+| **Web and server** | The same interface in the browser, and a Docker setup for your own VPS behind HTTPS, where the assistant runs as its own user, connector secrets are encrypted, and connector changes need your PIN || **White label** | Built on [Gentle Shell](https://github.com/Gentleman-Programming/gentle-pi), presented as Gentle Dot |<div align="right"><a href="#top">Back to top</a></div>diff --git a/compose.yaml b/compose.yamlindex 91b2ea3..48aa964 100644--- a/compose.yaml+++ b/compose.yaml@@ -10,6 +10,21 @@ services:GENTLE_DOT_ALLOWED_ORIGINS: '["https://${DOT_DOMAIN}"]'ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}OPENAI_API_KEY: ${OPENAI_API_KEY:-}+ # Encrypts connector secrets at rest; only the daemon sees it (docs/deploy-vps.md, step 3).+ GENTLE_DOT_SECRETS_KEY: ${GENTLE_DOT_SECRETS_KEY:-}+ # The daemon runs as root in the container only to start the engine (dot) and connector servers+ # (dotmcp) as their own users; it keeps nothing else (docs/deploy-vps.md, "What runs as whom").+ security_opt:+ - no-new-privileges:true+ cap_drop:+ - ALL+ cap_add:+ - SETUID # start the engine and connector servers as their users+ - SETGID # with their own group and no supplementary groups+ - CHOWN # hand the files the daemon writes for the engine to the engine's user+ - FOWNER # keep the engine's folders private (chmod on folders the engine owns)+ - DAC_OVERRIDE # read and write the engine's folders (sessions, uploads, settings)+ - KILL # stop the engine and connector servers, which run as other usersvolumes:- dot-home:/home/dotports:diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 8f13d7d..a54352f 100755--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -1,5 +1,16 @@#!/bin/sh-# Starts the Gentle Dot daemon in the foreground. The engine starts its own memory server.+# Starts the Gentle Dot daemon in the foreground, as root inside the container: in server mode+# (GENTLE_DOT_VPS=1, docs/deploy-vps.md) it starts the engine as dot and stdio connector servers as+# dotmcp, and keeps its own files out of their reach. The engine starts its own memory server.set -eumkdir -p "$GENTLE_DOT_DATA_DIR"+if [ "${GENTLE_DOT_VPS:-}" = "1" ]; then+ # The volume's root is root's (an older image gave it to dot), so the engine cannot move the data+ # folder. Nothing of the engine runs yet, so handing its memory folder over here cannot race it.+ volume="$(dirname "$GENTLE_DOT_DATA_DIR")"+ chown root:root "$volume"+ chmod 0755 "$volume"+ mkdir -p "$GENTLE_DOT_ENGRAM_DATA_DIR"+ chown -R -P dot:dot "$GENTLE_DOT_ENGRAM_DATA_DIR"+fiexec node /app/packages/daemon/src/cli.tsdiff --git a/docs/deploy-vps.md b/docs/deploy-vps.mdindex 3b76739..a483c82 100644--- a/docs/deploy-vps.md+++ b/docs/deploy-vps.md@@ -12,6 +12,7 @@ Gentle Dot can read and write files and run commands. On a server, whoever reach- **Two locks.** Use the web server password (Basic Auth) *and* the Gentle Dot access key.- **Isolated machine.** The agent works inside its container volume. Never mount your personal folders, SSH keys, or another project's data.- **Your model key is a secret.** Keep it only in the server's `.env` file with `chmod 600`, and never commit it.+- **A PIN for what matters.** In the browser, connecting or changing a connector and allowing an action that sends something need a PIN you set the first time. The assistant never sees it.## What runs@@ -21,7 +22,31 @@ browser ──HTTPS──▶ Apache (cPanel) or Caddy ──▶ 127.0.0.1:4317└─ engram serve (memory)```-The image (`Dockerfile`) installs `gentle-pi` (it provides `gentle-shell`) and the matching `pi`, builds Engram, and builds the web UI. On its first start the container installs the assistant's companion packages, which takes about 15 seconds and needs internet access. The `dot-home` volume keeps conversations, memory, the access key, and the agent login across restarts.+The image (`Dockerfile`) installs `gentle-pi` (it provides `gentle-shell`) and the matching `pi`, builds Engram, and builds the web UI. On its first start the container installs the assistant's companion packages, which takes about 15 seconds and needs internet access. The `dot-home` volume keeps conversations, memory, the access key, the agent login, and the encrypted connector secrets across restarts.++### What runs as whom++The image runs in server mode (`GENTLE_DOT_VPS=1`). The assistant has a shell, so it is kept away from the daemon's files by the operating system, not by checks:++| Process | User | Reaches |+|---|---|---|+| Daemon (`node …/cli.ts`) | `root` in the container, with only the capabilities below | Everything in the volume |+| Agent, its tools and shell, its subagents, and its memory server | `dot` | Its own folders: `agent`, `home`, `workspace`, `sessions`, `gentle-ai` under `/home/dot/.gentle-dot`, and `/home/dot/.engram` |+| Connector servers the daemon starts (stdio, for example Discord) | `dotmcp` | Only its own home and working folder, `/home/dot/.gentle-dot/connector-home` |++- The data folder `/home/dot/.gentle-dot` is `root`'s with mode `0711`: the agent can reach its own folders by name but cannot list the folder or read the access key (`token`), `connectors.json`, the encrypted secrets (`secrets.enc.json`), or the PIN hash (`web-pin.json`), all `root`'s with mode `0600`. The daemon's code in `/app` is `root`'s and read-only for everyone else.+- Connector servers run as `dotmcp`, with their own home and working folder in `connector-home`, so they cannot see the agent's workspace: a server that works on files there (for example a filesystem MCP server pointed at the workspace) does not work on a server. The agent cannot read their environment, where their token is.+- Connector secrets (sign-ins, bot tokens, client secrets) are encrypted at rest with AES-256-GCM, each with its own nonce, under `GENTLE_DOT_SECRETS_KEY` (step 3). Only the daemon's environment holds it: it is never written to the volume and never passed to the agent or a connector server. Without it, connectors that need a secret stay off and say why. Secrets an older version kept in plain files move into the encrypted file once, at the first start with the key. Anyone who opens a shell in the container (`docker compose exec`) also gets it in their environment, as with every variable from `.env`.+- `connectors.json` is signed with a key kept in the same encrypted store, so a change made behind the daemon's back is set aside at the next start.+- The daemon keeps only these capabilities (`compose.yaml`), and `no-new-privileges` is on; the agent and connector servers run with none:++| Capability | Why the daemon needs it |+|---|---|+| `SETUID`, `SETGID` | Start the agent as `dot` and connector servers as `dotmcp`, without supplementary groups |+| `CHOWN` | Give the agent the files the daemon writes for it (`mcp.json`, sign-ins, settings, uploads) |+| `FOWNER` | Keep the agent's folders private (`chmod` on folders the agent owns) |+| `DAC_OVERRIDE` | Read and write in the agent's folders: history, uploads, settings |+| `KILL` | Stop the agent and connector servers, which run as other users |## Steps@@ -50,9 +75,12 @@ DOT_PORT=4317ANTHROPIC_API_KEY=OPENAI_API_KEY=EOF+echo "GENTLE_DOT_SECRETS_KEY=$(openssl rand -base64 32)" >> .envchmod 600 .env```+`GENTLE_DOT_SECRETS_KEY` encrypts the connectors' secrets. Keep a copy of `.env` somewhere safe outside the server: a backup of the volume without this key cannot open them, and losing it means signing in to every connector again.+Fill in one model key, or leave both empty and sign in from the browser once Gentle Dot is open (step 6): open **Accounts**, or type `/login` in the chat, and choose a subscription or an API key. The sign-in is kept in the volume.For the Caddy option, also add `DOT_USER` and `DOT_PASSWORD_HASH`. Generate the hash with `docker run --rm caddy:2 caddy hash-password --plaintext 'your-password'`, and write every `$` as `$$`.@@ -96,6 +124,8 @@ Open `https://dot.example.com/#token=<your access key>`. The browser asks for thIf you left the model keys empty in step 3, sign in now: open **Accounts** (or type `/login`), pick a subscription or an API key, and follow the steps on screen.+The first time you connect a connector or change what it may do, the page asks you to create a PIN (6 to 12 digits). From then on, connecting, disconnecting, removing, switching a connector to read and send, importing servers, and allowing an action that sends something (an email, a message, a page) ask for it. Declining needs no PIN. After 5 wrong PINs in a row it locks for 15 minutes, also across restarts.+## Update, back up, roll back```bash@@ -117,6 +147,10 @@ Never run `docker compose down -v`: `-v` deletes the volume with your conversati| You want no usage metrics | The companion packages send anonymous usage metrics by default. Opt out with `docker compose exec gentle-dot gentle-ai telemetry disable`. || "The assistant is restarting" stays on | The agent cannot start; check `docker compose logs gentle-dot` for the reason. || "Connect an AI account first" | No account is connected. Open **Accounts** (or type `/login`) and sign in, or add a model key to `.env` and run `docker compose up -d`. |+| "Connectors that need a secret are off on this server" | `GENTLE_DOT_SECRETS_KEY` is missing or not 32 bytes. Add it to `.env` (step 3) and run `docker compose up -d`. |+| "The stored connector secrets cannot be opened" | The key changed. Put the old one back in `.env`, or remove the secrets and sign in to the connectors again: `docker compose exec gentle-dot rm /home/dot/.gentle-dot/secrets.enc.json`. |+| You forgot the PIN | Remove it on the server, then set a new one in the browser: `docker compose exec gentle-dot rm /home/dot/.gentle-dot/web-pin.json`. |+| "Server mode … needs the daemon to run as root" | The container was started as another user (`user:` in compose, `docker run -u`). Remove that; the daemon starts the agent as `dot` itself. |## Video outline (about 2 minutes)@@ -126,4 +160,4 @@ Never run `docker compose down -v`: `-v` deletes the volume with your conversati4. `docker compose up -d --build`, `curl` the health check, and read the access key from the container (step 4).5. In WHM: run AutoSSL, add the password file, and drop in the Apache include (step 5a).6. Open `https://dot.<domain>/#token=…` on a phone, and sign in from **Accounts** if there is no model key: same assistant, same memory.-7. Close with the safety rules: HTTPS, two locks, an isolated container.+7. Close with the safety rules: HTTPS, two locks, an isolated container, and a PIN the assistant never sees.diff --git a/docs/design.md b/docs/design.mdindex a352dfb..206e638 100644--- a/docs/design.md+++ b/docs/design.md@@ -288,6 +288,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.+- Server mode (S25.8, `GENTLE_DOT_VPS=1`, set only by the container image; `daemon/src/vps.ts`): the daemon runs as root in the container with only `SETUID`, `SETGID`, `CHOWN`, `FOWNER`, `DAC_OVERRIDE`, and `KILL` and `no-new-privileges`, and refuses server mode otherwise. It starts the engine as `dot` (`spawn` `uid`/`gid`; its tools, shell, subagents, and memory server inherit it) and its stdio connector servers as `dotmcp` through `setpriv` (no groups, no capabilities), with their own home and working folder in `<data>/connector-home`, so they cannot see the engine's workspace. The data folder is the daemon's (0711); the token, `connectors.json`, the secrets, and the PIN hash are the daemon's (0600); the engine's folders (`agent`, `home`, `workspace`, `sessions`, `gentle-ai`) are `dot`'s, and what the daemon writes there is handed over with `chown -R -P --from=0:0` (no links followed, only the daemon's own files). Without the app, connector secrets live in `<data>/secrets.enc.json`, AES-256-GCM per record (random nonce, the id as additional data) under `GENTLE_DOT_SECRETS_KEY`, which only the daemon's environment holds (removed from `process.env` at start and from every child's environment); without it, connectors that need a secret fail closed and say why; with it, secrets older files still hold move there once (`migrate`). Privileged actions from the web page need a PIN instead of the app: `pin_set` (once; a salted scrypt hash in `<data>/web-pin.json`), `pin_command {pin, command}` for a connector change (the PIN is its confirmation), and `pin_approve {requestId, pin}` for an approval shown as an ask with `method: "pin"` and the full preview (`ui_response confirmed:false` declines without it); 5 wrong tries in a row lock it for 15 minutes, persisted. With the app's channel nothing changes: the WebSocket gets `app_required`, also for the PIN messages, and secrets stay in the app's store.- 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. On Linux the app keeps connector secrets in the Secret Service (GNOME Keyring or KWallet), encrypted at rest; the Secret Service has no per-caller access list, so any same-user process, the agent's shell included, can read the items while the keyring is unlocked (S25.7, documented limit). The app channel, the MCP proxy, and native approvals work as on macOS: no child of the daemon holds the channel (checked in containers by `scripts/package/linux-cargo-check.mjs` and the package smoke). Without a Secret Service at start, the connectors' integrity key cannot be read, so connectors that need a secret stay locked until Gentle Dot restarts (`daemon.log` names the missing keyring; the assistant is told to restart); if the keyring goes away later, the assistant and `daemon.log` (`connector <id> cannot get its secrets: …`) name it. Only the Linux keyring message is passed on this way; other store refusals keep their earlier wording. Still open: 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.tsindex 0f09225..c1fc21d 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -9,17 +9,19 @@ import {type ConnectorInfo,type Features,isAppCommand,+ isPinCommand,isThinkingLevel,type MessageQueue,type ModelGroup,type ModelRef,+ PIN_REQUIRED,parseClientMessage,parseQueue,type RoleRoute,type ServerPayload,type VoiceCapability,} from "@gentle-dot/protocol";-import type { AppApproval, AppLink } from "./app-channel.ts";+import { APPROVAL_WAIT_MS, type AppApproval, type AppLink } from "./app-channel.ts";import type { AuthManager } from "./auth.ts";import type { ConnectorManager, ConnectorRefusal } from "./connectors.ts";import {@@ -44,6 +46,7 @@ import { DEFAULT_ROTATION, type RotationLimits, SessionRotator } from "./rotatioimport type { AgentRecord, AgentSupervisor, SupervisorEvent } from "./supervisor.ts";import { composePrompt, type StoredFile, splitAttachments, type UploadStore } from "./uploads.ts";import type { VoiceService } from "./voice.ts";+import type { PinGate } from "./web-pin.ts";import { isBlockedInput, presentText, shouldShowToast } from "./white-label.ts";export interface BridgeClient {@@ -65,6 +68,15 @@ export interface BridgeOptions {* connector changes and the only place approvals are answered. Without it they fail closed.*/app?: AppLink;+ /**+ * A server without the desktop app (S25.8): the web page makes connector changes and allows+ * sending actions with this PIN instead. Never set together with `app`.+ */+ pin?: PinGate;+ /** How long a PIN approval waits for an answer. Default 130 s, like the app's. */+ approvalWaitMs?: number;+ /** Server mode (S25.8): gives a handoff session to the engine's user. */+ handOver?: (paths: string[]) => void;/** How long switching conversations waits for a running answer to stop. Default 10 s. */stopTimeoutMs?: number;/** Optional parts of the app; by default one continuous chat. */@@ -117,6 +129,10 @@ 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>();+ /** The answer each open PIN approval waits for, by request id (S25.8). */+ private readonly pinWaiters = new Map<string, (allowed: boolean) => void>();+ /** Connector changes a window confirmed with the PIN: their own confirmation is not asked again. */+ private readonly pinConfirmed = new WeakSet<ClientMessage>();/** 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>();@@ -155,6 +171,7 @@ export class DotBridge {limits: options.rotation ?? DEFAULT_ROTATION,canRotate: () =>supervisor.state === "ready" && !supervisor.busy && this.asks.size === 0 && this.sending === 0,+ ...(options.handOver ? { handOver: options.handOver } : {}),log: (line) => this.log(line),});supervisor.onEvent((event) => this.onAgentEvent(event));@@ -179,6 +196,7 @@ export class DotBridge {*/askInApp(request: AppApproval, signal?: AbortSignal): Promise<boolean> {const app = this.options.app;+ if (!app?.connected && this.options.pin) return this.askWithPin(request, signal);if (!app?.connected) return Promise.reject(new Error(APP_REQUIRED));const requestId = `app-${randomUUID()}`;const ask: Ask = {@@ -193,6 +211,83 @@ export class DotBridge {return app.approve(request, signal).finally(() => this.resolveAsk(requestId));}+ /**+ * On a server (S25.8): every window shows the approval with its full preview, and it is allowed+ * only with the PIN (`pin_approve`). Declining, no answer in time, `signal`, or the run ending+ * resolve false.+ */+ private askWithPin(request: AppApproval, signal?: AbortSignal): Promise<boolean> {+ if (signal?.aborted) return Promise.resolve(false);+ const requestId = `pin-${randomUUID()}`;+ const preview = request.preview.map(+ ({ name, value }) => `${name}: ${typeof value === "string" ? value : JSON.stringify(value)}`,+ );+ const ask: Ask = {+ requestId,+ method: "pin",+ title: presentText(request.title ?? `Allow ${request.connector} to ${request.action}?`),+ message: presentText(+ [+ request.summary ?? `The assistant wants to ${request.action} in ${request.connector}.`,+ ...preview,+ ].join("\n\n"),+ ),+ };+ return new Promise<boolean>((resolve) => {+ const timer = setTimeout(+ () => this.resolveAsk(requestId),+ this.options.approvalWaitMs ?? APPROVAL_WAIT_MS,+ );+ this.pinWaiters.set(requestId, resolve);+ signal?.addEventListener("abort", () => this.resolveAsk(requestId), { once: true });+ this.asks.set(requestId, { ask, timer });+ this.broadcast({ type: "ask", ask });+ this.refreshState();+ });+ }++ /** A window's PIN message on a server (S25.8); without server mode they open nothing. */+ private async pinMessage(+ client: BridgeClient,+ message: Extract<ClientMessage, { type: "pin_set" | "pin_command" | "pin_approve" }>,+ ): Promise<void> {+ const pin = this.options.pin;+ if (!pin || this.options.app?.connected) {+ this.deliver(client, { type: "error", code: "app_required", message: APP_REQUIRED });+ return;+ }+ if (message.type === "pin_set") {+ const outcome = await pin.set(message.pin);+ if (outcome.ok) this.broadcast({ type: "pin_status", pin: pin.status() });+ else this.deliver(client, { type: "error", code: outcome.code, message: outcome.message });+ return;+ }+ if (message.type === "pin_approve" && this.asks.get(message.requestId)?.ask.method !== "pin") {+ this.deliver(client, {+ type: "error",+ code: "ask_not_found",+ message: "That question is no longer open.",+ });+ return;+ }+ const outcome = await pin.verify(message.pin);+ if (!outcome.ok) {+ this.deliver(client, { type: "error", code: outcome.code, message: outcome.message });+ if (outcome.code === "pin_locked") this.broadcast({ type: "pin_status", pin: pin.status() });+ return;+ }+ if (message.type === "pin_approve") {+ const waiter = this.pinWaiters.get(message.requestId);+ this.pinWaiters.delete(message.requestId);+ waiter?.(true);+ this.resolveAsk(message.requestId);+ return;+ }+ if (!isPinCommand(message.command)) return;+ this.pinConfirmed.add(message.command);+ await this.run(client, message.command);+ }+attach(client: BridgeClient): () => void {this.clients.add(client);const clientId = randomBytes(18).toString("base64url");@@ -205,6 +300,7 @@ export class DotBridge {...(this.supervisor.model ? { model: this.supervisor.model } : {}),features: this.features,...(this.options.voice ? { voice: this.options.voice.capability() } : {}),+ ...(this.options.pin && !this.options.app?.connected ? { pin: this.options.pin.status() } : {}),});if (this.queued()) this.deliver(client, { type: "queue", ...this.queue });for (const { ask } of this.asks.values()) this.deliver(client, { type: "ask", ask });@@ -222,8 +318,15 @@ export class DotBridge {/** A window's message. Connector changes come only from the desktop app (S25.2). */async handle(client: BridgeClient, message: ClientMessage): Promise<void> {+ if (message.type === "pin_set" || message.type === "pin_command" || message.type === "pin_approve") {+ await this.pinMessage(client, message);+ return;+ }if (isAppCommand(message)) {- this.deliver(client, { type: "error", code: "app_required", message: APP_REQUIRED });+ // On a server the PIN stands in for the app (S25.8); the computer helper is the desktop's only.+ if (this.options.pin && !this.options.app?.connected && isPinCommand(message))+ this.deliver(client, { type: "error", code: "pin_required", message: PIN_REQUIRED });+ else this.deliver(client, { type: "error", code: "app_required", message: APP_REQUIRED });return;}await this.run(client, message);@@ -338,6 +441,12 @@ export class DotBridge {this.deliver(client, { type: "error", code: "app_required", message: WAITING_IN_APP });return;}+ // Allowing needs the PIN (`pin_approve`); declining narrows nothing, so any window may.+ if (pending.ask.method === "pin") {+ if (message.confirmed === false || message.cancelled) this.resolveAsk(requestId);+ else this.deliver(client, { type: "error", code: "pin_required", message: PIN_REQUIRED });+ return;+ }const answer: Record<string, unknown> = {};if (message.cancelled) answer.cancelled = true;else if (message.confirmed !== undefined) answer.confirmed = message.confirmed;@@ -462,7 +571,7 @@ export class DotBridge {const emit = (payload: ServerPayload) => this.deliver(client, payload);const { draftId, approve } = message;const draft = this.options.connectors?.drafts().find((d) => d.draftId === draftId);- if (approve && draft && !(await this.confirmChange(client, draftApproval(draft)))) return;+ if (approve && draft && !(await this.confirmChange(client, draftApproval(draft), message))) return;const refused = this.requireConnectors().decideDraft(client, draftId, approve, emit);if (refused) this.deliver(client, { type: "error", ...refused });else this.broadcast({ type: "connector_draft_resolved", draftId, approved: approve });@@ -481,7 +590,10 @@ export class DotBridge {const connectors = this.requireConnectors();// The confirmed plan is what gets imported, whatever a later scan finds.const plan = connectors.importPlan(message.ids);- if (plan.choices.length > 0 && !(await this.confirmChange(client, importApproval(plan.choices))))+ if (+ plan.choices.length > 0 &&+ !(await this.confirmChange(client, importApproval(plan.choices), message))+ )return;this.deliver(client, {type: "connector_imported",@@ -658,7 +770,7 @@ export class DotBridge {const connectors = this.requireConnectors();const emit = (payload: ServerPayload) => this.deliver(client, payload);const widening = wideningApproval(connectors.list(), message);- if (widening && !(await this.confirmChange(client, widening))) return;+ if (widening && !(await this.confirmChange(client, widening, message))) return;let refused: ConnectorRefusal | undefined;switch (message.type) {case "connector_connect":@@ -687,7 +799,13 @@ export class DotBridge {* A change that widens what the assistant can reach, confirmed in the app's native dialog even* though the app sent it (S25.3). False, with a note for the window, when it was not allowed.*/- private async confirmChange(client: BridgeClient, request: AppApproval): Promise<boolean> {+ private async confirmChange(+ client: BridgeClient,+ request: AppApproval,+ message: ClientMessage,+ ): Promise<boolean> {+ // The PIN the user typed for this very change confirms it (S25.8).+ if (this.pinConfirmed.has(message)) return true;const allowed = await this.askInApp(request).catch(() => undefined);if (allowed === undefined) {this.deliver(client, { type: "error", code: "app_required", message: APP_REQUIRED });@@ -1211,6 +1329,9 @@ export class DotBridge {if (!entry) return;clearTimeout(entry.timer);this.asks.delete(requestId);+ // A PIN approval still waiting is refused: declined, timed out, or the run ended.+ this.pinWaiters.get(requestId)?.(false);+ this.pinWaiters.delete(requestId);this.broadcast({ type: "ask_resolved", requestId });this.refreshState();}diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex d171f1b..de1b4b1 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -6,6 +6,8 @@ import { loadConfig } from "./config.ts";import { APPROVAL_GUARD, bundledMcpCli } from "./connectors.ts";import { startDaemon, startupMessage } from "./daemon.ts";import { resolveEngramBin, runtimeDir } from "./runtime.ts";+import { SECRETS_KEY_VAR } from "./secret-file.ts";+import { loadVpsOptions } from "./vps.ts";import { IDENTITY_SOURCE } from "./white-label.ts";const log = (line: string) => process.stderr.write(`${new Date().toISOString()} ${line}\n`);@@ -37,6 +39,10 @@ async function main(): Promise<void> {// The desktop app that launched the daemon hands over its private channel on fd 3 (S25.1); it is// opened before anything is spawned, and refused if children would inherit it.const appChannel = inheritedAppSocket({ log });+ // Server mode only when GENTLE_DOT_VPS says so (S25.8). The secrets key is read once and removed+ // from the process environment, so no child the daemon starts can inherit it.+ const vps = loadVpsOptions(process.env, { uid: process.getuid?.() ?? -1 });+ delete process.env[SECRETS_KEY_VAR];const daemon = await startDaemon({port: config.port,host: config.host,@@ -49,6 +55,7 @@ async function main(): Promise<void> {...(config.agentHome ? { agentHome: config.agentHome } : {}),allowedOrigins: config.allowedOrigins,...(appChannel ? { appChannel } : {}),+ ...(vps ? { vps } : {}),log,});process.stdout.write(`${startupMessage(daemon.url, config.dataDir, process.stdout.isTTY === true)}\n`);diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex d532628..06854c8 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -1138,7 +1138,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();+ if (!source?.available) throw new SecretsUnavailableError(source?.unavailable);return source;}@@ -1225,7 +1225,7 @@ export class ConnectorStore {const name = specOf(id, saved)?.name ?? id;const locked =waiting || !this.options.secrets?.available- ? NO_APP+ ? (this.options.secrets?.unavailable ?? NO_APP): `A secret ${name} needs is missing from the app's secure store. Ask the user to set up ${name} again in Connectors.`;return { open, locked };}diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 02850b3..bec63af 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -34,10 +34,13 @@ import {import { MCP_PREFIX, McpProxy, type ProxiedConnector, type UpstreamCredentials } from "./mcp-proxy.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { type RotationLimits, rotationLimits } from "./rotation.ts";+import { FileSecretSource, SECRETS_FILE, SECRETS_KEY_VAR } from "./secret-file.ts";import { AppSecretSource } from "./secret-source.ts";import { AgentSupervisor } from "./supervisor.ts";import { UploadStore } from "./uploads.ts";import { VoiceService } from "./voice.ts";+import { CONNECTOR_HOME, chownHandOver, prepareVpsLayout, type VpsOptions } from "./vps.ts";+import { PIN_FILE, PinGate } from "./web-pin.ts";import { identityArgs } from "./white-label.ts";export interface DaemonOptions {@@ -76,6 +79,11 @@ export interface DaemonOptions {appChannel?: Duplex;/** How long an approval waits for the app's answer; default 130 s (the app declines at 120 s). */approvalWaitMs?: number;+ /**+ * Server mode (S25.8, `GENTLE_DOT_VPS`): the engine runs as another user, connector secrets are+ * encrypted in a daemon file, and without the app the web page uses a PIN for privileged actions.+ */+ vps?: VpsOptions;/** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */allowedOrigins?: string[];backoffMs?: number[];@@ -156,6 +164,10 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {]: [];let agentEnv = { ...(options.agentEnv ?? process.env) };+ // The server's secrets key is the daemon's only, whatever the engine is (S25.8).+ delete agentEnv[SECRETS_KEY_VAR];+ const vps = options.vps;+ const handOver = vps ? (vps.handOver ?? chownHandOver(vps.engine, log)) : undefined;const homeArgs: string[] = [];const memory = options.agentHome ? await privateMemory(agentEnv, options.dataDir, log) : undefined;if (options.agentHome) {@@ -181,7 +193,15 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {// The assistant's own engine: its subagents load the guard from its extensions folder (S25.4)....(options.agentHome ? { childGuard: true } : {}),env: agentEnv,- secrets: new AppSecretSource(app),+ // On a server without the app, an encrypted file with a key from the daemon's environment (S25.8).+ secrets:+ vps && !app+ ? new FileSecretSource({+ file: join(options.dataDir, SECRETS_FILE),+ key: vps.secretsKey,+ ...(vps.secretsKeyProblem ? { problem: vps.secretsKeyProblem } : {}),+ })+ : new AppSecretSource(app),log,});// The engine reaches every connector through the proxy (S25.4); its key changes with every launch.@@ -199,6 +219,9 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {...(options.connectorTransport ? { transport: options.connectorTransport } : {}),env: agentEnv,cwd: options.workspace,+ ...(vps?.connector+ ? { stdio: { user: vps.connector, home: join(options.dataDir, CONNECTOR_HOME) } }+ : {}),log,});connectorStore.onUpdated = () => proxy.sync();@@ -216,6 +239,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {cwd: options.workspace,dataDir: options.dataDir,env: agentEnv,+ ...(vps ? { user: vps.engine } : {}),// mcp.json is read when a session starts: put back anything not approved, and hand the guard// its policy from the daemon's memory, never from the files.// The proxy's key changes with every launch (after the check, so a change is still reported).@@ -228,6 +252,13 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {log("subagents are off for this engine start: their approval guard is not in place");env.GENTLE_PI_AGENTS = "0";}+ // What the daemon wrote for this launch (mcp.json, sign-ins, settings) becomes the engine's.+ handOver?.([+ agentHome,+ join(options.dataDir, "gentle-ai"),+ join(options.dataDir, "home"),+ join(options.dataDir, "sessions"),+ ]);return env;},// The first start in a new home installs the engine's companion packages.@@ -243,6 +274,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {configHome: join(options.dataDir, "gentle-ai"),agentHome,importPath: options.profilesImportPath ?? defaultImportPath(process.env),+ ...(handOver ? { handOver } : {}),});const connectors = new ConnectorManager({store: connectorStore,@@ -259,6 +291,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {});const uploads = new UploadStore({workspace: options.workspace,+ ...(handOver ? { handOver } : {}),...(options.uploadLimits ? { limits: options.uploadLimits } : {}),});const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);@@ -271,6 +304,9 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {voice,uploads,...(app ? { app } : {}),+ ...(vps && !app ? { pin: new PinGate({ file: join(options.dataDir, PIN_FILE) }) } : {}),+ ...(options.approvalWaitMs ? { approvalWaitMs: options.approvalWaitMs } : {}),+ ...(handOver ? { handOver } : {}),features: { conversations: options.conversations ?? process.env.GENTLE_DOT_CONVERSATIONS === "1" },rotation: options.rotation ?? rotationLimits(process.env),...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),@@ -294,7 +330,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();});- } else+ } else if (vps)+ log(+ `server mode: the engine runs as uid ${vps.engine.uid}; connector changes and approvals need the web PIN${vps.secretsKey ? "" : `; ${vps.secretsKeyProblem ?? "connector secrets are off"}`}`,+ );+ elselog("no desktop app channel: connector changes and approvals are refused, and connectors that need a secret fail closed; to use them, stop this assistant and open the Gentle Dot app, which starts its own",);@@ -364,10 +404,12 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {void close().catch(() => {});});+ // Server mode: the daemon's files stay its own, the engine's folders become the engine's (S25.8).+ if (vps && handOver) prepareVpsLayout(options.dataDir, handOver, vps.connector);// 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?.connected)+ // Secrets that files still hold move into the app's store, once; on a server, into its encrypted file.+ if (app?.connected || (vps && !app && vps.secretsKey))void connectorStore.migrate().catch((error: Error) => log(`connector secrets were not moved: ${error.message}`));diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.tsindex 561fd50..849323c 100644--- a/packages/daemon/src/isolation.ts+++ b/packages/daemon/src/isolation.ts@@ -76,6 +76,9 @@ const SUBAGENT_VARIABLES = ["GENTLE_PI_AGENTS_PI",];+/** What only the daemon may hold: the server's connector secrets key (S25.8). */+const DAEMON_ONLY = ["GENTLE_DOT_SECRETS_KEY"];+/** Subagents are on unless `GENTLE_DOT_SUBAGENTS` is `off`, `0`, or `false`. */export function subagentsEnabled(base: NodeJS.ProcessEnv): boolean {const value = base.GENTLE_DOT_SUBAGENTS?.trim().toLowerCase();@@ -112,6 +115,7 @@ export function ensureMemoryProject(workspace: string): void {* user's server. The user's own `ENGRAM_PORT` and `ENGRAM_URL` are kept.* `GENTLE_DOT_ENGRAM=private` instead runs a memory of its own under the* engine's home, on port 7438 (`GENTLE_DOT_ENGRAM_PORT` overrides it).+ * The server's connector secrets key (`GENTLE_DOT_SECRETS_KEY`, S25.8) is never passed on.* Subagents are on (`GENTLE_PI_AGENTS=1`) unless `GENTLE_DOT_SUBAGENTS=off`: their child engines* reach connectors only through the daemon's proxy, like the engine itself (S25.4).*@@ -134,7 +138,7 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeXDG_CACHE_HOME: join(home, ".cache"),XDG_STATE_HOME: join(home, ".local", "state"),};- for (const key of [...INHERITED_HOMES, ...SUBAGENT_VARIABLES]) delete env[key];+ for (const key of [...INHERITED_HOMES, ...SUBAGENT_VARIABLES, ...DAEMON_ONLY]) delete env[key];if (!base.TMPDIR) {env.TMPDIR = join(home, ".cache", "tmp");ensurePrivateDir(env.TMPDIR);diff --git a/packages/daemon/src/mcp-proxy.ts b/packages/daemon/src/mcp-proxy.tsindex c2957f6..7df69ca 100644--- a/packages/daemon/src/mcp-proxy.ts+++ b/packages/daemon/src/mcp-proxy.ts@@ -35,6 +35,7 @@ import {import { McpOAuthAuthorizationRequiredError } from "@earendil-works/pi-mcp/oauth";import { type ConnectorMode, isReadOnlyTool } from "./extensions/approval-guard.ts";import { NO_APP, SecretsUnavailableError } from "./secret-source.ts";+import { type OsUser, stdioCommand } from "./vps.ts";/** Where the engine reaches a connector: `/mcp/<id>`. */export const MCP_PREFIX = "/mcp/";@@ -84,6 +85,11 @@ export interface McpProxyOptions {/** The environment stdio servers start from (the engine's own), and their working folder. */env?: NodeJS.ProcessEnv;cwd?: string;+ /**+ * Server mode (S25.8): stdio servers run as this user, with this folder as their home and working+ * folder, out of reach of both the engine and the daemon's files.+ */+ stdio?: { user: OsUser; home: string };log?: (line: string) => void;}@@ -391,12 +397,24 @@ export class McpProxy {// Nothing listens for the server's own messages.openGetStream: false,});- const cwd = this.options.cwd ?? process.cwd();+ const stdio = this.options.stdio;+ const cwd = stdio?.home ?? this.options.cwd ?? process.cwd();+ const launch = stdioCommand(stdio?.user, expandHome(server.command), (server.args ?? []).map(expandHome));+ const home: Record<string, string> = stdio+ ? {+ HOME: stdio.home,+ XDG_CONFIG_HOME: join(stdio.home, ".config"),+ XDG_DATA_HOME: join(stdio.home, ".local", "share"),+ XDG_CACHE_HOME: join(stdio.home, ".cache"),+ XDG_STATE_HOME: join(stdio.home, ".local", "state"),+ TMPDIR: join(stdio.home, ".cache", "tmp"),+ }+ : {};return new StdioTransport({- command: expandHome(server.command),- ...(server.args ? { args: server.args.map(expandHome) } : {}),+ command: launch.command,+ ...(launch.args.length > 0 ? { args: launch.args } : {}),cwd: resolve(cwd, expandHome(server.cwd ?? ".")),- env: { ...stringEnv(this.options.env ?? process.env), ...credentials.env },+ env: { ...stringEnv(this.options.env ?? process.env), ...home, ...credentials.env },inheritEnv: false,stderr: "pipe",});diff --git a/packages/daemon/src/profiles.ts b/packages/daemon/src/profiles.tsindex 4da6162..86f2caf 100644--- a/packages/daemon/src/profiles.ts+++ b/packages/daemon/src/profiles.ts@@ -252,6 +252,8 @@ export interface ProfileStoreOptions {agentHome: string;/** Another setup's `profiles.json`, only ever read, for the one-time import. */importPath: string;+ /** Server mode (S25.8): gives what a write left in the engine's folders to the engine's user. */+ handOver?: (paths: string[]) => void;}export interface ImportResult {@@ -492,7 +494,15 @@ export class ProfileStore {}private enqueue<T>(task: () => T | Promise<T>): Promise<T> {- const run = this.queue.then(task, task);+ const { handOver, configHome, agentHome } = this.options;+ const write = async () => {+ try {+ return await task();+ } finally {+ handOver?.([configHome, agentHome]);+ }+ };+ const run = this.queue.then(write, write);this.queue = run.catch(() => {});return run;}diff --git a/packages/daemon/src/rotation.ts b/packages/daemon/src/rotation.tsindex 77cc6c4..e999663 100644--- a/packages/daemon/src/rotation.ts+++ b/packages/daemon/src/rotation.ts@@ -125,6 +125,8 @@ export interface RotatorOptions {canRotate: () => boolean;/** The engine's working folder, for a previous session without one. */cwd?: string;+ /** Server mode (S25.8): gives the handoff session to the engine's user, which opens and extends it. */+ handOver?: (paths: string[]) => void;log?: (line: string) => void;}@@ -173,6 +175,7 @@ export class SessionRotator {let seed: string;try {seed = await writeHandoffSession(file, handoffText(file), this.options.cwd);+ this.options.handOver?.([seed]);} catch (error) {this.log(`rotation skipped, the chat stays in ${file}: ${(error as Error).message}`);return false;diff --git a/packages/daemon/src/secret-file.ts b/packages/daemon/src/secret-file.tsnew file mode 100644index 0000000..5ef083a--- /dev/null+++ b/packages/daemon/src/secret-file.ts@@ -0,0 +1,155 @@+/**+ * Connector secrets on a server (S25.8, docs/deploy-vps.md): there is no desktop app and no OS+ * store, so the daemon keeps them in `<data>/secrets.enc.json` (mode 0600, in a folder the engine's+ * user cannot list). Each secret is encrypted on its own with AES-256-GCM: a random 12-byte nonce+ * per write, and its id as additional data, so a record moved to another id does not open. The key+ * is 32 bytes from `GENTLE_DOT_SECRETS_KEY`, read only from the daemon's environment; the daemon+ * never writes it to a file and never passes it to a child. Without it, or with another key, every+ * call fails closed with a reason the user can act on, and nothing is written.+ *+ * File: `{"version":1,"records":{"<id>":{"nonce":"<base64>","data":"<base64>","tag":"<base64>"}}}`.+ */+import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";+import { readFileSync, renameSync, writeFileSync } from "node:fs";+import { type SecretSource, SecretsUnavailableError } from "./secret-source.ts";++/** The daemon's environment variable with the key. */+export const SECRETS_KEY_VAR = "GENTLE_DOT_SECRETS_KEY";+/** The file's name in the data folder. */+export const SECRETS_FILE = "secrets.enc.json";++export const NO_SECRETS_KEY = `Connectors that need a secret are off on this server: set ${SECRETS_KEY_VAR} (32 random bytes in base64, for example from \`openssl rand -base64 32\`) and restart Gentle Dot.`;+export const BAD_SECRETS_KEY = `${SECRETS_KEY_VAR} must be 32 bytes in base64 or hex (for example from \`openssl rand -base64 32\`); connectors that need a secret are off until it is.`;+const CANNOT_OPEN = `The stored connector secrets cannot be opened with this ${SECRETS_KEY_VAR} (another key, or the file was changed); nothing was read or written.`;+const DAMAGED = `The stored connector secrets file is damaged; nothing was read or written. Restore it from a backup, or remove ${SECRETS_FILE} and sign in to the connectors again.`;++const ID = /^[A-Za-z0-9._:@/-]{1,200}$/;+const AAD = "gentle-dot/secrets/v1\n";++/** The key as bytes: 64 hex digits, or base64 (standard or URL-safe) of exactly 32 bytes. */+export function parseSecretsKey(text: string | undefined): Buffer | undefined {+ const value = text?.trim() ?? "";+ if (/^[0-9a-fA-F]{64}$/.test(value)) return Buffer.from(value, "hex");+ if (!/^[A-Za-z0-9+/_-]{43}=?$/.test(value)) return undefined;+ const key = Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/"), "base64");+ return key.length === 32 ? key : undefined;+}++interface SealedRecord {+ nonce: string;+ data: string;+ tag: string;+}++export interface FileSecretSourceOptions {+ file: string;+ /** Undefined when the key is missing or not valid; `problem` then says why. */+ key: Buffer | undefined;+ problem?: string;+}++export class FileSecretSource implements SecretSource {+ private readonly options: FileSecretSourceOptions;++ constructor(options: FileSecretSourceOptions) {+ this.options = options;+ }++ get available(): boolean {+ return this.options.key !== undefined;+ }++ get unavailable(): string | undefined {+ return this.options.key ? undefined : (this.options.problem ?? NO_SECRETS_KEY);+ }++ async get(id: string): Promise<string | undefined> {+ const records = this.read(id);+ const record = records[id];+ return record === undefined ? undefined : this.open(id, record);+ }++ async put(id: string, secret: string): Promise<void> {+ const records = this.readAll(id);+ records[id] = this.seal(id, secret);+ this.write(records);+ }++ async delete(id: string): Promise<boolean> {+ const records = this.readAll(id);+ if (records[id] === undefined) return false;+ delete records[id];+ this.write(records);+ return true;+ }++ async list(): Promise<string[]> {+ return Object.keys(this.read()).sort();+ }++ private key(): Buffer {+ const key = this.options.key;+ if (!key) throw new SecretsUnavailableError(this.options.problem ?? NO_SECRETS_KEY);+ return key;+ }++ /** The records as stored, after checking the key and the id; none when there is no file yet. */+ private read(id?: string): Record<string, SealedRecord> {+ this.key();+ if (id !== undefined && !ID.test(id)) throw new Error("That secret id is not valid.");+ let text: string;+ try {+ text = readFileSync(this.options.file, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};+ throw new SecretsUnavailableError(DAMAGED);+ }+ try {+ const parsed = JSON.parse(text) as { version?: unknown; records?: unknown };+ if (parsed.version === 1 && typeof parsed.records === "object" && parsed.records !== null)+ return parsed.records as Record<string, SealedRecord>;+ } catch {}+ throw new SecretsUnavailableError(DAMAGED);+ }++ /** Every record, each checked to open with this key: a write never mixes two keys in one file. */+ private readAll(id: string): Record<string, SealedRecord> {+ const records = this.read(id);+ for (const [name, record] of Object.entries(records)) this.open(name, record);+ return records;+ }++ private seal(id: string, secret: string): SealedRecord {+ const nonce = randomBytes(12);+ const cipher = createCipheriv("aes-256-gcm", this.key(), nonce);+ cipher.setAAD(Buffer.from(AAD + id, "utf8"));+ const data = Buffer.concat([cipher.update(secret, "utf8"), cipher.final()]);+ return {+ nonce: nonce.toString("base64"),+ data: data.toString("base64"),+ tag: cipher.getAuthTag().toString("base64"),+ };+ }++ private open(id: string, record: SealedRecord): string {+ try {+ const nonce = Buffer.from(record.nonce, "base64");+ const tag = Buffer.from(record.tag, "base64");+ if (nonce.length !== 12 || tag.length !== 16) throw new Error("bad record");+ const decipher = createDecipheriv("aes-256-gcm", this.key(), nonce);+ decipher.setAAD(Buffer.from(AAD + id, "utf8"));+ decipher.setAuthTag(tag);+ return Buffer.concat([decipher.update(Buffer.from(record.data, "base64")), decipher.final()]).toString(+ "utf8",+ );+ } catch {+ throw new SecretsUnavailableError(CANNOT_OPEN);+ }+ }++ private write(records: Record<string, SealedRecord>): void {+ const temp = `${this.options.file}.${process.pid}.tmp`;+ writeFileSync(temp, `${JSON.stringify({ version: 1, records })}\n`, { mode: 0o600 });+ renameSync(temp, this.options.file);+ }+}diff --git a/packages/daemon/src/secret-source.ts b/packages/daemon/src/secret-source.tsindex 659bc7e..3f1dc05 100644--- a/packages/daemon/src/secret-source.ts+++ b/packages/daemon/src/secret-source.ts@@ -5,7 +5,8 @@* the app's private channel (`secret_get`, `secret_put`, `secret_delete`, `secret_list`). The daemon* keeps them in memory only and never writes them to a file or a log. Without the app (a daemon it* only attached to, one started from a terminal, the web) there is no source, and connectors that- * need a secret fail closed with {@link NO_APP}; there is no file fallback.+ * need a secret fail closed with {@link NO_APP}; there is no file fallback. A server in server mode+ * (S25.8) has its own source instead: an encrypted file (`secret-file.ts`).*/import { APPROVAL_WAIT_MS, type AppChannel } from "./app-channel.ts";@@ -29,6 +30,8 @@ export class SecretsUnavailableError extends Error {export interface SecretSource {/** False while there is no app to ask; every call then rejects with {@link SecretsUnavailableError}. */readonly available: boolean;+ /** Why it is not available, when the source knows better than {@link NO_APP}; safe to show. */+ readonly unavailable?: string | undefined;/** The secret under `id`, or undefined when there is none. */get(id: string): Promise<string | undefined>;/** Stores `secret` under `id`, replacing any previous one. */diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.tsindex 4c25594..0cbdd21 100644--- a/packages/daemon/src/supervisor.ts+++ b/packages/daemon/src/supervisor.ts@@ -2,6 +2,7 @@ import { type ChildProcess, spawn } from "node:child_process";import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";import { join } from "node:path";import { encodeRecord, JsonlDecoder } from "./jsonl.ts";+import type { OsUser } from "./vps.ts";/** A record the agent wrote to stdout that is not a command response. */export type AgentRecord = { type: string; [key: string]: unknown };@@ -33,6 +34,8 @@ export interface SupervisorOptions {/** Directory for `sessions/` and `state.json` (the open session and the chains of rotated ones). */dataDir: string;env?: NodeJS.ProcessEnv;+ /** The user the agent runs as (server mode, S25.8); by default the daemon's own. */+ user?: OsUser;/** Runs before every spawn (first start, restart, respawn); returns variables added to `env`. */prepareSpawn?: () => NodeJS.ProcessEnv;/** Respawn delays; the last value repeats. Default 1s, 2s, 4s, 8s, 16s, 30s. */@@ -213,11 +216,12 @@ export class AgentSupervisor {}private spawnChild(): ChildProcess {- const { command, args = [], extraArgs = [], cwd, env, prepareSpawn } = this.options;+ const { command, args = [], extraArgs = [], cwd, env, prepareSpawn, user } = this.options;const child = spawn(command, [...args, "--mode", "rpc", "--session-dir", this.sessionDir, ...extraArgs], {cwd,env: { ...(env ?? process.env), ...prepareSpawn?.() },stdio: ["pipe", "pipe", "pipe"],+ ...(user ? { uid: user.uid, gid: user.gid } : {}),});this.child = child;const decoder = new JsonlDecoder(diff --git a/packages/daemon/src/uploads.ts b/packages/daemon/src/uploads.tsindex f1696cb..1a12ed1 100644--- a/packages/daemon/src/uploads.ts+++ b/packages/daemon/src/uploads.ts@@ -45,6 +45,8 @@ export interface UploadStoreOptions {/** How long an upload that was never sent is kept. Default one hour. */ttlMs?: number;now?: () => number;+ /** Server mode (S25.8): gives the stored files to the engine's user, which reads them. */+ handOver?: (paths: string[]) => void;}const UNSENT_TTL_MS = 60 * 60 * 1000;@@ -122,10 +124,12 @@ export class UploadStore {private readonly limits: AttachmentLimits;private readonly ttlMs: number;private readonly now: () => number;+ private readonly handOver: ((paths: string[]) => void) | undefined;private readonly batches = new Map<string, Batch>();constructor(options: UploadStoreOptions) {this.root = join(options.workspace, "uploads");+ this.handOver = options.handOver;this.limits = options.limits ?? ATTACHMENT_LIMITS;this.ttlMs = options.ttlMs ?? UNSENT_TTL_MS;this.now = options.now ?? Date.now;@@ -186,6 +190,7 @@ export class UploadStore {}const file: StoredFile = { name, size: written.size, mime: sniffMime(written.head), path };batch.files.set(name, file);+ this.handOver?.([this.root]);return {ok: true,file: { uploadId, name, size: file.size, mime: file.mime, path: `uploads/${uploadId}/${name}` },diff --git a/packages/daemon/src/vps.ts b/packages/daemon/src/vps.tsnew file mode 100644index 0000000..32f7d88--- /dev/null+++ b/packages/daemon/src/vps.ts@@ -0,0 +1,161 @@+/**+ * Server mode (S25.8, docs/deploy-vps.md): the container's daemon, explicitly turned on with+ * `GENTLE_DOT_VPS=1`; a desktop build never turns it on by itself. The daemon runs as root inside+ * its container (with only the capabilities compose.yaml grants) so it can start the engine as+ * another user (`GENTLE_DOT_ENGINE_USER`, default `dot`) and the stdio connector servers it runs as+ * a third one (`GENTLE_DOT_CONNECTOR_USER`, default `dotmcp`). The data folder is the daemon's+ * (0711: the engine passes through it to its own folders but cannot list it); the access key,+ * `connectors.json`, the encrypted secrets, and the PIN hash stay the daemon's (0600), and the+ * engine's folders ({@link ENGINE_DIRS}) belong to the engine's user. Files the daemon writes into+ * those folders are handed over with `chown -R -P --from=<daemon> <engine>`: GNU chown walks with+ * directory descriptors and never follows a link, and `--from` touches only what the daemon itself+ * created.+ */+import { spawnSync } from "node:child_process";+import { chmodSync, lchownSync, lstatSync, mkdirSync, readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { BAD_SECRETS_KEY, NO_SECRETS_KEY, parseSecretsKey, SECRETS_KEY_VAR } from "./secret-file.ts";++export interface OsUser {+ uid: number;+ gid: number;+}++export interface VpsOptions {+ /** The engine's user: the engine, its tools and shell, and its subagents run as it. */+ engine: OsUser;+ /** The user the daemon's stdio connector servers run as; never the engine's or the daemon's. */+ connector?: OsUser;+ /** The connector secrets key; undefined fails closed with `secretsKeyProblem`. */+ secretsKey?: Buffer | undefined;+ secretsKeyProblem?: string;+ /** Gives paths the daemon wrote in the engine's folders to the engine's user; default {@link chownHandOver}. */+ handOver?: (paths: string[]) => void;+}++/** The engine's own folders in the data folder (`<data>/<name>`). */+export const ENGINE_DIRS = ["agent", "home", "workspace", "sessions", "gentle-ai"] as const;+/** The stdio connector servers' home and working folder (`<data>/connector-home`), the connector user's. */+export const CONNECTOR_HOME = "connector-home";++export function vpsEnabled(env: NodeJS.ProcessEnv): boolean {+ return ["1", "on", "true"].includes(env.GENTLE_DOT_VPS?.trim().toLowerCase() ?? "");+}++/** A user by name (from `/etc/passwd` text) or as `uid:gid`. */+export function lookupUser(spec: string, passwd: string): OsUser {+ const ids = /^(\d+):(\d+)$/.exec(spec);+ if (ids) return { uid: Number(ids[1]), gid: Number(ids[2]) };+ for (const line of passwd.split("\n")) {+ const [name, , uid, gid] = line.split(":");+ if (name === spec && uid !== undefined && gid !== undefined && /^\d+$/.test(uid) && /^\d+$/.test(gid))+ return { uid: Number(uid), gid: Number(gid) };+ }+ throw new Error(`Server mode: there is no user ${spec} for Gentle Dot to run as.`);+}++/**+ * Server mode from the daemon's environment, or undefined when it is off. Throws when it is on but+ * the separation cannot be made: the daemon is not root, or a user is missing, root, or shared.+ */+export function loadVpsOptions(+ env: NodeJS.ProcessEnv,+ self: { uid: number; passwd?: string },+): VpsOptions | undefined {+ if (!vpsEnabled(env)) return undefined;+ if (self.uid !== 0)+ throw new Error(+ "Server mode (GENTLE_DOT_VPS) needs the daemon to run as root in its container, to start the engine as another user.",+ );+ const passwd = self.passwd ?? readFileSync("/etc/passwd", "utf8");+ const engine = lookupUser(env.GENTLE_DOT_ENGINE_USER || "dot", passwd);+ const connector = lookupUser(env.GENTLE_DOT_CONNECTOR_USER || "dotmcp", passwd);+ if (engine.uid === 0 || connector.uid === 0)+ throw new Error("Server mode: the engine and connector users must not be root.");+ if (engine.uid === connector.uid)+ throw new Error("Server mode: the engine and the connector servers need different users.");+ const text = env[SECRETS_KEY_VAR];+ const secretsKey = parseSecretsKey(text);+ return {+ engine,+ connector,+ secretsKey,+ ...(secretsKey ? {} : { secretsKeyProblem: text?.trim() ? BAD_SECRETS_KEY : NO_SECRETS_KEY }),+ };+}++/** The command that hands `paths` to `engine`: only entries `daemon` owns, never through a link. */+export function handOverCommand(engine: OsUser, daemon: OsUser, paths: string[]) {+ return {+ command: "chown",+ args: ["-R", "-P", `--from=${daemon.uid}:${daemon.gid}`, `${engine.uid}:${engine.gid}`, "--", ...paths],+ };+}++/** Hands paths over with GNU chown; a failure is logged, and the engine then cannot use those files. */+export function chownHandOver(engine: OsUser, log: (line: string) => void): (paths: string[]) => void {+ const daemon = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };+ return (paths) => {+ if (paths.length === 0) return;+ const { command, args } = handOverCommand(engine, daemon, paths);+ // `-f` is not used: a refusal must be seen. Missing paths are not an error worth a line.+ const result = spawnSync(command, args, { encoding: "utf8", env: { PATH: process.env.PATH ?? "" } });+ const problems = (result.stderr ?? "")+ .split("\n")+ .filter((line) => line && !/No such file or directory/.test(line));+ if (result.error || problems.length > 0)+ log(`could not give the engine its files: ${result.error?.message ?? problems.join("; ")}`);+ };+}++/** How the daemon starts a stdio connector server: as the connector user, with no groups or capabilities. */+export function stdioCommand(user: OsUser | undefined, command: string, args: readonly string[]) {+ if (!user) return { command, args: [...args] };+ return {+ command: "setpriv",+ args: [+ `--reuid=${user.uid}`,+ `--regid=${user.gid}`,+ "--clear-groups",+ "--inh-caps=-all",+ "--",+ command,+ ...args,+ ],+ };+}++/**+ * Lays out the data folder for server mode before the engine starts: the folder itself 0711 and the+ * daemon's, every entry that is not an engine folder the daemon's (an older image ran everything as+ * the engine's user), the identity prompt readable by name, the engine folders handed over, and+ * the connector servers' home given to the connector user.+ */+export function prepareVpsLayout(+ dataDir: string,+ handOver: (paths: string[]) => void,+ connector: OsUser | undefined,+): void {+ const self = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };+ lchownSync(dataDir, self.uid, self.gid);+ chmodSync(dataDir, 0o711);+ if (connector) {+ const home = join(dataDir, CONNECTOR_HOME);+ mkdirSync(home, { recursive: true, mode: 0o700 });+ // An entry of the daemon's own folder: no link can stand in for it.+ lchownSync(home, connector.uid, connector.gid);+ chmodSync(home, 0o700);+ }+ const engine = new Set<string>(ENGINE_DIRS);+ for (const name of ENGINE_DIRS) mkdirSync(join(dataDir, name), { recursive: true, mode: 0o700 });+ for (const name of readdirSync(dataDir)) {+ if (engine.has(name) || name === CONNECTOR_HOME) continue;+ const path = join(dataDir, name);+ const stat = lstatSync(path);+ if (stat.uid !== self.uid || stat.gid !== self.gid) lchownSync(path, self.uid, self.gid);+ // Only the identity prompt is the engine's to read; everything else stays private.+ if (!stat.isSymbolicLink())+ chmodSync(path, name === "identity.md" ? 0o644 : stat.isDirectory() ? 0o700 : 0o600);+ }+ handOver(ENGINE_DIRS.map((name) => join(dataDir, name)));+}diff --git a/packages/daemon/src/web-pin.ts b/packages/daemon/src/web-pin.tsnew file mode 100644index 0000000..c241166--- /dev/null+++ b/packages/daemon/src/web-pin.ts@@ -0,0 +1,177 @@+/**+ * The web PIN on a server (S25.8, docs/deploy-vps.md). Without the desktop app there is no native+ * dialog, so the web page confirms connector changes and sending actions with a PIN the user sets+ * on first use. Only a salted scrypt hash is kept, in `<data>/web-pin.json` (mode 0600, in a folder+ * the engine's user cannot list), compared in constant time. After {@link PIN_ATTEMPTS} wrong tries+ * in a row it is locked for {@link PIN_LOCK_MS}; the count and the lock are in the same file, so a+ * restart does not reset them. Checks run one at a time, so tries sent together still count one by+ * one. The PIN reaches the daemon over the WebSocket and goes nowhere else: not to the engine, not+ * to a log. Forgotten PIN: remove the file on the server (docs/deploy-vps.md), then set a new one.+ */+import { randomBytes, type ScryptOptions, scrypt, timingSafeEqual } from "node:crypto";+import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { PIN_PATTERN, type PinStatus } from "@gentle-dot/protocol";++export const PIN_FILE = "web-pin.json";+/** Wrong tries in a row before the PIN locks. */+export const PIN_ATTEMPTS = 5;+/** How long it stays locked. */+export const PIN_LOCK_MS = 15 * 60_000;++const SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const;+const HASH_BYTES = 32;++export type PinOutcome =+ | { ok: true }+ | {+ ok: false;+ code: "pin_required" | "pin_wrong" | "pin_locked" | "pin_invalid" | "pin_exists";+ message: string;+ };++interface Saved {+ version: 1;+ kdf: "scrypt";+ N: number;+ r: number;+ p: number;+ salt: string;+ hash: string;+ failures: number;+ lockedUntil: number;+}++const DAMAGED: PinOutcome = {+ ok: false,+ code: "pin_locked",+ message:+ "The PIN file on the server is damaged. Remove it on the server to set a new PIN (see the deploy guide).",+};++function derive(pin: string, salt: Buffer, options: ScryptOptions & { N: number }): Promise<Buffer> {+ return new Promise((resolve, reject) =>+ scrypt(pin, salt, HASH_BYTES, options, (error, key) => (error ? reject(error) : resolve(key))),+ );+}++export class PinGate {+ private readonly file: string;+ private readonly now: () => number;+ /** Every set and check, one after the other. */+ private queue: Promise<unknown> = Promise.resolve();++ constructor(options: { file: string; now?: () => number }) {+ this.file = options.file;+ this.now = options.now ?? Date.now;+ }++ status(): PinStatus {+ const saved = this.load();+ if (saved === undefined) return { set: false };+ if (saved === "damaged" || saved.lockedUntil > this.now()) return { set: true, locked: true };+ return { set: true };+ }++ /** Sets the PIN when there is none yet; never replaces one. */+ set(pin: string): Promise<PinOutcome> {+ return this.serial(async () => {+ if (!PIN_PATTERN.test(pin)) return { ok: false, code: "pin_invalid", message: "Use 6 to 12 digits." };+ const saved = this.load();+ if (saved === "damaged") return DAMAGED;+ if (saved !== undefined)+ return { ok: false, code: "pin_exists", message: "A PIN is already set for this assistant." };+ const salt = randomBytes(16);+ const hash = await derive(pin, salt, SCRYPT);+ const { N, r, p } = SCRYPT;+ this.save({+ version: 1,+ kdf: "scrypt",+ N,+ r,+ p,+ salt: salt.toString("base64"),+ hash: hash.toString("base64"),+ failures: 0,+ lockedUntil: 0,+ });+ return { ok: true };+ });+ }++ /** Checks the PIN; a wrong one counts towards the lock. */+ verify(pin: string): Promise<PinOutcome> {+ return this.serial(async () => {+ const saved = this.load();+ if (saved === "damaged") return DAMAGED;+ if (saved === undefined) return { ok: false, code: "pin_required", message: "Set a PIN first." };+ if (saved.lockedUntil > this.now()) return this.locked(saved);+ const expected = Buffer.from(saved.hash, "base64");+ const given = PIN_PATTERN.test(pin)+ ? await derive(pin, Buffer.from(saved.salt, "base64"), {+ N: saved.N,+ r: saved.r,+ p: saved.p,+ maxmem: SCRYPT.maxmem,+ })+ : Buffer.alloc(expected.length);+ if (given.length === expected.length && timingSafeEqual(given, expected) && PIN_PATTERN.test(pin)) {+ if (saved.failures !== 0 || saved.lockedUntil !== 0)+ this.save({ ...saved, failures: 0, lockedUntil: 0 });+ return { ok: true };+ }+ const failures = saved.failures + 1;+ if (failures >= PIN_ATTEMPTS) {+ const lockedUntil = this.now() + PIN_LOCK_MS;+ this.save({ ...saved, failures: 0, lockedUntil });+ return this.locked({ ...saved, lockedUntil });+ }+ this.save({ ...saved, failures, lockedUntil: 0 });+ const left = PIN_ATTEMPTS - failures;+ return {+ ok: false,+ code: "pin_wrong",+ message: `Wrong PIN. ${left} ${left === 1 ? "try" : "tries"} left before it locks for ${PIN_LOCK_MS / 60_000} minutes.`,+ };+ });+ }++ private locked(saved: Saved): PinOutcome {+ const minutes = Math.max(1, Math.ceil((saved.lockedUntil - this.now()) / 60_000));+ return {+ ok: false,+ code: "pin_locked",+ message: `Too many wrong PINs. Try again in ${minutes} ${minutes === 1 ? "minute" : "minutes"}.`,+ };+ }++ private serial<T>(run: () => Promise<T>): Promise<T> {+ const next = this.queue.then(run, run);+ this.queue = next.catch(() => undefined);+ return next;+ }++ /** The saved PIN, undefined when none was set, or `damaged` when the file cannot be trusted. */+ private load(): Saved | undefined | "damaged" {+ if (!existsSync(this.file)) return undefined;+ try {+ const saved = JSON.parse(readFileSync(this.file, "utf8")) as Partial<Saved>;+ const numbers = [saved.N, saved.r, saved.p, saved.failures, saved.lockedUntil];+ if (+ saved.version === 1 &&+ saved.kdf === "scrypt" &&+ numbers.every((n) => Number.isSafeInteger(n) && (n as number) >= 0) &&+ typeof saved.salt === "string" &&+ typeof saved.hash === "string" &&+ Buffer.from(saved.hash, "base64").length === HASH_BYTES+ )+ return saved as Saved;+ } catch {}+ return "damaged";+ }++ private save(saved: Saved): void {+ const temp = `${this.file}.${process.pid}.tmp`;+ writeFileSync(temp, `${JSON.stringify(saved)}\n`, { mode: 0o600 });+ renameSync(temp, this.file);+ }+}diff --git a/packages/daemon/test/cli.test.ts b/packages/daemon/test/cli.test.tsindex 32bc1d3..be0e465 100644--- a/packages/daemon/test/cli.test.ts+++ b/packages/daemon/test/cli.test.ts@@ -38,6 +38,37 @@ describe("gentle-dot command", () => {expect(statSync(dataDir).mode & 0o777).toBe(0o700);});+ it.skipIf((process.getuid?.() ?? 0) === 0)(+ "refuses server mode it cannot keep: GENTLE_DOT_VPS as a user that is not root (S25.8)",+ async () => {+ const dataDir = join(tempDir(), "data");+ const child = spawn(process.execPath, [CLI], {+ env: {+ ...process.env,+ GENTLE_DOT_VPS: "1",+ GENTLE_DOT_DATA_DIR: dataDir,+ GENTLE_DOT_PORT: "0",+ GENTLE_DOT_AGENT_BIN: process.execPath,+ GENTLE_DOT_AGENT_ARGS: JSON.stringify([FAKE_AGENT]),+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ for (const stream of [child.stdout, child.stderr])+ stream.on("data", (chunk: Buffer) => {+ output += chunk.toString();+ });+ const code = await Promise.race([+ new Promise((resolve) => child.on("close", resolve)),+ new Promise((resolve) => setTimeout(() => resolve("still running"), 10_000)),+ ]);+ if (code === "still running") child.kill("SIGTERM");+ expect(code).toBe(1);+ expect(output).toMatch(/failed to start: Server mode .* root/);+ expect(output).not.toContain("Gentle Dot is running");+ },+ );+it("a daemon launched with the app's channel exits when the app goes (S35.2, #22)", async () => {const dataDir = join(tempDir(), "data");const { app, daemon } = await socketPair();diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex fab9bd9..21086d7 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -38,6 +38,8 @@// FAKE_AGENT_DROP_CUSTOM load session files without their custom messages (a format drift)// FAKE_AGENT_PROMPTS_FILE append every prompt command (message, images, streamingBehavior) as JSONL// FAKE_AGENT_MARKER_FILE write whether the `--home` folder held gentle-shell's `.gentle-shell-home` at launch+// FAKE_AGENT_PROCESS_FILE write the whole environment, argv, and the process's uid and gid as JSON+// FAKE_AGENT_STDIN_FILE append every line the daemon writes to the agent's stdin// get_available_models lists MODELS; set_model and set_thinking_level change what// get_state reports, so tests can read the last values back. A model's `input` says whether it// accepts images, like the engine's models.@@ -106,6 +108,12 @@ if (process.env.FAKE_AGENT_ENV_FILE) {),);}+if (process.env.FAKE_AGENT_PROCESS_FILE) {+ writeFileSync(+ process.env.FAKE_AGENT_PROCESS_FILE,+ JSON.stringify({ env: process.env, argv, uid: process.getuid?.(), gid: process.getgid?.() }),+ );+}const sessionDir = argValue("--session-dir") ?? join(process.cwd(), ".fake-sessions");mkdirSync(sessionDir, { recursive: true });@@ -533,6 +541,8 @@ process.stdin.on("data", (chunk: string) => {while (newline >= 0) {const line = buffer.slice(0, newline).replace(/\r$/, "");buffer = buffer.slice(newline + 1);+ if (line && process.env.FAKE_AGENT_STDIN_FILE)+ appendFileSync(process.env.FAKE_AGENT_STDIN_FILE, `${line}\n`);if (line) handle(JSON.parse(line) as Rec);newline = buffer.indexOf("\n");}diff --git a/packages/daemon/test/isolation.test.ts b/packages/daemon/test/isolation.test.tsindex 120ec46..1314862 100644--- a/packages/daemon/test/isolation.test.ts+++ b/packages/daemon/test/isolation.test.ts@@ -124,6 +124,19 @@ describe("isolatedAgentEnv subagents", () => {});});+describe("isolatedAgentEnv secrets key", () => {+ it("never passes the server's secrets key to the engine, and keeps everything else (S25.8)", () => {+ const env = isolatedAgentEnv(+ { HOME: tempDir(), GENTLE_DOT_SECRETS_KEY: "server-only-key", OPENAI_API_KEY: "sk-model", LANG: "C" },+ tempDir(),+ );+ expect(env).not.toHaveProperty("GENTLE_DOT_SECRETS_KEY");+ // The model keys and the rest of the environment are the engine's, as before.+ expect(env.OPENAI_API_KEY).toBe("sk-model");+ expect(env.LANG).toBe("C");+ });+});+describe("isolatedAgentEnv temporary folder", () => {it("gives the engine a private TMPDIR when none is set, so its caches never land in a shared /tmp", () => {const dataDir = tempDir();diff --git a/packages/daemon/test/secret-file.test.ts b/packages/daemon/test/secret-file.test.tsnew file mode 100644index 0000000..89796dd--- /dev/null+++ b/packages/daemon/test/secret-file.test.ts@@ -0,0 +1,104 @@+// Connector secrets on a server (S25.8): no desktop app, so the daemon keeps them in a file of its+// own, each one encrypted with AES-256-GCM under a key that only the daemon's environment holds.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { FileSecretSource, NO_SECRETS_KEY, parseSecretsKey } from "../src/secret-file.ts";+import { SecretsUnavailableError } from "../src/secret-source.ts";+import { tempDir } from "./helpers.ts";++const SECRET = "xoxb-plain-bot-token-0123456789";++function store(key: Buffer | undefined) {+ const file = join(tempDir(), "secrets.enc.json");+ return { file, key, source: new FileSecretSource({ file, key }) };+}++describe("encrypted secrets file", () => {+ it("stores a secret that only the same key reads back, with no plaintext on disk", async () => {+ const { file, key, source } = store(randomBytes(32));+ expect(source.available).toBe(true);+ await source.put("connector/slack/bot", SECRET);+ await source.put("integrity/connectors", "a".repeat(64));+ const text = readFileSync(file, "utf8");+ expect(text).not.toContain(SECRET);+ expect(text).not.toContain(Buffer.from(SECRET).toString("base64"));+ expect(text).not.toContain("a".repeat(64));+ expect(statSync(file).mode & 0o777).toBe(0o600);+ // Every record has its own nonce: the same secret twice is two different ciphertexts.+ await source.put("connector/discord/bot", SECRET);+ const records = JSON.parse(readFileSync(file, "utf8")).records as Record<+ string,+ { data: string; nonce: string }+ >;+ expect(records["connector/slack/bot"]?.nonce).not.toBe(records["connector/discord/bot"]?.nonce);+ expect(records["connector/slack/bot"]?.data).not.toBe(records["connector/discord/bot"]?.data);++ const again = new FileSecretSource({ file, key });+ expect(await again.get("connector/slack/bot")).toBe(SECRET);+ expect(await again.get("missing/one")).toBeUndefined();+ expect(await again.list()).toEqual([+ "connector/discord/bot",+ "connector/slack/bot",+ "integrity/connectors",+ ]);+ expect(await again.delete("connector/discord/bot")).toBe(true);+ expect(await again.delete("connector/discord/bot")).toBe(false);+ expect(await again.list()).toEqual(["connector/slack/bot", "integrity/connectors"]);+ });++ it("fails closed without a key, saying which variable to set, and writes nothing", async () => {+ const { file, source } = store(undefined);+ expect(source.available).toBe(false);+ await expect(source.put("connector/slack/bot", SECRET)).rejects.toThrow(SecretsUnavailableError);+ await expect(source.get("connector/slack/bot")).rejects.toThrow(/GENTLE_DOT_SECRETS_KEY/);+ await expect(source.list()).rejects.toThrow(NO_SECRETS_KEY);+ expect(existsSync(file)).toBe(false);+ });++ it("refuses a wrong key without changing the file", async () => {+ const { file, source } = store(randomBytes(32));+ await source.put("connector/slack/bot", SECRET);+ const before = readFileSync(file, "utf8");+ const wrong = new FileSecretSource({ file, key: randomBytes(32) });+ await expect(wrong.get("connector/slack/bot")).rejects.toThrow(SecretsUnavailableError);+ await expect(wrong.get("connector/slack/bot")).rejects.toThrow(/cannot be opened/);+ // A wrong key never writes: a put or a delete would mix two keys in one file.+ await expect(wrong.put("connector/notion/token", "other")).rejects.toThrow(/cannot be opened/);+ await expect(wrong.delete("connector/slack/bot")).rejects.toThrow(/cannot be opened/);+ expect(readFileSync(file, "utf8")).toBe(before);+ });++ it("detects a changed ciphertext and a record moved to another id", async () => {+ const { file, key, source } = store(randomBytes(32));+ await source.put("connector/slack/bot", SECRET);+ await source.put("connector/notion/token", "notion-token");+ const saved = JSON.parse(readFileSync(file, "utf8"));+ const flipped = structuredClone(saved);+ const data = Buffer.from(flipped.records["connector/slack/bot"].data, "base64");+ data[0] = (data[0] ?? 0) ^ 1;+ flipped.records["connector/slack/bot"].data = data.toString("base64");+ writeFileSync(file, JSON.stringify(flipped));+ await expect(new FileSecretSource({ file, key }).get("connector/slack/bot")).rejects.toThrow(+ SecretsUnavailableError,+ );+ // Each record is bound to its id: Slack's record under Notion's id does not open.+ const swapped = structuredClone(saved);+ swapped.records["connector/notion/token"] = saved.records["connector/slack/bot"];+ writeFileSync(file, JSON.stringify(swapped));+ await expect(new FileSecretSource({ file, key }).get("connector/notion/token")).rejects.toThrow(+ /cannot be opened/,+ );+ });++ it("reads the key as 32 bytes in base64 or hex, and nothing else", () => {+ const key = randomBytes(32);+ expect(parseSecretsKey(key.toString("base64"))).toEqual(key);+ expect(parseSecretsKey(key.toString("base64url"))).toEqual(key);+ expect(parseSecretsKey(key.toString("hex"))).toEqual(key);+ expect(parseSecretsKey(` ${key.toString("base64")}\n`)).toEqual(key);+ for (const text of [undefined, "", "short", randomBytes(16).toString("base64"), "z".repeat(64)])+ expect(parseSecretsKey(text), String(text)).toBeUndefined();+ });+});diff --git a/packages/daemon/test/supervisor.test.ts b/packages/daemon/test/supervisor.test.tsindex e9c2e35..a8b612c 100644--- a/packages/daemon/test/supervisor.test.ts+++ b/packages/daemon/test/supervisor.test.ts@@ -26,6 +26,33 @@ describe("AgentSupervisor", () => {expect(supervisor.state).toBe("ready");});+ it("starts the agent as the configured user, and as the daemon's own user without one (S25.8)", async () => {+ const own = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };+ const processFile = join(tempDir(), "process.json");+ const env = { ...process.env, FAKE_AGENT_PROCESS_FILE: processFile };+ // Without a user, the agent runs as the daemon does today.+ const plain = track(fakeSupervisor({ env }));+ await plain.supervisor.start();+ expect(JSON.parse(readFileSync(processFile, "utf8"))).toMatchObject(own);+ await plain.supervisor.stop();+ const as = track(fakeSupervisor({ env, user: own }));+ await as.supervisor.start();+ expect(JSON.parse(readFileSync(processFile, "utf8"))).toMatchObject(own);+ expect(as.supervisor.state).toBe("ready");+ });++ it.skipIf((process.getuid?.() ?? 0) === 0)(+ "applies the user to the spawn: one it cannot take is refused",+ async () => {+ const own = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };+ const { supervisor } = track(+ fakeSupervisor({ user: { uid: own.uid + 1, gid: own.gid }, startTimeoutMs: 2000 }),+ );+ await expect(supervisor.start()).rejects.toThrow();+ expect(supervisor.state).not.toBe("ready");+ },+ );+it("correlates responses by id across concurrent commands", async () => {const { supervisor } = track(fakeSupervisor());await supervisor.start();diff --git a/packages/daemon/test/vps-gateway.test.ts b/packages/daemon/test/vps-gateway.test.tsnew file mode 100644index 0000000..b2b0fc6--- /dev/null+++ b/packages/daemon/test/vps-gateway.test.ts@@ -0,0 +1,484 @@+// The daemon in server mode (S25.8), end to end with the fake agent: the engine runs as another+// user, the daemon's own files stay out of its reach, connector secrets are encrypted at rest with a+// key only the daemon's environment holds, and the web page changes connectors and allows sending+// actions only with a PIN the agent never sees. With the desktop app's channel, nothing changes.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { McpClient, type McpError, StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";+import { APP_REQUIRED, type ServerMessage } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DaemonOptions, type DotDaemon, startDaemon } from "../src/daemon.ts";+import { FileSecretSource } from "../src/secret-file.ts";+import { PIN_ATTEMPTS } from "../src/web-pin.ts";+import { fakeApp } from "./fake-app.ts";+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";+import { oauthOptions } from "./fake-oauth.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const PIN = "731942";+const SIGNED_IN_TOKEN = "access-token-1";+const own = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };+const ENGINE_DIRS = ["agent", "home", "workspace", "sessions", "gentle-ai"];++const TOOLS: Tool[] = [+ { name: "notion-search", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },+ { name: "notion-create-pages", inputSchema: { type: "object" } },+];++const daemons: DotDaemon[] = [];+const closers: (() => Promise<unknown>)[] = [];+afterEach(async () => {+ await Promise.all(closers.splice(0).map((close) => close().catch(() => undefined)));+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++interface Setup {+ app?: boolean;+ vps?: false | Partial<NonNullable<DaemonOptions["vps"]>>;+ env?: NodeJS.ProcessEnv;+ /** A `connectors.json` left by an older version, written before the daemon starts. */+ connectors?: object;+}++async function setup(options: Setup = {}) {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ if (options.connectors) writeFileSync(join(dataDir, "connectors.json"), JSON.stringify(options.connectors));+ const processFile = join(dataDir, "..", `${randomBytes(6).toString("hex")}-process.json`);+ const stdinFile = join(dataDir, "..", `${randomBytes(6).toString("hex")}-stdin.jsonl`);+ const key = randomBytes(32);+ const handedOver: string[][] = [];+ const logs: string[] = [];+ const notionCalls: string[] = [];+ const notionUrl = await fakeNotion(notionCalls);+ const app = fakeApp([], "allow");+ const fake = fakeAuthRuntime();+ const vps =+ options.vps === false+ ? undefined+ : {+ engine: own,+ connector: own,+ secretsKey: key,+ handOver: (paths: string[]) => handedOver.push(paths),+ ...options.vps,+ };+ 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,+ agentEnv: {+ ...process.env,+ FAKE_AGENT_PROCESS_FILE: processFile,+ FAKE_AGENT_STDIN_FILE: stdinFile,+ ...options.env,+ },+ backoffMs: [50],+ authRuntime: async () => fake.runtime,+ connectorOAuth: oauthOptions(true),+ connectorTransport: (_connector, credentials) =>+ new StreamableHttpTransport({+ url: notionUrl,+ ...(credentials.headers ? { headers: credentials.headers } : {}),+ ...(credentials.authProvider ? { authProvider: credentials.authProvider } : {}),+ openGetStream: false,+ }),+ approvalWaitMs: 1500,+ ...(options.app ? { appChannel: app.daemonEnd } : {}),+ ...(vps ? { vps } : {}),+ log: (line) => logs.push(line),+ });+ daemons.push(d);+ const window = await connect(d);+ const engineProcess = () =>+ JSON.parse(readFileSync(processFile, "utf8")) as {+ env: Record<string, string>;+ uid: number;+ argv: string[];+ };+ const stdin = () => (existsSync(stdinFile) ? readFileSync(stdinFile, "utf8") : "");+ const connectorsText = () => readFileSync(join(dataDir, "connectors.json"), "utf8");+ const mcpText = () => readFileSync(join(agentHome, "mcp.json"), "utf8");+ const engineClient = async (id: string) => {+ const entry = JSON.parse(mcpText()).mcpServers[id] as { url: string; headers: Record<string, string> };+ const client = new McpClient({ name: "engine", version: "1" });+ closers.push(() => client.close());+ await client.connect(new StreamableHttpTransport({ url: entry.url, headers: entry.headers }));+ return client;+ };+ return {+ d,+ dataDir,+ agentHome,+ key,+ app,+ logs,+ handedOver,+ notionCalls,+ engineProcess,+ stdin,+ connectorsText,+ mcpText,+ engineClient,+ ...window,+ };+}++/** Notion as far as the proxy can tell: plain JSON over HTTP, recording the tools it ran. */+async function fakeNotion(calls: string[]) {+ const server: Server = createServer((req, res) => {+ let body = "";+ req.on("data", (chunk: Buffer) => {+ body += chunk.toString("utf8");+ });+ req.on("end", () => {+ const message = JSON.parse(body) as { id?: number; method: string; params?: Record<string, unknown> };+ if (message.id === undefined) {+ res.writeHead(202).end();+ return;+ }+ if (message.method === "tools/call") calls.push(String(message.params?.name));+ const result =+ message.method === "initialize"+ ? {+ protocolVersion: message.params?.protocolVersion,+ capabilities: { tools: {} },+ serverInfo: { name: "notion", version: "1" },+ }+ : message.method === "tools/list"+ ? { tools: TOOLS }+ : { content: [{ type: "text", text: `notion ran ${String(message.params?.name)}` }] };+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));+ });+ });+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));+ closers.push(() => new Promise((done) => server.close(done)));+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`;+}++async function connect(d: DotDaemon) {+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ closers.push(async () => ws.close());+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));+ const send = (m: object) => ws.send(JSON.stringify(m));+ function find<T extends ServerMessage["type"]>(+ type: T,+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,+ after = 0,+ ) {+ return waitFor(() =>+ messages+ .slice(after)+ .find(+ (m): m is Extract<ServerMessage, { type: T }> =>+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),+ ),+ );+ }+ return { ws, messages, send, find, ready };+}++const settle = (ms = 200) => new Promise((resolve) => setTimeout(resolve, ms));+const mode = (connectorId: string, value: "read_only" | "read_write") => ({+ type: "connector_mode",+ connectorId,+ mode: value,+});++/** Connects Notion with the PIN (the stand-in OAuth signs in at once) and waits for the new engine. */+async function connectNotion(s: Awaited<ReturnType<typeof setup>>) {+ const pid = s.d.supervisor.pid;+ s.send({ type: "pin_command", pin: PIN, command: { type: "connector_connect", connectorId: "notion" } });+ await s.find("auth_done", (m) => m.ok);+ await waitFor(() => s.d.supervisor.pid !== pid && s.d.supervisor.state === "ready");+}++describe("server mode: the engine as another user (S25.8)", () => {+ it.skipIf(own.uid === 0)("starts the engine under the engine user's uid and gid", async () => {+ const { d, engineProcess } = await setup();+ await waitFor(() => d.supervisor.state === "ready");+ expect(engineProcess()).toMatchObject({ uid: own.uid });+ // A uid this test process cannot take: the spawn itself is refused, so the uid is applied.+ const other = await setup({ vps: { engine: { uid: own.uid + 1, gid: own.gid } } });+ await waitFor(() => other.logs.some((line) => /EPERM|agent failed to start/.test(line)));+ expect(other.d.supervisor.state).not.toBe("ready");+ });++ it("keeps the daemon's files private and hands the engine's folders to the engine user", async () => {+ const { d, dataDir, agentHome, handedOver, send, find } = await setup();+ await waitFor(() => d.supervisor.state === "ready");+ // The engine may pass through the data folder to its own folders, but not list it.+ expect(statSync(dataDir).mode & 0o777).toBe(0o711);+ expect(statSync(join(dataDir, "token")).mode & 0o777).toBe(0o600);+ // The engine reads its identity prompt by name.+ expect(statSync(join(dataDir, "identity.md")).mode & 0o777).toBe(0o644);+ for (const dir of ENGINE_DIRS) expect(statSync(join(dataDir, dir)).isDirectory(), dir).toBe(true);+ // At start every engine folder, and before every launch the ones the daemon writes into.+ expect(handedOver[0]?.slice().sort()).toEqual(ENGINE_DIRS.map((dir) => join(dataDir, dir)).sort());+ expect(+ handedOver.some((paths) => paths.includes(agentHome) && paths.includes(join(dataDir, "sessions"))),+ ).toBe(true);+ const launches = handedOver.length;+ await d.supervisor.restart();+ expect(handedOver.length).toBeGreaterThan(launches);+ // An uploaded file is the engine's to read.+ const upload = await fetch(`http://127.0.0.1:${d.port}/upload`, {+ method: "POST",+ headers: { authorization: `Bearer ${d.token}`, "x-file-name": "notes.txt" },+ body: "hello",+ });+ expect(upload.status).toBe(200);+ expect(handedOver.at(-1)).toEqual([join(dataDir, "workspace", "uploads")]);+ // So is what a profile change writes into its store and the engine's home.+ send({ type: "profile_save", name: "work", roles: {} });+ await find("profiles");+ expect(handedOver.at(-1)).toEqual([join(dataDir, "gentle-ai"), agentHome]);+ // Nothing of the daemon's own is ever handed over.+ const handed = handedOver.flat();+ for (const name of [+ "token",+ "connectors.json",+ "secrets.enc.json",+ "web-pin.json",+ "connector-signin",+ "config.json",+ ])+ expect(+ handed.some((path) => path === join(dataDir, name) || path.startsWith(`${join(dataDir, name)}/`)),+ name,+ ).toBe(false);+ });++ it("never passes the secrets key to the engine", async () => {+ const { d, engineProcess } = await setup({ env: { GENTLE_DOT_SECRETS_KEY: "do-not-leak-this-key" } });+ await waitFor(() => d.supervisor.state === "ready");+ const seen = JSON.stringify(engineProcess());+ expect(seen).not.toContain("GENTLE_DOT_SECRETS_KEY");+ expect(seen).not.toContain("do-not-leak-this-key");+ });+});++describe("server mode: connector secrets encrypted at rest (S25.8)", () => {+ it("keeps a sign-in only encrypted, in a daemon file the same key opens", async () => {+ const s = await setup();+ await waitFor(() => s.d.supervisor.state === "ready");+ s.send({ type: "pin_set", pin: PIN });+ await s.find("pin_status", (m) => m.pin.set);+ await connectNotion(s);+ const file = join(s.dataDir, "secrets.enc.json");+ await waitFor(() => existsSync(file) && readFileSync(file, "utf8").includes("connector/notion"));+ const text = readFileSync(file, "utf8");+ expect(text).not.toContain(SIGNED_IN_TOKEN);+ expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(s.mcpText()).not.toContain(SIGNED_IN_TOKEN);+ const ids = await new FileSecretSource({ file, key: s.key }).list();+ expect(ids).toEqual(expect.arrayContaining(["integrity/connectors"]));+ expect(ids.some((id) => id.startsWith("connector/notion"))).toBe(true);+ });++ it("moves a secret an older version left in connectors.json into the encrypted file, once", async () => {+ const token = "older-discord-bot-token-0123";+ const s = await setup({+ connectors: {+ version: 1,+ connectors: { discord: { enabled: true, mode: "read_only", values: { token } } },+ },+ });+ await waitFor(() => s.d.supervisor.state === "ready");+ await waitFor(() => !s.connectorsText().includes(token));+ const file = join(s.dataDir, "secrets.enc.json");+ expect(readFileSync(file, "utf8")).not.toContain(token);+ expect(await new FileSecretSource({ file, key: s.key }).get("connector/discord/value/token")).toBe(token);+ expect(JSON.parse(s.connectorsText()).connectors.discord.values).toEqual({+ token: { secretRef: "connector/discord/value/token" },+ });+ });++ it("without the key, connectors that need a secret fail closed with the reason", async () => {+ const s = await setup({ vps: { secretsKey: undefined } });+ await waitFor(() => s.d.supervisor.state === "ready");+ s.send({ type: "pin_set", pin: PIN });+ await s.find("pin_status", (m) => m.pin.set);+ s.send({ type: "pin_command", pin: PIN, command: { type: "connector_connect", connectorId: "notion" } });+ const failed = await waitFor(() =>+ s.messages.find(+ (m) =>+ (m.type === "auth_done" && !m.ok) ||+ (m.type === "error" && /GENTLE_DOT_SECRETS_KEY/.test(m.message)),+ ),+ );+ expect(JSON.stringify(failed)).toMatch(/GENTLE_DOT_SECRETS_KEY/);+ expect(existsSync(join(s.dataDir, "secrets.enc.json"))).toBe(false);+ });+});++describe("server mode: the web PIN (S25.8)", () => {+ it("asks for a PIN for connector changes, sets it on first use, and stores only its hash", async () => {+ const s = await setup();+ await waitFor(() => s.d.supervisor.state === "ready");+ expect(s.ready).toMatchObject({ type: "ready", pin: { set: false } });+ const before = existsSync(join(s.dataDir, "connectors.json")) ? s.connectorsText() : "";+ s.send(mode("notion", "read_write"));+ expect(await s.find("error", (m) => m.code === "pin_required")).toMatchObject({ code: "pin_required" });+ s.send({ type: "pin_command", pin: PIN, command: mode("notion", "read_write") });+ await s.find("error", (m) => m.code === "pin_required", 2);+ await settle();+ expect(existsSync(join(s.dataDir, "connectors.json")) ? s.connectorsText() : "").toBe(before);++ s.send({ type: "pin_set", pin: PIN });+ expect(await s.find("pin_status", (m) => m.pin.set)).toMatchObject({ pin: { set: true } });+ const stored = readFileSync(join(s.dataDir, "web-pin.json"), "utf8");+ expect(stored).not.toContain(PIN);+ expect(statSync(join(s.dataDir, "web-pin.json")).mode & 0o777).toBe(0o600);+ // A second window learns it is set; nobody can set it again.+ const other = await connect(s.d);+ expect(other.ready).toMatchObject({ pin: { set: true } });+ other.send({ type: "pin_set", pin: "111111" });+ await other.find("error", (m) => m.code === "pin_exists");+ expect(readFileSync(join(s.dataDir, "web-pin.json"), "utf8")).toBe(stored);+ });++ it("refuses a wrong PIN without changing anything, makes the change with the right one, and locks after repeated tries", async () => {+ const s = await setup();+ await waitFor(() => s.d.supervisor.state === "ready");+ s.send({ type: "pin_set", pin: PIN });+ await s.find("pin_status", (m) => m.pin.set);+ await connectNotion(s);+ const saved = () => JSON.parse(s.connectorsText()).connectors.notion as { mode: string };+ expect(saved().mode).toBe("read_only");+ const before = s.connectorsText();++ const seen = s.messages.length;+ s.send({ type: "pin_command", pin: "000000", command: mode("notion", "read_write") });+ const wrong = await s.find("error", (m) => m.code === "pin_wrong", seen);+ expect(wrong.message).toMatch(new RegExp(`${PIN_ATTEMPTS - 1}`));+ await settle();+ expect(s.connectorsText()).toBe(before);++ const pid = s.d.supervisor.pid;+ s.send({ type: "pin_command", pin: PIN, command: mode("notion", "read_write") });+ await waitFor(() => saved().mode === "read_write");+ await waitFor(() => s.d.supervisor.pid !== pid && s.d.supervisor.state === "ready");+ // The PIN confirmed it; nothing was asked again.+ expect(s.messages.filter((m) => m.type === "ask")).toEqual([]);++ const changed = s.connectorsText();+ for (let i = 0; i < PIN_ATTEMPTS; i++)+ s.send({ type: "pin_command", pin: "000000", command: mode("notion", "read_only") });+ await s.find("error", (m) => m.code === "pin_locked");+ expect(await s.find("pin_status", (m) => m.pin.locked === true)).toMatchObject({+ pin: { set: true, locked: true },+ });+ const locked = s.messages.length;+ s.send({ type: "pin_command", pin: PIN, command: mode("notion", "read_only") });+ await s.find("error", (m) => m.code === "pin_locked", locked);+ await settle();+ expect(s.connectorsText()).toBe(changed);+ });++ it("allows a sending action only with the PIN; a wrong PIN keeps it waiting, and declining needs none", async () => {+ const s = await setup();+ await waitFor(() => s.d.supervisor.state === "ready");+ s.send({ type: "pin_set", pin: PIN });+ await s.find("pin_status", (m) => m.pin.set);+ await connectNotion(s);+ const pid = s.d.supervisor.pid;+ s.send({ type: "pin_command", pin: PIN, command: mode("notion", "read_write") });+ await waitFor(() => s.d.supervisor.pid !== pid && s.d.supervisor.state === "ready");+ const client = await s.engineClient("notion");+ const refusal = (call: Promise<unknown>) =>+ call.then(+ () => undefined,+ (e: unknown) => e as McpError,+ );++ const args = { title: "Plan", parent: "Team space" };+ const allowed = client.callTool("notion-create-pages", args);+ const ask = await s.find("ask", (m) => m.ask.method === "pin");+ expect(ask.ask).toMatchObject({ method: "pin", title: "Allow Notion to create pages?" });+ expect(ask.ask.message).toContain("Plan");+ expect(ask.ask.message).toContain("Team space");+ // Yes without the PIN is not an answer.+ s.send({ type: "ui_response", requestId: ask.ask.requestId, confirmed: true });+ await s.find("error", (m) => m.code === "pin_required");+ s.send({ type: "pin_approve", requestId: ask.ask.requestId, pin: "000000" });+ await s.find("error", (m) => m.code === "pin_wrong");+ await settle();+ expect(s.notionCalls).toEqual([]);+ s.send({ type: "pin_approve", requestId: ask.ask.requestId, pin: PIN });+ expect(await allowed).toMatchObject({ content: [{ text: "notion ran notion-create-pages" }] });+ expect(s.notionCalls).toEqual(["notion-create-pages"]);+ await s.find("ask_resolved", (m) => m.requestId === ask.ask.requestId);++ const seen = s.messages.length;+ const declined = refusal(client.callTool("notion-create-pages", args));+ const second = await s.find("ask", (m) => m.ask.method === "pin", seen);+ s.send({ type: "ui_response", requestId: second.ask.requestId, confirmed: false });+ expect((await declined)?.message).toMatch(/did not allow/);+ expect(s.notionCalls).toEqual(["notion-create-pages"]);++ // The PIN went to the daemon only: never to the engine's input, its environment, or a log.+ s.send({ type: "send", text: "hello", requestId: "r1" });+ await s.find("message_done");+ expect(s.stdin()).toContain("hello");+ expect(s.stdin()).not.toContain(PIN);+ expect(JSON.stringify(s.engineProcess())).not.toContain(PIN);+ expect(s.logs.join("\n")).not.toContain(PIN);+ });+});++describe("with the desktop app's channel, server mode changes nothing (S25.2)", () => {+ it("keeps app_required on the WebSocket, offers no PIN, and keeps secrets in the app", async () => {+ const s = await setup({ app: true });+ await waitFor(() => s.d.supervisor.state === "ready");+ expect(s.ready).toMatchObject({ type: "ready" });+ expect(s.ready).not.toHaveProperty("pin");+ for (const message of [+ { type: "pin_set", pin: PIN },+ { type: "pin_command", pin: PIN, command: mode("notion", "read_write") },+ mode("notion", "read_write"),+ ])+ s.send(message);+ await waitFor(+ () => s.messages.filter((m) => m.type === "error" && m.code === "app_required").length === 3,+ );+ expect(+ s.messages+ .filter((m) => m.type === "error")+ .every((m) => m.type === "error" && m.message === APP_REQUIRED),+ ).toBe(true);+ expect(existsSync(join(s.dataDir, "web-pin.json"))).toBe(false);+ // Secrets stay in the app's store.+ await waitFor(() => s.app.secretCalls.some((call) => call.includes("integrity/connectors")));+ expect(existsSync(join(s.dataDir, "secrets.enc.json"))).toBe(false);+ });++ it("without server mode and without the app, a PIN opens nothing", async () => {+ const s = await setup({ vps: false });+ await waitFor(() => s.d.supervisor.state === "ready");+ expect(s.ready).not.toHaveProperty("pin");+ s.send({ type: "pin_set", pin: PIN });+ s.send({ type: "pin_command", pin: PIN, command: mode("notion", "read_write") });+ await waitFor(+ () => s.messages.filter((m) => m.type === "error" && m.code === "app_required").length === 2,+ );+ expect(existsSync(join(s.dataDir, "web-pin.json"))).toBe(false);+ // The data folder stays 0700 and nothing is handed over outside server mode.+ expect(statSync(s.dataDir).mode & 0o777).toBe(0o700);+ expect(s.handedOver).toEqual([]);+ });+});diff --git a/packages/daemon/test/vps.test.ts b/packages/daemon/test/vps.test.tsnew file mode 100644index 0000000..a52ae0a--- /dev/null+++ b/packages/daemon/test/vps.test.ts@@ -0,0 +1,89 @@+// Server mode (S25.8): explicit, only when GENTLE_DOT_VPS is on; the daemon runs as root in its+// container, the engine as another user, and stdio connector servers as a third one.+import { randomBytes } from "node:crypto";+import { describe, expect, it } from "vitest";+import { NO_SECRETS_KEY } from "../src/secret-file.ts";+import { handOverCommand, loadVpsOptions, lookupUser, stdioCommand, vpsEnabled } from "../src/vps.ts";++const PASSWD = [+ "root:x:0:0:root:/root:/bin/bash",+ "dot:x:1000:1000::/home/dot:/bin/sh",+ "dotmcp:x:1001:1001::/nonexistent:/usr/sbin/nologin",+ "",+].join("\n");++const base = { GENTLE_DOT_VPS: "1", GENTLE_DOT_ENGINE_USER: "dot", GENTLE_DOT_CONNECTOR_USER: "dotmcp" };++describe("server mode", () => {+ it("is on only when GENTLE_DOT_VPS says so", () => {+ expect(vpsEnabled({})).toBe(false);+ expect(vpsEnabled({ GENTLE_DOT_VPS: "0" })).toBe(false);+ expect(vpsEnabled({ GENTLE_DOT_VPS: "" })).toBe(false);+ for (const value of ["1", "on", "true", "TRUE"]) expect(vpsEnabled({ GENTLE_DOT_VPS: value })).toBe(true);+ expect(loadVpsOptions({ GENTLE_DOT_ENGINE_USER: "dot" }, { uid: 0, passwd: PASSWD })).toBeUndefined();+ });++ it("finds the users by name or as uid:gid", () => {+ expect(lookupUser("dot", PASSWD)).toEqual({ uid: 1000, gid: 1000 });+ expect(lookupUser("1234:5678", PASSWD)).toEqual({ uid: 1234, gid: 5678 });+ expect(() => lookupUser("nobody-here", PASSWD)).toThrow(/nobody-here/);+ });++ it("resolves the engine and connector users and the secrets key", () => {+ const key = randomBytes(32);+ const options = loadVpsOptions(+ { ...base, GENTLE_DOT_SECRETS_KEY: key.toString("base64") },+ { uid: 0, passwd: PASSWD },+ );+ expect(options).toMatchObject({ engine: { uid: 1000, gid: 1000 }, connector: { uid: 1001, gid: 1001 } });+ expect(options?.secretsKey).toEqual(key);+ // Without a key the server starts, and connectors that need a secret fail closed with why.+ const none = loadVpsOptions(base, { uid: 0, passwd: PASSWD });+ expect(none?.secretsKey).toBeUndefined();+ expect(none?.secretsKeyProblem).toBe(NO_SECRETS_KEY);+ const bad = loadVpsOptions({ ...base, GENTLE_DOT_SECRETS_KEY: "short" }, { uid: 0, passwd: PASSWD });+ expect(bad?.secretsKeyProblem).toMatch(/32 bytes/);+ });++ it("refuses to start half-separated", () => {+ // Only root can start the engine as another user.+ expect(() => loadVpsOptions(base, { uid: 1000, passwd: PASSWD })).toThrow(/root/);+ expect(() =>+ loadVpsOptions({ ...base, GENTLE_DOT_ENGINE_USER: "root" }, { uid: 0, passwd: PASSWD }),+ ).toThrow(/must not be root/);+ expect(() =>+ loadVpsOptions({ ...base, GENTLE_DOT_CONNECTOR_USER: "dot" }, { uid: 0, passwd: PASSWD }),+ ).toThrow(/different/);+ expect(() =>+ loadVpsOptions({ ...base, GENTLE_DOT_ENGINE_USER: "ghost" }, { uid: 0, passwd: PASSWD }),+ ).toThrow(/ghost/);+ });++ it("hands the daemon's files in the engine's folders over with chown, never following links", () => {+ expect(handOverCommand({ uid: 1000, gid: 1000 }, { uid: 0, gid: 0 }, ["/d/agent", "/d/home"])).toEqual({+ command: "chown",+ args: ["-R", "-P", "--from=0:0", "1000:1000", "--", "/d/agent", "/d/home"],+ });+ });++ it("runs a stdio connector server as the connector user, with no supplementary groups", () => {+ expect(stdioCommand({ uid: 1001, gid: 1001 }, "npx", ["-y", "server"])).toEqual({+ command: "setpriv",+ args: [+ "--reuid=1001",+ "--regid=1001",+ "--clear-groups",+ "--inh-caps=-all",+ "--",+ "npx",+ "-y",+ "server",+ ],+ });+ // Without server mode, the server runs as it does today.+ expect(stdioCommand(undefined, "npx", ["-y", "server"])).toEqual({+ command: "npx",+ args: ["-y", "server"],+ });+ });+});diff --git a/packages/daemon/test/web-pin.test.ts b/packages/daemon/test/web-pin.test.tsnew file mode 100644index 0000000..076f544--- /dev/null+++ b/packages/daemon/test/web-pin.test.ts@@ -0,0 +1,98 @@+// The web PIN on a server (S25.8): set once in the web page, kept only as a salted scrypt hash in a+// file of the daemon, and locked after repeated wrong tries, also across restarts.+import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { PIN_ATTEMPTS, PIN_LOCK_MS, PinGate } from "../src/web-pin.ts";+import { tempDir } from "./helpers.ts";++const PIN = "482913";++function gate(file = join(tempDir(), "web-pin.json")) {+ let now = 1_000_000;+ const clock = { advance: (ms: number) => (now += ms) };+ return { file, clock, pin: new PinGate({ file, now: () => now }) };+}++describe("web PIN", () => {+ it("is set on first use only, and only its salted hash reaches the disk", async () => {+ const { file, pin } = gate();+ expect(pin.status()).toEqual({ set: false });+ expect(existsSync(file)).toBe(false);+ // Nothing can be checked before the PIN exists.+ expect(await pin.verify(PIN)).toMatchObject({ ok: false, code: "pin_required" });+ expect(await pin.set(PIN)).toEqual({ ok: true });+ expect(pin.status()).toEqual({ set: true });+ const text = readFileSync(file, "utf8");+ expect(text).not.toContain(PIN);+ const saved = JSON.parse(text) as Record<string, unknown>;+ expect(saved).toMatchObject({ version: 1, kdf: "scrypt" });+ expect(typeof saved.salt).toBe("string");+ expect(typeof saved.hash).toBe("string");+ expect(statSync(file).mode & 0o777).toBe(0o600);+ // Two PINs set from the same digits still differ: the salt is random.+ const other = gate();+ await other.pin.set(PIN);+ expect(JSON.parse(readFileSync(other.file, "utf8")).hash).not.toBe(saved.hash);++ // Set once: a second set does not replace it.+ expect(await pin.set("111111")).toMatchObject({ ok: false, code: "pin_exists" });+ expect(readFileSync(file, "utf8")).toBe(text);+ expect(await pin.verify(PIN)).toEqual({ ok: true });+ expect(await new PinGate({ file }).verify(PIN)).toEqual({ ok: true });+ });++ it("refuses a PIN that is not 6 to 12 digits", async () => {+ const { file, pin } = gate();+ expect(await pin.set("1234")).toMatchObject({ ok: false, code: "pin_invalid" });+ expect(existsSync(file)).toBe(false);+ });++ it("locks after repeated wrong tries, even for the right PIN, and stays locked after a restart", async () => {+ const { file, clock, pin } = gate();+ await pin.set(PIN);+ for (let i = 1; i < PIN_ATTEMPTS; i++) {+ const wrong = await pin.verify("000000");+ expect(wrong).toMatchObject({ ok: false, code: "pin_wrong" });+ if (!wrong.ok) expect(wrong.message).toContain(`${PIN_ATTEMPTS - i}`);+ }+ expect(await pin.verify("000000")).toMatchObject({ ok: false, code: "pin_locked" });+ expect(pin.status()).toEqual({ set: true, locked: true });+ expect(await pin.verify(PIN)).toMatchObject({ ok: false, code: "pin_locked" });+ // A restarted daemon reads the lock from its file.+ const restarted = new PinGate({ file, now: () => 1_000_000 + 60_000 });+ expect(await restarted.verify(PIN)).toMatchObject({ ok: false, code: "pin_locked" });+ clock.advance(PIN_LOCK_MS + 1);+ expect(pin.status()).toEqual({ set: true });+ expect(await pin.verify(PIN)).toEqual({ ok: true });+ });++ it("counts tries made at the same time, one after the other", async () => {+ const { pin } = gate();+ await pin.set(PIN);+ const answers = await Promise.all(Array.from({ length: PIN_ATTEMPTS + 3 }, () => pin.verify("000000")));+ expect(answers.filter((a) => !a.ok && a.code === "pin_wrong")).toHaveLength(PIN_ATTEMPTS - 1);+ expect(answers.filter((a) => !a.ok && a.code === "pin_locked")).toHaveLength(4);+ });++ it("a right PIN clears the count of wrong tries", async () => {+ const { pin } = gate();+ await pin.set(PIN);+ for (let i = 1; i < PIN_ATTEMPTS; i++) await pin.verify("000000");+ expect(await pin.verify(PIN)).toEqual({ ok: true });+ expect(await pin.verify("000000")).toMatchObject({+ ok: false,+ code: "pin_wrong",+ message: expect.stringContaining(`${PIN_ATTEMPTS - 1}`),+ });+ });++ it("fails closed on a damaged PIN file instead of letting a new PIN replace it", async () => {+ const { file, pin } = gate();+ writeFileSync(file, "not json");+ expect(pin.status()).toEqual({ set: true, locked: true });+ expect(await pin.set(PIN)).toMatchObject({ ok: false });+ expect(await pin.verify(PIN)).toMatchObject({ ok: false, code: "pin_locked" });+ expect(readFileSync(file, "utf8")).toBe("not json");+ });+});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex c0cec56..48f96b6 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -22,9 +22,10 @@ export interface Ask {requestId: string;/*** `app`: an approval the desktop app asks in a native dialog (S25.3). Windows only show that it- * waits there; it cannot be answered with `ui_response`.+ * waits there; it cannot be answered with `ui_response`. `pin`: an approval on a server (S25.8),+ * allowed with `pin_approve` and the web PIN; `ui_response` with `confirmed: false` declines it.*/- method: "select" | "confirm" | "input" | "editor" | "app";+ method: "select" | "confirm" | "input" | "editor" | "app" | "pin";title: string;message?: string;options?: string[];@@ -80,6 +81,12 @@ export interface Features {conversations: boolean;}+/** The web PIN on a server (S25.8): whether it was set, and whether wrong tries locked it for now. */+export interface PinStatus {+ set: boolean;+ locked?: boolean;+}+/** What talking to the assistant can use through the daemon (an OpenAI API key, S30.2). */export interface VoiceCapability {/** The daemon can turn a recording into text. */@@ -375,7 +382,13 @@ export type ClientMessage =| { type: "computer_unregister" }/** A recording to turn into text: its audio type and the bytes in base64. */| { type: "voice_transcribe"; requestId: string; mime: string; data: string }- | { type: "voice_speak"; requestId: string; text: string };+ | { type: "voice_speak"; requestId: string; text: string }+ /** Sets the web PIN on a server, once (S25.8). */+ | { type: "pin_set"; pin: string }+ /** One connector change from the web page on a server, with the PIN ({@link isPinCommand}). */+ | { type: "pin_command"; pin: string; command: ClientMessage }+ /** Allows a `pin` ask with the PIN. */+ | { type: "pin_approve"; requestId: string; pin: string };export type ServerPayload =| {@@ -390,7 +403,10 @@ export type ServerPayload =model?: string;features?: Features;voice?: VoiceCapability;+ /** On a server without the desktop app (S25.8): connector changes and approvals need this PIN. */+ pin?: PinStatus;}+ | { type: "pin_status"; pin: PinStatus }| { type: "agent_state"; state: AgentState }| { type: "user_message"; messageId: string; text: string; attachments?: AttachmentInfo[] }| { type: "message_delta"; messageId: string; delta: string }@@ -483,6 +499,19 @@ export function isAppCommand(message: ClientMessage): boolean {return (APP_COMMANDS as readonly string[]).includes(message.type);}+/** Why a window on a server must give the PIN first (S25.8). */+export const PIN_REQUIRED = "Enter your PIN to change connectors or allow this action.";++/** What a web PIN may confirm on a server (S25.8): the app commands, except the desktop's computer helper. */+export function isPinCommand(message: ClientMessage): boolean {+ return (+ isAppCommand(message) && message.type !== "computer_register" && message.type !== "computer_unregister"+ );+}++/** A web PIN: 6 to 12 digits. */+export const PIN_PATTERN = /^[0-9]{6,12}$/;+/** Every daemon message carries a per-connection, monotonic `seq`. */export type ServerMessage = ServerPayload & { seq: number };@@ -492,6 +521,7 @@ const MAX_TEXT = 100_000;const CONNECTOR_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;const isConnectorId = (value: unknown): value is string => isString(value) && CONNECTOR_ID.test(value);const isShortString = (value: unknown): value is string => isString(value) && value.length <= 200;+const isPin = (value: unknown): value is string => isString(value) && PIN_PATTERN.test(value);const MAX_IMPORTS = 200;const COMPUTER_URL = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})\/mcp$/;const VOICE_MIME =@@ -659,6 +689,17 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {m.text.length <= MAX_VOICE_TEXT? { type: "voice_speak", requestId: m.requestId, text: m.text }: undefined;+ case "pin_set":+ return isPin(m.pin) ? { type: "pin_set", pin: m.pin } : undefined;+ case "pin_command": {+ if (!isPin(m.pin) || typeof m.command !== "object" || m.command === null) return undefined;+ const command = parseClientMessage(JSON.stringify(m.command));+ return command && isPinCommand(command) ? { type: "pin_command", pin: m.pin, command } : undefined;+ }+ case "pin_approve":+ return isShortString(m.requestId) && isPin(m.pin)+ ? { type: "pin_approve", requestId: m.requestId, pin: m.pin }+ : undefined;case "computer_unregister":case "connectors_list":case "connectors_scan":diff --git a/packages/protocol/test/pin.test.ts b/packages/protocol/test/pin.test.tsnew file mode 100644index 0000000..1003b86--- /dev/null+++ b/packages/protocol/test/pin.test.ts@@ -0,0 +1,65 @@+// The web PIN on a server (S25.8): the messages a browser sends to set it, to make a connector+// change with it, and to allow an approval with it. Anything else is refused at the parser.+import { describe, expect, it } from "vitest";+import { isPinCommand, PIN_REQUIRED, parseClientMessage } from "../src/index.ts";++const parse = (value: unknown) => parseClientMessage(JSON.stringify(value));++describe("web PIN messages", () => {+ it("accepts a PIN of 6 to 12 digits to set it", () => {+ expect(parse({ type: "pin_set", pin: "123456" })).toEqual({ type: "pin_set", pin: "123456" });+ expect(parse({ type: "pin_set", pin: "123456789012" })).toEqual({ type: "pin_set", pin: "123456789012" });+ for (const pin of ["12345", "1234567890123", "12345a", " 123456", 123456, ""])+ expect(parse({ type: "pin_set", pin }), String(pin)).toBeUndefined();+ });++ it("wraps one connector change with the PIN", () => {+ expect(+ parse({+ type: "pin_command",+ pin: "123456",+ command: { type: "connector_mode", connectorId: "notion", mode: "read_write" },+ }),+ ).toEqual({+ type: "pin_command",+ pin: "123456",+ command: { type: "connector_mode", connectorId: "notion", mode: "read_write" },+ });+ });++ it("refuses a PIN command that wraps anything but a connector change", () => {+ const wrapped = [+ { type: "send", text: "hi" },+ { type: "computer_register", url: "http://127.0.0.1:5000/mcp", token: "a".repeat(43) },+ { type: "computer_unregister" },+ { type: "pin_set", pin: "123456" },+ { type: "connector_mode", connectorId: "notion", mode: "everything" },+ { type: "connector_draft_reply", draftId: "d1", approve: false },+ ];+ for (const command of wrapped)+ expect(parse({ type: "pin_command", pin: "123456", command }), command.type).toBeUndefined();+ expect(+ parse({ type: "pin_command", pin: "12", command: { type: "connector_remove", connectorId: "notion" } }),+ ).toBeUndefined();+ });++ it("allows an approval with the PIN", () => {+ expect(parse({ type: "pin_approve", requestId: "pin-1", pin: "123456" })).toEqual({+ type: "pin_approve",+ requestId: "pin-1",+ pin: "123456",+ });+ expect(parse({ type: "pin_approve", requestId: "pin-1" })).toBeUndefined();+ expect(parse({ type: "pin_approve", requestId: 1, pin: "123456" })).toBeUndefined();+ });++ it("names the connector changes a PIN may make: every app command except the computer helper", () => {+ const change = parse({ type: "connector_import", ids: ["claude:notion"] });+ const approveDraft = parse({ type: "connector_draft_reply", draftId: "d1", approve: true });+ const computer = parse({ type: "computer_unregister" });+ expect(change && isPinCommand(change)).toBe(true);+ expect(approveDraft && isPinCommand(approveDraft)).toBe(true);+ expect(computer && isPinCommand(computer)).toBe(false);+ expect(PIN_REQUIRED).toMatch(/PIN/);+ });+});diff --git a/packages/ui/src/components/AskCard.tsx b/packages/ui/src/components/AskCard.tsxindex 57e42ea..0b0e1f2 100644--- a/packages/ui/src/components/AskCard.tsx+++ b/packages/ui/src/components/AskCard.tsx@@ -1,8 +1,10 @@-import type { Ask } from "@gentle-dot/protocol";+import type { Ask, PinStatus } from "@gentle-dot/protocol";import { useEffect, useRef, useState } from "react";+import { PinForm } from "./PinForm.tsx";import type { Send } from "./types.ts";-export function AskCard({ ask, send }: { ask: Ask; send: Send }) {+/** `pin`: the web PIN on a server (S25.8), for approvals allowed with it. */+export function AskCard({ ask, send, pin }: { ask: Ask; send: Send; pin?: PinStatus }) {const [value, setValue] = useState(ask.prefill ?? "");const card = useRef<HTMLElement>(null);// A question that arrives below a long conversation must be seen.@@ -23,6 +25,34 @@ export function AskCard({ ask, send }: { ask: Ask; send: Send }) {);}+ // On a server, an approval is allowed with the web PIN (S25.8); declining needs none.+ if (ask.method === "pin") {+ return (+ <section ref={card} className="ask-card" aria-label="The assistant needs your answer">+ <p className="eyebrow">Needs your answer</p>+ <p className="ask-title">{ask.title}</p>+ {ask.message ? (+ // biome-ignore lint/a11y/noNoninteractiveTabindex: a scrollable region must be reachable by keyboard.+ <section className="ask-message" aria-label="Details" tabIndex={0}>+ {ask.message}+ </section>+ ) : null}+ <PinForm+ pin={pin ?? { set: true }}+ action="Allow"+ onPin={(value, created) => {+ if (created) send({ type: "pin_set", pin: value });+ send({ type: "pin_approve", requestId: ask.requestId, pin: value });+ }}+ >+ <button type="button" onClick={() => answer({ confirmed: false })}>+ Deny+ </button>+ </PinForm>+ </section>+ );+ }+return (<section ref={card} className="ask-card" aria-label="The assistant needs your answer"><p className="eyebrow">Needs your answer</p>diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex a21e727..0e59866 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -30,6 +30,7 @@ import {} from "./icons.tsx";import { MessageList } from "./MessageList.tsx";import { ModelPicker } from "./ModelPicker.tsx";+import { describePinCommand, PinForm } from "./PinForm.tsx";import { ProfilesPanel } from "./ProfilesPanel.tsx";import { SettingsPanel } from "./SettingsPanel.tsx";import { newRequestId, type Send } from "./types.ts";@@ -92,6 +93,11 @@ export function ChatSurface({settings,}: ChatSurfaceProps) {const [showSettings, setShowSettings] = useState(false);+ /** A connector change waiting for the web PIN (S25.8). */+ const [pinPending, setPinPending] = useState<ClientMessage>();+ // On a server without the desktop app, connector changes go out with the web PIN instead.+ const pin = state.pin;+ const changeSend: Send | undefined = appSend ?? (pin ? setPinPending : undefined);const openAccounts = () => {setShowSettings(false);send({ type: "auth_list" });@@ -302,7 +308,7 @@ export function ChatSurface({<ConnectorsPanelconnectors={state.connectors}send={send}- {...(appSend ? { appSend } : {})}+ {...(changeSend ? { appSend: changeSend } : {})}dispatch={dispatch}openUrl={openUrl}{...(computer?.available ? { computer } : {})}@@ -350,20 +356,53 @@ export function ChatSurface({</div>) : null}{state.asks.map((ask) => (- <AskCard key={ask.requestId} ask={ask} send={send} />+ <AskCard key={ask.requestId} ask={ask} send={send} {...(pin ? { pin } : {})} />))}{(state.connectors.drafts ?? []).map((draft) => (<ConnectorDraftCardkey={draft.draftId}draft={draft}send={send}- {...(appSend ? { appSend } : {})}+ {...(changeSend ? { appSend: changeSend } : {})}// Its secrets are asked in the Connectors screen.approved={() => dispatch({ type: "connector_started", connectorId: draft.name })}/>))}</main>+ {pinPending && pin ? (+ <div+ className="switch-confirm pin-dialog"+ role="dialog"+ aria-label={pin.set ? "Enter your PIN" : "Create a PIN"}+ >+ <p>{describePinCommand(pinPending, state.connectors.list)}</p>+ <PinForm+ pin={pin}+ action="Continue"+ onPin={(value, created) => {+ if (created) send({ type: "pin_set", pin: value });+ send({ type: "pin_command", pin: value, command: pinPending });+ setPinPending(undefined);+ }}+ >+ <button+ type="button"+ onClick={() => {+ setPinPending(undefined);+ // Nothing was sent: a sign-in that was starting stops, as when the app declines.+ dispatch({+ type: "server",+ message: { type: "error", code: "declined", message: "Nothing was changed.", seq: 0 },+ });+ }}+ >+ Cancel+ </button>+ </PinForm>+ </div>+ ) : null}+{pendingSwitch ? (<div className="switch-confirm" role="alertdialog" aria-label="Stop and switch?"><p>The assistant is still answering. Stop it and open the other conversation?</p>diff --git a/packages/ui/src/components/PinForm.tsx b/packages/ui/src/components/PinForm.tsxnew file mode 100644index 0000000..63f33e0--- /dev/null+++ b/packages/ui/src/components/PinForm.tsx@@ -0,0 +1,87 @@+import { type ClientMessage, type ConnectorInfo, PIN_PATTERN, type PinStatus } from "@gentle-dot/protocol";+import { type ReactNode, useState } from "react";++interface PinFormProps {+ pin: PinStatus;+ /** The submit button's label. */+ action: string;+ /** A valid PIN; `created` when the user just chose it (send `pin_set` first). */+ onPin: (pin: string, created: boolean) => void;+ /** Buttons shown next to the submit button. */+ children?: ReactNode;+}++/**+ * The web PIN on a server (S25.8): a new one is chosen and repeated on first use, then typed before+ * each connector change or allowed action. It goes to the daemon only; the assistant never sees it.+ */+export function PinForm({ pin, action, onPin, children }: PinFormProps) {+ const [value, setValue] = useState("");+ const [repeat, setRepeat] = useState("");+ const [problem, setProblem] = useState<string>();+ const field = (label: string, text: string, set: (v: string) => void) => (+ <input+ aria-label={label}+ type="password"+ inputMode="numeric"+ autoComplete="off"+ placeholder={label}+ value={text}+ onChange={(event) => {+ setProblem(undefined);+ set(event.target.value);+ }}+ />+ );+ return (+ <form+ className="ask-form pin-form"+ onSubmit={(event) => {+ event.preventDefault();+ if (!PIN_PATTERN.test(value)) return setProblem("Use 6 to 12 digits.");+ if (!pin.set && repeat !== value) return setProblem("The two PINs are different.");+ onPin(value, !pin.set);+ setValue("");+ setRepeat("");+ }}+ >+ {pin.set ? null : (+ <p className="connector-note">+ Choose a PIN of 6 to 12 digits. You will need it to change connectors and to allow actions. The+ assistant never sees it.+ </p>+ )}+ {pin.locked ? <p className="connector-note">Too many wrong PINs. Try again later.</p> : null}+ {pin.set ? field("PIN", value, setValue) : field("New PIN", value, setValue)}+ {pin.set ? null : field("Repeat the PIN", repeat, setRepeat)}+ {problem ? <p role="alert">{problem}</p> : null}+ <button type="submit" className="primary">+ {action}+ </button>+ {children}+ </form>+ );+}++/** What a connector change confirmed with the PIN will do, in the user's words. */+export function describePinCommand(message: ClientMessage, connectors: ConnectorInfo[] = []): string {+ const name = (id: string) => connectors.find((c) => c.id === id)?.name ?? id;+ switch (message.type) {+ case "connector_mode":+ return `Switch ${name(message.connectorId)} to ${message.mode === "read_write" ? "read and send" : "read only"}?`;+ case "connector_connect":+ case "connector_signin":+ case "connector_setup":+ return `Connect ${name(message.connectorId)}?`;+ case "connector_disconnect":+ return `Disconnect ${name(message.connectorId)}?`;+ case "connector_remove":+ return `Remove ${name(message.connectorId)}?`;+ case "connector_draft_reply":+ return "Add the connector the assistant drafted?";+ case "connector_import":+ return `Import ${message.ids.length} ${message.ids.length === 1 ? "server" : "servers"}?`;+ default:+ return "Change your connectors?";+ }+}diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsindex 0f8bf20..3aec34a 100644--- a/packages/ui/src/store.ts+++ b/packages/ui/src/store.ts@@ -15,6 +15,7 @@ import type {ModelGroup,ModelOption,ModelRef,+ PinStatus,Profile,ProfilePick,ProfileRole,@@ -81,7 +82,7 @@ export interface ModelsState {/** Errors about the picker's choice show in the picker, not as a notice. */const MODEL_ERRORS = new Set(["model_unavailable", "thinking_unavailable", "model_switch_failed"]);/** A connector change that did not happen: the app declined it, or there is no app to make it. */-const CONNECTOR_REFUSALS = new Set(["declined", "app_required"]);+const CONNECTOR_REFUSALS = new Set(["declined", "app_required", "pin_required", "pin_wrong", "pin_locked"]);/** The daemon's answer to a voice request, matched by `requestId`. */export type VoiceReply = Extract<@@ -136,6 +137,8 @@ export interface DotState {voice: VoiceCapability;/** The latest answers to voice requests, newest last. */voiceReplies: VoiceReply[];+ /** On a server without the desktop app (S25.8): connector changes and approvals need the web PIN. */+ pin?: PinStatus;}export type DotAction =@@ -223,9 +226,11 @@ export function reduce(state: DotState, action: DotAction): DotState {function reduceServer(state: DotState, message: ServerMessage): DotState {switch (message.type) {- case "ready":+ case "ready": {+ const { pin: _pin, ...rest } = state;return {- ...state,+ ...rest,+ ...(message.pin ? { pin: message.pin } : {}),agentState: message.agentState,...(message.clientId ? { clientId: message.clientId } : {}),// The daemon sends the queue right after ready when one exists.@@ -237,6 +242,9 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {// The daemon sends the drafts still waiting right after ready.connectors: { ...state.connectors, drafts: [] },};+ }+ case "pin_status":+ return { ...state, pin: message.pin };case "agent_state":return { ...state, agentState: message.state };case "user_message":diff --git a/packages/ui/test/pin.test.tsx b/packages/ui/test/pin.test.tsxnew file mode 100644index 0000000..0ddec04--- /dev/null+++ b/packages/ui/test/pin.test.tsx@@ -0,0 +1,144 @@+// The web PIN on a server (S25.8): the page sets it on first use, and asks for it before a connector+// change or before allowing a sending action. Without server mode, the web page stays as it was.+import {+ APP_REQUIRED,+ type Ask,+ type ClientMessage,+ type ConnectorInfo,+ type ServerMessage,+ type ServerPayload,+} from "@gentle-dot/protocol";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { useReducer } from "react";+import { describe, expect, it, vi } from "vitest";+import { AskCard } from "../src/components/AskCard.tsx";+import { ChatSurface } from "../src/components/ChatSurface.tsx";+import { type DotState, initialState, reduce } from "../src/store.ts";++const PIN = "731942";++const notion: ConnectorInfo = {+ id: "notion",+ name: "Notion",+ reads: "Search and read your pages.",+ sends: "Create and edit pages, after you approve each one.",+ added: true,+ enabled: true,+ mode: "read_only",+ status: "connected",+};++function apply(state: DotState, ...payloads: ServerPayload[]): DotState {+ return payloads.reduce(+ (s, p) => reduce(s, { type: "server", message: { ...p, seq: 1 } as ServerMessage }),+ state,+ );+}++const open = (pin?: { set: boolean; locked?: boolean }) =>+ apply(+ { ...initialState, connection: "open" },+ { type: "ready", agentState: "idle", ...(pin ? { pin } : {}) },+ { type: "connectors", connectors: [notion], open: true },+ );++function Web({ initial, send }: { initial: DotState; send: (m: ClientMessage) => void }) {+ const [state, dispatch] = useReducer(reduce, initial);+ return <ChatSurface variant="web" state={state} send={send} dismiss={vi.fn()} dispatch={dispatch} />;+}++describe("PIN state", () => {+ it("follows the daemon: present only in server mode, updated when it changes", () => {+ expect(open().pin).toBeUndefined();+ let s = open({ set: false });+ expect(s.pin).toEqual({ set: false });+ s = apply(s, { type: "pin_status", pin: { set: true, locked: true } });+ expect(s.pin).toEqual({ set: true, locked: true });+ });+});++describe("connector changes in the web page", () => {+ it("stay locked with the reason when the server has no PIN mode", () => {+ render(<Web initial={open()} send={vi.fn()} />);+ expect(screen.getByText(APP_REQUIRED)).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: "Read and send" })).toBeDisabled();+ });++ it("create the PIN on first use, then send the change with it", async () => {+ const send = vi.fn();+ render(<Web initial={open({ set: false })} send={send} />);+ expect(screen.queryByText(APP_REQUIRED)).toBeNull();+ await userEvent.click(screen.getByRole("radio", { name: "Read and send" }));+ const dialog = screen.getByRole("dialog", { name: "Create a PIN" });+ await userEvent.type(within(dialog).getByLabelText("New PIN"), PIN);+ await userEvent.type(within(dialog).getByLabelText("Repeat the PIN"), "000000");+ await userEvent.click(within(dialog).getByRole("button", { name: "Continue" }));+ expect(within(dialog).getByRole("alert")).toHaveTextContent("The two PINs are different.");+ expect(send).not.toHaveBeenCalledWith(expect.objectContaining({ type: "pin_set" }));+ await userEvent.clear(within(dialog).getByLabelText("Repeat the PIN"));+ await userEvent.type(within(dialog).getByLabelText("Repeat the PIN"), PIN);+ await userEvent.click(within(dialog).getByRole("button", { name: "Continue" }));+ expect(send.mock.calls.map(([m]) => m)).toEqual(+ expect.arrayContaining([+ { type: "pin_set", pin: PIN },+ {+ type: "pin_command",+ pin: PIN,+ command: { type: "connector_mode", connectorId: "notion", mode: "read_write" },+ },+ ]),+ );+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("ask for the PIN once it is set, and can be cancelled", async () => {+ const send = vi.fn();+ render(<Web initial={open({ set: true })} send={send} />);+ await userEvent.click(screen.getByRole("radio", { name: "Read and send" }));+ const dialog = screen.getByRole("dialog", { name: "Enter your PIN" });+ expect(within(dialog).getByText(/Switch Notion to read and send/)).toBeInTheDocument();+ await userEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));+ expect(send).not.toHaveBeenCalledWith(expect.objectContaining({ type: "pin_command" }));+ await userEvent.click(screen.getByRole("radio", { name: "Read and send" }));+ await userEvent.type(screen.getByLabelText("PIN"), `${PIN}{Enter}`);+ expect(send).toHaveBeenCalledWith({+ type: "pin_command",+ pin: PIN,+ command: { type: "connector_mode", connectorId: "notion", mode: "read_write" },+ });+ expect(send).not.toHaveBeenCalledWith(expect.objectContaining({ type: "pin_set" }));+ });+});++describe("an approval in the web page", () => {+ const ask: Ask = {+ requestId: "pin-1",+ method: "pin",+ title: "Allow Notion to create pages?",+ message: "The assistant wants to create pages in Notion.\n\ntitle: Plan",+ };++ it("is allowed with the PIN and declined without one", async () => {+ const send = vi.fn();+ render(<AskCard ask={ask} send={send} pin={{ set: true }} />);+ expect(screen.getByText(/title: Plan/)).toBeInTheDocument();+ await userEvent.type(screen.getByLabelText("PIN"), PIN);+ await userEvent.click(screen.getByRole("button", { name: "Allow" }));+ expect(send).toHaveBeenCalledWith({ type: "pin_approve", requestId: "pin-1", pin: PIN });+ await userEvent.click(screen.getByRole("button", { name: "Deny" }));+ expect(send).toHaveBeenCalledWith({ type: "ui_response", requestId: "pin-1", confirmed: false });+ });++ it("creates the PIN first when there is none yet", async () => {+ const send = vi.fn();+ render(<AskCard ask={ask} send={send} pin={{ set: false }} />);+ await userEvent.type(screen.getByLabelText("New PIN"), PIN);+ await userEvent.type(screen.getByLabelText("Repeat the PIN"), PIN);+ await userEvent.click(screen.getByRole("button", { name: "Allow" }));+ expect(send.mock.calls.map(([m]) => m)).toEqual([+ { type: "pin_set", pin: PIN },+ { type: "pin_approve", requestId: "pin-1", pin: PIN },+ ]);+ });+});