diff --git a/README.md b/README.md index c0309ba28..6b2dd4364 100644 --- a/README.md +++ b/README.md @@ -718,6 +718,8 @@ Start with the product-facing destination, then move into the operational refere | [ODD workflow](docs/readme-reference.md#organic-driven-development) · [Technical reference](docs/readme-reference.md) | Everyday work and recovery, installation, configuration, commands, and contributor detail. | | [Installation wizard (preview)](docs/install-wizard.md) | How the browser installer checks your computer, what it installs on the release and main channels, its security model, and what is still being verified. | | [Removing Gentle Shell](docs/gentle-shell-uninstall.md) | What `gentle-shell self-uninstall` removes, keeps and never touches. | +| [Remote use](docs/remote.md) | Agents on one machine, driven from others: what runs on the server and on each client, pairing with a short code, sessions, host tools, forwarded pages and terminals, with diagrams and the security model. | +| [`gentle-shell serve`](docs/serve.md) | The server's reference: commands, files, every endpoint, pairing, device tokens, the HTTP + SSE protocol, limits and troubleshooting. | | [Review integration](docs/review-integration.md) | The provider/consumer boundary for native review. | | [Native authority architecture](docs/native-authority-architecture.md) | Ownership boundaries and review architecture. | | [Delegated verification](docs/delegated-verification.md) | Practical verification guidance. | diff --git a/bin/gentle-shell.mjs b/bin/gentle-shell.mjs index f263f473b..e91c09bdf 100755 --- a/bin/gentle-shell.mjs +++ b/bin/gentle-shell.mjs @@ -2264,6 +2264,42 @@ async function main() { else await handleSelfUninstallCommand(args.commandArgs); return; } + // `gentle-shell [home selectors] serve`: one server per agent home that owns + // `--mode rpc` sessions for remote clients (docs/serve.md). Its sessions are + // this same launcher with the same home, so they resolve Pi like a plain launch. + if (args.command === "serve") { + const { parseServeArgs, runServeCommand } = await import("../runtime/serve-cli.mjs"); + const serve = parseServeArgs(args.commandArgs); + if ("error" in serve) fail(`gentle-shell serve: ${serve.error}\nRun 'gentle-shell serve --help' for usage.`, 2); + let home = resolveHome({ args, env: process.env, homedir: homedir(), config: loadConfig() }); + if (home.mode === "path") home = { ...home, dir: resolvePath(home.dir) }; + // The server file lives inside the home: create a new home the way a first + // launch does, so its sessions still treat it as Gentle Shell's own. + if ((serve.action === "start" || serve.action === "share") && (home.mode === "isolated" || home.mode === "path") && !existsSync(home.dir)) await bootstrapOwnedHome(home); + const homeFlags = home.mode === "link" ? ["--link"] : home.mode === "isolated" ? ["--isolated"] : ["--home", home.dir]; + // After `POST /api/upgrade` the server restarts on the launcher of the installed version: this one + // (npm and pnpm upgrade it in place), or the bundled version `current` names by then. + const restartLauncher = bundled ? () => { + const current = join(bundled.root, "current"); + const versionDir = process.platform === "win32" ? join(bundled.root, "versions", readFileSync(current, "utf8").trim()) : current; + return join(versionDir, "node_modules", "gentle-pi", "bin", "gentle-shell.mjs"); + } : undefined; + process.exitCode = await runServeCommand(serve, { agentHome: home.dir, homeFlags, launcher: fileURLToPath(import.meta.url), nodePath: process.execPath, + version: ownPackageVersion(), env: process.env, stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text), + ...(restartLauncher ? { restartLauncher } : {}) }); + return; + } + // `gentle-shell [home selectors] relay`: the rendezvous that lets devices outside + // a server's network reach it (docs/serve.md#relay). Its secret lives in the home. + if (args.command === "relay") { + const { parseRelayArgs, runRelayCommand } = await import("../runtime/serve-relay-cli.mjs"); + const relay = parseRelayArgs(args.commandArgs); + if ("error" in relay) fail(`gentle-shell relay: ${relay.error}\nRun 'gentle-shell relay --help' for usage.`, 2); + let home = resolveHome({ args, env: process.env, homedir: homedir(), config: loadConfig() }); + if (home.mode === "path") home = { ...home, dir: resolvePath(home.dir) }; + process.exitCode = await runRelayCommand(relay, { agentHome: home.dir, env: process.env, stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }); + return; + } const startupCode = await startupUpdate(bundled, args, startupEnv); if (startupCode !== undefined) { @@ -2569,6 +2605,10 @@ async function main() { // A nested launch must not inherit a stale reporter handoff. if (herdr.reporter) invocation.env[HERDR_REPORTER_ENV] = "1"; else delete invocation.env[HERDR_REPORTER_ENV]; + // A Desktop client's package install or removal runs this same CLI with this + // same home (lib/desktop-packages-service.ts), wherever the session runs. + const selfHomeFlags = home.mode === "path" ? ["--home", resolvePath(home.dir)] : homeSelectorFlags(home); + invocation.env.GENTLE_SHELL_LAUNCH = JSON.stringify({ command: process.execPath, args: [fileURLToPath(import.meta.url), ...selfHomeFlags] }); const resumeHandoff = args.piSubcommand === undefined ? createResumeHandoff() : undefined; const childEnv = resumeHandoff ? { ...invocation.env, [RESUME_HANDOFF_ENV]: resumeHandoff.path } : invocation.env; diff --git a/docs/desktop-rpc.md b/docs/desktop-rpc.md index d5b004b41..cc96d77a9 100644 --- a/docs/desktop-rpc.md +++ b/docs/desktop-rpc.md @@ -10,7 +10,7 @@ Start Pi in RPC mode with the interactive-host marker: GENTLE_SHELL_INTERACTIVE_HOST=1 pi --mode rpc ``` -The channel is inactive in the TUI and in headless RPC children. It does not register an agent-callable tool. +The channel is inactive in the TUI and in headless RPC children. It registers no agent-callable tool of its own; the only tools it adds are the ones a connected client provides with [`set_host_tools`](#set_host_tools), and those run on the client. A Desktop that shows the design canvas itself also sets `GENTLE_DESIGN_OPEN_BROWSER=0`, so `gentle_design {action: "open"}` never launches the system browser. The canvas still starts, the `open` transition still reaches the `design_canvas` event, and the tool answers `opened: false, browserDisabled: true` with the URL. @@ -53,7 +53,7 @@ Registered extension commands are consumed by Pi. The real-runtime maintainer pr } ``` -Requests are limited to 64 KiB. `requestId` is required and limited to 128 characters. Method names use lowercase snake case and are limited to 64 characters. +Requests are limited to 64 KiB, except `set_host_tools` (1 MiB), `host_message` and `set_host_context` (2 MiB each) and `host_tool_result` (10 MiB). Over its limit a request is answered `invalid_request` with `requestId: null`. `requestId` is required and limited to 128 characters. Method names use lowercase snake case and are limited to 64 characters. ### `capabilities` @@ -64,21 +64,22 @@ Returns the currently implemented contract; clients must not infer support from "schema": "gentle-shell.desktop-rpc/v1", "command": "gentle:desktop", "widget": "gentle-desktop-rpc", - "methods": ["capabilities", "get_snapshot", "get_config", "set_config", "get_permission_mode", "set_permission_mode", "get_subscription_usage", "refresh_subscription_usage", "get_design_canvas", "list_jobs", "cancel_job", "get_job_output", "apply_profile", "list_subagents", "cancel_subagent", "get_subagent_thread", "list_sessions", "switch_session", "get_changes", "get_change_diff", "get_review_mode", "set_review_mode", "get_usage_stats", "get_update_status", "list_agent_definitions", "get_status", "get_background_subagents", "set_background_subagents", "get_profile_binding", "clear_profile_binding", "get_auth_status", "reload_credentials"], - "events": ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "session_snapshot"] + "methods": ["capabilities", "get_snapshot", "get_config", "set_config", "get_permission_mode", "set_permission_mode", "get_subscription_usage", "refresh_subscription_usage", "get_design_canvas", "list_jobs", "cancel_job", "get_job_output", "apply_profile", "list_subagents", "cancel_subagent", "get_subagent_thread", "list_sessions", "switch_session", "get_changes", "get_change_diff", "get_review_mode", "set_review_mode", "get_usage_stats", "get_update_status", "list_agent_definitions", "get_status", "get_background_subagents", "set_background_subagents", "get_profile_binding", "clear_profile_binding", "get_auth_status", "reload_credentials", "list_available_models", "set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context", "set_host_activity", "login_start", "login_complete", "login_cancel", "set_api_key", "remove_credentials", "list_packages", "install_package", "remove_package"], + "events": ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished", "session_snapshot"] } ``` -The permission methods, the bounded config read and write, the subscription-usage read and refresh, the design-canvas read, the background-jobs list, cancel, and output read, the profile apply, the subagents list, cancel, and thread read, the review-mode read and change, the cross-session usage-stats read, the update-status read, and the `config_changed`, `permission_mode_changed`, `rate_limit`, `design_canvas`, `jobs_update`, `profile_applied`, `agents_update`, and `review_mode_changed` events are advertised because this extension wires them. `set_config` and `config_changed` are advertised only because the config bridge actually implements that writer — advertising is not a forward-looking wish list. The design slice advertises exactly its one read method and its one transition event, not the canvas `open`/`stop` actions, which stay the `gentle_design` tool's job. The jobs slice advertises exactly its list, cancel, and output-read methods and its one registry-change event, not the `bash_background`/`monitor` start tools, which stay agent tools. The profiles slice advertises exactly its one apply method and its one applied event; profile edits stay `set_config`. The subagents slice advertises exactly its list, cancel, and thread-read methods and its one transition event, not the agent dispatch tools, which stay agent tools. `session_snapshot` is the one entry that depends on the session: it is listed only while the feed owner seam (`extensions/gentle-desktop-feed.ts`) is wired for this session, and absent otherwise; the `get_snapshot` method itself is always listed. The review slice advertises exactly its read and change methods and its one change event; review start, skip, and consent stay terminal-only. The stats slice advertises exactly its one read method and no event: usage stats are an explicit read. The updates slice advertises exactly its one read method and no event; running an update stays the launcher's job. The agent-definitions slice advertises exactly its one read method and no event; editing definitions stays a file edit. The package-status slice advertises exactly its one read method and no event; `/gentle:doctor` stays terminal-only. The background-subagents slice advertises exactly its read and change methods and no event; every answer carries the state. Method availability is not a claim that every dependency is loaded — see [Permission limits](#permission-limits), [Configuration limits](#configuration-limits), [Usage limits](#usage-limits), [Design limits](#design-limits), [Jobs limits](#jobs-limits), [Profiles limits](#profiles-limits), [Subagents limits](#subagents-limits), [Review limits](#review-limits), [Stats limits](#stats-limits), [Updates limits](#updates-limits), [Agent definitions limits](#agent-definitions-limits), [Status limits](#status-limits), and [Background subagents limits](#background-subagents-limits). +The permission methods, the bounded config read and write, the subscription-usage read and refresh, the design-canvas read, the background-jobs list, cancel, and output read, the profile apply, the subagents list, cancel, and thread read, the review-mode read and change, the cross-session usage-stats read, the update-status read, and the `config_changed`, `permission_mode_changed`, `rate_limit`, `design_canvas`, `jobs_update`, `profile_applied`, `agents_update`, and `review_mode_changed` events are advertised because this extension wires them. `set_config` and `config_changed` are advertised only because the config bridge actually implements that writer — advertising is not a forward-looking wish list. The design slice advertises exactly its one read method and its one transition event, not the canvas `open`/`stop` actions, which stay the `gentle_design` tool's job. The jobs slice advertises exactly its list, cancel, and output-read methods and its one registry-change event, not the `bash_background`/`monitor` start tools, which stay agent tools. The profiles slice advertises exactly its one apply method and its one applied event; profile edits stay `set_config`. The subagents slice advertises exactly its list, cancel, and thread-read methods and its one transition event, not the agent dispatch tools, which stay agent tools. `session_snapshot` is the one entry that depends on the session: it is listed only while the feed owner seam (`extensions/gentle-desktop-feed.ts`) is wired for this session, and absent otherwise (when listed it comes last); the `get_snapshot` method itself is always listed. The review slice advertises exactly its read and change methods and its one change event; review start, skip, and consent stay terminal-only. The stats slice advertises exactly its one read method and no event: usage stats are an explicit read. The updates slice advertises exactly its one read method and no event; running an update stays the launcher's job. The agent-definitions slice advertises exactly its one read method and no event; editing definitions stays a file edit. The package-status slice advertises exactly its one read method and no event; `/gentle:doctor` stays terminal-only. The background-subagents slice advertises exactly its read and change methods and no event; every answer carries the state. The host tools slice advertises its six methods (`set_host_activity` is sent only by `gentle-shell serve`) and its two call events. Method availability is not a claim that every dependency is loaded — see [Permission limits](#permission-limits), [Configuration limits](#configuration-limits), [Usage limits](#usage-limits), [Design limits](#design-limits), [Jobs limits](#jobs-limits), [Profiles limits](#profiles-limits), [Subagents limits](#subagents-limits), [Review limits](#review-limits), [Stats limits](#stats-limits), [Updates limits](#updates-limits), [Agent definitions limits](#agent-definitions-limits), [Status limits](#status-limits), [Background subagents limits](#background-subagents-limits), and [Host tools limits](#host-tools-limits). ### `get_snapshot` -Returns the current event sequence and a bounded state projection: +Returns the current event sequence, its epoch, and a bounded state projection: ```json { "schema": "gentle-shell.desktop-rpc/v1", "sequence": 0, + "epoch": "3b0e9a52-8c1d-4f7e-9a6b-2d5c7e1f4a90", "state": { "config": { "stores": [ @@ -91,18 +92,19 @@ Returns the current event sequence and a bounded state projection: { "store": "persona", "scope": "global+project", "readOnly": false, "status": "ok", "revision": "sha256:41aa…" }, { "store": "banner", "scope": "global", "readOnly": false, "status": "missing", "revision": "sha256:9c02…" }, { "store": "notifications", "scope": "global", "readOnly": false, "status": "ok", "revision": "sha256:d317…" }, - { "store": "mcp", "scope": "global+project", "readOnly": true, "status": "ok", "revision": "sha256:5e21…" }, - { "store": "pi_settings", "scope": "global+project", "readOnly": true, "status": "ok", "revision": "sha256:a8c4…" }, - { "store": "claude_bridge", "scope": "global", "readOnly": true, "status": "missing", "revision": "sha256:07fd…" } + { "store": "mcp", "scope": "global+project", "readOnly": false, "status": "ok", "revision": "sha256:5e21…" }, + { "store": "pi_settings", "scope": "global+project", "readOnly": false, "status": "ok", "revision": "sha256:a8c4…" }, + { "store": "claude_bridge", "scope": "global", "readOnly": true, "status": "missing", "revision": "sha256:07fd…" }, + { "store": "custom_models", "scope": "global", "readOnly": false, "status": "missing", "revision": "sha256:c4d9…" } ] } } } ``` -The projection carries only store identity, scope, mutability, status, and revision — never store content, never a path. It is the cheap way for a client to notice that one of the twelve revisions moved and then call `get_config` for that store. `state` is `{}` when no Desktop command has bound a session context yet, or when that context has no working directory: without one, the project and pin layers cannot be read truthfully, so nothing is projected instead of a guess. +The projection carries only store identity, scope, mutability, status, and revision — never store content, never a path. It is the cheap way for a client to notice that one of the thirteen revisions moved and then call `get_config` for that store. `state` is `{}` when no Desktop command has bound a session context yet, or when that context has no working directory: without one, the project and pin layers cannot be read truthfully, so nothing is projected instead of a guess. -This snapshot does not project permission state: use `get_permission_mode` for that. `sequence` is the number of delivered events, so a client that saw `seq: 4` expects `sequence: 4` from a fresh snapshot unless it missed an event. +This snapshot does not project permission state: use `get_permission_mode` for that. `sequence` is the number of delivered events, so a client that saw `seq: 4` expects `sequence: 4` from a fresh snapshot unless it missed an event. `epoch` names the numbering `sequence` counts in, as every event's `epoch` does (see [Events](#events)): a snapshot of another epoch than the events a client followed comes from a channel that numbers its events anew, so its `sequence` replaces the client's baseline even when it is smaller. #### Session sections @@ -123,6 +125,7 @@ Without a `sections` key the request is the legacy read above, byte-for-byte (ot { "schema": "gentle-shell.desktop-rpc/v1", "sequence": 4, + "epoch": "3b0e9a52-8c1d-4f7e-9a6b-2d5c7e1f4a90", "state": { "config": { "stores": ["…as above…"] }, "session": { @@ -158,7 +161,7 @@ Reads one existing configuration store through the owner that already reads it. | Param | Required | Type | Meaning | | --- | --- | --- | --- | -| `store` | yes | one of the twelve store identifiers below | The store to read. | +| `store` | yes | one of the thirteen store identifiers below | The store to read. | Any other key — including `scope`, `path`, `file`, or `physical_path` — is rejected as `invalid_request`. A string that is not a known store identifier is rejected as `unknown_store`. Neither case reads anything. @@ -173,9 +176,10 @@ Any other key — including `scope`, `path`, `file`, or `physical_path` — is r | `persona` | `readPersonaLayer` + `resolvePersonaMode` over `/persona.json` + `/.pi/gentle-ai/persona.json` | `global+project` | `false` | `{ mode }`: the persona in effect, the project layer winning. | | `banner` | `readBannerConfigSync` over `/banner.json` | `global` | `false` | `{ showRose, showTextLogo, color }`. | | `notifications` | `parseNotificationSettingsFile` over `/notifications.json` | `global` | `false` | The validated settings without `schema`, every `file:` sound replaced by `"file"`. | -| `mcp` | `readMcpConfig` (mirrors Pi's `loadMcpConfig`) over `/mcp.json` + `/.pi/mcp.json` (project file only for a trusted project) | `global+project` | `true` | `{ servers: [{ name, transport, enabled }], truncated, omitted }`, `transport` being `stdio` or `http`: at most 64 servers, in Pi's load order; `truncated` reports the cut at 64 and `omitted` counts servers left out because their name is longer than 128 characters. No `command`, `args`, `env`, `cwd`, `url`, `headers`, `oauth`, or `auth` value. | -| `pi_settings` | `readPiSettings` through Pi's `SettingsManager` over `/settings.json` + `/.pi/settings.json` (project file only for a trusted project) | `global+project` | `true` | Display settings only: `{ defaultProvider, defaultModel, defaultThinkingLevel, enabledModels, extensions, truncated }`, `extensions` being names. Packages (see `get_update_status`), the theme, and `sessionDir` are not part of it. | +| `mcp` | `readMcpConfig` (mirrors Pi's `loadMcpConfig`) plus `readMcpLayer` over `/mcp.json` + `/.pi/mcp.json` (project file only for a trusted project) | `global+project` | `false` | `{ servers: [{ name, transport, enabled }], truncated, omitted, documents: { global?, project? } }`, `transport` being `stdio` or `http`: at most 64 servers, in Pi's load order; `truncated` reports the cut at 64 and `omitted` counts servers left out because their name is longer than 128 characters. `documents` holds each layer Pi reads as its whole document, every secret replaced by `"•••"`. Writable per layer — see [`set_config`](#data-for-mcp). | +| `pi_settings` | `readPiSettings` through Pi's `SettingsManager` over `/settings.json` + `/.pi/settings.json` (project file only for a trusted project) | `global+project` | `false` | Display settings only: `{ defaultProvider, defaultModel, defaultThinkingLevel, enabledModels, extensions, truncated }`, `extensions` being names. Packages (see `get_update_status`), the theme, and `sessionDir` are not part of it. The four model keys are writable in the global file — see [`set_config`](#data-for-pi_settings). | | `claude_bridge` | `readClaudeBridgeConfig` over `/claude-bridge.json` | `global` | `true` | `{ plan }` from `provider.plan` in the config file of `pi-claude-bridge`, a third-party Pi package some users already have. `missing` when the file is absent. | +| `custom_models` | `readCustomModels` over `/models.json` (Pi's custom providers and models) | `global` | `false` | The whole document as Pi reads it (`providers`, and any other key), every secret replaced by `"•••"`. Writable — see [`set_config`](#data-for-custom_models). | Success: @@ -207,25 +211,26 @@ Success: | --- | --- | | `store` | The store identifier that was read. | | `scope` | Which owner layers this store is assembled from: `global`, `global+project`, or `local+repo`. | -| `readOnly` | `false` for the six writable stores (`profiles`, `profile_fallbacks`, `pins`, `persona`, `banner`, `notifications`); `true` for the three derived or installer-owned stores (`models`, `subagents`, `managed_assets`) and the three display stores (`mcp`, `pi_settings`, `claude_bridge`). | +| `readOnly` | `false` for the nine writable stores (`profiles`, `profile_fallbacks`, `pins`, `persona`, `banner`, `notifications`, `mcp`, `pi_settings`, `custom_models`); `true` for the three derived or installer-owned stores (`models`, `subagents`, `managed_assets`) and the `claude_bridge` display store. | | `status` | `ok` (normalized content follows), `missing` (no layer produced content because no layer file exists), or `invalid` (layers exist but none of them produced content). See [Layer semantics](#layer-semantics). | | `revision` | Opaque read-time digest of the canonical normalized content. See [Revision limits](#revision-limits). | | `value` | Normalized owner content, present when the store produced one. Absent when a layer is missing or invalid. | | `layers` | Per-layer status, `global` then `project`, or `local` then `repo`. Each entry is `ok`, `missing`, or `invalid` for the file that layer owns. | -| `writeTargets` | Present only for the three writable stores. One entry per file the owner rewrites, with that file's own `writeRevision` — the token `set_config` requires. See [Write targets](#write-targets). | +| `writeTargets` | Present only for the writable stores. One entry per file the owner rewrites, with that file's own `writeRevision` — the token `set_config` requires. See [Write targets](#write-targets). | #### Layer semantics `status` answers for the store; `layers` answers for each file it is assembled from. For a merged store the two are different questions: -- `profiles`, `profile_fallbacks`, `managed_assets`, `banner`, `notifications`, and `claude_bridge` have one layer, so `status` is that layer's status. +- `profiles`, `profile_fallbacks`, `managed_assets`, `banner`, `notifications`, `claude_bridge`, and `custom_models` have one layer, so `status` is that layer's status. - `mcp` and `pi_settings` follow Pi's project trust: Pi reads the project `mcp.json` and `settings.json` only when the session trusts the project, so these stores list a `project` layer only then. For an untrusted project (or a host that cannot say) `layers` holds the `global` layer alone and `value` ignores the project file. A file that is not JSON (or, for `mcp`, not an object with an `mcpServers` object) is an `invalid` layer and the other layer still merges. Pi does not announce a trust change to extensions, so a change made during the session is noticed when the next Desktop command binds the session: `mcp` and `pi_settings` are re-read then, and each whose revision moved is announced as an external `config_changed`. Until a command arrives nothing is pushed, so a client should re-read these stores (or send any command) after the user trusts or distrusts the project. -- `mcp` lists the servers Pi's MCP loader would produce from those files: a project entry replaces the global entry of the same name, a project entry without `command`, `url`, or `type` only overrides `enabled` (and exposure) of an existing global server, and an entry Pi would reject is left out while the rest of the file still loads. `transport` is the one Pi connects with: `http` whenever the entry has a `url` key (even with `type: "stdio"` and a `command`), otherwise `stdio`; `enabled` is `false` only when the file says so. Pi's loader is not part of its package exports, so `lib/mcp-config.ts` mirrors that resolution and its per-entry checks (OAuth and `auth` included), and a test compares it with Pi's own loader. Servers an extension registers at runtime are not listed. -- `pi_settings` is Pi's own merged view (global, then the trusted project file on top, with Pi's migrations), read without taking Pi's settings lock and never written back. `defaultProvider` is shown only as one plain token. `defaultModel` and each `enabledModels` entry are shown only in Pi's `--models` shape: a bare model id or `provider/modelId` (the id may hold more `/`, as in `openrouter/anthropic/claude-3.5-sonnet`), with wildcards and an optional `:thinking` suffix; every `/`-separated segment starts with a letter or digit. Any other value is `null` (or left out of `enabledModels`): a value with both `@` and `:` (`user:secret@host`), a backslash, an absolute path (`/home/...`) or a `./` / `../` path, a URL, control text, or more than 128 characters. `defaultThinkingLevel` is one of Pi's levels or `null`; `enabledModels` is `null` when no layer restricts models. An extension is named by its last path segment, and only when that segment is a plain file or package name (letters, digits, `.`, `_`, `+`, `-`; at most 128 characters); an entry that is a URL, or whose name is longer, credential-shaped, or holds control text, is left out. Each list keeps at most 64 entries and `truncated` reports a cut. When Pi's own getters cannot read a merged value, `value` is absent, every layer whose file exists reads `invalid`, and an absent file still reads `missing`. +- `mcp` lists the servers Pi's MCP loader would produce from those files: a project entry replaces the global entry of the same name, a project entry without `command`, `url`, or `type` only overrides `enabled` (and exposure) of an existing global server, and an entry Pi would reject is left out while the rest of the file still loads. `transport` is the one Pi connects with: `http` whenever the entry has a `url` key (even with `type: "stdio"` and a `command`), otherwise `stdio`; `enabled` is `false` only when the file says so. Pi's loader is not part of its package exports, so `lib/mcp-config.ts` mirrors that resolution and its per-entry checks (OAuth and `auth` included), and a test compares it with Pi's own loader. Servers an extension registers at runtime are not listed. `documents.global` and `documents.project` are the files an editor changes: each layer Pi reads, as its whole document (`mcpServers`, `autoEnableCodemode`, any other key), present when that file is a JSON object whose `mcpServers`, if any, is an object, and redacted (see [Secrets](#secrets-in-custom_models-and-mcp)). A server Pi would refuse stays in its document as written; Pi skips only that server, and so does `servers`. +- `pi_settings` is Pi's own merged view (global, then the trusted project file on top, with Pi's migrations), read without taking Pi's settings lock and never written back by a read. `defaultProvider` is shown only as one plain token. `defaultModel` and each `enabledModels` entry are shown only in Pi's `--models` shape: a bare model id or `provider/modelId` (the id may hold more `/`, as in `openrouter/anthropic/claude-3.5-sonnet`), with wildcards and an optional `:thinking` suffix; every `/`-separated segment starts with a letter or digit. Any other value is `null` (or left out of `enabledModels`): a value with both `@` and `:` (`user:secret@host`), a backslash, an absolute path (`/home/...`) or a `./` / `../` path, a URL, control text, or more than 128 characters. `defaultThinkingLevel` is one of Pi's levels or `null`; `enabledModels` is `null` when no layer restricts models. An extension is named by its last path segment, and only when that segment is a plain file or package name (letters, digits, `.`, `_`, `+`, `-`; at most 128 characters); an entry that is a URL, or whose name is longer, credential-shaped, or holds control text, is left out. Each list keeps at most 64 entries and `truncated` reports a cut. When Pi's own getters cannot read a merged value, `value` is absent, every layer whose file exists reads `invalid`, and an absent file still reads `missing`. A write changes only the four model keys of the global file (see [`data` for `pi_settings`](#data-for-pi_settings)); its one write target is that file. - `claude_bridge` reads `claude-bridge.json` in the Pi agent dir, the config file of the third-party `pi-claude-bridge` package. Gentle Shell does not install or write it; the store only lets a client show the plan a user already chose. `value` is `{ "plan": | null }`: the plan when `provider.plan` is a short plain token (letters, digits, `.`, `_`, `-`; at most 32 characters), otherwise `null`. No other key crosses. The installed package version is not reported: Pi's package listing can run `npm root -g` synchronously, which a revision recompute must not do. - `persona` has a `global` layer (`persona.json` in the Gentle config home) and a `project` layer (`/.pi/gentle-ai/persona.json`); `value` is `{ "mode": "gentleman" | "neutral" }`, the mode in effect (the project layer wins), exactly as the prompt build resolves it. - `banner` is `{ showRose, showTextLogo, color }` from `banner.json`. A file without those three valid settings is `invalid` and is never repaired by a read; extra keys are ignored, as the `/gentle:banner` editor ignores them, and a Desktop write keeps only the three settings. - `notifications` is the owner's validated `notifications.json` without its `schema` key. Every `file:` sound is replaced by the marker `"file"`, so no sound path crosses the wire. +- `custom_models` is Pi's own `models.json` in the agent home — the custom providers and models (`providers.`: `baseUrl`, `api`, `apiKey`, `headers`, `models`, `modelOverrides`, …). It is read exactly as Pi loads it: `//` comments and trailing commas are allowed, and the document must pass the schema Pi publishes with its package (`schemas/models.schema.json`); a file that does not is `invalid`, because Pi ignores it whole. `value` is the whole document, unknown keys included, with the secrets redacted (see [Secrets](#secrets-in-custom_models-and-mcp)). Pi has no project `models.json`. - `subagents` mirrors the runtime reader: a layer that cannot be parsed is skipped and the remaining layer still merges. `status` is `ok` as soon as one layer is usable, and `layers` still names the broken one. - `models` keeps the owner's merge rule, which rejects the saved routing when a layer it reads is malformed; there `status` is `invalid` even if the other layer is fine. - `missing` means every layer file is absent. `invalid` means layer files exist but none produced content; in that case the owner would fall back to its own defaults, which are not the content of this store, so no `value` is returned. @@ -315,6 +320,9 @@ A write target is one file, not one store, with one exception: `persona`'s `glob | `persona` | `global` | `/persona.json`, plus `/.pi/gentle-ai/persona.json` when it already exists | | `banner` | `global` | `/banner.json` | | `notifications` | `global` | `/notifications.json` | +| `mcp` | `global`, plus `project` for a trusted project | `/mcp.json`, `/.pi/mcp.json` | +| `pi_settings` | `global` | `/settings.json` (its four model keys) | +| `custom_models` | `global` | `/models.json` | `persona`'s `global` target covers both persona files, because the owner rewrites the project file too when it exists: its `writeRevision` digests both layers (so a project edit makes a token stale even while the global file is missing), and its `value` is `{ global, project }` layer states rather than one file. Each file is replaced atomically, but the two-file write is not a transaction: a failure after the global file is written can leave the project file unchanged, and the answer reports the layers as they are. @@ -360,11 +368,11 @@ Writes one existing, owner-maintained store. Desktop names a store and, for `pin | Param | Required | Type | Meaning | | --- | --- | --- | --- | -| `store` | yes | `profiles` \| `profile_fallbacks` \| `pins` | The one store to write. | -| `data` | yes | store-specific object (below) | The **complete** new content of that store, not a patch. | +| `store` | yes | a writable store: `profiles` \| `profile_fallbacks` \| `pins` \| `persona` \| `banner` \| `notifications` \| `mcp` \| `pi_settings` \| `custom_models` | The one store to write. | +| `data` | yes | store-specific object (below) | The **complete** new content of that store (or of one `pins`/`mcp` layer), not a patch; `pi_settings` alone takes a patch of its model keys. | | `expectedRevision` | yes | string | `writeTargets[].writeRevision` of the target as the client last read it. | -Exactly these three keys are accepted. Any other key — including `scope`, `path`, `file`, or `physical_path` — is rejected as `invalid_request` before anything is read or written. An unknown store string is `unknown_store`. A write to `models`, `subagents`, `managed_assets`, `mcp`, `pi_settings`, or `claude_bridge` is `read_only`, rejected before its `data` is inspected, because the reason the write cannot happen is the store, not the payload. +Exactly these three keys are accepted. Any other key — including `scope`, `path`, `file`, or `physical_path` — is rejected as `invalid_request` before anything is read or written. An unknown store string is `unknown_store`. A write to `models`, `subagents`, `managed_assets`, or `claude_bridge` is `read_only`, rejected before its `data` is inspected, because the reason the write cannot happen is the store, not the payload. #### `data` for `profiles` @@ -435,13 +443,85 @@ One selected layer and what it should hold — a profile to pin, or `null` to cl A layer whose file currently reads `invalid` is likewise a valid target for a set: replacing a broken pin with a valid one is an explicit operation. +#### `data` for `custom_models` + +The complete new `models.json`, as `get_config` returned it with the client's changes: + +```json +{ + "providers": { + "local": { + "baseUrl": "http://127.0.0.1:11434/v1", + "api": "openai-completions", + "apiKey": "•••", + "models": [{ "id": "llama-3.1-70b", "contextWindow": 128000 }] + } + } +} +``` + +It replaces the whole file. It must pass Pi's own models schema (`providers` is required; unknown keys are kept, as Pi keeps them); otherwise the answer is `invalid_data` and its `message` names the first problem as Pi's loader would, for example `Invalid custom_models data: providers.local.models.0.id: must not have fewer than 1 characters`. The file is written as plain JSON (`0600`, atomically), so comments in it do not survive a write. A file that currently reads `invalid` may be replaced: nothing of it is kept. + +After a write that changed the file, the session's model registry re-reads it before the answer is sent (`modelRegistry.refresh`, no network), so the new models are usable in this session at once. Other sessions on the same machine refresh theirs when their watcher sees the change (see [`config_changed`](#config_changed)). + +#### `data` for `pi_settings` + +A patch of Pi's four model keys in the global `settings.json`: + +```json +{ "defaultProvider": "openai", "defaultModel": "gpt-5", "defaultThinkingLevel": null, "enabledModels": ["openai/gpt-5", "anthropic/*"] } +``` + +| Field | Required | Meaning | +| --- | --- | --- | +| `defaultProvider` | no | A provider id, or `null` to remove the key. | +| `defaultModel` | no | A model id, or `null` to remove the key. | +| `defaultThinkingLevel` | no | A Pi thinking level, or `null` to remove the key. | +| `enabledModels` | no | The scoped models (patterns such as `anthropic/*` or `openai/gpt-5`), or `null` to remove the key (every model is available). | + +A key the patch leaves out keeps its value. The store's `value` is Pi's merged display view (a trusted project's `settings.json` on top), so a patch never makes a client send back values it saw only through the merge or the display filter; a key a trusted project file sets still wins over what the global file holds, and the answer shows the result. The `expectedRevision` is the `global` target's `writeRevision`, a digest of the global file's model keys. See [Configuration limits](#configuration-limits) for the value rules. + +#### `data` for `mcp` + +One selected layer and its complete new document, as `value.documents` returned it with the client's changes: + +```json +{ + "source": "global", + "document": { + "mcpServers": { + "files": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], "env": { "TOKEN": "•••" } }, + "docs": { "url": "https://docs.example/mcp", "headers": { "Authorization": "•••" } } + } + } +} +``` + +| Field | Required | Meaning | +| --- | --- | --- | +| `source` | yes | `global` (`/mcp.json`) or `project` (`/.pi/mcp.json`, only while the session trusts the project; otherwise `project_untrusted`). | +| `document` | yes | The whole new file for that layer. | + +Exactly `{source, document}` is accepted. Every server is checked as Pi loads it: Pi's own `validateMcpServerConfig` (stdio `command`/`args`/`env`/`cwd`, HTTP `url`/`headers`/`oauth`/`auth`, `enabled`, `exposure`, `toolExposure`, `description`, `timeout`), names that clash once `-` and `_` are equal are refused, `autoEnableCodemode` must be a boolean, and for the `project` layer an override must name a global server and set only `enabled`, `exposure`, or `toolExposure`, and `auth` is refused. The first problem answers `invalid_data` with a message such as `Invalid mcp data: server "docs": auth is only allowed in the global mcp.json`. The `expectedRevision` is that layer's own `writeRevision`. Pi's validator is not part of its package exports, so it is loaded from Pi's installed package by path (`dist/core/mcp-servers.js`); when a Pi update moves it, every write answers `invalid_data` naming the missing validator instead of writing unchecked. + +Pi's MCP extension reads `mcp.json` only when a session starts. After a write that changed a layer, the session reloads itself (as `/reload` does) once it is idle and after the answer has been sent, so its servers connect without a restart; the client sees the session's usual reload (a new event epoch). Other sessions get a `config_changed` (`source: "external"`) and load the servers on their next reload or start. + +#### Secrets in `custom_models` and `mcp` + +No secret crosses the wire. Every string in a secret position is read as the marker `"•••"`: + +- `custom_models`: each provider's `apiKey`, and every value of `headers` on a provider, on a `models[]` entry, and on a `modelOverrides` entry; +- `mcp` documents: every value of a server's `env` and `headers`, its `oauth.clientSecret`, and its `url` when the URL carries userinfo (`user:pass@`) or a query string (where keys often travel). The `servers` summary carries no such field at all. + +That covers literal keys as well as `$NAME`/`${NAME}` references and `!command` values, which can carry a key too. Sending `"•••"` back in the same position keeps the value the file holds there — the same provider's `apiKey` or header, the same model (matched by `id`, so models may be reordered), the same MCP server's `env` entry, header, client secret, or URL. `"•••"` where the current file holds no string at that position is `invalid_data`; any other string replaces the secret. The revisions digest the real content, so a secret changed elsewhere still moves them. Values outside these positions (`command`, `args`, `cwd`, a plain `url`, `baseUrl`, …) are returned as written: they are the user's own configuration an editor has to show. + #### Validation and revision guard The checks below run in this order, and the first one that fails answers the request. Nothing is read or written after a rejection. 1. **Envelope** (`invalid_request`): exactly the keys `store`, `data`, and `expectedRevision`; `store` must be a string; `data` must be present. A request missing `data` is malformed whatever store or revision it names, so this check comes before the store rules — a `models` write without `data` is `invalid_request`, not `read_only`. Store contents are not looked at here. -2. **Store identity** (`unknown_store`): the string must be one of the twelve store identifiers. -3. **Mutability** (`read_only`): `models`, `subagents`, `managed_assets`, `mcp`, `pi_settings`, and `claude_bridge` are rejected before their `data` is inspected or their revision is compared, so any payload gets the same answer. +2. **Store identity** (`unknown_store`): the string must be one of the thirteen store identifiers. +3. **Mutability** (`read_only`): `models`, `subagents`, `managed_assets`, and `claude_bridge` are rejected before their `data` is inspected or their revision is compared, so any payload gets the same answer. 4. **Usable revision** (`revision_conflict`): `expectedRevision` must be a non-empty string. Absent, empty, and non-string tokens are all "the client did not prove it saw the current state", and this is decided before the payload is validated. 5. **Session roots** (`config_unavailable`): the bound session must have a working directory. 6. **Payload** (`invalid_data`): `data` is validated by the owner's own normalizer (`normalizeProfilesFile`, `normalizeFallbacksFile`, the pin name and store rules). A value the owner would reject is `invalid_data`. So is any value the owner's normalizer would **rewrite or silently drop** — an illegal profile or agent name, a stale `active` marker, an unknown workflow mode, an empty fallback chain, the `effort` alias, an organic workflow entry, an unknown routing member. A write is applied complete or not at all, so a client can never delete or silently reshape content by sending it: send exactly the canonical form `get_config` returned. For `pins`, `profile` must be a defined profile name or the literal `null`; a missing, empty, non-string, or unknown `profile`, an extra `data` key, and a `source` other than `local`/`repo` are all `invalid_data`, and a pin request outside a resolvable Git worktree is `config_unavailable`. @@ -484,7 +564,7 @@ The payload is the same `get_config` projection of the store **after** the write | Field | Meaning | | --- | --- | -| `writeTarget` | The target this request named: `global`, `local`, or `repo`. | +| `writeTarget` | The target this request named: `global`, `project`, `local`, or `repo`. | | `writeRevision` | That target's resulting revision, to use as `expectedRevision` on the next write. | | `changed` | `true` only if this request actually changed the target's content. A no-op answers `false` with the unchanged state and no event. | @@ -1183,7 +1263,7 @@ Any other key (including a Pi-style `sessionPath`), a missing or empty `id`, or - **Switching to the current session** is a no-op: `{ "id": …, "changed": false }`, no switch, no event. - **A cancelled switch** (an extension's `session_before_switch` handler cancelled it) answers `{ "id": …, "changed": false, "cancelled": true }`; the session is unchanged. - **A refused switch** (for example the session's working directory no longer exists) answers `sessions_unavailable` with a fixed message; Pi's error, which names paths, never crosses. -- **The sequence resets.** A switch starts a new session, exactly like Pi's own `switch_session`: the old session receives `session_shutdown`, the new one starts with a fresh channel, and event `seq` starts again at 1. The response is published by the new session, after it started, still correlated by `requestId`; an event of the new session may precede it. Fetch `get_snapshot` after a switch. +- **The sequence resets.** A switch starts a new session, exactly like Pi's own `switch_session`: the old session receives `session_shutdown`, the new one starts with a fresh channel, a new `epoch`, and event `seq` starts again at 1. The response is published by the new session, after it started, still correlated by `requestId`; an event of the new session may precede it. Fetch `get_snapshot` after a switch. - **One switch at a time; nothing is lost.** From the moment a `switch_session` is dispatched until it answers, every other Desktop request (any method, including another `switch_session` and `capabilities`) is answered at once with the retryable `session_switching` error and does nothing. A request that was already waiting on an owner when the switch tears the session down is answered `session_switching` right before the teardown, and a request Pi delivers to the replaced session during the replacement is answered `session_switching` too. Every request gets exactly one response; only the switch itself answers from the new session. This includes `capabilities` and `get_snapshot`: they are refused too, because their answer would describe the session being replaced. Retry every refused request, including those two, after the switch's response arrives. A switch that ends without replacing the session (cancelled, refused, or `not_found`) releases the gate at once. Use a fresh `requestId` per request: the exemption for the in-flight switch is by `requestId`. - **A streaming turn is aborted.** Pi settles any active response before it replaces the session, so a switch during a streaming turn aborts that turn and persists it to the old session first, as Pi's own `switch_session` does. - This slice emits no event of its own. @@ -1568,8 +1648,8 @@ Lists the providers this session knows models for, and whether each has credenti "ok": true, "data": { "providers": [ - { "provider": "anthropic", "displayName": "Anthropic", "configured": true, "type": "oauth", "source": "stored" }, - { "provider": "openai-codex", "displayName": "OpenAI Codex", "configured": false, "type": null, "source": null } + { "provider": "anthropic", "displayName": "Anthropic", "configured": true, "type": "oauth", "source": "stored", "loginKinds": ["oauth", "api_key"] }, + { "provider": "openai-codex", "displayName": "OpenAI Codex", "configured": false, "type": null, "source": null, "loginKinds": ["oauth", "device"] } ], "truncated": false } @@ -1582,6 +1662,7 @@ Lists the providers this session knows models for, and whether each has credenti | `configured` | Pi has credentials it can use for this provider. | | `type` | `oauth` (a sign-in) or `api_key` when configured, otherwise `null`. | | `source` | Where Pi found them: `stored` (Pi's credential store), `runtime`, `environment`, `models_json` (a key or a command in `models.json`; which one is not said), or `extension` (a provider extension's fallback). `null` when not configured. | +| `loginKinds` | How a client can sign in to this provider, from Pi's provider definition: `oauth` (a browser sign-in), `device` (a device code the user types on the provider's page), `api_key` (a key, with [`set_api_key`](#set_api_key)). Pi's OAuth flows that run a device code only (`github-copilot`, `kimi-coding`, `meta`, `xai`) list `device` and not `oauth`; `openai-codex` and `radius` list both (the flow asks which). Empty when the provider takes only ambient credentials (environment, AWS profiles). | The registry's status label (an environment variable name or a command) never crosses, nor any value. Errors: `invalid_request` (any param), and `auth_unavailable` (no registry in this session, or the registry read failed). @@ -1595,6 +1676,206 @@ Makes this session pick up credentials added or removed elsewhere (another termi `failedProviders` lists the ids whose refresh reported an error; the error text never crosses. Errors: `invalid_request`, `auth_unavailable` (no registry in this session, or the session was replaced during the reload), and `reload_failed` (the refresh itself failed). +### `list_available_models` + +The models this session's Pi can use now and the thinking levels of its current model: what Pi RPC's `get_available_models` and `get_available_thinking_levels` answer, from the same registry (`modelRegistry.getAvailable()`, read from memory; no network, no turn). A client without a conversation of its own (a phone, Configuration on a [server](serve.md#desktop-rpc-without-a-session-post-apidesktop)) fills a model picker with it. Params must be an empty object. It has no side effects and emits no event; read it again after a sign-in or a `reload_credentials`. + +```json +{ + "ok": true, + "data": { + "models": [ + { "provider": "anthropic", "id": "claude-sol", "name": "Claude Sol", "contextWindow": 200000, "reasoning": true, "input": ["text", "image"] } + ], + "thinkingLevels": ["off", "minimal", "low", "medium", "high", "xhigh"], + "current": { "provider": "anthropic", "id": "claude-sol", "thinkingLevel": "high" }, + "truncated": false + } +} +``` + +| Field | Meaning | +| --- | --- | +| `models` | In Pi's order, at most 1000 (`truncated` says more were left out). `provider` and `id` always (a provider id that is not a plain name, or an id over 256 characters or with control characters, is skipped); `name` (up to 128 characters), `contextWindow`, `reasoning` and `input` (`text`, `image`) only when Pi gives them that shape. Nothing else of a model crosses: no base URL, headers, cost or compatibility settings. | +| `thinkingLevels` | What the current model accepts, low to high, by Pi's own rule (what `get_available_thinking_levels` answers: `off` only for a model without reasoning, Pi's placeholder before any model is chosen included). | +| `current` | The session's model and thinking level; absent when no model is chosen yet. | + +Errors: `invalid_request` (any param), and `auth_unavailable` (no registry in this session, a Pi without the available-model snapshot, or the read failed). + +### `set_host_tools` + +Registers the tools a client provides and runs itself (*host tools*): the desktop app today, a phone later. The agent sees each one as an ordinary tool; when it calls one, this channel emits [`host_tool_call`](#host_tool_call), the client runs the tool on its own device, and answers with [`host_tool_result`](#host_tool_result). How to use a tool is told to the model by the tool's `description` and `guidelines`, so a client needs no extension or instructions file on the machine the agent runs on. + +```json +{ + "provider": "gentle-desktop", + "tools": [ + { + "name": "desktop_screenshot", + "label": "Screenshot", + "description": "Capture the user's screen or one window and return it as an image.", + "parameters": { "type": "object", "properties": { "window": { "type": "string" } } }, + "guidelines": ["Use desktop_screenshot when the user refers to what is on their screen."] + } + ] +} +``` + +| Field | Rule | +| --- | --- | +| `provider` | 1-64 characters, no control characters. Names the client. Through `gentle-shell serve` the server replaces it with the calling device's id, so a client cannot register as another device. | +| `tools` | At most 32. The list is the provider's whole set: it replaces what that provider registered before, and an empty list unregisters it. | +| `name` | `^[a-z][a-z0-9_]{0,63}$`, unique in the list. | +| `label` | 1-64 characters; shown in UIs. | +| `description` | 1-4096 characters; what the model reads about the tool. Its first line is also the tool's entry in the system prompt's tool list. | +| `parameters` | A JSON Schema object with `type: "object"`, at most 16 KiB serialized. Pi validates the model's arguments against it before a call goes out. | +| `guidelines` | Optional, at most 16 single-line strings of up to 512 characters. Each becomes a bullet in the system prompt's rules while the tool is registered. A bullet that does not contain the tool's name gets `name: ` in front, so the model knows which tool it means. | + +Unknown fields are rejected. The answer lists what registered and what did not: + +```json +{ "ok": true, "data": { "registered": ["desktop_screenshot"], "rejected": [{ "name": "bash", "reason": "A built-in or extension tool already has this name" }] } } +``` + +A name is rejected only when a built-in or extension tool already has it; the rest of the set still registers. Several providers may offer the same name (the Mac app and a phone can both offer `device_screenshot`), even with different descriptions or schemas: the model sees one tool, with the definition of the provider that registered it most recently. When that provider drops it, the next most recent provider's definition takes over; when the last one drops it, the tool is hidden. Each tool is registered with Pi's `pi.registerTool()` after startup (again whenever its active definition changes), which refreshes Pi's tool registry and system prompt at once, so the change applies from the next model request. Pi cannot remove a tool, so an unregistered host tool is registered again as `hidden`: never declared to the model, never callable, its guidelines out of the prompt. Its name is free for any provider afterwards. + +A call to a tool several providers offer goes to one of them, named in [`host_tool_call`](#host_tool_call)'s `provider`: the most recently active connected provider that offers it, as reported by [`set_host_activity`](#set_host_activity); without that report (one client over stdio), or when none of them is connected, the provider that registered it most recently. + +Registrations belong to the session: a new session, a `switch_session`, or a shutdown unregisters every host tool and fails every call still waiting, so a client registers its set again after the session changes. Errors: `invalid_request` (the message says which field), `host_tools_unavailable` (the running Pi has no tool registration API, or registering failed). + +### `host_tool_result` + +The client's answer to a `host_tool_call`: + +```json +{ "callId": "htc_…", "content": [{ "type": "text", "text": "Captured the editor window." }, { "type": "image", "data": "iVBORw0KGgo…", "mimeType": "image/png" }], "isError": false, "details": { "window": "editor", "width": 1280 } } +``` + +`content` holds 1-64 items, each `{ "type": "text", "text" }` or `{ "type": "image", "data": , "mimeType": "image/…" }`, at most 8 MiB together (text counted in UTF-8 bytes, images in base64 characters). It is what the model reads as the tool's result; with `isError: true` the model reads it as a failed call. `details` (optional, a JSON object of at most 1 MiB serialized) becomes the Pi tool result's `details` as sent, so a client draws from the tool result in the transcript (`get_messages`, `get_entries`) the way an extension's tool result does; the model never reads it. Without it, `details` is `{ "provider", "callId" }`. Answers `{ "accepted": true }`. Errors: `invalid_request`, `too_large` (content over 8 MiB, or `details` over 1 MiB), `unknown_call` (no call with this id in this session), `already_answered` (the call is settled: answered, cancelled, or timed out). Only the first answer counts. + +### `host_tool_progress` + +A heartbeat from the provider while it is still working on a call, so a long, user-paced call (a review the user is reading, a browser wait, a device flow, a download) is not failed after 10 minutes: + +```json +{ "callId": "htc_…", "message": "Waiting for the user's review" } +``` + +`callId` is the call's id; `message` (optional, at most 512 characters) is reserved for showing progress and ignored for now. Each `host_tool_progress` restarts the call's no-answer deadline at 10 minutes from now; there is no upper bound on a call's total time while heartbeats keep coming. Answers `{ "extended": true, "deadlineMs": }`, the new deadline. Errors: `invalid_request`, `unknown_call`, `already_answered` (the call was answered, cancelled, or timed out: stop working on it). The request is limited to 64 KiB like any other method. + +A client sends it every 60 s for every in-flight host tool call it is still working on, whatever the tool, and stops when it answers the call or gets its `host_tool_cancel`. A client that dies or hangs stops sending, and the call still fails 10 minutes after its last heartbeat, so a dead client never blocks a turn forever. + +### `host_message` + +Puts a client's custom message into the conversation, the way an extension does with Pi's `pi.sendMessage()` (for example: the user clicked a button in a generated UI): + +```json +{ "customType": "host.genui.event", "content": "The user clicked Save on surface s1.", "display": true, "details": { "surface": "s1" }, "deliver": "auto" } +``` + +| Field | Required | Meaning | +| --- | --- | --- | +| `customType` | yes | `^host\.[a-z0-9][a-z0-9_.-]{0,63}$`. The `host.` prefix keeps client messages apart from extensions' own. | +| `content` | yes | The text the model reads (as a user-role message), at most 64 KiB of UTF-8. May be empty. | +| `display` | yes | Whether a transcript shows the message; the model reads it either way. | +| `details` | no | A JSON object of at most 1 MiB serialized, kept with the message for the client; the model never reads it. | +| `deliver` | yes | `auto`, `steer`, `followUp` or `nextTurn`. | +| `triggerTurn` | no | Boolean, passed to Pi (see below). | + +`auto` is what a client wants almost always: when the agent is idle the message starts a run (`triggerTurn`, default `true`; with `false` it is only recorded), and while a run is going it steers that run (delivered after the current tool calls, before the next model request). `steer`, `followUp` and `nextTurn` are Pi's own `deliverAs` with `triggerTurn` passed as given: while a run is going `steer` and `followUp` queue the message into it; `nextTurn` holds it until the next run starts; when idle, a message without `triggerTurn: true` is only recorded. The message is a session entry (`custom_message`) like any extension's custom message, so a client rebuilds its state from `get_entries` / `get_messages`. Answers `{ "delivered": true }` once Pi has it (the run it starts goes on afterwards). Errors: `invalid_request`, `too_large` (content over 64 KiB or `details` over 1 MiB), `host_messages_unavailable` (the running Pi cannot take messages). + +### `set_host_context` + +Keeps a hidden context message for one provider, added before every agent run while it is set (for example: which simulators are booted): + +```json +{ "provider": "gentle-desktop", "content": "Booted simulators: iPhone 16 (iOS 18.2).", "details": { "booted": ["iPhone 16"] } } +``` + +`provider` is 1-64 characters; `content` at most 64 KiB of UTF-8, and an empty `content` clears the provider's context; `details` is optional, a JSON object of at most 1 MiB serialized. While set, Pi's `before_agent_start` adds a custom message `{ "customType": "host.context.", "content", "display": false, "details" }` to each run (one per provider, at most 16 providers), exactly as the generative UI extension adds its own context. Each injected message is part of that run's history (so it is in `get_messages`); a cleared context is not added to later runs. A new `set_host_context` for the same provider replaces content and details. Contexts belong to the session: a new session, a `switch_session` or a shutdown clears them all. Answers `{ "set": true }`. Errors: `invalid_request`, `too_large` (content or `details` over their limits, or a 17th provider), `host_messages_unavailable`. + +### `set_host_activity` + +Sent by [`gentle-shell serve`](serve.md#host-tools), never by an app: the providers that are connected right now, most recently active first. It decides which provider runs a call to a host tool several providers offer. + +```json +{ "providers": ["", ""] } +``` + +At most 64 distinct providers of 1-64 characters each; the list replaces the previous one, and a session change forgets it. Answers `{ "set": true }`. Errors: `invalid_request`. + +### `login_start` + +Starts Pi's own sign-in to a provider for a client that is not in front of this machine: the flow `/login` runs, through Pi's model runtime (`ModelRuntime.login`, behind the session's `ctx.modelRegistry`). What Pi's login dialog would show becomes a [`login_prompt`](#login_prompt) event; each question waits for [`login_complete`](#login_complete); the end is one [`login_finished`](#login_finished). + +```json +{ "provider": "anthropic", "kind": "oauth" } +``` + +`provider` is a provider id from [`get_auth_status`](#get_auth_status). `kind` is optional: `oauth` (the provider's OAuth sign-in, a browser sign-in or a device code, whichever its `loginKinds` say) or `api_key` (the provider's interactive key setup, for a provider whose key comes with other values, such as an account id). Without it, `oauth` when the provider has one, else `api_key`. Answers `{ "loginId": "login_<16 hex>" }` before the flow's first event. One sign-in per provider at a time (also against `set_api_key` and `remove_credentials` for it), and each is cancelled after 15 minutes. A session change (new session, `switch_session`, shutdown) cancels it, with no `login_finished`. + +On success Pi stores the credential in its credential store (`auth.json` in the agent home, owner-only) exactly as `/login` does, synchronizes the provider, and this slice then refreshes the registry as [`reload_credentials`](#reload_credentials) does: the provider's models are available at once, without restarting the session. Other sessions read the stored credential on their next request and list the provider as configured after their own `reload_credentials`. + +Errors: `invalid_request`, `login_unavailable` (no model runtime in this session), `unknown_provider`, `login_unsupported` (the provider has no sign-in of that kind), `login_in_progress`. + +A browser sign-in whose provider redirects to a loopback callback on this machine (`http://localhost:1455/auth/callback` for OpenAI, `http://localhost:53692/callback` for Anthropic) cannot be completed by the browser of another device: that redirect would reach the client's own machine. Pi listens for it here and, at the same time, asks for the code or the redirect URL to be pasted (`input` with `redirectPrefix`). A client intercepts its browser's redirect to `redirectPrefix` (or lets the user paste the address bar) and sends the full URL with `login_complete`; Pi checks the state and exchanges the code exactly as its callback would. When the redirect does reach this machine's callback (the client runs on it), Pi completes on its own and the paste prompt is withdrawn. + +### `login_complete` + +Answers the question a sign-in is waiting on (the last `login_prompt` of kind `input`): + +```json +{ "loginId": "login_…", "value": "http://localhost:1455/auth/callback?code=…&state=…" } +``` + +`value` is at most 8 KiB: the pasted code, the full redirect URL, the text typed, the key (for `secret: true`), or, for a choice (`options`), one option's `id`. Answers `{ "accepted": true }`. Errors: `invalid_request` (also a value that is not one of the options), `unknown_login` (no such sign-in running, or it finished), `no_pending_prompt` (the sign-in is not waiting for an answer: a device code, or the redirect already reached Pi's callback). + +### `login_cancel` + +```json +{ "loginId": "login_…" } +``` + +Ends a running sign-in: Pi's flow is aborted, nothing is stored, and `login_finished` follows with `ok: false` and `error: "Sign-in cancelled"`. Answers `{ "cancelled": true }`. Errors: `invalid_request`, `unknown_login`. + +### `set_api_key` + +Saves an API key for a provider, the way `/login`'s key setup does: the provider's own key setup (`apiKey.login`) receives the key, and Pi stores `{ "type": "api_key", "key" }` in its credential store (owner-only) and synchronizes the provider; then the registry is refreshed as `reload_credentials` does. + +```json +{ "provider": "openrouter", "key": "sk-or-…" } +``` + +`key` is one line of 1-4096 printable characters; surrounding whitespace is dropped. Answers `{ "saved": true }`. The key is never echoed in an answer, an event or an error, and this process never logs it. Errors: `invalid_request`, `login_unavailable`, `unknown_provider`, `login_unsupported` (no key setup: ambient credentials only, or OAuth only), `login_in_progress`, `interactive_setup_required` (the provider asks for more than the key; use `login_start` with `kind: "api_key"`), `save_failed`. + +### `remove_credentials` + +```json +{ "provider": "openrouter" } +``` + +`/logout`: removes what Pi stored for the provider, a sign-in or a key, through Pi's runtime (`ModelRuntime.logout`), then refreshes the registry. Environment variables and `models.json` are not touched, so a provider configured there stays configured. Answers `{ "removed": true }`, or `{ "removed": false }` when nothing was stored for it. Errors: `invalid_request`, `login_unavailable`, `login_in_progress`, `remove_failed`. + +### `list_packages` + +The packages Pi's settings name, as `gentle-shell list` prints them. Params must be an empty object. + +```json +{ "ok": true, "data": { "packages": [{ "source": "npm:pi-skills", "version": "1.4.0", "scope": "user" }, { "source": "git:github.com/acme/tools", "scope": "project" }] } } +``` + +`scope` is `user` (the agent home's settings) or `project` (the session folder's). `version` is the installed package's `package.json` version, when it is installed and has one. A local path is listed absolute (settings keep it relative to their own folder, while `remove_package` resolves a path against the session's folder), so every listed `source` can be passed to `remove_package` as it is. At most 500. Errors: `invalid_request`, `packages_unavailable`. + +### `install_package` + +### `remove_package` + +```json +{ "source": "npm:pi-skills", "scope": "user" } +``` + +Run the same CLI a user would, as a job: `gentle-shell [home] install [-l]` / `remove [-l]` (`-l` for `scope: "project"`; `scope` defaults to `user`), with the launcher and home this session was started with, in the session's folder, stdin closed, color off. So the source syntax (`npm:`, `git:`, URLs, local paths), the project trust check (a project-scope change needs the folder trusted), the npm or git work and the settings write are the CLI's own, and so are its error messages. `source` is 1-1024 characters, without control characters, surrounding spaces, or a leading `-` (it would be read as an option). Answers `{ "jobId": "pkg_<16 hex>" }`, then [`package_progress`](#package_progress) events with the CLI's output lines and one [`package_finished`](#package_finished). One job at a time per session; a job still running after 20 minutes is stopped. After a success the session reloads (`/reload`: extensions, skills, prompts and themes) once the agent is idle, so what was installed is there without restarting it; the reload replaces this session's extensions like any `/reload`, so a client asks [`capabilities`](#capabilities) again after it. Other sessions on the same machine load the change when they start or reload. Errors: `invalid_request`, `packages_unavailable`, `package_job_running`. + ## Responses Success: @@ -1624,13 +1905,14 @@ Failure: } ``` -Current error codes are `invalid_request`, `unknown_store`, `read_only`, `invalid_data`, `revision_conflict`, `write_failed`, `unsupported_method`, `permission_unavailable`, `permission_denied`, `config_unavailable`, `usage_unavailable`, `design_unavailable`, `jobs_unavailable`, `agents_unavailable`, `changes_unavailable`, `profiles_unavailable`, `unknown_profile`, `profile_apply_busy`, `sessions_unavailable`, `session_switching`, `review_unavailable`, `review_mode_busy`, `stats_unavailable`, `session_unavailable`, `updates_unavailable`, `agent_definitions_unavailable`, `status_unavailable`, `background_subagents_unavailable`, `background_subagents_busy`, `auth_unavailable`, `reload_failed`, `not_found`, and `internal_error`. A request that cannot supply a valid correlation ID uses `requestId: null`. State/provider failures use the generic `internal_error` message rather than exposing raw paths, credentials, or provider errors. Transport failures from `setWidget` are never retried as a second response. +Current error codes are `invalid_request`, `unknown_store`, `read_only`, `invalid_data`, `revision_conflict`, `write_failed`, `unsupported_method`, `permission_unavailable`, `permission_denied`, `config_unavailable`, `usage_unavailable`, `design_unavailable`, `jobs_unavailable`, `agents_unavailable`, `changes_unavailable`, `profiles_unavailable`, `unknown_profile`, `profile_apply_busy`, `sessions_unavailable`, `session_switching`, `review_unavailable`, `review_mode_busy`, `stats_unavailable`, `session_unavailable`, `updates_unavailable`, `agent_definitions_unavailable`, `status_unavailable`, `background_subagents_unavailable`, `background_subagents_busy`, `auth_unavailable`, `reload_failed`, `host_tools_unavailable`, `host_messages_unavailable`, `unknown_call`, `already_answered`, `too_large`, `project_untrusted`, `not_found`, and `internal_error`. A request that cannot supply a valid correlation ID uses `requestId: null`. State/provider failures use the generic `internal_error` message rather than exposing raw paths, credentials, or provider errors. Transport failures from `setWidget` are never retried as a second response. | Code | Meaning | | --- | --- | | `invalid_request` | Malformed envelope, unsupported params (including a physical path, `set_config` without `data`, or an `apply_profile` mode other than `default`/`session`), or an unknown permission mode. State unchanged. | | `unknown_store` | A store identifier this slice does not implement. Nothing was read or written. | -| `read_only` | `set_config` named `models`, `subagents`, `managed_assets`, `mcp`, `pi_settings`, or `claude_bridge`. Rejected before the payload was inspected; nothing was written. | +| `read_only` | `set_config` named `models`, `subagents`, `managed_assets`, or `claude_bridge`. Rejected before the payload was inspected; nothing was written. | +| `project_untrusted` | `set_config` named the `project` layer of `mcp` while the session does not trust the project: Pi does not read that file, so it is not written. Nothing was written. | | `invalid_data` | `set_config` data the owner would reject or would silently drop. Nothing was written, and no file was created. | | `revision_conflict` | `expectedRevision` was missing, unusable, or no longer current. Nothing was written. | | `write_failed` | The owner's atomic write threw. State is whatever the owner left; the message stays generic. | @@ -1660,6 +1942,11 @@ Current error codes are `invalid_request`, `unknown_store`, `read_only`, `invali | `auth_unavailable` | `get_auth_status` or `reload_credentials`: no credential registry in this session, the registry read failed, or the session was replaced during the reload. | | `reload_failed` | The `reload_credentials` refresh itself failed. The error text never crosses. | | `not_found` | `cancel_job` or `get_job_output` named a job id, or `cancel_subagent` or `get_subagent_thread` named a subagent id, that does not exist, belongs to another session, or was already evicted by the store; or `switch_session` named an id that does not resolve in the requested scope; or `get_change_diff` named a root and path that are not a file in the owner's current change set. Nothing was stopped, read, or switched. | +| `host_tools_unavailable` | `set_host_tools` could not register with Pi (no tool registration API in the running Pi, or the registration threw). | +| `unknown_call` | `host_tool_result` or `host_tool_progress` named a call id this session never emitted. | +| `already_answered` | `host_tool_result` or `host_tool_progress` named a call that is already settled: answered, cancelled because the turn was aborted, or timed out. | +| `too_large` | `host_tool_result` content over 8 MiB; a `details` over 1 MiB; `host_message` / `set_host_context` content over 64 KiB; a 17th host context provider. | +| `host_messages_unavailable` | `host_message` / `set_host_context` could not reach Pi (no `sendMessage` / event API in the running Pi, or the call threw). | | `internal_error` | Unexpected failure; message stays generic. | ## Events @@ -1671,6 +1958,7 @@ Domain events use the same widget channel: "schema": "gentle-shell.desktop-rpc/v1", "kind": "event", "seq": 1, + "epoch": "3b0e9a52-8c1d-4f7e-9a6b-2d5c7e1f4a90", "event": "example_event", "data": {} } @@ -1678,6 +1966,8 @@ Domain events use the same widget channel: The event name above is illustrative; `capabilities` is authoritative for implemented events. `seq` starts at 1 after successful delivery in each newly started session and resets on session shutdown, reload, or a session switch (Pi's own `switch_session` or this channel's). After shutdown the channel does not answer further commands. Clients should fetch `get_snapshot` after connecting and whenever they detect a sequence gap. Responses do not increment the event sequence. +`epoch` tells a client when the numbering restarted. It is an opaque string, compared only for equality, minted each time the channel starts (session start, reload, switch, a restarted process) — exactly when `seq` restarts — and carried by every event and every `get_snapshot` answer of that channel, `session_snapshot` events included. Within one epoch `seq` only advances, so a `seq` at or below the last one seen is a replay; an event or snapshot of another epoch is a new numbering that starts at 1, never a replay. A first event of a new epoch with `seq` above 1 means the events before it were missed: resync from `get_snapshot`. Releases before the epoch send no `epoch`; a client then has only `seq` to go by. + ### `permission_mode_changed` Emitted in two ways: @@ -1781,7 +2071,7 @@ An external change: `store`, `scope`, `revision`, and `status` match what `get_config` and `get_snapshot` would answer for that store at that moment. There is no `value`, no `writeTarget` or `writeRevision` (an external writer may have touched any layer), and no path; read the store with `get_config` for its content and write targets. -Detection watches the owner files' directories, non-recursively, for an interactive RPC host only: the config home (`profiles.json`, `profile-fallbacks.json`, `models.json`, `persona.json`, `banner.json`, `notifications.json`), the project `.pi/gentle-ai/` directory (`persona.json`), the agent home and its `gentle-ai/` directory (global `subagents.json`, `mcp.json`, `settings.json`, `claude-bridge.json`, the managed-assets manifest), the session cwd's `.pi/` and `.pi/gentle-ai/` (project `subagents.json`, `mcp.json`, `settings.json`, and `models.json`, the `repo` pin), and the Git common dir's `gentle-ai/` (the `local` pin) when the cwd is a resolvable worktree. Only events for those owner file names count. About 250 ms after the last relevant event, every store's revision is recomputed with the same readers `get_config` uses, and an event is emitted only for a store whose revision differs from the last revision this channel reported (a `get_config` answer, a `get_snapshot` projection, a `set_config` answer, or an earlier event). Consequences: +Detection watches the owner files' directories, non-recursively, for an interactive RPC host only: the config home (`profiles.json`, `profile-fallbacks.json`, `models.json`, `persona.json`, `banner.json`, `notifications.json`), the project `.pi/gentle-ai/` directory (`persona.json`), the agent home and its `gentle-ai/` directory (global `subagents.json`, `mcp.json`, `settings.json`, `claude-bridge.json`, Pi's `models.json` for `custom_models`, the managed-assets manifest), the session cwd's `.pi/` and `.pi/gentle-ai/` (project `subagents.json`, `mcp.json`, `settings.json`, and `models.json`, the `repo` pin), and the Git common dir's `gentle-ai/` (the `local` pin) when the cwd is a resolvable worktree. Only events for those owner file names count. About 250 ms after the last relevant event, every store's revision is recomputed with the same readers `get_config` uses, and an event is emitted only for a store whose revision differs from the last revision this channel reported (a `get_config` answer, a `get_snapshot` projection, a `set_config` answer, or an earlier event). A `custom_models` change seen this way also refreshes the session's model registry, so a model another session added is usable here too. Consequences: - a Desktop `set_config` is never echoed: its response records the resulting revision before the owner's own rename wakes the watcher; - reformatting a file, rewriting identical content, or undoing a change inside the window emits nothing, because the revision did not move; @@ -1958,15 +2248,76 @@ Follows a confirmed `set_review_mode` whose re-read state differs from the state `mode` is identical to the response's `mode`. `confirmation_required`, a no-op (`changed: false`), an unreadable re-read, and every error emit nothing. A change made in the TUI, in Herdr, or by another process emits nothing on this channel; re-read with `get_review_mode`. +### `host_tool_call` + +The agent called a host tool. The client that registered `provider` runs `tool` with `args` (already validated against the tool's `parameters`) and answers with `host_tool_result` carrying the same `callId`. Other clients ignore it, including another provider of the same tool name: each call goes to exactly one provider (see [`set_host_tools`](#set_host_tools)). + +```json +{ "event": "host_tool_call", "data": { "callId": "htc_3f2a…", "provider": "gentle-desktop", "tool": "desktop_screenshot", "args": { "window": "editor" } } } +``` + +The call waits for the answer. When the user aborts the turn, it ends at once as a cancelled call; when no answer comes within 10 minutes, it ends with an error the model reads (` got no answer from within 10 minutes.`). Either way `host_tool_cancel` follows. A client working on a long call keeps it alive with [`host_tool_progress`](#host_tool_progress) every 60 s: each one restarts the 10 minutes. + +### `host_tool_cancel` + +The call is over without the client's answer (the turn was aborted, or 10 minutes passed without a result or a `host_tool_progress`): the client stops running it and stops its heartbeats. A `host_tool_result` or `host_tool_progress` sent afterwards is answered `already_answered`. + +```json +{ "event": "host_tool_cancel", "data": { "callId": "htc_3f2a…" } } +``` + +### `login_prompt` + +Something a running sign-in ([`login_start`](#login_start)) shows or asks, in order: + +```json +{ "event": "login_prompt", "data": { "loginId": "login_…", "kind": "open_url", "url": "https://auth.openai.com/oauth/authorize?…", "message": "Complete login in your browser.", "redirectPrefix": "http://localhost:1455/" } } +``` + +| `kind` | Fields | The client | +| --- | --- | --- | +| `open_url` | `url` (`https:`/`http:`), `message?`, `redirectPrefix?` | Opens `url` in a browser. `redirectPrefix` is the loopback callback the provider redirects to (`http://localhost:1455/`, `http://127.0.0.1:53692/`…) when the sign-in waits for that redirect: the client watches for a navigation that starts with it and sends the full URL with `login_complete` when the paste `input` comes. | +| `device_code` | `url` (the verification page), `userCode` | Shows the code and opens (or offers) the page; nothing to answer, Pi polls the provider. | +| `input` | `message`, `placeholder?`, `secret?: true`, `options?: [{ id, label }]`, `redirectPrefix?` | Asks the user and answers with `login_complete`. `secret` masks the field (a key). `options` is a choice (Anthropic, OpenAI Codex and Radius first ask browser or device/copy-code); the answer is an option's `id`. `redirectPrefix` marks the paste prompt that races Pi's own callback: the intercepted redirect URL, or the code, is the answer. | +| `progress` | `message`, `url?` | Shows a status line (`url`: a link to show with it). | + +Text fields are one line each, control characters replaced, at most 1024 characters (`placeholder` and option labels 256, `userCode` 64, URLs 4096); an event Pi raises without anything to show is not sent. + +### `login_finished` + +```json +{ "event": "login_finished", "data": { "loginId": "login_…", "provider": "anthropic", "ok": true } } +``` + +The sign-in is over. `ok: true`: the credential is stored and the registry was refreshed (as `reload_credentials`); a client reads [`get_auth_status`](#get_auth_status) again. `ok: false` carries `error`, Pi's message on one line, at most 300 characters: `Sign-in cancelled`, `Sign-in timed out` (15 minutes), or the provider flow's own failure (a state mismatch, a refused code). Never a credential. + +### `package_progress` + +```json +{ "event": "package_progress", "data": { "jobId": "pkg_…", "line": "Installing npm:pi-skills..." } } +``` + +One line of the CLI's output (stdout and stderr, in order per stream), color codes and control characters removed, blank lines skipped, at most 2000 characters. At most 2000 lines per job; after that one `… N more lines` line closes the progress. + +### `package_finished` + +```json +{ "event": "package_finished", "data": { "jobId": "pkg_…", "ok": false, "error": "No matching package found for npm:pi-skills" } } +``` + +The job is over: `ok` is the CLI's exit status 0. On failure `error` is the CLI's last line on stderr (at most 300 characters), or `Stopped: it ran past the time limit`. After `ok: true` the session reloads once idle (see [`install_package`](#install_package)). + ## Configuration limits -- **One reader and one writer per store.** Each `get_config` answer and each `set_config` write comes from the module that already owns that file (`agent-profiles.ts`, `model-routing-authority.ts`, `model-fallback-store.ts`, `agents-config.ts`, `agent-profile-pin.ts`, `agent-assets.ts`, `persona-config.ts`, `banner-config.ts`, `notification-policy.ts`, Pi's `SettingsManager` through `pi-settings.ts`, `claude-bridge-config.ts`). The one exception is `mcp-config.ts`: Pi does not export its `mcp.json` loader, so this module is a parallel reader that re-implements Pi's resolution and per-entry validation (layering, trust gate, overrides, field and OAuth checks, and the transport Pi connects with). `tests/desktop-rpc-config-mcp-fidelity.test.ts` runs Pi's real `loadMcpConfig` and transport factory on the same fixtures and fails when the two disagree, so a Pi update that changes the rules is caught by the suite. For every other store there is no second store, no cached copy, no parallel parser, no shadow precedence, and no re-implemented invariant: the merge rules are the owner's own (`readSavedModelConfig`, `parseAgentsConfig`, `evaluateProfilePin`) and the writes are the owner's validated atomic writers (`writeProfilesFileSync`, `writeFallbacksFile`, `writeProfilePinSync`). +- **One reader and one writer per store.** Each `get_config` answer and each `set_config` write comes from the module that already owns that file (`agent-profiles.ts`, `model-routing-authority.ts`, `model-fallback-store.ts`, `agents-config.ts`, `agent-profile-pin.ts`, `agent-assets.ts`, `persona-config.ts`, `banner-config.ts`, `notification-policy.ts`, Pi's `SettingsManager` through `pi-settings.ts`, `claude-bridge-config.ts`, `pi-user-config.ts` for Pi's `models.json` and `mcp.json` documents, `profiles-orchestrator.ts` for the model keys of `settings.json`). The one exception is `mcp-config.ts`: Pi does not export its `mcp.json` loader, so this module is a parallel reader that re-implements Pi's resolution and per-entry validation (layering, trust gate, overrides, field and OAuth checks, and the transport Pi connects with) for the `mcp` store's `servers` list. `tests/desktop-rpc-config-mcp-fidelity.test.ts` runs Pi's real `loadMcpConfig` and transport factory on the same fixtures and fails when the two disagree, so a Pi update that changes the rules is caught by the suite. An `mcp` write is checked by Pi's own `validateMcpServerConfig`, and a `custom_models` write by Pi's published models schema, both loaded from Pi's installed package by path because Pi does not export them. For every other store there is no second store, no cached copy, no parallel parser, no shadow precedence, and no re-implemented invariant: the merge rules are the owner's own (`readSavedModelConfig`, `parseAgentsConfig`, `evaluateProfilePin`) and the writes are the owner's validated atomic writers (`writeProfilesFileSync`, `writeFallbacksFile`, `writeProfilePinSync`, `writePiModelDefaults`, `writePiConfigDocument`). - **Settings stores.** `persona` takes `{ "mode": "gentleman" | "neutral" }` and writes like `/gentle:persona`: the global file, plus the project file only when it already exists, so a project override never silently outranks the change (its `writeRevision` covers both layers, and a project file is never created). `banner` takes exactly `{ showRose, showTextLogo, color }`. `notifications` takes the settings as read: an event may keep the `"file"` marker only where its current sound is a file, which keeps that file; a new `file:` path is `invalid_data`, because the Desktop never sees one. All three write atomically, and none waits for a profile apply (`profile_apply_busy` applies only to the profile stores). Telemetry and the Pi theme are not config stores here: telemetry is a consent switch, and Pi persists its theme through an asynchronous settings queue and exports no list of installed themes to validate against. -- **Bounded write surface.** `set_config` exists only for `profiles`, `profile_fallbacks`, `pins`, and the settings stores above, and only as a whole-store replacement, one explicitly selected pin layer, or the explicit clear of one pin layer (`profile: null`). There is no generic physical-file target, no patch operation, no setter for `models`, `subagents`, `managed_assets`, `mcp`, `pi_settings`, or `claude_bridge`, no way to clear both layers in one request, and no profile application or materialization: a profile write stores the definition, it does not apply it, and nothing else is rewritten as a side effect. -- **Read-only rationale.** `models` and `subagents` are derived: the owners write them when a profile is applied or a route is materialized, so a Desktop write would fight that writer and leave the runtime and the store disagreeing. `managed_assets` is the installer's ownership manifest with hashes it verifies on install, so a client write would silently disable ownership checks. `mcp`, `pi_settings`, and `claude_bridge` are display projections of files Pi and a third-party package own (and `mcp.json` and `settings.json` can hold credentials this channel never returns), so they stay read-only; settings changes go through `apply_profile` and Pi's own editors. Only the stores whose owners accept validated writes report `readOnly: false`, and that flag describes the store's owner capability, which now matches this slice's write surface. +- **Pi's model keys.** `pi_settings` takes a patch of the four model keys: a key the request names is set, `null` removes it from `settings.json`, and a key it leaves out keeps its value (`{}` changes nothing). Every other settings key (`packages`, theme, telemetry, …) is kept, the project file is never written, and the global file is replaced atomically. Provider and model are 1–256 characters without control characters, `defaultThinkingLevel` a Pi thinking level, `enabledModels` at most 512 distinct such strings; any other key (the read-only `extensions` and `truncated` included) or shape is `invalid_data`. A `settings.json` that is not a JSON object is never replaced: the write answers `write_failed`. The write revision digests only the model keys of the global file. Because `apply_profile` sets the orchestrator's `defaultProvider`/`defaultModel`/`defaultThinkingLevel`, a `pi_settings` write waits for an apply like the profile stores (`profile_apply_busy`). Sessions already running keep the model they have; the defaults apply to new sessions. +- **Pi's own files.** `custom_models` and `mcp` write Pi's `models.json` and `mcp.json`, so they are validated by Pi's own rules (its published models schema, its MCP server validator and loader rules) rather than a Gentle owner, replaced whole and atomically (`0600`), and never echo a secret: see [Secrets](#secrets-in-custom_models-and-mcp). A client never reads or writes these files itself; the stores are the only way it reaches them. +- **Bounded write surface.** `set_config` exists only for `profiles`, `profile_fallbacks`, `pins`, `mcp`, `pi_settings`, `custom_models`, and the settings stores above, and only as a whole-store replacement, one explicitly selected pin or MCP layer, the patch of `pi_settings`' four model keys, or the explicit clear of one pin layer (`profile: null`). There is no generic physical-file target, no setter for `models`, `subagents`, `managed_assets`, or `claude_bridge`, no way to clear both layers in one request, and no profile application or materialization: a profile write stores the definition, it does not apply it. The only side effects are Pi's own reloads of what was written: a `custom_models` write refreshes the model registry, an `mcp` write reloads the session. +- **Read-only rationale.** `models` and `subagents` are derived: the owners write them when a profile is applied or a route is materialized, so a Desktop write would fight that writer and leave the runtime and the store disagreeing. `managed_assets` is the installer's ownership manifest with hashes it verifies on install, so a client write would silently disable ownership checks. `claude_bridge` is the file of a third-party package Gentle Shell does not install. Only the stores whose owners accept validated writes report `readOnly: false`, and that flag describes the store's owner capability, which now matches this slice's write surface. - **No-op means no write.** Sending the content a store already holds, or clearing a pin layer that has no file, is answered with `changed: false`, no rewrite, no mtime churn, no removal, and no event, so a client can safely reconcile by re-sending what it read. - **Per-process guard, not a transaction.** The `expectedRevision` check and the owner's atomic rename happen in one synchronous step, so concurrent Desktop requests in one process cannot both commit from the same revision. Across processes there is no lock: another `pi` process, `/gentle:profiles`, or the installer can write between the check and the rename, and this contract cannot detect that. Treat `expectedRevision` as conflict detection, not as mutual exclusion. -- **No paths, no secrets.** Physical paths are rejected as request input and never appear in a response, an event, or an error message. Content is limited to what these stores hold: profile names, routing entries, fallback chains, pin names, layer statuses, asset ownership keys and hashes, MCP server names with their transport and enabled flag, the default model and thinking level, enabled model patterns, extension names, and the bridge plan. `managed_assets` is additionally filtered to ownership-shaped entries — a relative asset path below the agent home plus a 64-hex sha256 digest — so an absolute path, a traversal segment, or an arbitrary string in the manifest is omitted rather than echoed. `mcp.json`, `settings.json`, and `claude-bridge.json` can hold env values, headers, tokens, commands, and paths: they are read to build the projection, but only the fields listed for each store are returned, and the `mcp`, `pi_settings`, and `claude_bridge` revisions digest only the returned value, so a hidden field never reaches the wire, not even as a digest. No auth file, provider error, or conversation content is read or returned. +- **No paths, no secrets.** Physical paths are rejected as request input and never appear in a response, an event, or an error message, except the paths a user wrote into their own `mcp.json` (`command`, `args`, `cwd`), which the `mcp` documents return so an editor can show them. Content is limited to what these stores hold: profile names, routing entries, fallback chains, pin names, layer statuses, asset ownership keys and hashes, MCP server names with their transport and enabled flag plus the redacted `mcp.json` and `models.json` documents, the default model and thinking level, enabled model patterns, extension names, and the bridge plan. `managed_assets` is additionally filtered to ownership-shaped entries — a relative asset path below the agent home plus a 64-hex sha256 digest — so an absolute path, a traversal segment, or an arbitrary string in the manifest is omitted rather than echoed. `mcp.json`, `models.json`, `settings.json`, and `claude-bridge.json` can hold env values, headers, tokens, commands, and paths: every secret position reads as `"•••"` (see [Secrets](#secrets-in-custom_models-and-mcp)), and `pi_settings` and `claude_bridge` return only the fields listed for them. The `pi_settings` and `claude_bridge` revisions digest only the returned value; the `mcp`, `custom_models`, and `notifications` revisions digest the real content too, so a secret or sound path changed elsewhere still moves them (a digest, never the value). No auth file, provider error, or conversation content is read or returned. - **Truthful normalization.** Content is what the owner's normalizer produced. Entries an owner drops (an unsafe agent key, an unknown thinking level, a stale `active` marker) are absent from `value`; if everything was dropped, the store reads `ok` with an empty map rather than being reported as `invalid`. A file the owner cannot parse at all reads `invalid`. A **write** may not rely on that leniency: data the normalizer would drop is rejected as `invalid_data`, so a Desktop write can never delete content it does not understand. - **Best-effort external events.** A change made by another `pi` process, by `/gentle:profiles`, by an editor, or by the installer produces a debounced `config_changed` with `source: "external"` when the owner directory can be watched and the store's revision really moved (see [`config_changed`](#config_changed)). When a watcher cannot be created, nothing is pushed for that directory and the change becomes visible on the next read. There is no polling and no cached copy: the watcher only decides when to recompute revisions with the owner readers. - **This slice does not implement** permission changes beyond the existing slice, subscription usage beyond the read/refresh contract below, subagents beyond the list/cancel/thread-read contract below, music, profile application, store materialization, or any Gentle Desktop client change. @@ -2054,7 +2405,7 @@ Follows a confirmed `set_review_mode` whose re-read state differs from the state - **Ids in, ids out.** The wire carries session ids, never a session file path, working directory, or parent-session path. The path Pi resolves stays inside the process and goes straight to the command context's `switchSession`. - **Bounded projection.** Each entry carries exactly `id`, `name?`, `modified`, `messageCount?`, `firstMessage` (at most 200 characters), `project` (a display name), and `current`. The full conversation text Pi reads for search is never returned. A page holds at most 50 entries. - **The listing reads files.** Pi reads every session file in scope to build its list, so `scope: "all"` over a large history costs as much as Pi's own `/resume` across all projects. Prefer `project` and page with `limit`. -- **A switch replaces the session.** Every per-session bridge and the router restart with the new session; event `seq` restarts at 1, and Desktop should re-read `get_snapshot` and any state it shows. A switch during a streaming turn aborts that turn first (Pi's behavior). A failure after Pi already tore the old session down cannot be answered by either session. +- **A switch replaces the session.** Every per-session bridge and the router restart with the new session; event `seq` restarts at 1 under a new `epoch`, and Desktop should re-read `get_snapshot` and any state it shows. A switch during a streaming turn aborts that turn first (Pi's behavior). A failure after Pi already tore the old session down cannot be answered by either session. - **Exactly once across a switch.** Pi dispatches prompts concurrently, so requests sent right after a `switch_session` can reach the session being replaced. The router refuses them with `session_switching` while the switch is in flight, answers any request still waiting on an owner right before the teardown, and the replaced instance answers late deliveries through the UI object it extracted before Pi invalidated its context. The switch's own response comes from the new session. - **No agent tool.** Sessions are reachable only through `/gentle:desktop` over the interactive RPC channel. @@ -2123,10 +2474,28 @@ Follows a confirmed `set_review_mode` whose re-read state differs from the state ## Credential limits -- **Status, never values.** Only `getAll`, `getProviderAuthStatus`, `isUsingOAuth`, `getProviderDisplayName`, and `refresh` are called. The slice never reads `auth.json` and never calls a registry method that returns a key or a token. -- **No sign-in or sign-out.** Signing in stays with Pi's login flow; removing credentials is out of scope. -- **Offline reload.** `reload_credentials` never allows the network, so it does not fetch model catalogs. -- **No event.** Ask again, or call `reload_credentials`, after a change elsewhere. +- **Status, never values.** `get_auth_status` and `reload_credentials` call only `getAll`, `getProviderAuthStatus`, `isUsingOAuth`, `getProviderDisplayName`, `getProvider` (for `loginKinds`: which sign-in methods a provider defines), and `refresh`; `list_available_models` calls only `getAvailable`. They never read `auth.json` and never call a registry method that returns a key or a token. +- **Sign-in is Pi's.** `login_start`, `set_api_key` and `remove_credentials` drive Pi's own `ModelRuntime.login` / `logout`, the code `/login` and `/logout` run: the provider's flow, Pi's credential store (`auth.json`, `0600` in a `0700` agent home) and Pi's synchronization. This slice keeps no credential, never reads one back, never logs one, and never puts one in an answer or an event; an API key goes one way. +- **Bounded sign-ins.** One per provider at a time, 15 minutes each, cancelled with the session. A client answers only the question the flow is waiting on. +- **Offline reload.** `reload_credentials` (and the reload after a sign-in, a saved key or a removal) never allows the network, so it does not fetch model catalogs. +- **No status event.** Ask again, or call `reload_credentials`, after a change elsewhere; a sign-in from this channel ends with `login_finished`. + +## Packages limits + +- **The CLI's own rules.** Installs and removals run `gentle-shell install|remove [-l]` with this session's launcher and home (`GENTLE_SHELL_LAUNCH`, set by the launcher for every Pi it starts; a Pi started without it uses this package's launcher with `--home `). A source that starts with `-` is refused before it could become an option; everything else (source syntax, project trust, npm, git) is the CLI's. +- **One job per session, 20 minutes.** Its output is bounded (2000 lines of 2000 characters); stdin is closed, so nothing can wait for a prompt. +- **Reload after success.** The session reloads once idle, as a user would after installing; a failed job reloads nothing. A session change stops a running job, with no `package_finished`. +- **Same authority as the terminal.** Installing a package runs its install scripts as the server user, exactly as `gentle-shell install` typed in the session's terminal would; through `gentle-shell serve` it needs `sessions:operate`. + +## Host tools limits + +- **The client's code, the client's authority.** A host tool runs on the device that registered it, with that device's permissions (its screen, its files, its accounts), never on the machine where the agent runs. This process only relays: it emits the call and hands the model whatever content comes back. No client code, script, or command ever reaches the agent's machine, and a host tool cannot reach anything there that the agent could not already reach. +- **The model's arguments are untrusted input to the client.** They come from the model, shaped by the tool's schema; a client validates them and asks its user before anything sensitive, just as it would for any input from the agent. +- **Results are untrusted input to the model.** Text and images a client returns go into the conversation like any tool output. +- **No impersonation in serve.** Through `gentle-shell serve`, `provider` is always the calling device's id, and only that device may answer its calls; see [`docs/serve.md`](serve.md#host-tools). +- **Bounded.** 32 tools per provider, 16 KiB of schema and 16 guidelines per tool, 8 MiB of content per result, 10 minutes per call without a result or a `host_tool_progress` heartbeat. A name never shadows a built-in or extension tool. +- **Not persisted.** Nothing is written to disk; registrations last for the session. +- **Over stdio there is no "not connected".** The client that owns the Pi process is the only provider; if it stops answering and stops sending `host_tool_progress`, the 10-minute limit or an abort ends the call. ## Verification @@ -2152,11 +2521,14 @@ node --experimental-strip-types --test \ tests/desktop-rpc-status.test.ts \ tests/desktop-rpc-background-subagents.test.ts \ tests/desktop-rpc-auth.test.ts \ + tests/desktop-rpc-host-tools.test.ts \ tests/maintainer/desktop-rpc.maintest.ts ``` The permission tests register the real `registerYoloSessionPolicy` owner with an isolated temporary config home and a stub identity resolver; they never read or write the user's own permission store. +The host tools tests run the real extension over a fake Pi tool registry with fake timers and a fake clock: they cover every `set_host_tools`, `host_tool_result`, `host_tool_progress`, `host_message`, `set_host_context` and `set_host_activity` limit, registration as a `direct` Pi tool with its schema, snippet, and guidelines (and the tool name prefixed where a guideline lacks it), collisions with built-in and extension tools, two providers of one name (the newest definition wins, unregistering falls back to the other, the last one leaving hides it), calls routed to the most recently active connected provider, the next one when it is offline, the newest registration without an activity list, set replacement and unregistering as `hidden` (whose names are free again), the first answer settling a call with later answers `already_answered` and strangers `unknown_call`, error results, a result's `details` passed through, an abort cancelling the call with `host_tool_cancel`, the 10-minute limit, `host_tool_progress` restarting it (with its `deadlineMs`) as often as it comes while the call still fails 10 minutes after the last one, shutdown failing waiting calls and hiding every tool, every `host_message` delivery mode reaching `pi.sendMessage` (idle and streaming `auto`), host contexts injected per provider before a run, replaced, cleared and dropped on a session change, and the larger request caps for these methods only. Four more tests run a real Pi SDK session with an offline scripted provider (no model): a registered tool is declared in the next request with its guideline in the system prompt, the scripted tool call round-trips through `host_tool_call` and `host_tool_result` into the tool result the provider receives, unregistering removes the tool and its guideline from the next request, aborting the turn emits `host_tool_cancel`, an idle `host_message` starts a run and is persisted as a `custom_message` entry, a host context rides along hidden and stops after clearing, a `host_message` during a call steers the running turn, and a result's `details` lands in the Pi tool result. + The design tests use only injected fake canvas/server/browser factories and a fake owner service: they cover stopped/running/open/refresh/stop state, slug and connected-client counts, default URL omission, explicit `includeUrl` inclusion only after trust, untrusted omission, malformed adapters and params, owner absence (`design_unavailable`, never a fabricated `running: false`), failed and no-op actions emitting nothing, external (agent-driven) transition events, late-reset disposal and stale-outcome drops, and raw-error/token redaction. One test runs the real `gentleDesign` owner seam in-process to prove the stopped canvas state and the design list arrive from the single owner adapter. The usage tests use a fake owner service and a fake fetch/modelRegistry only: they cover the five statuses, the safe projection and plan-only-when-public rule, provider filters, unknown-provider `unavailable`, invalid params, refresh delegation with the provider filter forwarded, the response-before-event order over the router, the Anthropic typed `unsupported` no-op, the out-of-scope `out_of_scope` no-op (including the real owner never reaching the fetcher), content-based change detection (a same-millisecond payload change emits once, byte-equivalent data stays a no-op), late-discovery disposal after a reset, no duplicate event on no-op/failed refresh, raw-error and secret redaction, header-driven `rate_limit` events, stale-session disconnects, and the versioned adapter discovery. One test runs the real `gentleShell` owner seam to prove Claude's 5h/7d windows arrive as structured snapshots from response headers, never header text. diff --git a/docs/orchestration-plan.md b/docs/orchestration-plan.md new file mode 100644 index 000000000..585b2688f --- /dev/null +++ b/docs/orchestration-plan.md @@ -0,0 +1,123 @@ +# Plan: multi-repo orchestration (Phase 5) + +> **Status: plan, not implemented.** This document is the brief for whoever implements Phase 5 of [RFC #3527](https://github.com/Gentleman-Programming/gentle-shell/issues/3527) once phases 1–4 (`gentle-shell serve`, see [serve.md](serve.md) and [remote.md](remote.md)) are merged. It is written so a coding agent can take it as is: goal, contract, order of work, tests and acceptance criteria. + +## Goal + +One orchestrating agent opens and drives full Gentle Shell sessions ("threads") in other repositories, each with its own history and its own memory, while the user watches and steers every thread from a laptop, a phone or the web. + +```mermaid +flowchart LR + You["You
Mac · phone · web"] + subgraph Main["Main machine · orchestrator"] + O["Main Gentle Shell session
orchestrating agent"] + D["Dispatcher subagent
background"] + O -- delegates --> D + end + S["gentle-shell serve
+ orchestration MCP server"] + subgraph Threads["One thread per repository"] + A["Thread · project A
session · memory A"] + B["Thread · project B
session · memory B"] + end + You -- "asks for the task" --> O + You -- "sees and controls every thread" --> S + D -- "MCP tool calls" --> S + S -. "results · JSON" .-> D + S --> A & B +``` + +## What already exists (build on it, don't duplicate) + +- Sessions owned by `serve`, surviving clients and server restarts (session keepers), with `seq`/`epoch` resume, dialog replay and host tools ([serve.md](serve.md) "Process model", "Event stream"). +- Devices with scopes checked per request, pairing, revocation, `lastActiveDevice` ([serve.md](serve.md) "Authentication"). +- Desktop RPC over `serve` with or without a session (`/api/sessions/:id/desktop`, `/api/desktop`). +- Engram as each machine's memory service. + +## Contract to implement + +### 1. Threads = sessions with metadata + +- Every session record gains: `title` (≤ 120 chars, default: folder name), `project` (absolute cwd), `createdAt`, `lastActiveAt`, `archived` (bool), `createdBy` (device id), `parent` (thread id or `null`), `origin` (`"device"` | `"orchestrator"`). Persist it with the session keeper's record so it survives restarts. +- `POST /api/sessions` accepts `{ cwd, title?, parent? }`. +- `PATCH /api/sessions/:id { title }` — `sessions:operate`. +- `POST /api/sessions/:id/archive` — `sessions:operate`. Stops the process, keeps the Pi session file, keeps the record with `archived: true`. +- `POST /api/sessions/:id/unarchive` — `sessions:operate`. Starts a session resuming the same Pi session id (`--session-id`), same thread id. +- `GET /api/sessions?query=&project=&state=running|exited|archived&limit=&cursor=` — `sessions:read`. Search over title and project; keyset pagination (`nextCursor`). Archived threads are excluded unless `state=archived`. +- Every session's environment gets `GENTLE_SHELL_SESSION_ID=`. + +### 2. Scope `orchestrate` and a depth limit of one + +- New scope `orchestrate`, not part of the default pairing scopes. +- Creating a thread with `parent`, or any request made with an orchestration token, needs `orchestrate`; such threads get `origin: "orchestrator"`. +- A create whose `parent` is a thread with `origin: "orchestrator"` is refused with `403 depth_limit`. Delegated threads never delegate. + +### 3. Send and wait + +`POST /api/sessions/:id/send { text, wait?: "settled" | "question" | "none", timeoutMs? }` — `sessions:operate`. +Sends a Pi `prompt` (follow-up when the agent is busy) and, unless `wait` is `"none"`, waits until `agent_settled` or a pending `extension_ui_request`. Answers `{ state: "settled" | "question" | "timeout", reply?, dialog? }`: `reply` is the last assistant message's text, `dialog` the pending request (id, kind, title, options). + +### 4. Structured replies + +`POST /api/sessions/:id/ask_json { prompt, schema, timeoutMs? }` — `sessions:operate` + `orchestrate`. +Sends the prompt with an instruction to answer only a JSON object matching `schema`; waits for `agent_settled`; extracts the last assistant message's JSON (fenced or bare); validates against a JSON Schema subset (`type`, `properties`, `required`, `items`, `enum`, primitive types, nested objects/arrays); on failure retries once with the validation errors. Answers `{ ok: true, value }` or `{ ok: false, error, raw }`. + +### 5. Memory per project + +Each thread's memory project is the git repository root of its `cwd` (or `cwd` outside a repository). Find how Gentle Shell picks the Engram project today and make it explicit for threads (environment or extension setting); nothing crosses projects unless the agent asks. + +### 6. MCP server for orchestration + +`gentle-shell serve mcp [--server ] [--token-file ]`: an MCP server over stdio (initialize, `tools/list`, `tools/call`; JSON-RPC 2.0 framing per the MCP stdio transport; no new dependency) that calls `serve`'s API. + +- Server and token: by default the server in this agent home (`server.json`) and a dedicated device token with `sessions:read sessions:operate orchestrate`, minted on first use with the admin token and stored `0600` in `/serve/mcp-token`. +- Parent: threads it creates get `parent = $GENTLE_SHELL_SESSION_ID` when set, so the depth limit applies. +- Tools (input schemas in `tools/list`): + +| Tool | Does | +| --- | --- | +| `thread_create { cwd, title? }` | `POST /api/sessions` | +| `thread_send { id, text, wait? }` | `POST /:id/send` | +| `thread_wait { id, until: "settled" \| "question", timeoutMs? }` | waits on the event stream | +| `thread_read { id, after? }` | recent user/assistant messages, compact | +| `thread_answer { id, dialogId, value }` | answers a pending dialog | +| `thread_ask_json { id, prompt, schema }` | `POST /:id/ask_json` | +| `thread_list { query?, project?, state? }` | `GET /api/sessions` | +| `thread_stop { id }` | stops the thread | +| `thread_archive { id }` | archives it | + +### 7. Dispatcher subagent + +A Gentle Shell agent definition named `dispatcher` that owns the MCP tools: given a plan, it creates or reuses threads per repository, runs them in parallel, answers or escalates their questions, collects structured results and reports back, so the main session stays free. Document how to register the MCP server for an orchestrating session (`mcp.json` entry or `gentle-shell mcp add`). + +### 8. Clients + +- Clients connected to several servers at once (Gentle Shell GPUI already keeps several paired servers) show a threads view: every server's threads grouped by machine and project, with open, stop and archive. +- Answering a thread's question from any device (dialogs are already replayed to every subscriber). + +### 9. Linked environments (last) + +A server pairs another server as a device with narrow scopes (for example a sandbox that may only create threads under one folder, no terminals); the orchestrator reaches it with the same MCP tools (`--server`). + +## Rules + +- A thread is a full session: its own repository, history, tools, permissions and memory. Work never silently crosses threads or servers. +- The orchestrator's authority over a thread is what its device scopes allow. Consent prompts inside a thread stay the thread's: the orchestrator answers only what the user allowed; everything else goes to the user's devices. +- Delegated threads cannot delegate (depth 1), enforced by scope, not by convention. +- Threads outlive the orchestrator's turn: results stay listed until archived. + +## Order of work (one PR each) + +1. Thread metadata, archive/unarchive, search, `GENTLE_SHELL_SESSION_ID`. +2. `orchestrate` scope and depth limit. +3. `send` and `ask_json`. +4. Memory per project. +5. `gentle-shell serve mcp`. +6. `dispatcher` definition and `docs/orchestration.md` (user guide). +7. Clients: threads view across servers (Gentle Shell GPUI). +8. Linked environments. + +## Tests and acceptance + +- `tests/serve-*.test.ts` with the fake Pi child (extend `tests/fixtures/serve-fake-pi.mjs` to emit assistant messages, `agent_settled` and dialogs): metadata persists across a serve restart; archive frees the process and unarchive resumes the same Pi session; search and pagination; depth limit returns `403 depth_limit`; `send` returns the reply or the dialog; `ask_json` validates, retries once and fails cleanly; MCP handshake and every tool against a real `serve` in a temp home; token minting and file mode. +- No model turns in tests; temp homes only. +- Acceptance: from an orchestrating session with the MCP server registered, a prompt like "in repos A and B, list the failing tests as JSON" creates two threads, runs them in parallel, returns validated JSON per repo, and both threads appear in a client's threads view; a thread's attempt to create another thread is refused. diff --git a/docs/readme-reference.md b/docs/readme-reference.md index a01039cbc..47bf36afe 100644 --- a/docs/readme-reference.md +++ b/docs/readme-reference.md @@ -344,6 +344,7 @@ gentle-shell upgrade --rollback gentle-shell update [pi|self|--self|--all] [--latest] gentle-shell self-uninstall [--dry-run] [--yes] [--include-shared] gentle-shell desktop [--yes] [--no-open] | --status | --uninstall +gentle-shell [home selectors] serve [--listen :] [--allow-host ]... [--foreground] | share | status | stop | pair | devices ``` ### Flags @@ -659,6 +660,32 @@ it installed and puts back what was there before. Like `upgrade`, it runs before any Pi runtime check, and `gentle-shell upgrade` refreshes it when it was installed. Guide: [Gentle Shell Desktop](gentle-shell-desktop.md). +### `serve` subcommand + +To connect Gentle Shell GPUI from another computer on the same network, run +`gentle-shell serve share` on the machine where agents should run and type the +short code it prints (`ABCD-EFGH`) in the app (Configuration → Where agents run → +Gentle Shell server; valid 5 minutes, once): the app finds the server on the +network by itself. Where discovery does not reach, paste the long `gsc1.…` +connection code printed under it instead. It opens the server to the network +over plain HTTP (port 8787, or the next free one), reusing a running server +when it can; `--always` also starts it at login (systemd user unit or macOS +LaunchAgent) and `serve share --off` removes that. + +`gentle-shell serve` runs one server per agent home that owns Gentle Shell +sessions (one `gentle-shell --mode rpc` child each, with Desktop RPC on), so +they outlive the client that started them and paired devices can drive them +over HTTP + Server-Sent Events. It binds `127.0.0.1` on a random port unless +`--listen` says otherwise (`--allow-host ` admits one more `Host` name, +such as a tailnet MagicDNS name), and every request needs a device token: `serve pair` +prints a one-time code (5 minutes, single use) that a device redeems for a +revocable token with scopes (`sessions:read`, `sessions:operate`, `terminal`, `admin`). +`serve status`, `serve stop` and `serve devices [--revoke ]` manage it; +its files live in `/serve/` (owner-only). Home selectors go before +`serve`, as for `setup`. What runs where, diagrams and the security model: +[Remote use](remote.md). Protocol and endpoints: +[`gentle-shell serve`](serve.md). + ### First run in an isolated or custom home The first time `gentle-shell` resolves to an isolated or `--home ` home that does not already exist, it creates the directory, writes `"tuiMode": "fullscreen"` and, unless the home's `settings.json` already declares one, `"theme": "Gentleman-Cute"` into its `settings.json`, writes a small ownership marker file at `/.gentle-shell-home` (a one-line JSON object naming the `gentle-pi` version that created it), and prints one hint to stderr pointing at `--link` (and at `gentle-shell home import-pi` when your pi home has an `auth.json`). A `--link` home is never bootstrapped this way — it is assumed to already exist as your pi agent home. Later runs against the same home skip the write and the hint. The default theme is also re-applied after automatic or manual setup if gentle-ai's own managed install wrote a different theme into a home that had none before that run; a home (or `--link`) that already declares its own theme is never touched. diff --git a/docs/remote-test-runbook.md b/docs/remote-test-runbook.md new file mode 100644 index 000000000..e49e69b55 --- /dev/null +++ b/docs/remote-test-runbook.md @@ -0,0 +1,236 @@ +# Runbook: Gentle Shell server on Omarchy for a remote test + +You are a coding agent with a shell on the user's Omarchy PC (Arch Linux, x86_64, Hyprland). Your job: run the **server side** of Gentle Shell's remote use from the pull-request branches, so the user can connect from his Mac with Gentle Shell GPUI, and check the server while he tests. Follow the steps in order. Reference: `~/src/gentle-shell/docs/serve.md` (section "Try it from source on Linux") once the checkout exists. + +Branches under test: + +- Gentle Shell (server): `feat/serve-phase1` of https://github.com/ismaelosuna7824/gentle-shell (PR Gentleman-Programming/gentle-shell#3529) +- Gentle Shell GPUI (terminal host here, app on the Mac): `feat/remote-serve-backend` of https://github.com/Gentleman-Programming/gentle-shell-gpui (PR #255) + +## 1. Safety rules + +1. **Do not modify the installed Gentle Shell.** Never run `gentle-shell setup`, `gentle-shell upgrade`, `self-uninstall`, `npm install -g gentle-shell` or anything that rewrites `~/.gentle-shell/bin`, `~/.gentle-shell/config.json` or the installed packages. All commands here use the checkout through the `gsdev` function (step 3). The installed `gentle-shell serve` would only send "serve" as a prompt to a model: never run it. +2. **Agent home: reuse the real one** (the user wants his real providers and sign-ins). Use exactly the home selector he uses day to day (none, or `--link`, or `--home `); ask him if unsure. `gsdev` sets `GENTLE_SHELL_NO_AUTO_SETUP=1`, so the checkout never re-runs setup in that home. +3. **What the server writes:** only `/serve/` (`server.json`, `server-id`, `server.lock`, `devices.json`, `server.log`, `tls/`, `sessions/`, `uploads/`, `term/`, `term.sock`, `terminals.json`, `bin/`, `relay-secret`). Sessions the user starts from the Mac are ordinary Gentle Shell launches in that home: they write its sessions like any launch, and the Mac's Configuration screen (model defaults, `models.json`, MCP servers, packages, setup, sign-in) changes that home **on purpose** — that is what he is testing. You do not edit anything outside `/serve/` yourself, except `~/src/` (checkouts) and, only with `--always`, `~/.config/systemd/user/gentle-shell-serve.service`. +4. **No `sudo` without telling the user first** and getting his OK (firewall rules, pacman, `loginctl enable-linger`). Show the exact command. +5. **Never print secrets:** not the `adminToken` from `server.json`, not device tokens (`gss_…`), not `auth.json`, not `relay-secret`, not the TLS key in `/serve/tls/`. Read the admin token into a shell variable only (step 8), never `cat server.json`. Use `jq 'del(.adminToken)'` to show it. +6. **No model turns:** never send a `prompt` RPC or `POST /api/print` yourself; the user drives agents from the Mac. +7. Do not touch the user's open apps, windows or other projects. + +## 2. Prerequisites check + +```sh +uname -m # x86_64 +node --version # v22.19+ or v23.6+ (v25+: see below) +corepack --version # any version; "command not found" on Node 25+: sudo npm install -g corepack (ask first) +git --version +jq --version # used below; else: sudo pacman -S --needed jq (ask first) +command -v gentle-shell && gentle-shell --version # the installed one; note its "home" line +sudo ufw status # ask first; "Status: active" on Omarchy +ss -ltnup | grep -E ':(87(8[7-9]|9[0-6])|88[0-9][0-9])\b' || echo "ports free" +``` + +Expected: Node satisfying `^22.19.0 || >=23.6.0`; ports 8787-8796 and 8800-8899 free (if one is taken, `share` uses the next free one; note which). Missing Node: `sudo pacman -S --needed nodejs npm` (ask first). + +## 3. Install the checkout + +```sh +mkdir -p ~/src +git clone -b feat/serve-phase1 https://github.com/ismaelosuna7824/gentle-shell.git ~/src/gentle-shell +cd ~/src/gentle-shell && corepack pnpm install +gsdev() { GENTLE_SHELL_NO_AUTO_SETUP=1 node ~/src/gentle-shell/bin/gentle-shell.mjs "$@"; } +gsdev --version +``` + +`gsdev` lives only in your shell; redefine it in every new shell. If the user uses a home selector, put it right after `gsdev` in **every** command (e.g. `gsdev --link serve share`). Check that the `home` line of `gsdev --version` equals that of `gentle-shell --version` (the installed one). Set it for later steps: + +```sh +AGENT_HOME=~/.gentle-shell/agent # replace with the home line printed by 'gsdev --version' +``` + +If the user wants to open Gentle Tower from the Mac (optional): + +```sh +cd ~/src/gentle-shell && corepack pnpm run build:tower +``` + +Already cloned? `cd ~/src/gentle-shell && git fetch && git switch feat/serve-phase1 && git pull --ff-only && corepack pnpm install`. + +## 4. Build the terminal host + +Terminals from the Mac need `gentle-term-host` here. + +```sh +command -v cargo || { echo "need rustup"; } # if missing: sudo pacman -S --needed rustup base-devel (ask), then: rustup default stable +git clone -b feat/remote-serve-backend https://github.com/Gentleman-Programming/gentle-shell-gpui ~/src/gentle-shell-gpui +cd ~/src/gentle-shell-gpui && cargo build --release -p gentle-term-host +install -d -m 700 "$AGENT_HOME/serve" "$AGENT_HOME/serve/bin" +install -m 755 target/release/gentle-term-host "$AGENT_HOME/serve/bin/" +"$AGENT_HOME/serve/bin/gentle-term-host" --version 2>/dev/null || ls -l "$AGENT_HOME/serve/bin/gentle-term-host" +``` + +`/serve/bin/` is found by the server and by the `--always` unit (`GENTLE_TERM_HOST` also works, but the unit does not carry it). + +## 5. Start the server + +```sh +gsdev serve share +``` + +Expected output (port may differ): + +```text +Started the Gentle Shell server for your network on port 8787. + + Code: XXXX-XXXX + +In Gentle Shell GPUI → Configuration → Where agents run → Gentle Shell server, enter this code. Valid for 5 minutes, once. +If the app can't find this computer, paste this instead: +gsc1.… +It uses HTTPS; the app checks this computer's certificate, fingerprint …. +If the app cannot find or reach this computer, …: sudo ufw allow 8787 && sudo ufw allow 8800:8899/tcp +``` + +If it says it exits because of running sessions, see Troubleshooting. Optional, only if the user asks for it to survive logout/reboot: `gsdev serve share --always` (systemd user unit `gentle-shell-serve.service`, `KillMode=process`; boot without login needs `sudo loginctl enable-linger $USER`, ask first). Each `serve share` run prints a fresh code; run it again whenever the user needs one (codes last 5 minutes, single use). + +## 6. Firewall + +Ask the user, then: + +```sh +sudo ufw allow 8787 # TCP (HTTPS) + UDP (LAN discovery); use the port share printed +sudo ufw allow 8800:8899/tcp # forwarded pages (dev servers, design canvas, Tower) +sudo ufw status | grep -E '8787|8800' +``` + +firewalld instead of ufw: `sudo firewall-cmd --permanent --add-port=8787/tcp --add-port=8787/udp --add-port=8800-8899/tcp && sudo firewall-cmd --reload`. + +## 7. What to send the user + +- The **short code** (`XXXX-XXXX`) and the time it was minted (valid 5 minutes, once). +- The **long `gsc1.…` code**, as one line, for when the Mac cannot find this PC (different subnet, VPN, relay). +- The certificate fingerprint (from `serve status`), so he can compare if the app shows it. +- This PC's LAN IP (`ip -4 -br addr`) for reference. + +Never send: the `adminToken`, device tokens, `relay-secret`, anything from `tls/` or `auth.json`. + +## 8. Verify on the server, alone + +```sh +gsdev serve status # URL, pid, "HTTPS on the network, certificate fingerprint …", sessions +jq 'del(.adminToken)' "$AGENT_HOME/serve/server.json" # url http://127.0.0.1:, listen 0.0.0.0:, discovery true, forwardPorts 8800-8899 +PORT=$(jq -r '.listen' "$AGENT_HOME/serve/server.json" | sed 's/.*://') +LANIP=$(ip -4 -br addr | awk '$1!="lo"{split($3,a,"/"); print a[1]; exit}') +curl -sk "https://$LANIP:$PORT/.well-known/gentle-shell" | jq . # identity only (-k is fine here, nothing secret) +# (plain http to the LAN IP from this same PC is answered: a local peer; only other machines get 400 tls_required) +gsdev serve devices # paired devices (after the user pairs: his Mac appears) +URL=$(jq -r .url "$AGENT_HOME/serve/server.json") +ADMIN=$(jq -r .adminToken "$AGENT_HOME/serve/server.json") # never echo it +curl -s "$URL/api/sessions" -H "Authorization: Bearer $ADMIN" | jq '.sessions[] | {id, state, cwd}' +curl -s "$URL/api/terminals" -H "Authorization: Bearer $ADMIN" | jq '.terminals[] | {id}' +curl -s "$URL/api/term-host" -H "Authorization: Bearer $ADMIN" | jq '{available, running, path, version}' +tail -n 50 "$AGENT_HOME/serve/server.log" # with --always instead: journalctl --user -u gentle-shell-serve -n 100 --no-pager +systemctl --user status gentle-shell-serve --no-pager # only with --always +``` + +Expected: `available: true` for the term host (`running` becomes true once the Mac opens a terminal). + +## 9. During the user's test on the Mac + +Before a restart test, record ids: + +```sh +curl -s "$URL/api/sessions" -H "Authorization: Bearer $ADMIN" | jq -r '.sessions[] | "\(.id) \(.state)"' > /tmp/gs-before.txt +curl -s "$URL/api/terminals" -H "Authorization: Bearer $ADMIN" | jq -r '.terminals[].id' >> /tmp/gs-before.txt +``` + +Restart the server (sessions and terminals must survive): + +```sh +gsdev serve stop && gsdev serve share # background server; prints a new code (not needed: the Mac stays paired) +# with --always instead: +systemctl --user restart gentle-shell-serve +``` + +After it, re-read `URL`/`ADMIN` (the admin token changes every run), list again and compare with `diff /tmp/gs-before.txt <(…)` — same session ids (state `running`), same terminal ids. Tell the user when the restart is done so he checks that the Mac reattached. Also watch `server.log`/journal for errors while he tries files, git, uploads, terminals and forwards. + +## 10. Relay test (only if the user asks) + +Needs a machine both can reach (e.g. a VPS) with the same checkout and `gsdev`: + +```sh +# on the relay machine: +gsdev relay --listen 0.0.0.0:7700 # prints where its secret file is (/relay/secret); open TCP 7700 there +# on this PC (the user passes the secret to you out of band; do not print it): +install -m 600 /dev/stdin "$AGENT_HOME/serve/relay-secret" <<< 'the-relay-secret' +gsdev serve share --relay gsr://:7700 +gsdev serve status # "Relay gsr://…: connected" +``` + +Send the user the **long** code (it carries the relay); the short one works on the LAN only. If `share` refuses because sessions run, ask the user before `gsdev serve stop`. + +## 11. Troubleshooting + +| Symptom | Cause / fix | +| --- | --- | +| `421 bad_host` | Host header is not this server's IP/hostname:port. Use the IP, or restart with `gsdev serve --listen 0.0.0.0:8787 --allow-host ` (or keep `share` and use the IP). | +| `400 tls_required` | Something used plain `http://` from the network. Use `https://`; the app does by itself. | +| `401 unauthorized` | Token wrong, revoked, or from another home's server. Mac: re-pair with a fresh code. Your curl: re-read `ADMIN` (it changes each server run). | +| `403 forbidden` / `403 forbidden_origin` | Missing scope / a web page origin. Re-pair; native app sends no Origin. | +| `403 invalid_code` | Expired (5 min), used, mistyped, or minted by another home. Run `gsdev serve share` again. `429 rate_limited` after 10 failures: wait a minute. | +| Mac: "can't find this computer" | Not same subnet / client isolation / VPN, or UDP blocked. Check `sudo ufw status` shows 8787 (no `/tcp`), `jq .discovery server.json` is true. Send the long code. | +| Mac: connection refused / timeout | ufw (step 6), server not running (`serve status`), or listening on loopback only (`jq .listen` → `127.0.0.1:…`: `gsdev serve stop && gsdev serve share`). | +| `ports 8787-8796 are in use` / `EADDRINUSE` | `ss -ltnup 'sport = :8787'`; stop the other program or `gsdev serve share --port ` (and open that port). | +| `share` exits 1 about running sessions | It must restart the server (loopback→network, TLS/relay change, `--always`). Ask the user; then `gsdev serve stop` (sessions keep running and are reattached) and retry. | +| `serve status` not running but `server.json` exists | Stale from a kill/reboot; next start takes it over. Only if status reports a dead server: confirm nothing listens (`ss -ltnp`) and remove `$AGENT_HOME/serve/server.json` and `server.lock`. | +| `501 term_host_missing` / `available: false` | Step 4 not done or wrong home: check `ls -l $AGENT_HOME/serve/bin/gentle-term-host`. | +| Forwarded page doesn't load on the Mac | `sudo ufw allow 8800:8899/tcp`; `jq .forwardPorts server.json` must be 8800-8899 (else `serve stop` + `serve share`). `502`: nothing listens on that local port yet. | +| Tower: "web app is not built" | `cd ~/src/gentle-shell && corepack pnpm run build:tower`. | +| `gentle-shell serve` opened a chat | Installed release used by mistake; use `gsdev`. | +| Relay `not connected (retrying)` | Wrong host/port, relay port closed, or `relay-secret` mismatch. | + +## 12. Cleanup (when the user says the test is over) + +```sh +gsdev serve stop --sessions # stops the server and its sessions +gsdev serve share --off # only if --always was used: disables and removes the unit +systemctl --user daemon-reload +pkill -u "$USER" -x gentle-term-host # terminals outlive the server; ask the user first (it closes his remote terminals) +sudo ufw delete allow 8787 && sudo ufw delete allow 8800:8899/tcp # ask first +sudo loginctl disable-linger $USER # only if you enabled it; ask first +``` + +Folders: to forget the test completely, remove `$AGENT_HOME/serve/` (paired devices, server identity, certificate, uploads, term host binary) — ask first; keeping it lets the Mac reconnect later without re-pairing. `~/src/gentle-shell` and `~/src/gentle-shell-gpui` can be deleted. Do **not** delete anything else in the agent home (sessions, `auth.json`, settings are the user's). + +--- + +## Mac side (for the user) + +Build and run the PR app as a separate copy, next to the installed app, with real Gentle Shell sign-ins but its own window/settings: + +```sh +git clone -b feat/remote-serve-backend https://github.com/Gentleman-Programming/gentle-shell-gpui ~/src/gentle-shell-gpui +cd ~/src/gentle-shell-gpui +cargo build --release -p gentle-shell-gpui +sandbox="$(mktemp -d)" +cp "$HOME/Library/Application Support/gentle-shell-gpui/settings.json" "$sandbox/" # optional: theme, skips the welcome screen +GENTLE_SHELL_GPUI_DATA_DIR="$sandbox" ./target/release/gentle-shell-gpui "$(mktemp -d)" +``` + +(`cargo run --release -p gentle-shell-gpui` works too with the same variable. A `.app` bundle: `packaging/macos/bundle.sh aarch64-apple-darwin ` builds `dist/Gentle Shell.app` — don't copy it over the installed app.) Without `GENTLE_SHELL_GPUI_DATA_DIR` the build would hand off to the running installed app. + +Enter the code in **Configuration → Where agents run → Gentle Shell server** (short code first; the long `gsc1.…` code if not found). + +Checklist: + +- [ ] Pairing with the short code; then with the long code (fresh `serve share`). +- [ ] Files: browse, open, edit, save; Changes view; Branches (switch, create). +- [ ] Upload a file to the server; download one. +- [ ] Agent session: start, follow, stop (a real prompt with a real provider is yours to send). +- [ ] Terminal: open, type, resize, close; reopen app and find it again. +- [ ] Server restart (agent on Omarchy restarts it): agent session and terminal reattach, nothing lost. +- [ ] App relaunch: sessions and terminals reattach. +- [ ] Forwarded page: a dev server / design canvas / Gentle Tower opened from the Mac. +- [ ] Configuration on the server: model defaults; custom models (`models.json`) — the save notice appears only on its own card, not under MCP servers; MCP servers; packages; setup; sign-in with a real provider. +- [ ] Re-pair (pair again: replaces the earlier pairing, one entry in `serve devices`) and unpair (device disappears from `serve devices`). +- [ ] Relay: from another network with the long code. diff --git a/docs/remote.md b/docs/remote.md new file mode 100644 index 000000000..7c80dff17 --- /dev/null +++ b/docs/remote.md @@ -0,0 +1,465 @@ +# Remote use + +Gentle Shell can run its agents on one machine — a Linux PC on your home network, a workstation under the desk — and let you drive them from another: a laptop with Gentle Shell GPUI today, a phone later. The machine that runs the agents runs `gentle-shell serve`; every other device is a paired client of it. + +This page is the overview: what runs where and why, how a device connects, what happens when things disconnect or restart, how tools that need the client's own device work, how pages and terminals on the server reach you, and the security model. The exact endpoints, fields, limits and error codes are in the references: + +- [`gentle-shell serve`](serve.md) — commands, files, every HTTP endpoint, pairing and tokens, limits, troubleshooting. +- [Desktop RPC](desktop-rpc.md) — the in-session channel, including the [host tool methods and events](desktop-rpc.md#set_host_tools). + +## Contents + +- [What runs where](#what-runs-where) +- [Connecting with the short code](#connecting-with-the-short-code) +- [Session lifecycle](#session-lifecycle) +- [Host tools across several devices](#host-tools-across-several-devices) +- [Pages on the server: port forwarding](#pages-on-the-server-port-forwarding) +- [Terminals](#terminals) +- [Sign-in, packages and upgrades from the client](#sign-in-packages-and-upgrades-from-the-client) +- [Clients without sessions](#clients-without-sessions) +- [Security model](#security-model) +- [Reference](#reference) +- [Known limits and next steps](#known-limits-and-next-steps) + +## What runs where + +The rule is simple: **the work happens on the server; the client shows it and drives it.** The agent, its tools, the project files, git, shells and dev servers all live on the server machine, because that is where the project and the compute are. The client keeps only what is personal to the device in front of you — its screen, its windows, its own tools — and a cache of what it last saw. + +```mermaid +flowchart LR + subgraph Clients["Paired devices"] + A["Gentle Shell GPUI on a laptop"] + B["Another device (desktop, phone later)"] + end + + subgraph Server["Server machine: one agent home"] + S["gentle-shell serve
HTTP + SSE API, auth, routing"] + K1["Session keeper
owns Pi's stdio, seq, replay ring; outlives serve"] + P1["Session
gentle-shell --mode rpc (Pi)"] + P2["Session
gentle-shell --mode rpc (Pi), under its own keeper"] + H["gentle-term-host
PTYs, Unix socket (loopback TCP on Windows), outlives serve"] + F["Forward listeners
one port per forward"] + L["Pages on loopback
dev server, design canvas, Tower, Engram"] + FS[("Project files and git")] + end + + A -- "Bearer token: JSON requests, SSE streams" --> S + B -- "Bearer token" --> S + A -- "Cookie per forward" --> F + S -- "JSON lines over sessions/.sock" --> K1 + K1 -- "stdin / stdout JSON lines" --> P1 + S -- "via its keeper" --> P2 + S -- "JSON lines over term.sock (Windows: 127.0.0.1 + token)" --> H + S -- "files, git, uploads" --> FS + P1 -- "agent tools" --> FS + F -- "proxy to 127.0.0.1" --> L +``` + +| Piece | Runs on | Does | Why there | +| --- | --- | --- | --- | +| `gentle-shell serve` | Server | One long-lived process per agent home. Pairs devices, checks every request's token and scope, starts and stops sessions, serves each session's replay ring to devices, routes host tool calls, serves files, git and uploads, opens forwards, talks to the terminal host. | One owner per home: sessions must survive the client that started them, and every device must see the same state. | +| Session keeper | Server | One small detached Node process per session: starts Pi and owns its stdin and stdout, numbers its records, keeps the replay ring, pending dialogs and open host tool calls; `serve` attaches to it over an owner-only socket. | Sessions must survive a `serve` restart or upgrade with their ids and `seq`, as terminals do. | +| Session | Server | One `gentle-shell --mode rpc` process per session: the same launcher, Pi and extensions as a local launch, with Desktop RPC on. | The agent needs the project, the tools and the provider sign-ins that live on the server. Each session isolated in its own process: a crash or a hang takes down one session, not the server. | +| `gentle-term-host` | Server | A small native process that owns the PTYs (ConPTY on Windows); `serve` is its client over an owner-only Unix socket, or on Windows over loopback TCP with a token from an owner-only file. | Shells must survive a `serve` restart or upgrade, and a reattaching client needs the screen as it is, which a headless terminal emulator in the host can draw. | +| Forward listeners | Server (inside `serve`) | One listener per forward, proxying to a page on the server's loopback. | Pages bound to `127.0.0.1` (dev servers, the design canvas, Tower) are unreachable from another machine by design; a forward opens one of them to one device without opening the port to anyone. | +| Client app | Each device | Shows sessions, files, diffs, branches, terminals and forwarded pages; sends prompts, edits and keystrokes; runs its own [host tools](#host-tools-across-several-devices) (a screenshot of this Mac). Remembers the server, its device token, and the last `seq` / terminal offset it saw. | It is the person's device: the screen, the keyboard, and tools that only make sense on that device. | + +What the client does **not** do against a server: run the agent, read or write project files locally, run git locally, or start a shell locally for a server folder. Everything that touches the project goes through the server's API, so two devices never disagree about the state of the project. + +## Connecting with the short code + +On the server, `gentle-shell serve share` starts (or reuses) a network server and prints an 8-character pairing code, with a long `gsc1.…` connection code under it as the fallback. The person types the short code in the app; the app finds the server by itself and pairs. Details: [Share on your network](serve.md#share-on-your-network), [LAN discovery](serve.md#lan-discovery), [Connection code](serve.md#connection-code). + +```mermaid +sequenceDiagram + autonumber + actor U as Person + participant Srv as Server machine + participant S as gentle-shell serve + participant App as Client app + U->>Srv: gentle-shell serve share + Srv->>S: start on 0.0.0.0:8787 (or reuse), UDP discovery on the same port + S-->>U: Code: 7PH3-DM9V (5 minutes, single use) + gsc1.… fallback + U->>App: types 7PH3-DM9V + App->>App: UDP broadcast {"t":"gentle-shell/discover","v":1}
to 255.255.255.255 and each subnet, ports 8787-8796 + S-->>App: unicast {"t":"gentle-shell/here","v":1,"id":"srv_…","n":"linux-box","p":8787} + Note over App: collect replies for about 1.5 s + App->>S: GET https://REPLY_SOURCE_IP:8787/.well-known/gentle-shell + S-->>App: { serverId: "srv_…", name, protocol, version, tls: true, fp } + Note over App: keep only replies whose serverId matches and whose
certificate fingerprint equals fp, several servers: the person picks one + App->>S: POST /api/pair/proof { nonce } + S-->>App: { proofs: one HMAC per live code, keyed by scrypt of the code and fp } + Note over App: send the code only if a proof matches it
and the fingerprint seen in the TLS handshake + App->>S: POST /api/pair { code, name } + S-->>App: 201 { id: "dev_…", scopes, token: "gss_…" } (shown once) + Note over App: pins the fingerprint, stores the server URL and the token,
every later request carries Authorization: Bearer gss_… +``` + +- **Identity before secrets.** The pairing code is sent only to an address whose `/.well-known/gentle-shell` names the `serverId` the discovery reply (or the connection code) announced, over TLS to the certificate that answer names. With the short code the app also asks for a **pairing proof** first: for each live code the server answers `HMAC(scrypt(code, fingerprint), fingerprint ‖ nonce)` for the app's random nonce, and the app sends its code only when one proof matches it and the fingerprint it saw in the handshake. A device that answers discovery with a forged reply has neither the code nor the server's key, so it can neither prove the code nor stand in the middle. The `serverId` is minted once per agent home (`/serve/server-id`) and stays the same across restarts and upgrades, so the app recognises the server it paired with. +- **When discovery does not reach** (another subnet, a tailnet, a Wi-Fi with client isolation, UDP blocked), the long `gsc1.…` code carries the `serverId`, the port, up to 8 addresses to try, the pairing code, the certificate fingerprint (`fp`, pinned directly) and, when the server uses one, its relay (`r`). The app probes every address in parallel and pairs at the first whose identity and certificate match; with a relay it also tries the server through it ([Outside the network](#outside-the-network-the-relay)). +- **Manual pairing.** `gentle-shell serve pair` mints a code for a server on loopback, reached through an SSH tunnel ([Reach it from the Mac](serve.md#4-reach-it-from-the-mac)). + +## Session lifecycle + +A session belongs to the server, not to the client that started it. Clients come and go; the session keeps running until someone deletes it, Pi exits, or the server stops with `--sessions`. It also outlives the server itself: its keeper holds it while the server restarts. + +Every record a session prints gets the session's next sequence number (`seq`). The keeper keeps the newest records in a replay ring (2000 records or 8 MiB), which the server serves. A client follows a session with one SSE stream and remembers the last `seq` it saw; when it comes back it asks for everything after it. Details: [Event stream](serve.md#event-stream-get-apisessionsidevents), [Replay and resume](serve.md#replay-and-resume), [Sessions across server restarts](serve.md#sessions-across-server-restarts). + +```mermaid +sequenceDiagram + autonumber + participant App as Client app + participant S as serve + participant P as Session (Pi, under its keeper) + App->>S: POST /api/sessions { cwd } + S->>P: start a keeper, which runs gentle-shell --mode rpc in cwd + S-->>App: 201 { session: { id: "ses_…", seq: 0 } } + App->>S: GET /api/sessions/ses_…/events + S-->>App: event: hello { seq, oldest } + App->>S: POST /api/sessions/ses_…/rpc { type: "prompt", … } + P-->>S: records (stdout) + S-->>App: id: 41 / data: { … } (each record gets the next seq) + Note over App,S: Network drops, laptop sleeps, app quits + P-->>S: records keep coming, kept in the replay ring + App->>S: GET …/events?after=41 (or Last-Event-ID: 41) + alt 41 is still in the ring + S-->>App: hello, then records 42…N, then live + else the ring moved past it + S-->>App: event: snapshot-required { after, oldest, seq } + App->>S: POST …/rpc get_state and get_messages, POST …/desktop get_snapshot + S-->>App: current state, then the live stream continues on the same connection + end + S-->>App: event: dialog (any dialog still waiting for an answer) +``` + +| Situation | What happens | +| --- | --- | +| **Start** | `POST /api/sessions { cwd }` starts a keeper and Pi in that folder. `{ cwd, sessionId }` opens the Pi session with that exact id (an existing conversation in that folder, or a new one under that id). The starting device becomes the session's `lastActiveDevice`. | +| **Client disconnects** | Nothing stops. Pi keeps running and its records keep entering the ring. A turn waiting on a dialog keeps waiting (until the dialog's own timeout). | +| **Resume by `seq`** | The client reconnects with `after=`. Inside the ring it gets exactly what it missed, then live records. Dialogs still pending are re-sent as `dialog` events; a host tool call still waiting for this device is re-sent as `host_tool_call`. | +| **Snapshot required** | The cursor is older than the ring (the client was away for a long run) or newer than the stream (a cursor from another session). The client rebuilds its view from Pi `get_state` / `get_messages` and Desktop RPC `get_snapshot`, then follows the live stream on the same connection. | +| **Slow client** | A subscriber with more than 4 MiB unsent is dropped with a `resync` event and reconnects with its last `id`. The session is never slowed down by a client. | +| **Client restarts** | The app keeps the server URL, the token, the session ids it had open and their last `seq`. On relaunch it lists `GET /api/sessions` and reattaches each one as above; terminals reattach by id and offset (see [Terminals](#terminals)). | +| **Several clients** | Every subscriber sees the same records. The first answer to a dialog wins; the others get `serve_dialog_resolved` and close it. Each request is authorized on its own, by scope. | +| **Session ends** | `DELETE /api/sessions/:id`, or Pi exits on its own: the stream carries `serve_session_exited` and ends. Up to 16 exited sessions stay listed until deleted. The session's forwards close with it. | +| **Server restarts** | `serve stop`, a service manager's restart or an upgrade stops only `serve`: sessions keep running under their keepers. The next server reattaches every one before it answers requests: same ids, `seq` continuing, dialogs and host tool calls still pending; a device owing a host tool call has 30 s to reconnect. A client reconnects with `after=` and gets what it missed while the server was down. `serve stop --sessions` stops the sessions too; a reboot ends them (a client starts one again with `{ cwd, sessionId }` and Pi reopens the conversation from disk). A session no server came back to stops after 24 hours. Paired devices stay paired (`devices.json`), the server id stays the same, and terminals live on in the terminal host. | + +## Host tools across several devices + +Some tools only make sense on the device in front of you: a screenshot of this Mac, a photo from the phone, a simulator running on the laptop. A client registers such tools with the session as **host tools**; the agent calls them like any other tool, but they run on the client, with the client's authority, and only the result goes back into the conversation. Nothing is installed on the server for them. Details: [Host tools](serve.md#host-tools) in serve, and [`set_host_tools`](desktop-rpc.md#set_host_tools), [`host_tool_result`](desktop-rpc.md#host_tool_result), [`host_tool_progress`](desktop-rpc.md#host_tool_progress), [`host_tool_call`](desktop-rpc.md#host_tool_call), [`host_tool_cancel`](desktop-rpc.md#host_tool_cancel), [`set_host_activity`](desktop-rpc.md#set_host_activity) in Desktop RPC. + +```mermaid +sequenceDiagram + autonumber + participant Mac as Laptop (device A) + participant Phone as Phone (device B) + participant S as serve + participant P as Session (Pi) + Mac->>S: POST …/desktop set_host_tools { tools: [device_screenshot] } + S->>P: set_host_tools with provider = dev_A (whatever the body said) + Phone->>S: POST …/desktop set_host_tools { tools: [device_screenshot] } + S->>P: set_host_tools with provider = dev_B + Note over S: providers with an open stream,
most recently active first + S->>P: set_host_activity { providers: [dev_B, dev_A] } + Mac->>S: POST …/rpc prompt "what is on my screen?" + Note over S: dev_A drove the session last + S->>P: set_host_activity { providers: [dev_A, dev_B] } + P-->>S: host_tool_call { callId, provider: dev_A, tool, args } + S-->>Mac: event in the stream (provider is dev_A) + S-->>Phone: same event (not its provider: ignored) + Mac->>Mac: runs the tool on this device + Mac->>S: POST …/desktop host_tool_result { callId, content } + Note over S: only dev_A may answer this call (403 otherwise) + S->>P: host_tool_result + P-->>S: the model reads the result, the turn continues +``` + +- **Registration.** `set_host_tools` and `set_host_context` go through `POST /api/sessions/:id/desktop` only, with `sessions:operate`. The server always replaces `provider` with the calling device's id, so no device can register tools (or hidden context) as another one. Through `/rpc` these requests are refused (`400 use_desktop_endpoint`). +- **Last-active routing.** Several devices may offer the same tool name. The server tells the session, with `set_host_activity`, which providers have an open stream, most recently active first ("active" = sent a prompt, a steer, a dialog answer, a Desktop write, or started the session). The session sends each call to the first of them that offers the tool. Clients cannot send `set_host_activity` themselves. +- **Offline fallback.** If the chosen device has no open stream when the call appears, the server answers it at once with an error result the model reads — ` runs in , which isn't connected right now.` — instead of letting the turn hang. If a device's last stream closes while it owes results, the server waits 10 s for it to come back, then answers its calls the same way. Revoking a device answers its calls at once. +- **Cancel.** When the person aborts the turn, the call ends at once as cancelled; when no result arrives within 10 minutes, it ends with an error result. Either way the session emits `host_tool_cancel { callId }` and the client stops running it; a late `host_tool_result` is answered `already_answered`. +- **Long calls.** A client still working on a call (a review the person is reading, a browser wait, a device flow) sends `host_tool_progress { callId }` every 60 s; each one restarts the 10 minutes, with no cap on the total. A client that dies stops sending, and the call fails 10 minutes later. Heartbeats are not activity: they never change which device gets the next call. +- **Only the provider answers.** The server remembers which device each call went to until it settles (at most 11 minutes after the call or its last heartbeat); a `host_tool_result` or `host_tool_progress` from any other device is refused with `403 forbidden`. + +## Pages on the server: port forwarding + +A page the agent started on the server (`127.0.0.1:5173`), the design canvas, Gentle Tower or Engram listen on the server's loopback, which no other machine can reach. A **forward** opens one of them to one paired device. Details: [Port forwarding](serve.md#port-forwarding), [Forward security](serve.md#forward-security), [Server-level forwards and services](serve.md#server-level-forwards-and-services), [Gentle Tower](serve.md#gentle-tower). + +```mermaid +sequenceDiagram + autonumber + participant App as Client app (webview or browser) + participant S as serve API + participant F as Forward listener :8800 + participant Pg as Page on 127.0.0.1:5173 + App->>S: POST /api/sessions/:id/forwards { port: 5173, path: "/" } (Bearer) + S-->>App: 201 { id, listenPort: 8800, url: "http://host:8800/?gs_ticket=…", expiresAt } + App->>F: GET /?gs_ticket=… (ticket: single use, 60 s, this forward and device) + F-->>App: 303 Location: / + Set-Cookie: gs_fwd_ID=SECRET, HttpOnly, SameSite=Strict + App->>F: GET / (Cookie: gs_fwd_ID) + Note over F: checks Host and Origin, strips the ticket and every gs_fwd_* cookie + F->>Pg: GET / (Host: 127.0.0.1:5173) + Pg-->>F: 200, streamed + F-->>App: 200, streamed (Location to loopback rewritten to the forward) + App->>F: GET /events (SSE): piped as it arrives, never buffered + App->>F: WebSocket upgrade (Cookie): handed to the page, both sockets piped +``` + +- **One port per forward,** not a path prefix on the API port: pages use absolute paths (`/assets/app.js`, `/@vite/client`) and their own WebSocket URLs, which keep working unchanged on their own origin. `serve share` uses ports 8800-8899 (`--forward-ports`) so one firewall rule covers them. +- **A ticket, then a cookie.** Tokens never go in URLs. The link carries a 60-second single-use ticket, exchanged on first use for an `HttpOnly; SameSite=Strict` cookie named after the forward, so forwards on different ports of the same host never share a cookie. +- **Only loopback targets.** A forward targets `127.0.0.1:` (or `[::1]`) on the server machine, never another host and never the API's or another forward's port. +- **Scoped and short-lived.** A forward belongs to one device and (for session forwards) to one session. It closes on `DELETE`, when the session stops, when the device is revoked, when the server stops, or after 12 idle hours. + +## Terminals + +Terminals on the server are real shells in a project folder that keep running when the client disconnects, when another device takes over, and when `serve` itself restarts. Details: [Persistent terminals](serve.md#persistent-terminals), [The host](serve.md#the-host), [Terminal endpoints](serve.md#terminal-endpoints). + +```mermaid +sequenceDiagram + autonumber + participant App as Client app + participant S as serve + participant H as gentle-term-host + participant Sh as Shell (PTY) + App->>S: POST /api/terminals { cwd, cols, rows } + S->>H: connect term.sock or, on Windows, 127.0.0.1 + token (start the host if nothing answers) + S->>H: open + H->>Sh: fork a PTY, login shell + S-->>App: 201 { terminal: { id: "t_…", offset: 0 } } + App->>S: GET /api/terminals/t_…/stream + S->>H: attach + H-->>S: { offset } + S-->>App: event: attached, then output { offset, data } with id: offset + App->>S: POST …/input { data }, POST …/resize { cols, rows } + Note over App: app quits, the shell keeps running in the host + Note over S,H: serve may restart too, the host and its shells stay + App->>S: GET /api/terminals/t_…/stream?from=LAST_OFFSET + S->>H: attach { from } + alt from is still in the host's replay buffer + H-->>S: { offset: from } then the missed bytes + else too far behind + H-->>S: { offset, snapshot } drawn by the host's headless emulator + end + S-->>App: event: attached { offset, snapshot? }, then live output +``` + +- **The host owns the PTYs.** `serve` is only a client: it opens one control connection and one connection per stream. A `serve` restart closes connections, never terminals. The host exits by itself after 10 minutes with no terminals and no connections; a reboot or a host crash loses its terminals. +- **Attach, snapshot, resume.** Each terminal keeps at least the last 1 MiB of output. A client that comes back with an offset still in that buffer gets exactly the missed bytes. Otherwise it gets a snapshot: an ANSI sequence that, written into a fresh emulator of the terminal's size, reproduces the screen — contents, cursor, colours, alternate screen and modes — plus up to 2000 lines of scrollback. Full-screen programs such as `top` or an editor come back exactly as they are. +- **Ownership.** A terminal belongs to the device that opened it; other devices get `404` for it. An `admin` token sees all of them. Revoking a device closes its terminals. +- **Several viewers.** Every stream is its own attachment; two windows or two devices (with `admin`) can follow the same terminal. +- **Where the host comes from.** `$GENTLE_TERM_HOST`, else `/serve/bin/gentle-term-host`, else `gentle-term-host` on `PATH`. Without one the server has no `terminals` capability and the terminal endpoints answer `501 term_host_missing`; an `admin` client can install a build with `PUT /api/term-host` (sha256-checked). The host is a small Rust program (PTYs and a headless emulator); it is not shipped with the npm package, but every Gentle Shell GPUI release carries it per platform (`gentle-term-host--[.exe]`, in the release's `SHA256SUMS`), and `GET /api/term-host` names the one that fits the server (`asset`). + +## Sign-in, packages and upgrades from the client + +What a person would otherwise do in a terminal on the server, the client does over the same connection: + +| Task | How | Scope | +| --- | --- | --- | +| See which providers are signed in, and how each can be | [`get_auth_status`](desktop-rpc.md#get_auth_status) (`loginKinds`: `oauth`, `device`, `api_key`) | `sessions:read` | +| See which models the server can use, and their thinking levels | [`list_available_models`](desktop-rpc.md#list_available_models) | `sessions:read` | +| Sign in to a provider | [`login_start`](desktop-rpc.md#login_start), then [`login_prompt`](desktop-rpc.md#login_prompt) events answered with [`login_complete`](desktop-rpc.md#login_complete), until [`login_finished`](desktop-rpc.md#login_finished) | `sessions:operate` | +| Save or remove an API key | [`set_api_key`](desktop-rpc.md#set_api_key), [`remove_credentials`](desktop-rpc.md#remove_credentials) | `sessions:operate` | +| List, install or remove packages | [`list_packages`](desktop-rpc.md#list_packages); [`install_package`](desktop-rpc.md#install_package) / [`remove_package`](desktop-rpc.md#remove_package) with [`package_progress`](desktop-rpc.md#package_progress) and [`package_finished`](desktop-rpc.md#package_finished) | read / `sessions:operate` | +| Upgrade Gentle Shell | [`POST /api/upgrade`](serve.md#upgrade-from-a-client), its stream, then the server restarts on the new version | `admin` | +| Run Gentle Shell's setup (companion packages) | [`POST /api/setup`](serve.md#setup-from-a-client) and its stream; no restart | `admin` | +| See whether Node.js, the companion setup, Git and Engram are ready on the server | [`GET /api/checks`](serve.md#readiness-checks) (capability `checks`; the app's setup checklist rows, by the same rules) | `sessions:read` | +| Change model defaults (default model, effort, scoped models) | [`get_config`/`set_config`](desktop-rpc.md#set_config) store `pi_settings` (its four model keys, as a patch) | read / `sessions:operate` | +| Edit custom models (`models.json`) or MCP servers (`mcp.json`) | [`get_config`/`set_config`](desktop-rpc.md#set_config) stores `custom_models` and `mcp`; secrets read as `"•••"` | read / `sessions:operate` | + +The Desktop RPC rows go to a session's `/desktop` (`POST /api/sessions/:id/desktop`) or, without a session of the client's own, to the server's [`/api/desktop`](#clients-without-sessions): Pi runs its own `/login` flow, key setup, `/logout`, or the `gentle-shell install`/`remove` CLI, on the server, with the server's agent home. Credentials land in Pi's credential store on the server and serve every session there; the session that signed in has the new models at once, other sessions after `reload_credentials`. + +```mermaid +sequenceDiagram + participant App as Client app + participant S as gentle-shell serve + participant Pi as Control session (Pi) + participant B as Browser on the client + App->>S: /api/desktop login_start { provider } + S->>Pi: /gentle:desktop login_start + Pi-->>App: { loginId }, then login_prompt open_url { url, redirectPrefix: http://localhost:1455/ } (on /api/desktop/events) + App->>B: open url + B-->>App: redirect to http://localhost:1455/auth/callback?code=…&state=… (intercepted) + Pi-->>App: login_prompt input { redirectPrefix } + App->>S: /api/desktop login_complete { loginId, value: full redirect URL } + S->>Pi: /gentle:desktop login_complete + Pi->>Pi: Pi checks the state, exchanges the code, stores the credential, reloads + Pi-->>App: login_finished { ok: true } +``` + +A browser sign-in redirects to a loopback callback on the machine that started it; the browser is on the client, so the client catches that redirect (or the user pastes the address bar) and hands the full URL to the server, which completes the exchange exactly as its own callback would. A device-code sign-in needs nothing of the sort: the client shows the code and the page. The upgrade restarts only `serve`: sessions, their keepers and the terminal host keep running, and clients reconnect as after any [server restart](#session-lifecycle). + +## Clients without sessions + +Configuration, sign-in and packages belong to the server, not to a conversation, so a client that has no agent session open — a phone checking which providers are signed in, a web page, a script with curl, the app's Configuration screen — reaches them without starting one. `GET /api/server` lists the capability `desktop`; details: [Desktop RPC without a session](serve.md#desktop-rpc-without-a-session-post-apidesktop). + +```mermaid +sequenceDiagram + participant App as Client (no session) + participant S as gentle-shell serve + participant C as Control session (Pi, in the server user's home) + App->>S: GET /api/desktop/events + S->>C: first use: start it (hidden, never prompted) + S-->>App: event: hello, then its Desktop events only + App->>S: POST /api/desktop { method: "install_package", params: { source } } + S->>C: /gentle:desktop install_package + C-->>App: { jobId } (the HTTP answer) + C-->>App: package_progress …, package_finished (on the stream) + Note over S,C: 10 minutes without a request or an open stream: stopped; the next use starts it again +``` + +| | `POST /api/desktop` + `GET /api/desktop/events` | A session's `/desktop` + `/events` | +| --- | --- | --- | +| Needs | Nothing: the server starts its control session on first use | A session the client started or attached to | +| Answers | Configuration (`get_config`/`set_config`), models (`list_available_models`), sign-in, API keys, packages, update status, `capabilities` | The same, plus what is about that conversation (permission mode, jobs, subagents, changes) | +| Events | Desktop events only (`login_prompt`, `package_progress`, `config_changed`, …) with the stream's `seq`, `after`, tickets | Every record of the session | +| Host tools | Refused (`400 use_session_desktop`): they belong to the agent session whose model calls them | Registered and answered per device | +| Model turns | Never | Prompts, steering, … | +| Scopes | Per method, as `/desktop`: `capabilities`, `get_*`, `list_*` read; the rest operate | The same | + +The control session is a session like the others under the hood: the same launcher, Pi and extensions, its own keeper. Unlike them it ends with its server: it holds no user state, and a `serve` restart (after a `git pull`, a reinstall or an upgrade) must answer with the new code, so the next server starts a fresh one on first use and stops any an earlier server left running. It is never listed (an `admin` sees it with `GET /api/sessions?includeControl=1`), not reachable by id, and not counted against the 16 running sessions. + +## Security model + +### Threat model + +| Actor | Can | Cannot | +| --- | --- | --- | +| Someone on the same network, not paired | See that a server exists (discovery reply and `/.well-known/gentle-shell`: server id, hostname, port, version, certificate fingerprint). Try pairing codes, rate-limited. Only with `--no-tls`: read and alter traffic they can intercept (see [TLS on the network](#tls-on-the-network)). | Call any endpoint other than the identity, the pairing proof and pairing. Guess a pairing code: 40 random bits, 5 minutes, single use, 10 failures per minute pause pairing for everyone. Read or alter the traffic of a paired device (TLS to a pinned certificate). | +| A web page in a browser on any device | Nothing against the API. | Send requests with an `Origin` other than the server's own (refused before auth); ride a token (tokens are never cookies); use DNS rebinding (the `Host` header must name this server). Use a forward's cookie from another origin (`Origin` checked per forward; `SameSite=Strict`). | +| A paired device | What its scopes allow ([table below](#scopes)), as the server user. | Act as another device: register tools or context under another id, answer another device's host tool calls, see or drive another device's terminals or forwards (without `admin`). | +| A revoked device | Nothing: its token, tickets, streams, forwards, terminals and pending host tool calls end at once. | — | +| The model / agent | What its tools and the permission mode allow, as with a local session. Call host tools a client registered (the client decides how to run them and whether to ask). | Reach the client's device except through a registered host tool. | +| A local user other than the server user | Nothing: `/serve/` is `0700`, its files `0600`, the terminal socket `0600` (on Windows the host's port is reachable, but its token is in a file only the server user can read). | Read `server.json` (the local admin token) or connect to the terminal host. | + +### Scopes + +Every request is authorized on its own, by the device token's scopes; `/rpc` and `/desktop` are authorized per command or method. `serve share` and `serve pair` grant `sessions:read`, `sessions:operate` and `terminal` by default; `serve pair --scope …` narrows them. + +| Scope | Allows exactly | Notably does not allow | +| --- | --- | --- | +| `sessions:read` | List sessions and read their state; follow event streams; mint stream tickets; read-only Pi RPC (`get_state`, `get_messages`, `get_available_models`, `get_available_thinking_levels`, `get_session_stats`, `get_fork_messages`, `get_entries`, `get_tree`, `get_last_assistant_text`, `get_commands`); read-only Desktop RPC (`capabilities`, `get_*`, `list_*`); `GET /api/server`, `/api/services`, `/api/tower`, `/api/checks`, list its own forwards; **see every file name the server user can see** (`/api/fs/list`, `stat`, `search`, `watch`); git commands that print no file contents (`status`, branches, `log`, `diff --numstat`/`--name-status`, …). | Read a file's contents (`/api/fs/read`) or print them through git (`show`, patches, blobs, `blame`, `grep`); prompt, steer, answer dialogs, start or stop sessions, write files, change git state, open forwards or terminals. Sees session names, not absolute `cwd`. | +| `sessions:operate` | Everything a person typing in the session's terminal could do: start and delete sessions in any folder; every other Pi RPC command (prompts, steering, abort, bash, model changes, dialog answers); every other Desktop RPC method, **including `set_permission_mode`** and host tool registration; read, write, rename and remove files; any git command (except the refused program-running options); uploads; forwards; start and stop Tower. | Open shells (`terminal`), pair or revoke devices, stop the server, install the terminal host (`admin`). Remove or rename the file system root, the home folder or a folder above it. | +| `terminal` | Open, list, drive, resize and close its own terminals: an interactive shell as the server user. `GET /api/term-host`. | Other devices' terminals; installing the host. | +| `admin` | Pairing codes, list and revoke devices, stop the server, install the terminal host binary; see and close every device's forwards and terminals. Held by the local admin token (in owner-only `server.json`, used by the `serve` CLI); not granted by default to devices. | — | + +### Pairing, tokens and tickets + +| Credential | Form | Lifetime | Stored as | +| --- | --- | --- | --- | +| Pairing code | `ABCD-EFGH`, 40 random bits, Crockford base32 | 5 minutes, single use (the first attempt that names it consumes it); at most 16 live; 10 failures per minute pause pairing | In memory | +| Connection code | `gsc1.` + base64url JSON (server id, name, port, addresses, pairing code) | A secret while its pairing code is valid; afterwards only names the server | Not stored | +| Device token | `gss_` + 32 random bytes | Until revoked (`serve devices --revoke`, `DELETE /api/devices/:id`); at most 64 devices | sha256 only, in `devices.json` (`0600`); compared in constant time | +| Local admin token | Random, per server run | The server run | `server.json` (`0600`), owner only | +| Stream ticket | Random | 60 s, single use, one session's events stream, the minting device's scopes | In memory | +| Forward ticket | Random, in the link | 60 s, single use, one forward and device | In memory | +| Forward cookie | `gs_fwd_`, random secret, `HttpOnly; SameSite=Strict` | The forward's life (closed, revoked, 12 idle hours, server stop); 32 browser sessions per forward | In memory | + +### Host and Origin rules + +- **`Host`** must name this server and its port (`421 bad_host`): loopback names for a loopback bind; the bound address otherwise; for `0.0.0.0`/`::`, any IP literal or the machine's own hostname (also `.local`). Any other DNS name only when the operator adds it exactly with `--allow-host ` (for example a tailnet MagicDNS name). This blocks DNS rebinding. +- **`Origin`**, when present, must be `http://` or `https://` (`403 forbidden_origin`), checked before authentication, pairing included. Native clients and curl send none. +- **Forwards** apply the same `Host` rule to their own port and accept only their own origin, so one forwarded page cannot drive another forward's page with its cookie. +- **Headers** on every API answer: `Cache-Control: no-store`, `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`. No CORS headers. + +### TLS on the network + +Without `--listen` the server binds `127.0.0.1` only and speaks plain HTTP to this machine. A network server (`serve share`, or any non-loopback `--listen`) speaks **HTTPS** with a self-signed ECDSA P-256 certificate it makes on first run (`/serve/tls/`, key `0600`); clients pin its SHA-256 fingerprint at pairing and refuse any other certificate afterwards. Plain HTTP from another machine gets `400 tls_required`; connections from the server machine itself may still use plain HTTP. Changing the certificate (deleting `tls/`) makes every paired device pair again. + +`--no-tls` serves plain HTTP on the network, printed as a warning: the pairing code, the device token, prompts, file contents and terminal keystrokes then cross the network unencrypted. Use it only where the network encrypts by itself (a tailnet); otherwise keep TLS or the SSH tunnel. + +### Outside the network: the relay + +`gentle-shell relay --listen :` is a small self-hostable rendezvous (a VPS, any machine both sides reach). A server started with `--relay gsr://:` keeps one outbound control connection to it, authenticated with a shared secret (`/serve/relay-secret`, `0600`, or `GENTLE_SHELL_RELAY_SECRET`). A client asks the relay for a server by its certificate fingerprint; the relay asks that server to open one more outbound connection and splices the two TCP streams. TLS runs end to end between the client and `serve`, pinned to the fingerprint, so the relay only sees ciphertext and logs byte counts. `--relay` cannot be combined with `--no-tls`. Details: [Relay](serve.md#4-reach-it-from-the-mac). + +### What the server never does + +- **Run client code.** A host tool runs on the device that registered it; the server and the agent only see its arguments and its result. No script, binary or command from a client is executed on the server, except the terminal host binary an `admin` explicitly installs (hash-checked) and the commands a scope already allows (prompts, git, a shell). +- **Expose paths beyond scope.** A forward reaches only the server's loopback, never another host. Session lists show only the folder name to a `sessions:read` token. A device sees only its own forwards and terminals. Uploads go to an owner-only folder per device. The terminal host never listens on the network (on Windows only on `127.0.0.1`, behind a token). +- **Exceed the terminal's authority.** `sessions:operate` is exactly what typing in the session's terminal can do — including changing the permission mode, see the [Desktop RPC trust boundary](desktop-rpc.md#trust-boundary). Remote prompts are not interactive consent, provider consent stays terminal-only, and every existing check in the session still applies. +- **Store a token in clear.** Device tokens are kept as sha256 hashes; long-lived tokens never go in URLs. +- **Open a browser or listen beyond what was asked.** Sessions run with `GENTLE_DESIGN_OPEN_BROWSER=0`; forwards listen only while open; discovery listens only on a network bind. + +Note what `sessions:read` means: **the file endpoints run as the server user with no folder jail**, so a read-only device sees the name, size and changes of every file that user can see, and every session's conversation (including what its tools printed). It never reads a file's contents through the file or git endpoints, so secrets the configuration stores mask (`mcp.json`, provider credentials, SSH keys) stay unread. Pair `sessions:read` only with devices you would let watch your sessions; pair `sessions:operate` and `terminal` only with devices you would hand your terminal. + +## Reference + +### Endpoints + +| Area | Endpoints | Reference | +| --- | --- | --- | +| Identity and pairing | `GET /.well-known/gentle-shell`, `POST /api/pair` | [Endpoints](serve.md#endpoints), [Authentication](serve.md#authentication) | +| Server and devices | `GET /api/server`, `POST /api/server/stop`, `POST /api/upgrade`, `GET /api/upgrade/:jobId/stream`, `POST /api/setup`, `GET /api/setup/:jobId/stream`, `POST /api/pairing-codes`, `GET /api/devices`, `DELETE /api/devices/:id` | [Endpoints](serve.md#endpoints), [Upgrade from a client](serve.md#upgrade-from-a-client), [Setup from a client](serve.md#setup-from-a-client) | +| Sessions | `GET`/`POST /api/sessions`, `GET`/`DELETE /api/sessions/:id`, `POST …/rpc`, `POST …/desktop`, `GET …/events`, `POST /api/tickets` | [Pi RPC](serve.md#pi-rpc-post-apisessionsidrpc), [Desktop RPC](serve.md#desktop-rpc-post-apisessionsiddesktop), [Event stream](serve.md#event-stream-get-apisessionsidevents), [Stream tickets](serve.md#stream-tickets) | +| Desktop RPC without a session | `POST /api/desktop`, `GET /api/desktop/events` | [Desktop RPC without a session](serve.md#desktop-rpc-without-a-session-post-apidesktop), [Clients without sessions](#clients-without-sessions) | +| Forwards and services | `POST`/`GET /api/sessions/:id/forwards`, `DELETE …/forwards/:fid`, `POST`/`GET /api/forwards`, `DELETE /api/forwards/:fid`, `GET /api/services`, `POST`/`GET`/`DELETE /api/tower` | [Port forwarding](serve.md#port-forwarding), [Server-level forwards and services](serve.md#server-level-forwards-and-services), [Gentle Tower](serve.md#gentle-tower) | +| Files | `GET /api/fs/list`, `stat`, `search`, `watch` (`sessions:read`); `GET /api/fs/read`, `PUT /api/fs/write`; `POST /api/fs/mkdir`, `rename`, `remove` (`sessions:operate`) | [Files on the server](serve.md#files-on-the-server), [File safety](serve.md#file-safety) | +| Readiness | `GET /api/checks` | [Readiness checks](serve.md#readiness-checks) | +| git | `POST /api/git` | [git on the server](serve.md#git-on-the-server), [git scopes and refusals](serve.md#git-scopes-and-refusals) | +| One-shot prompts (commit messages) | `POST /api/print` | [One-shot prompts](serve.md#one-shot-prompts) | +| Uploads | `POST /api/uploads` | [Uploads](serve.md#uploads) | +| Terminals | `GET`/`POST /api/terminals`, `POST …/input`, `POST …/resize`, `DELETE /api/terminals/:t`, `GET …/stream`, `GET`/`PUT /api/term-host` | [Terminal endpoints](serve.md#terminal-endpoints), [The host](serve.md#the-host) | + +### Desktop RPC host tools + +| Name | Kind | Sent by | Reference | +| --- | --- | --- | --- | +| `set_host_tools` | Method | Client (through `/desktop`; provider forced to the device) | [desktop-rpc.md](desktop-rpc.md#set_host_tools) | +| `host_tool_result` | Method | The provider device only | [desktop-rpc.md](desktop-rpc.md#host_tool_result) | +| `host_tool_progress` | Method | The provider device only, every 60 s while it works on a call | [desktop-rpc.md](desktop-rpc.md#host_tool_progress) | +| `host_message` | Method | Client (through `/desktop`) | [desktop-rpc.md](desktop-rpc.md#host_message) | +| `set_host_context` | Method | Client (through `/desktop`; provider forced to the device) | [desktop-rpc.md](desktop-rpc.md#set_host_context) | +| `set_host_activity` | Method | `serve` only (`403` from a client) | [desktop-rpc.md](desktop-rpc.md#set_host_activity) | +| `host_tool_call` | Event | Session → every subscriber; the named `provider` runs it | [desktop-rpc.md](desktop-rpc.md#host_tool_call) | +| `host_tool_cancel` | Event | Session, on abort or after 10 minutes without a result or heartbeat | [desktop-rpc.md](desktop-rpc.md#host_tool_cancel) | + +Their limits: [Host tools limits](desktop-rpc.md#host-tools-limits). + +### Limits and timeouts + +The most relevant ones; the complete table is [Limits](serve.md#limits). + +| What | Value | +| --- | --- | +| Running sessions | 16 | +| Replay ring per session | 2000 records or 8 MiB | +| Unsent bytes per event subscriber | 4 MiB, then `resync` | +| `/rpc` and `/desktop` wait | 30 s (then `202 pending` / `504 desktop_timeout`) | +| Host tool call | Answered at once when its device is offline; 10 s grace after its last stream closes; 10 minutes without a result, restarted by each `host_tool_progress` | +| Pairing code / stream ticket / forward ticket | 5 minutes / 60 s / 60 s, all single use | +| Devices | 64 | +| Forwards | 32 open, 64 connections each, 12 hours idle | +| File read / write / upload | 8 MiB per read, 64 MiB per write or upload | +| git command | 120 s (600 s for network commands), 16 at once | +| One-shot prompt (`/api/print`) | 120 s, 1 MiB answer, 4 at once | +| Terminal replay | At least 1 MiB per terminal, then snapshot; 8 MiB unsent per stream, then `overflow` | +| SSE heartbeat | 20 s | + +### Error codes + +Every error is `{ "error": { "code", "message" } }`. The codes a client meets most: + +| Status and code | Meaning | Reference | +| --- | --- | --- | +| `401 unauthorized`, `401 invalid_ticket` | No valid token (or revoked); a stream ticket unknown, used or expired | [Authentication](serve.md#authentication) | +| `403 forbidden` | The token lacks the scope; or a `host_tool_result` / `host_tool_progress` for another device's call; or `set_host_activity` from a client | [Authentication](serve.md#authentication), [Host tools](serve.md#host-tools) | +| `403 forbidden_origin`, `421 bad_host` | `Origin` or `Host` rules | [Security model](serve.md#security-model) | +| `403 invalid_code`, `429 rate_limited`, `409 too_many_devices` | Pairing | [Endpoints](serve.md#endpoints) | +| `404 not_found` | Unknown session (deleted, or gone after a reboot), forward, terminal (or another device's) | [Replay and resume](serve.md#replay-and-resume) | +| `400 use_desktop_endpoint` | A host tool request sent through `/rpc` | [Pi RPC](serve.md#pi-rpc-post-apisessionsidrpc) | +| `400 use_session_desktop` | A host tool method sent to `/api/desktop` | [Desktop RPC without a session](serve.md#desktop-rpc-without-a-session-post-apidesktop) | +| `409 dialog_answered`, `404 unknown_dialog` | Another client answered first; no such dialog | [Dialogs](serve.md#dialogs) | +| `409 session_exited`, `503 session_busy`, `429 too_many_sessions` | Session state and limits | [Backpressure](serve.md#backpressure), [Limits](serve.md#limits) | +| `504 desktop_timeout`, `502 desktop_refused` | Desktop RPC through `/desktop` | [Desktop RPC](serve.md#desktop-rpc-post-apisessionsiddesktop) | +| `412 changed`, `409 exists`, `409 not_empty`, `403 protected_path`, `413 too_large` | Files | [Files on the server](serve.md#files-on-the-server) | +| `400 git_refused`, `429 too_many_git`, `501 git_missing` | git | [git scopes and refusals](serve.md#git-scopes-and-refusals) | +| `502 print_failed`, `502 output_too_large`, `504 print_timeout`, `429 too_many_prints` | One-shot prompts | [One-shot prompts](serve.md#one-shot-prompts) | +| `400 invalid_port`, `429 too_many_forwards`, `503 no_forward_port`, `503 tower_unavailable` | Forwards and Tower | [Port forwarding](serve.md#port-forwarding) | +| `501 term_host_missing`, `502 term_spawn_failed`, `409 terminal_exited`, `502 term_host_gone` | Terminals | [Terminal endpoints](serve.md#terminal-endpoints) | +| Desktop RPC `unknown_call`, `already_answered`, `too_large`, `host_tools_unavailable` | Inside a `/desktop` answer (`ok: false`) | [desktop-rpc.md](desktop-rpc.md#responses) | + +## Known limits and next steps + +- **Certificates.** The certificate is self-signed and pinned; there is no rotation command and no CA-signed option. A new certificate means pairing again. +- **Mobile.** No push notifications yet for a phone when a turn ends or a dialog waits; the relay covers reachability only. +- **`serve share --always`** (start at login) is Linux and macOS only. +- **Narrower scopes.** No folder jail and no separate `fs:read`/`fs:write` scopes yet; see [Not done yet](serve.md#not-done-yet) for the rest (WebSocket transport, native Desktop RPC frames, idle unload and crash resume). diff --git a/docs/serve.md b/docs/serve.md new file mode 100644 index 000000000..f36b8676c --- /dev/null +++ b/docs/serve.md @@ -0,0 +1,810 @@ +# `gentle-shell serve` + +`gentle-shell serve` runs one long-lived server per agent home. The server owns Gentle Shell sessions — one `gentle-shell --mode rpc` process each, under a small keeper process — so they keep running when the client that started them disconnects, and when the server itself restarts or is upgraded; any paired device can follow and drive them over HTTP and Server-Sent Events (SSE). A device can also open web pages that live on the server's own loopback — the design canvas, a dev server the agent started, [Gentle Tower](#gentle-tower) — through [authenticated port forwards](#port-forwarding). + +This is Phase 1 of [RFC #3527](https://github.com/Gentleman-Programming/gentle-shell/issues/3527), plus the `/.well-known/gentle-shell` identity, LAN discovery and `serve share` codes, and the pieces a remote client needs around sessions: [files](#files-on-the-server), [git](#git-on-the-server), [uploads](#uploads), [server-level forwards](#server-level-forwards-and-services) and [persistent terminals](#persistent-terminals) over a native terminal host. On a network it speaks HTTPS with a pinned self-signed certificate and can be reached through a self-hostable relay; SSH bootstrap and a mobile web client are not part of it; see [Not done yet](#not-done-yet). To run it from a source checkout on a Linux machine and reach it from another one, see [Try it](#try-it-from-source-on-linux). + +This page is the reference: commands, files, every endpoint, limits and troubleshooting. For the overview — what runs on the server and on each client, diagrams of pairing, sessions, host tools, forwards and terminals, and the security model in one place — read [Remote use](remote.md) first. + +## Quick start: connect from Gentle Shell GPUI + +On the computer where the agents should run (for example a Linux PC on your home network), run one command: + +```sh +gentle-shell serve share +``` + +It prints a short code, and a long one under it: + +```text +Started the Gentle Shell server for your network on port 8787. + + Code: 7PH3-DM9V + +In Gentle Shell GPUI → Configuration → Where agents run → Gentle Shell server, enter this code. Valid for 5 minutes, once. +If the app can't find this computer, paste this instead: +gsc1.eyJ2IjoxLCJpZCI6InNydl8… + +It uses HTTPS; the app checks this computer's certificate, fingerprint XpLq…. +``` + +Type the 8-character code in Gentle Shell GPUI on the other computer, in **Configuration → Where agents run → Gentle Shell server**: the app finds this computer on your network by itself ([LAN discovery](#lan-discovery)) and pairs. That is all: no SSH, IP addresses, ports or tunnels. When the app cannot find it — the computers are on different subnets, on a tailnet, or the Wi-Fi isolates clients — paste the long `gsc1.…` line in the same field instead. On Linux with a firewall, `share` also prints the command that opens the port (for example `sudo ufw allow 8787`, which covers both the HTTP connection and discovery). For another device, or when the code expired, run `serve share` again. `gentle-shell serve share --always` also starts the server at every login; `serve share --off` turns that off. Details: [Share on your network](#share-on-your-network). From a source checkout, run the checkout's launcher instead (`gsdev serve share`, see [Try it](#try-it-from-source-on-linux)). + +## Quick start by hand + +```sh +gentle-shell serve # start in the background; prints the URL +gentle-shell serve pair # one-time code for a device (5 minutes, single use) +curl -X POST http://127.0.0.1:PORT/api/pair \ + -H 'Content-Type: application/json' -d '{"code":"ABCD-EFGH","name":"laptop"}' +# → {"id":"dev_…","name":"laptop","scopes":[…],"token":"gss_…"} (the token is shown once) + +curl -X POST http://127.0.0.1:PORT/api/sessions -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' -d '{"cwd":"/path/to/project"}' +curl -X POST http://127.0.0.1:PORT/api/sessions/$SID/rpc -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' -d '{"type":"get_state"}' +curl -N "http://127.0.0.1:PORT/api/sessions/$SID/events?after=0" -H "Authorization: Bearer $TOKEN" + +gentle-shell serve status +gentle-shell serve stop # stops the server; its sessions keep running for the next one (--sessions stops them too) +``` + +## Commands + +| Command | Does | +| --- | --- | +| `gentle-shell serve share [--port ] [--always] [--json]` | Open the server to the local network (with [LAN discovery](#lan-discovery)) and print the short pairing code plus a [connection code](#connection-code) for Gentle Shell GPUI. See [Share on your network](#share-on-your-network). `--json` prints `{ code, pairingCode, port, addresses, expiresAt, serverId, discovery }` (`code` is the `gsc1.…` connection code, `pairingCode` the short one, `discovery` whether the server answers LAN discovery). | +| `gentle-shell serve share --off` | Remove the login autostart that `--always` installed (this stops the server it runs). | +| `gentle-shell serve [--listen :] [--allow-host ]... [--forward-ports -] [--foreground] [--json]` | Start the server. In the background by default (log in `serve/server.log`); `--foreground` keeps it in the terminal until Ctrl+C. `--listen` defaults to `127.0.0.1:0` (a random port); `:8787`, `8787` and `[::1]:8787` are accepted. `--allow-host` adds one DNS name clients may use in the `Host` header (repeatable; see [Security model](#security-model)). `--forward-ports` gives [port forwards](#port-forwarding) their listen ports from one range (at most 1000 ports), so a firewall can open it; without it each forward takes a random port. | +| `gentle-shell serve status [--json]` | URL, pid, start time, protocol and the session list. Exit 1 when no server runs. | +| `gentle-shell serve stop [--sessions]` | Asks the server to stop and waits for it to exit. Its sessions keep running and the next server reattaches them ([Sessions across server restarts](#sessions-across-server-restarts)); `--sessions` stops them first. | +| `gentle-shell serve pair [--scope ] [--json]` | Mint a pairing code. Scopes default to `sessions:read,sessions:operate,terminal`. | +| `gentle-shell serve devices [--revoke ] [--json]` | List paired devices or revoke one. Works without a running server too (on the devices file). | + +The home selectors work ahead of `serve` as they do for `setup`: `gentle-shell --home ~/work-agent serve` runs a separate server for that home, and its sessions run against that home. + +## Share on your network + +`serve share` is the one command a person runs to connect Gentle Shell GPUI on another computer of the same network: + +- **No server yet:** it starts one in the background on every interface (`--listen 0.0.0.0:8787 --allow-host --allow-host .local --forward-ports 8800-8899`). When the port is taken it tries the next nine; `--port ` starts the search elsewhere. [Forwarded pages](#port-forwarding) take ports 8800-8899. +- **A server on this computer only (loopback):** with no running sessions it is stopped and started again on the network, transparently. With running sessions it is left alone: `share` explains in one line and exits 1 (stop them or run `serve stop` first). +- **A server already on the network:** reused as it is (on its own port). + +Then it mints a pairing code (as `serve pair` does: default scopes, 5 minutes, single use) and prints it, followed by the [connection code](#connection-code) that carries it. The app takes either in the same field: the short code when it can [find the server on the network](#lan-discovery) by itself, the long one where discovery does not reach (another subnet, a tailnet, a Wi-Fi with client isolation). When the server could not open its UDP port, `share` says so in one line (discovery is off; the long code still works). On Linux, when `ufw` or `firewall-cmd` is installed, it also prints the exact command that opens the port for TCP and UDP and the forwarded pages' range for TCP (it never runs `sudo` itself), for example `sudo ufw allow 8787 && sudo ufw allow 8800:8899/tcp`. A server it reuses that was started by hand without `--forward-ports` gives forwarded pages random ports, which a firewall blocks; `share` then says how to restart it with the range. + +The network server speaks HTTPS with a self-signed certificate it makes on first run; the app pins its fingerprint and, with the short code, checks a pairing proof before sending the code (see [Security model](#security-model)). `--no-tls` serves plain HTTP instead, only for a network that encrypts by itself, such as a tailnet. Outside the local network, use the [relay](#4-reach-it-from-the-mac) or an SSH tunnel. + +### LAN discovery + +A server listening on a non-loopback address (`share`, or any `--listen` other than loopback) also binds UDP on `0.0.0.0:` and answers discovery queries. When that bind fails (the port is taken) the server logs `discovery off: …` and runs without it. + +- **Query** (client → broadcast): `{"t":"gentle-shell/discover","v":1}`, sent from one ephemeral UDP socket to `255.255.255.255` and to each interface's directed broadcast address, on ports 8787-8796 (the ports `share` tries). +- **Reply** (server → unicast to the query's source address and port): `{"t":"gentle-shell/here","v":1,"id":"","n":"","p":}`. + +Anything else is ignored: datagrams over 512 bytes, other JSON, other `t` or `v`. Replies are rate-limited (20 per second overall, 4 per second per source address). They carry no secrets. + +The client collects replies for about 1.5 s and, for each distinct one, checks `GET http://:

/.well-known/gentle-shell` names the same `serverId`. With a short code it then pairs with `POST /api/pair { code, name }` at the only server verified, lets the person pick one (name and IP) when several answered, and when none did asks them to check that both computers are on the same Wi-Fi and the firewall allows the port (`sudo ufw allow 8787` opens TCP and UDP), or to paste the long code instead. The pairing code is never sent to an address whose identity did not match. + +### Connection code + +The fallback for when discovery cannot reach the server: `gsc1.` followed by the base64url (no padding) of one JSON object: + +```json +{"v":1,"id":"srv_…","n":"linux-box","p":8787,"a":["192.168.1.20","100.101.102.103","linux-box","linux-box.local"],"c":"ABCD-EFGH"} +``` + +| Key | Value | +| --- | --- | +| `v` | `1` | +| `id` | The server's `serverId`. | +| `n` | The server machine's hostname, for display. | +| `p` | The port. | +| `a` | Addresses to try, best first, at most 8: the machine's IPv4 addresses except loopback and link-local (`169.254.x.x`) — private LAN ranges first, then others such as a tailnet's, then container and VM bridges (`docker0`, `virbr0`, …) — then its hostname and `.local`. | +| `c` | The pairing code. | + +The client probes `GET http://

:

/.well-known/gentle-shell` at every address in parallel (about 1.5 s each), keeps the first whose `serverId` equals `id`, pairs there with `POST /api/pair { code: c, name }`, and keeps that address as the server URL. It never sends the pairing code to an address whose identity did not match. The code is a secret while its pairing code is valid (5 minutes, single use); afterwards it only names the server and its addresses. + +### Start at login + +`serve share --always` hands the network server to the login service manager, so it starts at every login and restarts after a crash. The service runs the same launcher, the same home flags and the same `--listen`/`--allow-host` as `share` would, with `PATH` and the `GENTLE_SHELL_NO_AUTO_SETUP`, `GENTLE_SHELL_HOME`, `GENTLE_SHELL_CONFIG`, `GENTLE_PI_CONFIG_HOME`, `GENTLE_SHELL_PI` and `PI_CODING_AGENT_DIR` values of the invocation (when set), so a source checkout works too. + +| System | What it writes and runs | +| --- | --- | +| Linux | `~/.config/systemd/user/gentle-shell-serve.service` (`$XDG_CONFIG_HOME` when set), then `systemctl --user daemon-reload` and `systemctl --user enable --now gentle-shell-serve.service`. Output goes to the journal (`journalctl --user -u gentle-shell-serve`). A user unit runs while you are logged in; `sudo loginctl enable-linger $USER` starts it at boot and keeps it after logout (`share` prints this). | +| macOS | `~/Library/LaunchAgents/com.gentle-shell.serve.plist`, then `launchctl bootstrap gui/$UID` on it. Output goes to `/serve/server.log`. | +| Windows | Not supported yet: `--always` exits 1 before starting anything. | + +A server already running is replaced by the service only when it has no running sessions (otherwise `--always` exits 1 and leaves it alone); one the service already runs is reused. `serve share --off` disables and removes the unit (`systemctl --user disable --now`) or boots out and removes the agent, which stops the server it ran. One autostart per user: `--always` from another home replaces it. + +The systemd unit uses `KillMode=process`, so stopping or restarting the service ends only the server: session keepers and the terminal host it started keep running and the next server reattaches them (units written before this are rewritten by running `serve share --always` again). launchd ends only the server's own process group, and keepers have their own. Either manager starts the server again after an [upgrade from a client](#upgrade-from-a-client). + +## Files + +Everything lives in `/serve/`, a `0700` folder: + +| File | Content | +| --- | --- | +| `server.json` (`0600`) | `{ schema: "gentle-shell.serve.server/v1", protocol, serverId, url, listen, pid, startedAt, version, adminToken, discovery, forwardPorts? }`. Local clients discover the server here (`discovery`: whether it answers [LAN discovery](#lan-discovery); `forwardPorts`: `{ from, to }` when started with `--forward-ports`). Removed when the server stops. | +| `server-id` (`0600`) | The server's `serverId` (`srv_` and 16 hex digits), minted on the first run and kept: the id in `server.json`, `/.well-known/gentle-shell`, `GET /api/server`, discovery replies and connection codes stays the same across restarts and upgrades. Delete it to give the server a new identity. | +| `server.lock` (`0600`) | The pid holding the single-instance lock. A lock whose pid is gone is taken over. | +| `devices.json` (`0600`) | Paired devices: id, name, scopes, created and last-used times, and the **sha256 of the token** — never the token. | +| `server.log` (`0600`) | Background server log: lifecycle lines and each session's stderr while the server is attached, prefixed by session id. | +| `sessions/` (`0700`) | One [keeper](#sessions-across-server-restarts) per session: `.json` (`0600`) is its record (`{ schema: "gentle-shell.serve.session/v1", id, cwd, startedAt, keeperPid, pid, token, state, exitCode, exitSignal, exitedAt, seq, error? }`), kept after the session exits so the next server lists it, removed when the session is deleted or forgotten; `.sock` (`0600`) is the keeper's socket while it runs. | +| `uploads///` (`0700` folders, `0600` files) | [Uploads](#uploads) from devices; each removed 7 days after it arrived. | +| `term.sock` (`0600`) | The [terminal host](#persistent-terminals)'s Unix socket, while it runs (not on Windows). | +| `term/` (`0700`) | The terminal host's state folder: its log, `term-host.log`; over TCP (Windows) also `term-host.json` (`0600`; on Windows a DACL for its owner only): `{ port, token, pid }`. | +| `terminals.json` (`0600`) | Which device opened each terminal: `{ schema: "gentle-shell.serve.terminals/v1", owners: { : } }`. Terminals outlive the server, so their owners are kept on disk. | +| `bin/gentle-term-host` (`0755`) | A terminal host installed with `PUT /api/term-host`. | + +`adminToken` is a fresh random token per server run. It is how `serve status`, `pair`, `devices` and `stop` talk to the server, so anyone who can read `server.json` (the owner) administers it. + +## Process model + +Each session is a Pi process run by this same launcher (`node bin/gentle-shell.mjs --mode rpc [--session-id ]`, in the requested folder), so Pi is resolved exactly as a plain launch resolves it, with `GENTLE_SHELL_INTERACTIVE_HOST=1` (Desktop RPC and RPC dialogs on, as for Gentle Desktop) and `GENTLE_DESIGN_OPEN_BROWSER=0` (never a browser on the server machine). It is not the server's child: a small detached Node process, the session's **keeper**, starts it and owns its stdin and stdout, so the session outlives the server. + +- The keeper reads Pi's stdout continuously, whoever is listening, numbers each record (`seq`), keeps the replay ring, the dialogs waiting for an answer and the host tool calls still open, and keeps Pi's stdin open for its whole life (closing it is Pi's shutdown request). The server is a client of the keeper and holds a copy of that state, which it serves to devices. +- A session ends only when it is deleted (`DELETE /api/sessions/:id`), when the server stops with `--sessions` (`POST /api/server/stop { endSessions: true }`), when Pi exits on its own, or when no server came back to it for 24 hours. Its exit is a record in its stream (`serve_session_exited`) and a state in the list. Up to 16 exited sessions stay listed (with their replay ring while this server holds it) until deleted. +- Stopping closes stdin and sends SIGTERM together (Pi treats them as one orderly shutdown request), then SIGKILL after 5 s; then the keeper exits. +- At most 16 sessions run at once. + +### Sessions across server restarts + +Stopping the server (`serve stop`, SIGTERM from a service manager, Ctrl+C on a foreground server) closes its connections to the keepers and leaves the sessions running. The next server — the same version or an upgrade — scans `/serve/sessions/` and reattaches every keeper that answers before it serves requests. The [control session](#desktop-rpc-without-a-session-post-apidesktop) is the exception: it ends with its server. + +- **Same ids, same `seq`.** A session keeps its id, and its `seq` continues where it was: what Pi printed while no server ran is in the keeper's replay ring. A client reconnects to `GET /api/sessions/:id/events?after=` and gets exactly what it missed (or `snapshot-required` if the ring moved past it). `GET /api/server` lists the capability `persistent-sessions`. +- **Dialogs and host tool calls** still waiting are kept and re-sent to subscribers as before. The devices that registered host tools and which device drove the session last are kept with the keeper too; device streams are not, so a device owing a host tool call has 30 s after the restart to reconnect before the server answers the call for it ("isn't connected right now"). +- **A session that ended meanwhile** is listed as exited with its exit code (from its record). A keeper whose Pi exited while no server ran waits 60 s for a server to collect the end of its stream, then exits. A keeper that is gone without recording an exit (killed, a reboot) is listed with `exitCode: null` and `error: "keeper_lost"` in its record; a server attached to it when that happens adds `serve_session_exited` with `"error":"keeper_lost"` to the stream. +- **Orphans.** A keeper with no server attached for 24 hours stops its session. +- **Security.** Each keeper listens on an owner-only Unix socket `/serve/sessions/.sock` (`0600`, in a `0700` folder; on Windows the named pipe `\\.\pipe\gentle-shell-serve--`) and answers only a connection that first presents the session's random token from its record file (`0600`); one server at a time (a new one takes over). +- **What a restart loses:** requests in flight (they fail) and open event streams (clients reconnect with their last `id`); in-memory state of the old server such as forwards and Tower; the control session (the next server starts its own on first use). A server started without a serve folder (only in tests) keeps its keepers in a private temporary folder and stops them when it stops. + +## Protocol + +`gentle-shell.serve/v1`, protocol `1`. JSON over HTTP for requests; SSE for each session's output. All errors are `{ "error": { "code", "message" } }`. + +### Endpoints + +| Method and path | Scope | Body → answer | +| --- | --- | --- | +| `GET /.well-known/gentle-shell` | none | `{ schema: "gentle-shell.serve.identity/v1", serverId, name, protocol, version }`: who answers at this address (`name` is the machine's hostname). No secrets; `Host` and `Origin` rules still apply. A client holding a [connection code](#connection-code) probes it before pairing. | +| `POST /api/pair` | none (the code) | `{ code, name? }` → `201 { id, name, scopes, createdAt, token }`. `403 invalid_code`, `429 rate_limited`, `409 too_many_devices`. | +| `GET /api/server` | `sessions:read` | `{ schema, protocol, serverId, version, startedAt, capabilities, device, platform, arch, pathSeparator, home? }`. `capabilities` includes `desktop` ([Desktop RPC without a session](#desktop-rpc-without-a-session-post-apidesktop)), `forwards`, `server-forwards`, `services`, `tower`, `files`, `git`, `checks` ([readiness checks](#readiness-checks)), `uploads`, `print` ([one-shot prompts](#one-shot-prompts)), `persistent-sessions` ([sessions survive a server restart](#sessions-across-server-restarts)), `upgrade` ([upgrade from a client](#upgrade-from-a-client)), `setup` ([setup from a client](#setup-from-a-client)), `unpair` (a device can revoke itself: `DELETE /api/devices/self`), and `terminals` when a [terminal host](#persistent-terminals) binary is there. `platform` and `arch` are Node's `process.platform` and `os.arch()` of the server (`darwin`/`linux`/`win32`, `arm64`/`x64`), `pathSeparator` its path separator (`/` or `\`), so a client builds server paths without guessing. `home` is the absolute home folder of the user the server runs as (a default folder for new sessions), only for a token with `sessions:operate`. No configuration file path is reported: a client reads and changes Gentle Shell's and Pi's configuration (model defaults, custom models, MCP servers, …) through Desktop RPC config stores ([`get_config`/`set_config`](desktop-rpc.md#set_config)), never the files. | +| `POST /api/server/stop` | `admin` | `{ endSessions? }` → `202 { stopping: true, endSessions }`; the server exits. Its sessions keep running for the next server unless `endSessions` is `true`. | +| `POST /api/upgrade` | `admin` | `{ channel? }` (`release` or `main`) → `202 { jobId }`: runs `gentle-shell upgrade` on this machine. `409 upgrade_running` while one runs. See [Upgrade from a client](#upgrade-from-a-client). | +| `POST /api/setup` | `admin` | `{}` → `202 { jobId }` (`setup_…`): runs `gentle-shell setup` for this server's home. `409 setup_running` or `upgrade_running` while a job runs. See [Setup from a client](#setup-from-a-client). | +| `GET /api/setup/:jobId/stream` | `admin` | SSE as the upgrade stream: `line` `{ line }`, then `finished` `{ ok, error? }`. `404` for another job id. | +| `GET /api/checks` | `sessions:read` | `{ checks: [{ id, state, version, detail }] }`: whether Node.js, the companion setup, Git and Engram are ready on this machine. See [Readiness checks](#readiness-checks). | +| `GET /api/upgrade/:jobId/stream` | `admin` | SSE: `line` `{ line }` for each output line (those so far first), then `finished` `{ ok, error?, version? }`, then the stream ends. `404` for another job id. | +| `POST /api/pairing-codes` | `admin` | `{ scopes? }` → `201 { code, scopes, expiresAt }` | +| `GET /api/devices` | `admin` | `{ devices: [{ id, name, scopes, createdAt, lastUsedAt? }] }` | +| `DELETE /api/devices/:id` | `admin` | `{ revoked }`. Immediate: the token stops working, its tickets die, its open streams close. | +| `DELETE /api/devices/self` | any paired device | `{ revoked }`: the calling device unpairs itself (capability `unpair`), revoked as above. `400 not_a_device` for the server's own token. | +| `POST /api/devices/self/replace` | any paired device | `{ token }` (an earlier pairing's token) → `{ replaced }`: a device paired again takes the place of its earlier pairing (capability `unpair`): that device's [terminals](#persistent-terminals) become the caller's, then it is revoked. `404` when no paired device has that token, `400 same_device` for the caller's own. | +| `POST /api/tickets` | `sessions:read` | `{ sessionId }`, or `{ stream: "desktop" }` for `GET /api/desktop/events` → `201 { ticket, expiresAt }` (see [Stream tickets](#stream-tickets)). | +| `GET /api/sessions` | `sessions:read` | `{ sessions: [Session] }`. The [control session](#desktop-rpc-without-a-session-post-apidesktop) is never listed, except with `?includeControl=1` for an `admin` token (then with `control: true`). | +| `POST /api/sessions` | `sessions:operate` | `{ cwd, sessionId? }` → `201 { session }`. `cwd` must be an absolute path to an existing folder; `sessionId` is a Pi session id (`--session-id `: the folder's session with that exact id, or a new one with it when Pi never wrote it, as for a conversation with no messages yet), never a path. `503 session_start_failed` when its keeper could not start. | +| `GET /api/sessions/:id` | `sessions:read` | `{ session }` | +| `DELETE /api/sessions/:id` | `sessions:operate` | Stops the session (waits for its exit) and forgets it: `{ session }`. | +| `POST /api/sessions/:id/rpc` | per command | One Pi RPC command object → its Pi `response`. | +| `POST /api/sessions/:id/desktop` | per method | `{ method, params? }` → the Desktop RPC response object. | +| `GET /api/sessions/:id/events?after=` | `sessions:read` | SSE stream (bearer header, or `?ticket=`). | +| `POST /api/desktop` | per method | `{ method, params? }` → the Desktop RPC response object, from the server's control session: [Desktop RPC without a session](#desktop-rpc-without-a-session-post-apidesktop). | +| `GET /api/desktop/events?after=` | `sessions:read` | SSE stream of the control session's Desktop RPC events (bearer header, or `?ticket=`). | +| `POST /api/sessions/:id/forwards` | `sessions:operate` | `{ port, path? }` → `201 Forward & { url, expiresAt }` (`200` when the device already had it). See [Port forwarding](#port-forwarding). | +| `GET /api/sessions/:id/forwards` | `sessions:read` | `{ forwards: [Forward] }`: the calling device's forwards for the session (an admin token sees every device's). | +| `DELETE /api/sessions/:id/forwards/:fid` | `sessions:operate` | `{ closed }`. Only the device's own (`404` otherwise). | +| `POST /api/forwards` | `sessions:operate` | `{ port, path? }` → `201 Forward & { url, expiresAt }` (`200` when the device already had it): a [server-level forward](#server-level-forwards-and-services), not tied to a session. | +| `GET /api/forwards` | `sessions:read` | `{ forwards: [Forward] }`: every forward the calling device owns, of any kind (an admin token sees every device's). | +| `DELETE /api/forwards/:fid` | `sessions:operate` | `{ closed }`. Any of the device's own forwards (`404` otherwise). | +| `GET /api/services` | `sessions:read` | `{ services: [Service] }`: local services worth forwarding. See [Server-level forwards and services](#server-level-forwards-and-services). | +| `GET /api/terminals` | `terminal` | `{ terminals: [Terminal] }`. See [Persistent terminals](#persistent-terminals). | +| `POST /api/terminals` | `terminal` | `{ cwd, cols, rows, argv?, env? }` → `201 { terminal }` | +| `POST /api/terminals/:t/input` | `terminal` | `{ data }` (base64) → `{ ok }` | +| `POST /api/terminals/:t/resize` | `terminal` | `{ cols, rows }` → `{ ok }` | +| `DELETE /api/terminals/:t` | `terminal` | `{ closed }` | +| `GET /api/terminals/:t/stream?from=` | `terminal` | SSE: `attached`, then `output`, `title`, `resized`, `exit`. | +| `GET /api/term-host` | `terminal` | `{ available, running, path?, version?, pid?, protocol?, platform, arch, asset, transport }` | +| `PUT /api/term-host` | `admin` | Raw binary, header `x-sha256` → `201 { path, sha256, size, active }` | +| `POST /api/tower` | `sessions:operate` | → `201 Forward & { url, expiresAt, started }` (`200` when the device already had a forward to Tower). Starts [Gentle Tower](#gentle-tower) when it is not running and forwards it. `501 not_supported` when this server cannot start Tower, `503 tower_unavailable` when it failed to. | +| `GET /api/tower` | `sessions:read` | `{ running: false }` or `{ running: true, startedAt }`. | +| `DELETE /api/tower` | `sessions:operate` | `{ stopped }`. Stops Tower and closes its forwards. | +| `GET /api/fs/list?path=` | `sessions:read` | `{ path, entries: [Entry], truncated }`. See [Files on the server](#files-on-the-server). | +| `GET /api/fs/stat?path=` | `sessions:read` | `Entry & { path, mode, etag?, linkTarget?, realPath? }` | +| `GET /api/fs/read?path=&offset=&length=` | `sessions:operate` | The file's raw bytes. | +| `PUT /api/fs/write?path=[&create_only=1]` | `sessions:operate` | Raw body → `{ path, size, mtime, etag, created }`. | +| `POST /api/fs/mkdir` | `sessions:operate` | `{ path }` → `{ path, created }` | +| `POST /api/fs/rename` | `sessions:operate` | `{ from, to, overwrite? }` → `{ from, to }` | +| `POST /api/fs/remove` | `sessions:operate` | `{ path, recursive? }` → `{ removed }` | +| `GET /api/fs/search?root=&q=&limit=` | `sessions:read` | `{ root, results: [{ path, name, kind, score }], truncated }` | +| `GET /api/fs/watch?path=` | `sessions:read` | SSE stream of change batches. | +| `POST /api/git` | per command | `{ cwd, args, stdin?, env?, timeoutMs? }` → `{ code, signal, stdout, stderr, truncated, timedOut }`. See [git on the server](#git-on-the-server). | +| `POST /api/print` | `sessions:operate` | `{ cwd, prompt, model? }` → `{ text }`. See [One-shot prompts](#one-shot-prompts). | +| `POST /api/uploads?name=` | `sessions:operate` | Raw body → `201 { path, name, size, sha256, expiresAt }`. See [Uploads](#uploads). | + +`Session` is `{ id, name, cwd?, state: "running"|"exited", startedAt, exitedAt?, exitCode?, exitSignal?, seq, subscribers, pendingDialogs, lastActiveDevice }`. `name` is the folder's basename; the absolute `cwd` is included only for a token with `sessions:operate` (which can start sessions in any folder anyway). `lastActiveDevice` is the id of the device that most recently drove the session (started it, or sent any request that needs `sessions:operate`: a prompt, a steer, a follow-up, a dialog answer, a host message, a Desktop write), or `null`. + +### Pi RPC: `POST /api/sessions/:id/rpc` + +The body is one [Pi RPC command](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/rpc-commands.md) (`{ "type": "get_state" }`, `{ "type": "prompt", "message": "…" }`, …). Several clients can share a session, so the server sends it under its own id (`serve-rpc--N`, unique per server run) and puts the client's `id` back on the response it returns. The same response also appears in the event stream, under the server's id. + +- The server waits up to 30 s for the response. A command that takes longer (a long `bash`, `compact`) answers `202 { pending: true, id }`, and its response arrives in the stream under that `id`. +- `extension_ui_response` is the answer to a dialog: see [Dialogs](#dialogs). It answers `202 { accepted: true }`. +- Bodies are limited to 8 MiB (prompts can carry images). +- A `/gentle:desktop` prompt whose request is `set_host_tools`, `host_tool_result`, `host_tool_progress`, `host_message` or `set_host_context` is refused with `400 use_desktop_endpoint`: those go through `/desktop` only (see [Host tools](#host-tools)). + +### Desktop RPC: `POST /api/sessions/:id/desktop` + +A convenience over the existing [Desktop RPC](desktop-rpc.md) transport: the server sends the `/gentle:desktop` prompt with its own `requestId`, waits for the matching `gentle-desktop-rpc` widget answer, and returns it (`{ schema, kind: "response", requestId, ok, data | error }`; `requestId` is the server's, and any `schema` or `requestId` in the body is ignored). `504 desktop_timeout` after 30 s; `502 desktop_refused` (with Pi's prompt response) when the session refused the prompt. Bodies are limited to 80 KiB (Desktop RPC requests are limited to 64 KiB), except `set_host_tools`, `host_tool_result`, `host_message` and `set_host_context`, which may be up to 10 MiB less 1 KiB (a result can carry 8 MiB of screenshots and 1 MiB of details; the session caps each method at its own limit). Desktop RPC events keep arriving in the event stream as `setWidget` records, exactly as Desktop sees them. Sending `/gentle:desktop` prompts through `/rpc` also works for every other method; this endpoint only adds the correlation. + +The same endpoint signs the server in to providers and manages its packages, so a client never has to say "do this on the server": [`login_start`](desktop-rpc.md#login_start) / [`login_complete`](desktop-rpc.md#login_complete) / [`login_cancel`](desktop-rpc.md#login_cancel) run Pi's own sign-in with its prompts as [`login_prompt`](desktop-rpc.md#login_prompt) events (a browser sign-in's loopback redirect is intercepted by the client and handed over as the full URL), [`set_api_key`](desktop-rpc.md#set_api_key) and [`remove_credentials`](desktop-rpc.md#remove_credentials) save and remove keys, and [`install_package`](desktop-rpc.md#install_package) / [`remove_package`](desktop-rpc.md#remove_package) run the CLI as a job with [`package_progress`](desktop-rpc.md#package_progress) lines. Those need `sessions:operate`; [`list_packages`](desktop-rpc.md#list_packages), [`get_auth_status`](desktop-rpc.md#get_auth_status) (with each provider's `loginKinds`) and [`list_available_models`](desktop-rpc.md#list_available_models) (the models the server can use, for a model picker) need `sessions:read`. Credentials are stored in the server's agent home, for every session of this server. A client with no session of its own sends all of these to [`/api/desktop`](#desktop-rpc-without-a-session-post-apidesktop) instead. + +### Desktop RPC without a session: `POST /api/desktop` + +Configuration, sign-in and packages are the server's, not a conversation's, so a client reaches them without opening an agent session of its own (a phone, a web page, curl, the app's Configuration screen). `GET /api/server` lists the capability `desktop`. + +- **`POST /api/desktop { method, params? }`** works as [`/desktop`](#desktop-rpc-post-apisessionsiddesktop): the same answers (`{ schema, kind: "response", requestId, ok, data | error }`), the same scope per method (`capabilities`, `get_*` and `list_*` need `sessions:read`, every other method `sessions:operate`), `504 desktop_timeout` after 30 s and `502 desktop_refused`. Bodies are limited to 80 KiB. The host tool methods (`set_host_tools`, `host_tool_result`, `host_tool_progress`, `host_message`, `set_host_context`, `set_host_activity`) are refused with `400 use_session_desktop`: host tools belong to the agent session whose model calls them. +- **`GET /api/desktop/events`** follows the Desktop RPC events of the same session — [`login_prompt`](desktop-rpc.md#login_prompt), [`login_finished`](desktop-rpc.md#login_finished), [`package_progress`](desktop-rpc.md#package_progress), [`package_finished`](desktop-rpc.md#package_finished), [`config_changed`](desktop-rpc.md#config_changed), … — and nothing else of its stream (no Pi responses, no Desktop answers, no dialogs). The rules are a session stream's: `hello` first, each record with `id: ` and the `setWidget` record unchanged as `data` (whose Desktop event carries its own `epoch` and `seq`), `?after=` or `Last-Event-ID` to resume (`snapshot-required` when the ring moved past it, or the control session was started again), `resync` for a slow client, `: ping` every 20 s, and a [stream ticket](#stream-tickets) minted with `{ stream: "desktop" }` instead of the bearer header. +- **The control session** answers both: a session like any other (the same launcher, Pi and extensions, Desktop RPC on), started in the server user's home folder on the first request or stream, never given a prompt other than Desktop RPC (no model turn), not listed in `GET /api/sessions` (except `?includeControl=1` for `admin`), not reachable by id, and not counted against the 16 running sessions. It runs while requests or open event streams use it and stops after 10 minutes without either; the next use starts it again. Unlike the other sessions it does not outlive its server: it holds no user state and must run the server's own code (after a `git pull`, a reinstall or an [upgrade](#upgrade-from-a-client), a control session the old server started would still answer with the old one), so stopping the server stops it, and one an earlier server left running under its keeper (`/serve/sessions/control` names it: a crash, or a server from before this rule) is stopped at start, never taken back. A Desktop RPC job running in it (a login, a package install) ends with it; event streams get `snapshot-required` from the new one. + +A session's own `/desktop` stays the way to ask a session about itself (its permission mode, jobs, subagents, changes) and to register host tools. + +### Host tools + +A client can provide [host tools](desktop-rpc.md#set_host_tools): tools the agent calls like any other but that run on the client's own device (a screenshot of the Mac, a photo from the phone). The agent runs here; the tool runs there. The server routes the calls: + +- **The provider is the device.** `set_host_tools` and `set_host_context` through `/desktop` always register under the calling device's id (`provider` in the body is replaced), and need `sessions:operate`. The same requests through `/rpc` are refused, so no client can register tools or context as another device. +- **Messages.** [`host_message`](desktop-rpc.md#host_message) (a client's custom message into the conversation) goes through `/desktop` only too, with `sessions:operate`. [`set_host_context`](desktop-rpc.md#set_host_context) keeps one hidden context per device, added before each agent run until the device clears it or the session changes. +- **Only the provider answers.** A `host_tool_result` or `host_tool_progress` for a call whose `provider` is another device is refused with `403 forbidden`. The server remembers each call it saw in the session's output until a result settles it, a `host_tool_cancel` ends it, or 11 minutes pass since the call or its last accepted `host_tool_progress`. +- **One tool, several devices.** Devices may offer the same tool name (the Mac and the phone both offer `device_screenshot`). A call goes to the device that most recently drove the session (`lastActiveDevice`) if it offers the tool and has an open event stream; otherwise to the next most recently active one that does; when none does, it is answered at once as not connected. The server keeps the session told with [`set_host_activity`](desktop-rpc.md#set_host_activity) (connected providers, most recently active first) whenever that order changes; clients cannot send it (`403` through `/desktop`, `use_desktop_endpoint` through `/rpc`). +- **Delivery.** The `host_tool_call` event reaches every subscriber like any Desktop RPC event (`data.provider` says which device runs it; the others ignore it). A device that opens a stream while one of its calls is still waiting, and whose replay does not carry it, also gets it as an SSE event `event: host_tool_call` whose `data` is the original `setWidget` record. +- **Offline device: an answer at once.** If the call's device has no open event stream when the call appears, the server answers for it right away with an error result the model reads — ` runs in , which isn't connected right now.` — instead of letting the turn wait. If a device's last stream closes while it owes results, the server waits 10 s for it to reconnect, then answers its waiting calls the same way. Revoking a device answers its calls at once. +- **Time limit.** The session itself ends a call after 10 minutes without a result, with an error result and a `host_tool_cancel`. A device still working on a call sends [`host_tool_progress`](desktop-rpc.md#host_tool_progress) through `/desktop` every 60 s (`sessions:operate`; a body up to 80 KiB like other Desktop requests); each one restarts the 10 minutes. A heartbeat is not activity: it does not change `lastActiveDevice` or which device gets the next call. + +The server never runs client code: a host tool's work happens on the client, with the client's authority, and only its result comes back into the conversation. + +### Event stream: `GET /api/sessions/:id/events` + +Every record the child prints — Pi responses, session events, extension UI requests (including Desktop RPC answers and events) — gets the session's next `seq`, starting at 1. Each one is an SSE message with `id: ` and the record, unchanged, as `data`: + +```text +retry: 3000 + +event: hello +data: {"session":"ses_…","state":"running","seq":13,"oldest":1} + +id: 1 +data: {"type":"extension_ui_request","id":"…","method":"setStatus",…} + +id: 2 +data: {"type":"response","id":"serve-rpc-3f9a1c07-1","command":"get_state","success":true,"data":{…}} + +: ping +``` + +Other SSE events, which carry no `id` (so they never move a client's cursor): + +| Event | When | +| --- | --- | +| `hello` | First, on every connection: the session's state, current `seq` and oldest replayable `seq`. | +| `snapshot-required` | `after` is older than the replay ring (records the client never saw were evicted) or newer than the stream (a cursor from another session). `{ after, oldest, seq }`. The client recovers state with Pi `get_state` / `get_messages` and Desktop RPC `get_snapshot`, then follows the live stream that continues on the same connection. | +| `dialog` | A dialog still waiting for an answer that this connection's replay did not carry. `data` is the original `extension_ui_request`. | +| `host_tool_call` | To the device that provides it only: a host tool call still waiting for that device's result that this connection's replay did not carry. `data` is the original `setWidget` record. | +| `resync` | Sent as the stream is closed for falling behind: `{ reason: "slow_client", seq }`. Reconnect with the last `id` seen. | + +The server also adds its own records to the stream (they have a `seq` like any other): + +| Record | Meaning | +| --- | --- | +| `{"type":"serve_dialog_resolved","id"}` | A client answered this dialog; other clients can close it. | +| `{"type":"serve_session_exited","code","signal","error"?}` | Pi exited (`error`: `spawn_failed` when it could not start, `keeper_lost` when its keeper went away). The stream ends after it. | +| `{"type":"serve_record_dropped","reason":"too_large","maxBytes"}` | A stdout record over 16 MiB was dropped. | + +`after` comes from the query, or from the `Last-Event-ID` header that `EventSource` sends on reconnect. Without it the stream starts live (plus the pending dialogs and the device's waiting host tool calls). An exited session replays and then ends the stream. + +A comment line (`: ping`) is sent every 20 s so proxies do not close idle streams. + +#### Replay and resume + +Each session keeps a replay ring of its newest records: 2000 records or 8 MiB, whichever is reached first (the newest record is always kept). `after` inside the ring replays exactly what was missed; outside it the client gets `snapshot-required`. Sequence numbers belong to the session for its whole life, across [server restarts](#sessions-across-server-restarts). + +#### Dialogs + +`select`, `confirm`, `input` and `editor` requests stay pending until answered, until their own `timeout` passes, or until the session exits. A subscriber that connects later gets them as `dialog` events. Answer one with `POST /rpc` `{ "type": "extension_ui_response", "id": "", … }`: only the first answer reaches Pi; a later one gets `409 dialog_answered`, an unknown id `404 unknown_dialog`. The server then adds `serve_dialog_resolved` to the stream. + +#### Backpressure + +A slow client never slows a session. Pi's stdout is always read; each subscriber's unsent bytes are bounded (4 MiB). A subscriber over that bound is dropped: its stream ends with a `resync` event (and is cut 5 s later if it still is not reading), and it reconnects with its last `id`. Commands are refused with `503 session_busy` if Pi stops reading its stdin and 16 MiB pile up there. + +#### Framing + +Pi's stdout is split on LF only, with an optional CR before it stripped, never on U+2028/U+2029 (which are valid inside JSON strings, and which Node's `readline` would split on). A line that is not a JSON object is not forwarded, nor is a record whose `type` starts with `serve_` (those are the server side's own). Commands are written as one JSON object plus LF. + +## Upgrade from a client + +An `admin` client (the local admin token, or a device paired with `--scope …,admin`) upgrades Gentle Shell on the server without a terminal there. `GET /api/server` lists the capability `upgrade`. + +```sh +curl -X POST http://127.0.0.1:PORT/api/upgrade -H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' -d '{"channel":"release"}' +# → 202 {"jobId":"upg_…"} +curl -N http://127.0.0.1:PORT/api/upgrade/upg_…/stream -H "Authorization: Bearer $ADMIN" +``` + +```text +event: line +data: {"line":"Checking the release channel"} + +event: finished +data: {"ok":true,"version":"5.1.0"} +``` + +- **What runs.** The server's own launcher runs `gentle-shell upgrade [--channel release|main]` (the command a person types, with its channel record, npm/pnpm or bundled install handling and checks), in the user's home folder, with stdin closed and color off. `channel` is optional; without it the recorded channel is followed. Output lines become `line` events (color codes removed, each at most 2000 characters; the last 2000 are kept for a stream that connects late). `finished` carries `ok`, and `error` (the command's last line on stderr, at most 300 characters) or `version` (the installed package's version, when it can be read). An upgrade still running after 30 minutes is stopped. One at a time: another `POST` answers `409 upgrade_running`; a finished one does not block the next. +- **The restart.** About half a second after a successful `finished`, the server stops as `serve stop` does (connections close, sessions keep running under their keepers, the control session stops, the terminal host keeps running) and comes back on the new version on the same address, with the same server id and paired devices: a server started by `serve` or `serve --foreground` starts its replacement itself (`serve --foreground` with the same `--listen`, `--allow-host`, `--forward-ports`, `--no-tls` and `--relay`, detached, logging to `server.log`); a server run by `serve share --always` exits with status 75 and its service manager starts the upgraded one (systemd's `Restart=on-failure`, launchd's `KeepAlive`). The replacement runs the launcher of the installed version: the same path for an npm or pnpm install, the one `current` names for a bundled install. Its control session is a fresh one on the new version. +- **Clients.** Requests in flight fail and streams close, as on any [restart](#sessions-across-server-restarts); a client reconnects with its last event id and reads `GET /api/server` for the new `version`. A failed upgrade changes nothing and the server keeps running. + +## Setup from a client + +An `admin` client runs Gentle Shell's own setup for the server's agent home — the companion packages `gentle-shell setup` installs there — without a terminal on the server. `GET /api/server` lists the capability `setup`. + +```sh +curl -X POST http://127.0.0.1:PORT/api/setup -H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' -d '{}' +# → 202 {"jobId":"setup_…"} +curl -N http://127.0.0.1:PORT/api/setup/setup_…/stream -H "Authorization: Bearer $ADMIN" +``` + +- **What runs.** The server's own launcher runs `gentle-shell [home selector] setup` — the same home selector the server runs with — in the user's home folder, with stdin closed and color off. The body takes no options (`400` otherwise). Output, `finished` (`ok`, `error`; no `version`), the 30-minute limit and late-connecting streams work as for the upgrade. +- **One job at a time.** Setup and upgrade share one runner: while either runs, `POST /api/setup` and `POST /api/upgrade` answer `409` with `setup_running` or `upgrade_running` (whichever job is running). +- **No restart.** Setup installs packages into the agent home and never replaces the launcher, so the server keeps running; sessions started afterwards load the new packages, and running ones after `/reload`. + +## Readiness checks + +`GET /api/checks` (`sessions:read`) says whether this machine has what its sessions need: the same four rows, by the same rules, as Gentle Shell GPUI's setup checklist shows for the computer it runs on, so a client shows a server's setup the way it shows its own. `GET /api/server` lists the capability `checks`. + +```sh +curl http://127.0.0.1:PORT/api/checks -H "Authorization: Bearer $TOKEN" +# → {"checks":[{"id":"node","state":"ok","version":"22.19.0","detail":"npm 10.9.0"}, +# {"id":"companion","state":"ok","version":"1.40.2","detail":"Set up 2026-11-20"}, +# {"id":"git","state":"ok","version":"2.47.1","detail":null}, +# {"id":"engram","state":"missing","version":null,"detail":"Not installed"}]} +``` + +Each row is `{ id, state, version, detail }`: `state` is `ok`, `missing` or `error`; `version` is what was found (`X.Y.Z`, or `null`); `detail` says why in words (or `null`). A tool that is there but too old is an `error` whose `detail` names what it needs. + +| `id` | `ok` | `missing` | `error` | +| --- | --- | --- | --- | +| `node` | `node --version` is 22.19.0 or newer (gentle-pi's `engines.node`) and `npm --version` answers (`detail`: `npm `) | no `node` on the server's `PATH`; or Node found, but not npm (`version` set) | older than 22.19.0; `node` doesn't run or prints something else | +| `companion` | the launcher's own `gentle-shell [home selector] setup --check --json` says the home is set up (`version`: the Gentle AI it was set up with; `detail`: `Set up `); a `--link` home whose `settings.json` lists `gentle-engram` | never set up (a `--link` home that doesn't list it) | set up with another Gentle AI or gentle-pi (run [setup](#setup-from-a-client)); the check fails or can't run | +| `git` | `git --version` answers | no `git`, or it doesn't run; on macOS, `/usr/bin/git` while the Command Line Tools aren't installed (`xcode-select -p` fails) | — | +| `engram` | `engram version` answers 3.0.0 or newer (or a version it can't read; `detail`: its first line) | no `engram`, or it doesn't run | older than 3.0.0; `ENGRAM_BIN` names something that can't be run | + +- **How.** Every tool runs directly (no shell) with the server's environment, all at once, each stopped after 5 s (15 s for `setup --check`), which then counts as not running. `ENGRAM_BIN`, when set, is the Engram that runs. On Windows npm's `npm-cli.js` runs under `node`, since `npm.cmd` needs a shell. +- **Cached.** One result answers every request for 10 s, and is dropped when a [setup](#setup-from-a-client) or [upgrade](#upgrade-from-a-client) job ends (before its `finished` event), so a client that asks again then sees what the job changed. + +## Authentication + +There is no unauthenticated mode: every endpoint except `GET /.well-known/gentle-shell` (public identity, no secrets) and `POST /api/pair` needs a token. + +- **Pairing.** `gentle-shell serve pair` mints a code like `ABCD-EFGH` (40 random bits, Crockford base32; case, dashes and `O`/`I`/`L` look-alikes are forgiven). It is single use — the first attempt that names it consumes it — and expires after 5 minutes; at most 16 are live. Ten failed attempts in a minute, from anyone, pause pairing for the rest of that minute. +- **Device tokens.** `gss_` plus 32 random bytes (base64url). Shown once, in the pairing answer. Stored only as a sha256 hash; compared in constant time. Sent as `Authorization: Bearer `. At most 64 devices. +- **Scopes.** + - `sessions:read` — list and read sessions, follow their streams, mint stream tickets, read-only Pi RPC commands (`get_state`, `get_messages`, `get_available_models`, `get_available_thinking_levels`, `get_session_stats`, `get_fork_messages`, `get_entries`, `get_tree`, `get_last_assistant_text`, `get_commands`) and read-only Desktop RPC methods (`capabilities`, `get_*`, `list_*`). + - `sessions:operate` — start and stop sessions, every other Pi RPC command (prompts, steering, aborts, bash, model changes, `extension_ui_response`), and every other Desktop RPC method; [file](#files-on-the-server) contents and changes, [git](#git-on-the-server) commands that print file contents (`show`, patches, blobs, `blame`, `grep`) or change anything, [uploads](#uploads) and [forwards](#port-forwarding). (`sessions:read` also lists, stats, searches and watches files, runs git commands that print no file contents — status, branches, the log, changed paths and line counts — and reads the [readiness checks](#readiness-checks).) + - `terminal` — open, list, drive and close [persistent terminals](#persistent-terminals): a shell as the server user. In the default pairing scopes; `serve pair --scope sessions:read,sessions:operate` leaves it out. Devices paired before it existed do not have it: pair them again. + - `admin` — pairing codes, devices, stopping the server, installing the terminal host; sees every device's forwards and terminals. + + Authorization is checked per request (per command or method for `/rpc` and `/desktop`), never per connection. +- **Revocation** (`serve devices --revoke`, `DELETE /api/devices/:id`, or a device unpairing itself with `DELETE /api/devices/self`) takes effect at once: the token stops working, its stream tickets are discarded and its open streams are closed. +- **Local admin token.** The CLI uses the per-run token in the owner-only `server.json`; it has every scope. + +### Stream tickets + +Browsers' `EventSource` cannot send headers, and long-lived tokens never go in URLs. A client with a token calls `POST /api/tickets { sessionId }` and opens `GET /api/sessions/:id/events?ticket=` (or `POST /api/tickets { stream: "desktop" }` and `GET /api/desktop/events?ticket=`). A ticket is valid for 60 s, for one connection, to that one stream, with the scopes of the device that minted it. The events endpoints are the only ones that accept `?ticket=`. + +## Port forwarding + +A page that listens on the server's loopback — the design canvas (`127.0.0.1:`), a dev server the agent started (`127.0.0.1:5173`), Gentle Tower — cannot be opened from another machine. A forward opens it there, for one paired device, without opening the port itself to anyone. + +- **One listener per forward,** on the same address as the server (`--listen`): a loopback server makes loopback forwards (reach them through the same `ssh -L` tunnel, one per port), a network server makes network ones. Its own port, not a path prefix, so the page's absolute paths (`/assets/app.js`, `/@vite/client`) keep working. Ports come from `--forward-ports` when set (`share` uses 8800-8899), otherwise the OS picks one. +- **Only this machine's loopback.** A forward targets `127.0.0.1:`, or `[::1]:` when only IPv6 answers (a dev server bound to `localhost` on macOS). Never another host, never the server's own port or another forward's. +- **Per device, per session.** `POST /api/sessions/:id/forwards { port, path? }` opens one, or reuses the one the device already has for that session and port (a forward belongs to one session so that it closes with it; another device gets its own). Every call mints a fresh link. +- **Server-level forwards.** `POST /api/forwards { port, path? }` opens one that belongs to no session (`sessionId: null`, `kind: "server"`), for a page the server machine runs on its own — [Engram](#server-level-forwards-and-services), a database console. Same rules and answers as a session's; it closes on `DELETE`, when its device is revoked, after 12 idle hours, or when the server stops. + +```mermaid +sequenceDiagram + participant App as Client app + participant S as serve (API) + participant F as Forward listener (:8801) + participant P as Page (127.0.0.1:5173) + App->>S: POST /api/sessions/:id/forwards {port: 5173, path: "/"}
Authorization: Bearer gss_… + S-->>App: 201 {id, listenPort: 8801, url: "http://HOST:8801/?gs_ticket=…", expiresAt} + App->>F: GET /?gs_ticket=… (webview or browser) + F-->>App: 303 Location: / + Set-Cookie: gs_fwd_ID=SECRET, HttpOnly, SameSite=Strict, Path=/ + App->>F: GET / (Cookie: gs_fwd_ID) + F->>P: GET / (Host: 127.0.0.1:5173, no gs_fwd_* cookie) + P-->>F: 200 (streamed) + F-->>App: 200 (streamed) + App->>F: WebSocket upgrade (Cookie) — piped both ways +``` + +`Forward` is `{ id, port, listenPort, sessionId, kind, createdAt, lastUsedAt }`: `kind` is `"session"`, `"tower"` or `"server"`, and `sessionId` is `null` for Tower's and server-level ones. The answer to `POST` adds `url`, the link to open as it is — `http://:?gs_ticket=` (the ticket goes before any `#fragment` of `path`, after any query) — and `expiresAt`, when the ticket expires. `path` defaults to `/`; it must start with `/` (not `//`) and hold printable ASCII without spaces, at most 2048 characters. + +Errors: `400 invalid_port` (not 1-65535, or the server's own port or a forward's), `400 invalid_path`, `404 not_found` (session), `409 session_exited`, `429 too_many_forwards`, `503 no_forward_port` (every port in the range is taken). Whether something listens on the port is not checked when the forward opens (the agent may start the server later): until it does, the forward answers `502` with a plain text line. + +### Forward security + +- **A ticket, then a cookie.** The link's `gs_ticket` is single use, valid 60 s, and bound to that forward and its device. The first request that carries it gets a `303` to the same URL without it and a cookie `gs_fwd_` (a fresh random secret, `HttpOnly; SameSite=Strict; Path=/`). Every later request, WebSockets included, needs that cookie; without it the answer is `401`. A link already used opens again only in a browser that holds the cookie; otherwise ask for a new one (`POST` again). Browsers share cookies across ports of a host, so each forward's cookie has its own name, and the proxy strips the ticket and every `gs_fwd_*` cookie before the page sees the request, and drops any `gs_fwd_*` cookie the page tries to set. +- **Host and Origin.** The `Host` header follows the [main server's rules](#security-model) for the forward's port (`421` otherwise). A request with an `Origin` other than the forward's own (`http://`) is refused with `403`: another forwarded page on the same host is the same site for `SameSite`, so it could otherwise send requests that carry the cookie. No CORS headers are added. +- **What the page sees.** `Host` is `127.0.0.1:` (or `[::1]:`); the forward's own `Origin` and `Referer` are rewritten to the page's own, so pages that check them (Gentle Tower, dev servers) accept the request. Other cookies of the host still reach the page (as they would for any page on that host). Redirects (`Location`) to the page's loopback address are rewritten to the forward. Hop-by-hop headers are dropped both ways. +- **Streaming.** Requests and responses are piped, never buffered: SSE, downloads and uploads stream. A WebSocket upgrade is handed to the page and the two sockets are piped both ways. +- **Closing.** A forward closes, with its open connections, when its session stops or is deleted (session forwards), when its device is revoked, on `DELETE`, when the server stops, and after 12 hours with no request and no open connection. +- **Same authority as the session.** A forward opens nothing the device could not already reach: `sessions:operate` can run `curl 127.0.0.1:` in the session. On a network listen it is HTTPS with the server's own certificate, like the rest of the server. + +### Firewall + +A network server's forwards listen on their own ports, so a firewall that allows only the server's port blocks them. Start the server with a range (`--forward-ports 8800-8899`; `serve share` does) and open it once: `sudo ufw allow 8800:8899/tcp`, or `sudo firewall-cmd --permanent --add-port=8800-8899/tcp && sudo firewall-cmd --reload`. Over an SSH tunnel, forward each forward's port too (`ssh -L 8800:127.0.0.1:8800 …`), with the same port on both ends. + +### Server-level forwards and services + +Some pages belong to the server machine rather than to a session. `GET /api/services` (`sessions:read`) lists the ones a client may want to open, so it can offer them without asking for a port: + +```json +{ "services": [ + { "id": "engram", "name": "Engram", "url": "http://127.0.0.1:7437", "port": 7437, "available": true, "forwardable": true, "via": "forwards" }, + { "id": "tower", "name": "Gentle Tower", "port": 41234, "available": true, "forwardable": true, "via": "tower" } +] } +``` + +- **Engram** is always listed: at the server's `ENGRAM_URL`, or `http://127.0.0.1:7437`. `available` says whether `GET /health` answered `2xx` within 1.5 s (credentials in `ENGRAM_URL` are sent as Basic auth and never shown). `forwardable` is `true` for a plain-HTTP loopback URL; then `via: "forwards"`: open it with `POST /api/forwards { port, path? }`. A remote or HTTPS Engram is listed with `forwardable: false` (the client reaches it directly, if at all). +- **Gentle Tower** is listed only while it runs, with `via: "tower"`: open it with `POST /api/tower` (which adds Tower's token path), never with `/api/forwards`. + +`Service` is `{ id, name, url?, port, available, forwardable, via? }`. + +## Gentle Tower + +`POST /api/tower` (`sessions:operate`: Tower sends messages to sessions and opens new ones) starts Gentle Tower inside the server process when it is not running — the same server `gentle-shell tower` runs, on `127.0.0.1` with a fresh token, without a browser — and answers with a forward to it like `POST …/forwards` does, plus `started` (whether this call started it). The link's path is Tower's own token path (`//`), so Tower's own token check still applies behind the forward's. Every device gets its own forward to the one Tower. `GET /api/tower` says whether it runs; `DELETE /api/tower` stops it and closes its forwards; it also stops with the server. + +- `503 tower_unavailable` with the reason when Tower cannot start (for example a source checkout whose web app is not built: `pnpm build:tower`). +- Tower shows the sessions of this machine (its hub is per user, not per agent home). Its "new floor" action opens a terminal window on the server machine, as it does locally. + +## Files on the server + +A client browses and edits files that live on the server — the project a session works in — through `/api/fs/*`. Every path is an **absolute path on the server** (`/home/you/project/src/main.rs`; on Windows `C:\…`), as a string of at most 4096 characters without NUL; relative paths answer `400 invalid_path`. Paths are normalized lexically (`a/../b` is `b`) before use. `GET /api/server` gives the server's `platform`, `pathSeparator` and (for `sessions:operate`) `home`. + +`Entry` is `{ name, kind: "file"|"dir"|"symlink"|"other", size, mtime, linkKind? }`: `mtime` in milliseconds since the epoch, `size` in bytes, and for a symlink `linkKind` is what it points to (`"file"`, `"dir"`, `"other"`, or `null` when it dangles). `other` is a socket, FIFO or device. + +| Endpoint | Behaviour | +| --- | --- | +| `list` | Every entry of the folder, hidden ones included, sorted by name (byte order). At most 5000; past that `truncated: true` (which 5000 is up to the file system). A symlinked folder is followed. | +| `stat` | `lstat` of the path: a symlink is reported as one, with `linkTarget` (the link's text), `linkKind`, and the `size` and `etag` of the file it points to. `realPath` is the path with every symlink resolved (absent when a link dangles). `mode` is the permission bits. | +| `read` | Up to 8 MiB from `offset` (default 0): `length` bytes, or as many as fit the cap and the file. `200 application/octet-stream` with `ETag`, `Last-Modified`, `X-File-Size`, `X-File-Mtime` (ms), `X-Offset` and `X-Truncated: 1` when bytes remain after this chunk. `If-None-Match: ` or `If-Modified-Since` answer `304` when the file did not change. Follows symlinks; a folder or special file answers `400 not_a_file`. | +| `write` | The raw request body (at most 64 MiB) becomes the file's content, atomically: it is written to a temporary file in the same folder and renamed over the target, so a reader sees the old or the new content, never a mix. An existing file keeps its permission bits; a new one gets the default (`0666` less the server's umask). Writing through a symlink replaces the file it points to and keeps the link. `create_only=1` refuses an existing file (`409 exists`; exclusive even against a concurrent writer). `If-Match: ` (from `stat`, `read` or a previous `write`) answers `412 changed` when the file changed since — a client's guard against overwriting someone else's edit. The folder must exist (`404`). `201` when it created the file, `200` otherwise. | +| `mkdir` | Creates the folder and any missing parent (`mkdir -p`). `201 { created: true }`, or `200 { created: false }` when it already existed. | +| `rename` | Moves `from` to `to` (a file, folder or symlink itself — never what a link points to). An existing `to` answers `409 exists` unless `overwrite: true` (a case-only rename of the same entry is not a clash). | +| `remove` | Removes a file or symlink (never what it points to), or a folder: an empty one, or with `recursive: true` everything in it (symlinks inside are removed, not followed). A non-empty folder without `recursive` answers `409 not_empty`. | +| `search` | File and folder names under `root` (an existing folder) matching `q` (1-256 characters, case-insensitive), best first: exact name, name prefix, name substring, relative-path substring (so `src/main` works), then the query's characters in order in the name. `limit` defaults to 100, at most 1000. Never enters `.git` or `node_modules`, nor follows symlinked folders. Looks at no more than 200 000 entries or 5 s; past that `truncated: true`. | +| `watch` | SSE: `event: ready` `{ path, recursive }`, then `event: changes` `{ paths: […] }` whenever something under `path` changes (a file or a folder, recursively where the platform supports it: macOS, Windows and Linux). Changes are batched: a batch is sent 150 ms after the last change, and at most 1 s after the first. A batch over 1000 paths is sent as `{ paths: [], overflow: true }` (rescan). It says *what* changed, not how: `stat` the paths. `event: error` `{ message }` ends the stream when the watch fails (for example the Linux inotify limit). `: ping` every 20 s. At most 32 open per device (`429 too_many_watchers`). | + +Errors are mapped from the file system: `404 not_found`, `400 not_a_directory`, `400 is_a_directory`, `400 not_a_file`, `403 permission_denied` (the server user may not), `409 exists`, `409 not_empty`, `409 cross_device` (a rename across volumes), `409 dangling_symlink` (a write through a link to nothing), `413 too_large`, `507 no_space`. + +### File safety + +- **The server user's authority.** These endpoints run as the user the server runs as, with no folder jail: `sessions:operate` can read and change every file that user can — the same authority a session's own tools (`bash`, `write`) already have — while `sessions:read` sees names, sizes and changes but never a file's contents (`403 forbidden` on `read`), so a device that only watches cannot read secrets such as `mcp.json` or `auth.json` that the configuration stores mask. Pair devices accordingly. +- **Refused targets.** `remove` and `rename` refuse (`403 protected_path`) the file system root, the server user's home folder, and every folder above the home. The check runs on the entry itself with its folder's symlinks resolved, so `/home/you/link-to-root/home` is refused like `/home`, while removing `/home/you/link-to-home` removes only the link. +- **No partial writes.** A write that fails, is cut short or is too large leaves the target untouched and removes its temporary file. + +## git on the server + +`POST /api/git` runs one `git` command in a folder on the server and answers when it ends, so a client shows and drives a repository that lives there (status, diffs, staging, commits, branches, fetch and push). + +```json +{ "cwd": "/home/you/project", "args": ["status", "--porcelain=v2", "-z"], "stdin": "", "env": { "GIT_AUTHOR_NAME": "…" }, "timeoutMs": 120000 } +``` + +- **No shell.** `git` (from the server's `PATH`) runs with `args` as its arguments, in `cwd` (an absolute path to an existing folder, symlinks resolved), in its own process group without a controlling terminal. `args`: 1-256 strings without NUL, each at most 32 KiB. `stdin` (base64, at most 8 MiB) is written to its standard input, which is then closed; without it standard input is empty. +- **Answer.** `200 { code, signal, stdout, stderr, truncated, timedOut }` whatever the exit code: `code` is git's exit code (`null` when a signal ended it), `stdout` and `stderr` are base64. `stdout` is cut at 32 MiB — git is then stopped and `truncated` is `true` — and `stderr` at 1 MiB. `501 git_missing` when the server has no `git`. +- **Nobody to ask.** The environment is the server's, without inherited `GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE` and the like, plus `GIT_TERMINAL_PROMPT=0` and `GCM_INTERACTIVE=never` (a credential prompt fails instead of waiting), `GIT_PAGER=cat`, `GIT_EDITOR=true` (a commit without `-m` aborts; a rebase takes its todo as is) and `GIT_MERGE_AUTOEDIT=no`; read-only commands also get `GIT_OPTIONAL_LOCKS=0` (they never write the index). `env` may add only: `GIT_AUTHOR_NAME`, `GIT_AUTHOR_EMAIL`, `GIT_AUTHOR_DATE`, `GIT_COMMITTER_NAME`, `GIT_COMMITTER_EMAIL`, `GIT_COMMITTER_DATE`, `GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`, `GIT_NAMESPACE`, `GIT_LITERAL_PATHSPECS`, `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`, `GIT_ICASE_PATHSPECS`, `GIT_REFLOG_ACTION`, `GIT_MERGE_AUTOEDIT`, `GIT_MERGE_VERBOSITY`, `GIT_OPTIONAL_LOCKS` (any other name: `400 env_not_allowed`). SSH keys, agents and credential helpers are the server user's own. +- **Time.** 120 s by default; `timeoutMs` (1000 or more) may lower it, or raise it up to 600 s for `fetch`, `push`, `clone`, `pull`, `ls-remote` and `submodule` (`400 invalid_timeout` otherwise). At the limit git's process group gets SIGTERM, then SIGKILL 2 s later, and the answer has `timedOut: true`. At most 16 commands run at once (`429 too_many_git`); the server's stop ends them. + +### git scopes and refusals + +A command that only reads and prints no file contents needs `sessions:read`; anything else needs `sessions:operate` — including reads that print file contents (a patch, a blob, `blame`, `grep`), so a device that only watches cannot read a secret the repository holds. The subcommand is the first argument after git's global options (`-C

`, `--no-pager`, `--git-dir=…`, …). `sessions:read` runs: + +- `status`, `rev-parse`, `ls-files`, `for-each-ref`, `ls-tree`, `rev-list`, `merge-base`, `describe`, `shortlog`, `name-rev`, `check-ignore`, `check-attr`, `show-ref`, `count-objects`, `version`, `ls-remote`, and git with no subcommand (`--version`); +- `log`, `diff-tree`, `diff-files` and `diff-index` without an option that prints or searches contents: `-p`/`-u`/`--patch` (and `--patch-with-*`), `-U`/`--unified`, `-c`/`--cc`/`--dd`/`-m`/`--diff-merges`/`--remerge-diff`, `--word-diff`/`--color-words`, `-W`/`--function-context`, `--binary`, `--check`, `-L`, `-S`/`-G`/`--pickaxe-*`/`--find-object`, `--ext-diff`, `--textconv` (also bundled, as in `-pM`); `diff` the same, and only with an option that replaces its patch: `--name-only`, `--name-status`, `--numstat`, `--stat`, `--shortstat`, `--compact-summary`, `--dirstat`, `--summary`, `--raw`, `-s`/`--no-patch` or `--quiet`; +- `cat-file -t`/`-s`/`-e`/`--batch-check` (an object's type, size or existence, never `-p`, `--batch` or a type name); +- `branch` and `tag` listing (no name, or `--list`/`-l`, `--contains`, `--merged`, `--points-at`, `--show-current`, …, and no flag that creates, deletes, moves or signs); `config --get`/`--get-all`/`--get-regexp`/`--get-urlmatch`/`--list` and `config get`/`config list`; `remote` with no subcommand, `remote get-url` and `remote show`; `stash list`/`show` without a patch option; `worktree list`; `symbolic-ref` with one name. + +`show`, `blame` and `grep` always need `sessions:operate`, and so does anything with `--output` (writes a file). + +Any `-c`/`--config-env` override makes a command an operation (configuration can make a read run a program). Some configuration and options are refused outright with `400 git_refused`, whatever the scope, because they make git run another program: the keys `core.sshCommand`, `core.fsmonitor`, `core.hooksPath`, `core.gitProxy`, `uploadpack.*`, `alias.*`, `remote..uploadpack`, `remote..receivepack` and `protocol.ext.allow` (in `-c`, `--config-env`, and `clone -c`/`--config`); `--exec-path=`; `--upload-pack`, `--receive-pack` and `--exec` (and `-u` for `clone` and `ls-remote`). Arguments after `--` are paths and never checked as options. + +This is defence in depth, not a sandbox: `sessions:operate` is the server user's authority (it can already write `.git/config` through the file endpoints or a session's tools), so the refusals only keep the convenient injection routes closed and keep `sessions:read` from becoming command execution. + +## One-shot prompts + +`POST /api/print` answers one prompt with this machine's Gentle Shell and nothing else — no session, no tools — so a client writes a commit message (or a title) for a folder that lives on the server, exactly as it does with its own local Gentle Shell. + +```json +{ "cwd": "/home/you/project", "prompt": "Write a git commit message for …", "model": "anthropic/claude-sonnet-4-5" } +``` + +- **What runs.** The same launcher and agent home as the sessions, the way the app runs it locally: `node bin/gentle-shell.mjs --print --no-session --no-tools [--model ]`, in `cwd` (an absolute path to an existing folder), in its own process group, with the sessions' environment but without `GENTLE_SHELL_INTERACTIVE_HOST` (nothing answers dialogs in a one-shot run). The prompt goes on standard input (Pi takes piped input as the message), so it never shows in the process list. `prompt`: a non-empty string of at most 256 KiB. `model` (optional) is passed as `--model` (Pi's pattern: `provider/id` or `id`, optionally `:`): at most 200 characters, no spaces or control characters, not starting with `-`. +- **Answer.** `200 { text }`: the run's standard output as it printed it. `502 print_failed` when it exits with an error (or cannot start): `message` is the end of its stderr (2000 characters), and the answer also carries `exitCode`. `502 output_too_large` past 1 MiB of output, `504 print_timeout` after 120 s; both stop the run (SIGTERM to its process group, SIGKILL 2 s later), and so does a client that hangs up. `400 invalid_cwd`, `invalid_prompt`, `invalid_model`; `429 too_many_prints` with 4 already running; `501 not_supported` on a server built without a launcher (no `print` capability). + +## Uploads + +A client that wants the agent to see a file from its own machine — a chat attachment, a screenshot, a log — sends it with `POST /api/uploads?name=` (the raw bytes as the body, at most 64 MiB, `sessions:operate`) and puts the answered `path` in the prompt. + +- It is stored at `/serve/uploads//<16 random hex>/`: owner-only (`0700` folders, `0600` file), one fresh folder per upload so names never clash. `name` keeps only its last path component, with control characters and `<>:"|?*` replaced by `_`, at most 200 UTF-8 bytes (`upload` when nothing is left). +- The answer is `201 { path, name, size, sha256, expiresAt }`. A refused or cut-short upload leaves nothing behind. +- Uploads are removed 7 days after they arrived (checked at start and hourly). They are plain files: the agent reads them with its own tools, and a client can also read them back through [`/api/fs/read`](#files-on-the-server). + +## Persistent terminals + +A device can open real terminals on the server — a shell in the project folder — that keep running when it disconnects, when another device takes over, and when `serve` itself restarts. The PTYs live in a separate native process, `gentle-term-host`; `serve` is only a client of it. + +```mermaid +sequenceDiagram + participant App as Client app + participant S as serve + participant H as gentle-term-host + participant P as Shell (PTY) + App->>S: POST /api/terminals {cwd, cols, rows} + S->>H: connect term.sock, or 127.0.0.1:port + auth on Windows (start the host, detached, if nothing answers) + S->>H: {"op":"hello"} / {"op":"open",…} + H->>P: fork a PTY: login shell -l, TERM=xterm-256color + H-->>S: {"ok":true,"term":"t_…","pid":…} + S-->>App: 201 {terminal} + App->>S: GET /api/terminals/t_…/stream?from=LAST_OFFSET + S->>H: new connection: {"op":"attach","term":"t_…","from":…} + H-->>S: {"offset", "snapshot"?} + S-->>App: event: attached {offset, snapshot?} + P-->>H: output bytes + H-->>S: {"ev":"output","offset","data"} + S-->>App: id: OFFSET / event: output {offset, data} + App->>S: POST /api/terminals/t_…/input {data} + S->>H: {"op":"write",…} + H->>P: keystrokes + Note over App,S: The app disconnects: the shell keeps running in the host + Note over S,H: serve restarts: the host and its terminals stay, serve reconnects (term.sock or the port file) +``` + +### The host + +- **Where it comes from.** `serve` runs `$GENTLE_TERM_HOST` when set, otherwise `/serve/bin/gentle-term-host` (`.exe` on Windows), otherwise the first `gentle-term-host` on `PATH`. Without one, `GET /api/server` has no `terminals` capability and the terminal endpoints answer `501 term_host_missing`. A client can install one: `PUT /api/term-host` (`admin`) with the binary as the raw body (at most 64 MiB) and its sha256 in the `x-sha256` header; the server checks the hash (`400 sha256_mismatch`), makes it `0755`, and moves it into place atomically (on Windows, where a running `.exe` can't be replaced, the old one is renamed aside to `*.old` and removed by a later install). `active` in the answer says whether it is the one `serve` now uses (`false` when `$GENTLE_TERM_HOST` points elsewhere). `GET /api/term-host` tells `platform`, `arch` and `asset`: the name of the prebuilt binary for this server in Gentle Shell GPUI's GitHub releases (`gentle-term-host--[.exe]`, os `linux`/`macos`/`windows`, arch `x64`/`arm64`; `null` when none is built for it, e.g. Windows on arm64), listed in the release's `SHA256SUMS`, so a client downloads it, checks it and installs it. A host already running keeps running its old binary until it exits. +- **Started on first use.** The first terminal request connects to `/serve/term.sock`; when nothing answers there, `serve` starts the host detached (`--socket /serve/term.sock --state-dir /serve/term`, its own session, output appended to `term/term-host.log`) and waits up to 5 s for its socket. A host that is already running — started by an earlier `serve` — is simply reused. The socket is owner-only (`0600`, in the `0700` serve folder). +- **On Windows: loopback TCP.** There `serve` starts the host with `--tcp --state-dir /serve/term` (`transport: "tcp"` in `GET /api/term-host`; `GENTLE_TERM_HOST_TRANSPORT=tcp` picks it on Linux and macOS too). The host listens on `127.0.0.1` at a port the system picks and writes `{ port, token, pid }` to `term/term-host.json`, readable only by the server user (a protected DACL for the file's owner). Every connection's first line must be `{"op":"auth","token":…}` (answered `{ ok: true }`); anything else gets `unauthorized` and the connection closes, as it does after 10 s without it. A port file whose port refuses the connection (or the token) is left from a host that died: `serve` removes it and starts another. The host compares tokens in constant time; other local users can reach the port but not the token. +- **Lifetime.** The host keeps every terminal while no client is connected and outlives `serve`: stopping or restarting `serve` closes its connections, never the terminals. The host exits on its own when it has had no terminals and no connections for 10 minutes. A host restart (a reboot, a crash) loses its terminals. +- **Protocol.** JSON Lines over the socket, one request `{ id, op, … }` → one reply `{ id, ok, … }`, plus events (`output`, `exit`, `title`, `resized`, `overflow`) on connections attached to a terminal; terminal bytes travel as base64. `serve` keeps one control connection and opens one more per stream. + +### Terminal endpoints + +`Terminal` is `{ id, pid, cwd, argv, cols, rows, title, alive, exitCode?, createdAt, offset, owner }`: `createdAt` in ms since the epoch, `offset` the number of bytes the terminal has written so far, `owner` the id of the device that opened it. + +- **Open.** `POST /api/terminals { cwd, cols, rows, argv?, env? }`: `cwd` an absolute path to an existing folder, `cols` 1-1000, `rows` 1-500; `argv` (1-256 strings) defaults to the server user's login shell with `-l` (on Windows PowerShell: `pwsh.exe -NoLogo` when `pwsh.exe` is on `PATH`, else `powershell.exe -NoLogo`; the PTY is a ConPTY); `env` (at most 128 names) is added to the host's environment, which also sets `TERM=xterm-256color`, `COLORTERM=truecolor` and `TERM_PROGRAM=GentleShell`. `502 term_spawn_failed` when the program cannot start. +- **Ownership.** A terminal belongs to the device that opened it: the list shows a device its own, and every other endpoint answers `404` for another device's terminal. A token with `admin` sees and drives all of them. Revoking a device closes its terminals and ends its streams; a device paired again that replaces its earlier pairing (`POST /api/devices/self/replace`) takes its terminals over first. +- **Input and resize.** `POST …/input { data }` writes base64 bytes as typed (keys, pastes, and the answers a terminal emulator gives to queries such as cursor position reports). `POST …/resize { cols, rows }`. Both answer `409 terminal_exited` once the program ended. +- **Close.** `DELETE /api/terminals/:t` closes a running terminal (SIGHUP, then SIGKILL to its process group after 3 s; on Windows the program is ended at once and closing its pseudoconsole ends what else ran in it; it leaves the list at once) or forgets an exited one. +- **Stream.** `GET …/stream?from=` (or `Last-Event-ID`, as `EventSource` sends it) is SSE: + - first `event: attached` `{ offset, snapshot? }`. When `from` is still in the terminal's replay buffer (at least the last 1 MiB of output), there is no snapshot: `offset` is `from` and the missed bytes follow as `output`. Otherwise `snapshot` (base64) is an ANSI sequence that, written into a fresh terminal emulator of the terminal's size, reproduces its screen — contents, cursor, colours and attributes, alternate screen, cursor visibility, bracketed paste, mouse and application-cursor modes — with up to 2000 lines of scrollback above it; `offset` is the current end. A client resets its emulator, writes the snapshot, and continues. + - `event: output` `{ offset, data }` with `id: `: `data` is base64 terminal output and `offset` the byte offset of the end of this chunk, so the last `id` seen is the `from` to resume with. + - `event: title` `{ title }`, `event: resized` `{ cols, rows }` (whoever resized it). + - `event: exit` `{ code }`: the program ended; the stream ends after it. Attaching to an exited terminal gives its final snapshot and `exit` at once. + - `event: overflow` `{ reason }`: this stream fell behind (8 MiB unsent, at the host or here) and ends; reconnect, without `from` if it is no longer in the buffer. + - `event: error` `{ code: "term_host_gone" }` when the host went away. `: ping` every 20 s. + + Every stream is its own attachment, so several devices (or windows) can follow the same terminal; each needs its own `GET`. + +### Terminal security + +- **A terminal is a shell as the server user.** The `terminal` scope is that authority, separately from `sessions:operate` so a device can drive sessions without opening shells. The server adds no sandbox. +- **Owner-only socket.** Only the server user can connect to the host; the host never listens on the network. Remote devices reach terminals only through `serve`'s authenticated endpoints. +- **Installing the host** needs `admin`, and the hash the client sent must match the bytes received; it is the same trust as an admin token already has (it could start sessions that run anything). + +## Security model + +- **Loopback by default.** Without `--listen` the server binds `127.0.0.1` on a random port. Remote use goes through `ssh -L` (or a tunnel) to that port. +- **HTTPS on a network.** A non-loopback `--listen` (for example `0.0.0.0:8787`) serves HTTPS with a self-signed certificate whose fingerprint clients pin at pairing; the short code is only sent after the server proves it knows it for that certificate. Plain HTTP on a network needs `--no-tls` and prints a warning; use it only on a network that encrypts by itself (a tailnet). Loopback stays plain HTTP. +- **LAN discovery reveals presence only.** A network server answers the UDP [discovery query](#lan-discovery) of anyone on the network with its `serverId`, hostname and port — what `/.well-known/gentle-shell` already tells — and nothing else; replies are rate-limited and go only to the sender (a reply is about the size of the query, so it cannot amplify traffic). A loopback server does not listen for discovery. +- **Origin and Host.** A request whose `Origin` is not this server's own origin (`http://`) is refused (`403 forbidden_origin`), before authentication, including `POST /api/pair`. Requests without `Origin` (curl, native clients) are accepted; tokens are never cookies, so a browser cannot attach them on another page's behalf. The `Host` header must name this server and its port (`421 bad_host`): loopback names for a loopback bind, the bound address otherwise, and for `0.0.0.0`/`::` any IP literal or this machine's own hostname (also as `.local`) — never another DNS name (DNS rebinding). A name the operator trusts, such as a tailnet MagicDNS name (`box.tail1234.ts.net`), is added with `--allow-host `; it is an exact name, never a pattern. No CORS headers are sent. +- **Headers.** `Cache-Control: no-store`, `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`. +- **Bounded input.** 16 KiB for small JSON bodies, 80 KiB for Desktop RPC (10 MiB for host tool registrations, results, messages and context), 8 MiB for Pi RPC commands, 64 MiB for a file write; 20 s to send headers. +- **Host tools run on the client.** A device's host tools run on that device with its own authority; the server and the agent only see the call's arguments and the result. A device can only register tools as itself and answer its own calls. +- **Remote authority never exceeds the terminal's.** `sessions:operate` is the same authority as typing into the session's terminal or writing the Desktop app's RPC stdin — including `/gentle:mode`, `set_permission_mode` and the rest of the [Desktop RPC trust boundary](desktop-rpc.md#trust-boundary). The server forwards to Pi unchanged and bypasses none of the existing rules: remote prompts are not interactive consent, provider consent stays terminal-only, and Desktop RPC's own checks apply inside the child. Pair `sessions:operate` only with devices you would hand your terminal; `sessions:read` follows without driving. + +## Limits + +| Limit | Value | +| --- | --- | +| Running sessions | 16 (`429 too_many_sessions`) | +| Exited sessions kept | 16 | +| Session with no server attached | 24 hours, then stopped; an exited one waits 60 s for a server to collect its stream | +| Host tool call after a server restart | 30 s for its device to reconnect | +| Replay ring per session | 2000 records or 8 MiB | +| Unsent bytes per subscriber | 4 MiB, then `resync` | +| One stdout record | 16 MiB, then `serve_record_dropped` | +| Pending stdin per session | 16 MiB, then `503 session_busy` | +| `/rpc` and `/desktop` wait | 30 s (`202 pending` / `504 desktop_timeout`); the same for `/api/desktop` | +| Control session (`/api/desktop`) | stopped after 10 minutes with no request and no open event stream | +| Host tool call, device offline | answered at once; 10 s grace after its last stream closes | +| Host tool call, no result | 10 minutes, restarted by each `host_tool_progress` | +| Heartbeat | 20 s | +| Pairing code | 5 minutes, single use, 16 live, 10 failures per minute | +| Stream ticket | 60 s, single use, 256 live | +| Devices | 64 | +| LAN discovery replies | 20 per second overall, 4 per second per source address; queries over 512 bytes dropped | +| Forwards | 32 open at once; 64 connections each | +| Forward ticket | 60 s, single use, 256 live | +| Forward browser sessions | 32 cookies per forward (the oldest is dropped) | +| Forward idle | 12 hours with no request and no open connection | +| Forward connect to the page | 10 s, then `502` | +| File read | 8 MiB per call | +| File write | 64 MiB per call | +| Folder list | 5000 entries, then `truncated` | +| File search | 1000 results; 200 000 entries or 5 s walked, then `truncated` | +| Change streams | 32 per device; batches after 150 ms quiet, at most 1 s late, 1000 paths | +| git command | 120 s (600 s for network commands); 32 MiB stdout, 1 MiB stderr, 8 MiB stdin; 16 at once | +| One-shot prompt | 120 s; 256 KiB prompt, 1 MiB answer; 4 at once | +| Upload | 64 MiB; kept 7 days | +| Terminals | `cols` 1-1000, `rows` 1-500; input 4 MiB per request; replay buffer at least 1 MiB per terminal; 8 MiB unsent per stream, then `overflow`; host start 5 s; host request 10 s | +| Terminal host binary | 64 MiB | + +## Try it from source on Linux + +A walkthrough for running this branch on a Linux machine (written for Arch / Omarchy; other distributions differ only in package names) and reaching it from another machine, for example a Mac running Gentle Shell GPUI. No released Gentle Shell has `serve` yet: the installed `gentle-shell` takes `serve` as a prompt for the model, so every command below runs the checkout's launcher, and the installed Gentle Shell is left as it is. + +### 1. Install the checkout + +Requirements: `git`, Node `^22.19.0 || >=23.6.0` (`package.json` `engines`), and corepack to get the pinned pnpm (`packageManager`: `pnpm@11.1.1`). Node 22 and 24 ship corepack; Node 25 and later do not, so install it with `npm install -g corepack` (with `sudo` for a system Node from pacman; not with mise). + +```sh +sudo pacman -S --needed git nodejs npm # or: mise use -g node@22 +node --version # v25 or later? then: sudo npm install -g corepack +git clone -b feat/serve-phase1 https://github.com/ismaelosuna7824/gentle-shell.git ~/src/gentle-shell +cd ~/src/gentle-shell +corepack pnpm install +``` + +`pnpm install` installs the dependencies (Pi included, in `node_modules`) and its `postinstall` downloads the pinned Gentle AI release binary, verified against its signed checksums, into `.gentle-ai/v/` inside the checkout. It writes nothing in your home (a git checkout is not a Pi-managed install, so the global Pi settings are not touched). + +[Gentle Tower](#gentle-tower) is a separate web build. Only if you want to open it from a client, build it once in the checkout: + +```sh +corepack pnpm run build:tower +``` + +A shell function keeps the commands short: + +```sh +gsdev() { GENTLE_SHELL_NO_AUTO_SETUP=1 node ~/src/gentle-shell/bin/gentle-shell.mjs "$@"; } +``` + +`GENTLE_SHELL_NO_AUTO_SETUP=1` keeps the checkout from re-running setup in your agent home when its version differs from the one that set the home up (see [step 3](#3-choose-the-agent-home)). + +### 2. Build the terminal host + +[Persistent terminals](#persistent-terminals) run in `gentle-term-host`, a native binary from the Gentle Shell GPUI repository. Without it everything else works and opening a terminal answers `501 term_host_missing`. No release ships it for this branch yet, so build it from the GPUI pull request's branch: + +```sh +sudo pacman -S --needed rustup base-devel +rustup default stable +git clone -b feat/remote-serve-backend https://github.com/Gentleman-Programming/gentle-shell-gpui ~/src/gentle-shell-gpui +cd ~/src/gentle-shell-gpui +cargo build --release -p gentle-term-host +``` + +The server looks for it in `$GENTLE_TERM_HOST`, then `/serve/bin/gentle-term-host`, then on `PATH`. Copy it into the home's `serve/bin/` (the home of [step 3](#3-choose-the-agent-home); `gsdev --version` prints it): + +```sh +AGENT_HOME=~/.gentle-shell/agent # the home line of 'gsdev --version' +install -d -m 700 "$AGENT_HOME/serve" "$AGENT_HOME/serve/bin" +install -m 755 target/release/gentle-term-host "$AGENT_HOME/serve/bin/" +``` + +Or leave it in place and start the server with `GENTLE_TERM_HOST=$HOME/src/gentle-shell-gpui/target/release/gentle-term-host` in its environment (not carried into the `--always` unit, so prefer `serve/bin/` there). A client can also install one with `PUT /api/term-host`. + +### 3. Choose the agent home + +The checkout resolves its home exactly as the installed `gentle-shell` does: `--link`, `--isolated` or `--home ` when given, otherwise the home saved in `~/.gentle-shell/config.json`, otherwise `~/.gentle-shell/agent` (or `$GENTLE_SHELL_HOME`). So with no flags it uses the same home as your installed Gentle Shell, with its sign-ins (`auth.json`), providers and settings. Compare the `home` line of both: + +```sh +gentle-shell --version # the installed one +gsdev --version # the checkout; writes nothing +``` + +- **Reuse your providers (recommended):** run `gsdev serve …` with the same home selector you use day to day (none, or `--link` if you launch `gentle-shell --link`). `serve` itself writes only `/serve/`. Its sessions are ordinary launches of the checkout in that home, so they also read and write the home's sessions and settings, as any Gentle Shell launch does, and a client's Configuration changes (model defaults, `models.json`, MCP servers, packages, setup, sign-in) change that home too. `GENTLE_SHELL_NO_AUTO_SETUP=1` (in `gsdev`) keeps the companion packages as your installed Gentle Shell left them. The installed Gentle Shell keeps working alongside; the two never share a process. +- **Fully separate:** `gsdev --home ~/.gentle-shell-serve serve …` uses a new home (the selector goes before `serve` in every command below). Copy your sign-ins into it if you want them (`install -m 600 ~/.gentle-shell/agent/auth.json ~/.gentle-shell-serve/`); without `GENTLE_SHELL_NO_AUTO_SETUP=1` its first session installs the companion packages there. + +Sessions use the checkout's Pi (`node_modules`), not the installed one's. + +### 4. Reach it from the Mac + +```sh +gsdev serve share +``` + +It starts the server in the background on every interface (port 8787, or the next free one up to 8796; `--port ` starts the search elsewhere), with forwarded pages on ports 8800-8899, and prints a short code and a long `gsc1.…` code ([Share on your network](#share-on-your-network)). In Gentle Shell GPUI on the Mac, **Configuration → Where agents run → Gentle Shell server**, enter the short code: the app finds the Linux machine with a UDP broadcast ([LAN discovery](#lan-discovery)). Where discovery does not reach (another subnet, a tailnet, Wi-Fi client isolation, a relay) paste the long code instead: it carries the addresses, the port, the pairing code, the certificate fingerprint (`fp`) and the relay (`r`) when there is one ([Connection code](#connection-code)). A code is valid 5 minutes, once; run `serve share` again for another device or a fresh code. + +The network server speaks HTTPS with a self-signed certificate made on first run (`/serve/tls/`). The long code carries its fingerprint, which the app pins; with the short code the app first asks the server for a pairing proof (`POST /api/pair/proof`) that binds the code to the certificate, so the code only goes to a server that already knows it. On the Linux machine itself `http://127.0.0.1:` keeps working; plain HTTP from another machine gets `400 tls_required`. `--no-tls` serves plain HTTP on the network as before, only for a network that encrypts by itself, such as a tailnet. + +**Firewall.** Omarchy enables `ufw` (`sudo ufw status`). `share` prints the exact command for the port it took and never runs `sudo` itself: + +```sh +sudo ufw allow 8787 # TCP for HTTPS, UDP for discovery +sudo ufw allow 8800:8899/tcp # pages the app opens from here (forwards) +# firewalld instead: +sudo firewall-cmd --permanent --add-port=8787/tcp --add-port=8787/udp --add-port=8800-8899/tcp && sudo firewall-cmd --reload +``` + +**Start at login.** `gsdev serve share --always` writes `~/.config/systemd/user/gentle-shell-serve.service` with the same command, home flags, `PATH` and the environment listed in [Start at login](#start-at-login) (`GENTLE_SHELL_NO_AUTO_SETUP` included), then runs `systemctl --user enable --now`. The unit uses `KillMode=process`: restarting it ends only the server, and the next one reattaches the sessions and terminals. Its output goes to the journal (`journalctl --user -u gentle-shell-serve -f`). A user unit runs while you are logged in; `sudo loginctl enable-linger $USER` starts it at boot. `gsdev serve share --off` disables and removes it, which stops that server. + +**Relay.** For a Mac outside the Linux machine's network, run a relay where both can reach it (a VPS, or any machine with an open port) and register the server with it: + +```sh +# on the relay machine (the same checkout and gsdev): +gsdev relay --listen 0.0.0.0:7700 # makes /relay/secret on first run and says where it is +# on the Linux server, with that secret's first line: +install -m 600 /dev/stdin ~/.gentle-shell/agent/serve/relay-secret <<< 'the-relay-secret' +gsdev serve share --relay gsr://relay.example.com:7700 +``` + +`GENTLE_SHELL_RELAY_SECRET` works instead of the file, but the `--always` unit does not carry it. The long code then carries the relay (`r`); the short code works on the local network only. The relay sees only TLS ciphertext, so `--relay` cannot be combined with `--no-tls`. `serve status` says whether the relay is connected. `share` does not restart a server with running sessions to change its TLS or relay settings: stop them, or `serve stop`, first. + +**SSH tunnel instead.** A server kept on loopback (`gsdev serve --listen 127.0.0.1:8787`) is reached from the Mac through `ssh -N -L 8787:127.0.0.1:8787 you@linux-box` at `http://127.0.0.1:8787`, paired by hand ([step 5](#5-check-pair-by-hand-stop)). Keep the **same port on both ends**: the server accepts only its own port in `Host` (`421 bad_host` otherwise). On a network server, a DNS name other than the machine's hostname (for example a full MagicDNS name) needs `--allow-host `. + +### 5. Check, pair by hand, stop + +```sh +gsdev serve status # URL, pid, certificate fingerprint, relay, sessions +gsdev serve pair # one-time code for a client that pairs by hand (5 minutes, single use) +gsdev serve devices # paired devices; --revoke removes one +gsdev serve stop # stops the server; sessions and terminals keep running (--sessions stops sessions too) +``` + +The log is `/serve/server.log` (rewritten on each start; the journal under `--always`). Gentle Shell never launches the server on its own: once started it runs until `serve stop`, a reboot, or its process is killed. Sessions run on the Linux machine, so their `cwd` is a path there. + +By hand on the Linux machine, over plain HTTP on loopback: + +```sh +URL=$(jq -r .url ~/.gentle-shell/agent/serve/server.json) # http://127.0.0.1: +curl -s $URL/.well-known/gentle-shell +curl -sX POST $URL/api/pair -H 'Content-Type: application/json' -d '{"code":"ABCD-EFGH","name":"curl"}' +# → {"id":"dev_…","name":"curl","scopes":["sessions:read","sessions:operate","terminal"],"createdAt":"…","token":"gss_…"} +TOKEN=gss_… # shown once: keep it +curl -sX POST $URL/api/sessions -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' -d '{"cwd":"/home/you/project"}' +``` + +From another machine use `https://
:` and pin the fingerprint `serve status` prints; `curl -k` skips that check and is fit only for looking at `/.well-known/gentle-shell`. A `{"type":"prompt","message":"…"}` RPC command starts a model turn with the home's provider, exactly as typing in the session would. A device stays paired across server restarts (`/serve/devices.json`) until revoked. + +### Troubleshooting + +| Symptom | Cause and fix | +| --- | --- | +| `421 bad_host` | The `Host` header does not name this server and port: a tunnel with a different local port (use the same port on both ends), or a DNS name other than the hostname (use the IP, or `--allow-host `). | +| `400 tls_required` | Plain `http://` to a network server from another machine. Use `https://` (the app does), or `--no-tls` on a network that encrypts by itself. | +| `403 forbidden_origin` | The request carries an `Origin` other than the server's own (a web page on another origin). Native clients and curl send no `Origin`. | +| `401 unauthorized` | No `Authorization: Bearer `, a mistyped token, a revoked device, or a token paired with another home's server (devices are per home). Pair again. | +| `403 forbidden` | The token lacks the scope (for example an `admin` endpoint). Pair with `serve pair --scope …`. | +| `403 invalid_code` | The code is mistyped, expired (5 minutes), already used (the first attempt consumes it), or was minted by another home's server. Run `serve share` again. After 10 failures in a minute pairing answers `429 rate_limited` until the minute ends. | +| The app does not find the computer from the short code | Not the same network segment (another subnet or VLAN, guest Wi-Fi with client isolation, VPN or tailnet), or the firewall drops UDP on the port (`sudo ufw allow 8787` opens TCP and UDP). Paste the long code. `share` says when discovery is off on the server (its UDP port was taken). | +| `Connection refused` or a timeout from the Mac | The firewall drops the port, the server listens on loopback only (`serve status`; `serve share` reopens it on the network when no session runs), or it is not running. | +| `ports 8787-8796 are in use`, or `listen EADDRINUSE` | Something else listens: `ss -ltnup 'sport = :8787'`. Stop it or use `serve share --port `. `already running at …` means this home's server already runs (`serve status`). | +| `share` exits 1 about running sessions | Opening a loopback server to the network, changing its TLS or relay settings, or handing it to `--always` restarts it: stop its sessions or run `serve stop` first. | +| `serve status` says not running but `/serve/server.json` exists | A killed server (or a reboot) left it; the next start takes it over. Only if a reused pid makes `status` report a server that does not answer, confirm nothing listens (`ss -ltnp`) and remove `/serve/server.json` and `server.lock`. | +| A terminal answers `501 term_host_missing` | No `gentle-term-host`: [build it](#2-build-the-terminal-host) and put it in `/serve/bin/` or `GENTLE_TERM_HOST`. | +| `gentle-shell serve` opens a chat | That is the installed release, which has no `serve`; use the checkout (`gsdev serve`). | +| Gentle Tower: `the web app is not built` | Run `corepack pnpm run build:tower` in the checkout. | +| A forwarded page does not load from another computer | The firewall blocks the forward's port: `sudo ufw allow 8800:8899/tcp`. A server started without `--forward-ports` (not by `share`) gives forwards random ports: `serve stop`, then `serve share`. | +| A forward link answers `401` | The link was already used or is older than 60 s, and this browser has no cookie for the forward: open it again from the app. | +| A forward answers `502` | Nothing listens on that port of the server's loopback yet, or the page closed: start it, then reload. | +| `serve status` shows the relay `not connected (retrying)` | The relay is unreachable or refuses the server: check its address and port, and that `/serve/relay-secret` (or `GENTLE_SHELL_RELAY_SECRET`) holds the relay's secret. | + +## Not done yet + +- **WebSocket.** The RFC proposes one WebSocket per client with `hello`/`welcome` negotiation and `session/subscribe`. This phase uses HTTP + SSE instead, which needs no dependency (Gentle Shell ships one runtime dependency) and works from browsers, phones and curl. The contract — per-session `seq`, replay window, `snapshot-required`, dialog replay, per-request scopes, tickets for streams — is transport-independent, so a WebSocket transport can be added later behind it. +- **Native Desktop RPC frames.** Desktop RPC still travels as `/gentle:desktop` prompts and `setWidget` records inside each session; `/desktop` only correlates them. +- **Idle unload and crash resume.** Sessions run until stopped and survive a server restart, but not a reboot or a crash of their keeper: start them again with `sessionId` and Pi reopens the conversation from disk. +- **`message_update` coalescing.** Slow clients are dropped into a resync instead. +- **Narrower file scopes.** File access uses `sessions:read` and `sessions:operate`; separate `fs:read`/`fs:write` scopes, or a folder jail per device, are not there. +- **SSH bootstrap** (Phase 3), **the mobile web client and QR codes** (Phase 4). diff --git a/extensions/gentle-desktop-rpc.ts b/extensions/gentle-desktop-rpc.ts index 949bf77dd..500e06a04 100644 --- a/extensions/gentle-desktop-rpc.ts +++ b/extensions/gentle-desktop-rpc.ts @@ -46,6 +46,12 @@ import { DesktopBackgroundSubagentsBridge } from "../lib/desktop-background-suba import { DESKTOP_PROFILE_BINDING_EVENTS, DESKTOP_PROFILE_BINDING_METHODS, DesktopProfileBindingBridge } from "../lib/desktop-rpc-profile-binding.ts"; import { DESKTOP_AUTH_EVENTS, DESKTOP_AUTH_METHODS } from "../lib/desktop-rpc-auth.ts"; import { DesktopAuthBridge } from "../lib/desktop-auth-service.ts"; +import { DESKTOP_HOST_TOOLS_EVENTS, DESKTOP_HOST_TOOLS_METHODS, DESKTOP_HOST_TOOLS_REQUEST_BYTES } from "../lib/desktop-rpc-host-tools.ts"; +import { DesktopHostToolsBridge, type DesktopHostToolsOptions } from "../lib/desktop-host-tools-service.ts"; +import { DESKTOP_LOGIN_EVENTS, DESKTOP_LOGIN_METHODS } from "../lib/desktop-rpc-login.ts"; +import { DesktopLoginBridge, type DesktopLoginOptions } from "../lib/desktop-login-service.ts"; +import { DESKTOP_PACKAGES_EVENTS, DESKTOP_PACKAGES_METHODS } from "../lib/desktop-rpc-packages.ts"; +import { DesktopPackagesBridge, type DesktopPackagesOptions } from "../lib/desktop-packages-service.ts"; import { isInteractiveRpcHost } from "../lib/rpc-host.ts"; import type { DesktopChangeTimers, DesktopDirectoryWatch } from "../lib/desktop-rpc-config-watch.ts"; @@ -58,6 +64,12 @@ export interface DesktopRpcExtensionOptions { updateTimeoutMs?: number; /** Test seam for `list_agent_definitions`; production uses the session's discovery roots. */ agentDefinitionsLocation?: AgentDefinitionsLocationFactory; + /** Test seams for host tool calls: timers, the 10-minute cap and call ids. */ + hostTools?: DesktopHostToolsOptions; + /** Test seams for provider sign-in: the 15-minute cap and login ids. */ + login?: DesktopLoginOptions; + /** Test seams for package jobs: the CLI runner, the listing, the cap and job ids. */ + packages?: DesktopPackagesOptions; } function publisher(ctx: ExtensionContext): DesktopRpcPublish { @@ -119,14 +131,28 @@ export default function desktopRpc(pi: ExtensionAPI, options: DesktopRpcExtensio ...(options.updateTimeoutMs === undefined ? {} : { timeoutMs: options.updateTimeoutMs }), }); const packageStatus = new DesktopStatusBridge(pi); - const auth = new DesktopAuthBridge(); + const auth = new DesktopAuthBridge(() => pi.getThinkingLevel()); const profileBinding = new DesktopProfileBindingBridge(pi); const backgroundSubagents = new DesktopBackgroundSubagentsBridge(pi); const agentDefinitions = new DesktopAgentDefinitionsBridge(options.agentDefinitionsLocation === undefined ? {} : { location: options.agentDefinitionsLocation }); + // Host tools are tools the connected client runs on its own device: this + // process registers them with Pi and relays calls and results, nothing more. + const hostTools = new DesktopHostToolsBridge(pi, options.hostTools); + // Sign-in and API keys go through Pi's own model runtime and credential + // store; package installs run the same CLI a user would. + const login = new DesktopLoginBridge(options.login); + const packages = new DesktopPackagesBridge(options.packages); const domain: DesktopRpcDomain = (method, params) => { // Captured before any await: a background-subagents write dispatched before a // session reset must not run under the replacement session. const backgroundGeneration = backgroundSubagents.dispatchGeneration(); + const hostToolsOutcome = hostTools.handle(method, params); + if (hostToolsOutcome !== undefined) return hostToolsOutcome; + // Synchronous answers (`{ loginId }`, `{ jobId }`) are published before the flow's first event. + const loginOutcome = login.handle(method, params); + if (loginOutcome !== undefined) return loginOutcome; + const packagesOutcome = packages.handle(method, params); + if (packagesOutcome !== undefined) return packagesOutcome; const sessionsOutcome = sessionList.handle(method, params, dispatchingRequestId); if (sessionsOutcome !== undefined) return sessionsOutcome; // Config is the only synchronous bridge; permission, usage, design, jobs, @@ -168,9 +194,9 @@ export default function desktopRpc(pi: ExtensionAPI, options: DesktopRpcExtensio return updates.handle(method, params); })(); }; - const events = [...DESKTOP_CONFIG_EVENTS, DESKTOP_PERMISSION_EVENT, ...DESKTOP_USAGE_EVENTS, ...DESKTOP_DESIGN_EVENTS, ...DESKTOP_JOBS_EVENTS, ...DESKTOP_PROFILES_EVENTS, ...DESKTOP_AGENTS_EVENTS, ...DESKTOP_SESSIONS_EVENTS, ...DESKTOP_CHANGES_EVENTS, ...DESKTOP_REVIEW_EVENTS, ...DESKTOP_STATS_EVENTS, ...DESKTOP_UPDATES_EVENTS, ...DESKTOP_AGENT_DEFINITIONS_EVENTS, ...DESKTOP_STATUS_EVENTS, ...DESKTOP_BACKGROUND_SUBAGENTS_EVENTS, ...DESKTOP_PROFILE_BINDING_EVENTS, ...DESKTOP_AUTH_EVENTS]; + const events = [...DESKTOP_CONFIG_EVENTS, DESKTOP_PERMISSION_EVENT, ...DESKTOP_USAGE_EVENTS, ...DESKTOP_DESIGN_EVENTS, ...DESKTOP_JOBS_EVENTS, ...DESKTOP_PROFILES_EVENTS, ...DESKTOP_AGENTS_EVENTS, ...DESKTOP_SESSIONS_EVENTS, ...DESKTOP_CHANGES_EVENTS, ...DESKTOP_REVIEW_EVENTS, ...DESKTOP_STATS_EVENTS, ...DESKTOP_UPDATES_EVENTS, ...DESKTOP_AGENT_DEFINITIONS_EVENTS, ...DESKTOP_STATUS_EVENTS, ...DESKTOP_BACKGROUND_SUBAGENTS_EVENTS, ...DESKTOP_PROFILE_BINDING_EVENTS, ...DESKTOP_AUTH_EVENTS, ...DESKTOP_HOST_TOOLS_EVENTS, ...DESKTOP_LOGIN_EVENTS, ...DESKTOP_PACKAGES_EVENTS]; const router = new DesktopRpcRouter( - ["capabilities", "get_snapshot", ...DESKTOP_CONFIG_METHODS, ...DESKTOP_PERMISSION_METHODS, ...DESKTOP_USAGE_METHODS, ...DESKTOP_DESIGN_METHODS, ...DESKTOP_JOBS_METHODS, ...DESKTOP_PROFILES_METHODS, ...DESKTOP_AGENTS_METHODS, ...DESKTOP_SESSIONS_METHODS, ...DESKTOP_CHANGES_METHODS, ...DESKTOP_REVIEW_METHODS, ...DESKTOP_STATS_METHODS, ...DESKTOP_UPDATES_METHODS, ...DESKTOP_AGENT_DEFINITIONS_METHODS, ...DESKTOP_STATUS_METHODS, ...DESKTOP_BACKGROUND_SUBAGENTS_METHODS, ...DESKTOP_PROFILE_BINDING_METHODS, ...DESKTOP_AUTH_METHODS], + ["capabilities", "get_snapshot", ...DESKTOP_CONFIG_METHODS, ...DESKTOP_PERMISSION_METHODS, ...DESKTOP_USAGE_METHODS, ...DESKTOP_DESIGN_METHODS, ...DESKTOP_JOBS_METHODS, ...DESKTOP_PROFILES_METHODS, ...DESKTOP_AGENTS_METHODS, ...DESKTOP_SESSIONS_METHODS, ...DESKTOP_CHANGES_METHODS, ...DESKTOP_REVIEW_METHODS, ...DESKTOP_STATS_METHODS, ...DESKTOP_UPDATES_METHODS, ...DESKTOP_AGENT_DEFINITIONS_METHODS, ...DESKTOP_STATUS_METHODS, ...DESKTOP_BACKGROUND_SUBAGENTS_METHODS, ...DESKTOP_PROFILE_BINDING_METHODS, ...DESKTOP_AUTH_METHODS, ...DESKTOP_HOST_TOOLS_METHODS, ...DESKTOP_LOGIN_METHODS, ...DESKTOP_PACKAGES_METHODS], // `session_snapshot` is advertised only while the feed owner seam is wired. () => (sessions.wired ? [...events, ...DESKTOP_SESSION_EVENTS] : events), () => config.snapshotState(), @@ -182,6 +208,8 @@ export default function desktopRpc(pi: ExtensionAPI, options: DesktopRpcExtensio // prompts concurrently, and an answer that settled after the teardown would // otherwise be dropped with the old session. router.setGate(() => (sessionList.switchInFlight() ? SESSION_SWITCHING : undefined)); + // A host tool result may carry screenshots; registering a full set of tools is larger than a usual request too. + router.setRequestLimits(DESKTOP_HOST_TOOLS_REQUEST_BYTES); pi.on("session_start", (_event, ctx) => { permissions.reset(); @@ -202,6 +230,9 @@ export default function desktopRpc(pi: ExtensionAPI, options: DesktopRpcExtensio backgroundSubagents.reset(); profileBinding.reset(); auth.reset(); + hostTools.reset(); + login.reset(); + packages.reset(); router.stop(); activePublish = undefined; retiredPublish = undefined; @@ -212,6 +243,12 @@ export default function desktopRpc(pi: ExtensionAPI, options: DesktopRpcExtensio sessions.attach(ctx); activePublish = publisher(ctx); router.start(activePublish); + // The agent's calls to host tools become `host_tool_call` / `host_tool_cancel` + // events; the client answers with `host_tool_result`. + hostTools.wire((event, data) => router.emit(event, data)); + // Sign-in prompts and package job output become `login_*` / `package_*` events. + login.wire((event, data) => router.emit(event, data)); + packages.wire((event, data) => router.emit(event, data)); // Header-driven usage snapshots (Claude's 5h/7d windows, Codex SSE // headers) become ordered `rate_limit` events through the router. usage.wire((event, data) => router.emit(event, data)); @@ -278,6 +315,9 @@ export default function desktopRpc(pi: ExtensionAPI, options: DesktopRpcExtensio backgroundSubagents.reset(); profileBinding.reset(); auth.reset(); + hostTools.reset(); + login.reset(); + packages.reset(); router.stop(); }); @@ -312,6 +352,9 @@ export default function desktopRpc(pi: ExtensionAPI, options: DesktopRpcExtensio backgroundSubagents.attach(ctx); profileBinding.attach(ctx); auth.attach(ctx); + hostTools.attach(ctx); + login.attach(ctx); + packages.attach(ctx); dispatchingRequestId = desktopRequestId(args); let pending: void | Promise; try { diff --git a/lib/desktop-auth-service.ts b/lib/desktop-auth-service.ts index f7cdf8b2e..a2326afb8 100644 --- a/lib/desktop-auth-service.ts +++ b/lib/desktop-auth-service.ts @@ -1,6 +1,7 @@ -// Gentle Desktop credential-status bridge: answers `get_auth_status` and -// `reload_credentials` from the session's own model registry -// (`ctx.modelRegistry`) and projects it with `lib/desktop-rpc-auth.ts`. +// Gentle Desktop credential-status bridge: answers `get_auth_status`, +// `reload_credentials` and `list_available_models` from the session's own +// model registry (`ctx.modelRegistry`) and projects it with +// `lib/desktop-rpc-auth.ts`. // // `reload_credentials` calls `modelRegistry.refresh({ allowNetwork: false })`: // Pi rebuilds which providers are configured and which models are available @@ -9,29 +10,39 @@ // themselves are already re-read by Pi on each request. Concurrent reloads // share one refresh. +import { getSupportedThinkingLevels, type Api, type Model } from "@earendil-works/pi-ai"; import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; import type { DesktopRpcOutcome } from "./desktop-rpc.ts"; import { AUTH_UNAVAILABLE, failedProviderIds, INVALID_GET_AUTH_STATUS, + INVALID_LIST_AVAILABLE_MODELS, INVALID_RELOAD_CREDENTIALS, isDesktopAuthRegistry, parseEmptyParams, projectAuthStatus, + projectAvailableModels, RELOAD_FAILED, type DesktopAuthRegistry, } from "./desktop-rpc-auth.ts"; /** * The Desktop domain slice for credential status. No event and no write: the - * credential store is Pi's, and sign-in and sign-out stay out of scope. A reset - * drops the bound context and the answer of any call that started before it. + * credential store is Pi's, and sign-in, API keys and sign-out are the login + * slice's (`lib/desktop-login-service.ts`). A reset drops the bound context and + * the answer of any call that started before it. */ export class DesktopAuthBridge { private host: ExtensionContext | undefined; private generation = 0; private inFlight: { registry: DesktopAuthRegistry; run: Promise<{ aborted: boolean; errors: ReadonlyMap }> } | undefined; + /** The session's thinking level (`pi.getThinkingLevel()`), for `list_available_models`' `current`. */ + private readonly thinkingLevel: () => string | undefined; + + constructor(thinkingLevel: () => string | undefined = () => undefined) { + this.thinkingLevel = thinkingLevel; + } attach(context: ExtensionContext): void { this.host = context; @@ -48,6 +59,20 @@ export class DesktopAuthBridge { } async handle(method: string, params: Record): Promise { + if (method === "list_available_models") { + if (!parseEmptyParams(params)) return { ok: false, error: INVALID_LIST_AVAILABLE_MODELS }; + const registry = this.registry(); + if (!registry || typeof registry.getAvailable !== "function") return { ok: false, error: AUTH_UNAVAILABLE }; + try { + let level: string | undefined; + try { level = this.thinkingLevel(); } catch { level = undefined; } + const current = (this.host as { model?: Model } | undefined)?.model; + // Pi's `get_available_thinking_levels`: the current model's levels, every level without one. + return { ok: true, data: { ...projectAvailableModels(registry.getAvailable(), current, level, getSupportedThinkingLevels) } }; + } catch { + return { ok: false, error: AUTH_UNAVAILABLE }; + } + } if (method === "get_auth_status") { if (!parseEmptyParams(params)) return { ok: false, error: INVALID_GET_AUTH_STATUS }; const registry = this.registry(); diff --git a/lib/desktop-host-tools-service.ts b/lib/desktop-host-tools-service.ts new file mode 100644 index 000000000..1aebd0bc5 --- /dev/null +++ b/lib/desktop-host-tools-service.ts @@ -0,0 +1,392 @@ +// Gentle Desktop host tools bridge: answers `set_host_tools` and +// `host_tool_result`, and turns the agent's calls to a host tool into +// `host_tool_call` / `host_tool_cancel` events (contract in +// `lib/desktop-rpc-host-tools.ts`). +// +// Each host tool is a real Pi tool registered with `pi.registerTool()` after +// startup (Pi refreshes its tool registry and system prompt at once, so the +// next model request sees it), with the client's description, its JSON Schema +// as `parameters`, and its guidelines as `promptGuidelines` (bullets Pi adds to +// the system prompt only while the tool is active). Pi has no way to remove a +// registered tool, so unregistering re-registers it with `exposure: "hidden"`: +// registered but unreachable, never declared to the model, guidelines left out. +// Registering the name again later makes it `direct` and active again. +// +// Several providers (the Mac app and a phone) may offer the same name. The +// model sees one tool: the definition of the provider that registered it most +// recently; when that provider drops it, the next one's definition takes over. +// A call goes to the most recently active provider that offers the tool and is +// connected (`set_host_activity`, sent by `gentle-shell serve`); without that +// list (one client over stdio) to the provider that registered most recently. +// +// The tool's `execute` never runs client code: it emits the call, waits for the +// client's content, and gives up when the turn is aborted or after ten minutes. +// +// `host_message` hands a custom message to `pi.sendMessage` (persisted in the +// session like any extension's custom message). `set_host_context` keeps one +// hidden custom message per provider that a `before_agent_start` handler adds +// to every run while it is set; a session change drops them all. + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { randomBytes } from "node:crypto"; +import type { DesktopRpcOutcome } from "./desktop-rpc.ts"; +import { + ALREADY_ANSWERED, + DESKTOP_HOST_TOOLS_LIMITS, + HOST_MESSAGES_UNAVAILABLE, + HOST_TOOLS_UNAVAILABLE, + hostContextType, + hostToolOfflineText, + modelGuidelines, + parseHostMessage, + parseHostToolProgress, + parseHostToolResult, + parseSetHostActivity, + parseSetHostContext, + parseSetHostTools, + promptSnippet, + TOO_MANY_CONTEXTS, + UNKNOWN_CALL, + type HostToolContent, + type HostToolSpec, +} from "./desktop-rpc-host-tools.ts"; + +export type DesktopHostToolsEmit = (event: string, data: Record) => void; + +export interface DesktopHostToolsTimers { + setTimeout(callback: () => void, ms: number): unknown; + clearTimeout(handle: unknown): void; +} + +export interface DesktopHostToolsOptions { + timers?: DesktopHostToolsTimers; + callTimeoutMs?: number; + newCallId?: () => string; + /** Epoch milliseconds, for the `deadlineMs` a `host_tool_progress` answers with. */ + now?: () => number; +} + +/** + * What a host tool call resolves to; Pi shows `content` to the model, as an + * error when `isError`. `details` is the client's own `details` when it sent + * one, otherwise who answered. + */ +export interface HostToolCallResult { + content: HostToolContent[]; + details: Record; + isError?: boolean; +} + +interface HostContext { + content: string; + details?: Record; + /** Removes the provider's `before_agent_start` handler. */ + off: () => void; +} + +interface PendingCall { + provider: string; + tool: string; + finish: (result: HostToolCallResult) => void; + /** Restarts the no-answer deadline; returns the new deadline in epoch ms. */ + extend: () => number; +} + +const realTimers: DesktopHostToolsTimers = { + setTimeout(callback, ms) { + const handle = setTimeout(callback, ms); + handle.unref?.(); + return handle; + }, + clearTimeout: (handle) => clearTimeout(handle as NodeJS.Timeout), +}; + +const HIDDEN_PARAMETERS = { type: "object", properties: {} }; + +function errorResult(provider: string, text: string, callId?: string): HostToolCallResult { + return { content: [{ type: "text", text }], details: { provider, ...(callId === undefined ? {} : { callId }) }, isError: true }; +} + +/** + * The Desktop domain slice for host tools. Registrations and calls belong to + * the running session: a reset (new session, switch, shutdown) hides every + * host tool and fails every call still waiting, so a client registers again + * in the next session. + */ +export class DesktopHostToolsBridge { + private readonly pi: ExtensionAPI; + private readonly timers: DesktopHostToolsTimers; + private readonly callTimeoutMs: number; + private readonly newCallId: () => string; + private readonly now: () => number; + private emit: DesktopHostToolsEmit | undefined; + /** Host tools by name: every provider offering it, oldest registration first; the last one's definition is the active one. */ + private readonly tools = new Map>(); + /** Connected providers, most recently active first, when the transport knows them (serve); `undefined` over stdio. */ + private active: string[] | undefined; + /** Every name this bridge registered with Pi, active or hidden: never a collision for a later host. */ + private readonly owned = new Set(); + private readonly calls = new Map(); + private readonly settled: string[] = []; + private readonly contexts = new Map(); + private isIdle: () => boolean = () => true; + + constructor(pi: ExtensionAPI, options: DesktopHostToolsOptions = {}) { + this.pi = pi; + this.timers = options.timers ?? realTimers; + this.callTimeoutMs = options.callTimeoutMs ?? DESKTOP_HOST_TOOLS_LIMITS.callTimeoutMs; + this.newCallId = options.newCallId ?? (() => `htc_${randomBytes(12).toString("hex")}`); + this.now = options.now ?? Date.now; + } + + /** Events go out through the Desktop router while the session's transport is up. */ + wire(emit: DesktopHostToolsEmit): void { + this.emit = emit; + } + + /** Whether the agent is idle, read from the dispatching command's context when `host_message` says `auto`. */ + attach(ctx: { isIdle(): boolean }): void { + this.isIdle = () => ctx.isIdle(); + } + + reset(): void { + this.emit = undefined; + this.isIdle = () => true; + this.active = undefined; + for (const [callId, call] of [...this.calls]) call.finish(errorResult(call.provider, `${call.tool} was stopped: the session ended before ${call.provider} answered.`, callId)); + for (const name of [...this.tools.keys()]) this.hide(name); + this.tools.clear(); + for (const provider of [...this.contexts.keys()]) this.clearContext(provider); + } + + handle(method: string, params: Record): DesktopRpcOutcome | undefined { + if (method === "set_host_tools") return this.setHostTools(params); + if (method === "host_message") return this.message(params); + if (method === "set_host_context") return this.setContext(params); + if (method === "host_tool_result") return this.answer(params); + if (method === "host_tool_progress") return this.progress(params); + if (method === "set_host_activity") return this.setActivity(params); + return undefined; + } + + private setHostTools(params: Record): DesktopRpcOutcome { + const parsed = parseSetHostTools(params); + if (parsed.ok === false) return { ok: false, error: parsed.error }; + const { provider, tools } = parsed.value; + if (typeof this.pi.registerTool !== "function" || typeof this.pi.getAllTools !== "function") return { ok: false, error: HOST_TOOLS_UNAVAILABLE }; + try { + const taken = new Set(this.pi.getAllTools().map((tool) => tool.name).filter((name) => !this.owned.has(name))); + const registered: string[] = []; + const rejected: Array<{ name: string; reason: string }> = []; + const accepted: HostToolSpec[] = []; + for (const spec of tools) { + if (taken.has(spec.name)) rejected.push({ name: spec.name, reason: "A built-in or extension tool already has this name" }); + else accepted.push(spec); + } + const keep = new Set(accepted.map((spec) => spec.name)); + for (const [name, entries] of [...this.tools]) { + if (keep.has(name) || !entries.some((entry) => entry.provider === provider)) continue; + this.withoutProvider(name, provider); + } + for (const spec of accepted) { + // The newest registration is the definition the model sees. + const others = (this.tools.get(spec.name) ?? []).filter((entry) => entry.provider !== provider); + this.tools.set(spec.name, [...others, { provider, spec }]); + this.register(spec); + registered.push(spec.name); + } + return { ok: true, data: { registered, rejected } }; + } catch { + return { ok: false, error: HOST_TOOLS_UNAVAILABLE }; + } + } + + /** Drops one provider of `name`; the next provider's definition takes over, or the tool is hidden. */ + private withoutProvider(name: string, provider: string): void { + const rest = (this.tools.get(name) ?? []).filter((entry) => entry.provider !== provider); + if (rest.length === 0) { + this.tools.delete(name); + this.hide(name); + return; + } + this.tools.set(name, rest); + this.register(rest.at(-1)!.spec); + } + + private setActivity(params: Record): DesktopRpcOutcome { + const parsed = parseSetHostActivity(params); + if (parsed.ok === false) return { ok: false, error: parsed.error }; + this.active = parsed.value.providers; + return { ok: true, data: { set: true } }; + } + + /** Who runs a call to `name`: the most recently active connected provider of it, else its newest registration. */ + private route(name: string): string | undefined { + const entries = this.tools.get(name); + if (!entries) return undefined; + const offering = new Set(entries.map((entry) => entry.provider)); + return this.active?.find((provider) => offering.has(provider)) ?? entries.at(-1)!.provider; + } + + private register(spec: HostToolSpec): void { + const guidelines = modelGuidelines(spec); + this.owned.add(spec.name); + this.pi.registerTool({ + name: spec.name, + label: spec.label, + description: spec.description, + promptSnippet: promptSnippet(spec), + ...(guidelines.length === 0 ? {} : { promptGuidelines: guidelines }), + // A client's JSON Schema, not a TypeBox value: Pi validates arguments with a JSON Schema compiler. + parameters: spec.parameters as never, + exposure: "direct", + execute: (_toolCallId, args, signal) => this.call(spec.name, args as Record, signal), + }); + } + + private hide(name: string): void { + try { + this.pi.registerTool({ + name, + label: name, + description: `${name} is not provided right now.`, + parameters: HIDDEN_PARAMETERS as never, + exposure: "hidden", + execute: async () => errorResult("none", `${name} is not provided right now.`), + }); + } catch { + // A torn-down extension instance cannot register; its tools went with its session. + } + } + + private call(name: string, args: Record, signal: AbortSignal | undefined): Promise { + const provider = this.route(name); + if (provider === undefined) return Promise.resolve(errorResult("none", `${name} is not provided right now.`)); + const emit = this.emit; + if (!emit) return Promise.resolve(errorResult(provider, hostToolOfflineText(name, provider))); + if (signal?.aborted) return Promise.resolve(errorResult(provider, `${name} was cancelled.`)); + const callId = this.newCallId(); + const { promise, resolve } = Promise.withResolvers(); + let timer: unknown; + const onAbort = () => { + finish(errorResult(provider, `${name} was cancelled.`, callId)); + this.cancel(callId); + }; + const finish = (result: HostToolCallResult) => { + if (!this.calls.delete(callId)) return; + this.timers.clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + this.settled.push(callId); + if (this.settled.length > DESKTOP_HOST_TOOLS_LIMITS.settledMemory) this.settled.shift(); + resolve(result); + }; + const expire = () => { + finish(errorResult(provider, `${name} got no answer from ${provider} within ${Math.round(this.callTimeoutMs / 60_000)} minutes.`, callId)); + this.cancel(callId); + }; + const extend = () => { + this.timers.clearTimeout(timer); + timer = this.timers.setTimeout(expire, this.callTimeoutMs); + return this.now() + this.callTimeoutMs; + }; + this.calls.set(callId, { provider, tool: name, finish, extend }); + timer = this.timers.setTimeout(expire, this.callTimeoutMs); + signal?.addEventListener("abort", onAbort, { once: true }); + try { + emit("host_tool_call", { callId, provider, tool: name, args }); + } catch { + finish(errorResult(provider, hostToolOfflineText(name, provider), callId)); + } + return promise; + } + + private cancel(callId: string): void { + try { + this.emit?.("host_tool_cancel", { callId }); + } catch { + /* the call is already settled; a lost cancel only leaves the client working */ + } + } + + private answer(params: Record): DesktopRpcOutcome { + const parsed = parseHostToolResult(params); + if (parsed.ok === false) return { ok: false, error: parsed.error }; + const { callId, content, isError, details } = parsed.value; + const call = this.calls.get(callId); + if (!call) return { ok: false, error: this.settled.includes(callId) ? ALREADY_ANSWERED : UNKNOWN_CALL }; + call.finish({ content, details: details ?? { provider: call.provider, callId }, ...(isError ? { isError: true } : {}) }); + return { ok: true, data: { accepted: true } }; + } + + /** The client is still working on the call: its no-answer deadline starts over. */ + private progress(params: Record): DesktopRpcOutcome { + const parsed = parseHostToolProgress(params); + if (parsed.ok === false) return { ok: false, error: parsed.error }; + const call = this.calls.get(parsed.value.callId); + if (!call) return { ok: false, error: this.settled.includes(parsed.value.callId) ? ALREADY_ANSWERED : UNKNOWN_CALL }; + return { ok: true, data: { extended: true, deadlineMs: call.extend() } }; + } + + /** + * `auto` is what a client wants almost always: start a run when the agent is + * idle (unless `triggerTurn` is false), steer the running one otherwise. The + * other modes are Pi's own `deliverAs`, with `triggerTurn` passed as given. + */ + private message(params: Record): DesktopRpcOutcome { + const parsed = parseHostMessage(params); + if (parsed.ok === false) return { ok: false, error: parsed.error }; + const { customType, content, display, details, deliver, triggerTurn } = parsed.value; + if (typeof this.pi.sendMessage !== "function") return { ok: false, error: HOST_MESSAGES_UNAVAILABLE }; + const options = deliver === "auto" + ? (this.isIdle() ? { triggerTurn: triggerTurn ?? true } : { deliverAs: "steer" as const }) + : { deliverAs: deliver, ...(triggerTurn === undefined ? {} : { triggerTurn }) }; + try { + this.pi.sendMessage({ customType, content, display, ...(details === undefined ? {} : { details }) }, options); + } catch { + return { ok: false, error: HOST_MESSAGES_UNAVAILABLE }; + } + return { ok: true, data: { delivered: true } }; + } + + private setContext(params: Record): DesktopRpcOutcome { + const parsed = parseSetHostContext(params); + if (parsed.ok === false) return { ok: false, error: parsed.error }; + const { provider, content, details } = parsed.value; + if (content.length === 0) { + this.clearContext(provider); + return { ok: true, data: { set: true } }; + } + const current = this.contexts.get(provider); + if (current) { + this.contexts.set(provider, { content, ...(details === undefined ? {} : { details }), off: current.off }); + return { ok: true, data: { set: true } }; + } + if (this.contexts.size >= DESKTOP_HOST_TOOLS_LIMITS.contextProviders) return { ok: false, error: TOO_MANY_CONTEXTS }; + if (typeof this.pi.on !== "function") return { ok: false, error: HOST_MESSAGES_UNAVAILABLE }; + const customType = hostContextType(provider); + let off: unknown; + try { + // One handler per provider: a `before_agent_start` result carries one message. + off = this.pi.on("before_agent_start", () => { + const entry = this.contexts.get(provider); + if (!entry) return undefined; + return { message: { customType, content: entry.content, display: false, ...(entry.details === undefined ? {} : { details: entry.details }) } }; + }); + } catch { + return { ok: false, error: HOST_MESSAGES_UNAVAILABLE }; + } + this.contexts.set(provider, { content, ...(details === undefined ? {} : { details }), off: typeof off === "function" ? (off as () => void) : () => {} }); + return { ok: true, data: { set: true } }; + } + + private clearContext(provider: string): void { + const entry = this.contexts.get(provider); + if (!entry) return; + this.contexts.delete(provider); + try { + entry.off(); + } catch { + // A torn-down extension instance took its handlers with it. + } + } +} diff --git a/lib/desktop-login-service.ts b/lib/desktop-login-service.ts new file mode 100644 index 000000000..d1bee8ac8 --- /dev/null +++ b/lib/desktop-login-service.ts @@ -0,0 +1,385 @@ +// Gentle Desktop sign-in bridge: `login_start` / `login_complete` / +// `login_cancel` run Pi's own provider sign-in for a client on another device, +// and `set_api_key` / `remove_credentials` save or remove a stored credential. +// +// Everything goes through Pi's model runtime, the one `/login` and `/logout` +// use (`ModelRuntime.login` / `logout`, behind the session's +// `ctx.modelRegistry`): the provider's own flow, Pi's credential store +// (`auth.json`, owner-only), and Pi's synchronization of the provider's models. +// Then the session's registry is refreshed as `reload_credentials` does, so the +// new models are available without a restart. +// +// The flow's interaction is what crosses: each thing Pi's login dialog would +// show is a `login_prompt` event, and each question waits for the client's +// `login_complete`. A browser sign-in whose provider redirects to a loopback +// callback (`http://localhost:1455/…`) on this machine cannot reach it from the +// client's browser: the client intercepts that redirect and sends the full URL +// as the answer to the paste prompt Pi raises beside its callback, and Pi +// completes the exchange exactly as its callback would. + +import { randomBytes } from "node:crypto"; +import { getAgentDir, SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent"; +import type { DesktopRpcOutcome } from "./desktop-rpc.ts"; +import { + DESKTOP_LOGIN_LIMITS, + INTERACTIVE_SETUP_REQUIRED, + INVALID_CHOICE, + INVALID_LOGIN_CANCEL, + INVALID_LOGIN_COMPLETE, + INVALID_LOGIN_START, + INVALID_REMOVE_CREDENTIALS, + INVALID_SET_API_KEY, + LOGIN_IN_PROGRESS, + LOGIN_UNAVAILABLE, + LOGIN_UNSUPPORTED, + loginErrorText, + NO_PENDING_PROMPT, + parseLoginCancel, + parseLoginComplete, + parseLoginStart, + parseRemoveCredentials, + parseSetApiKey, + promptForEvent, + promptForQuestion, + redirectPrefixOf, + REMOVE_FAILED, + SAVE_FAILED, + UNKNOWN_LOGIN, + UNKNOWN_PROVIDER, + type LoginAuthEvent, + type LoginAuthPrompt, + type LoginStartKind, +} from "./desktop-rpc-login.ts"; + +/** Pi's `AuthInteraction`, structurally. */ +export interface LoginInteraction { + signal: AbortSignal; + prompt(prompt: LoginAuthPrompt): Promise; + notify(event: LoginAuthEvent): void; +} + +/** Pi's provider definition: only which sign-ins it has is read. */ +export interface LoginProviderDefinition { + auth?: { oauth?: unknown; apiKey?: { login?: unknown } }; +} + +/** The part of Pi's `ModelRuntime` this bridge drives. */ +export interface LoginRuntime { + getProvider(providerId: string): LoginProviderDefinition | undefined; + login(providerId: string, type: LoginStartKind, interaction: LoginInteraction, options?: { getDeviceId?: () => string }): Promise; + logout(providerId: string, options?: { signal?: AbortSignal }): Promise; + listCredentials(options?: { signal?: AbortSignal }): Promise>; +} + +export type DesktopLoginEmit = (event: string, data: Record) => void; + +export interface DesktopLoginOptions { + /** A sign-in that has not finished by then is cancelled (15 minutes). */ + timeoutMs?: number; + newLoginId?: () => string; +} + +function isLoginRuntime(value: unknown): value is LoginRuntime { + const runtime = value as Partial | undefined; + return !!runtime && typeof runtime.getProvider === "function" && typeof runtime.login === "function" + && typeof runtime.logout === "function" && typeof runtime.listCredentials === "function"; +} + +/** Pi's `CredentialSynchronizationError`: the credential was saved, only the local model refresh failed. */ +function credentialsCommitted(error: unknown): boolean { + return error instanceof Error && error.name === "CredentialSynchronizationError"; +} + +interface PendingPrompt { + resolve: (value: string) => void; + reject: (error: Error) => void; + options?: ReadonlySet; +} + +interface ActiveLogin { + loginId: string; + provider: string; + controller: AbortController; + timer: NodeJS.Timeout; + pending?: PendingPrompt; + /** The loopback callback of the last authorization URL, for a pasted redirect. */ + redirectPrefix?: string; + /** Why the flow was aborted, when it was. */ + ended?: string; +} + +/** Where a session's sign-ins go: its model registry (for the reload) and Pi's runtime behind it. */ +interface SessionAuth { + runtime: LoginRuntime; + refresh: () => Promise; + deviceId: () => string; +} + +export class DesktopLoginBridge { + private host: ExtensionContext | undefined; + private emit: DesktopLoginEmit | undefined; + private generation = 0; + private readonly logins = new Map(); + /** Providers with a sign-in, a key save or a removal under way: one at a time per provider. */ + private readonly busy = new Set(); + private readonly timeoutMs: number; + private readonly newLoginId: () => string; + + constructor(options: DesktopLoginOptions = {}) { + this.timeoutMs = options.timeoutMs ?? DESKTOP_LOGIN_LIMITS.timeoutMs; + this.newLoginId = options.newLoginId ?? (() => `login_${randomBytes(8).toString("hex")}`); + } + + attach(context: ExtensionContext): void { + this.host = context; + } + + wire(emit: DesktopLoginEmit): void { + this.emit = emit; + } + + /** A session change ends every sign-in still running; its events would reach no one. */ + reset(): void { + this.generation += 1; + this.host = undefined; + this.emit = undefined; + for (const login of [...this.logins.values()]) this.end(login, "The session ended"); + } + + private session(): SessionAuth | undefined { + const host = this.host; + try { + const registry = (host as { modelRegistry?: unknown } | undefined)?.modelRegistry as { runtime?: unknown; refresh?: (options: { allowNetwork: boolean }) => Promise } | undefined; + const runtime = registry?.runtime; + if (!isLoginRuntime(runtime) || typeof registry?.refresh !== "function") return undefined; + const cwd = host!.cwd; + return { + runtime, + // `reload_credentials` semantics: rebuild which providers are configured, never fetch a catalog. + refresh: () => registry.refresh!({ allowNetwork: false }), + // The stable id of this installation, which OpenAI's sign-in sends; Pi's own `/login` uses the same. + deviceId: () => SettingsManager.create(cwd, getAgentDir()).getOrCreateDeviceId(), + }; + } catch { + return undefined; + } + } + + handle(method: string, params: Record): DesktopRpcOutcome | Promise | undefined { + switch (method) { + case "login_start": return this.start(params); + case "login_complete": return this.complete(params); + case "login_cancel": return this.cancel(params); + case "set_api_key": return this.setApiKey(params); + case "remove_credentials": return this.removeCredentials(params); + default: return undefined; + } + } + + private start(params: Record): DesktopRpcOutcome { + const request = parseLoginStart(params); + if (!request) return { ok: false, error: INVALID_LOGIN_START }; + const session = this.session(); + if (!session) return { ok: false, error: LOGIN_UNAVAILABLE }; + let auth: LoginProviderDefinition["auth"]; + try { + const provider = session.runtime.getProvider(request.provider); + if (!provider) return { ok: false, error: UNKNOWN_PROVIDER }; + auth = provider.auth; + } catch { + return { ok: false, error: LOGIN_UNAVAILABLE }; + } + const kind: LoginStartKind = request.kind ?? (auth?.oauth ? "oauth" : "api_key"); + if (kind === "oauth" ? !auth?.oauth : typeof auth?.apiKey?.login !== "function") return { ok: false, error: LOGIN_UNSUPPORTED }; + if (this.busy.has(request.provider)) return { ok: false, error: LOGIN_IN_PROGRESS }; + const loginId = this.newLoginId(); + const controller = new AbortController(); + const login: ActiveLogin = { + loginId, + provider: request.provider, + controller, + timer: setTimeout(() => this.end(login, "Sign-in timed out"), this.timeoutMs), + }; + login.timer.unref?.(); + this.logins.set(loginId, login); + this.busy.add(request.provider); + // The flow starts after this answer is published, so `{ loginId }` precedes its first `login_prompt`. + setImmediate(() => void this.run(login, kind, session)); + return { ok: true, data: { loginId } }; + } + + private async run(login: ActiveLogin, kind: LoginStartKind, session: SessionAuth): Promise { + const generation = this.generation; + const send = (event: string, data: Record) => { + if (generation !== this.generation) return; + try { + this.emit?.(event, data); + } catch { + /* the transport is gone; the flow goes on */ + } + }; + const interaction: LoginInteraction = { + signal: login.controller.signal, + notify: (event) => { + if (event?.type === "auth_url" && typeof event.url === "string") login.redirectPrefix = redirectPrefixOf(event.url) ?? login.redirectPrefix; + const data = promptForEvent(login.loginId, event); + if (data) send("login_prompt", { ...data }); + }, + prompt: (prompt) => this.ask(login, prompt, send), + }; + let error: string | undefined; + if (login.controller.signal.aborted) error = login.ended; + else { + try { + await session.runtime.login(login.provider, kind, interaction, { getDeviceId: session.deviceId }); + } catch (failure) { + if (!credentialsCommitted(failure)) error = login.ended ?? loginErrorText(failure); + } + } + clearTimeout(login.timer); + this.drop(login); + if (error === undefined) { + try { + await session.refresh(); + } catch { + /* the credential is saved; the next reload_credentials picks it up */ + } + } + send("login_finished", { loginId: login.loginId, provider: login.provider, ok: error === undefined, ...(error === undefined ? {} : { error }) }); + } + + /** One question of the flow: a `login_prompt` now, the answer when `login_complete` brings it. */ + private ask(login: ActiveLogin, prompt: LoginAuthPrompt, send: DesktopLoginEmit): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + if (login.controller.signal.aborted || !this.logins.has(login.loginId)) { + reject(new Error(login.ended ?? "Sign-in cancelled")); + return promise; + } + // Pi asks one question at a time; a new one replaces any left unanswered. + login.pending?.reject(new Error("Superseded by another question")); + const pending: PendingPrompt = { + resolve, + reject, + ...(prompt.type === "select" ? { options: new Set(prompt.options.map((option) => String(option.id))) } : {}), + }; + login.pending = pending; + // The flow withdraws a question it no longer needs (its own callback received the redirect first). + prompt.signal?.addEventListener("abort", () => { + if (login.pending === pending) login.pending = undefined; + reject(new Error("Sign-in cancelled")); + }, { once: true }); + send("login_prompt", { ...promptForQuestion(login.loginId, prompt, login.redirectPrefix) }); + return promise; + } + + private complete(params: Record): DesktopRpcOutcome { + const request = parseLoginComplete(params); + if (!request) return { ok: false, error: INVALID_LOGIN_COMPLETE }; + const login = this.logins.get(request.loginId); + if (!login) return { ok: false, error: UNKNOWN_LOGIN }; + const pending = login.pending; + if (!pending) return { ok: false, error: NO_PENDING_PROMPT }; + if (pending.options && !pending.options.has(request.value)) return { ok: false, error: INVALID_CHOICE }; + login.pending = undefined; + pending.resolve(request.value); + return { ok: true, data: { accepted: true } }; + } + + private cancel(params: Record): DesktopRpcOutcome { + const request = parseLoginCancel(params); + if (!request) return { ok: false, error: INVALID_LOGIN_CANCEL }; + const login = this.logins.get(request.loginId); + if (!login) return { ok: false, error: UNKNOWN_LOGIN }; + this.end(login, "Sign-in cancelled"); + return { ok: true, data: { cancelled: true } }; + } + + /** Aborts a sign-in; its flow then finishes with `reason` as the error. */ + private end(login: ActiveLogin, reason: string): void { + if (login.ended !== undefined) return; + login.ended = reason; + clearTimeout(login.timer); + const pending = login.pending; + login.pending = undefined; + pending?.reject(new Error(reason)); + login.controller.abort(new Error(reason)); + } + + private drop(login: ActiveLogin): void { + if (this.logins.get(login.loginId) !== login) return; + this.logins.delete(login.loginId); + this.busy.delete(login.provider); + } + + /** + * Saves an API key through the provider's own key setup (`apiKey.login`), the + * path `/login` takes: Pi stores it in its owner-only credential file and + * synchronizes the provider. A setup that asks for more than the key is + * refused; `login_start` with `kind: "api_key"` runs it interactively. + */ + private async setApiKey(params: Record): Promise { + const request = parseSetApiKey(params); + if (!request) return { ok: false, error: INVALID_SET_API_KEY }; + const session = this.session(); + if (!session) return { ok: false, error: LOGIN_UNAVAILABLE }; + let provider: LoginProviderDefinition | undefined; + try { + provider = session.runtime.getProvider(request.provider); + } catch { + return { ok: false, error: LOGIN_UNAVAILABLE }; + } + if (!provider) return { ok: false, error: UNKNOWN_PROVIDER }; + if (typeof provider.auth?.apiKey?.login !== "function") return { ok: false, error: LOGIN_UNSUPPORTED }; + if (this.busy.has(request.provider)) return { ok: false, error: LOGIN_IN_PROGRESS }; + this.busy.add(request.provider); + let keyGiven = false; + let askedMore = false; + try { + await session.runtime.login(request.provider, "api_key", { + signal: AbortSignal.timeout(DESKTOP_LOGIN_LIMITS.saveTimeoutMs), + notify: () => {}, + prompt: async (prompt) => { + if (prompt.type === "secret" && !keyGiven) { + keyGiven = true; + return request.key; + } + askedMore = true; + throw new Error("This provider asks for more than a key"); + }, + }); + } catch (error) { + // Pi's message may quote the provider's answer; the key is never echoed, so nothing of it crosses. + if (!credentialsCommitted(error)) return { ok: false, error: askedMore || !keyGiven ? INTERACTIVE_SETUP_REQUIRED : SAVE_FAILED }; + } finally { + this.busy.delete(request.provider); + } + await session.refresh().catch(() => undefined); + return { ok: true, data: { saved: true } }; + } + + /** `/logout`: removes what Pi stored for the provider (a sign-in or a key); environment variables and models.json stay. */ + private async removeCredentials(params: Record): Promise { + const request = parseRemoveCredentials(params); + if (!request) return { ok: false, error: INVALID_REMOVE_CREDENTIALS }; + const session = this.session(); + if (!session) return { ok: false, error: LOGIN_UNAVAILABLE }; + if (this.busy.has(request.provider)) return { ok: false, error: LOGIN_IN_PROGRESS }; + this.busy.add(request.provider); + try { + const signal = AbortSignal.timeout(DESKTOP_LOGIN_LIMITS.saveTimeoutMs); + const stored = (await session.runtime.listCredentials({ signal })).some((entry) => entry?.providerId === request.provider); + if (!stored) return { ok: true, data: { removed: false } }; + try { + await session.runtime.logout(request.provider, { signal }); + } catch (error) { + if (!credentialsCommitted(error)) return { ok: false, error: REMOVE_FAILED }; + } + } catch { + return { ok: false, error: REMOVE_FAILED }; + } finally { + this.busy.delete(request.provider); + } + await session.refresh().catch(() => undefined); + return { ok: true, data: { removed: true } }; + } +} diff --git a/lib/desktop-packages-service.ts b/lib/desktop-packages-service.ts new file mode 100644 index 000000000..98dbe456d --- /dev/null +++ b/lib/desktop-packages-service.ts @@ -0,0 +1,306 @@ +// Gentle Desktop packages bridge: `list_packages` reads the packages Pi's +// settings name, and `install_package` / `remove_package` run the same CLI a +// user would (`gentle-shell install [-l]`, `gentle-shell remove …`), +// so the validation, the project trust check, the npm/git work and the +// settings write are the CLI's own. Its output becomes `package_progress` +// lines and its exit one `package_finished`. After a success the session +// reloads (`/reload`: extensions, skills, prompts and themes), once it is idle, +// so what was installed is there without restarting it. + +import { spawn, type ChildProcess } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { CONFIG_DIR_NAME, DefaultPackageManager, getAgentDir, SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent"; +import type { DesktopRpcOutcome } from "./desktop-rpc.ts"; +import { + DESKTOP_PACKAGES_LIMITS, + INVALID_INSTALL_PACKAGE, + INVALID_LIST_PACKAGES, + INVALID_REMOVE_PACKAGE, + PACKAGE_JOB_RUNNING, + PACKAGES_UNAVAILABLE, + parsePackageRequest, + progressLines, + type DesktopPackage, + type PackageAction, + type PackageScope, +} from "./desktop-rpc-packages.ts"; +import { INTERACTIVE_HOST_ENV } from "./rpc-host.ts"; + +/** The launcher and home of this session, as `bin/gentle-shell.mjs` hands them to Pi: `{ command, args }` (JSON). */ +export const GENTLE_SHELL_LAUNCH_ENV = "GENTLE_SHELL_LAUNCH"; + +export interface PackageJobInput { + action: PackageAction; + source: string; + scope: PackageScope; + cwd: string; + signal: AbortSignal; + onLine: (line: string) => void; +} + +/** Runs one install or removal; resolves with its outcome, never rejects. */ +export type PackageRunner = (input: PackageJobInput) => Promise<{ ok: true } | { ok: false; error: string }>; +export type PackageLister = (cwd: string) => DesktopPackage[] | Promise; +export type DesktopPackagesEmit = (event: string, data: Record) => void; + +export interface DesktopPackagesOptions { + /** Test seam: the CLI run; production spawns the launcher (`cliPackageRunner`). */ + runner?: PackageRunner; + /** Test seam: the listing; production reads Pi's settings (`settingsPackages`). */ + lister?: PackageLister; + timeoutMs?: number; + newJobId?: () => string; +} + +/** The command that runs this Gentle Shell's CLI with this session's home. */ +export function packageCli(env: NodeJS.ProcessEnv = process.env): { command: string; args: string[] } { + const raw = env[GENTLE_SHELL_LAUNCH_ENV]; + if (raw) { + try { + const parsed = JSON.parse(raw) as { command?: unknown; args?: unknown }; + if (typeof parsed.command === "string" && parsed.command.length > 0 && Array.isArray(parsed.args) && parsed.args.every((arg) => typeof arg === "string")) { + return { command: parsed.command, args: parsed.args as string[] }; + } + } catch { /* fall back below */ } + } + // Pi started without the launcher: the launcher of this package, on Pi's own agent home. + return { command: process.execPath, args: [fileURLToPath(new URL("../bin/gentle-shell.mjs", import.meta.url)), "--home", getAgentDir()] }; +} + +/** The tail of a failed run's output, as its error: the CLI's last word on it. */ +function failureText(lines: readonly string[], code: number | null, signal: NodeJS.Signals | null): string { + const last = lines.at(-1); + if (last) return last.length > DESKTOP_PACKAGES_LIMITS.error ? `${last.slice(0, DESKTOP_PACKAGES_LIMITS.error - 1)}…` : last; + return signal ? `Stopped by ${signal}` : `Exited with code ${code}`; +} + +/** + * Production runner: ` install|remove [-l]` in the session's + * folder, stdin closed (nothing can prompt), color off. A stop (timeout, a + * session change) sends SIGTERM, then SIGKILL 5 s later. + */ +export function cliPackageRunner(cli: { command: string; args: string[] } = packageCli()): PackageRunner { + return (input) => { + const { promise, resolve } = Promise.withResolvers<{ ok: true } | { ok: false; error: string }>(); + const env: NodeJS.ProcessEnv = { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + delete env[INTERACTIVE_HOST_ENV]; + const args = [...cli.args, input.action, input.source, ...(input.scope === "project" ? ["-l"] : [])]; + let child: ChildProcess; + try { + child = spawn(cli.command, args, { cwd: input.cwd, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + } catch (error) { + resolve({ ok: false, error: error instanceof Error ? error.message : String(error) }); + return promise; + } + const errors: string[] = []; + const reader = (stream: NodeJS.ReadableStream | null, isError: boolean) => { + let rest = ""; + stream?.setEncoding("utf8"); + stream?.on("data", (chunk: string) => { + const text = rest + chunk; + const cut = Math.max(text.lastIndexOf("\n"), text.lastIndexOf("\r")); + rest = cut === -1 ? text : text.slice(cut + 1); + for (const line of progressLines(cut === -1 ? "" : text.slice(0, cut + 1))) { + if (isError) errors.push(line); + input.onLine(line); + } + }); + stream?.on("end", () => { + for (const line of progressLines(rest)) { + if (isError) errors.push(line); + input.onLine(line); + } + rest = ""; + }); + }; + reader(child.stdout, false); + reader(child.stderr, true); + let kill: NodeJS.Timeout | undefined; + const stop = () => { + child.kill("SIGTERM"); + kill = setTimeout(() => child.kill("SIGKILL"), 5000); + kill.unref(); + }; + input.signal.addEventListener("abort", stop, { once: true }); + child.once("error", (error) => { + input.signal.removeEventListener("abort", stop); + resolve({ ok: false, error: error.message }); + }); + child.once("close", (code, signal) => { + input.signal.removeEventListener("abort", stop); + clearTimeout(kill); + if (input.signal.aborted) resolve({ ok: false, error: input.signal.reason instanceof Error ? input.signal.reason.message : "Stopped" }); + else if (code === 0) resolve({ ok: true }); + else resolve({ ok: false, error: failureText(errors, code, signal) }); + }); + return promise; + }; +} + +function installedVersion(installedPath: string | undefined): string | undefined { + if (!installedPath) return undefined; + try { + const version = JSON.parse(readFileSync(join(installedPath, "package.json"), "utf8").replace(/^\uFEFF/, ""))?.version; + return typeof version === "string" && version.length > 0 && version.length <= 64 ? version : undefined; + } catch { + return undefined; + } +} + +/** Prefixes Pi reads as a non-local source; any other source is a path (Pi's `isLocalPath`). */ +const NON_LOCAL_SOURCE = /^(npm|git|github|http|https|ssh|builtin):/; + +/** + * Production listing: the packages Pi's user and project settings name (what `gentle-shell list` prints), with the installed version when there is one. + * A local path is listed absolute: settings keep it relative to their own folder, while `install`/`remove` resolve + * a typed path against the session's folder, so the listed source is one `remove_package` accepts as it is. + */ +export function settingsPackages(cwd: string): DesktopPackage[] { + const agentDir = getAgentDir(); + const manager = new DefaultPackageManager({ cwd, agentDir, settingsManager: SettingsManager.create(cwd, agentDir) }); + return manager.listConfiguredPackages().slice(0, DESKTOP_PACKAGES_LIMITS.packages).map((entry) => { + const version = installedVersion(entry.installedPath); + const local = !NON_LOCAL_SOURCE.test(entry.source.trim()); + const source = local ? (entry.installedPath ?? resolve(entry.scope === "project" ? join(cwd, CONFIG_DIR_NAME) : agentDir, entry.source.trim())) : entry.source; + return { source, ...(version === undefined ? {} : { version }), scope: entry.scope }; + }); +} + +interface Job { + jobId: string; + controller: AbortController; +} + +export class DesktopPackagesBridge { + private host: ExtensionContext | undefined; + private emit: DesktopPackagesEmit | undefined; + private generation = 0; + private job: Job | undefined; + private readonly runner: PackageRunner; + private readonly lister: PackageLister; + private readonly timeoutMs: number; + private readonly newJobId: () => string; + + constructor(options: DesktopPackagesOptions = {}) { + this.runner = options.runner ?? cliPackageRunner(); + this.lister = options.lister ?? settingsPackages; + this.timeoutMs = options.timeoutMs ?? DESKTOP_PACKAGES_LIMITS.timeoutMs; + this.newJobId = options.newJobId ?? (() => `pkg_${randomBytes(8).toString("hex")}`); + } + + attach(context: ExtensionContext): void { + this.host = context; + } + + wire(emit: DesktopPackagesEmit): void { + this.emit = emit; + } + + /** A session change stops a running job: its events and its reload would reach no one. */ + reset(): void { + this.generation += 1; + this.host = undefined; + this.emit = undefined; + this.job?.controller.abort(new Error("The session ended")); + } + + handle(method: string, params: Record): DesktopRpcOutcome | Promise | undefined { + if (method === "list_packages") return this.list(params); + if (method === "install_package") return this.start("install", params); + if (method === "remove_package") return this.start("remove", params); + return undefined; + } + + private async list(params: Record): Promise { + if (Object.keys(params).length > 0) return { ok: false, error: INVALID_LIST_PACKAGES }; + const cwd = this.cwd(); + if (cwd === undefined) return { ok: false, error: PACKAGES_UNAVAILABLE }; + try { + return { ok: true, data: { packages: await this.lister(cwd) } }; + } catch { + return { ok: false, error: PACKAGES_UNAVAILABLE }; + } + } + + private cwd(): string | undefined { + try { + const cwd = this.host?.cwd; + return typeof cwd === "string" && cwd.length > 0 ? cwd : undefined; + } catch { + return undefined; + } + } + + private start(action: PackageAction, params: Record): DesktopRpcOutcome { + const request = parsePackageRequest(params); + if (!request) return { ok: false, error: action === "install" ? INVALID_INSTALL_PACKAGE : INVALID_REMOVE_PACKAGE }; + const cwd = this.cwd(); + if (cwd === undefined) return { ok: false, error: PACKAGES_UNAVAILABLE }; + if (this.job) return { ok: false, error: PACKAGE_JOB_RUNNING }; + const job: Job = { jobId: this.newJobId(), controller: new AbortController() }; + this.job = job; + const host = this.host; + // The job starts after this answer is published, so `{ jobId }` precedes its first `package_progress`. + setImmediate(() => void this.run(job, action, request.source, request.scope, cwd, host)); + return { ok: true, data: { jobId: job.jobId } }; + } + + private async run(job: Job, action: PackageAction, source: string, scope: PackageScope, cwd: string, host: ExtensionContext | undefined): Promise { + const generation = this.generation; + const send = (event: string, data: Record) => { + if (generation !== this.generation) return; + try { + this.emit?.(event, data); + } catch { + /* the transport is gone; the job goes on */ + } + }; + let sent = 0; + let dropped = 0; + const timer = setTimeout(() => job.controller.abort(new Error("Stopped: it ran past the time limit")), this.timeoutMs); + timer.unref?.(); + let outcome: { ok: true } | { ok: false; error: string }; + try { + outcome = await this.runner({ + action, + source, + scope, + cwd, + signal: job.controller.signal, + onLine: (line) => { + if (sent >= DESKTOP_PACKAGES_LIMITS.lines) { + dropped += 1; + return; + } + sent += 1; + send("package_progress", { jobId: job.jobId, line }); + }, + }); + } catch (error) { + outcome = { ok: false, error: error instanceof Error ? error.message : String(error) }; + } finally { + clearTimeout(timer); + if (this.job === job) this.job = undefined; + } + if (dropped > 0) send("package_progress", { jobId: job.jobId, line: `… ${dropped} more lines` }); + const error = outcome.ok === false ? (outcome.error.slice(0, DESKTOP_PACKAGES_LIMITS.error) || "Failed") : undefined; + send("package_finished", { jobId: job.jobId, ok: outcome.ok, ...(error === undefined ? {} : { error }) }); + if (outcome.ok && generation === this.generation) await this.reload(host, generation); + } + + /** `/reload` once the agent is idle, as a user would after `gentle-shell install`: the session loads what changed. */ + private async reload(host: ExtensionContext | undefined, generation: number): Promise { + const command = host as (ExtensionContext & { waitForIdle?: () => Promise; reload?: () => Promise }) | undefined; + try { + if (typeof command?.reload !== "function") return; + await command.waitForIdle?.(); + if (generation !== this.generation) return; + await command.reload(); + } catch { + /* a replaced session reloads on its own start */ + } + } +} diff --git a/lib/desktop-rpc-auth.ts b/lib/desktop-rpc-auth.ts index 75489169c..91a0042dc 100644 --- a/lib/desktop-rpc-auth.ts +++ b/lib/desktop-rpc-auth.ts @@ -5,26 +5,33 @@ // value. The only registry calls it makes are the ones that cannot return a // secret: `getAll` (models, for provider ids), `getProviderAuthStatus` // (`{ configured, source }`, from Pi's in-memory snapshot), `isUsingOAuth`, -// `getProviderDisplayName`, and `refresh`. It never calls `getApiKey*` or +// `getProviderDisplayName`, `getProvider` (which sign-in methods a provider +// has, never a credential), and `refresh`. It never calls `getApiKey*` or // `getProviderAuth`, never reads `auth.json`, and never forwards a status // `label` (an environment variable name or source text) or an error message. -export const DESKTOP_AUTH_METHODS = ["get_auth_status", "reload_credentials"] as const; +export const DESKTOP_AUTH_METHODS = ["get_auth_status", "reload_credentials", "list_available_models"] as const; /** Every answer carries the provider list; this slice advertises no event. */ export const DESKTOP_AUTH_EVENTS = [] as const; export const INVALID_GET_AUTH_STATUS = { code: "invalid_request", message: "Invalid get_auth_status parameters" } as const; export const INVALID_RELOAD_CREDENTIALS = { code: "invalid_request", message: "Invalid reload_credentials parameters" } as const; +export const INVALID_LIST_AVAILABLE_MODELS = { code: "invalid_request", message: "Invalid list_available_models parameters" } as const; export const AUTH_UNAVAILABLE = { code: "auth_unavailable", message: "Credential status unavailable" } as const; export const RELOAD_FAILED = { code: "reload_failed", message: "Credentials could not be reloaded" } as const; -export const DESKTOP_AUTH_LIMITS = { providers: 200, displayName: 128 } as const; +export const DESKTOP_AUTH_LIMITS = { providers: 200, displayName: 128, models: 1000, modelId: 256 } as const; + +/** Pi's thinking levels, low to high: what a session without a model accepts. */ +export const DESKTOP_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const; /** Provider ids that may cross the wire; anything else is skipped. */ -const PROVIDER_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; +export const PROVIDER_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; export type CredentialType = "oauth" | "api_key"; export type CredentialSource = "stored" | "runtime" | "environment" | "models_json" | "extension"; +/** How a client can sign in to a provider: a browser sign-in, a device code, or a pasted API key. */ +export type LoginKind = "oauth" | "device" | "api_key"; export interface DesktopProviderAuth { provider: string; @@ -33,6 +40,8 @@ export interface DesktopProviderAuth { /** `oauth` or `api_key` when configured, otherwise `null`. */ type: CredentialType | null; source: CredentialSource | null; + /** What `login_start` / `set_api_key` can do for this provider; empty when nothing (ambient credentials only). */ + loginKinds: LoginKind[]; } export interface DesktopAuthStatus { @@ -45,8 +54,12 @@ export interface DesktopAuthRegistry { getAll(): ReadonlyArray<{ provider: string }>; getProviderAuthStatus(provider: string): { configured: boolean; source?: string }; getProviderDisplayName?(provider: string): string; + /** Pi's provider definition: only its `auth` methods are read, to tell which sign-ins it supports. */ + getProvider?(provider: string): { auth?: { oauth?: unknown; apiKey?: { login?: unknown } } } | undefined; isUsingOAuth(model: { provider: string }): boolean; refresh(options?: { allowNetwork?: boolean }): Promise<{ aborted: boolean; errors: ReadonlyMap }>; + /** Pi's available-model snapshot (`get_available_models`): models with credentials, read from memory. */ + getAvailable?(): ReadonlyArray; } export function isDesktopAuthRegistry(value: unknown): value is DesktopAuthRegistry { @@ -79,6 +92,43 @@ function displayName(registry: DesktopAuthRegistry, provider: string): string { return provider; } +/** + * Pi's OAuth sign-ins that run as a device code only (the user types a code on + * the provider's page), and those that offer a device code beside the browser + * sign-in. Pi's provider definitions do not say which flow they run, so this is + * read from Pi's own flows (`@earendil-works/pi-ai/dist/auth/oauth`); any other + * OAuth provider is a browser sign-in. + */ +const OAUTH_FLOWS: Readonly> = { + "github-copilot": "device", + "kimi-coding": "device", + meta: "device", + xai: "device", + "openai-codex": "both", + radius: "both", +}; + +/** The sign-ins a provider supports, from its definition: never a credential. */ +export function loginKinds(provider: string, definition: { auth?: { oauth?: unknown; apiKey?: { login?: unknown } } } | undefined): LoginKind[] { + const kinds: LoginKind[] = []; + const auth = definition?.auth; + if (auth?.oauth) { + const flow = Object.hasOwn(OAUTH_FLOWS, provider) ? OAUTH_FLOWS[provider] : undefined; + if (flow !== "device") kinds.push("oauth"); + if (flow !== undefined) kinds.push("device"); + } + if (typeof auth?.apiKey?.login === "function") kinds.push("api_key"); + return kinds; +} + +function providerLoginKinds(registry: DesktopAuthRegistry, provider: string): LoginKind[] { + try { + return loginKinds(provider, registry.getProvider?.(provider)); + } catch { + return []; + } +} + /** One row per provider that has models, sorted by id, from the registry's safe reads only. */ export function projectAuthStatus(registry: DesktopAuthRegistry): DesktopAuthStatus { const firstModel = new Map(); @@ -92,7 +142,7 @@ export function projectAuthStatus(registry: DesktopAuthRegistry): DesktopAuthSta const source = configured && typeof status.source === "string" && Object.hasOwn(SOURCES, status.source) ? SOURCES[status.source]! : null; let type: CredentialType | null = null; if (configured) type = registry.isUsingOAuth(firstModel.get(provider)!) ? "oauth" : "api_key"; - return { provider, displayName: displayName(registry, provider), configured, type, source }; + return { provider, displayName: displayName(registry, provider), configured, type, source, loginKinds: providerLoginKinds(registry, provider) }; }); return { providers, truncated: ids.length > DESKTOP_AUTH_LIMITS.providers }; } @@ -101,3 +151,76 @@ export function projectAuthStatus(registry: DesktopAuthRegistry): DesktopAuthSta export function failedProviderIds(errors: ReadonlyMap): string[] { return [...errors.keys()].filter((id) => PROVIDER_ID.test(id)).sort().slice(0, DESKTOP_AUTH_LIMITS.providers); } + +/** One model Pi can use now (it has credentials), as `list_available_models` lists it. */ +export interface DesktopAvailableModel { + provider: string; + id: string; + name?: string; + contextWindow?: number; + reasoning?: boolean; + /** What the model takes: `text`, `image`. */ + input?: Array<"text" | "image">; +} + +export interface DesktopAvailableModels { + models: DesktopAvailableModel[]; + /** What the session's current model accepts, low to high (Pi's `get_available_thinking_levels`). */ + thinkingLevels: string[]; + current?: { provider: string; id: string; thinkingLevel: string }; + truncated: boolean; +} + +/** A model id as it may cross: 1–256 characters, no control characters (ids may hold `/`, `:` or `.`). */ +function modelId(value: unknown): value is string { + return typeof value === "string" && value.length > 0 && value.length <= DESKTOP_AUTH_LIMITS.modelId && !/[\u0000-\u001f\u007f]/.test(value); +} + +/** A model as it may cross: provider and id always, the rest only when it has the shape Pi gives it. */ +function availableModel(model: unknown): DesktopAvailableModel | undefined { + if (!model || typeof model !== "object") return undefined; + const m = model as Record; + if (typeof m.provider !== "string" || !PROVIDER_ID.test(m.provider) || !modelId(m.id)) return undefined; + const out: DesktopAvailableModel = { provider: m.provider, id: m.id }; + if (typeof m.name === "string" && m.name.trim().length > 0) out.name = m.name.trim().slice(0, DESKTOP_AUTH_LIMITS.displayName); + if (typeof m.contextWindow === "number" && Number.isSafeInteger(m.contextWindow) && m.contextWindow > 0) out.contextWindow = m.contextWindow; + if (typeof m.reasoning === "boolean") out.reasoning = m.reasoning; + if (Array.isArray(m.input)) out.input = (["text", "image"] as const).filter((kind) => (m.input as unknown[]).includes(kind)); + return out; +} + +/** + * `list_available_models`: the models Pi's `get_available_models` lists (the + * registry's available snapshot: models with credentials, no network), and + * the thinking levels Pi's `get_available_thinking_levels` gives for the + * session's current model (`levelsOf`, Pi's own rule), plus that model and + * its level. Nothing else of a model (its base URL, headers, cost, compat + * overrides) crosses. + */ +export function projectAvailableModels( + available: readonly unknown[], + current: M | undefined, + thinkingLevel: string | undefined, + levelsOf: (model: M) => readonly string[], +): DesktopAvailableModels { + const models: DesktopAvailableModel[] = []; + let valid = 0; + for (const model of available) { + const projected = availableModel(model); + if (!projected) continue; + valid += 1; + if (models.length < DESKTOP_AUTH_LIMITS.models) models.push(projected); + } + const levels = current ? levelsOf(current) : DESKTOP_THINKING_LEVELS; + const thinkingLevels = levels.filter((level) => (DESKTOP_THINKING_LEVELS as readonly string[]).includes(level)); + // Pi's placeholder before any model is chosen (`unknown/unknown`) is no current model. + const projected = current === undefined ? undefined : availableModel(current); + const model = projected?.provider === "unknown" && projected.id === "unknown" ? undefined : projected; + const level = thinkingLevel !== undefined && (DESKTOP_THINKING_LEVELS as readonly string[]).includes(thinkingLevel) ? thinkingLevel : undefined; + return { + models, + thinkingLevels, + ...(model && level ? { current: { provider: model.provider, id: model.id, thinkingLevel: level } } : {}), + truncated: valid > DESKTOP_AUTH_LIMITS.models, + }; +} diff --git a/lib/desktop-rpc-config.ts b/lib/desktop-rpc-config.ts index 2ecd581a0..9d7d4e60e 100644 --- a/lib/desktop-rpc-config.ts +++ b/lib/desktop-rpc-config.ts @@ -9,10 +9,13 @@ // so no invariant is re-implemented here. A pin layer is set or cleared through // the owner's `writeProfilePinSync` / `clearProfilePinSync`, one explicitly named // layer per request. `models`, `subagents`, and `managed_assets` are derived or -// installer-owned, and `mcp`, `pi_settings`, and `claude_bridge` are display -// projections of files Pi or a third-party package own; all of them answer a -// typed `read_only` error to every write. There is no second store and no -// cached copy. +// installer-owned and answer a typed `read_only` error to every write, and so +// does `claude_bridge`, a display projection of a third-party package's file. +// Pi's own files are written through their stores too: `custom_models` +// (models.json, whole), `mcp` (one mcp.json layer, whole) and the model keys of +// `pi_settings` (settings.json, patched), each validated by Pi's own rules and +// with every secret redacted (`pi-user-config.ts`): clients never touch those +// files themselves. There is no second store and no cached copy. // // Changes made outside this channel are detected best effort: once wired for an // interactive RPC host, the bridge watches the owner files' directories (see @@ -50,6 +53,7 @@ import type { DesktopRpcOutcome, DesktopRpcState } from "./desktop-rpc.ts"; import { DesktopDirectoryWatcher, type DesktopDirectoryWatcherOptions, type DesktopWatchTarget } from "./desktop-rpc-config-watch.ts"; import { isDesktopProfileApplyRunning } from "./desktop-rpc-profiles.ts"; import { fallbacksFilePath, normalizeFallbacksFile, readFallbacksFile, writeFallbacksFile } from "./model-fallback-store.ts"; +import { parsePiModelDefaults, PI_MODEL_DEFAULTS_KEYS, projectPiModelDefaults, readOrchestratorSettings, writePiModelDefaults, type PiModelDefaults } from "./profiles-orchestrator.ts"; import { modelConfigPaths, normalizeModelConfig, readModelConfigFile, readSavedModelConfig } from "./model-routing-authority.ts"; import type { WorktreeResolver } from "./session-worktree-registry.ts"; import { globalPersonaPath, isPersonaMode, projectPersonaPath, readPersonaLayer, resolvePersonaMode, writePersonaMode, type PersonaLayerRead } from "./persona-config.ts"; @@ -60,6 +64,19 @@ import { join } from "node:path"; import { globalMcpConfigPath, projectMcpConfigPath, readMcpConfig } from "./mcp-config.ts"; import { globalPiSettingsPath, projectPiSettingsPath, readPiSettings } from "./pi-settings.ts"; import { claudeBridgeConfigPath, readClaudeBridgeConfig } from "./claude-bridge-config.ts"; +import { + collectMcpServers, + customModelsPath, + customModelsProblem, + readCustomModels, + readMcpLayer, + redactCustomModels, + redactMcpDocument, + restoreCustomModels, + restoreMcpDocument, + writePiConfigDocument, + type PiConfigFileRead, +} from "./pi-user-config.ts"; export const DESKTOP_CONFIG_METHODS = ["get_config", "set_config"] as const; /** Advertised only because this module wires the writer that publishes it. */ @@ -80,6 +97,7 @@ export const DESKTOP_CONFIG_STORES = [ "mcp", "pi_settings", "claude_bridge", + "custom_models", ] as const; export type DesktopConfigStore = (typeof DESKTOP_CONFIG_STORES)[number]; @@ -122,7 +140,7 @@ export interface DesktopConfigData { * each own a single global file, while `pins` owns two independent layers that a * request must select explicitly. */ -export type DesktopConfigWriteTarget = "global" | "local" | "repo"; +export type DesktopConfigWriteTarget = "global" | "project" | "local" | "repo"; export interface DesktopConfigWriteTargetInfo { target: DesktopConfigWriteTarget; @@ -141,6 +159,7 @@ const UNKNOWN_PIN_PROFILE = { code: "invalid_data", message: "Pin target profile const MISSING_REVISION = { code: "revision_conflict", message: "expectedRevision is required before writing" } as const; const STALE_REVISION = { code: "revision_conflict", message: "Config changed since expectedRevision was read" } as const; const WRITE_FAILED = { code: "write_failed", message: "Config store write failed" } as const; +const PROJECT_UNTRUSTED = { code: "project_untrusted", message: "Pi reads this project's files only once the project is trusted" } as const; /** Stores with a layer that the session cwd locates (project layers and pins). */ const CWD_DEPENDENT_STORES: readonly DesktopConfigStore[] = ["models", "subagents", "pins", "persona", "mcp", "pi_settings"]; @@ -149,10 +168,10 @@ const CWD_DEPENDENT_STORES: readonly DesktopConfigStore[] = ["models", "subagent const TRUST_GATED_STORES: readonly DesktopConfigStore[] = ["mcp", "pi_settings"]; /** Authoritative stores this slice may write; every other store is read-only. */ -const AUTHORITATIVE_STORES: ReadonlySet = new Set(["profiles", "profile_fallbacks", "pins", "persona", "banner", "notifications"]); +const AUTHORITATIVE_STORES: ReadonlySet = new Set(["profiles", "profile_fallbacks", "pins", "persona", "banner", "notifications", "mcp", "pi_settings", "custom_models"]); -/** The stores an `apply_profile` reads and rewrites; only their writes wait for an apply. */ -const PROFILE_FAMILY_STORES: ReadonlySet = new Set(["profiles", "profile_fallbacks", "pins"]); +/** The stores an `apply_profile` reads and rewrites (it sets the orchestrator's model keys in settings.json); only their writes wait for an apply. */ +const PROFILE_FAMILY_STORES: ReadonlySet = new Set(["profiles", "profile_fallbacks", "pins", "pi_settings"]); export function storeReadOnly(store: DesktopConfigStore): boolean { return !AUTHORITATIVE_STORES.has(store); @@ -189,6 +208,12 @@ export interface DesktopConfigOverrides { */ function withRoots(context: ExtensionContext, overrides: DesktopConfigOverrides): DesktopConfigRoots | undefined { if (typeof context.cwd !== "string" || context.cwd.length === 0) return undefined; + let projectTrusted = false; + try { + projectTrusted = typeof context.isProjectTrusted === "function" && context.isProjectTrusted() === true; + } catch { + /* a stale context has no trust to report */ + } return { cwd: context.cwd, configHome: overrides.configHome ?? gentlePiConfigHome(), @@ -478,7 +503,7 @@ function readNotifications(root: DesktopConfigRoots): StoreRead { }; } -// ---- Display stores: mcp, pi_settings, claude_bridge (read-only) ---- +// ---- Pi's own stores: mcp, pi_settings, claude_bridge ---- /** Bounds the `mcp` server list; `truncated` reports the cut. */ export const DESKTOP_MCP_SERVER_LIMIT = 64; @@ -492,6 +517,19 @@ function trustedLayers(global: LayerReadStatus, project: LayerReadStatus | undef }; } +/** Each mcp.json Pi reads in this session as a whole document: the project one only for a trusted project. */ +function mcpFiles(root: DesktopConfigRoots): { global: PiConfigFileRead; project?: PiConfigFileRead } { + return { + global: readMcpLayer(globalMcpConfigPath(root.agentHome)), + ...(root.projectTrusted === true ? { project: readMcpLayer(projectMcpConfigPath(root.cwd)) } : {}), + }; +} + +/** + * The servers Pi would load (display facts), and the documents a client edits: + * each layer Pi reads, its secrets redacted. The revision digests the real + * documents, so a secret changed elsewhere still moves it. + */ function readMcp(root: DesktopConfigRoots): StoreRead { const read = readMcpConfig({ agentHome: root.agentHome, cwd: root.cwd, projectTrusted: root.projectTrusted === true }); const { layers, status } = trustedLayers(read.global, read.project); @@ -499,7 +537,13 @@ function readMcp(root: DesktopConfigRoots): StoreRead { // `omitted` counts servers left out for an over-long name; `truncated` is only the cut at the bound. const named = read.servers.filter((server) => server.name.length <= MCP_NAME_LIMIT); const servers = named.slice(0, DESKTOP_MCP_SERVER_LIMIT); - return { status, value: { servers, truncated: named.length > DESKTOP_MCP_SERVER_LIMIT, omitted: read.servers.length - named.length }, layers }; + const summary = { servers, truncated: named.length > DESKTOP_MCP_SERVER_LIMIT, omitted: read.servers.length - named.length }; + const files = mcpFiles(root); + const documents = (redact: boolean) => Object.fromEntries((["global", "project"] as const).flatMap((source) => { + const file = files[source]; + return file?.status === "valid" ? [[source, redact ? redactMcpDocument(file.document) : file.document]] : []; + })); + return { status, value: { ...summary, documents: documents(true) }, revisionValue: { ...summary, documents: documents(false) }, layers }; } function readPiSettingsStore(root: DesktopConfigRoots): StoreRead { @@ -520,6 +564,15 @@ function readPiSettingsStore(root: DesktopConfigRoots): StoreRead { } } +type ModelDefaultsRead = { status: "missing" } | { status: "invalid" } | { status: "valid"; defaults: PiModelDefaults }; + +/** The model keys of the global settings.json, the only part of `pi_settings` a write changes. */ +function readModelDefaultsFile(root: DesktopConfigRoots): ModelDefaultsRead { + const read = readOrchestratorSettings(globalPiSettingsPath(root.agentHome)); + if (read.status !== "valid") return { status: read.status }; + return { status: "valid", defaults: projectPiModelDefaults(read.value) }; +} + function readClaudeBridge(root: DesktopConfigRoots): StoreRead { const read = readClaudeBridgeConfig(root.agentHome); return { @@ -529,6 +582,17 @@ function readClaudeBridge(root: DesktopConfigRoots): StoreRead { }; } +// ---- Pi's own custom models file, secrets redacted ---- + +function readCustomModelsStore(root: DesktopConfigRoots): StoreRead { + const read = readCustomModels(root.agentHome); + return { + status: read.status === "valid" ? "ok" : read.status, + // The revision digests the real document, so a key changed elsewhere still moves it. + ...(read.status === "valid" ? { value: redactCustomModels(read.document), revisionValue: read.document } : {}), + layers: [layer("global", read.status)], + }; +} const STORE_READERS: Record StoreRead }> = { profiles: { scope: "global", read: readProfiles }, models: { scope: "global+project", read: readModels }, @@ -542,6 +606,7 @@ const STORE_READERS: Record { writeNotificationSettings(settings, { gentlePiConfigHome: root.configHome }); } }; } +/** + * `pi_settings` writes only Pi's model keys (`defaultProvider`, `defaultModel`, + * `defaultThinkingLevel`, `enabledModels`) in the global settings.json, as a + * patch: a key the request names is set (`null` removes it) and a key it leaves + * out keeps its value. The store reads Pi's merged view (a trusted project's file + * on top, display-filtered), so a full replacement would make a client send back + * values it only saw through that view. Every other settings.json key is kept by + * the owner writer, and a file that is not a JSON object is never replaced: the + * write fails instead. + */ +function planPiSettingsWrite(data: unknown, root: DesktopConfigRoots, expected: string): WritePlan { + if (!isRecordValue(data)) return { error: INVALID_DATA }; + const current = readModelDefaultsFile(root); + const currentValue = current.status === "valid" ? current.defaults : undefined; + const next: Record = { ...currentValue }; + for (const [key, value] of Object.entries(data)) { + if (!(PI_MODEL_DEFAULTS_KEYS as readonly string[]).includes(key)) return { error: INVALID_DATA }; + if (value === null) delete next[key]; + else next[key] = value; + } + const defaults = parsePiModelDefaults(next); + if (!defaults || canonicalJson(defaults) !== canonicalJson(next)) return { error: INVALID_DATA }; + const writeRevision = configWriteRevision("pi_settings", "global", current.status === "valid" ? "ok" : current.status, currentValue); + const conflict = revisionConflict(expected, writeRevision); + if (conflict) return { error: conflict }; + if (current.status === "invalid") return { error: WRITE_FAILED }; + const changed = canonicalJson(currentValue ?? {}) !== canonicalJson(defaults); + return { + target: "global", + writeRevision, + changed, + write: () => { + const result = writePiModelDefaults(globalPiSettingsPath(root.agentHome), defaults); + if (result.status === "invalid") throw new Error(result.reason); + }, + }; +} + +/** `invalid_data` naming what Pi would refuse, so a client can show it; it carries no path. */ +function invalidPiData(store: DesktopConfigStore, problem: string): { code: string; message: string } { + return { code: INVALID_DATA.code, message: `Invalid ${store} data: ${problem}` }; +} + +/** + * `custom_models` replaces the whole models.json with a document Pi's own schema + * accepts. A redaction marker keeps the secret stored at the same place; any + * other value replaces it. An unreadable file may be replaced, since nothing of + * it is kept. + */ +function planCustomModelsWrite(data: unknown, root: DesktopConfigRoots, expected: string): WritePlan { + const current = readCustomModels(root.agentHome); + const restored = restoreCustomModels(data, current.status === "valid" ? current.document : undefined); + if ("error" in restored) return { error: invalidPiData("custom_models", restored.error) }; + const problem = customModelsProblem(restored.document); + if (problem !== undefined) return { error: invalidPiData("custom_models", problem) }; + const { writeRevision } = piFileWriteInfo("custom_models", "global", current); + const conflict = revisionConflict(expected, writeRevision); + if (conflict) return { error: conflict }; + const changed = current.status !== "valid" || canonicalJson(current.document) !== canonicalJson(restored.document); + return { target: "global", writeRevision, changed, write: () => writePiConfigDocument(customModelsPath(root.agentHome), restored.document) }; +} + +/** + * `mcp` replaces one layer's whole mcp.json, named by `source`. Every server + * must load as Pi loads it; a project file is checked against the global servers + * it may override, and is written only for a trusted project, the only one Pi + * reads. Markers keep the same server's stored secrets. + */ +function planMcpWrite(data: unknown, root: DesktopConfigRoots, expected: string): WritePlan { + if (!isRecordValue(data) || !("document" in data) || !Object.keys(data).every((key) => key === "source" || key === "document")) return { error: INVALID_DATA }; + const source = data.source; + if (source !== "global" && source !== "project") return { error: INVALID_DATA }; + const files = mcpFiles(root); + const current = files[source]; + if (current === undefined) return { error: PROJECT_UNTRUSTED }; + const restored = restoreMcpDocument(data.document, current.status === "valid" ? current.document : undefined); + if ("error" in restored) return { error: invalidPiData("mcp", restored.error) }; + const base = source === "project" && files.global.status === "valid" ? collectMcpServers(files.global.document, "global").servers : undefined; + const problem = collectMcpServers(restored.document, source, base).problems[0]; + if (problem !== undefined) return { error: invalidPiData("mcp", problem) }; + const { writeRevision } = piFileWriteInfo("mcp", source, current); + const conflict = revisionConflict(expected, writeRevision); + if (conflict) return { error: conflict }; + const changed = current.status !== "valid" || canonicalJson(current.document) !== canonicalJson(restored.document); + const path = source === "global" ? globalMcpConfigPath(root.agentHome) : projectMcpConfigPath(root.cwd); + return { target: source, writeRevision, changed, write: () => writePiConfigDocument(path, restored.document) }; +} + /** * The owner normalizer drops entries it cannot keep (an illegal profile name, an * unsafe agent key, a stale `active` marker, an unknown workflow mode). Writing @@ -907,6 +1077,8 @@ export class DesktopConfigBridge { private watchedTrust: boolean | undefined; /** The last revision this channel reported per store (read, snapshot, write, or event). */ private readonly reported = new Map(); + /** Bumped by every reset, so a reload one session scheduled never runs in the next. */ + private generation = 0; constructor(overrides: DesktopConfigOverrides = {}, watchOptions: DesktopDirectoryWatcherOptions = {}) { this.overrides = overrides; @@ -942,12 +1114,41 @@ export class DesktopConfigBridge { /** Session start/shutdown: watchers, baselines, and the emitter belong to one session. */ reset(): void { + this.generation += 1; this.host = undefined; this.emit = undefined; this.unwatch(); this.reported.clear(); } + /** Pi re-reads models.json when its registry refreshes, so the session has the new custom models at once. */ + private async refreshModels(host: ExtensionContext): Promise { + try { + await host.modelRegistry?.refresh({ allowNetwork: false }); + } catch { + /* the file is written; a load problem is Pi's to report through its registry */ + } + } + + /** + * Pi's MCP extension reads mcp.json only when a session starts, so the session + * reloads (`/reload`) once it is idle, as after a package install. It runs after + * the answer has gone out; a session replaced meanwhile loads the file itself. + */ + private reloadWhenIdle(host: ExtensionContext): void { + const generation = this.generation; + const command = host as ExtensionContext & { waitForIdle?: () => Promise; reload?: () => Promise }; + if (typeof command.reload !== "function") return; + setImmediate(async () => { + try { + await command.waitForIdle?.(); + if (generation === this.generation) await command.reload!(); + } catch { + /* a replaced session reloads on its own start */ + } + }); + } + /** * Interactive RPC hosts only: turn external store changes into ordered * `config_changed` events. The current revisions become the baseline, so @@ -1011,6 +1212,8 @@ export class DesktopConfigBridge { } if (this.reported.get(store) === current.revision) continue; this.reported.set(store, current.revision); + // Another session (or an editor) changed models.json: this session's registry follows it too. + if (store === "custom_models") void this.refreshModels(host); try { emit(DESKTOP_CONFIG_EVENT, { store: current.store, @@ -1025,7 +1228,7 @@ export class DesktopConfigBridge { } } - handle(method: string, params: Record): DesktopRpcOutcome | undefined { + handle(method: string, params: Record): DesktopRpcOutcome | Promise | undefined { // Only the config methods are this bridge's business; anything else falls // through to the next domain (the permission bridge) untouched. if (method !== "get_config" && method !== "set_config") return undefined; @@ -1052,9 +1255,11 @@ export class DesktopConfigBridge { * concurrently, and only an `await` can interleave another request, so the check * and the owner's atomic rename cannot be split by another Desktop request in * this process. That is a per-process guarantee only; it is not a cross-process - * transaction (see `docs/desktop-rpc.md`). + * transaction (see `docs/desktop-rpc.md`). Only what follows a committed write + * may wait: a `custom_models` answer waits for the session's model registry to + * re-read the file. */ - private write(host: ExtensionContext, params: Record): DesktopRpcOutcome { + private write(host: ExtensionContext, params: Record): DesktopRpcOutcome | Promise { for (const key of Object.keys(params)) { if (key !== "store" && key !== "data" && key !== "expectedRevision") { return { ok: false, error: INVALID_PARAMS }; @@ -1089,6 +1294,9 @@ export class DesktopConfigBridge { case "persona": plan = planPersonaWrite(params.data, root, expected); break; case "banner": plan = planBannerWrite(params.data, root, expected); break; case "notifications": plan = planNotificationsWrite(params.data, root, expected); break; + case "pi_settings": plan = planPiSettingsWrite(params.data, root, expected); break; + case "custom_models": plan = planCustomModelsWrite(params.data, root, expected); break; + case "mcp": plan = planMcpWrite(params.data, root, expected); break; default: plan = planPinsWrite(params.data, root, expected); } if ("error" in plan) return { ok: false, error: plan.error }; @@ -1115,7 +1323,7 @@ export class DesktopConfigBridge { const changed = writeRevision !== plan.writeRevision; const data = { ...after, writeTarget: plan.target, writeRevision, changed } as Record; if (!changed) return { ok: true, data }; - return { + const outcome: DesktopRpcOutcome = { ok: true, data, event: { @@ -1130,6 +1338,10 @@ export class DesktopConfigBridge { }, }, }; + // Applied as Pi applies the file: models at once, MCP servers when the session restarts. + if (store === "custom_models") return this.refreshModels(host).then(() => outcome); + if (store === "mcp") this.reloadWhenIdle(host); + return outcome; } /** Bounded status/revision/readOnly projection; store content never enters a snapshot. */ diff --git a/lib/desktop-rpc-host-tools.ts b/lib/desktop-rpc-host-tools.ts new file mode 100644 index 000000000..0290a2fcd --- /dev/null +++ b/lib/desktop-rpc-host-tools.ts @@ -0,0 +1,293 @@ +// Gentle Desktop host tools: the pure contract shared by the Desktop bridge +// (`lib/desktop-host-tools-service.ts`) and its tests. +// +// A client of the Desktop RPC channel (the desktop app, later a phone) offers +// tools that run on the client itself. The agent sees them as ordinary tools; +// a call becomes a `host_tool_call` event, the client runs it on its own device +// with its own authority, and answers with `host_tool_result`. Nothing here +// runs client code: a host tool's only effect in this process is the event it +// emits and the content the client sends back. +// +// The same client may also talk to the agent without a tool call: a +// `host_message` is a custom message in the conversation (Pi's +// `pi.sendMessage`), and `set_host_context` keeps a hidden custom message that +// is added before every agent run while it is set. + +export const DESKTOP_HOST_TOOLS_METHODS = ["set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context", "set_host_activity"] as const; +export const DESKTOP_HOST_TOOLS_EVENTS = ["host_tool_call", "host_tool_cancel"] as const; + +export const DESKTOP_HOST_TOOLS_LIMITS = { + provider: 64, + tools: 32, + label: 64, + description: 4096, + /** Bytes of a tool's `parameters` JSON Schema, serialized. */ + parametersBytes: 16 * 1024, + guidelines: 16, + guideline: 512, + callId: 128, + contentItems: 64, + /** Text bytes (UTF-8) plus base64 image characters across one result. */ + contentBytes: 8 * 1024 * 1024, + mimeType: 128, + /** Bytes of a result's, message's or context's `details` object, serialized. */ + detailsBytes: 1024 * 1024, + /** UTF-8 bytes of a `host_message` or `set_host_context` content string. */ + messageBytes: 64 * 1024, + /** Providers that may hold a host context at once. */ + contextProviders: 16, + /** Providers one `set_host_activity` may list. */ + activeProviders: 64, + /** A call no client answered fails after this long; each `host_tool_progress` restarts it. */ + callTimeoutMs: 10 * 60 * 1000, + /** Characters of a `host_tool_progress` message (reserved, ignored for now). */ + progressMessage: 512, + /** Settled call ids remembered so a late answer is `already_answered`, not `unknown_call`. */ + settledMemory: 256, +} as const; + +/** Whole `/gentle:desktop` request documents these methods may carry; every other method keeps the router's default. */ +export const DESKTOP_HOST_TOOLS_REQUEST_BYTES: Readonly> = { + set_host_tools: 1024 * 1024, + host_tool_result: 10 * 1024 * 1024, + host_message: 2 * 1024 * 1024, + set_host_context: 2 * 1024 * 1024, +}; + +export const INVALID_SET_HOST_TOOLS = { code: "invalid_request", message: "Invalid set_host_tools parameters" } as const; +export const INVALID_HOST_TOOL_RESULT = { code: "invalid_request", message: "Invalid host_tool_result parameters" } as const; +export const INVALID_HOST_TOOL_PROGRESS = { code: "invalid_request", message: "Invalid host_tool_progress parameters" } as const; +export const INVALID_HOST_MESSAGE = { code: "invalid_request", message: "Invalid host_message parameters" } as const; +export const INVALID_SET_HOST_CONTEXT = { code: "invalid_request", message: "Invalid set_host_context parameters" } as const; +export const INVALID_SET_HOST_ACTIVITY = { code: "invalid_request", message: "Invalid set_host_activity parameters" } as const; +export const HOST_TOOL_RESULT_TOO_LARGE = { code: "too_large", message: "host_tool_result content is over 8 MiB" } as const; +export const DETAILS_TOO_LARGE = { code: "too_large", message: "details is over 1 MiB serialized" } as const; +export const MESSAGE_TOO_LARGE = { code: "too_large", message: "content is over 64 KiB" } as const; +export const TOO_MANY_CONTEXTS = { code: "too_large", message: "At most 16 providers may hold a host context" } as const; +export const UNKNOWN_CALL = { code: "unknown_call", message: "No host tool call with this callId" } as const; +export const ALREADY_ANSWERED = { code: "already_answered", message: "This host tool call is already settled" } as const; +export const HOST_TOOLS_UNAVAILABLE = { code: "host_tools_unavailable", message: "Host tools cannot be registered in this session" } as const; +export const HOST_MESSAGES_UNAVAILABLE = { code: "host_messages_unavailable", message: "Host messages cannot be delivered in this session" } as const; + +export const TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/; +export const HOST_MESSAGE_TYPE = /^host\.[a-z0-9][a-z0-9_.-]{0,63}$/; +export const HOST_MESSAGE_DELIVERIES = ["auto", "steer", "followUp", "nextTurn"] as const; +export type HostMessageDelivery = (typeof HOST_MESSAGE_DELIVERIES)[number]; + +const CONTROL = /[\u0000-\u001f\u007f]/; +const MIME_TYPE = /^image\/[a-z0-9][a-z0-9.+-]{0,100}$/; +const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/; + +export interface HostToolSpec { + name: string; + label: string; + description: string; + parameters: Record; + guidelines: string[]; +} + +export interface SetHostToolsRequest { + provider: string; + tools: HostToolSpec[]; +} + +export type HostToolContent = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; + +export interface HostToolResultRequest { + callId: string; + content: HostToolContent[]; + isError: boolean; + /** The client's own data for the result; becomes the Pi tool result's `details`. */ + details?: Record; +} + +export interface HostMessageRequest { + customType: string; + content: string; + display: boolean; + details?: Record; + deliver: HostMessageDelivery; + triggerTurn?: boolean; +} + +export interface SetHostContextRequest { + provider: string; + /** Empty clears the provider's context. */ + content: string; + details?: Record; +} + +export type Parsed = { ok: true; value: T } | { ok: false; error: { code: string; message: string } }; + +function isPlainObject(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value); +} + +function onlyKeys(value: Record, allowed: readonly string[]): boolean { + return Object.keys(value).every((key) => allowed.includes(key)); +} + +function text(value: unknown, max: number, allowNewlines = false): value is string { + if (typeof value !== "string" || value.trim().length === 0 || value.length > max) return false; + return allowNewlines ? !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value) : !CONTROL.test(value); +} + +function invalid(message: string): { ok: false; error: { code: string; message: string } } { + return { ok: false, error: { code: INVALID_SET_HOST_TOOLS.code, message: `${INVALID_SET_HOST_TOOLS.message}: ${message}` } }; +} + +function parseTool(raw: unknown, index: number): Parsed { + const at = `tools[${index}]`; + if (!isPlainObject(raw) || !onlyKeys(raw, ["name", "label", "description", "parameters", "guidelines"])) return invalid(`${at} must be an object with name, label, description, parameters and optional guidelines`); + if (typeof raw.name !== "string" || !TOOL_NAME.test(raw.name)) return invalid(`${at}.name must match ${TOOL_NAME.source}`); + if (!text(raw.label, DESKTOP_HOST_TOOLS_LIMITS.label)) return invalid(`${at}.label must be 1-${DESKTOP_HOST_TOOLS_LIMITS.label} characters`); + if (!text(raw.description, DESKTOP_HOST_TOOLS_LIMITS.description, true)) return invalid(`${at}.description must be 1-${DESKTOP_HOST_TOOLS_LIMITS.description} characters`); + if (!isPlainObject(raw.parameters) || raw.parameters.type !== "object") return invalid(`${at}.parameters must be a JSON Schema object with type "object"`); + if (Buffer.byteLength(JSON.stringify(raw.parameters), "utf8") > DESKTOP_HOST_TOOLS_LIMITS.parametersBytes) return invalid(`${at}.parameters is over ${DESKTOP_HOST_TOOLS_LIMITS.parametersBytes} bytes`); + let guidelines: string[] = []; + if (raw.guidelines !== undefined) { + if (!Array.isArray(raw.guidelines) || raw.guidelines.length > DESKTOP_HOST_TOOLS_LIMITS.guidelines || !raw.guidelines.every((line) => text(line, DESKTOP_HOST_TOOLS_LIMITS.guideline))) { + return invalid(`${at}.guidelines must be at most ${DESKTOP_HOST_TOOLS_LIMITS.guidelines} single-line strings of 1-${DESKTOP_HOST_TOOLS_LIMITS.guideline} characters`); + } + guidelines = raw.guidelines as string[]; + } + return { ok: true, value: { name: raw.name, label: raw.label, description: raw.description, parameters: raw.parameters, guidelines } }; +} + +/** `{ provider, tools }`: the whole set one provider offers; an empty list unregisters it. */ +export function parseSetHostTools(params: Record): Parsed { + if (!onlyKeys(params, ["provider", "tools"])) return invalid("only provider and tools are allowed"); + if (!text(params.provider, DESKTOP_HOST_TOOLS_LIMITS.provider)) return invalid(`provider must be 1-${DESKTOP_HOST_TOOLS_LIMITS.provider} characters`); + if (!Array.isArray(params.tools) || params.tools.length > DESKTOP_HOST_TOOLS_LIMITS.tools) return invalid(`tools must be a list of at most ${DESKTOP_HOST_TOOLS_LIMITS.tools}`); + const tools: HostToolSpec[] = []; + const names = new Set(); + for (const [index, raw] of params.tools.entries()) { + const tool = parseTool(raw, index); + if (tool.ok === false) return { ok: false, error: tool.error }; + if (names.has(tool.value.name)) return invalid(`tool ${tool.value.name} is listed twice`); + names.add(tool.value.name); + tools.push(tool.value); + } + return { ok: true, value: { provider: params.provider, tools } }; +} + +/** A `details` value: absent, or a JSON object of at most 1 MiB serialized. */ +function checkDetails(value: unknown): "absent" | "ok" | "invalid" | "too_large" { + if (value === undefined) return "absent"; + if (!isPlainObject(value)) return "invalid"; + return Buffer.byteLength(JSON.stringify(value), "utf8") > DESKTOP_HOST_TOOLS_LIMITS.detailsBytes ? "too_large" : "ok"; +} + +/** `{ callId, content, isError?, details? }`, with the content cap counted over text bytes and base64 characters. */ +export function parseHostToolResult(params: Record): Parsed { + const bad = { ok: false as const, error: INVALID_HOST_TOOL_RESULT }; + if (!onlyKeys(params, ["callId", "content", "isError", "details"])) return bad; + if (typeof params.callId !== "string" || params.callId.length === 0 || params.callId.length > DESKTOP_HOST_TOOLS_LIMITS.callId) return bad; + if (params.isError !== undefined && typeof params.isError !== "boolean") return bad; + const details = checkDetails(params.details); + if (details === "invalid") return bad; + if (details === "too_large") return { ok: false, error: DETAILS_TOO_LARGE }; + if (!Array.isArray(params.content) || params.content.length === 0 || params.content.length > DESKTOP_HOST_TOOLS_LIMITS.contentItems) return bad; + const content: HostToolContent[] = []; + let bytes = 0; + for (const item of params.content) { + if (!isPlainObject(item)) return bad; + if (item.type === "text" && onlyKeys(item, ["type", "text"]) && typeof item.text === "string") { + bytes += Buffer.byteLength(item.text, "utf8"); + content.push({ type: "text", text: item.text }); + } else if (item.type === "image" && onlyKeys(item, ["type", "data", "mimeType"]) && typeof item.data === "string" && item.data.length > 0 + && typeof item.mimeType === "string" && item.mimeType.length <= DESKTOP_HOST_TOOLS_LIMITS.mimeType && MIME_TYPE.test(item.mimeType)) { + bytes += item.data.length; + if (bytes > DESKTOP_HOST_TOOLS_LIMITS.contentBytes) return { ok: false, error: HOST_TOOL_RESULT_TOO_LARGE }; + if (item.data.length % 4 !== 0 || !BASE64.test(item.data)) return bad; + content.push({ type: "image", data: item.data, mimeType: item.mimeType }); + } else { + return bad; + } + if (bytes > DESKTOP_HOST_TOOLS_LIMITS.contentBytes) return { ok: false, error: HOST_TOOL_RESULT_TOO_LARGE }; + } + return { ok: true, value: { callId: params.callId, content, isError: params.isError === true, ...(details === "ok" ? { details: params.details as Record } : {}) } }; +} + +/** `{ callId, message? }`; the message is reserved for showing progress and ignored for now. */ +export function parseHostToolProgress(params: Record): Parsed<{ callId: string }> { + const bad = { ok: false as const, error: INVALID_HOST_TOOL_PROGRESS }; + if (!onlyKeys(params, ["callId", "message"])) return bad; + if (typeof params.callId !== "string" || params.callId.length === 0 || params.callId.length > DESKTOP_HOST_TOOLS_LIMITS.callId) return bad; + if (params.message !== undefined && (typeof params.message !== "string" || params.message.length > DESKTOP_HOST_TOOLS_LIMITS.progressMessage)) return bad; + return { ok: true, value: { callId: params.callId } }; +} + +/** `{ customType, content, display, details?, deliver, triggerTurn? }`. */ +export function parseHostMessage(params: Record): Parsed { + const bad = { ok: false as const, error: INVALID_HOST_MESSAGE }; + if (!onlyKeys(params, ["customType", "content", "display", "details", "deliver", "triggerTurn"])) return bad; + if (typeof params.customType !== "string" || !HOST_MESSAGE_TYPE.test(params.customType)) return bad; + if (typeof params.content !== "string" || typeof params.display !== "boolean") return bad; + if (typeof params.deliver !== "string" || !(HOST_MESSAGE_DELIVERIES as readonly string[]).includes(params.deliver)) return bad; + if (params.triggerTurn !== undefined && typeof params.triggerTurn !== "boolean") return bad; + const details = checkDetails(params.details); + if (details === "invalid") return bad; + if (Buffer.byteLength(params.content, "utf8") > DESKTOP_HOST_TOOLS_LIMITS.messageBytes) return { ok: false, error: MESSAGE_TOO_LARGE }; + if (details === "too_large") return { ok: false, error: DETAILS_TOO_LARGE }; + return { + ok: true, + value: { + customType: params.customType, + content: params.content, + display: params.display, + ...(details === "ok" ? { details: params.details as Record } : {}), + deliver: params.deliver as HostMessageDelivery, + ...(typeof params.triggerTurn === "boolean" ? { triggerTurn: params.triggerTurn } : {}), + }, + }; +} + +/** `{ provider, content, details? }`; an empty content clears the provider's context. */ +export function parseSetHostContext(params: Record): Parsed { + const bad = { ok: false as const, error: INVALID_SET_HOST_CONTEXT }; + if (!onlyKeys(params, ["provider", "content", "details"])) return bad; + if (!text(params.provider, DESKTOP_HOST_TOOLS_LIMITS.provider) || typeof params.content !== "string") return bad; + const details = checkDetails(params.details); + if (details === "invalid") return bad; + if (Buffer.byteLength(params.content, "utf8") > DESKTOP_HOST_TOOLS_LIMITS.messageBytes) return { ok: false, error: MESSAGE_TOO_LARGE }; + if (details === "too_large") return { ok: false, error: DETAILS_TOO_LARGE }; + return { ok: true, value: { provider: params.provider, content: params.content, ...(details === "ok" ? { details: params.details as Record } : {}) } }; +} + +/** `{ providers }`: the connected providers, most recently active first (sent by `gentle-shell serve`). */ +export function parseSetHostActivity(params: Record): Parsed<{ providers: string[] }> { + const bad = { ok: false as const, error: INVALID_SET_HOST_ACTIVITY }; + if (!onlyKeys(params, ["providers"]) || !Array.isArray(params.providers) || params.providers.length > DESKTOP_HOST_TOOLS_LIMITS.activeProviders) return bad; + const providers: string[] = []; + for (const provider of params.providers) { + if (!text(provider, DESKTOP_HOST_TOOLS_LIMITS.provider) || providers.includes(provider)) return bad; + providers.push(provider); + } + return { ok: true, value: { providers } }; +} + +/** The hidden custom message type that carries a provider's host context. */ +export function hostContextType(provider: string): string { + return `host.context.${provider}`; +} + +/** + * Guidelines reach the model as flat bullets of the system prompt's rules, with + * no tool name in front (Pi's `promptGuidelines`). One that does not name its + * tool gets the name prefixed, so "this tool" is never ambiguous. + */ +export function modelGuidelines(tool: Pick): string[] { + return tool.guidelines.map((line) => (line.includes(tool.name) ? line : `${tool.name}: ${line}`)); +} + +/** The one-line entry in the system prompt's tool list: the description's first line. */ +export function promptSnippet(tool: Pick): string { + const first = tool.description.trim().split(/\r?\n/, 1)[0] ?? ""; + return first.length > 200 ? `${first.slice(0, 199)}…` : first; +} + +/** What the model reads when a host tool's provider cannot run it. */ +export function hostToolOfflineText(tool: string, providerLabel: string): string { + return `${tool} runs in ${providerLabel}, which isn't connected right now.`; +} diff --git a/lib/desktop-rpc-login.ts b/lib/desktop-rpc-login.ts new file mode 100644 index 000000000..970fcd8df --- /dev/null +++ b/lib/desktop-rpc-login.ts @@ -0,0 +1,214 @@ +// Gentle Desktop sign-in slice: the pure contract of `login_start`, +// `login_complete`, `login_cancel`, `set_api_key` and `remove_credentials`, +// shared by the bridge (`lib/desktop-login-service.ts`) and its tests. +// +// A client drives Pi's own provider sign-in from another device: what Pi's +// `/login` dialog would show becomes a `login_prompt` event, and what the user +// types or pastes there comes back as `login_complete`. Nothing here ever +// carries a credential back to the client: an API key goes one way, and +// errors are Pi's message text, bounded, never a stored value. + +import { PROVIDER_ID } from "./desktop-rpc-auth.ts"; + +export const DESKTOP_LOGIN_METHODS = ["login_start", "login_complete", "login_cancel", "set_api_key", "remove_credentials"] as const; +export const DESKTOP_LOGIN_EVENTS = ["login_prompt", "login_finished"] as const; + +export const DESKTOP_LOGIN_LIMITS = { + /** A sign-in that has not finished by then is cancelled. */ + timeoutMs: 15 * 60_000, + /** `set_api_key` / `remove_credentials` give up on Pi's credential store after this. */ + saveTimeoutMs: 30_000, + /** A pasted code, an answer or a full redirect URL. */ + value: 8 * 1024, + apiKey: 4 * 1024, + text: 1024, + url: 4096, + options: 32, + error: 300, +} as const; + +const err = (code: string, message: string) => ({ code, message }) as const; +export const INVALID_LOGIN_START = err("invalid_request", "Invalid login_start parameters"); +export const INVALID_LOGIN_COMPLETE = err("invalid_request", "Invalid login_complete parameters"); +export const INVALID_LOGIN_CANCEL = err("invalid_request", "Invalid login_cancel parameters"); +export const INVALID_SET_API_KEY = err("invalid_request", "Invalid set_api_key parameters"); +export const INVALID_REMOVE_CREDENTIALS = err("invalid_request", "Invalid remove_credentials parameters"); +export const LOGIN_UNAVAILABLE = err("login_unavailable", "Sign-in is not available in this session"); +export const UNKNOWN_PROVIDER = err("unknown_provider", "No such provider"); +export const LOGIN_UNSUPPORTED = err("login_unsupported", "This provider has no sign-in of that kind"); +export const LOGIN_IN_PROGRESS = err("login_in_progress", "A sign-in to this provider is already in progress"); +export const UNKNOWN_LOGIN = err("unknown_login", "No such sign-in in progress"); +export const NO_PENDING_PROMPT = err("no_pending_prompt", "This sign-in is not waiting for an answer"); +export const INVALID_CHOICE = err("invalid_request", "value must be one of the prompt's option ids"); +export const INTERACTIVE_SETUP_REQUIRED = err("interactive_setup_required", "This provider needs more than a key; use login_start with kind api_key"); +export const SAVE_FAILED = err("save_failed", "The API key could not be saved"); +export const REMOVE_FAILED = err("remove_failed", "The credentials could not be removed"); + +/** `login_start`'s `kind`: Pi's OAuth sign-in (browser or device code), or its interactive API key setup. */ +export type LoginStartKind = "oauth" | "api_key"; + +/** Pi's `AuthEvent` (`@earendil-works/pi-ai`), structurally: what a sign-in shows. */ +export type LoginAuthEvent = + | { type: "info"; message: string; links?: ReadonlyArray<{ url: string; label?: string }> } + | { type: "auth_url"; url: string; instructions?: string } + | { type: "device_code"; userCode: string; verificationUri: string } + | { type: "progress"; message: string }; + +/** Pi's `AuthPrompt`, structurally: what a sign-in asks. */ +export type LoginAuthPrompt = { signal?: AbortSignal } & ( + | { type: "text" | "secret" | "manual_code"; message: string; placeholder?: string } + | { type: "select"; message: string; options: ReadonlyArray<{ id: string; label: string; description?: string }> } +); + +/** The `login_prompt` event's data. */ +export interface LoginPromptEvent { + loginId: string; + kind: "open_url" | "device_code" | "input" | "progress"; + url?: string; + userCode?: string; + message?: string; + placeholder?: string; + /** The loopback callback the provider redirects the browser to, when the sign-in waits for that redirect. */ + redirectPrefix?: string; + /** `input` only: mask what the user types (an API key). */ + secret?: true; + /** `input` only: a choice; `login_complete`'s value is one option's `id`. */ + options?: Array<{ id: string; label: string }>; +} + +export const LOGIN_ID = /^login_[0-9a-f]{16}$/; + +function onlyKeys(params: Record, keys: readonly string[]): boolean { + return Object.keys(params).every((key) => keys.includes(key)); +} + +export function parseLoginStart(params: Record): { provider: string; kind?: LoginStartKind } | undefined { + if (!onlyKeys(params, ["provider", "kind"])) return undefined; + if (typeof params.provider !== "string" || !PROVIDER_ID.test(params.provider)) return undefined; + if (params.kind !== undefined && params.kind !== "oauth" && params.kind !== "api_key") return undefined; + const kind = params.kind as LoginStartKind | undefined; + return { provider: params.provider, ...(kind === undefined ? {} : { kind }) }; +} + +export function parseLoginComplete(params: Record): { loginId: string; value: string } | undefined { + if (!onlyKeys(params, ["loginId", "value"])) return undefined; + if (typeof params.loginId !== "string" || !LOGIN_ID.test(params.loginId)) return undefined; + if (typeof params.value !== "string" || params.value.length > DESKTOP_LOGIN_LIMITS.value) return undefined; + return { loginId: params.loginId, value: params.value }; +} + +export function parseLoginCancel(params: Record): { loginId: string } | undefined { + if (!onlyKeys(params, ["loginId"])) return undefined; + if (typeof params.loginId !== "string" || !LOGIN_ID.test(params.loginId)) return undefined; + return { loginId: params.loginId }; +} + +/** A key is one line of printable characters; surrounding whitespace is dropped, as a paste often carries it. */ +export function parseSetApiKey(params: Record): { provider: string; key: string } | undefined { + if (!onlyKeys(params, ["provider", "key"])) return undefined; + if (typeof params.provider !== "string" || !PROVIDER_ID.test(params.provider)) return undefined; + if (typeof params.key !== "string") return undefined; + const key = params.key.trim(); + // eslint-disable-next-line no-control-regex + if (key.length === 0 || key.length > DESKTOP_LOGIN_LIMITS.apiKey || /[\u0000-\u001f\u007f]/.test(key)) return undefined; + return { provider: params.provider, key }; +} + +export function parseRemoveCredentials(params: Record): { provider: string } | undefined { + if (!onlyKeys(params, ["provider"])) return undefined; + if (typeof params.provider !== "string" || !PROVIDER_ID.test(params.provider)) return undefined; + return { provider: params.provider }; +} + +/** One line of display text: control characters become spaces, bounded. */ +export function boundedText(value: unknown, limit: number = DESKTOP_LOGIN_LIMITS.text): string | undefined { + if (typeof value !== "string") return undefined; + // eslint-disable-next-line no-control-regex + const text = value.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim(); + if (text.length === 0) return undefined; + return text.length > limit ? `${text.slice(0, limit - 1)}…` : text; +} + +function boundedUrl(value: unknown): string | undefined { + if (typeof value !== "string" || value.length > DESKTOP_LOGIN_LIMITS.url) return undefined; + try { + const url = new URL(value); + return url.protocol === "https:" || url.protocol === "http:" ? value : undefined; + } catch { + return undefined; + } +} + +const LOOPBACK_HOSTS: Readonly> = { localhost: true, "127.0.0.1": true, "[::1]": true }; + +/** + * The loopback origin a URL names (`http://localhost:1455/`), when it is one: + * the callback a browser sign-in redirects to on the machine that started it. + */ +export function loopbackPrefix(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + try { + const url = new URL(value); + if (url.protocol !== "http:" || !Object.hasOwn(LOOPBACK_HOSTS, url.hostname)) return undefined; + return `${url.protocol}//${url.host}/`; + } catch { + return undefined; + } +} + +/** The loopback callback an authorization URL asks the provider to redirect to (`redirect_uri`, or OpenRouter's `callback_url`). */ +export function redirectPrefixOf(authUrl: string): string | undefined { + try { + const params = new URL(authUrl).searchParams; + return loopbackPrefix(params.get("redirect_uri")) ?? loopbackPrefix(params.get("callback_url")); + } catch { + return undefined; + } +} + +/** A `login_prompt` for something the sign-in shows; `undefined` for an event with nothing to show. */ +export function promptForEvent(loginId: string, event: LoginAuthEvent): LoginPromptEvent | undefined { + switch (event?.type) { + case "auth_url": { + const url = boundedUrl(event.url); + if (!url) return undefined; + const message = boundedText(event.instructions); + const redirectPrefix = redirectPrefixOf(url); + return { loginId, kind: "open_url", url, ...(message ? { message } : {}), ...(redirectPrefix ? { redirectPrefix } : {}) }; + } + case "device_code": { + const url = boundedUrl(event.verificationUri); + const userCode = boundedText(event.userCode, 64); + if (!url || !userCode) return undefined; + return { loginId, kind: "device_code", url, userCode }; + } + case "info": + case "progress": { + const message = boundedText(event.message); + if (!message) return undefined; + const link = event.type === "info" ? boundedUrl(event.links?.[0]?.url) : undefined; + return { loginId, kind: "progress", message, ...(link ? { url: link } : {}) }; + } + default: + return undefined; + } +} + +/** The `login_prompt` for a question the sign-in asks; `redirectPrefix` is the open sign-in's callback, for a pasted redirect URL. */ +export function promptForQuestion(loginId: string, prompt: LoginAuthPrompt, redirectPrefix: string | undefined): LoginPromptEvent { + const message = boundedText(prompt.message) ?? ""; + if (prompt.type === "select") { + const options = prompt.options.slice(0, DESKTOP_LOGIN_LIMITS.options).map((option) => ({ id: String(option.id), label: boundedText(option.label, 256) ?? String(option.id) })); + return { loginId, kind: "input", message, options }; + } + const placeholder = boundedText(prompt.placeholder, 256); + // A pasted code races the provider's redirect to the server's own callback: say which redirect the client may intercept. + const prefix = prompt.type === "manual_code" ? (redirectPrefix ?? loopbackPrefix(prompt.placeholder)) : undefined; + return { loginId, kind: "input", message, ...(placeholder ? { placeholder } : {}), ...(prompt.type === "secret" ? { secret: true as const } : {}), ...(prefix ? { redirectPrefix: prefix } : {}) }; +} + +/** A failure's text for `login_finished`: Pi's message, one line, bounded. */ +export function loginErrorText(error: unknown): string { + const message = error instanceof Error ? error.message : typeof error === "string" ? error : ""; + return boundedText(message, DESKTOP_LOGIN_LIMITS.error) ?? "Sign-in failed"; +} diff --git a/lib/desktop-rpc-packages.ts b/lib/desktop-rpc-packages.ts new file mode 100644 index 000000000..be9162495 --- /dev/null +++ b/lib/desktop-rpc-packages.ts @@ -0,0 +1,68 @@ +// Gentle Desktop packages slice: the pure contract of `list_packages`, +// `install_package` and `remove_package`, shared by the bridge +// (`lib/desktop-packages-service.ts`) and its tests. An install or a removal is +// a job: the answer is its id, then `package_progress` lines and one +// `package_finished`. + +export const DESKTOP_PACKAGES_METHODS = ["list_packages", "install_package", "remove_package"] as const; +export const DESKTOP_PACKAGES_EVENTS = ["package_progress", "package_finished"] as const; + +export const DESKTOP_PACKAGES_LIMITS = { + source: 1024, + /** One progress line, in characters. */ + line: 2000, + /** Progress lines one job emits; the rest are counted, not sent. */ + lines: 2000, + packages: 500, + error: 300, + /** A job still running then is stopped (npm or git hanging on the network). */ + timeoutMs: 20 * 60_000, +} as const; + +const err = (code: string, message: string) => ({ code, message }) as const; +export const INVALID_LIST_PACKAGES = err("invalid_request", "Invalid list_packages parameters"); +export const INVALID_INSTALL_PACKAGE = err("invalid_request", "Invalid install_package parameters"); +export const INVALID_REMOVE_PACKAGE = err("invalid_request", "Invalid remove_package parameters"); +export const PACKAGES_UNAVAILABLE = err("packages_unavailable", "Packages are not available in this session"); +export const PACKAGE_JOB_RUNNING = err("package_job_running", "Another package install or removal is running"); + +export type PackageScope = "user" | "project"; +export type PackageAction = "install" | "remove"; + +export interface DesktopPackage { + source: string; + version?: string; + scope: PackageScope; +} + +export const JOB_ID = /^pkg_[0-9a-f]{16}$/; + +/** + * `{ source, scope? }`. The source is handed to the CLI as one argument, as a + * user types it after `install`; one that starts with `-` would be read as an + * option, so it is refused here. The CLI validates the rest. + */ +export function parsePackageRequest(params: Record): { source: string; scope: PackageScope } | undefined { + if (!Object.keys(params).every((key) => key === "source" || key === "scope")) return undefined; + const { source, scope } = params; + if (typeof source !== "string" || source.length === 0 || source.length > DESKTOP_PACKAGES_LIMITS.source) return undefined; + // eslint-disable-next-line no-control-regex + if (source.trim() !== source || source.startsWith("-") || /[\u0000-\u001f\u007f]/.test(source)) return undefined; + if (scope !== undefined && scope !== "user" && scope !== "project") return undefined; + return { source, scope: (scope as PackageScope | undefined) ?? "user" }; +} + +// eslint-disable-next-line no-control-regex +const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-Z\\-_]/g; + +/** Output text as progress lines: no color codes, no control characters, no blank lines, each bounded. */ +export function progressLines(text: string): string[] { + const lines: string[] = []; + for (const raw of text.replace(ANSI, "").split(/\r\n|\r|\n/)) { + // eslint-disable-next-line no-control-regex + const line = raw.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "").trimEnd(); + if (line.trim().length === 0) continue; + lines.push(line.length > DESKTOP_PACKAGES_LIMITS.line ? `${line.slice(0, DESKTOP_PACKAGES_LIMITS.line - 1)}…` : line); + } + return lines; +} diff --git a/lib/desktop-rpc.ts b/lib/desktop-rpc.ts index 3a1a5f8f1..82b1a9147 100644 --- a/lib/desktop-rpc.ts +++ b/lib/desktop-rpc.ts @@ -1,3 +1,5 @@ +import { randomUUID } from "node:crypto"; + export const DESKTOP_RPC_SCHEMA = "gentle-shell.desktop-rpc/v1"; export const DESKTOP_RPC_COMMAND = "gentle:desktop"; export const DESKTOP_RPC_WIDGET = "gentle-desktop-rpc"; @@ -64,8 +66,10 @@ function validRequestId(value: unknown): value is string { return typeof value === "string" && value.length > 0 && value.length <= 128; } -function decodeRequest(raw: string): DecodedRequest { - if (Buffer.byteLength(raw, "utf8") > MAX_REQUEST_BYTES) return { requestId: null }; +/** Requests up to the default cap, or a larger cap a method was given with `setRequestLimits`; over it, no requestId is answered. */ +function decodeRequest(raw: string, limits: Readonly>): DecodedRequest { + const bytes = Buffer.byteLength(raw, "utf8"); + if (bytes > Math.max(MAX_REQUEST_BYTES, ...Object.values(limits))) return { requestId: null }; let value: unknown; try { value = JSON.parse(raw); @@ -79,6 +83,7 @@ function decodeRequest(raw: string): DecodedRequest { if (requestId === null || typeof candidate.method !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(candidate.method)) { return { requestId }; } + if (bytes > (Object.hasOwn(limits, candidate.method) ? limits[candidate.method] : MAX_REQUEST_BYTES)) return { requestId: null }; if (candidate.params !== undefined && (!candidate.params || typeof candidate.params !== "object" || Array.isArray(candidate.params))) { return { requestId }; } @@ -100,6 +105,13 @@ function isThenable(value: unknown): value is Promise(); private gate: DesktopRpcGate | undefined; + private requestLimits: Readonly> = {}; constructor( methods: readonly string[] = DEFAULT_METHODS, @@ -126,6 +139,7 @@ export class DesktopRpcRouter { start(publish: DesktopRpcPublish): void { this.sequence = 0; + this.epoch = randomUUID(); this.publisher = publish; } @@ -141,6 +155,11 @@ export class DesktopRpcRouter { this.gate = gate; } + /** Raise the request size cap for the named methods (for example a tool result carrying images). */ + setRequestLimits(limits: Readonly>): void { + this.requestLimits = limits; + } + /** * Answer every still-pending domain request with `error`, except those * `keep` names, and drop their late outcomes. Used right before the session @@ -163,7 +182,7 @@ export class DesktopRpcRouter { } snapshot() { - return { schema: DESKTOP_RPC_SCHEMA, sequence: this.sequence, state: this.state() }; + return { schema: DESKTOP_RPC_SCHEMA, sequence: this.sequence, epoch: this.epoch, state: this.state() }; } emit(event: string, data: Record): void { @@ -173,6 +192,7 @@ export class DesktopRpcRouter { schema: DESKTOP_RPC_SCHEMA, kind: "event", seq: sequence, + epoch: this.epoch, event, data, })); @@ -187,7 +207,7 @@ export class DesktopRpcRouter { handle(raw: string): void | Promise { if (!this.publisher) return; const publish = this.publisher; - const decoded = decodeRequest(raw); + const decoded = decodeRequest(raw, this.requestLimits); const request = decoded.request; if (!request) { publish(JSON.stringify(errorResponse(decoded.requestId, "invalid_request", "Request must be a valid JSON object"))); diff --git a/lib/gentle-shell-launcher.ts b/lib/gentle-shell-launcher.ts index 914ae4733..5622920d9 100644 --- a/lib/gentle-shell-launcher.ts +++ b/lib/gentle-shell-launcher.ts @@ -6,7 +6,7 @@ import { GENTLE_SHELL_CONFIG_HOME_ENV } from "./gentle-shell-bundled.ts"; // env/fs/exec. `bin/gentle-shell.mjs` (T2) wires these into the real process, // filesystem and child process so this module stays fully unit-testable. -export type LauncherCommand = "home" | "setup" | "upgrade" | "self-uninstall" | "memory" | "desktop" | "tower"; +export type LauncherCommand = "home" | "setup" | "upgrade" | "self-uninstall" | "memory" | "desktop" | "tower" | "serve" | "relay"; // pi's own package-management subcommands (see pi's cli/args.ts printHelp // "Commands" list): each is dispatched by pi itself, before pi's own flag @@ -152,8 +152,10 @@ export function parseLauncherArgs(argv: string[]): ParsedLauncherArgs { // token — once a pi subcommand (or any other passthrough token) has // already started, a later "setup" is just an ordinary passthrough // argument, same as "home" is. - if (arg === "setup" && command === undefined && passthrough.length === 0) { - command = "setup"; + // `serve` takes them too: one server per agent home, and its sessions + // run against the home those selectors resolve to. So does `relay`, whose secret lives in the home. + if ((arg === "setup" || arg === "serve" || arg === "relay") && command === undefined && passthrough.length === 0) { + command = arg; commandArgs = argv.slice(i + 1); break; } @@ -1479,6 +1481,8 @@ export function helpText(): string { " gentle-shell self-uninstall [--dry-run] [--yes] [--include-shared]", " gentle-shell desktop [--yes] [--no-open] | --status | --uninstall", " gentle-shell tower [--no-open] [--port ] [--json]", + " gentle-shell [home selectors] serve [--listen :] [--allow-host ]... [--foreground] | share | status | stop | pair | devices", + " gentle-shell [home selectors] relay --listen : [--secret-file ] [--json]", "", "Opens pi with the Gentle Shell package loaded, without touching your", "vanilla pi installation.", @@ -1535,6 +1539,15 @@ export function helpText(): string { " as a floor, in your browser. Prints the local URL and serves until Ctrl+C.", " --no-open only prints the URL; --port fixes the port (127.0.0.1 only);", " --json prints one JSON line with the URL instead, for programs.", + " serve Run a per-user server that owns Gentle Shell sessions (one '--mode rpc' child", + " each) so paired devices drive them over HTTP + Server-Sent Events, and they", + " outlive the client. 127.0.0.1 on a random port by default; every request", + " needs a device token. 'serve share' opens it to your network and prints one", + " code to paste in Gentle Shell GPUI. 'serve status', 'serve stop', 'serve pair", + " [--scope …]', 'serve devices [--revoke ]'; 'gentle-shell serve --help'.", + " relay Run a relay that lets devices outside a server's network reach it: servers", + " connect out to it ('serve share --relay gsr://host:port'), it splices raw TLS", + " streams and never sees their content. 'gentle-shell relay --help'.", "", "Managing packages:", " gentle-shell install npm: Run pi's own 'install' against the resolved home.", diff --git a/lib/pi-user-config.ts b/lib/pi-user-config.ts new file mode 100644 index 000000000..1c6211bb6 --- /dev/null +++ b/lib/pi-user-config.ts @@ -0,0 +1,357 @@ +// Pi's own user configuration files that Desktop clients edit through config +// stores instead of the file endpoints: the custom models file +// `/models.json` (`custom_models`) and the MCP servers files +// `/mcp.json` and `/.pi/mcp.json` (`mcp`; the project one is +// read by Pi only in a trusted project, paths from `mcp-config.ts`). +// +// Validation is Pi's own: models documents are checked against the JSON schema +// Pi publishes with its package (`schemas/models.schema.json`, generated from the +// schema its loader compiles), and every MCP server entry goes through Pi's +// `validateMcpServerConfig`. The file-level rules around them mirror Pi's +// loaders (`ModelConfig.load`, the MCP extension's `readConfigFile`). +// +// Secrets never cross the wire: every string in a secret position is replaced by +// `SECRET_MARKER` on read, and a write that sends the marker back in the same +// position keeps the value the file holds there. + +import { existsSync, readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { join } from "node:path"; +import { getPackageDir } from "@earendil-works/pi-coding-agent"; +import type { TSchema } from "typebox"; +import { Compile } from "typebox/compile"; +import { writeJsonFileAtomicallySync } from "./agent-profiles.ts"; + +/** What a secret reads as; sent back in the same position, it keeps the stored value. */ +export const SECRET_MARKER = "•••"; + +export type JsonRecord = Record; + +export type PiConfigFileRead = { status: "missing" } | { status: "invalid"; reason: string } | { status: "valid"; document: JsonRecord }; + +export function isJsonRecord(value: unknown): value is JsonRecord { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** A copy built from own entries, so a `__proto__` key stays a plain member. */ +function mapRecord(record: JsonRecord, map: (key: string, value: unknown) => unknown): JsonRecord { + return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(key, value)])); +} + +function own(record: unknown, key: string): unknown { + return isJsonRecord(record) && Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined; +} + +/** The file's text without a byte-order mark, as Pi reads it; `undefined` when absent. */ +function readText(path: string): string | undefined { + if (!existsSync(path)) return undefined; + const text = readFileSync(path, "utf8"); + return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text; +} + +/** Writes a whole document, replacing the file atomically (owner-only mode, it may hold secrets). */ +export function writePiConfigDocument(path: string, document: JsonRecord): void { + writeJsonFileAtomicallySync(path, `${JSON.stringify(document, null, 2)}\n`); +} + +/** Every string value of a string map (`headers`, `env`) becomes the marker. */ +function redactStringMap(map: unknown): unknown { + return isJsonRecord(map) ? mapRecord(map, (_key, value) => (typeof value === "string" ? SECRET_MARKER : value)) : map; +} + +/** A secret the client did not see is kept: the marker becomes the stored value, if there is one. */ +class MarkerError extends Error {} + +function restoreSecret(value: unknown, current: unknown, where: string): unknown { + if (value !== SECRET_MARKER) return value; + if (typeof current !== "string") throw new MarkerError(`${where}: "${SECRET_MARKER}" keeps a stored value, and there is none`); + return current; +} + +function restoreStringMap(map: unknown, current: unknown, where: string): unknown { + if (!isJsonRecord(map)) return map; + return mapRecord(map, (key, value) => restoreSecret(value, own(current, key), `${where}.${key}`)); +} + +// ---- Custom models: /models.json ---- + +export function customModelsPath(agentHome: string): string { + return join(agentHome, "models.json"); +} + +interface SchemaError { + keyword: string; + instancePath: string; + message: string; + params?: { requiredProperties?: string[] }; +} + +interface ModelsValidator { + Check(value: unknown): boolean; + Errors(value: unknown): Iterable; +} + +let modelsValidator: ModelsValidator | null | undefined; + +/** Pi's published models.json schema, compiled once; `null` when this Pi ships none. */ +function customModelsValidator(): ModelsValidator | null { + if (modelsValidator !== undefined) return modelsValidator; + try { + const schema = JSON.parse(readFileSync(join(getPackageDir(), "schemas", "models.schema.json"), "utf8")) as TSchema; + modelsValidator = Compile(schema) as unknown as ModelsValidator; + } catch { + modelsValidator = null; + } + return modelsValidator; +} + +/** Pi's `stripJsonComments`: `//` line comments and trailing commas, string literals untouched. */ +function stripJsonComments(input: string): string { + return input + .replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (match) => (match[0] === '"' ? match : "")) + .replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (match, tail) => tail ?? (match[0] === '"' ? match : "")); +} + +/** The error Pi's loader reports, as `path: message` (`providers.x.models.0.id: …`). */ +function schemaErrorLine(error: SchemaError): string { + const base = error.instancePath.replace(/^\//, "").replace(/\//g, "."); + const required = error.keyword === "required" ? error.params?.requiredProperties?.[0] : undefined; + const path = required ? (base ? `${base}.${required}` : required) : base || "root"; + return `${path}: ${error.message}`; +} + +/** Why Pi would refuse this models document, or `undefined` when it loads it. */ +export function customModelsProblem(document: unknown): string | undefined { + const validator = customModelsValidator(); + if (!validator) return "Pi's models.json schema is not available"; + if (validator.Check(document)) return undefined; + const first = [...validator.Errors(document)][0]; + return first ? schemaErrorLine(first) : "does not match Pi's models.json schema"; +} + +/** Reads models.json as Pi's `ModelConfig.load` does: comments allowed, then Pi's schema. */ +export function readCustomModels(agentHome: string): PiConfigFileRead { + let text: string | undefined; + try { + text = readText(customModelsPath(agentHome)); + } catch { + return { status: "invalid", reason: "unreadable" }; + } + if (text === undefined) return { status: "missing" }; + let parsed: unknown; + try { + parsed = JSON.parse(stripJsonComments(text)); + } catch { + return { status: "invalid", reason: "not JSON" }; + } + const problem = customModelsProblem(parsed); + if (problem !== undefined || !isJsonRecord(parsed)) return { status: "invalid", reason: problem ?? "not an object" }; + return { status: "valid", document: parsed }; +} + +function redactModelEntry(model: unknown): unknown { + return isJsonRecord(model) ? mapRecord(model, (key, value) => (key === "headers" ? redactStringMap(value) : value)) : model; +} + +function redactProvider(provider: unknown): unknown { + if (!isJsonRecord(provider)) return provider; + return mapRecord(provider, (key, value) => { + if (key === "apiKey") return typeof value === "string" ? SECRET_MARKER : value; + if (key === "headers") return redactStringMap(value); + if (key === "models") return Array.isArray(value) ? value.map(redactModelEntry) : value; + if (key === "modelOverrides") return isJsonRecord(value) ? mapRecord(value, (_id, entry) => redactModelEntry(entry)) : value; + return value; + }); +} + +/** The document a client sees: `apiKey` and every header value become the marker. */ +export function redactCustomModels(document: JsonRecord): JsonRecord { + return mapRecord(document, (key, value) => (key === "providers" && isJsonRecord(value) ? mapRecord(value, (_id, provider) => redactProvider(provider)) : value)); +} + +function currentModel(provider: unknown, id: unknown): unknown { + const models = own(provider, "models"); + return Array.isArray(models) ? models.find((model) => isJsonRecord(model) && model.id === id) : undefined; +} + +function restoreProvider(provider: unknown, current: unknown, where: string): unknown { + if (!isJsonRecord(provider)) return provider; + return mapRecord(provider, (key, value) => { + if (key === "apiKey") return restoreSecret(value, own(current, "apiKey"), `${where}.apiKey`); + if (key === "headers") return restoreStringMap(value, own(current, "headers"), `${where}.headers`); + if (key === "models" && Array.isArray(value)) { + // Models are matched by id, so a client may reorder them. + return value.map((model, index) => isJsonRecord(model) + ? mapRecord(model, (field, entry) => field === "headers" ? restoreStringMap(entry, own(currentModel(current, model.id), "headers"), `${where}.models.${index}.headers`) : entry) + : model); + } + if (key === "modelOverrides" && isJsonRecord(value)) { + return mapRecord(value, (id, override) => isJsonRecord(override) + ? mapRecord(override, (field, entry) => field === "headers" ? restoreStringMap(entry, own(own(own(current, "modelOverrides"), id), "headers"), `${where}.modelOverrides.${id}.headers`) : entry) + : override); + } + return value; + }); +} + +export type RestoreResult = { document: JsonRecord } | { error: string }; + +/** A client document with every marker replaced by the stored secret at the same place. */ +export function restoreCustomModels(document: unknown, current: JsonRecord | undefined): RestoreResult { + if (!isJsonRecord(document)) return { error: "root: must be an object" }; + try { + return { + document: mapRecord(document, (key, value) => key === "providers" && isJsonRecord(value) + ? mapRecord(value, (id, provider) => restoreProvider(provider, own(own(current, "providers"), id), `providers.${id}`)) + : value), + }; + } catch (error) { + if (error instanceof MarkerError) return { error: error.message }; + throw error; + } +} + +// ---- MCP servers: /mcp.json and /.pi/mcp.json ---- + +export type McpLayer = "global" | "project"; + +type McpServerValidator = (name: string, raw: unknown) => unknown; + +let mcpValidator: McpServerValidator | null | undefined; + +/** Pi's `validateMcpServerConfig` (pi-mcp's shared fields plus Pi's own); `null` when this Pi has none. */ +function mcpServerValidator(): McpServerValidator | null { + if (mcpValidator !== undefined) return mcpValidator; + try { + const file = join(getPackageDir(), "dist", "core", "mcp-servers.js"); + const validate = own(createRequire(file)(file), "validateMcpServerConfig"); + mcpValidator = typeof validate === "function" ? (validate as McpServerValidator) : null; + } catch { + mcpValidator = null; + } + return mcpValidator; +} + +/** Reads an mcp.json as Pi's MCP extension does: a JSON object whose `mcpServers`, if any, is an object. */ +export function readMcpLayer(path: string): PiConfigFileRead { + let text: string | undefined; + try { + text = readText(path); + } catch { + return { status: "invalid", reason: "unreadable" }; + } + if (text === undefined) return { status: "missing" }; + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return { status: "invalid", reason: "not JSON" }; + } + if (!isJsonRecord(parsed) || (parsed.mcpServers !== undefined && !isJsonRecord(parsed.mcpServers))) { + return { status: "invalid", reason: 'expected an object with an "mcpServers" object' }; + } + return { status: "valid", document: parsed }; +} + +/** A server URL carrying userinfo or a query string may hold a credential, so it crosses only as the marker. */ +function urlMayHoldSecret(url: string): boolean { + if (!URL.canParse(url)) return false; + const parsed = new URL(url); + return parsed.username !== "" || parsed.password !== "" || parsed.search !== ""; +} + +function redactMcpServer(server: unknown): unknown { + if (!isJsonRecord(server)) return server; + return mapRecord(server, (key, value) => { + if (key === "env" || key === "headers") return redactStringMap(value); + if (key === "url" && typeof value === "string" && urlMayHoldSecret(value)) return SECRET_MARKER; + if (key === "oauth" && isJsonRecord(value)) return mapRecord(value, (field, entry) => (field === "clientSecret" && typeof entry === "string" ? SECRET_MARKER : entry)); + return value; + }); +} + +/** The document a client sees: `env` and `headers` values, `oauth.clientSecret`, and a URL with userinfo or a query become the marker. */ +export function redactMcpDocument(document: JsonRecord): JsonRecord { + return mapRecord(document, (key, value) => (key === "mcpServers" && isJsonRecord(value) ? mapRecord(value, (_name, server) => redactMcpServer(server)) : value)); +} + +function restoreMcpServer(server: unknown, current: unknown, where: string): unknown { + if (!isJsonRecord(server)) return server; + return mapRecord(server, (key, value) => { + if (key === "env" || key === "headers") return restoreStringMap(value, own(current, key), `${where}.${key}`); + if (key === "url") return restoreSecret(value, own(current, key), `${where}.url`); + if (key === "oauth" && isJsonRecord(value)) { + return mapRecord(value, (field, entry) => field === "clientSecret" ? restoreSecret(entry, own(own(current, "oauth"), "clientSecret"), `${where}.oauth.clientSecret`) : entry); + } + return value; + }); +} + +/** A client document with every marker replaced by the stored secret of the same server. */ +export function restoreMcpDocument(document: unknown, current: JsonRecord | undefined): RestoreResult { + if (!isJsonRecord(document)) return { error: "root: must be an object" }; + try { + return { + document: mapRecord(document, (key, value) => key === "mcpServers" && isJsonRecord(value) + ? mapRecord(value, (name, server) => restoreMcpServer(server, own(own(current, "mcpServers"), name), `mcpServers.${name}`)) + : value), + }; + } catch (error) { + if (error instanceof MarkerError) return { error: error.message }; + throw error; + } +} + +const MCP_OVERRIDE_KEYS = ["enabled", "exposure", "toolExposure"]; + +/** pi-mcp's `mcpNamespace`: names that differ only in `-` and `_` share one. */ +function mcpNamespace(name: string): string { + return `mcp__${name.replace(/-/g, "_")}`; +} + +/** + * The servers a layer contributes, and the problems Pi's loader would report for + * it, by the loader's own rules: a project entry without a transport overrides + * `enabled`/`exposure`/`toolExposure` of a global server, `auth` is global-only, + * and names sharing a namespace clash. `base` holds the global servers when the + * layer is the project one. + */ +export function collectMcpServers(document: JsonRecord, layer: McpLayer, base: ReadonlyMap = new Map()): { servers: Map; problems: string[] } { + const servers = new Map(base); + const problems: string[] = []; + const validate = mcpServerValidator(); + if (!validate) return { servers, problems: ["Pi's MCP server validator is not available"] }; + if (document.mcpServers !== undefined && !isJsonRecord(document.mcpServers)) return { servers, problems: ['expected an object with an "mcpServers" object'] }; + if (document.autoEnableCodemode !== undefined && typeof document.autoEnableCodemode !== "boolean") problems.push("autoEnableCodemode must be a boolean"); + for (const [name, value] of Object.entries((document.mcpServers ?? {}) as JsonRecord)) { + // pi-mcp's `isMcpServerOverride`: an entry that names no transport. + if (layer === "project" && isJsonRecord(value) && value.command === undefined && value.url === undefined && value.type === undefined) { + const global = base.get(name); + const extra = Object.keys(value).filter((key) => !MCP_OVERRIDE_KEYS.includes(key)); + if (!global) problems.push(`server "${name}" needs "command" or "url", or a global server to override`); + else if (extra.length > 0) problems.push(`server "${name}": an override can only set ${MCP_OVERRIDE_KEYS.join(", ")}`); + else { + const config = validate(name, { ...global, ...value }); + if (typeof config === "string") problems.push(config); + else servers.set(name, config as JsonRecord); + } + continue; + } + const config = validate(name, value); + if (typeof config === "string") { + problems.push(config); + continue; + } + const clash = [...servers.keys()].find((other) => other !== name && mcpNamespace(other) === mcpNamespace(name)); + if (clash) { + problems.push(`server "${name}" conflicts with "${clash}"`); + continue; + } + if (layer === "project" && isJsonRecord(config) && "url" in config && config.auth) { + problems.push(`server "${name}": auth is only allowed in the global mcp.json`); + continue; + } + servers.set(name, config as JsonRecord); + } + return { servers, problems }; +} diff --git a/lib/profiles-orchestrator.ts b/lib/profiles-orchestrator.ts index ab8806466..cda3b54d5 100644 --- a/lib/profiles-orchestrator.ts +++ b/lib/profiles-orchestrator.ts @@ -20,6 +20,7 @@ import { isThinkingLevel, normalizeModelId, type AgentRoutingEntry, + type ThinkingLevel, } from "./model-routing-authority.ts"; /** The three Pi settings keys a profile's orchestrator entry owns. */ @@ -132,6 +133,78 @@ export function applyOrchestratorSettings( return { status: "written", previous }; } +/** + * The model defaults Configuration › Models edits: the orchestrator's three keys + * plus Pi's `enabledModels` (the scoped models Ctrl+P cycles). Absent means unset. + */ +export interface PiModelDefaults { + defaultProvider?: string; + defaultModel?: string; + defaultThinkingLevel?: ThinkingLevel; + enabledModels?: string[]; +} + +export const PI_MODEL_DEFAULTS_KEYS = [...ORCHESTRATOR_SETTINGS_KEYS, "enabledModels"] as const; + +const MODEL_DEFAULT_TEXT_MAX = 256; +const ENABLED_MODELS_MAX = 512; + +function isModelDefaultText(value: unknown): value is string { + // eslint-disable-next-line no-control-regex + return typeof value === "string" && value.trim().length > 0 && value.length <= MODEL_DEFAULT_TEXT_MAX && !/[\u0000-\u001f\u007f]/.test(value); +} + +/** + * The model defaults a settings object holds, each key only when it has the + * shape Pi reads; a mistyped key reads as unset, exactly as Pi treats it. + */ +export function projectPiModelDefaults(settings: Record): PiModelDefaults { + const defaults: PiModelDefaults = {}; + if (isModelDefaultText(settings.defaultProvider)) defaults.defaultProvider = settings.defaultProvider; + if (isModelDefaultText(settings.defaultModel)) defaults.defaultModel = settings.defaultModel; + if (isThinkingLevel(settings.defaultThinkingLevel)) defaults.defaultThinkingLevel = settings.defaultThinkingLevel; + if (Array.isArray(settings.enabledModels) && settings.enabledModels.every(isModelDefaultText)) defaults.enabledModels = [...settings.enabledModels]; + return defaults; +} + +/** + * A complete model-defaults write: only the four keys, each well-formed, no + * duplicate scoped model. `undefined` for anything else. + */ +export function parsePiModelDefaults(value: unknown): PiModelDefaults | undefined { + if (!isRecord(value)) return undefined; + if (!Object.keys(value).every((key) => (PI_MODEL_DEFAULTS_KEYS as readonly string[]).includes(key))) return undefined; + const { defaultProvider, defaultModel, defaultThinkingLevel, enabledModels } = value; + if (defaultProvider !== undefined && !isModelDefaultText(defaultProvider)) return undefined; + if (defaultModel !== undefined && !isModelDefaultText(defaultModel)) return undefined; + if (defaultThinkingLevel !== undefined && !isThinkingLevel(defaultThinkingLevel)) return undefined; + if (enabledModels !== undefined) { + if (!Array.isArray(enabledModels) || enabledModels.length > ENABLED_MODELS_MAX || !enabledModels.every(isModelDefaultText)) return undefined; + if (new Set(enabledModels).size !== enabledModels.length) return undefined; + } + return projectPiModelDefaults(value); +} + +/** + * Replace the model defaults in a Pi settings file: the four keys become exactly + * `defaults` (an absent key is removed), every other key is kept, and a file + * that is not a JSON object is refused, never replaced. + */ +export function writePiModelDefaults(settingsPath: string, defaults: PiModelDefaults): OrchestratorSettingsWriteResult { + const read = readOrchestratorSettings(settingsPath); + if (read.status === "invalid") return { status: "invalid", reason: read.reason }; + const previous = readPrevious(settingsPath); + const next: Record = { ...(read.status === "valid" ? read.value : {}) }; + for (const key of PI_MODEL_DEFAULTS_KEYS) { + if (defaults[key] === undefined) delete next[key]; + else next[key] = defaults[key]; + } + const text = `${JSON.stringify(next, null, 2)}\n`; + if (previous === text) return { status: "unchanged" }; + writeFileAtomically(settingsPath, text); + return { status: "written", previous }; +} + function readPrevious(settingsPath: string): string | undefined { try { return readFileSync(settingsPath, "utf8"); diff --git a/lib/serve-auth.ts b/lib/serve-auth.ts new file mode 100644 index 000000000..f9cde9223 --- /dev/null +++ b/lib/serve-auth.ts @@ -0,0 +1,291 @@ +// Authentication for `gentle-shell serve`: one-time pairing codes, per-device +// bearer tokens stored only as hashes in an owner-only file, short-lived +// single-use stream tickets for EventSource (which cannot send headers), and +// the local admin token the CLI reads from the owner-only server file. + +import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; + +export const SERVE_SCOPES = ["sessions:read", "sessions:operate", "terminal", "admin"] as const; +export type ServeScope = (typeof SERVE_SCOPES)[number]; +export const DEFAULT_PAIR_SCOPES: readonly ServeScope[] = ["sessions:read", "sessions:operate", "terminal"]; + +export const SERVE_AUTH_LIMITS = { + pairingCodeTtlMs: 5 * 60_000, + ticketTtlMs: 60_000, + /** Failed `POST /api/pair` attempts allowed per window, across all callers. */ + pairFailures: 10, + pairFailureWindowMs: 60_000, + /** Live pairing codes and tickets held at once; the oldest is dropped past this. */ + maxCodes: 16, + maxTickets: 256, + maxDevices: 64, + deviceNameChars: 64, + /** `lastUsedAt` is persisted at most this often per device. */ + lastUsedPersistMs: 60_000, +}; + +const DEVICES_SCHEMA = "gentle-shell.serve.devices/v1"; +const CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // Crockford base32: no I, L, O, U + +export function isServeScope(value: unknown): value is ServeScope { + return typeof value === "string" && (SERVE_SCOPES as readonly string[]).includes(value); +} + +export function hashSecret(secret: string): Buffer { + return createHash("sha256").update(secret, "utf8").digest(); +} + +/** Constant-time over equal-length digests, so neither length nor content leaks. */ +export function sameSecret(given: string | undefined | null, expected: string): boolean { + if (typeof given !== "string" || given.length === 0) return false; + return timingSafeEqual(hashSecret(given), hashSecret(expected)); +} + +function matchesHash(given: Buffer, storedHex: string): boolean { + const stored = Buffer.from(storedHex, "hex"); + return stored.length === given.length && timingSafeEqual(stored, given); +} + +export interface DeviceRecord { + id: string; + name: string; + scopes: ServeScope[]; + /** sha256 of the token, hex. The token itself is never stored. */ + tokenHash: string; + createdAt: string; + lastUsedAt?: string; +} + +export type PublicDevice = Omit; + +export interface Principal { + /** "local" for the CLI's admin token; a device id otherwise. */ + deviceId: string; + name: string; + scopes: readonly ServeScope[]; +} + +export function hasScope(principal: Principal, scope: ServeScope): boolean { + return principal.scopes.includes(scope); +} + +/** Normalizes a typed code: case-insensitive, separators ignored, O/I/L read as 0/1/1. */ +export function normalizePairingCode(code: string): string { + return code.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1"); +} + +function newPairingCode(): string { + const bytes = randomBytes(8); + let out = ""; + for (const b of bytes) out += CODE_ALPHABET[b & 31]; + return `${out.slice(0, 4)}-${out.slice(4)}`; +} + +function writePrivateJson(path: string, value: unknown): void { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + writeFileSync(temp, `${JSON.stringify(value, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } +} + +function parseDevices(text: string): DeviceRecord[] { + const parsed = JSON.parse(text) as { schema?: unknown; devices?: unknown }; + if (parsed?.schema !== DEVICES_SCHEMA || !Array.isArray(parsed.devices)) throw new Error("unrecognized devices file"); + return parsed.devices.filter((d): d is DeviceRecord => !!d && typeof d === "object" + && typeof d.id === "string" && typeof d.name === "string" && typeof d.tokenHash === "string" && /^[0-9a-f]{64}$/.test(d.tokenHash) + && typeof d.createdAt === "string" && Array.isArray(d.scopes) && d.scopes.every(isServeScope)); +} + +/** Reads the devices file; a missing file is no devices. */ +export function readDevicesFile(path: string): DeviceRecord[] { + if (!existsSync(path)) return []; + return parseDevices(readFileSync(path, "utf8")); +} + +export function writeDevicesFile(path: string, devices: readonly DeviceRecord[]): void { + writePrivateJson(path, { schema: DEVICES_SCHEMA, devices }); +} + +export function publicDevice(device: DeviceRecord): PublicDevice { + const { tokenHash: _hash, ...rest } = device; + return rest; +} + +interface PairingCode { + scopes: ServeScope[]; + expiresAt: number; + /** Normalized, kept for the TLS pairing proof (`POST /api/pair/proof`). */ + code: string; +} + +interface Ticket { + principal: Principal; + sessionId: string; + expiresAt: number; +} + +export type RedeemResult = + | { device: PublicDevice; token: string } + | { error: "invalid_code" | "rate_limited" | "too_many_devices" }; + +export interface ServeAuthOptions { + devicesFile: string; + adminToken: string; + now?: () => number; + limits?: Partial; +} + +export class ServeAuth { + private readonly devicesFile: string; + private readonly adminToken: string; + private readonly now: () => number; + private readonly limits: typeof SERVE_AUTH_LIMITS; + private devices: DeviceRecord[]; + /** Keyed by the code's hash, so a lookup never compares the code itself. */ + private readonly codes = new Map(); + private readonly tickets = new Map(); + private readonly persistedUse = new Map(); + private readonly revokeListeners: Array<(deviceId: string) => void> = []; + private failures: number[] = []; + + constructor(options: ServeAuthOptions) { + this.devicesFile = options.devicesFile; + this.adminToken = options.adminToken; + this.now = options.now ?? Date.now; + this.limits = { ...SERVE_AUTH_LIMITS, ...options.limits }; + this.devices = readDevicesFile(this.devicesFile); + } + + onRevoke(listener: (deviceId: string) => void): void { + this.revokeListeners.push(listener); + } + + /** Resolves a bearer token: the local admin token, or a paired device's. */ + authenticate(token: string | undefined): Principal | undefined { + if (!token) return undefined; + if (sameSecret(token, this.adminToken)) return { deviceId: "local", name: "local", scopes: SERVE_SCOPES }; + const digest = hashSecret(token); + let found: DeviceRecord | undefined; + // Every stored hash is compared, so the time taken does not depend on which one matched. + for (const device of this.devices) if (matchesHash(digest, device.tokenHash)) found = device; + if (!found) return undefined; + this.touch(found); + return { deviceId: found.id, name: found.name, scopes: [...found.scopes] }; + } + + private touch(device: DeviceRecord): void { + const now = this.now(); + device.lastUsedAt = new Date(now).toISOString(); + const last = this.persistedUse.get(device.id) ?? 0; + if (now - last < this.limits.lastUsedPersistMs) return; + this.persistedUse.set(device.id, now); + try { this.save(); } catch { /* usage time is advisory; auth never fails on it */ } + } + + private save(): void { + writeDevicesFile(this.devicesFile, this.devices); + } + + mintPairingCode(scopes: readonly ServeScope[] = DEFAULT_PAIR_SCOPES): { code: string; expiresAt: number; scopes: ServeScope[] } { + this.prune(); + const code = newPairingCode(); + const entry = { scopes: [...new Set(scopes)], expiresAt: this.now() + this.limits.pairingCodeTtlMs }; + this.codes.set(hashSecret(normalizePairingCode(code)).toString("hex"), { ...entry, code: normalizePairingCode(code) }); + while (this.codes.size > this.limits.maxCodes) this.codes.delete(this.codes.keys().next().value!); + return { code, ...entry }; + } + + /** The live pairing codes, normalized: the pairing proof binds each to the server's certificate. */ + livePairingCodes(): string[] { + this.prune(); + return [...this.codes.values()].map((entry) => entry.code); + } + + /** Single use: the code is gone after the first attempt that names it, success or not. */ + redeem(code: unknown, name: unknown): RedeemResult { + this.prune(); + const now = this.now(); + this.failures = this.failures.filter((t) => now - t < this.limits.pairFailureWindowMs); + if (this.failures.length >= this.limits.pairFailures) return { error: "rate_limited" }; + const key = typeof code === "string" && code.length <= 32 ? hashSecret(normalizePairingCode(code)).toString("hex") : undefined; + const entry = key === undefined ? undefined : this.codes.get(key); + if (!entry || key === undefined) { + this.failures.push(now); + return { error: "invalid_code" }; + } + this.codes.delete(key); + if (this.devices.length >= this.limits.maxDevices) return { error: "too_many_devices" }; + const token = `gss_${randomBytes(32).toString("base64url")}`; + const device: DeviceRecord = { + id: `dev_${randomUUID().replace(/-/g, "").slice(0, 16)}`, + name: cleanDeviceName(name), + scopes: entry.scopes, + tokenHash: hashSecret(token).toString("hex"), + createdAt: new Date(now).toISOString(), + }; + this.devices.push(device); + this.save(); + return { device: publicDevice(device), token }; + } + + listDevices(): PublicDevice[] { + return this.devices.map(publicDevice); + } + + /** Takes effect at once: the token stops working, its tickets die and listeners close its streams. */ + revoke(deviceId: string): boolean { + const before = this.devices.length; + this.devices = this.devices.filter((d) => d.id !== deviceId); + if (this.devices.length === before) return false; + this.save(); + for (const [key, ticket] of this.tickets) if (ticket.principal.deviceId === deviceId) this.tickets.delete(key); + for (const listener of this.revokeListeners) listener(deviceId); + return true; + } + + mintTicket(principal: Principal, sessionId: string): { ticket: string; expiresAt: number } { + this.prune(); + const ticket = randomBytes(24).toString("base64url"); + const expiresAt = this.now() + this.limits.ticketTtlMs; + this.tickets.set(hashSecret(ticket).toString("hex"), { principal, sessionId, expiresAt }); + while (this.tickets.size > this.limits.maxTickets) this.tickets.delete(this.tickets.keys().next().value!); + return { ticket, expiresAt }; + } + + /** Single use and bound to one session. */ + redeemTicket(ticket: string | null | undefined, sessionId: string): Principal | undefined { + if (!ticket || ticket.length > 64) return undefined; + this.prune(); + const key = hashSecret(ticket).toString("hex"); + const entry = this.tickets.get(key); + if (!entry) return undefined; + this.tickets.delete(key); + return entry.sessionId === sessionId ? entry.principal : undefined; + } + + private prune(): void { + const now = this.now(); + for (const [key, entry] of this.codes) if (entry.expiresAt <= now) this.codes.delete(key); + for (const [key, entry] of this.tickets) if (entry.expiresAt <= now) this.tickets.delete(key); + } +} + +export function cleanDeviceName(name: unknown): string { + const text = typeof name === "string" ? name.replace(/[\u0000-\u001f\u007f]/g, " ").trim() : ""; + return (text || "device").slice(0, SERVE_AUTH_LIMITS.deviceNameChars); +} + +/** Parses `--scope` values: comma lists, repeated flags; unknown names are an error. */ +export function parseScopes(values: readonly string[]): { scopes: ServeScope[] } | { error: string } { + const scopes: ServeScope[] = []; + for (const value of values.flatMap((v) => v.split(","))) { + const scope = value.trim(); + if (!scope) continue; + if (!isServeScope(scope)) return { error: `unknown scope "${scope}" (expected ${SERVE_SCOPES.join(", ")})` }; + if (!scopes.includes(scope)) scopes.push(scope); + } + return scopes.length === 0 ? { error: "--scope needs at least one scope" } : { scopes }; +} diff --git a/lib/serve-checks.ts b/lib/serve-checks.ts new file mode 100644 index 000000000..39a7d4d12 --- /dev/null +++ b/lib/serve-checks.ts @@ -0,0 +1,289 @@ +// `GET /api/checks` for `gentle-shell serve` (`sessions:read`): whether this +// server has what its sessions need, the four rows Gentle Shell GPUI's own +// setup checklist shows (crates/app/src/features/setup: `extras.rs`, +// `gentle.rs`), with the same rules, so a device shows the server's setup the +// way it shows its own: Node.js (22.19.0 or newer, with npm), Git (not macOS's +// stub without the Command Line Tools), Engram (3.0.0 or newer; a broken +// `ENGRAM_BIN` override is reported) and the companion setup (the launcher's +// own `setup --check`). Each tool runs with a short timeout, all at once, +// never through a shell; one result is kept for `cacheMs`. + +import { execFile } from "node:child_process"; +import { constants as fsConstants, realpathSync } from "node:fs"; +import { access, readFile, stat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { delimiter, dirname, isAbsolute, join } from "node:path"; +import { launcherConfigPath, parseRawLauncherConfig, provisionedEntry } from "./gentle-shell-launcher.ts"; +import type { SessionLaunch } from "./serve-session.ts"; + +export const SERVE_CHECK_LIMITS = { + /** How long one result answers every request. */ + cacheMs: 10_000, + /** A tool's `--version` still running then is killed (and counts as not running). */ + toolTimeoutMs: 5_000, + /** `gentle-shell setup --check` starts Node and reads the home. */ + companionTimeoutMs: 15_000, + outputBytes: 64 * 1024, + detail: 300, +}; + +/** gentle-pi `engines.node`, as the app's `MIN_NODE`. */ +export const MIN_NODE: Version = [22, 19, 0]; +/** gentle-engram accepts a stable Engram core from 3.0.0 (the app's `MIN_ENGRAM`). */ +export const MIN_ENGRAM: Version = [3, 0, 0]; + +export type CheckId = "companion" | "node" | "git" | "engram"; +export type CheckState = "ok" | "missing" | "error"; + +export interface ServeCheck { + id: CheckId; + state: CheckState; + /** What was found, `X.Y.Z` (no `v`); the companion's is the Gentle AI it was set up with. */ + version: string | null; + /** Why, in words; an outdated tool is an `error` that says what it needs. */ + detail: string | null; +} + +export type Version = [number, number, number]; + +export interface ServeChecksOptions { + /** The environment tools are looked up and run with (the server's). */ + env: NodeJS.ProcessEnv; + /** `gentle-shell [home flags] setup --check --json` for this server's home; without it the companion row is an `error`. */ + companion?: () => SessionLaunch; + /** The agent home the server serves (a `--link` home's `settings.json`, the setup marker's key). */ + agentHome?: string; + /** The running Gentle Shell version, named when the setup was made by another one. */ + version?: string; + platform?: NodeJS.Platform; + limits?: Partial; + now?: () => number; +} + +/** `v22.19.0`, `22.19`, `3.0.0-beta`: the leading numbers, as the app's `parse_version`. */ +export function parseVersion(text: string): Version | undefined { + let rest = text.trim(); + if (rest.startsWith("go")) rest = rest.slice(2); + if (rest.startsWith("v")) rest = rest.slice(1); + const parts: Version = [0, 0, 0]; + let found = 0; + for (const [i, part] of rest.split(".").slice(0, 3).entries()) { + const digits = /^\d*/.exec(part)![0]; + if (digits === "") break; + parts[i] = Number(digits); + found = i + 1; + if (digits.length !== part.length) break; + } + return found > 0 ? parts : undefined; +} + +export function showVersion(version: Version): string { + return version.join("."); +} + +function older(a: Version, b: Version): boolean { + for (let i = 0; i < 3; i += 1) if (a[i] !== b[i]) return a[i] < b[i]; + return false; +} + +/** An executable named `name` (a path, or looked up on `env`'s PATH with Windows' extensions), or undefined. */ +export async function findProgram(name: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform = process.platform): Promise { + const windows = platform === "win32"; + const extensions = windows ? ["", ...(env.PATHEXT ?? env.Pathext ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const runnable = async (path: string) => { + try { + if (!(await stat(path)).isFile()) return false; + if (!windows) await access(path, fsConstants.X_OK); + return true; + } catch { + return false; + } + }; + const candidates = (base: string) => extensions.map((ext) => base + ext); + if (isAbsolute(name) || name.includes("/") || (windows && name.includes("\\"))) { + for (const path of candidates(name)) if (await runnable(path)) return path; + return undefined; + } + const pathVar = env.PATH ?? env.Path ?? ""; + for (const dir of pathVar.split(windows ? ";" : delimiter)) { + if (dir === "") continue; + for (const path of candidates(join(dir, name))) if (await runnable(path)) return path; + } + return undefined; +} + +interface RunResult { + /** Exit code 0 within the time limit. */ + ok: boolean; + /** The exit code, when it exited by itself. */ + code: number | null; + stdout: string; +} + +function run(command: string, args: string[], options: { env: NodeJS.ProcessEnv; cwd?: string; timeoutMs: number; outputBytes: number }): Promise { + const { promise, resolve } = Promise.withResolvers(); + execFile(command, args, { env: options.env, cwd: options.cwd ?? homedir(), timeout: options.timeoutMs, killSignal: "SIGKILL", maxBuffer: options.outputBytes, windowsHide: true, encoding: "utf8" }, + (error, stdout) => { + const code = error ? (typeof error.code === "number" ? error.code : null) : 0; + resolve({ ok: !error, code, stdout: typeof stdout === "string" ? stdout : "" }); + }).stdin?.end(); + return promise; +} + +/** `settings.json` `packages` lists `name` (string or `{source}` entries, `npm:[@version]`), as the app's `settings_list`. */ +export function settingsList(settings: unknown, name: string): boolean { + const packages = (settings as { packages?: unknown } | null)?.packages; + if (!Array.isArray(packages)) return false; + return packages.some((entry) => { + const source = typeof entry === "string" ? entry : (entry as { source?: unknown } | null)?.source; + if (typeof source !== "string" || !source.startsWith("npm:")) return false; + const spec = source.slice(4); + const at = spec.startsWith("@") ? spec.indexOf("@", 1) : spec.indexOf("@"); + return (at === -1 ? spec : spec.slice(0, at)) === name; + }); +} + +export class ServeChecks { + private readonly env: NodeJS.ProcessEnv; + private readonly platform: NodeJS.Platform; + private readonly limits: typeof SERVE_CHECK_LIMITS; + private readonly now: () => number; + private readonly companionLaunch?: () => SessionLaunch; + private readonly agentHome?: string; + private readonly version?: string; + private cached?: { at: number; checks: Promise }; + + constructor(options: ServeChecksOptions) { + this.env = options.env; + this.platform = options.platform ?? process.platform; + this.limits = { ...SERVE_CHECK_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.companionLaunch = options.companion; + this.agentHome = options.agentHome; + this.version = options.version; + } + + /** Every row, in the app's order; requests within `cacheMs` (and while one runs) share one result. */ + checks(): Promise { + const now = this.now(); + if (this.cached && now - this.cached.at < this.limits.cacheMs) return this.cached.checks; + const checks = Promise.all([this.node(), this.companion(), this.git(), this.engram()]); + this.cached = { at: now, checks }; + return checks; + } + + /** The next request runs the checks again (after a setup or upgrade job). */ + forget(): void { + this.cached = undefined; + } + + private tool(command: string, args: string[]): Promise { + return run(command, args, { env: this.env, timeoutMs: this.limits.toolTimeoutMs, outputBytes: this.limits.outputBytes }); + } + + private row(id: CheckId, state: CheckState, version: string | null, detail: string | null): ServeCheck { + const clip = (text: string | null) => (text === null || text.length <= this.limits.detail ? text : `${text.slice(0, this.limits.detail - 1)}…`); + return { id, state, version: clip(version), detail: clip(detail) }; + } + + private async node(): Promise { + const node = await findProgram("node", this.env, this.platform); + if (!node) return this.row("node", "missing", null, "Node.js isn't installed"); + const result = await this.tool(node, ["--version"]); + const text = result.stdout.trim(); + if (!result.ok) return this.row("node", "error", null, `${node} doesn't run`); + const parsed = parseVersion(text); + if (!parsed) return this.row("node", "error", null, `Unexpected \`node --version\`: ${text}`); + const version = showVersion(parsed); + if (older(parsed, MIN_NODE)) return this.row("node", "error", version, `Node ${version} — needs ${showVersion(MIN_NODE)} or newer`); + const npm = await this.npm(node); + return npm === undefined + ? this.row("node", "missing", version, `Node ${version} found, but not npm`) + : this.row("node", "ok", version, `npm ${npm}`); + } + + /** `npm --version`; on Windows npm is a `.cmd`, which only a shell runs, so its `npm-cli.js` runs under `node` instead. */ + private async npm(node: string): Promise { + const npm = await findProgram("npm", this.env, this.platform); + if (!npm) return undefined; + const result = this.platform === "win32" && /\.(cmd|bat)$/i.test(npm) + ? await this.tool(node, [join(dirname(npm), "node_modules", "npm", "bin", "npm-cli.js"), "--version"]) + : await this.tool(npm, ["--version"]); + const version = result.stdout.trim(); + return result.ok && version !== "" ? version : undefined; + } + + private async git(): Promise { + const missing = this.row("git", "missing", null, "Git isn't installed"); + const git = await findProgram("git", this.env, this.platform); + if (!git) return missing; + // macOS's /usr/bin/git is a stub that offers the Command Line Tools until they are installed. + if (this.platform === "darwin" && git === "/usr/bin/git" && !(await this.tool("/usr/bin/xcode-select", ["-p"])).ok) return missing; + const result = await this.tool(git, ["--version"]); + if (!result.ok) return missing; + const version = result.stdout.trim().replace(/^git version /, "").trim(); + return this.row("git", "ok", version || null, null); + } + + private async engram(): Promise { + const override = this.env.ENGRAM_BIN; + let engram: string | undefined; + if (override) { + engram = await findProgram(override, this.env, this.platform); + if (!engram) return this.row("engram", "error", null, `ENGRAM_BIN points to ${override}, which can't be run. Fix or remove it.`); + } else { + engram = await findProgram("engram", this.env, this.platform); + } + const result = engram ? await this.tool(engram, ["version"]) : undefined; + if (!result?.ok) return this.row("engram", "missing", null, "Not installed"); + // `engram 1.18.0`, then maybe an update notice: the first line's last word. + const line = result.stdout.trim().split(/\r?\n/, 1)[0].trim() || "installed"; + const word = line.split(/\s+/).at(-1) ?? ""; + const parsed = parseVersion(word); + if (parsed && older(parsed, MIN_ENGRAM)) { + return this.row("engram", "error", showVersion(parsed), `Engram ${showVersion(parsed)} — needs ${showVersion(MIN_ENGRAM)} or newer`); + } + return this.row("engram", "ok", parsed ? showVersion(parsed) : null, line); + } + + /** The launcher's own `setup --check --json` for this home; a `--link` home is set up once it lists gentle-engram. */ + private async companion(): Promise { + if (!this.companionLaunch) return this.row("companion", "error", null, "This server can't check its setup"); + const launch = this.companionLaunch(); + const result = await run(launch.command, launch.args, { env: launch.env, cwd: launch.cwd, timeoutMs: this.limits.companionTimeoutMs, outputBytes: this.limits.outputBytes }); + let report: { needsSetup?: unknown; reasons?: unknown; home?: { mode?: unknown }; error?: unknown } | undefined; + try { + report = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1) ?? ""); + } catch { /* reported below */ } + if (!report || typeof report !== "object" || (result.code !== 0 && result.code !== 1)) { + const why = typeof report?.error === "string" ? report.error : result.code === null ? "it didn't finish" : `it exited with ${result.code}`; + return this.row("companion", "error", null, `\`gentle-shell setup --check\` failed: ${why}`); + } + const home = this.agentHome; + if (report.home?.mode === "link" && home !== undefined) { + let settings: unknown; + try { settings = JSON.parse(await readFile(join(home, "settings.json"), "utf8")); } catch { /* not set up */ } + return settingsList(settings, "gentle-engram") + ? this.row("companion", "ok", null, `Linked to ${home}`) + : this.row("companion", "missing", null, `${home} isn't set up yet`); + } + const entry = await this.marker(); + if (report.needsSetup === false) return this.row("companion", "ok", entry?.gentleAi ?? null, entry ? `Set up ${entry.at.slice(0, 10)}` : null); + const reasons = Array.isArray(report.reasons) ? report.reasons : []; + if (!entry || reasons.includes("never-provisioned")) return this.row("companion", "missing", null, "Not set up yet — the first chat would do it silently"); + if (reasons.includes("gentle-ai-changed")) return this.row("companion", "error", entry.gentleAi, `Set up with Gentle AI ${entry.gentleAi}`); + return this.row("companion", "error", entry.gentleAi, + `Set up with gentle-pi ${entry.gentlePi ?? "an older version"}; ${this.version ?? "another version"} is installed`); + } + + /** This home's setup record in the launcher config (`GENTLE_SHELL_CONFIG`, else `~/.gentle-shell/config.json`). */ + private async marker(): Promise<{ gentleAi: string; gentlePi?: string; at: string } | undefined> { + if (this.agentHome === undefined) return undefined; + const path = this.env.GENTLE_SHELL_CONFIG || launcherConfigPath(homedir()); + let text: string | undefined; + try { text = await readFile(path, "utf8"); } catch { return undefined; } + let key = this.agentHome; + try { key = realpathSync(key); } catch { /* as given */ } + return provisionedEntry(parseRawLauncherConfig(text), key); + } +} diff --git a/lib/serve-cli.ts b/lib/serve-cli.ts new file mode 100644 index 000000000..c7c2a74ad --- /dev/null +++ b/lib/serve-cli.ts @@ -0,0 +1,930 @@ +// `gentle-shell serve`: argument parsing, the per-user server file and lock +// under `/serve`, the foreground server, the detached daemon, the +// local CLI client (`status`, `stop`, `pair`, `devices`) that talks to the +// running server with the owner-only admin token from the server file, and +// `share`, which opens the server to the local network (answering LAN +// discovery) and prints the short pairing code plus a connection code fallback. + +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs"; +import { createServer as createNetServer } from "node:net"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { INTERACTIVE_HOST_ENV } from "./rpc-host.ts"; +import { DEFAULT_PAIR_SCOPES, parseScopes, readDevicesFile, ServeAuth, writeDevicesFile, type PublicDevice, type ServeScope } from "./serve-auth.ts"; +import { isLoopbackHost, isUnspecified, SERVE_PROTOCOL, startServeServer, type ServeServer, type ServeTower } from "./serve-server.ts"; +import { parseRelayUrl } from "./serve-relay.ts"; +import { loadOrCreateServeTls, type ServeTlsIdentity } from "./serve-tls.ts"; +import type { SessionLaunch } from "./serve-session.ts"; +import { AUTOSTART_LABEL, autostartCommand, autostartFile, autostartInstalled, defaultShareSystem, encodeConnectionCode, firewallHint, HOST_NAME, installAutostart, ownHostNames, + removeAutostart, SHARE_DEFAULT_PORT, SHARE_FORWARD_PORTS, SHARE_PORT_ATTEMPTS, shareAddresses, type PortRange, type ShareSystem } from "./serve-share.ts"; +import type { UpgradeChannel } from "./serve-upgrade.ts"; +import { openTowerServer } from "./tower-open.ts"; + +export const SERVE_SERVER_FILE_SCHEMA = "gentle-shell.serve.server/v1"; +const DEFAULT_LISTEN = { host: "127.0.0.1", port: 0 }; +const DAEMON_START_TIMEOUT_MS = 15_000; +const STOP_TIMEOUT_MS = 15_000; + +// --- arguments ----------------------------------------------------------------- + +export type ServeArgs = + | { action: "start"; host: string; port: number; foreground: boolean; json: boolean; allowHosts?: string[]; forwardPorts?: PortRange; noTls?: true; relay?: string } + | { action: "status"; json: boolean } + | { action: "stop"; endSessions: boolean } + | { action: "pair"; scopes: ServeScope[]; json: boolean } + | { action: "devices"; revoke?: string; json: boolean } + | { action: "share"; port: number; always: boolean; json: boolean; noTls?: true; relay?: string } + | { action: "share-off" } + | { action: "help" }; + +export function parseListen(value: string): { host: string; port: number } | { error: string } { + const m = /^(?:\[([0-9A-Fa-f:.]+)\]|([^:\s[\]]+))?:(\d{1,5})$/.exec(value) ?? (/^\d{1,5}$/.test(value) ? [value, undefined, undefined, value] : null); + if (!m) return { error: `--listen needs : (got "${value}")` }; + const port = Number(m[3]); + if (!(port >= 0 && port <= 65535)) return { error: `--listen port must be 0-65535 (got "${m[3]}")` }; + const host = m[1] !== undefined ? m[1] : m[2] ?? DEFAULT_LISTEN.host; + return { host: host.toLowerCase() === "localhost" ? "127.0.0.1" : host, port }; +} + +export function parseServeArgs(args: readonly string[]): ServeArgs | { error: string } { + const first = args[0]; + const sub = first === "status" || first === "stop" || first === "pair" || first === "devices" || first === "share" ? first : undefined; + const rest = sub ? args.slice(1) : args; + let json = false; + let foreground = false; + let listen = DEFAULT_LISTEN; + let revoke: string | undefined; + let sharePort: number | undefined; + let always = false; + let off = false; + let endSessions = false; + let forwardPorts: PortRange | undefined; + let noTls = false; + let relay: string | undefined; + const scopeValues: string[] = []; + const allowHosts: string[] = []; + for (let i = 0; i < rest.length; i += 1) { + const arg = rest[i]; + const value = (flag: string): string | undefined => { + if (arg === flag) return rest[(i += 1)]; + return arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : undefined; + }; + if (arg === "--help" || arg === "-h") return { action: "help" }; + if (arg === "--json" && sub !== "stop") { json = true; continue; } + if (sub === undefined && arg === "--foreground") { foreground = true; continue; } + if ((sub === undefined || sub === "share") && arg === "--no-tls") { noTls = true; continue; } + if ((sub === undefined || sub === "share") && (arg === "--relay" || arg.startsWith("--relay="))) { + const parsed = parseRelayUrl(value("--relay") ?? ""); + if ("error" in parsed) return { error: `--relay: ${parsed.error}` }; + relay = parsed.url; + continue; + } + if (sub === undefined && (arg === "--listen" || arg.startsWith("--listen="))) { + const v = value("--listen"); + if (v === undefined) return { error: "--listen needs :" }; + const parsed = parseListen(v); + if ("error" in parsed) return parsed; + listen = parsed; + continue; + } + if (sub === undefined && (arg === "--allow-host" || arg.startsWith("--allow-host="))) { + const v = value("--allow-host")?.toLowerCase(); + if (v === undefined || !HOST_NAME.test(v)) return { error: `--allow-host needs a DNS name without a port (got "${v ?? ""}")` }; + if (!allowHosts.includes(v)) allowHosts.push(v); + continue; + } + if (sub === undefined && (arg === "--forward-ports" || arg.startsWith("--forward-ports="))) { + const v = value("--forward-ports"); + const parsed = v === undefined ? undefined : parsePortRange(v); + if (!parsed) return { error: `--forward-ports needs a port range like 8800-8899 (got "${v ?? ""}")` }; + forwardPorts = parsed; + continue; + } + if (sub === "pair" && (arg === "--scope" || arg.startsWith("--scope="))) { + const v = value("--scope"); + if (v === undefined) return { error: "--scope needs a scope list" }; + scopeValues.push(v); + continue; + } + if (sub === "devices" && (arg === "--revoke" || arg.startsWith("--revoke="))) { + const v = value("--revoke"); + if (!v || !/^[A-Za-z0-9_]{1,64}$/.test(v)) return { error: "--revoke needs a device id" }; + revoke = v; + continue; + } + if (sub === "share" && (arg === "--port" || arg.startsWith("--port="))) { + const v = value("--port"); + if (v === undefined || !/^\d{1,5}$/.test(v) || Number(v) < 1 || Number(v) > 65535) return { error: `--port needs a port 1-65535 (got "${v ?? ""}")` }; + sharePort = Number(v); + continue; + } + if (sub === "share" && arg === "--always") { always = true; continue; } + if (sub === "share" && arg === "--off") { off = true; continue; } + if (sub === "stop" && arg === "--sessions") { endSessions = true; continue; } + return { error: `unknown serve${sub ? ` ${sub}` : ""} argument "${arg}"` }; + } + if (noTls && relay !== undefined) return { error: "--relay needs TLS (the relay must only see ciphertext): leave out --no-tls" }; + const network = { ...(noTls ? { noTls: true as const } : {}), ...(relay === undefined ? {} : { relay }) }; + if (sub === "status") return { action: "status", json }; + if (sub === "stop") return { action: "stop", endSessions }; + if (sub === "devices") return { action: "devices", json, ...(revoke === undefined ? {} : { revoke }) }; + if (sub === "share") { + if (off) return always || json || sharePort !== undefined || noTls || relay !== undefined ? { error: "serve share --off takes no other argument" } : { action: "share-off" }; + return { action: "share", port: sharePort ?? SHARE_DEFAULT_PORT, always, json, ...network }; + } + if (sub === "pair") { + if (scopeValues.length === 0) return { action: "pair", scopes: [...DEFAULT_PAIR_SCOPES], json }; + const parsed = parseScopes(scopeValues); + return "error" in parsed ? parsed : { action: "pair", scopes: parsed.scopes, json }; + } + return { action: "start", host: listen.host, port: listen.port, foreground, json, ...(allowHosts.length === 0 ? {} : { allowHosts }), ...(forwardPorts ? { forwardPorts } : {}), ...network }; +} + +/** `-`, both 1-65535, from ≤ to, at most 1000 ports. */ +export function parsePortRange(value: string): PortRange | undefined { + const m = /^(\d{1,5})-(\d{1,5})$/.exec(value); + if (!m) return undefined; + const from = Number(m[1]); + const to = Number(m[2]); + return from >= 1 && to <= 65535 && from <= to && to - from < 1000 ? { from, to } : undefined; +} + +export const SERVE_HELP = [ + "Usage: gentle-shell [home selectors] serve share [--port ] [--always] [--no-tls] [--relay gsr://:] [--json]", + " gentle-shell [home selectors] serve share --off", + " gentle-shell [home selectors] serve [--listen :] [--allow-host ]... [--forward-ports -] [--no-tls] [--relay gsr://:] [--foreground] [--json]", + " gentle-shell [home selectors] serve status [--json]", + " gentle-shell [home selectors] serve stop [--sessions]", + " gentle-shell [home selectors] serve pair [--scope ] [--json]", + " gentle-shell [home selectors] serve devices [--revoke ] [--json]", + "", + "Runs one server per agent home that owns Gentle Shell sessions (one `--mode rpc` child each)", + "and lets paired devices drive them over HTTP + Server-Sent Events. Sessions keep running when", + "clients disconnect. Binds 127.0.0.1 on a random port unless --listen says otherwise; every", + "request needs a device token (there is no unauthenticated mode). A non-loopback --listen", + "serves HTTPS with a self-signed certificate made on first run (/serve/tls/); devices pin", + "its fingerprint. This computer itself may keep using plain http://127.0.0.1.", + "", + " serve share The easy way to connect Gentle Shell GPUI from another computer on your", + " network: opens the server to the network (HTTPS, port 8787 or the next", + " free one; --port picks another) and prints a short code to enter in the app", + " (valid 5 minutes, once). The app finds this computer on the network by itself", + " (UDP broadcast on the same port); where it cannot (another subnet, a tailnet,", + " client isolation, a relay), paste the long gsc1. code printed under it. Reuses", + " a server already on the network; one on this computer only (or with other", + " TLS or relay settings) is reopened when it runs no sessions. Pages it forwards", + " to the app (dev servers, the design canvas, Gentle Tower) take ports 8800-8899.", + " --always Also start that server at every login (systemd user unit on Linux, a", + " LaunchAgent on macOS). 'serve share --off' turns it off and stops it.", + " serve Start the server in the background (--foreground keeps it in this terminal).", + " serve status Show whether the server runs, its URL and its sessions.", + " serve stop Stop the server. Its sessions keep running and the next server picks them", + " up (a session no server came back to stops after 24 hours); --sessions", + " stops them too.", + " serve pair Print a one-time pairing code (single use, 5 minutes). Scopes default to", + " sessions:read,sessions:operate,terminal; leave terminal out (--scope", + " sessions:read,sessions:operate) for a device that must not open shells, and", + " add admin only for a device you fully trust.", + " serve devices List paired devices; --revoke removes one at once (its streams close).", + "", + " --allow-host One more name clients may use in the Host header, for example a tailnet", + " MagicDNS name (repeatable). Names not allowed are refused (DNS rebinding).", + " --forward-ports Listen ports for forwarded pages (for example 8800-8899), so a firewall can", + " open one range; without it each forward takes a random port.", + " --no-tls Plain HTTP on the network, as before TLS existed: tokens and traffic cross", + " the network unencrypted. Only for a network that encrypts by itself.", + " --relay Also register with a relay (gentle-shell relay), so devices outside this", + " network reach the server through it with the long code. The relay sees only", + " TLS ciphertext. Its secret comes from GENTLE_SHELL_RELAY_SECRET or", + " /serve/relay-secret.", + "", + "Paired devices can also read and write files, run git and open persistent terminals here,", + "all as the user the server runs as. Terminals run in gentle-term-host ($GENTLE_TERM_HOST,", + "/serve/bin/gentle-term-host or on PATH), which keeps them alive across clients and", + "server restarts.", + "", + "Protocol, endpoints and security model: docs/serve.md.", +].join("\n"); + +// --- server file and lock -------------------------------------------------------- + +export interface ServerFile { + schema: typeof SERVE_SERVER_FILE_SCHEMA; + protocol: number; + serverId: string; + url: string; + listen: { host: string; port: number }; + pid: number; + startedAt: string; + version: string; + /** Owner-only local admin token for the CLI. */ + adminToken: string; + /** Whether it answers LAN discovery; absent in files written before discovery existed. */ + discovery?: boolean; + /** Listen ports forwarded pages take; absent when the OS assigns them. */ + forwardPorts?: PortRange; + /** The certificate's fingerprint when the server serves HTTPS on the network. */ + fingerprint?: string; + /** The relay it registers with (`gsr://host:port`). */ + relay?: string; +} + +export function serveDir(agentHome: string): string { + return join(agentHome, "serve"); +} + +export function serveFiles(agentHome: string) { + const dir = serveDir(agentHome); + return { dir, server: join(dir, "server.json"), lock: join(dir, "server.lock"), devices: join(dir, "devices.json"), log: join(dir, "server.log") }; +} + +function privateDir(dir: string): void { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + try { chmodSync(dir, 0o700); } catch { /* Windows: ACLs, not modes */ } +} + +export function readServerFile(path: string): ServerFile | undefined { + try { + const parsed = JSON.parse(readFileSync(path, "utf8")) as ServerFile; + if (parsed?.schema !== SERVE_SERVER_FILE_SCHEMA || typeof parsed.url !== "string" || typeof parsed.pid !== "number" || typeof parsed.adminToken !== "string") return undefined; + return parsed; + } catch { + return undefined; + } +} + +function writeServerFile(path: string, file: ServerFile): void { + const temp = `${path}.${process.pid}.tmp`; + writeFileSync(temp, `${JSON.stringify(file, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows */ } +} + +export function processAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "EPERM"; + } +} + +/** + * Single instance per agent home: an exclusive create of the lock file, which + * names its pid. A lock whose pid is gone is stale and is taken over once. + */ +export function acquireServeLock(lockPath: string, pid: number = process.pid): { acquired: true } | { heldBy: number } { + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + const fd = openSync(lockPath, "wx", 0o600); + writeSync(fd, `${pid}\n`); + closeSync(fd); + return { acquired: true }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + let holder = NaN; + try { holder = Number(readFileSync(lockPath, "utf8").trim()); } catch { /* vanished: retry */ } + if (Number.isInteger(holder) && holder !== pid && processAlive(holder)) return { heldBy: holder }; + rmSync(lockPath, { force: true }); + } + } + return { heldBy: NaN }; +} + +function releaseServeLock(lockPath: string, pid: number = process.pid): void { + try { + if (Number(readFileSync(lockPath, "utf8").trim()) === pid) rmSync(lockPath, { force: true }); + } catch { /* already gone */ } +} + +/** The server file of a live server, or undefined (a stale file is ignored). */ +export function liveServer(agentHome: string): ServerFile | undefined { + const file = readServerFile(serveFiles(agentHome).server); + return file && processAlive(file.pid) ? file : undefined; +} + +// --- running ----------------------------------------------------------------------- + +export interface ServeCommandContext { + agentHome: string; + /** Home selector flags that make a child resolve this same home. */ + homeFlags: string[]; + /** Absolute path of bin/gentle-shell.mjs. */ + launcher: string; + nodePath: string; + version: string; + env: NodeJS.ProcessEnv; + stdout: (text: string) => void; + stderr: (text: string) => void; + /** Resolves when a foreground server should stop (defaults to SIGINT/SIGTERM). */ + untilStopped?: (stopRequested: Promise) => Promise; + /** Machine facts and the command runner for `serve share` (defaults to this machine). */ + system?: ShareSystem; + /** + * The launcher that runs the installed version after an upgrade, resolved then: + * `launcher` for an npm or pnpm install (upgraded in place), the one `current` + * names in a bundled install (an upgrade installs a new version beside this one). + */ + restartLauncher?: () => string; + /** Test seam: the upgrade command `POST /api/upgrade` runs (defaults to `upgradeLaunch`). */ + upgradeCommand?: (channel: UpgradeChannel | undefined) => SessionLaunch; + /** Test seam: the setup command `POST /api/setup` runs (defaults to `setupLaunch`). */ + setupCommand?: () => SessionLaunch; +} + +/** The exit code that asks a service manager (systemd `Restart=on-failure`, launchd `KeepAlive`) to start the upgraded server. */ +export const SERVE_RESTART_EXIT = 75; + +/** + * Whether a service manager runs this server (`serve share --always`): systemd + * names this process in `SYSTEMD_EXEC_PID`, launchd sets its job label. + */ +export function supervisedServe(env: NodeJS.ProcessEnv, pid: number = process.pid): boolean { + return env.SYSTEMD_EXEC_PID === String(pid) || env.XPC_SERVICE_NAME === AUTOSTART_LABEL; +} + +/** `gentle-shell upgrade [--channel ]`, run by this launcher outside any session, never prompting. */ +export function upgradeLaunch(ctx: Pick, channel: UpgradeChannel | undefined): SessionLaunch { + const env: NodeJS.ProcessEnv = { ...ctx.env, NO_COLOR: "1", FORCE_COLOR: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + delete env[INTERACTIVE_HOST_ENV]; + return { command: ctx.nodePath, args: [ctx.launcher, "upgrade", ...(channel === undefined ? [] : ["--channel", channel])], cwd: homedir(), env }; +} + +/** `gentle-shell [home flags] setup` for this server's home, run by this launcher outside any session, never prompting. */ +export function setupLaunch(ctx: Pick, args: readonly string[] = []): SessionLaunch { + const env: NodeJS.ProcessEnv = { ...ctx.env, NO_COLOR: "1", FORCE_COLOR: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + delete env[INTERACTIVE_HOST_ENV]; + return { command: ctx.nodePath, args: [ctx.launcher, ...ctx.homeFlags, "setup", ...args], cwd: homedir(), env }; +} + +/** The version the launcher's package now holds, read after an upgrade. */ +function launcherVersion(launcher: string): string | undefined { + try { + const version = JSON.parse(readFileSync(join(dirname(dirname(launcher)), "package.json"), "utf8"))?.version; + return typeof version === "string" && version.length <= 64 ? version : undefined; + } catch { + return undefined; + } +} + +/** + * The child for one session: this same launcher, same home, Pi RPC mode, Desktop RPC on. + * `sessionId` resumes by exact id (`--session-id`): the project's session with that id, or a + * new one under it when Pi never wrote it (a conversation with no messages yet has no file). + * `--session` would fail then, and could stop to ask about forking another project's session. + */ +export function sessionLaunch(ctx: Pick, input: { cwd: string; sessionId?: string }): SessionLaunch { + const env: NodeJS.ProcessEnv = { ...ctx.env, [INTERACTIVE_HOST_ENV]: "1", GENTLE_DESIGN_OPEN_BROWSER: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + return { + command: ctx.nodePath, + args: [ctx.launcher, ...ctx.homeFlags, "--mode", "rpc", ...(input.sessionId === undefined ? [] : ["--session-id", input.sessionId])], + cwd: input.cwd, + env, + }; +} + +/** + * A one-shot prompt (`POST /api/print`): this same launcher and home, run the way the app runs + * it for commit messages (`--print --no-session --no-tools`), with the prompt on stdin. Never the + * interactive host: nothing answers its dialogs in a one-shot run. + */ +export function printLaunch(ctx: Pick, input: { cwd: string; model?: string }): SessionLaunch { + const env: NodeJS.ProcessEnv = { ...ctx.env, GENTLE_DESIGN_OPEN_BROWSER: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + delete env[INTERACTIVE_HOST_ENV]; + return { + command: ctx.nodePath, + args: [ctx.launcher, ...ctx.homeFlags, "--print", "--no-session", "--no-tools", ...(input.model === undefined ? [] : ["--model", input.model])], + cwd: input.cwd, + env, + }; +} + +function untilSignal(stopRequested: Promise): Promise { + const { promise, resolve } = Promise.withResolvers(); + const done = () => { + process.off("SIGINT", done); + process.off("SIGTERM", done); + process.off("SIGHUP", done); + resolve(); + }; + process.on("SIGINT", done); + process.on("SIGTERM", done); + if (process.platform !== "win32") process.on("SIGHUP", done); + stopRequested.then(done); + return promise; +} + +function plainHttpWarning(host: string): string { + return `gentle-shell serve: warning: listening on ${host} over plain HTTP (--no-tls). Device tokens and session traffic cross the network unencrypted; use it only on a network that encrypts by itself, such as a tailnet.\n`; +} + +type StartArgs = { host: string; port: number; allowHosts?: readonly string[]; forwardPorts?: PortRange; noTls?: true; relay?: string }; + +/** The relay secret a server presents: `GENTLE_SHELL_RELAY_SECRET`, else the first line of `/serve/relay-secret`. */ +export function relaySecret(env: NodeJS.ProcessEnv, serveDirectory: string): string | undefined { + const fromEnv = env.GENTLE_SHELL_RELAY_SECRET?.trim(); + if (fromEnv) return fromEnv; + try { + return readFileSync(join(serveDirectory, "relay-secret"), "utf8").split(/\r?\n/)[0].trim() || undefined; + } catch { + return undefined; + } +} + +/** HTTPS on a network listen (unless --no-tls) and always with a relay: the certificate, made on first run. */ +function serverTls(ctx: ServeCommandContext, args: StartArgs, serveDirectory: string): ServeTlsIdentity | undefined { + if (args.noTls || (isLoopbackHost(args.host) && args.relay === undefined)) return undefined; + const system = ctx.system ?? defaultShareSystem(ctx.env); + const name = system.hostname(); + const addresses = isUnspecified(args.host) ? shareAddresses(system.networkInterfaces(), name) : [args.host]; + return loadOrCreateServeTls(serveDirectory, { + commonName: `gentle-shell serve ${name}`, + dnsNames: ["localhost", ...ownHostNames(name), ...(args.allowHosts ?? [])], + ips: ["127.0.0.1", "::1", ...addresses], + }); +} + +/** Gentle Tower in this process, on 127.0.0.1 with a fresh token: what `gentle-shell tower` runs, never a browser. */ +async function startTower(env: NodeJS.ProcessEnv): Promise { + const tower = await openTowerServer(env); + return { port: tower.port, path: new URL(tower.url).pathname, close: () => tower.close() }; +} + +async function runForeground(ctx: ServeCommandContext, args: StartArgs & { json: boolean }): Promise { + const result = await serveForeground(ctx, args); + if (result.restartPort === undefined) return result.code; + return restartServer(ctx, { ...args, port: result.restartPort }); +} + +/** Serves until stopped; `restartPort` when it stopped for an upgrade, so the next server takes the same address. */ +async function serveForeground(ctx: ServeCommandContext, args: StartArgs & { json: boolean }): Promise<{ code: number; restartPort?: number }> { + const files = serveFiles(ctx.agentHome); + privateDir(files.dir); + const lock = acquireServeLock(files.lock); + if ("heldBy" in lock) { + const running = readServerFile(files.server); + ctx.stderr(`gentle-shell serve: already running${Number.isNaN(lock.heldBy) ? "" : ` (pid ${lock.heldBy})`}${running ? ` at ${running.url}` : ""}\n`); + return { code: 1 }; + } + let server: ServeServer | undefined; + let endSessions = false; + let restart = false; + try { + const tls = serverTls(ctx, args, files.dir); + if (!isLoopbackHost(args.host) && !tls) ctx.stderr(plainHttpWarning(args.host)); + const secret = args.relay === undefined ? undefined : relaySecret(ctx.env, files.dir); + const adminToken = `gsa_${randomBytes(32).toString("base64url")}`; + const auth = new ServeAuth({ devicesFile: files.devices, adminToken }); + const stop = Promise.withResolvers(); + const log = (line: string) => ctx.stderr(`${new Date().toISOString()} ${line}\n`); + server = await startServeServer({ + host: args.host, + port: args.port, + allowHosts: args.allowHosts ?? [], + ...(args.forwardPorts ? { forwardPorts: args.forwardPorts } : {}), + ...(tls ? { tls } : {}), + ...(args.relay === undefined ? {} : { relay: { url: args.relay, ...(secret === undefined ? {} : { secret }) } }), + startTower: () => startTower(ctx.env), + serveDir: files.dir, + env: ctx.env, + auth, + version: ctx.version, + launchSession: (input) => sessionLaunch(ctx, input), + launchPrint: (input) => printLaunch(ctx, input), + log, + onStopRequested: (request) => { endSessions = request.endSessions; stop.resolve(); }, + upgrade: { + launch: (channel) => (ctx.upgradeCommand ?? ((chosen: UpgradeChannel | undefined) => upgradeLaunch(ctx, chosen)))(channel), + installedVersion: () => launcherVersion(ctx.restartLauncher?.() ?? ctx.launcher), + // Sessions keep running under their keepers; the next server reattaches them. + onUpgraded: () => { restart = true; stop.resolve(); }, + // Setup installs the home's companion packages, never the launcher: no restart. + setup: () => (ctx.setupCommand ?? (() => setupLaunch(ctx)))(), + }, + // `GET /api/checks`: the companion row is the launcher's own read-only `setup --check`. + checks: { companion: () => setupLaunch(ctx, ["--check", "--json"]), agentHome: ctx.agentHome }, + }); + const file: ServerFile = { + schema: SERVE_SERVER_FILE_SCHEMA, + protocol: SERVE_PROTOCOL, + serverId: server.serverId, + url: server.url, + listen: { host: args.host, port: server.port }, + pid: process.pid, + startedAt: new Date(server.startedAt).toISOString(), + version: ctx.version, + adminToken, + discovery: server.discovery, + ...(args.forwardPorts ? { forwardPorts: args.forwardPorts } : {}), + ...(server.fingerprint === undefined ? {} : { fingerprint: server.fingerprint }), + ...(args.relay === undefined ? {} : { relay: args.relay }), + }; + writeServerFile(files.server, file); + if (tls) log(`HTTPS for the network: certificate ${tls.fingerprint}${tls.created ? " (new)" : ""}`); + if (args.relay !== undefined && secret === undefined) log(`relay: no relay secret (GENTLE_SHELL_RELAY_SECRET or ${join(files.dir, "relay-secret")}); a relay that has one refuses this server`); + ctx.stdout(args.json + ? `${JSON.stringify({ schema: "gentle-shell.serve/v1", url: server.url, pid: process.pid, serverId: server.serverId, ...(server.fingerprint === undefined ? {} : { fingerprint: server.fingerprint }), ...(args.relay === undefined ? {} : { relay: args.relay }) })}\n` + : `Gentle Shell server: ${server.url} (pid ${process.pid})\n${server.fingerprint === undefined ? "" : `HTTPS on the network, certificate fingerprint ${server.fingerprint}\n`}${args.relay === undefined ? "" : `Relay: ${args.relay}\n`}Pair a device with 'gentle-shell serve pair'. Press Ctrl+C to stop.\n`); + await (ctx.untilStopped ?? untilSignal)(stop.promise); + log(restart ? "stopping to restart on the upgraded version" : "stopping"); + return restart ? { code: 0, restartPort: server.port } : { code: 0 }; + } catch (error) { + ctx.stderr(`gentle-shell serve: could not start: ${error instanceof Error ? error.message : String(error)}\n`); + return { code: 1 }; + } finally { + await server?.close({ endSessions }); + if (readServerFile(files.server)?.pid === process.pid) rmSync(files.server, { force: true }); + releaseServeLock(files.lock); + } +} + +/** + * After an upgrade, once this server let go of its lock and server file: a + * service manager starts the upgraded server itself (this process exits with + * `SERVE_RESTART_EXIT`); otherwise a detached `serve --foreground` on the new + * version takes the same address, logging to `server.log`. + */ +function restartServer(ctx: ServeCommandContext, args: StartArgs): number { + const stamp = () => new Date().toISOString(); + if (supervisedServe(ctx.env)) { + ctx.stderr(`${stamp()} exiting with ${SERVE_RESTART_EXIT}: the service manager starts the upgraded server\n`); + return SERVE_RESTART_EXIT; + } + const files = serveFiles(ctx.agentHome); + const logFd = openSync(files.log, "a", 0o600); + try { + const child = spawn(ctx.nodePath, [ctx.restartLauncher?.() ?? ctx.launcher, ...ctx.homeFlags, ...foregroundArgs(args)], { + detached: true, + stdio: ["ignore", logFd, logFd], + env: ctx.env, + windowsHide: true, + }); + child.once("error", (error) => ctx.stderr(`${stamp()} could not restart: ${error.message}\n`)); + child.unref(); + ctx.stderr(`${stamp()} restarted on the upgraded version as pid ${child.pid} (log: ${files.log})\n`); + return 0; + } catch (error) { + ctx.stderr(`${stamp()} could not restart: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } finally { + closeSync(logFd); + } +} + +/** `serve --foreground` with the same listen address, hosts, forward ports, TLS choice and relay. */ +function foregroundArgs(args: StartArgs): string[] { + const listen = `${args.host.includes(":") ? `[${args.host}]` : args.host}:${args.port}`; + const allow = (args.allowHosts ?? []).flatMap((name) => ["--allow-host", name]); + const ports = args.forwardPorts ? ["--forward-ports", `${args.forwardPorts.from}-${args.forwardPorts.to}`] : []; + const network = [...(args.noTls ? ["--no-tls"] : []), ...(args.relay === undefined ? [] : ["--relay", args.relay])]; + return ["serve", "--foreground", "--listen", listen, ...allow, ...ports, ...network]; +} + +async function startDaemon(ctx: ServeCommandContext, args: StartArgs & { json: boolean }): Promise { + const files = serveFiles(ctx.agentHome); + const running = liveServer(ctx.agentHome); + if (running) { + ctx.stderr(`gentle-shell serve: already running at ${running.url} (pid ${running.pid})\n`); + return 1; + } + const started = await spawnDaemon(ctx, args); + if ("log" in started) { + ctx.stderr(`gentle-shell serve: the server did not start.${started.log ? `\n${started.log}` : ""}\n`); + return 1; + } + const file = started.file; + ctx.stdout(args.json + ? `${JSON.stringify({ schema: "gentle-shell.serve/v1", url: file.url, pid: file.pid, serverId: file.serverId })}\n` + : `Gentle Shell server: ${file.url} (pid ${file.pid})\nLog: ${files.log}\nPair a device with 'gentle-shell serve pair'; stop with 'gentle-shell serve stop'.\n`); + return 0; +} + +/** Starts `serve --foreground` detached, logging to `server.log`; on failure, the log's tail. */ +async function spawnDaemon(ctx: ServeCommandContext, args: StartArgs): Promise<{ file: ServerFile } | { log: string }> { + const files = serveFiles(ctx.agentHome); + privateDir(files.dir); + const logFd = openSync(files.log, "w", 0o600); + const child = spawn(ctx.nodePath, [ctx.launcher, ...ctx.homeFlags, ...foregroundArgs(args)], { + detached: true, + stdio: ["ignore", logFd, logFd], + env: ctx.env, + windowsHide: true, + }); + closeSync(logFd); + child.unref(); + const deadline = Date.now() + DAEMON_START_TIMEOUT_MS; + while (Date.now() < deadline) { + const file = readServerFile(files.server); + if (file?.pid === child.pid) return { file }; + if (child.exitCode !== null || child.signalCode !== null) break; + await new Promise((r) => setTimeout(r, 100)); + } + let log = ""; + try { log = readFileSync(files.log, "utf8").slice(-2000); } catch { /* no log */ } + return { log }; +} + +interface ApiResult { + status: number; + data: Partial & { error?: { code?: string; message?: string } }; +} + +interface SessionSummary { + id: string; + state: string; + name: string | null; + cwd?: string; + seq: number; + subscribers: number; + pendingDialogs: number; +} + +async function api(server: ServerFile, method: string, path: string, body?: unknown): Promise> { + const response = await fetch(`${server.url}${path}`, { + method, + headers: { Authorization: `Bearer ${server.adminToken}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + signal: AbortSignal.timeout(10_000), + }); + const text = await response.text(); + let data: unknown; + try { data = text ? JSON.parse(text) : {}; } catch { data = undefined; } + // The server owning this home's server file answers in its own documented shapes; fields stay optional. + const shaped = data && typeof data === "object" ? data : { error: { message: text.slice(0, 200) } }; + return { status: response.status, data: shaped as ApiResult["data"] }; +} + +function apiFailure(ctx: ServeCommandContext, what: string, result: ApiResult): number { + const error = result.data.error; + ctx.stderr(`gentle-shell serve: ${what} failed (${result.status}${error?.code ? ` ${error.code}` : ""}): ${error?.message ?? "no details"}\n`); + return 1; +} + +function formatDevices(devices: readonly PublicDevice[]): string { + if (devices.length === 0) return "No paired devices.\n"; + return devices.map((d) => `${d.id} ${d.name} [${d.scopes.join(",")}] paired ${d.createdAt}${d.lastUsedAt ? `, last used ${d.lastUsedAt}` : ""}`).join("\n") + "\n"; +} + +async function waitForExit(pid: number, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (!processAlive(pid)) return true; + await new Promise((r) => setTimeout(r, 100)); + } + return !processAlive(pid); +} + +async function stopServer(ctx: ServeCommandContext, server: ServerFile, endSessions = false): Promise { + const result = await api(server, "POST", "/api/server/stop", { endSessions }); + if (result.status !== 202) process.kill(server.pid, "SIGTERM"); + if (await waitForExit(server.pid, STOP_TIMEOUT_MS)) return true; + ctx.stderr(`gentle-shell serve: pid ${server.pid} is still running\n`); + return false; +} + +// --- share ------------------------------------------------------------------------- + +const LAN_HOST = "0.0.0.0"; + +function canBind(port: number, host: string): Promise { + const { promise, resolve } = Promise.withResolvers(); + const probe = createNetServer(); + probe.once("error", () => resolve(false)); + probe.listen(port, host, () => probe.close(() => resolve(true))); + return promise; +} + +/** + * Whether nothing listens on `port` (a quick probe; the bind can still race). + * Loopback too: macOS lets a wildcard bind share a port that another server + * holds on 127.0.0.1, which would then answer this machine's own requests. + */ +async function portFree(port: number): Promise { + return (await canBind(port, LAN_HOST)) && (await canBind(port, "127.0.0.1")); +} + +async function runningSessions(server: ServerFile): Promise { + const list = await api<{ sessions: SessionSummary[] }>(server, "GET", "/api/sessions"); + if (list.status !== 200 || !Array.isArray(list.data.sessions)) throw new Error(`listing its sessions failed (${list.status})`); + return list.data.sessions.filter((s) => s.state === "running").length; +} + +async function waitForServer(agentHome: string, timeoutMs: number, accept: (file: ServerFile) => boolean): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const file = liveServer(agentHome); + if (file && accept(file)) return file; + await new Promise((r) => setTimeout(r, 100)); + } + return undefined; +} + +/** + * `serve share`: make sure this home's server listens on the local network + * (start it, reopen a loopback one that runs no sessions, or reuse one already + * there), mint a pairing code and print the connection code that carries it. + */ +async function runShare(ctx: ServeCommandContext, args: { port: number; always: boolean; json: boolean; noTls?: true; relay?: string }): Promise { + const system = ctx.system ?? defaultShareSystem(ctx.env); + const files = serveFiles(ctx.agentHome); + const fail = (message: string): number => { ctx.stderr(`gentle-shell serve share: ${message}\n`); return 1; }; + if (args.always && !autostartFile(system)) return fail(`--always (start at login) is not supported on ${system.platform === "win32" ? "Windows" : system.platform} yet; run 'gentle-shell serve share' without it.`); + const allowHosts = ownHostNames(system.hostname()); + const autostartFor = (port: number) => autostartCommand({ nodePath: ctx.nodePath, launcher: ctx.launcher, homeFlags: ctx.homeFlags, port, allowHosts, forwardPorts: SHARE_FORWARD_PORTS, + ...(args.noTls ? { noTls: true } : {}), ...(args.relay === undefined ? {} : { relay: args.relay }), env: ctx.env, logFile: files.log }); + let server = liveServer(ctx.agentHome); + let opened: "started" | "reopened" | "reused" = "started"; + let atLogin = false; + try { + if (server) { + const lan = !isLoopbackHost(server.listen.host); + // TLS as asked (a server from before TLS is reopened with it); the relay asked for, when one is (none asked keeps the one it has). + const sameNetwork = (server.fingerprint !== undefined) === !args.noTls && (args.relay === undefined || server.relay === args.relay); + atLogin = lan && autostartInstalled(system, autostartFor(server.listen.port)); + if (lan && sameNetwork && (!args.always || atLogin)) { + opened = "reused"; + } else { + // Reopening it on the network, or under the service manager, would end its sessions. + const busy = await runningSessions(server); + if (busy > 0) { + return fail(!lan + ? `the server here is reachable from this computer only and has ${busy} running session(s); stop them or run 'gentle-shell serve stop', then run share again to open it to your network.` + : !sameNetwork + ? `the server has ${busy} running session(s), and changing its TLS or relay settings has to restart it; stop them or run 'gentle-shell serve stop', then try again.` + : `the server has ${busy} running session(s), and --always has to restart it; stop them or run 'gentle-shell serve stop', then try again.`); + } + if (!(await stopServer(ctx, server))) return 1; + if (!lan) opened = "reopened"; + server = undefined; + } + } + if (!server) { + const ports = Array.from({ length: SHARE_PORT_ATTEMPTS }, (_, i) => args.port + i).filter((port) => port <= 65535); + const busyPorts = `port${ports.length > 1 ? `s ${ports[0]}-${ports.at(-1)} are` : ` ${ports[0]} is`} in use; choose another with --port`; + if (args.always) { + let port: number | undefined; + for (const candidate of ports) if (await portFree(candidate)) { port = candidate; break; } + if (port === undefined) return fail(busyPorts); + const installed = await installAutostart(system, autostartFor(port)); + if ("error" in installed) return fail(`could not turn on start at login: ${installed.error}`); + server = await waitForServer(ctx.agentHome, DAEMON_START_TIMEOUT_MS, (file) => !isLoopbackHost(file.listen.host)); + if (!server) return fail(`start at login is on (${installed.file}), but the server did not start; see ${system.platform === "darwin" ? files.log : "journalctl --user -u gentle-shell-serve"}.`); + atLogin = true; + } else { + for (const port of ports) { + if (!(await portFree(port))) continue; + const started = await spawnDaemon(ctx, { host: LAN_HOST, port, allowHosts, forwardPorts: SHARE_FORWARD_PORTS, ...(args.noTls ? { noTls: true } : {}), ...(args.relay === undefined ? {} : { relay: args.relay }) }); + if ("file" in started) { server = started.file; break; } + // Taken between the probe and the bind: try the next one. + if (!started.log.includes("EADDRINUSE")) return fail(`the server did not start.${started.log ? `\n${started.log}` : ""}`); + } + if (!server) return fail(busyPorts); + } + } + + const minted = await api<{ code: string; expiresAt: string }>(server, "POST", "/api/pairing-codes", {}); + if (minted.status !== 201 || typeof minted.data.code !== "string") return apiFailure(ctx, "pair", minted); + const port = server.listen.port; + const host = server.listen.host; + const addresses = isUnspecified(host) ? shareAddresses(system.networkInterfaces(), system.hostname()) : [host.includes(":") ? `[${host}]` : host]; + const pairingCode = minted.data.code; + const fingerprint = server.fingerprint; + const code = encodeConnectionCode({ id: server.serverId, n: system.hostname(), p: port, a: addresses, c: pairingCode, + ...(fingerprint === undefined ? {} : { fp: fingerprint }), ...(server.relay === undefined ? {} : { r: server.relay }) }); + // A server file from before discovery existed has no flag: that server does not answer it. + const discovery = server.discovery === true; + if (args.json) { + ctx.stdout(`${JSON.stringify({ code, pairingCode, port, addresses, expiresAt: minted.data.expiresAt, serverId: server.serverId, discovery, tls: fingerprint !== undefined, + ...(fingerprint === undefined ? {} : { fingerprint }), ...(server.relay === undefined ? {} : { relay: server.relay }) })}\n`); + return 0; + } + const firewall = firewallHint(system.platform, port, system.has, server.forwardPorts); + ctx.stdout([ + opened === "reused" ? `The Gentle Shell server is already open to your network on port ${port}.` + : opened === "reopened" ? `Opened the Gentle Shell server to your network on port ${port} (it was reachable from this computer only).` + : `Started the Gentle Shell server for your network on port ${port}.`, + "", + ` Code: ${pairingCode}`, + "", + "In Gentle Shell GPUI → Configuration → Where agents run → Gentle Shell server, enter this code. Valid for 5 minutes, once.", + "If the app can't find this computer, paste this instead:", + code, + "", + ...(discovery ? [] : [`Discovery is off on this server (UDP port ${port} could not be opened), so the app cannot find this computer by itself: paste the long code.`]), + ...(server.relay === undefined ? [] : [`Outside this network the app reaches it through the relay ${server.relay} with the long code (the short code works on this network only).`]), + fingerprint === undefined + ? "It uses plain HTTP on your network (--no-tls): share only on a network that encrypts by itself." + : `It uses HTTPS; the app checks this computer's certificate, fingerprint ${fingerprint}.`, + ...(firewall ? [`If the app cannot find or reach this computer, or a page it opens from here, open the ports in the firewall: ${firewall}`] : []), + ...(firewall && !server.forwardPorts ? ["This server gives forwarded pages random ports; to keep them in one range (8800-8899), run 'gentle-shell serve stop' and then 'gentle-shell serve share'."] : []), + ...(atLogin ? ["It starts at every login; turn that off with 'gentle-shell serve share --off'."] : []), + ...(atLogin && system.platform === "linux" ? [`To start it at boot, before anyone logs in: sudo loginctl enable-linger ${system.user}`] : []), + "", + ].join("\n")); + return 0; + } catch (error) { + return fail(`could not reach the server${server ? ` at ${server.url}` : ""}: ${error instanceof Error ? error.message : String(error)}`); + } +} + +async function runShareOff(ctx: ServeCommandContext): Promise { + const system = ctx.system ?? defaultShareSystem(ctx.env); + if (!autostartFile(system)) { + ctx.stdout("Start at login was not on.\n"); + return 0; + } + const removed = await removeAutostart(system); + ctx.stdout(removed.removed ? `Start at login is off (removed ${removed.file}); the server it started has stopped.\n` : "Start at login was not on.\n"); + return 0; +} + +export async function runServeCommand(args: ServeArgs, ctx: ServeCommandContext): Promise { + if (args.action === "help") { + ctx.stdout(`${SERVE_HELP}\n`); + return 0; + } + if (args.action === "start") return args.foreground ? runForeground(ctx, args) : startDaemon(ctx, args); + if (args.action === "share") return runShare(ctx, args); + if (args.action === "share-off") return runShareOff(ctx); + const files = serveFiles(ctx.agentHome); + const server = liveServer(ctx.agentHome); + + if (args.action === "devices" && !server) { + // Without a server the file is the whole state: list or revoke there. + const devices = readDevicesFile(files.devices); + if (args.revoke !== undefined) { + if (!devices.some((d) => d.id === args.revoke)) { ctx.stderr(`gentle-shell serve: no device ${args.revoke}\n`); return 1; } + writeDevicesFile(files.devices, devices.filter((d) => d.id !== args.revoke)); + ctx.stdout(`Revoked ${args.revoke}.\n`); + return 0; + } + const list = devices.map(({ tokenHash: _h, ...d }) => d); + ctx.stdout(args.json ? `${JSON.stringify({ devices: list })}\n` : formatDevices(list)); + return 0; + } + if (!server) { + if (args.action === "status" && args.json) ctx.stdout(`${JSON.stringify({ running: false })}\n`); + else ctx.stderr("gentle-shell serve: not running\n"); + return args.action === "stop" ? 0 : 1; + } + + try { + if (args.action === "status") { + const info = await api<{ protocol: number; tls?: { fingerprint: string }; relay?: { url: string; connected: boolean } }>(server, "GET", "/api/server"); + const list = await api<{ sessions: SessionSummary[] }>(server, "GET", "/api/sessions"); + if (info.status !== 200) return apiFailure(ctx, "status", info); + const sessions = Array.isArray(list.data.sessions) ? list.data.sessions : []; + if (args.json) { + ctx.stdout(`${JSON.stringify({ running: true, url: server.url, pid: server.pid, serverId: server.serverId, protocol: server.protocol, startedAt: server.startedAt, version: server.version, + ...(info.data.tls ? { tls: info.data.tls } : {}), ...(info.data.relay ? { relay: info.data.relay } : {}), sessions })}\n`); + } else { + ctx.stdout(`Running at ${server.url} (pid ${server.pid}, since ${server.startedAt}, protocol ${server.protocol})\n`); + if (info.data.tls) ctx.stdout(`HTTPS on the network, certificate fingerprint ${info.data.tls.fingerprint}\n`); + if (info.data.relay) ctx.stdout(`Relay ${info.data.relay.url}: ${info.data.relay.connected ? "connected" : "not connected (retrying)"}\n`); + ctx.stdout(sessions.length === 0 ? "No sessions.\n" : sessions.map((s) => `${s.id} ${s.state} ${s.cwd ?? s.name} seq ${s.seq}, ${s.subscribers} subscriber(s)${s.pendingDialogs ? `, ${s.pendingDialogs} dialog(s) waiting` : ""}`).join("\n") + "\n"); + } + return 0; + } + if (args.action === "stop") { + if (!(await stopServer(ctx, server, args.endSessions))) return 1; + ctx.stdout("Stopped.\n"); + return 0; + } + if (args.action === "pair") { + const result = await api<{ code: string; scopes: string[]; expiresAt: string }>(server, "POST", "/api/pairing-codes", { scopes: args.scopes }); + if (result.status !== 201) return apiFailure(ctx, "pair", result); + const { code, scopes = [], expiresAt } = result.data; + if (args.json) { + ctx.stdout(`${JSON.stringify({ code, scopes, expiresAt, url: server.url })}\n`); + } else { + ctx.stdout([ + `Pairing code: ${code}`, + `Server: ${server.url}`, + `Scopes: ${scopes.join(", ")}`, + `Expires: ${expiresAt} (single use)`, + "", + "Redeem it from the device:", + ` curl -X POST ${server.url}/api/pair -H 'Content-Type: application/json' -d '{"code":"${code}","name":"my-device"}'`, + "", + ].join("\n")); + } + return 0; + } + if (args.revoke !== undefined) { + const result = await api(server, "DELETE", `/api/devices/${args.revoke}`); + if (result.status !== 200) return apiFailure(ctx, "revoke", result); + ctx.stdout(`Revoked ${args.revoke}.\n`); + return 0; + } + const result = await api<{ devices: PublicDevice[] }>(server, "GET", "/api/devices"); + if (result.status !== 200) return apiFailure(ctx, "devices", result); + ctx.stdout(args.json ? `${JSON.stringify({ devices: result.data.devices ?? [] })}\n` : formatDevices(result.data.devices ?? [])); + return 0; + } catch (error) { + ctx.stderr(`gentle-shell serve: could not reach the server at ${server.url}: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +} diff --git a/lib/serve-discovery.ts b/lib/serve-discovery.ts new file mode 100644 index 000000000..526c05095 --- /dev/null +++ b/lib/serve-discovery.ts @@ -0,0 +1,114 @@ +// LAN discovery for `gentle-shell serve`: a server open to the network answers a +// UDP broadcast query with its id, name and HTTP port, so a client that holds +// only the short pairing code can find it. Replies carry no secrets; a client +// still checks `/.well-known/gentle-shell` at the reply's source address before +// it sends the pairing code there. Zero dependencies (node:dgram). + +import { createSocket, type RemoteInfo } from "node:dgram"; + +export const DISCOVERY_QUERY = "gentle-shell/discover"; +export const DISCOVERY_REPLY = "gentle-shell/here"; +export const DISCOVERY_VERSION = 1; +/** Larger datagrams are dropped unread. */ +export const DISCOVERY_MAX_DATAGRAM = 512; +export const DISCOVERY_LIMITS = { globalPerSecond: 20, perSourcePerSecond: 4 }; + +/** Whether `datagram` is a discovery query: `{"t":"gentle-shell/discover","v":1}` (other keys ignored). */ +export function isDiscoveryQuery(datagram: Buffer): boolean { + if (datagram.length === 0 || datagram.length > DISCOVERY_MAX_DATAGRAM) return false; + try { + const value = JSON.parse(datagram.toString("utf8")) as unknown; + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const query = value as { t?: unknown; v?: unknown }; + return query.t === DISCOVERY_QUERY && query.v === DISCOVERY_VERSION; + } catch { + return false; + } +} + +/** `{"t":"gentle-shell/here","v":1,"id","n","p"}`, plus `"tls":true,"fp"` when the server serves HTTPS: a hint only, the client pins what the handshake shows after a pairing proof. */ +export function discoveryReply(server: { id: string; name: string; port: number; fingerprint?: string }): Buffer { + return Buffer.from(JSON.stringify({ t: DISCOVERY_REPLY, v: DISCOVERY_VERSION, id: server.id, n: server.name, p: server.port, ...(server.fingerprint === undefined ? {} : { tls: true, fp: server.fingerprint }) }), "utf8"); +} + +/** + * Replies allowed per one-second window, overall and per source address. The + * global cap is checked first, so a window tracks at most that many sources. + */ +export class DiscoveryRateLimiter { + private windowStart = Number.NEGATIVE_INFINITY; + private total = 0; + private readonly perSource = new Map(); + private readonly limits: typeof DISCOVERY_LIMITS; + constructor(limits: typeof DISCOVERY_LIMITS = DISCOVERY_LIMITS) { + this.limits = limits; + } + + allow(source: string, now: number): boolean { + if (now - this.windowStart >= 1000 || now < this.windowStart) { + this.windowStart = now; + this.total = 0; + this.perSource.clear(); + } + if (this.total >= this.limits.globalPerSecond) return false; + const count = this.perSource.get(source) ?? 0; + if (count >= this.limits.perSourcePerSecond) return false; + this.perSource.set(source, count + 1); + this.total += 1; + return true; + } +} + +export interface DiscoveryResponderOptions { + /** UDP port to bind on 0.0.0.0 (the server's HTTP port). */ + port: number; + serverId: string; + /** HTTP port the reply advertises. */ + httpPort: number; + name: () => string; + /** The certificate's fingerprint when the server serves HTTPS. */ + fingerprint?: string; + limits?: typeof DISCOVERY_LIMITS; + now?: () => number; + log?: (line: string) => void; +} + +export interface DiscoveryResponder { + port: number; + close(): Promise; +} + +/** Binds UDP `0.0.0.0:` and answers discovery queries by unicast to their sender; rejects when the bind fails. */ +export function startDiscoveryResponder(options: DiscoveryResponderOptions): Promise { + const now = options.now ?? Date.now; + const log = options.log ?? (() => {}); + const limiter = new DiscoveryRateLimiter(options.limits); + const socket = createSocket({ type: "udp4" }); + const { promise, resolve, reject } = Promise.withResolvers(); + let bound = false; + socket.on("error", (error) => { + if (!bound) { + socket.close(); + reject(error); + return; + } + log(`discovery: ${error.message}`); + }); + socket.on("message", (datagram: Buffer, from: RemoteInfo) => { + if (!isDiscoveryQuery(datagram) || !limiter.allow(from.address, now())) return; + const reply = discoveryReply({ id: options.serverId, name: options.name(), port: options.httpPort, ...(options.fingerprint === undefined ? {} : { fingerprint: options.fingerprint }) }); + socket.send(reply, from.port, from.address, (error) => { if (error) log(`discovery: reply to ${from.address}:${from.port} failed: ${error.message}`); }); + }); + socket.bind({ port: options.port, address: "0.0.0.0", exclusive: true }, () => { + bound = true; + resolve({ + port: socket.address().port, + close: () => { + const closed = Promise.withResolvers(); + socket.close(() => closed.resolve()); + return closed.promise; + }, + }); + }); + return promise; +} diff --git a/lib/serve-files.ts b/lib/serve-files.ts new file mode 100644 index 000000000..3c22286a5 --- /dev/null +++ b/lib/serve-files.ts @@ -0,0 +1,422 @@ +// Files on the server for `gentle-shell serve`: list, stat, read, write, +// mkdir, rename, remove, filename search and change streams, so a client +// can browse and edit a project that lives on the server. Paths are absolute +// server paths; every operation runs as the server user, so `sessions:operate` +// is that user's file authority (the same as a session's own tools): it reads +// and changes files. `sessions:read` lists, stats, searches names and watches. + +import { randomBytes } from "node:crypto"; +import { constants as fsConstants, realpathSync, statSync, watch, type FSWatcher, type Stats } from "node:fs"; +import { chmod, copyFile, link, lstat, mkdir, open, opendir, readlink, realpath, rename, rm, rmdir, stat, unlink } from "node:fs/promises"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import { homedir } from "node:os"; +import { basename, dirname, join, parse, relative, sep } from "node:path"; +import type { Principal } from "./serve-auth.ts"; +import { absolutePath, fsHttpError, HttpError, need, readJsonBody, realDirectory, receiveBodyToFile, SECURITY_HEADERS, sendJson, sseEvent, startSse } from "./serve-http.ts"; + +export const SERVE_FS_LIMITS = { + /** Entries one `list` returns; `truncated` past this. */ + listEntries: 5000, + /** Bytes one `read` returns. */ + readBytes: 8 * 1024 * 1024, + /** Bytes one `write` accepts. */ + writeBytes: 64 * 1024 * 1024, + searchDefault: 100, + searchMax: 1000, + /** Directory entries one search looks at, and how long it may walk. */ + searchVisit: 200_000, + searchMs: 5_000, + /** Quiet time before a batch of changes is sent, and the longest a change waits. */ + watchDebounceMs: 150, + watchMaxDelayMs: 1_000, + watchersPerDevice: 32, + /** Paths one change batch names; past this it says `overflow` (rescan). */ + watchBatchPaths: 1000, + smallBodyBytes: 16 * 1024, +}; + +/** Folders a search never enters. */ +const SEARCH_SKIP: Record = { ".git": true, "node_modules": true }; + +export type EntryKind = "file" | "dir" | "symlink" | "other"; + +function kindOf(stats: Stats): EntryKind { + if (stats.isSymbolicLink()) return "symlink"; + if (stats.isDirectory()) return "dir"; + if (stats.isFile()) return "file"; + return "other"; +} + +/** A validator for a file's version: size and modification time (µs). */ +export function fileEtag(stats: Stats): string { + return `"${stats.size.toString(36)}-${Math.round(stats.mtimeMs * 1000).toString(36)}"`; +} + +async function linkKind(path: string): Promise<"file" | "dir" | "other" | null> { + try { + const target = await stat(path); + return target.isDirectory() ? "dir" : target.isFile() ? "file" : "other"; + } catch { + return null; // dangling + } +} + +/** + * Scores a filename against a lowercase query: exact name 100, name prefix 80, + * name substring 60, relative path substring 40, the query's characters in + * order in the name 10; 0 is no match. + */ +export function searchScore(name: string, relativePath: string, needle: string): number { + const lower = name.toLowerCase(); + if (lower === needle) return 100; + if (lower.startsWith(needle)) return 80; + if (lower.includes(needle)) return 60; + if (relativePath.toLowerCase().replaceAll("\\", "/").includes(needle)) return 40; + let at = 0; + for (const ch of lower) if (ch === needle[at]) at += 1; + return at === needle.length ? 10 : 0; +} + +interface Watch { + deviceId: string; + res: ServerResponse; + watcher: FSWatcher; + pending: Set; + firstAt: number; + timer?: NodeJS.Timeout; +} + +export interface FileServiceOptions { + limits?: Partial; + now?: () => number; + log?: (line: string) => void; +} + +export class FileService { + private readonly limits: typeof SERVE_FS_LIMITS; + private readonly now: () => number; + private readonly log: (line: string) => void; + private readonly watches = new Set(); + /** The server user's home, symlinks resolved: never removed or renamed, nor any folder above it. */ + private readonly home: string; + + constructor(options: FileServiceOptions = {}) { + this.limits = { ...SERVE_FS_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.log = options.log ?? (() => {}); + let home = homedir(); + try { home = realpathSync(home); } catch { /* keep as is */ } + this.home = home; + } + + /** Answers `/api/fs/*`; false for any other path. */ + async route(req: IncomingMessage, res: ServerResponse, method: string, path: string, url: URL, principal: Principal | undefined): Promise { + if (!path.startsWith("/api/fs/")) return false; + const op = path.slice("/api/fs/".length); + const expect = (wanted: string) => { if (method !== wanted) throw new HttpError(405, "method_not_allowed", `Use ${wanted}`); }; + switch (op) { + case "list": expect("GET"); need(principal, "sessions:read"); await this.list(res, url); return true; + case "stat": expect("GET"); need(principal, "sessions:read"); await this.stat(res, url); return true; + // Contents need `sessions:operate`: a device that only watches would otherwise read secrets (mcp.json, auth.json). + case "read": expect("GET"); need(principal, "sessions:operate"); await this.read(req, res, url); return true; + case "search": expect("GET"); need(principal, "sessions:read"); await this.search(res, url); return true; + case "watch": expect("GET"); this.watch(req, res, url, need(principal, "sessions:read")); return true; + case "write": expect("PUT"); need(principal, "sessions:operate"); await this.write(req, res, url); return true; + case "mkdir": expect("POST"); need(principal, "sessions:operate"); await this.mkdir(req, res); return true; + case "rename": expect("POST"); need(principal, "sessions:operate"); await this.rename(req, res); return true; + case "remove": expect("POST"); need(principal, "sessions:operate"); await this.remove(req, res); return true; + default: throw new HttpError(404, "not_found", "Not found"); + } + } + + private async list(res: ServerResponse, url: URL): Promise { + const dirPath = absolutePath(url.searchParams.get("path")); + const names: string[] = []; + let truncated = false; + try { + const dir = await opendir(dirPath); + for await (const entry of dir) { + if (names.length >= this.limits.listEntries) { truncated = true; break; } + names.push(entry.name); + } + } catch (error) { + throw fsHttpError(error, dirPath); + } + const entries: Array<{ name: string; kind: EntryKind; size: number; mtime: number; linkKind?: string | null }> = []; + for (let i = 0; i < names.length; i += 128) { + const batch = await Promise.all(names.slice(i, i + 128).map(async (name) => { + const full = join(dirPath, name); + try { + const stats = await lstat(full); + const kind = kindOf(stats); + return { name, kind, size: stats.size, mtime: Math.floor(stats.mtimeMs), ...(kind === "symlink" ? { linkKind: await linkKind(full) } : {}) }; + } catch { + return undefined; // removed while listing + } + })); + for (const entry of batch) if (entry) entries.push(entry); + } + entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + sendJson(res, 200, { path: dirPath, entries, truncated }); + } + + private async stat(res: ServerResponse, url: URL): Promise { + const path = absolutePath(url.searchParams.get("path")); + let stats: Stats; + try { stats = await lstat(path); } catch (error) { throw fsHttpError(error, path); } + const kind = kindOf(stats); + let real: string | undefined; + try { real = await realpath(path); } catch { /* dangling link */ } + const followed = kind === "symlink" && real !== undefined ? await stat(real).catch(() => undefined) : undefined; + sendJson(res, 200, { + path, + name: basename(path), + kind, + size: stats.size, + mtime: Math.floor(stats.mtimeMs), + mode: stats.mode & 0o7777, + ...(kind === "file" ? { etag: fileEtag(stats) } : {}), + ...(kind === "symlink" ? { linkTarget: await readlink(path).catch(() => null), linkKind: await linkKind(path) } : {}), + ...(followed?.isFile() ? { etag: fileEtag(followed), size: followed.size } : {}), + ...(real === undefined ? {} : { realPath: real }), + }); + } + + private async read(req: IncomingMessage, res: ServerResponse, url: URL): Promise { + const path = absolutePath(url.searchParams.get("path")); + const offset = wholeNumber(url.searchParams.get("offset"), "offset") ?? 0; + const asked = wholeNumber(url.searchParams.get("length"), "length"); + // O_NONBLOCK: opening a FIFO never waits for a writer. + const handle = await open(path, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0)).catch((error: unknown) => { throw fsHttpError(error, path); }); + try { + const stats = await handle.stat(); + if (!stats.isFile()) throw new HttpError(400, "not_a_file", `${path} is not a regular file`); + const etag = fileEtag(stats); + const headers = { ETag: etag, "Last-Modified": new Date(stats.mtimeMs).toUTCString(), "X-File-Size": String(stats.size), "X-File-Mtime": String(Math.floor(stats.mtimeMs)) }; + const inm = req.headers["if-none-match"]; + const ims = req.headers["if-modified-since"]; + const unchanged = typeof inm === "string" ? inm.split(",").some((tag) => tag.trim() === etag) + : typeof ims === "string" && Number.isFinite(Date.parse(ims)) && Math.floor(stats.mtimeMs / 1000) * 1000 <= Date.parse(ims); + if (unchanged) { + res.writeHead(304, { ...SECURITY_HEADERS, ...headers }); + return void res.end(); + } + const length = Math.max(0, Math.min(asked ?? this.limits.readBytes, this.limits.readBytes, stats.size - offset)); + const buffer = Buffer.allocUnsafe(length); + let got = 0; + while (got < length) { + const { bytesRead } = await handle.read(buffer, got, length - got, offset + got); + if (bytesRead === 0) break; + got += bytesRead; + } + res.writeHead(200, { ...SECURITY_HEADERS, ...headers, "Content-Type": "application/octet-stream", "Content-Length": got, "X-Offset": String(offset), + "X-Truncated": offset + got < stats.size ? "1" : "0" }); + res.end(got === length ? buffer : buffer.subarray(0, got)); + } finally { + await handle.close(); + } + } + + private async write(req: IncomingMessage, res: ServerResponse, url: URL): Promise { + const target = absolutePath(url.searchParams.get("path")); + const createOnly = url.searchParams.get("create_only") === "1" || url.searchParams.get("create_only") === "true"; + // A save through a symlink replaces the file it points to and keeps the link. + let real: string; + let existing: Stats | undefined; + try { + real = await realpath(target); + existing = await stat(real); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw fsHttpError(error, target); + if (await lstat(target).then((s) => s.isSymbolicLink(), () => false)) throw new HttpError(409, "dangling_symlink", `${target} is a link to a file that does not exist`); + const parent = await realpath(dirname(target)).catch((e: unknown) => { throw fsHttpError(e, dirname(target)); }); + real = join(parent, basename(target)); + } + if (existing && createOnly) throw new HttpError(409, "exists", `${target} already exists`); + if (existing && !existing.isFile()) throw new HttpError(400, "not_a_file", `${target} is not a regular file`); + const ifMatch = req.headers["if-match"]; + if (typeof ifMatch === "string" && (!existing || !ifMatch.split(",").some((tag) => tag.trim() === fileEtag(existing)))) { + throw new HttpError(412, "changed", `${target} changed since it was read`); + } + const temp = join(dirname(real), `.${basename(real)}.gs-${randomBytes(6).toString("hex")}.tmp`); + const mode = existing ? existing.mode & 0o7777 : 0o666; + try { + await receiveBodyToFile(req, temp, this.limits.writeBytes, mode).catch((error: unknown) => { throw fsHttpError(error, target); }); + if (existing) await chmod(temp, mode); + if (createOnly) { + try { + await link(temp, real); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new HttpError(409, "exists", `${target} already exists`); + // No hard links here (some network and FAT volumes): an exclusive copy. + await copyFile(temp, real, fsConstants.COPYFILE_EXCL).catch((e: unknown) => { throw fsHttpError(e, target); }); + } + } else { + await rename(temp, real).catch((error: unknown) => { throw fsHttpError(error, target); }); + } + } finally { + await rm(temp, { force: true }); + } + const stats = await stat(real); + sendJson(res, existing ? 200 : 201, { path: target, size: stats.size, mtime: Math.floor(stats.mtimeMs), etag: fileEtag(stats), created: !existing }); + } + + private async mkdir(req: IncomingMessage, res: ServerResponse): Promise { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const path = absolutePath(body.path); + const first = await mkdir(path, { recursive: true }).catch((error: unknown) => { throw fsHttpError(error, path); }); + sendJson(res, first === undefined ? 200 : 201, { path, created: first !== undefined }); + } + + /** The entry itself (its folder's symlinks resolved, the last component kept), refused when it is a root, the home or a folder above it. */ + private async entry(path: string): Promise { + const root = parse(path).root; + const canonical = path === root ? root : join(await realpath(dirname(path)).catch((e: unknown) => { throw fsHttpError(e, path); }), basename(path)); + if (canonical === parse(canonical).root || canonical === this.home || this.home.startsWith(canonical.endsWith(sep) ? canonical : canonical + sep)) { + throw new HttpError(403, "protected_path", `${path} is the file system root, the home folder or a folder that holds it`); + } + return canonical; + } + + private async rename(req: IncomingMessage, res: ServerResponse): Promise { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const from = absolutePath(body.from, "from"); + const to = absolutePath(body.to, "to"); + const source = await this.entry(from); + const dest = await this.entry(to); + const sourceStats = await lstat(source).catch((error: unknown) => { throw fsHttpError(error, from); }); + if (body.overwrite !== true) { + const there = await lstat(dest).catch(() => undefined); + // The same entry (a case-only rename on a case-insensitive volume) is not a clash. + if (there && !(there.ino === sourceStats.ino && there.dev === sourceStats.dev)) throw new HttpError(409, "exists", `${to} already exists`); + } + await rename(source, dest).catch((error: unknown) => { throw fsHttpError(error, to); }); + sendJson(res, 200, { from, to }); + } + + private async remove(req: IncomingMessage, res: ServerResponse): Promise { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const path = absolutePath(body.path); + const canonical = await this.entry(path); + const stats = await lstat(canonical).catch((error: unknown) => { throw fsHttpError(error, path); }); + try { + if (stats.isDirectory()) { + if (body.recursive === true) await rm(canonical, { recursive: true }); + else await rmdir(canonical); + } else { + await unlink(canonical); + } + } catch (error) { + throw fsHttpError(error, path); + } + sendJson(res, 200, { removed: path }); + } + + private async search(res: ServerResponse, url: URL): Promise { + const root = realDirectory(url.searchParams.get("root")); + const q = url.searchParams.get("q") ?? ""; + if (q.length === 0 || q.length > 256 || q.includes("\0")) throw new HttpError(400, "invalid_query", "q must be 1-256 characters"); + const limit = Math.min(wholeNumber(url.searchParams.get("limit"), "limit") ?? this.limits.searchDefault, this.limits.searchMax); + const needle = q.toLowerCase(); + const deadline = this.now() + this.limits.searchMs; + const matches: Array<{ path: string; name: string; kind: EntryKind; score: number }> = []; + const queue = [root]; + let visited = 0; + let truncated = false; + walk: while (queue.length > 0) { + const dir = queue.shift()!; + let handle; + try { handle = await opendir(dir); } catch { continue; } + for await (const entry of handle) { + visited += 1; + if (visited > this.limits.searchVisit || this.now() > deadline) { truncated = true; break walk; } + const full = join(dir, entry.name); + if (entry.isDirectory()) { + if (Object.hasOwn(SEARCH_SKIP, entry.name)) continue; + queue.push(full); + } + const score = searchScore(entry.name, relative(root, full), needle); + if (score > 0) matches.push({ path: full, name: entry.name, kind: entry.isSymbolicLink() ? "symlink" : entry.isDirectory() ? "dir" : entry.isFile() ? "file" : "other", score }); + } + } + matches.sort((a, b) => b.score - a.score || a.path.length - b.path.length || (a.path < b.path ? -1 : 1)); + sendJson(res, 200, { root, results: matches.slice(0, limit), truncated }); + } + + private watch(req: IncomingMessage, res: ServerResponse, url: URL, principal: Principal): void { + const path = absolutePath(url.searchParams.get("path")); + let stats: Stats; + try { + stats = statSync(path); + } catch (error) { + throw fsHttpError(error, path); + } + const own = [...this.watches].filter((w) => w.deviceId === principal.deviceId).length; + if (own >= this.limits.watchersPerDevice) throw new HttpError(429, "too_many_watchers", `At most ${this.limits.watchersPerDevice} change streams per device`); + const isDir = stats.isDirectory(); + let watcher: FSWatcher; + let recursive = isDir; + try { + try { + watcher = watch(path, { recursive }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM") throw error; + recursive = false; + watcher = watch(path); + } + } catch (error) { + throw fsHttpError(error, path); + } + const base = isDir ? path : dirname(path); + const entry: Watch = { deviceId: principal.deviceId, res, watcher, pending: new Set(), firstAt: 0 }; + this.watches.add(entry); + startSse(req, res); + res.write(`retry: 3000\n\n${sseEvent("ready", { path, recursive })}`); + const flush = () => { + entry.timer = undefined; + const paths = [...entry.pending]; + entry.pending.clear(); + if (paths.length === 0) return; + res.write(sseEvent("changes", paths.length > this.limits.watchBatchPaths ? { paths: [], overflow: true } : { paths })); + }; + watcher.on("change", (_type, filename) => { + const name = filename === null || filename === undefined ? "" : filename.toString(); + if (entry.pending.size === 0) entry.firstAt = this.now(); + entry.pending.add(name === "" ? path : isDir ? join(base, name) : path); + clearTimeout(entry.timer); + const wait = Math.max(0, Math.min(this.limits.watchDebounceMs, entry.firstAt + this.limits.watchMaxDelayMs - this.now())); + entry.timer = setTimeout(flush, wait); + }); + watcher.on("error", (error) => { + res.end(sseEvent("error", { message: error.message })); + }); + res.on("close", () => this.stopWatch(entry)); + this.log(`watch ${path} for ${principal.deviceId}${recursive ? " (recursive)" : ""}`); + } + + private stopWatch(entry: Watch): void { + if (!this.watches.delete(entry)) return; + clearTimeout(entry.timer); + entry.watcher.close(); + if (!entry.res.writableEnded) entry.res.end(); + } + + heartbeat(): void { + for (const entry of this.watches) entry.res.write(": ping\n\n"); + } + + /** Ends a device's change streams (revoked). */ + closeDevice(deviceId: string): void { + for (const entry of [...this.watches]) if (entry.deviceId === deviceId) this.stopWatch(entry); + } + + closeAll(): void { + for (const entry of [...this.watches]) this.stopWatch(entry); + } +} + +function wholeNumber(raw: string | null, name: string): number | undefined { + if (raw === null || raw === "") return undefined; + if (!/^\d{1,15}$/.test(raw)) throw new HttpError(400, `invalid_${name}`, `${name} must be a whole number`); + return Number(raw); +} diff --git a/lib/serve-forward.ts b/lib/serve-forward.ts new file mode 100644 index 000000000..b965a3074 --- /dev/null +++ b/lib/serve-forward.ts @@ -0,0 +1,513 @@ +// Authenticated port forwarding for `gentle-shell serve`: a web page that +// lives on the server's loopback (the design canvas, a dev server the agent +// started, Gentle Tower) opened from another machine. Each forward is its own +// listener on the server's listen address, so the page's absolute paths keep +// working, and it proxies only to 127.0.0.1: or [::1]:. +// +// A forward belongs to one device. Its first request carries a single-use +// ticket (`gs_ticket`, 60 s); the listener answers with a redirect that drops +// the ticket and sets a per-forward cookie (`gs_fwd_`), which every later +// request needs. Browsers share cookies across ports, so the name is the +// forward's own and the proxy strips every `gs_fwd_*` cookie and the ticket +// before the target sees the request. Zero dependencies: `http` and `net`. + +import { randomBytes } from "node:crypto"; +import { request as httpRequest, type IncomingMessage, type OutgoingHttpHeaders, type ServerResponse } from "node:http"; +import { connect, type Server, type Socket } from "node:net"; +import { hashSecret } from "./serve-auth.ts"; +import { createServeListener, requestScheme, type ConnectionVia, type ServeListener, type ServeTlsMaterial } from "./serve-tls.ts"; + +export const SERVE_FORWARD_LIMITS = { + ticketTtlMs: 60_000, + maxTickets: 256, + /** A forward with no open connection and no request for this long is closed. */ + idleMs: 12 * 60 * 60_000, + sweepMs: 60_000, + /** Forwards open at once, across devices. */ + maxForwards: 32, + /** Open client connections per forward; more are refused at accept. */ + maxConnections: 64, + /** Browser sessions (cookies) one forward keeps; the oldest is dropped past this. */ + maxCookies: 32, + /** Connecting to the page on the server. */ + connectTimeoutMs: 10_000, + /** The browser sending a request's headers. */ + headersTimeoutMs: 20_000, + /** An idle keep-alive connection from the browser. */ + keepAliveTimeoutMs: 5_000, +}; + +export const FORWARD_TICKET_PARAM = "gs_ticket"; +export const FORWARD_COOKIE_PREFIX = "gs_fwd_"; + +/** A session's page (closed with it), Gentle Tower, or a server-level page such as Engram (`POST /api/forwards`). */ +export type ForwardKind = "session" | "tower" | "server"; + +export interface ForwardInfo { + id: string; + /** The page's port on the server's loopback. */ + port: number; + /** The forward's own port on the server's listen address. */ + listenPort: number; + deviceId: string; + /** The session it belongs to; null for Gentle Tower's and server-level ones. */ + sessionId: string | null; + kind: ForwardKind; + createdAt: number; + lastUsedAt: number; +} + +export class ForwardError extends Error { + readonly status: number; + readonly code: string; + constructor(status: number, code: string, message: string) { + super(message); + this.status = status; + this.code = code; + } +} + +export interface ForwardManagerOptions { + /** The main server's bind address: forwards listen on the same one. */ + bindHost: string; + /** The Host header check for a listener on `port` (the main server's rules). */ + hostCheck: (port: number) => (host: string) => boolean; + /** Listen ports to take forwards from (inclusive); OS-assigned when absent. */ + portRange?: { from: number; to: number }; + now?: () => number; + log?: (line: string) => void; + limits?: Partial; + /** The main server's certificate: every forward then speaks TLS to the network (plain HTTP from this machine), like the API. */ + tls?: ServeTlsMaterial; +} + +/** Hop-by-hop headers (RFC 9110 §7.6.1), never passed through a proxy. */ +const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"]); + +const OWN_HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer" }; + +type Upstream = "127.0.0.1" | "::1"; +const literal = (host: Upstream) => (host === "::1" ? "[::1]" : host); + +interface ForwardState { + info: ForwardInfo; + server: Server; + listener: ServeListener; + hostOk: (host: string) => boolean; + sockets: Set; + /** sha256 (hex) of each cookie secret, oldest first. */ + cookies: Set; + /** Which loopback address answered last; probed again after a refusal. */ + upstream?: Upstream; +} + +interface TicketEntry { + forwardId: string; + deviceId: string; + expiresAt: number; +} + +/** The Connection header's own hop-by-hop names, plus the fixed ones. */ +function hopHeaders(headers: IncomingMessage["headers"]): Set { + const names = new Set(HOP_BY_HOP); + const connection = headers.connection; + if (typeof connection === "string") for (const token of connection.split(",")) if (token.trim()) names.add(token.trim().toLowerCase()); + return names; +} + +/** Every cookie except the forwards' own, joined as the browser sent them; undefined when none is left. */ +export function stripForwardCookies(header: string | undefined): string | undefined { + if (!header) return undefined; + const kept = header.split(";").map((c) => c.trim()).filter((c) => c && !c.startsWith(FORWARD_COOKIE_PREFIX)); + return kept.length === 0 ? undefined : kept.join("; "); +} + +function cookieValue(header: string | undefined, name: string): string | undefined { + if (!header) return undefined; + for (const part of header.split(";")) { + const eq = part.indexOf("="); + if (eq !== -1 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim(); + } + return undefined; +} + +/** The request target without the ticket parameter, and the ticket (when present). */ +export function splitTicket(rawUrl: string): { path: string; ticket?: string } { + const q = rawUrl.indexOf("?"); + if (q === -1) return { path: rawUrl }; + let ticket: string | undefined; + const kept: string[] = []; + for (const param of rawUrl.slice(q + 1).split("&")) { + if (param.startsWith(`${FORWARD_TICKET_PARAM}=`)) ticket = param.slice(FORWARD_TICKET_PARAM.length + 1); + else if (param !== "") kept.push(param); + } + return { path: rawUrl.slice(0, q) + (kept.length ? `?${kept.join("&")}` : ""), ...(ticket === undefined ? {} : { ticket }) }; +} + +function plain(res: ServerResponse, status: number, text: string, extra: OutgoingHttpHeaders = {}): void { + if (res.headersSent) { res.destroy(); return; } + res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8", "Content-Length": Buffer.byteLength(text), ...OWN_HEADERS, ...extra }); + res.end(text); +} + +function refuseUpgrade(socket: Socket, status: number, reason: string): void { + socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); +} + +function listenOn(server: Server, port: number, host: string): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const onError = (error: Error) => reject(error); + server.once("error", onError); + server.listen(port, host, () => { + server.off("error", onError); + const address = server.address(); + resolve(typeof address === "object" && address ? address.port : port); + }); + return promise; +} + +function canConnect(host: Upstream, port: number, timeoutMs: number): Promise { + const { promise, resolve } = Promise.withResolvers(); + const socket = connect({ host, port }); + const timer = setTimeout(() => { socket.destroy(); resolve(false); }, timeoutMs); + socket.once("connect", () => { clearTimeout(timer); socket.destroy(); resolve(true); }); + socket.once("error", () => { clearTimeout(timer); resolve(false); }); + return promise; +} + +export class ForwardManager { + private readonly options: ForwardManagerOptions; + private readonly limits: typeof SERVE_FORWARD_LIMITS; + private readonly now: () => number; + private readonly log: (line: string) => void; + private readonly forwards = new Map(); + /** Keyed by the ticket's hash. */ + private readonly tickets = new Map(); + private readonly sweep: NodeJS.Timeout; + private closed = false; + + constructor(options: ForwardManagerOptions) { + this.options = options; + this.limits = { ...SERVE_FORWARD_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.log = options.log ?? (() => {}); + this.sweep = setInterval(() => this.closeIdle(), this.limits.sweepMs); + this.sweep.unref(); + } + + /** Ports the forwards listen on: never a target (a forward to a forward loops). */ + listenPorts(): number[] { + return [...this.forwards.values()].map((f) => f.info.listenPort); + } + + list(filter: { deviceId?: string; sessionId?: string | null; kind?: ForwardKind } = {}): ForwardInfo[] { + return [...this.forwards.values()].map((f) => f.info).filter((f) => + (filter.deviceId === undefined || f.deviceId === filter.deviceId) + && (filter.sessionId === undefined || f.sessionId === filter.sessionId) + && (filter.kind === undefined || f.kind === filter.kind)); + } + + get(id: string): ForwardInfo | undefined { + return this.forwards.get(id)?.info; + } + + /** + * The device's forward to `port` for this session (or Gentle Tower), opened + * when it has none. A forward belongs to one session so that it closes with it. + */ + async open(input: { deviceId: string; sessionId: string | null; kind: ForwardKind; port: number }): Promise<{ forward: ForwardInfo; created: boolean }> { + if (this.closed) throw new ForwardError(503, "shutting_down", "The server is stopping"); + const existing = this.list({ deviceId: input.deviceId, sessionId: input.sessionId, kind: input.kind }).find((f) => f.port === input.port); + if (existing) { + existing.lastUsedAt = this.now(); + return { forward: existing, created: false }; + } + if (this.forwards.size >= this.limits.maxForwards) throw new ForwardError(429, "too_many_forwards", `At most ${this.limits.maxForwards} forwards are open at once; close one first`); + const id = `fwd_${randomBytes(8).toString("hex")}`; + const info: ForwardInfo = { id, port: input.port, listenPort: 0, deviceId: input.deviceId, sessionId: input.sessionId, kind: input.kind, createdAt: this.now(), lastUsedAt: this.now() }; + const sockets = new Set(); + const listener = createServeListener({ + ...(this.options.tls === undefined ? {} : { tls: this.options.tls }), + setup: (http, via) => { + http.headersTimeout = this.limits.headersTimeoutMs; + http.requestTimeout = 0; // streams (SSE) stay open + http.keepAliveTimeout = this.limits.keepAliveTimeoutMs; + http.on("request", (req: IncomingMessage, res: ServerResponse) => this.handle(state, req, res, via)); + http.on("upgrade", (req: IncomingMessage, socket: Socket, head: Buffer) => this.upgrade(state, req, socket, head, via)); + http.on("clientError", (_error, socket: Socket) => { if (socket.writable) socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"); else socket.destroy(); }); + }, + onConnection: (socket) => { + sockets.add(socket); + socket.on("close", () => sockets.delete(socket)); + }, + }); + const state: ForwardState = { info, server: listener.server, listener, hostOk: () => false, sockets, cookies: new Set() }; + const server = state.server; + server.maxConnections = this.limits.maxConnections; + const host = this.options.bindHost.replace(/^\[|\]$/g, ""); + state.info.listenPort = await this.bind(server, host); + if (this.closed) { + server.close(); + throw new ForwardError(503, "shutting_down", "The server is stopping"); + } + state.hostOk = this.options.hostCheck(state.info.listenPort); + this.forwards.set(id, state); + this.log(`forward ${id}: :${state.info.listenPort} → loopback:${input.port} for ${input.deviceId}${input.sessionId ? ` (${input.sessionId})` : ` (${input.kind})`}`); + return { forward: state.info, created: true }; + } + + private async bind(server: Server, host: string): Promise { + const range = this.options.portRange; + if (!range) return listenOn(server, 0, host); + const taken = new Set(this.listenPorts()); + for (let port = range.from; port <= range.to; port += 1) { + if (taken.has(port)) continue; + try { + return await listenOn(server, port, host); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== "EADDRINUSE" && code !== "EACCES") throw error; + } + } + throw new ForwardError(503, "no_forward_port", `Every port in the forward range ${range.from}-${range.to} is in use`); + } + + /** A single-use ticket for the forward's first request, bound to the forward and its device. */ + mintTicket(forwardId: string): { ticket: string; expiresAt: number } { + const state = this.forwards.get(forwardId); + if (!state) throw new ForwardError(404, "not_found", "No such forward"); + this.pruneTickets(); + const ticket = randomBytes(24).toString("base64url"); + const expiresAt = this.now() + this.limits.ticketTtlMs; + this.tickets.set(hashSecret(ticket).toString("hex"), { forwardId, deviceId: state.info.deviceId, expiresAt }); + while (this.tickets.size > this.limits.maxTickets) this.tickets.delete(this.tickets.keys().next().value!); + return { ticket, expiresAt }; + } + + /** Where a relayed connection for a forward's listen port goes; undefined when no forward listens there. */ + relayTarget(listenPort: number): ((socket: Socket) => void) | undefined { + const state = [...this.forwards.values()].find((f) => f.info.listenPort === listenPort); + if (!state) return undefined; + return (socket) => { + if (state.sockets.size >= this.limits.maxConnections) return void socket.destroy(); + state.listener.acceptRelayed(socket); + }; + } + + /** The URL a browser opens: the host and scheme the client used, the forward's port, the page's path and the ticket. */ + urlFor(forwardId: string, clientHost: string, path: string, ticket: string, scheme: "http" | "https" = "http"): string { + const state = this.forwards.get(forwardId); + if (!state) throw new ForwardError(404, "not_found", "No such forward"); + const hash = path.indexOf("#"); + const target = hash === -1 ? path : path.slice(0, hash); + const fragment = hash === -1 ? "" : path.slice(hash); + return `${scheme}://${clientHost}:${state.info.listenPort}${target}${target.includes("?") ? "&" : "?"}${FORWARD_TICKET_PARAM}=${ticket}${fragment}`; + } + + private redeemTicket(ticket: string, state: ForwardState): boolean { + if (ticket.length === 0 || ticket.length > 64) return false; + this.pruneTickets(); + const key = hashSecret(ticket).toString("hex"); + const entry = this.tickets.get(key); + if (!entry) return false; + this.tickets.delete(key); + return entry.forwardId === state.info.id && entry.deviceId === state.info.deviceId; + } + + private pruneTickets(): void { + const now = this.now(); + for (const [key, entry] of this.tickets) if (entry.expiresAt <= now) this.tickets.delete(key); + } + + private cookieName(state: ForwardState): string { + return `${FORWARD_COOKIE_PREFIX}${state.info.id}`; + } + + private hasCookie(state: ForwardState, req: IncomingMessage): boolean { + const value = cookieValue(req.headers.cookie, this.cookieName(state)); + if (!value || value.length > 128) return false; + return state.cookies.has(hashSecret(value).toString("hex")); + } + + /** Host and Origin, as the main server checks them (no Host check through a relay); a message when refused. */ + private refused(state: ForwardState, req: IncomingMessage, via: ConnectionVia): { status: number; reason: string; message: string } | undefined { + const host = req.headers.host; + if (typeof host !== "string" || (via !== "relay" && !state.hostOk(host))) return { status: 421, reason: "Misdirected Request", message: "Unexpected Host header" }; + // Another page (another forward on this host is the same site) never drives this one; no CORS is added either. + const origin = req.headers.origin?.toLowerCase(); + if (origin !== undefined && origin !== `http://${host.toLowerCase()}` && origin !== `https://${host.toLowerCase()}`) return { status: 403, reason: "Forbidden", message: "Origin not allowed" }; + if (!(req.url ?? "").startsWith("/")) return { status: 400, reason: "Bad Request", message: "Bad request" }; + return undefined; + } + + private handle(state: ForwardState, req: IncomingMessage, res: ServerResponse, via: ConnectionVia): void { + const refused = this.refused(state, req, via); + if (refused) return plain(res, refused.status, refused.message); + const { path, ticket } = splitTicket(req.url ?? "/"); + if (ticket !== undefined) { + if (req.method !== "GET" && req.method !== "HEAD") return plain(res, 405, "A forward link opens with GET"); + const headers: OutgoingHttpHeaders = { Location: path }; + if (this.redeemTicket(ticket, state)) { + const secret = randomBytes(32).toString("base64url"); + state.cookies.add(hashSecret(secret).toString("hex")); + while (state.cookies.size > this.limits.maxCookies) state.cookies.delete(state.cookies.values().next().value!); + headers["Set-Cookie"] = `${this.cookieName(state)}=${secret}; HttpOnly; SameSite=Strict; Path=/`; + } else if (!this.hasCookie(state, req)) { + return plain(res, 401, "This link expired or was already used. Open the page again from Gentle Shell."); + } + state.info.lastUsedAt = this.now(); + res.writeHead(303, { ...OWN_HEADERS, ...headers, "Content-Length": 0 }); + return void res.end(); + } + if (!this.hasCookie(state, req)) return plain(res, 401, "Open this page from Gentle Shell: it needs a fresh link."); + state.info.lastUsedAt = this.now(); + void this.proxy(state, req, res, path); + } + + /** Which loopback address answers on the port: 127.0.0.1 first, then [::1] (servers that bound `localhost` on IPv6 only). */ + private async upstream(state: ForwardState): Promise { + if (state.upstream) return state.upstream; + for (const host of ["127.0.0.1", "::1"] as const) { + if (await canConnect(host, state.info.port, this.limits.connectTimeoutMs)) return (state.upstream = host); + } + return undefined; + } + + /** The request's headers for the page: hop-by-hop gone, Host the page's own, Origin and Referer translated, forward cookies stripped. */ + private upstreamHeaders(state: ForwardState, req: IncomingMessage, upstream: Upstream, keepUpgrade: boolean): Record { + const own = `${requestScheme(req)}://${req.headers.host}`; + const target = `http://${literal(upstream)}:${state.info.port}`; + const drop = hopHeaders(req.headers); + const headers: Record = {}; + for (const [name, value] of Object.entries(req.headers)) { + if (value === undefined || name === "host" || name === "cookie") continue; + if (drop.has(name) && !(keepUpgrade && (name === "connection" || name === "upgrade"))) continue; + headers[name] = value; + } + headers.host = `${literal(upstream)}:${state.info.port}`; + const cookie = stripForwardCookies(req.headers.cookie); + if (cookie !== undefined) headers.cookie = cookie; + if (typeof headers.origin === "string") headers.origin = target; + if (typeof headers.referer === "string" && (headers.referer === own || headers.referer.startsWith(`${own}/`))) headers.referer = target + headers.referer.slice(own.length); + return headers; + } + + /** The page's response headers for the browser: hop-by-hop gone, loopback redirects pointed back at the forward, no `gs_fwd_*` cookie. */ + private downstreamHeaders(state: ForwardState, req: IncomingMessage, upRes: IncomingMessage): string[] { + const drop = hopHeaders(upRes.headers); + const loopback = new RegExp(`^https?://(?:127\\.0\\.0\\.1|localhost|\\[::1\\]):${state.info.port}(?=[/?#]|$)`, "i"); + const out: string[] = []; + const raw = upRes.rawHeaders; + for (let i = 0; i + 1 < raw.length; i += 2) { + const name = raw[i]; + let value = raw[i + 1]; + const lower = name.toLowerCase(); + if (drop.has(lower)) continue; + if (lower === "set-cookie" && value.trimStart().startsWith(FORWARD_COOKIE_PREFIX)) continue; + if (lower === "location" || lower === "content-location") value = value.replace(loopback, `${requestScheme(req)}://${req.headers.host}`); + out.push(name, value); + } + return out; + } + + private async proxy(state: ForwardState, req: IncomingMessage, res: ServerResponse, path: string): Promise { + const upstream = await this.upstream(state); + if (res.destroyed) return; + if (!upstream) return plain(res, 502, `Nothing answers on port ${state.info.port} of the server.`); + const up = httpRequest({ host: upstream, port: state.info.port, method: req.method, path, headers: this.upstreamHeaders(state, req, upstream, false), agent: false }); + const connectTimer = setTimeout(() => up.destroy(new Error("connect timeout")), this.limits.connectTimeoutMs); + up.once("socket", (socket: Socket) => { + socket.setNoDelay(true); + if (!socket.connecting) clearTimeout(connectTimer); + else socket.once("connect", () => clearTimeout(connectTimer)); + }); + up.on("response", (upRes: IncomingMessage) => { + res.writeHead(upRes.statusCode ?? 502, upRes.statusMessage, this.downstreamHeaders(state, req, upRes)); + // Headers now, so a stream (SSE) starts before its first event; the body is never buffered. + res.flushHeaders(); + upRes.pipe(res); + upRes.on("error", () => res.destroy()); + upRes.on("aborted", () => res.destroy()); + }); + up.on("error", (error: NodeJS.ErrnoException) => { + clearTimeout(connectTimer); + if (error.code === "ECONNREFUSED") state.upstream = undefined; + if (!res.headersSent) plain(res, 502, `The page on port ${state.info.port} did not answer.`); + else res.destroy(); + }); + res.on("close", () => { + clearTimeout(connectTimer); + if (!res.writableFinished) up.destroy(); + }); + req.pipe(up); + } + + private upgrade(state: ForwardState, req: IncomingMessage, socket: Socket, head: Buffer, via: ConnectionVia): void { + socket.on("error", () => socket.destroy()); + const refused = this.refused(state, req, via); + if (refused) return refuseUpgrade(socket, refused.status, refused.reason); + // A WebSocket opens from a page already loaded through the forward: the cookie, never a ticket. + if (!this.hasCookie(state, req)) return refuseUpgrade(socket, 401, "Unauthorized"); + state.info.lastUsedAt = this.now(); + const { path } = splitTicket(req.url ?? "/"); + void this.upstream(state).then((upstream) => { + if (socket.destroyed) return; + if (!upstream) return refuseUpgrade(socket, 502, "Bad Gateway"); + const headers = this.upstreamHeaders(state, req, upstream, true); + const lines = [`${req.method} ${path} HTTP/1.1`]; + for (const [name, value] of Object.entries(headers)) for (const v of Array.isArray(value) ? value : [value]) lines.push(`${name}: ${v}`); + const target = connect({ host: upstream, port: state.info.port }); + const connectTimer = setTimeout(() => target.destroy(new Error("connect timeout")), this.limits.connectTimeoutMs); + let connected = false; + target.once("connect", () => { + connected = true; + clearTimeout(connectTimer); + target.setNoDelay(true); + socket.setNoDelay(true); + target.write(`${lines.join("\r\n")}\r\n\r\n`); + if (head.length > 0) target.write(head); + target.pipe(socket); + socket.pipe(target); + }); + target.on("error", (error: NodeJS.ErrnoException) => { + clearTimeout(connectTimer); + if (error.code === "ECONNREFUSED") state.upstream = undefined; + if (!connected) refuseUpgrade(socket, 502, "Bad Gateway"); + }); + target.on("close", () => { if (connected) socket.destroy(); }); + socket.on("close", () => target.destroy()); + }); + } + + /** Closes one forward: its listener, its open connections (WebSockets included) and its tickets. */ + close(id: string, reason = "closed"): boolean { + const state = this.forwards.get(id); + if (!state) return false; + this.forwards.delete(id); + for (const [key, entry] of this.tickets) if (entry.forwardId === id) this.tickets.delete(key); + state.server.close(); + state.listener.closeAllConnections(); + for (const socket of state.sockets) socket.destroy(); + this.log(`forward ${id}: ${reason}`); + return true; + } + + closeWhere(predicate: (forward: ForwardInfo) => boolean, reason: string): number { + let count = 0; + for (const forward of this.list()) if (predicate(forward) && this.close(forward.id, reason)) count += 1; + return count; + } + + private closeIdle(): void { + const now = this.now(); + for (const state of [...this.forwards.values()]) { + if (state.sockets.size === 0 && now - state.info.lastUsedAt >= this.limits.idleMs) this.close(state.info.id, "idle"); + } + } + + closeAll(): void { + this.closed = true; + clearInterval(this.sweep); + for (const id of [...this.forwards.keys()]) this.close(id, "server stopping"); + } +} diff --git a/lib/serve-git.ts b/lib/serve-git.ts new file mode 100644 index 000000000..021dd57f1 --- /dev/null +++ b/lib/serve-git.ts @@ -0,0 +1,298 @@ +// `POST /api/git` for `gentle-shell serve`: one `git` command in a folder on +// the server (no shell), with its exit code and output, so a client shows +// and drives a repository that lives there. Commands that only read and print +// no file contents (status, branches, the log, changed paths and line counts) +// need `sessions:read`; anything else, contents included (`show`, a patch, a +// blob, `blame`, `grep`), `sessions:operate`, which is the server user's own +// authority: a device that only watches could otherwise read secrets the +// repository holds. Configuration and arguments that make git run another +// program are refused, so a read-only token cannot turn a read into a command. + +import { spawn, type ChildProcess } from "node:child_process"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import type { Principal, ServeScope } from "./serve-auth.ts"; +import { HttpError, need, readJsonBody, realDirectory, sendJson } from "./serve-http.ts"; + +export const SERVE_GIT_LIMITS = { + /** Default run time, and the most a request may ask for. */ + timeoutMs: 120_000, + /** The most a fetch, push, clone, pull, ls-remote or submodule may ask for. */ + networkTimeoutMs: 600_000, + stdoutBytes: 32 * 1024 * 1024, + stderrBytes: 1024 * 1024, + stdinBytes: 8 * 1024 * 1024, + /** The JSON body: base64 stdin plus arguments. */ + bodyBytes: 12 * 1024 * 1024, + maxArgs: 256, + argChars: 32 * 1024, + /** git processes at once, across devices. */ + maxRunning: 16, + /** After a timeout or truncation, SIGTERM; SIGKILL this much later. */ + killGraceMs: 2_000, +}; + +/** Global options that take the next argument as their value. */ +const GLOBAL_WITH_VALUE: Record = { "-C": true, "-c": true, "--git-dir": true, "--work-tree": true, "--namespace": true, "--super-prefix": true, "--config-env": true }; + +/** Configuration keys (lowercase) that run a program or redirect what git runs. */ +const BLOCKED_CONFIG = [/^core\.sshcommand$/, /^core\.fsmonitor$/, /^core\.hookspath$/, /^core\.gitproxy$/, /^uploadpack\./, /^alias\./, + /^remote\..+\.(uploadpack|receivepack)$/, /^protocol\.ext\.allow$/]; + +/** Subcommands that only read and never print a file's contents. */ +const READ_SUBCOMMANDS: Record = { + status: true, "rev-parse": true, "ls-files": true, "for-each-ref": true, "ls-tree": true, "rev-list": true, "merge-base": true, describe: true, + shortlog: true, "name-rev": true, "check-ignore": true, "check-attr": true, "show-ref": true, "count-objects": true, version: true, "ls-remote": true, +}; + +/** Reads that print commits or changed paths, and contents (a patch) only when asked; `diff` prints one unless told not to. */ +const DIFF_SUBCOMMANDS: Record = { log: true, diff: true, "diff-tree": true, "diff-files": true, "diff-index": true }; + +/** Long options that print file contents (a patch, changed lines) or search them (a read-only token could guess a secret). */ +const CONTENT_OPTIONS = ["--patch", "--patch-with-raw", "--patch-with-stat", "--unified", "--cc", "--dd", "--word-diff", "--word-diff-regex", "--color-words", + "--function-context", "--binary", "--check", "--pickaxe-regex", "--pickaxe-all", "--find-object", "--diff-merges", "--remerge-diff", "--ext-diff", "--textconv"]; + +/** Short options (alone or bundled, `-pM`, `-U5`) that do the same: patch, unified context, combined diffs, -m, -W, -L, -S, -G. */ +const CONTENT_SHORT = /^-[^-]*[pucmWLSGU]/; + +/** `diff` options that print paths, counts or nothing instead of its patch. */ +const NO_PATCH_OPTIONS = ["--name-only", "--name-status", "--numstat", "--stat", "--shortstat", "--compact-summary", "--dirstat", "--dirstat-by-file", + "--summary", "--raw", "-s", "--no-patch", "--quiet"]; + +/** Subcommands that talk to a remote and may run up to `networkTimeoutMs`. */ +const NETWORK_SUBCOMMANDS: Record = { fetch: true, push: true, clone: true, pull: true, "ls-remote": true, submodule: true }; + +/** Variables a request may set; the rest of the environment is the server's. */ +const ALLOWED_ENV: Record = { + GIT_AUTHOR_NAME: true, GIT_AUTHOR_EMAIL: true, GIT_AUTHOR_DATE: true, GIT_COMMITTER_NAME: true, GIT_COMMITTER_EMAIL: true, GIT_COMMITTER_DATE: true, + GIT_DIR: true, GIT_WORK_TREE: true, GIT_INDEX_FILE: true, GIT_NAMESPACE: true, GIT_LITERAL_PATHSPECS: true, GIT_GLOB_PATHSPECS: true, + GIT_NOGLOB_PATHSPECS: true, GIT_ICASE_PATHSPECS: true, GIT_REFLOG_ACTION: true, GIT_MERGE_AUTOEDIT: true, GIT_MERGE_VERBOSITY: true, GIT_OPTIONAL_LOCKS: true, +}; + +/** Inherited variables that would point git at another repository than the request's. */ +const DROPPED_ENV = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_PREFIX"]; + +export interface GitCommand { + /** The subcommand (`status`, `commit`, …); undefined for `git --version` and the like. */ + subcommand?: string; + scope: ServeScope; + network: boolean; +} + +function blockedConfig(entry: string): boolean { + const key = entry.split("=", 1)[0].trim().toLowerCase(); + return BLOCKED_CONFIG.some((pattern) => pattern.test(key)); +} + +const refuse = (message: string) => new HttpError(400, "git_refused", message); + +/** + * What a git argument list does: its subcommand, whether it only reads, and + * whether it is a network command. Throws `400 git_refused` for configuration + * or options that make git run another program. + */ +export function classifyGitArgs(args: readonly string[]): GitCommand { + let i = 0; + let configured = false; + for (; i < args.length; i += 1) { + const arg = args[i]; + if (!arg.startsWith("-")) break; + if (arg.startsWith("--exec-path=")) throw refuse("--exec-path= is refused: it chooses which programs git runs"); + const config = arg === "-c" || arg === "--config-env" ? args[i + 1] ?? "" : arg.startsWith("--config-env=") ? arg.slice("--config-env=".length) : undefined; + if (config !== undefined) { + if (blockedConfig(config)) throw refuse(`-c ${config.split("=", 1)[0]} is refused: it makes git run a program`); + configured = true; + } + if (Object.hasOwn(GLOBAL_WITH_VALUE, arg)) i += 1; + } + const subcommand = args[i]; + const rest = args.slice(i + 1); + const end = rest.indexOf("--"); + const options = end === -1 ? rest : rest.slice(0, end); + for (let j = 0; j < options.length; j += 1) { + const arg = options[j]; + if (/^--(upload-pack|receive-pack|exec)(=|$)/.test(arg)) throw refuse(`${arg.split("=", 1)[0]} is refused: it makes git run a program`); + if ((subcommand === "clone" || subcommand === "ls-remote") && /^-u/.test(arg)) throw refuse("-u (upload-pack) is refused: it makes git run a program"); + if (subcommand === "clone") { + const value = arg === "-c" || arg === "--config" ? options[j + 1] ?? "" : arg.startsWith("--config=") ? arg.slice("--config=".length) : arg.startsWith("-c") && arg.length > 2 ? arg.slice(2) : undefined; + if (value !== undefined && blockedConfig(value)) throw refuse(`--config ${value.split("=", 1)[0]} is refused: it makes git run a program`); + } + } + const network = subcommand !== undefined && Object.hasOwn(NETWORK_SUBCOMMANDS, subcommand); + // A configuration override can change what any command does: only a token that operates may set one. + const read = !configured && (subcommand === undefined || readOnly(subcommand, options)); + return { ...(subcommand === undefined ? {} : { subcommand }), scope: read ? "sessions:read" : "sessions:operate", network }; +} + +function readOnly(subcommand: string, options: readonly string[]): boolean { + const flags = options.filter((a) => a.startsWith("-")); + const positionals = options.filter((a) => !a.startsWith("-")); + const has = (...names: string[]) => flags.some((f) => names.includes(f.split("=", 1)[0])); + if (has("--output")) return false; + if (Object.hasOwn(READ_SUBCOMMANDS, subcommand)) return true; + const content = has(...CONTENT_OPTIONS) || flags.some((f) => CONTENT_SHORT.test(f)); + if (Object.hasOwn(DIFF_SUBCOMMANDS, subcommand)) return !content && (subcommand !== "diff" || has(...NO_PATCH_OPTIONS)); + switch (subcommand) { + case "branch": + return !has("-d", "-D", "--delete", "-m", "-M", "--move", "-c", "-C", "--copy", "-f", "--force", "--set-upstream-to", "-u", "--unset-upstream", + "--edit-description", "-t", "--track", "--no-track", "--create-reflog") + && (positionals.length === 0 || has("-l", "--list", "--show-current", "--contains", "--no-contains", "--merged", "--no-merged", "--points-at")); + case "tag": + return !has("-a", "--annotate", "-s", "--sign", "-u", "--local-user", "-f", "--force", "-d", "--delete", "-m", "--message", "-F", "--file", "-e", "--edit", "--create-reflog") + && (positionals.length === 0 || has("-l", "--list", "--contains", "--no-contains", "--merged", "--no-merged", "--points-at") || flags.some((f) => /^-n\d*$/.test(f))); + case "config": + if (positionals[0] === "get" || positionals[0] === "list") return !has("-e", "--edit"); + return has("--get", "--get-all", "--get-regexp", "--get-urlmatch", "--get-color", "--get-colorbool", "-l", "--list") + && !has("--add", "--unset", "--unset-all", "--replace-all", "--rename-section", "--remove-section", "-e", "--edit"); + case "remote": + return positionals.length === 0 || positionals[0] === "get-url" || positionals[0] === "show"; + case "stash": + // `stash show` prints a diffstat, `stash list` the log; either prints a patch when asked. + return (positionals[0] === "list" || positionals[0] === "show") && !content; + case "cat-file": + // An object's type, size or existence; never its contents (`-p`, `blob`, `--batch`). + return has("-t", "-s", "-e", "--batch-check") && !has("-p", "--batch", "--batch-command", "--textconv", "--filters"); + case "worktree": + return positionals[0] === "list"; + case "symbolic-ref": + return positionals.length <= 1 && !has("-d", "--delete"); + default: + return false; + } +} + +export interface GitServiceOptions { + /** The environment git runs with (the server's). */ + env: NodeJS.ProcessEnv; + limits?: Partial; + log?: (line: string) => void; +} + +export class GitService { + private readonly env: NodeJS.ProcessEnv; + private readonly limits: typeof SERVE_GIT_LIMITS; + private readonly log: (line: string) => void; + private readonly running = new Set(); + + constructor(options: GitServiceOptions) { + this.env = options.env; + this.limits = { ...SERVE_GIT_LIMITS, ...options.limits }; + this.log = options.log ?? (() => {}); + } + + async route(req: IncomingMessage, res: ServerResponse, principal: Principal | undefined): Promise { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const body = await readJsonBody(req, this.limits.bodyBytes); + const args = body.args; + if (!Array.isArray(args) || args.length === 0 || args.length > this.limits.maxArgs + || !args.every((a): a is string => typeof a === "string" && a.length <= this.limits.argChars && !a.includes("\0"))) { + throw new HttpError(400, "invalid_args", `args must be 1-${this.limits.maxArgs} strings without NUL`); + } + const command = classifyGitArgs(args); + need(principal, command.scope); + const cwd = realDirectory(body.cwd); + let stdin: Buffer | undefined; + if (body.stdin !== undefined) { + if (typeof body.stdin !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(body.stdin)) throw new HttpError(400, "invalid_stdin", "stdin must be base64"); + stdin = Buffer.from(body.stdin, "base64"); + if (stdin.length > this.limits.stdinBytes) throw new HttpError(413, "too_large", `stdin over ${this.limits.stdinBytes} bytes`); + } + const extraEnv: Record = {}; + if (body.env !== undefined) { + if (!body.env || typeof body.env !== "object" || Array.isArray(body.env)) throw new HttpError(400, "invalid_env", "env must be an object of strings"); + for (const [name, value] of Object.entries(body.env)) { + if (!Object.hasOwn(ALLOWED_ENV, name)) throw new HttpError(400, "env_not_allowed", `${name} may not be set (allowed: ${Object.keys(ALLOWED_ENV).join(", ")})`); + if (typeof value !== "string" || value.includes("\0") || value.length > 4096) throw new HttpError(400, "invalid_env", `${name} must be a string`); + extraEnv[name] = value; + } + } + const ceiling = command.network ? this.limits.networkTimeoutMs : this.limits.timeoutMs; + let timeoutMs = this.limits.timeoutMs; + if (body.timeoutMs !== undefined) { + if (typeof body.timeoutMs !== "number" || !Number.isInteger(body.timeoutMs) || body.timeoutMs < 1000 || body.timeoutMs > ceiling) { + throw new HttpError(400, "invalid_timeout", `timeoutMs must be a whole number from 1000 to ${ceiling} for git ${command.subcommand ?? ""}`.trimEnd()); + } + timeoutMs = body.timeoutMs; + } + if (this.running.size >= this.limits.maxRunning) throw new HttpError(429, "too_many_git", `At most ${this.limits.maxRunning} git commands run at once`); + const env: NodeJS.ProcessEnv = { ...this.env }; + for (const name of DROPPED_ENV) delete env[name]; + Object.assign(env, { + GIT_TERMINAL_PROMPT: "0", + GCM_INTERACTIVE: "never", + GIT_PAGER: "cat", + PAGER: "cat", + // Nothing can answer an editor: a commit without a message aborts instead of waiting. + GIT_EDITOR: "true", + GIT_MERGE_AUTOEDIT: "no", + ...(command.scope === "sessions:read" ? { GIT_OPTIONAL_LOCKS: "0" } : {}), + }, extraEnv); + const result = await this.run(args, cwd, env, stdin, timeoutMs); + sendJson(res, 200, result); + } + + private run(args: string[], cwd: string, env: NodeJS.ProcessEnv, stdin: Buffer | undefined, timeoutMs: number) { + const { promise, resolve, reject } = Promise.withResolvers<{ code: number | null; signal: string | null; stdout: string; stderr: string; truncated: boolean; timedOut: boolean }>(); + // Its own process group (POSIX), so a timeout ends git's helpers too, and no controlling terminal for ssh to prompt on. + const child = spawn("git", args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true }); + this.running.add(child); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + let outBytes = 0; + let errBytes = 0; + let truncated = false; + let timedOut = false; + let killTimer: NodeJS.Timeout | undefined; + const stop = () => { + if (killTimer || child.exitCode !== null) return; + this.signal(child, "SIGTERM"); + killTimer = setTimeout(() => this.signal(child, "SIGKILL"), this.limits.killGraceMs); + }; + const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs); + child.stdout!.on("data", (chunk: Buffer) => { + if (truncated) return; + const room = this.limits.stdoutBytes - outBytes; + if (chunk.length > room) { + stdout.push(chunk.subarray(0, room)); + outBytes += room; + truncated = true; + return stop(); + } + stdout.push(chunk); + outBytes += chunk.length; + }); + child.stderr!.on("data", (chunk: Buffer) => { + const room = this.limits.stderrBytes - errBytes; + if (room <= 0) return; + stderr.push(chunk.length > room ? chunk.subarray(0, room) : chunk); + errBytes += Math.min(room, chunk.length); + }); + child.stdin!.on("error", () => { /* git exited before reading all of stdin */ }); + child.stdin!.end(stdin); + child.on("error", (error: NodeJS.ErrnoException) => { + clearTimeout(timer); + clearTimeout(killTimer); + this.running.delete(child); + reject(error.code === "ENOENT" ? new HttpError(501, "git_missing", "git is not installed on the server (not on its PATH)") : error); + }); + child.on("close", (code, signal) => { + clearTimeout(timer); + clearTimeout(killTimer); + this.running.delete(child); + if (timedOut) this.log(`git ${args[0]} timed out after ${timeoutMs} ms`); + resolve({ code, signal, stdout: Buffer.concat(stdout).toString("base64"), stderr: Buffer.concat(stderr).toString("base64"), truncated, timedOut }); + }); + return promise; + } + + private signal(child: ChildProcess, signal: NodeJS.Signals): void { + try { + if (process.platform !== "win32" && child.pid !== undefined) process.kill(-child.pid, signal); + else child.kill(signal); + } catch { /* already gone */ } + } + + /** Ends every running git command (the server is stopping). */ + closeAll(): void { + for (const child of this.running) this.signal(child, "SIGKILL"); + } +} diff --git a/lib/serve-http.ts b/lib/serve-http.ts new file mode 100644 index 000000000..78ab3d6ff --- /dev/null +++ b/lib/serve-http.ts @@ -0,0 +1,178 @@ +// HTTP helpers shared by `gentle-shell serve`'s endpoints: the error type every +// route throws, JSON and SSE answers with the server's security headers, +// bounded JSON and raw bodies, scope checks, and path validation. + +import { createHash } from "node:crypto"; +import { createWriteStream, realpathSync, rmSync, statSync } from "node:fs"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import { isAbsolute, resolve } from "node:path"; +import { hasScope, type Principal, type ServeScope } from "./serve-auth.ts"; + +export class HttpError extends Error { + readonly status: number; + readonly code: string; + constructor(status: number, code: string, message: string) { + super(message); + this.status = status; + this.code = code; + } +} + +export const SECURITY_HEADERS = { + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "Cache-Control": "no-store", + "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'", +}; + +export function sendJson(res: ServerResponse, status: number, body: unknown): void { + if (res.headersSent) return; + const text = JSON.stringify(body); + res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(text), ...SECURITY_HEADERS }); + res.end(text); +} + +export function sendError(res: ServerResponse, status: number, code: string, message: string): void { + sendJson(res, status, { error: { code, message } }); +} + +/** Starts an SSE answer: headers flushed, Nagle off. */ +export function startSse(req: IncomingMessage, res: ServerResponse): void { + res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", Connection: "keep-alive", "X-Accel-Buffering": "no", ...SECURITY_HEADERS }); + res.flushHeaders(); + req.socket.setNoDelay(true); +} + +/** One SSE message; `data` is JSON. */ +export function sseEvent(event: string, data: unknown, id?: string | number): string { + return `${id === undefined ? "" : `id: ${id}\n`}event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; +} + +/** The principal when it holds `scope`; 401 without a token, 403 without the scope. */ +export function need(principal: Principal | undefined, scope: ServeScope): Principal { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + if (!hasScope(principal, scope)) throw new HttpError(403, "forbidden", `This token lacks the ${scope} scope`); + return principal; +} + +export function readJsonBody(req: IncomingMessage, limit: number): Promise> { + const { promise, resolve: done, reject } = Promise.withResolvers>(); + const declared = Number(req.headers["content-length"]); + if (Number.isFinite(declared) && declared > limit) { + reject(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + req.resume(); + return promise; + } + const chunks: Buffer[] = []; + let size = 0; + let over = false; + req.on("data", (chunk: Buffer) => { + size += chunk.length; + if (size > limit) over = true; + else chunks.push(chunk); + }); + req.on("error", reject); + req.on("end", () => { + if (over) return reject(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + if (size === 0) return done({}); + try { + const value = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("not an object"); + done(value); + } catch { + reject(new HttpError(400, "invalid_json", "The body must be one JSON object")); + } + }); + return promise; +} + +/** + * Streams a raw request body into a new file (`wx`, so it never follows or + * replaces anything at `path`), at most `limit` bytes; the file is removed on + * any failure. Returns its size and sha256 (hex). + */ +export function receiveBodyToFile(req: IncomingMessage, path: string, limit: number, mode: number): Promise<{ size: number; sha256: string }> { + const { promise, resolve: done, reject } = Promise.withResolvers<{ size: number; sha256: string }>(); + const declared = Number(req.headers["content-length"]); + if (Number.isFinite(declared) && declared > limit) { + req.resume(); + reject(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + return promise; + } + const hash = createHash("sha256"); + let size = 0; + let failed = false; + let opened = false; + const out = createWriteStream(path, { flags: "wx", mode }); + out.on("open", () => { opened = true; }); + const fail = (error: Error) => { + if (failed) return; + failed = true; + req.unpipe(out); + req.resume(); + out.destroy(); + out.once("close", () => { + if (opened) rmSync(path, { force: true }); + reject(error); + }); + }; + req.on("data", (chunk: Buffer) => { + size += chunk.length; + if (size > limit) return fail(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + hash.update(chunk); + }); + req.on("aborted", () => fail(new HttpError(400, "aborted", "The upload was cut short"))); + req.on("error", (error) => fail(error)); + out.on("error", (error) => fail(error)); + out.on("close", () => { if (!failed) done({ size, sha256: hash.digest("hex") }); }); + req.pipe(out); + return promise; +} + +/** A path from a request: absolute, no NUL, at most 4096 characters; normalized (`..` resolved lexically). */ +export function absolutePath(value: unknown, name = "path"): string { + if (typeof value !== "string" || value.length === 0 || value.length > 4096 || value.includes("\0") || !isAbsolute(value)) { + throw new HttpError(400, "invalid_path", `${name} must be an absolute path on the server`); + } + return resolve(value); +} + +/** An existing folder, symlinks resolved. */ +export function realDirectory(cwd: unknown): string { + if (typeof cwd !== "string" || cwd.length === 0 || cwd.length > 4096 || cwd.includes("\0") || !isAbsolute(cwd)) { + throw new HttpError(400, "invalid_cwd", "cwd must be an absolute path to a folder"); + } + try { + const real = realpathSync(cwd); + if (!statSync(real).isDirectory()) throw new Error("not a folder"); + return real; + } catch { + throw new HttpError(400, "invalid_cwd", "cwd must be an absolute path to an existing folder"); + } +} + +/** A file system error as the HTTP answer a client can act on. */ +export function fsHttpError(error: unknown, path: string): HttpError { + if (error instanceof HttpError) return error; + const code = (error as NodeJS.ErrnoException)?.code; + switch (code) { + case "ENOENT": return new HttpError(404, "not_found", `${path} does not exist`); + case "ENOTDIR": return new HttpError(400, "not_a_directory", `A part of ${path} is not a folder`); + case "EISDIR": return new HttpError(400, "is_a_directory", `${path} is a folder`); + case "EACCES": + case "EPERM": return new HttpError(403, "permission_denied", `The server user may not access ${path}`); + case "EEXIST": return new HttpError(409, "exists", `${path} already exists`); + case "ENOTEMPTY": return new HttpError(409, "not_empty", `${path} is not empty`); + case "EXDEV": return new HttpError(409, "cross_device", "Source and destination are on different file systems"); + case "EINVAL": return new HttpError(400, "invalid_operation", `The operation is not possible on ${path}`); + case "ENAMETOOLONG": return new HttpError(400, "invalid_path", `${path} is too long`); + case "ELOOP": return new HttpError(400, "symlink_loop", `${path} has too many levels of symbolic links`); + case "ENOSPC": return new HttpError(507, "no_space", "The server's disk is full"); + default: return new HttpError(500, "fs_error", `${code ?? "error"} on ${path}`); + } +} + +/** Whether the principal is the given device or holds `admin`. */ +export function ownsOrAdmin(principal: Principal, deviceId: string): boolean { + return principal.deviceId === deviceId || hasScope(principal, "admin"); +} diff --git a/lib/serve-print.ts b/lib/serve-print.ts new file mode 100644 index 000000000..ac64bd133 --- /dev/null +++ b/lib/serve-print.ts @@ -0,0 +1,143 @@ +// `POST /api/print` for `gentle-shell serve`: one one-shot prompt (a commit +// message, a title) answered by this machine's Gentle Shell, the way the app +// runs it locally: `gentle-shell --print --no-session --no-tools` in a folder, +// no session written, no tools, no interactive host. The prompt goes on stdin +// (Pi reads piped stdin as the message), so its size is not bound by the +// command line and it never shows in the process list. + +import { spawn, type ChildProcess } from "node:child_process"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import type { Principal } from "./serve-auth.ts"; +import { HttpError, need, readJsonBody, realDirectory, sendJson } from "./serve-http.ts"; +import type { SessionLaunch } from "./serve-session.ts"; + +export const SERVE_PRINT_LIMITS = { + timeoutMs: 120_000, + promptBytes: 256 * 1024, + bodyBytes: 512 * 1024, + stdoutBytes: 1024 * 1024, + /** The end of stderr a failure reports. */ + stderrChars: 2000, + /** One-shot runs at once, across devices. */ + maxRunning: 4, + /** After a timeout, an oversize answer or a client that left: SIGTERM, then SIGKILL this much later. */ + killGraceMs: 2_000, +}; + +/** Pi's `--model` pattern: `provider/id` or `id`, optionally `:thinking`; never an option. */ +const MODEL = /^(?!-)[^\s\0-\x1f\x7f]{1,200}$/; + +export interface PrintServiceOptions { + /** The one-shot run for a folder; absent where the server has no launcher (it answers `not_supported`). */ + launchPrint?: (input: { cwd: string; model?: string }) => SessionLaunch; + limits?: Partial; + log: (line: string) => void; +} + +type Outcome = { text: string } | { error: HttpError; exitCode?: number | null }; + +export class PrintService { + private readonly options: PrintServiceOptions; + private readonly limits: typeof SERVE_PRINT_LIMITS; + private readonly running = new Set(); + + constructor(options: PrintServiceOptions) { + this.options = options; + this.limits = { ...SERVE_PRINT_LIMITS, ...options.limits }; + } + + get available(): boolean { + return this.options.launchPrint !== undefined; + } + + async route(req: IncomingMessage, res: ServerResponse, principal: Principal | undefined): Promise { + need(principal, "sessions:operate"); + const launchPrint = this.options.launchPrint; + if (!launchPrint) throw new HttpError(501, "not_supported", "This server cannot run one-shot prompts"); + const body = await readJsonBody(req, this.limits.bodyBytes); + const cwd = realDirectory(body.cwd); + const prompt = body.prompt; + if (typeof prompt !== "string" || prompt.trim() === "") throw new HttpError(400, "invalid_prompt", "prompt must be a non-empty string"); + if (Buffer.byteLength(prompt, "utf8") > this.limits.promptBytes) throw new HttpError(400, "invalid_prompt", `prompt over ${this.limits.promptBytes} bytes`); + const model = body.model; + if (model !== undefined && (typeof model !== "string" || !MODEL.test(model))) throw new HttpError(400, "invalid_model", "model must be a model name such as provider/id"); + if (this.running.size >= this.limits.maxRunning) throw new HttpError(429, "too_many_prints", `At most ${this.limits.maxRunning} one-shot prompts run at once`); + const launch = launchPrint({ cwd, ...(typeof model === "string" ? { model } : {}) }); + const outcome = await this.run(launch, prompt, res); + if ("text" in outcome) return sendJson(res, 200, { text: outcome.text }); + const { error, exitCode } = outcome; + return sendJson(res, error.status, { error: { code: error.code, message: error.message }, ...(exitCode === undefined ? {} : { exitCode }) }); + } + + private run(launch: SessionLaunch, prompt: string, res: ServerResponse): Promise { + const { promise, resolve } = Promise.withResolvers(); + // Its own process group (POSIX): the launcher starts Pi as its child, and a stop must end both. + const child = spawn(launch.command, launch.args, { cwd: launch.cwd, env: launch.env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true }); + this.running.add(child); + const stdout: Buffer[] = []; + let outBytes = 0; + let stderr = ""; + let ended: "timeout" | "too_large" | "client_left" | undefined; + let killTimer: NodeJS.Timeout | undefined; + const stop = (why: NonNullable) => { + ended ??= why; + // The group, even when the launcher already exited: Pi may still hold stdout. + if (killTimer) return; + this.signal(child, "SIGTERM"); + killTimer = setTimeout(() => this.signal(child, "SIGKILL"), this.limits.killGraceMs); + killTimer.unref?.(); + }; + const timer = setTimeout(() => stop("timeout"), this.limits.timeoutMs); + // A client that hangs up does not keep the model running. + const left = () => { if (!res.writableEnded) stop("client_left"); }; + res.once("close", left); + child.stdout!.on("data", (chunk: Buffer) => { + if (ended) return; + outBytes += chunk.length; + if (outBytes > this.limits.stdoutBytes) return stop("too_large"); + stdout.push(chunk); + }); + child.stderr!.on("data", (chunk: Buffer) => { stderr = (stderr + chunk.toString("utf8")).slice(-this.limits.stderrChars); }); + child.stdin!.on("error", () => { /* it exited before reading the prompt */ }); + child.stdin!.end(prompt); + let settled = false; + const finish = (outcome: Outcome) => { + if (settled) return; + settled = true; + clearTimeout(timer); + clearTimeout(killTimer); + res.off("close", left); + this.running.delete(child); + resolve(outcome); + }; + child.once("error", (error) => finish({ error: new HttpError(502, "print_failed", `Could not start gentle-shell: ${error.message}`) })); + child.once("close", (code, signal) => { + if (ended === "timeout") { + this.options.log(`print timed out after ${this.limits.timeoutMs} ms`); + return finish({ error: new HttpError(504, "print_timeout", `No answer within ${this.limits.timeoutMs / 1000} s`) }); + } + if (ended === "too_large") return finish({ error: new HttpError(502, "output_too_large", `The answer is over ${this.limits.stdoutBytes} bytes`) }); + if (ended === "client_left") return finish({ error: new HttpError(499, "client_left", "The client closed the request") }); + if (code !== 0) { + const detail = stderr.trim() || Buffer.concat(stdout).toString("utf8").trim().slice(-this.limits.stderrChars); + return finish({ error: new HttpError(502, "print_failed", detail || `gentle-shell exited with ${signal ?? `code ${code}`}`), exitCode: code }); + } + finish({ text: Buffer.concat(stdout).toString("utf8") }); + }); + return promise; + } + + private signal(child: ChildProcess, signal: NodeJS.Signals): void { + if (child.pid === undefined) return; + try { + if (process.platform !== "win32") process.kill(-child.pid, signal); + // Windows has no process groups: end the launcher and the Pi it started. + else spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => child.kill()); + } catch { /* already gone */ } + } + + /** Ends every one-shot run (the server is stopping). */ + closeAll(): void { + for (const child of this.running) this.signal(child, "SIGKILL"); + } +} diff --git a/lib/serve-relay-cli.ts b/lib/serve-relay-cli.ts new file mode 100644 index 000000000..00a78b912 --- /dev/null +++ b/lib/serve-relay-cli.ts @@ -0,0 +1,133 @@ +// `gentle-shell relay --listen :`: runs the rendezvous servers +// connect out to (lib/serve-relay.ts) in the foreground, with the secret a +// server must present to register. The secret comes from +// GENTLE_SHELL_RELAY_SECRET, --secret-file, or `/relay/secret` (made on +// first run, owner-only). Run it under a service manager to keep it up. + +import { randomBytes } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { parseListen } from "./serve-cli.ts"; +import { startRelay, type Relay } from "./serve-relay.ts"; + +export type RelayArgs = + | { action: "run"; host: string; port: number; secretFile?: string; json: boolean } + | { action: "help" }; + +export const RELAY_HELP = [ + "Usage: gentle-shell [home selectors] relay --listen : [--secret-file ] [--json]", + "", + "Runs a relay that lets devices outside a Gentle Shell server's network reach it. Servers connect", + "out to the relay ('gentle-shell serve share --relay gsr://:'), so they need no", + "open port; a device asks the relay for a server and the relay joins the two TCP streams. TLS runs", + "end to end between the device and the server, which the device pins: the relay sees only", + "ciphertext and logs byte counts, never content.", + "", + "A server must present the relay secret to register: GENTLE_SHELL_RELAY_SECRET, else the file", + "--secret-file names, else /relay/secret (made on first run, owner-only). Give it to each", + "server's owner, who puts it in /serve/relay-secret or GENTLE_SHELL_RELAY_SECRET.", + "", + " --listen Address and port to listen on, for example 0.0.0.0:7700 (required).", + " --secret-file A file whose first line is the secret.", + " --json Print one JSON line when listening, for programs.", + "", + "It runs in the foreground until Ctrl+C. Protocol and limits: docs/serve.md#relay.", +].join("\n"); + +export function parseRelayArgs(args: readonly string[]): RelayArgs | { error: string } { + let listen: { host: string; port: number } | undefined; + let secretFile: string | undefined; + let json = false; + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + const value = (flag: string): string | undefined => { + if (arg === flag) return args[(i += 1)]; + return arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : undefined; + }; + if (arg === "--help" || arg === "-h") return { action: "help" }; + if (arg === "--json") { json = true; continue; } + if (arg === "--listen" || arg.startsWith("--listen=")) { + const parsed = parseListen(value("--listen") ?? ""); + if ("error" in parsed) return parsed; + listen = parsed; + continue; + } + if (arg === "--secret-file" || arg.startsWith("--secret-file=")) { + secretFile = value("--secret-file"); + if (!secretFile) return { error: "--secret-file needs a path" }; + continue; + } + return { error: `unknown relay argument "${arg}"` }; + } + if (!listen) return { error: "relay needs --listen :, for example --listen 0.0.0.0:7700" }; + return { action: "run", host: listen.host, port: listen.port, json, ...(secretFile === undefined ? {} : { secretFile }) }; +} + +export interface RelayCommandContext { + agentHome: string; + env: NodeJS.ProcessEnv; + stdout: (text: string) => void; + stderr: (text: string) => void; + /** Resolves when the relay should stop (defaults to SIGINT/SIGTERM). */ + untilStopped?: () => Promise; +} + +/** The secret and where it came from; the default file is made on first run. */ +export function relayServerSecret(ctx: Pick, secretFile?: string): { secret: string; source: string } { + const fromEnv = ctx.env.GENTLE_SHELL_RELAY_SECRET?.trim(); + if (fromEnv) return { secret: fromEnv, source: "GENTLE_SHELL_RELAY_SECRET" }; + const path = secretFile ?? join(ctx.agentHome, "relay", "secret"); + if (secretFile !== undefined || existsSync(path)) { + const secret = readFileSync(path, "utf8").split(/\r?\n/)[0].trim(); + if (!secret) throw new Error(`${path} holds no secret on its first line`); + return { secret, source: path }; + } + mkdirSync(join(ctx.agentHome, "relay"), { recursive: true, mode: 0o700 }); + const secret = randomBytes(24).toString("base64url"); + writeFileSync(path, `${secret}\n`, { mode: 0o600, flag: "wx" }); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } + return { secret, source: path }; +} + +function untilSignal(): Promise { + const { promise, resolve } = Promise.withResolvers(); + const done = () => { + process.off("SIGINT", done); + process.off("SIGTERM", done); + resolve(); + }; + process.on("SIGINT", done); + process.on("SIGTERM", done); + return promise; +} + +export async function runRelayCommand(args: RelayArgs, ctx: RelayCommandContext): Promise { + if (args.action === "help") { + ctx.stdout(`${RELAY_HELP}\n`); + return 0; + } + let relay: Relay | undefined; + try { + const { secret, source } = relayServerSecret(ctx, args.secretFile); + const log = (line: string) => ctx.stderr(`${new Date().toISOString()} ${line}\n`); + relay = await startRelay({ host: args.host, port: args.port, secret, log }); + const host = args.host.includes(":") ? `[${args.host}]` : args.host; + ctx.stdout(args.json + ? `${JSON.stringify({ schema: "gentle-shell.relay/v1", host: args.host, port: relay.port, secretSource: source })}\n` + : [ + `Gentle Shell relay listening on ${host}:${relay.port}.`, + `Servers register with: gentle-shell serve share --relay gsr://:${relay.port}`, + `They need the relay secret from ${source}${source === "GENTLE_SHELL_RELAY_SECRET" ? "" : " (copy its first line)"}, in their /serve/relay-secret or GENTLE_SHELL_RELAY_SECRET.`, + "Press Ctrl+C to stop.", + "", + ].join("\n")); + await (ctx.untilStopped ?? untilSignal)(); + log("relay stopping"); + return 0; + } catch (error) { + ctx.stderr(`gentle-shell relay: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } finally { + await relay?.close(); + } +} diff --git a/lib/serve-relay.ts b/lib/serve-relay.ts new file mode 100644 index 000000000..3f0e6c92a --- /dev/null +++ b/lib/serve-relay.ts @@ -0,0 +1,554 @@ +// A self-hostable rendezvous for reaching `gentle-shell serve` from outside its +// network (`gentle-shell relay`). Servers connect out to the relay and keep a +// control connection; a client asks the relay for a server by its certificate +// fingerprint; the relay asks that server to open one more outbound data +// connection and splices the two TCP streams. TLS runs end to end between the +// client and serve (the client pins the fingerprint), so the relay only ever +// sees ciphertext and logs byte counts, never content. Zero dependencies. +// +// Every message before the splice is one JSON object on one line ending in +// `\n` (at most 4 KiB); after the client's `{"t":"ok"}` line the connection +// carries raw bytes. + +import { createHash, createPrivateKey, randomBytes, sign, timingSafeEqual, verify, X509Certificate } from "node:crypto"; +import { connect, createServer, type Server, type Socket } from "node:net"; +import { certificateFingerprint, fingerprintBytes } from "./serve-tls.ts"; + +export const RELAY_PROTOCOL = 1; +export const RELAY_URL_SCHEME = "gsr:"; +/** What a server signs, followed by the relay's nonce (base64url text), to prove it holds the certificate's key. */ +export const RELAY_SIGNATURE_PREFIX = "gentle-shell/relay-register/v1 "; + +export const RELAY_LIMITS = { + /** One handshake line, newline included. */ + lineBytes: 4096, + /** A connection that has not finished its handshake by then is closed. */ + helloTimeoutMs: 10_000, + /** How long a client waits for the server's data connection. */ + openTimeoutMs: 10_000, + maxServers: 256, + /** Spliced plus waiting connections per server. */ + maxConnectionsPerServer: 32, + /** A spliced pair with no byte either way for this long is closed. */ + idleMs: 30 * 60_000, + /** The relay pings each server's control connection this often... */ + pingMs: 25_000, + /** ...and drops one that has said nothing for this long. */ + deadMs: 75_000, + /** Per-server byte rates are logged this often while connections are open. */ + logEveryMs: 60_000, +}; + +export type RelayErrorCode = "bad_request" | "unsupported_version" | "unauthorized" | "full" | "offline" | "busy" | "timeout" | "refused" | "replaced"; + +/** `gsr://:`: host and port, nothing else. */ +export function parseRelayUrl(value: string): { url: string; host: string; port: number } | { error: string } { + let url: URL; + try { + url = new URL(value); + } catch { + return { error: `a relay URL looks like gsr://relay.example.com:7700 (got "${value}")` }; + } + if (url.protocol !== RELAY_URL_SCHEME) return { error: `a relay URL starts with gsr:// (got "${value}")` }; + if (url.username || url.password || (url.pathname !== "" && url.pathname !== "/") || url.search || url.hash) return { error: `a relay URL is only gsr://:; the relay secret goes in GENTLE_SHELL_RELAY_SECRET or the relay-secret file (got "${value}")` }; + if (!url.port) return { error: `a relay URL needs a port, as in gsr://relay.example.com:7700 (got "${value}")` }; + const host = url.hostname.replace(/^\[|\]$/g, ""); + return { url: `gsr://${url.host}`, host, port: Number(url.port) }; +} + +function send(socket: Socket, message: Record): void { + if (socket.writable) socket.write(`${JSON.stringify(message)}\n`); +} + +function fail(socket: Socket, code: RelayErrorCode, message: string): void { + if (socket.writable) socket.end(`${JSON.stringify({ t: "error", code, message })}\n`); + else socket.destroy(); +} + +/** One handshake line, parsed, and the bytes that came after it. */ +interface RelayLine { + message: Record; + rest: Buffer; +} + +/** Reads one handshake line; resolves with the parsed object and any bytes after it, which stay unread by the socket. */ +function readLine(socket: Socket, limits: { lineBytes: number; helloTimeoutMs: number }, initial: Buffer = Buffer.alloc(0)): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + let buffer = initial; + const done = (error?: Error) => { + clearTimeout(timer); + socket.off("data", onData); + socket.off("close", onClose); + if (error) reject(error); + }; + const parse = () => { + const end = buffer.indexOf(0x0a); + if (end === -1) { + if (buffer.length >= limits.lineBytes) done(new Error("line too long")); + return; + } + if (end + 1 > limits.lineBytes) return done(new Error("line too long")); + let message: unknown; + try { message = JSON.parse(buffer.subarray(0, end).toString("utf8")); } catch { return done(new Error("not JSON")); } + if (!message || typeof message !== "object" || Array.isArray(message) || !("t" in message) || typeof message.t !== "string") return done(new Error("not a message")); + socket.pause(); + done(); + resolve({ message: message as Record, rest: buffer.subarray(end + 1) }); + }; + const onData = (chunk: Buffer) => { + buffer = Buffer.concat([buffer, chunk]); + parse(); + }; + const onClose = () => done(new Error("closed")); + const timer = setTimeout(() => done(new Error("timeout")), limits.helloTimeoutMs); + socket.on("data", onData); + socket.once("close", onClose); + if (buffer.length > 0) parse(); + if (socket.isPaused()) socket.resume(); + return promise; +} + +/** Calls `onLine` for each line until the socket ends; a line over the limit or not JSON closes it. */ +function readLines(socket: Socket, lineBytes: number, initial: Buffer, onLine: (message: Record) => void): void { + let buffer = initial; + const drain = () => { + for (let end = buffer.indexOf(0x0a); end !== -1; end = buffer.indexOf(0x0a)) { + const line = buffer.subarray(0, end); + buffer = buffer.subarray(end + 1); + let message: unknown; + try { message = JSON.parse(line.toString("utf8")); } catch { return void socket.destroy(); } + if (message && typeof message === "object" && !Array.isArray(message)) onLine(message as Record); + } + if (buffer.length >= lineBytes) socket.destroy(); + }; + socket.on("data", (chunk: Buffer) => { + buffer = Buffer.concat([buffer, chunk]); + drain(); + }); + drain(); + socket.resume(); +} + +const sameSecret = (given: unknown, expected: string) => typeof given === "string" + && timingSafeEqual(createHash("sha256").update(given).digest(), createHash("sha256").update(expected).digest()); + +const shortId = (id: string) => id.slice(0, 8); + +// --- the relay --------------------------------------------------------------------- + +interface Pending { + cid: string; + key: string; + client: Socket; + rest: Buffer; + helloBytes: number; + timer: NodeJS.Timeout; +} + +interface Pair { + client: Socket; + data: Socket; + clientHello: number; + dataHello: number; + startedAt: number; + sampledUp: number; + sampledDown: number; +} + +interface Registration { + id: string; + control: Socket; + pending: Map; + pairs: Set; + lastHeard: number; + ping: NodeJS.Timeout; +} + +export interface RelayOptions { + host: string; + port: number; + /** Servers must present it to register; without one any server may. */ + secret?: string; + limits?: Partial; + now?: () => number; + log?: (line: string) => void; +} + +export interface Relay { + host: string; + port: number; + /** Registered servers (fingerprints), for tests and status. */ + servers(): string[]; + close(): Promise; +} + +export function startRelay(options: RelayOptions): Promise { + const limits = { ...RELAY_LIMITS, ...options.limits }; + const now = options.now ?? Date.now; + const log = options.log ?? (() => {}); + const registrations = new Map(); + const pendingByCid = new Map(); + const sockets = new Set(); + + const unregister = (registration: Registration, reason: string) => { + if (registrations.get(registration.id) !== registration) return; + registrations.delete(registration.id); + clearInterval(registration.ping); + for (const pending of registration.pending.values()) { + clearTimeout(pending.timer); + pendingByCid.delete(pending.cid); + fail(pending.client, "offline", "The server left the relay"); + } + registration.control.destroy(); + log(`relay: server ${shortId(registration.id)} left (${reason})`); + }; + + const registerServer = async (socket: Socket, hello: Record, rest: Buffer) => { + const id = typeof hello.id === "string" ? hello.id : ""; + if (!fingerprintBytes(id)) return fail(socket, "bad_request", "id must be the server certificate's base64url SHA-256 fingerprint"); + if (options.secret !== undefined && !sameSecret(hello.secret, options.secret)) { + log(`relay: refused server ${shortId(id)} from ${socket.remoteAddress}: wrong relay secret`); + return fail(socket, "unauthorized", "Wrong or missing relay secret"); + } + if (!registrations.has(id) && registrations.size >= limits.maxServers) return fail(socket, "full", "This relay serves as many servers as it can"); + const nonce = randomBytes(32).toString("base64url"); + send(socket, { t: "challenge", nonce }); + const auth = await readLine(socket, limits, rest); + if (auth.message.t !== "auth" || typeof auth.message.cert !== "string" || typeof auth.message.sig !== "string") return fail(socket, "bad_request", "Expected the auth line"); + let proven = false; + try { + const cert = new X509Certificate(Buffer.from(auth.message.cert, "base64url")); + proven = certificateFingerprint(cert.raw) === id && verify("sha256", Buffer.from(`${RELAY_SIGNATURE_PREFIX}${nonce}`, "ascii"), cert.publicKey, Buffer.from(auth.message.sig, "base64url")); + } catch { /* not a certificate or not a signature */ } + if (!proven) { + log(`relay: refused server ${shortId(id)} from ${socket.remoteAddress}: no proof of the certificate's key`); + return fail(socket, "unauthorized", "The signature does not prove this certificate"); + } + const previous = registrations.get(id); + if (previous) { + fail(previous.control, "replaced", "The same server registered again"); + unregister(previous, "replaced by a new connection"); + } + if (registrations.size >= limits.maxServers) return fail(socket, "full", "This relay serves as many servers as it can"); + const registration: Registration = { id, control: socket, pending: new Map(), pairs: new Set(), lastHeard: now(), ping: setInterval(() => { + if (now() - registration.lastHeard > limits.deadMs) return unregister(registration, "no answer to pings"); + send(socket, { t: "ping" }); + }, limits.pingMs) }; + registration.ping.unref(); + registrations.set(id, registration); + socket.setKeepAlive(true, limits.pingMs); + socket.once("close", () => unregister(registration, "control connection closed")); + send(socket, { t: "ready", v: RELAY_PROTOCOL }); + log(`relay: server ${shortId(id)} registered from ${socket.remoteAddress}`); + readLines(socket, limits.lineBytes, auth.rest, (message) => { + registration.lastHeard = now(); + if (message.t === "refuse" && typeof message.cid === "string") { + const pending = registration.pending.get(message.cid); + if (!pending) return; + registration.pending.delete(message.cid); + pendingByCid.delete(message.cid); + clearTimeout(pending.timer); + fail(pending.client, "refused", "The server has nothing on that port"); + } + }); + }; + + const openForClient = (client: Socket, hello: Record, rest: Buffer, helloBytes: number) => { + const id = typeof hello.id === "string" ? hello.id : ""; + const port = hello.port; + if (!fingerprintBytes(id)) return fail(client, "bad_request", "id must be the server certificate's base64url SHA-256 fingerprint"); + if (port !== undefined && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)) return fail(client, "bad_request", "port must be a whole number 1-65535"); + const registration = registrations.get(id); + if (!registration) return fail(client, "offline", "That server is not connected to this relay"); + if (registration.pending.size + registration.pairs.size >= limits.maxConnectionsPerServer) return fail(client, "busy", "That server has as many relayed connections as it may"); + const cid = randomBytes(12).toString("base64url"); + const key = randomBytes(16).toString("base64url"); + const pending: Pending = { cid, key, client, rest, helloBytes, timer: setTimeout(() => { + registration.pending.delete(cid); + pendingByCid.delete(cid); + fail(client, "timeout", "The server did not open a connection in time"); + }, limits.openTimeoutMs) }; + registration.pending.set(cid, pending); + pendingByCid.set(cid, { registration, pending }); + client.once("close", () => { + if (!registration.pending.delete(cid)) return; + pendingByCid.delete(cid); + clearTimeout(pending.timer); + }); + send(registration.control, { t: "open", cid, key, ...(port === undefined ? {} : { port }) }); + }; + + const splice = (data: Socket, hello: Record, rest: Buffer, helloBytes: number) => { + const found = typeof hello.cid === "string" ? pendingByCid.get(hello.cid) : undefined; + if (!found || !sameSecret(hello.key, found.pending.key)) return fail(data, "unauthorized", "Unknown or expired connection"); + const { registration, pending } = found; + registration.pending.delete(pending.cid); + pendingByCid.delete(pending.cid); + clearTimeout(pending.timer); + const client = pending.client; + if (client.destroyed) return void data.destroy(); + const pair: Pair = { client, data, clientHello: pending.helloBytes, dataHello: helloBytes, startedAt: now(), sampledUp: 0, sampledDown: 0 }; + registration.pairs.add(pair); + const end = () => { + if (!registration.pairs.delete(pair)) return; + client.destroy(); + data.destroy(); + const up = Math.max(0, client.bytesRead - pair.clientHello); + const down = Math.max(0, data.bytesRead - pair.dataHello); + log(`relay: server ${shortId(registration.id)}: connection closed after ${Math.round((now() - pair.startedAt) / 1000)} s, ${up} B up, ${down} B down`); + }; + for (const socket of [client, data]) { + socket.setNoDelay(true); + socket.setTimeout(limits.idleMs, end); + socket.once("close", end); + } + client.write(`${JSON.stringify({ t: "ok" })}\n`); + if (pending.rest.length > 0) data.write(pending.rest); + if (rest.length > 0) client.write(rest); + client.pipe(data); + data.pipe(client); + client.resume(); + data.resume(); + }; + + const rates = setInterval(() => { + for (const registration of registrations.values()) { + if (registration.pairs.size === 0) continue; + let up = 0; + let down = 0; + for (const pair of registration.pairs) { + const u = pair.client.bytesRead; + const d = pair.data.bytesRead; + up += u - Math.max(pair.sampledUp, pair.clientHello); + down += d - Math.max(pair.sampledDown, pair.dataHello); + pair.sampledUp = u; + pair.sampledDown = d; + } + const seconds = limits.logEveryMs / 1000; + log(`relay: server ${shortId(registration.id)}: ${registration.pairs.size} connection(s), ${Math.round(up / seconds)} B/s up, ${Math.round(down / seconds)} B/s down`); + } + }, limits.logEveryMs); + rates.unref(); + + const server: Server = createServer((socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + socket.on("error", () => socket.destroy()); + readLine(socket, limits).then(({ message, rest }) => { + const helloBytes = socket.bytesRead - rest.length; + if (message.v !== RELAY_PROTOCOL) return fail(socket, "unsupported_version", `This relay speaks version ${RELAY_PROTOCOL}`); + if (message.t === "gsr/server") return registerServer(socket, message, rest); + if (message.t === "gsr/client") return openForClient(socket, message, rest, helloBytes); + if (message.t === "gsr/data") return splice(socket, message, rest, helloBytes); + fail(socket, "bad_request", "Unknown hello"); + }).catch(() => socket.destroy()); + }); + + const { promise, resolve, reject } = Promise.withResolvers(); + server.once("error", reject); + server.listen(options.port, options.host.replace(/^\[|\]$/g, ""), () => { + server.off("error", reject); + const address = server.address(); + resolve({ + host: options.host, + port: typeof address === "object" && address ? address.port : options.port, + servers: () => [...registrations.keys()], + close: async () => { + clearInterval(rates); + for (const registration of [...registrations.values()]) unregister(registration, "relay stopping"); + const closed = Promise.withResolvers(); + server.close(() => closed.resolve()); + for (const socket of sockets) socket.destroy(); + await closed.promise; + }, + }); + }); + return promise; +} + +// --- a server's link to the relay -------------------------------------------------- + +export interface RelayLinkOptions { + url: string; + secret?: string; + /** The server's certificate (DER) and its key (PEM): the relay routes by the fingerprint and checks a signature. */ + certDer: Buffer; + keyPem: string; + /** Where a relayed connection for `port` goes (undefined: the API); undefined refuses it. */ + accept: (port: number | undefined) => ((socket: Socket) => void) | undefined; + limits?: Partial; + log?: (line: string) => void; + /** Reconnect delays: doubling from `retryMinMs` up to `retryMaxMs`. */ + retryMinMs?: number; + retryMaxMs?: number; +} + +export interface RelayLink { + url: string; + /** The routing id: the certificate's fingerprint. */ + id: string; + /** Whether the relay accepted the registration and the control connection is open. */ + connected(): boolean; + /** Resolves once registered (for tests and the CLI's first status line). */ + ready(): Promise; + close(): void; +} + +/** Keeps a registration with the relay: connects out, proves the certificate, opens a data connection per client, reconnects with backoff. */ +export function startRelayLink(options: RelayLinkOptions): RelayLink { + const parsed = parseRelayUrl(options.url); + if ("error" in parsed) throw new Error(parsed.error); + const limits = { ...RELAY_LIMITS, ...options.limits }; + const log = options.log ?? (() => {}); + const id = certificateFingerprint(options.certDer); + const key = createPrivateKey(options.keyPem); + const retryMin = options.retryMinMs ?? 1000; + const retryMax = options.retryMaxMs ?? 60_000; + let delay = retryMin; + let control: Socket | undefined; + let registered = false; + let closed = false; + let retry: NodeJS.Timeout | undefined; + let waiters: Array<() => void> = []; + const dataSockets = new Set(); + + const openData = (message: Record) => { + const cid = message.cid; + const dataKey = message.key; + if (typeof cid !== "string" || typeof dataKey !== "string") return; + const port = typeof message.port === "number" ? message.port : undefined; + const target = options.accept(port); + if (!target) { + if (control) send(control, { t: "refuse", cid }); + return; + } + const data = connect({ host: parsed.host, port: parsed.port }); + dataSockets.add(data); + data.once("close", () => dataSockets.delete(data)); + data.on("error", () => data.destroy()); + data.setTimeout(limits.openTimeoutMs, () => data.destroy()); + data.once("connect", () => { + data.setTimeout(0); + data.setNoDelay(true); + data.write(`${JSON.stringify({ t: "gsr/data", v: RELAY_PROTOCOL, cid, key: dataKey })}\n`); + target(data); + }); + }; + + const schedule = () => { + if (closed || retry) return; + retry = setTimeout(() => { + retry = undefined; + attempt(); + }, delay); + retry.unref(); + delay = Math.min(retryMax, delay * 2); + }; + + const attempt = () => { + if (closed) return; + const socket = connect({ host: parsed.host, port: parsed.port }); + control = socket; + socket.on("error", () => socket.destroy()); + socket.once("close", () => { + if (control === socket) control = undefined; + if (registered) log(`relay: disconnected from ${parsed.url}`); + registered = false; + schedule(); + }); + socket.once("connect", async () => { + try { + socket.setNoDelay(true); + socket.setKeepAlive(true, limits.pingMs); + send(socket, { t: "gsr/server", v: RELAY_PROTOCOL, id, ...(options.secret === undefined ? {} : { secret: options.secret }) }); + const challenge = await readLine(socket, limits); + if (challenge.message.t === "error") throw new Error(`${challenge.message.code}: ${challenge.message.message}`); + if (challenge.message.t !== "challenge" || typeof challenge.message.nonce !== "string") throw new Error("unexpected answer"); + const sig = sign("sha256", Buffer.from(`${RELAY_SIGNATURE_PREFIX}${challenge.message.nonce}`, "ascii"), key); + send(socket, { t: "auth", cert: options.certDer.toString("base64url"), sig: sig.toString("base64url") }); + const ready = await readLine(socket, limits, challenge.rest); + if (ready.message.t === "error") throw new Error(`${ready.message.code}: ${ready.message.message}`); + if (ready.message.t !== "ready") throw new Error("unexpected answer"); + registered = true; + delay = retryMin; + log(`relay: registered with ${parsed.url} as ${shortId(id)}`); + for (const done of waiters) done(); + waiters = []; + let heard = Date.now(); + const watchdog = setInterval(() => { if (Date.now() - heard > limits.deadMs) socket.destroy(); }, limits.pingMs); + watchdog.unref(); + socket.once("close", () => clearInterval(watchdog)); + readLines(socket, limits.lineBytes, ready.rest, (message) => { + heard = Date.now(); + if (message.t === "ping") send(socket, { t: "pong" }); + else if (message.t === "open") openData(message); + }); + } catch (error) { + log(`relay: ${parsed.url} refused the registration: ${error instanceof Error ? error.message : String(error)}`); + socket.destroy(); + } + }); + }; + + attempt(); + return { + url: parsed.url, + id, + connected: () => registered, + ready: () => { + if (registered) return Promise.resolve(); + const { promise, resolve } = Promise.withResolvers(); + waiters.push(resolve); + return promise; + }, + close: () => { + closed = true; + clearTimeout(retry); + control?.destroy(); + for (const socket of dataSockets) socket.destroy(); + }, + }; +} + +// --- a client through the relay ---------------------------------------------------- + +export class RelayError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +/** + * A TCP stream to the server with fingerprint `id` through the relay at `url` + * (to its listener on `port`, the API when absent). The caller runs TLS over it + * and pins `id`; the relay never sees the plaintext. + */ +export async function connectThroughRelay(url: string, id: string, options: { port?: number; timeoutMs?: number } = {}): Promise { + const parsed = parseRelayUrl(url); + if ("error" in parsed) throw new RelayError("bad_request", parsed.error); + const socket = connect({ host: parsed.host, port: parsed.port }); + const { promise, resolve, reject } = Promise.withResolvers(); + socket.once("connect", () => resolve()); + socket.once("error", reject); + await promise; + socket.off("error", reject); + socket.on("error", () => socket.destroy()); + socket.setNoDelay(true); + send(socket, { t: "gsr/client", v: RELAY_PROTOCOL, id, ...(options.port === undefined ? {} : { port: options.port }) }); + const limits = { ...RELAY_LIMITS, helloTimeoutMs: options.timeoutMs ?? RELAY_LIMITS.openTimeoutMs + 5_000 }; + let answer: RelayLine; + try { + answer = await readLine(socket, limits); + } catch (error) { + socket.destroy(); + throw new RelayError("timeout", `The relay did not answer: ${error instanceof Error ? error.message : String(error)}`); + } + if (answer.message.t !== "ok") { + socket.destroy(); + throw new RelayError(typeof answer.message.code === "string" ? answer.message.code : "bad_request", typeof answer.message.message === "string" ? answer.message.message : "The relay refused"); + } + if (answer.rest.length > 0) socket.unshift(answer.rest); + return socket; +} diff --git a/lib/serve-server.ts b/lib/serve-server.ts new file mode 100644 index 000000000..754c793fc --- /dev/null +++ b/lib/serve-server.ts @@ -0,0 +1,1132 @@ +// `gentle-shell serve`'s HTTP API: JSON endpoints plus Server-Sent Events, +// hardened like the Tower server (lib/tower-server.ts): no cookies, a bearer +// token on every authenticated request, any foreign Origin refused, the Host +// header checked against the listen address, bounded bodies, and CSP/no-store +// headers. Zero dependencies: SSE works from browsers, phones and curl; a +// WebSocket transport can come later behind the same contract. + +import { randomBytes } from "node:crypto"; +import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import type { IncomingMessage, Server as HttpServer, ServerResponse } from "node:http"; +import { arch, homedir, hostname } from "node:os"; +import { basename, join, sep } from "node:path"; +import { hasScope, isServeScope, type Principal, type ServeAuth, type ServeScope } from "./serve-auth.ts"; +import { startDiscoveryResponder, type DiscoveryResponder } from "./serve-discovery.ts"; +import { FileService, type SERVE_FS_LIMITS } from "./serve-files.ts"; +import { GitService, type SERVE_GIT_LIMITS } from "./serve-git.ts"; +import { ServeChecks, type ServeChecksOptions } from "./serve-checks.ts"; +import { ForwardError, ForwardManager, type ForwardInfo, type SERVE_FORWARD_LIMITS } from "./serve-forward.ts"; +import { HttpError, need, readJsonBody, realDirectory, SECURITY_HEADERS, sendError, sendJson } from "./serve-http.ts"; +import { UploadStore, type SERVE_UPLOAD_LIMITS } from "./serve-uploads.ts"; +import { PrintService, type SERVE_PRINT_LIMITS } from "./serve-print.ts"; +import { UPGRADE_CHANNELS, UpgradeService, type ServeUpgradeOptions, type UpgradeChannel } from "./serve-upgrade.ts"; +import { TerminalService, type SERVE_TERM_LIMITS } from "./serve-terminals.ts"; +import { HOST_TOOL_METHODS, isDesktopEventRecord, KeeperLink, SERVE_SESSION_LIMITS, ServeSession, SessionError, type ServeSessionLimits, type SessionLaunch } from "./serve-session.ts"; +import { exitedSnapshot, keeperAlive, keeperEndpoint, newKeeperToken, privateKeeperDir, readKeeperRecords, removeKeeperRecord, removePrivateKeeperDir, SERVE_KEEPER_LIMITS, spawnKeeper, writeKeeperRecord, type KeeperRecord } from "./serve-session-keeper.ts"; +import { startRelayLink, type RelayLink } from "./serve-relay.ts"; +import { createServeListener, PairProofs, PAIR_PROOF, requestScheme, type ConnectionVia, type ServeTlsIdentity } from "./serve-tls.ts"; + +export const SERVE_SCHEMA = "gentle-shell.serve/v1"; +export const SERVE_PROTOCOL = 1; +export const SERVE_IDENTITY_SCHEMA = "gentle-shell.serve.identity/v1"; +/** Public identity path: a client holding a connection code probes it to find the address that reaches this server. */ +export const SERVE_IDENTITY_PATH = "/.well-known/gentle-shell"; +export const SERVE_CAPABILITIES = ["sessions", "pi-rpc", "desktop-rpc", "desktop", "sse", "stream-tickets", "pairing", "devices", "forwards", "server-forwards", "services", "tower", "files", "git", "unpair", "checks"] as const; + +export const SERVE_SERVER_LIMITS = { + heartbeatMs: 20_000, + smallBodyBytes: 16 * 1024, + desktopBodyBytes: 80 * 1024, + /** Host tool methods (`host_tool_result` carries screenshots); the session caps the result's content at 8 MiB plus 1 MiB of details and the request at 10 MiB, envelope included. */ + hostToolBodyBytes: 10 * 1024 * 1024 - 1024, + /** Pi RPC commands may carry images. */ + rpcBodyBytes: 8 * 1024 * 1024, + rpcTimeoutMs: 30_000, + maxSessions: 16, + /** Exited sessions kept (with their replay ring) until deleted. */ + keepExited: 16, + /** The control session behind `/api/desktop` stops after this long with no request and no open stream. */ + controlIdleMs: 10 * 60_000, +}; + +/** What a stream ticket for `GET /api/desktop/events` is bound to (never a session id: those match `[A-Za-z0-9_]`). */ +const DESKTOP_STREAM = ":desktop"; + +/** Pi RPC commands that only read; every other command needs `sessions:operate`. */ +const READ_COMMANDS = new Set(["get_state", "get_messages", "get_available_models", "get_available_thinking_levels", "get_session_stats", + "get_fork_messages", "get_entries", "get_tree", "get_last_assistant_text", "get_commands"]); + +/** Desktop RPC reads (`capabilities`, `get_*`, `list_*`) need `sessions:read`; anything else operates. */ +export function desktopMethodScope(method: string): ServeScope { + return method === "capabilities" || method.startsWith("get_") || method.startsWith("list_") ? "sessions:read" : "sessions:operate"; +} + +export function rpcCommandScope(type: string): ServeScope { + return READ_COMMANDS.has(type) ? "sessions:read" : "sessions:operate"; +} + +/** + * Whether a Pi RPC message is a `/gentle:desktop` request for a host tool + * method (`set_host_tools`, `host_tool_result`, `host_tool_progress`, + * `host_message`, `set_host_context`). Those go only through `/desktop`, where the server sets + * the provider to the calling device and checks who answers a call; through + * `/rpc` a client could otherwise register as, or answer for, another device. + * Pi takes the command's arguments after the first space and the router parses + * them with `JSON.parse`, exactly as here. + */ +export function carriesHostToolRequest(message: string): boolean { + if (!message.startsWith("/gentle:desktop")) return false; + const space = message.indexOf(" "); + if (space === -1) return false; + let request: unknown; + try { + request = JSON.parse(message.slice(space + 1)); + } catch { + return false; + } + return !!request && typeof request === "object" && "method" in request && typeof request.method === "string" && Object.hasOwn(HOST_TOOL_METHODS, request.method); +} + +export interface ServeServerOptions { + /** Address to bind; loopback unless the operator chose otherwise. */ + host: string; + port: number; + /** Extra DNS names (no port) the Host header may carry, beyond those the listen address allows. */ + allowHosts?: readonly string[]; + auth: ServeAuth; + /** Builds the child for a new session (the real CLI spawns `gentle-shell --mode rpc`). */ + launchSession: (input: { cwd: string; sessionId?: string }) => SessionLaunch; + /** Builds a one-shot `--print` run in a folder (`POST /api/print`); without it the server runs none. */ + launchPrint?: (input: { cwd: string; model?: string }) => SessionLaunch; + printLimits?: Partial; + version: string; + limits?: Partial; + sessionLimits?: Partial; + keeperLimits?: Partial; + now?: () => number; + log?: (line: string) => void; + /** `POST /api/server/stop` (admin): the owner closes the server; `endSessions` asks to stop its sessions too. */ + onStopRequested?: (request: { endSessions: boolean }) => void; + /** Listen ports forwards take (inclusive), so a firewall can open them; OS-assigned when absent. */ + forwardPorts?: { from: number; to: number }; + forwardLimits?: Partial; + /** Starts Gentle Tower on this machine's loopback (`POST /api/tower`); the real CLI runs it in-process. */ + startTower?: () => Promise; + fsLimits?: Partial; + gitLimits?: Partial; + uploadLimits?: Partial; + /** `/serve`: the server id, session keepers, uploads and the terminal host's socket live under it. Without it the id changes every run, sessions end with the server, and uploads and terminals are off. */ + serveDir?: string; + termLimits?: Partial; + /** The environment for git commands and service lookups; this process's by default. */ + env?: NodeJS.ProcessEnv; + /** The certificate for HTTPS (`serve` passes it on a network listen or with a relay): TLS for network peers, plain HTTP stays for this machine. */ + tls?: Pick; + /** Keep a registration with this relay (`gsr://host:port`), reachable by the certificate's fingerprint; needs `tls`. */ + relay?: { url: string; secret?: string; retryMinMs?: number }; + /** `POST /api/upgrade` (admin): runs the upgrade command and, on success, calls `onUpgraded` so the owner restarts the server. Without it the server has no `upgrade` capability. */ + upgrade?: Omit; + /** `GET /api/checks`: the companion setup check and the agent home; tools are looked up in `env`. */ + checks?: Partial>; +} + +/** A running Gentle Tower: its loopback port, the path that carries its token, and how to stop it. */ +export interface ServeTower { + port: number; + path: string; + close(): Promise; +} + +export interface ServeServer { + serverId: string; + host: string; + port: number; + /** Base URL a local client uses. */ + url: string; + startedAt: number; + /** Whether it answers LAN discovery (network listen only, when the UDP port could be bound). */ + discovery: boolean; + /** The certificate's fingerprint when it serves HTTPS. */ + fingerprint?: string; + /** Its relay registration, when it has one. */ + relay?: RelayLink; + /** Stops the server. Its sessions keep running for the next server to reattach, unless `endSessions` (or the server has no serve folder). */ + close(options?: { endSessions?: boolean }): Promise; +} + +export function isLoopbackHost(host: string): boolean { + const h = host.replace(/^\[|\]$/g, "").toLowerCase(); + return h === "localhost" || h === "::1" || /^127(\.\d{1,3}){3}$/.test(h); +} + +export function isUnspecified(host: string): boolean { + return host === "0.0.0.0" || host === "::" || host === "[::]"; +} + +/** The Host header values a request may carry for this listen address (DNS-rebinding guard), plus `extra` names the operator allowed. */ +export function allowedHosts(bindHost: string, port: number, extra: readonly string[] = []): (host: string) => boolean { + const named = new Set(); + const add = (h: string) => named.add(`${h.toLowerCase()}:${port}`); + const bare = bindHost.replace(/^\[|\]$/g, ""); + if (isLoopbackHost(bare) || isUnspecified(bindHost)) for (const h of ["127.0.0.1", "localhost", "[::1]"]) add(h); + if (!isUnspecified(bindHost)) add(bare.includes(":") ? `[${bare}]` : bare); + if (isUnspecified(bindHost)) { + const own = hostname().toLowerCase(); + add(own); + if (!own.endsWith(".local")) add(`${own}.local`); + } + for (const h of extra) add(h); + return (value: string) => { + const host = value.toLowerCase(); + if (named.has(host)) return true; + // On an unspecified bind any of this machine's addresses can reach it; names other than its own cannot. + if (!isUnspecified(bindHost)) return false; + const m = /^(?:\[[0-9a-f:.]+\]|\d{1,3}(?:\.\d{1,3}){3}):(\d+)$/.exec(host); + return !!m && Number(m[1]) === port; + }; +} + +function bearer(req: IncomingMessage): string | undefined { + const header = req.headers.authorization; + if (typeof header !== "string") return undefined; + const m = /^Bearer\s+(\S{1,512})$/i.exec(header); + return m ? m[1] : undefined; +} + +/** + * The server's identity, minted once per agent home in `/server-id` + * (`0600`) and the same on every run, so a restart or upgrade keeps the id + * devices, connection codes and discovery replies know. Unreadable or + * malformed: minted again. + */ +export function stableServerId(serveDir: string): string { + const path = join(serveDir, "server-id"); + try { + const saved = readFileSync(path, "utf8").trim(); + if (/^srv_[0-9a-f]{16}$/.test(saved)) return saved; + } catch { /* none yet */ } + const minted = `srv_${randomBytes(8).toString("hex")}`; + mkdirSync(serveDir, { recursive: true, mode: 0o700 }); + writeFileSync(path, `${minted}\n`, { mode: 0o600 }); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } + return minted; +} + +export function startServeServer(options: ServeServerOptions): Promise { + if (options.relay && !options.tls) return Promise.reject(new Error("a relay needs TLS: the relay must only ever see ciphertext")); + const limits = { ...SERVE_SERVER_LIMITS, ...options.limits }; + const now = options.now ?? Date.now; + const log = options.log ?? (() => {}); + const serverId = options.serveDir === undefined ? `srv_${randomBytes(8).toString("hex")}` : stableServerId(options.serveDir); + const startedAt = now(); + const sessions = new Map(); + let hostOk: (host: string) => boolean = () => false; + let closing = false; + // Device names for the model-facing "not connected" answer of a host tool call. + const deviceNames = new Map(); + const deviceLabel = (deviceId: string) => deviceNames.get(deviceId) ?? options.auth.listDevices().find((d) => d.id === deviceId)?.name; + + let mainPort = options.port; + let relayLink: RelayLink | undefined; + // Pages on this machine's loopback, opened from a device: one listener each on the same address as this server. + const forwards = new ForwardManager({ + bindHost: options.host, + hostCheck: (port) => allowedHosts(options.host, port, options.allowHosts), + ...(options.forwardPorts === undefined ? {} : { portRange: options.forwardPorts }), + ...(options.tls === undefined ? {} : { tls: options.tls }), + now, + log, + limits: options.forwardLimits, + }); + // Pairing proofs bind each live code to the certificate, for a client that found this server through discovery. + const proofs = options.tls === undefined ? undefined : new PairProofs(options.tls.fingerprint, now); + // Files on this machine, and their change streams. + const files = new FileService({ limits: options.fsLimits, now, log }); + // git commands in folders on this machine. + const git = new GitService({ env: options.env ?? process.env, limits: options.gitLimits, log }); + // Whether this machine has what sessions need (`GET /api/checks`). + const checks = new ServeChecks({ env: options.env ?? process.env, version: options.version, ...options.checks }); + // One-shot prompts (commit messages) answered by this machine's Gentle Shell. + const prints = new PrintService({ ...(options.launchPrint ? { launchPrint: options.launchPrint } : {}), limits: options.printLimits, log }); + // Upgrades of Gentle Shell itself, from an admin client. + // A finished setup or upgrade changes what the readiness checks see. + const upgrade = options.upgrade ? new UpgradeService({ ...options.upgrade, onFinished: () => checks.forget(), log }) : undefined; + // Files a client sends for the agent to see. + const uploads = options.serveDir === undefined ? undefined : new UploadStore({ dir: join(options.serveDir, "uploads"), limits: options.uploadLimits, now, log }); + // Persistent terminals in the native terminal host, which outlives this server. + const terminals = options.serveDir === undefined ? undefined : new TerminalService({ serveDir: options.serveDir, env: options.env ?? process.env, limits: options.termLimits, log }); + // Gentle Tower, when a device asked for it; stopped with the server. + let tower: (ServeTower & { startedAt: number }) | undefined; + let towerStarting: Promise | undefined; + + options.auth.onRevoke((deviceId) => { + for (const s of sessions.values()) s.dropDevice(deviceId); + control?.dropDevice(deviceId); + forwards.closeWhere((f) => f.deviceId === deviceId, "device revoked"); + files.closeDevice(deviceId); + terminals?.closeDevice(deviceId); + }); + + const sessionView = (s: ServeSession, principal: Principal) => ({ + id: s.id, + name: basename(s.cwd) || null, + // The absolute folder only for a token that may start sessions anyway. + ...(hasScope(principal, "sessions:operate") ? { cwd: s.cwd } : {}), + state: s.state, + startedAt: new Date(s.startedAt).toISOString(), + ...(s.exitedAt === undefined ? {} : { exitedAt: new Date(s.exitedAt).toISOString(), exitCode: s.exitCode, exitSignal: s.exitSignal }), + seq: s.seq, + subscribers: s.subscriberCount, + pendingDialogs: s.pendingDialogs().length, + // The device that most recently drove the session: host tool calls go to it first. + lastActiveDevice: s.lastActiveDevice() ?? null, + }); + + const findSession = (id: string): ServeSession => { + const s = sessions.get(id); + if (!s) throw new HttpError(404, "not_found", "No such session"); + return s; + }; + + // Sessions run under detached keepers (lib/serve-session-keeper.ts) that outlive this server; a later server + // reattaches them. Without a serve folder they live in a private temporary folder and end with the server. + const keepSessions = options.serveDir !== undefined; + const keeperDir = options.serveDir !== undefined ? join(options.serveDir, "sessions") : privateKeeperDir(); + const keeperLimits = { ...SERVE_KEEPER_LIMITS, ...options.keeperLimits }; + let starting = 0; + + const forgetExited = () => { + const exited = [...sessions.values()].filter((s) => s.state === "exited"); + for (const s of exited.slice(0, Math.max(0, exited.length - limits.keepExited))) { + sessions.delete(s.id); + removeKeeperRecord(keeperDir, s.id); + } + }; + + const sessionHooks = (id: string) => ({ + limits: options.sessionLimits, + now, + onStderr: (text: string) => { for (const line of text.split("\n")) if (line.trim()) log(`[${id}] ${line}`); }, + onExit: (s: ServeSession) => { + log(`[${id}] exited (code ${s.exitCode}, signal ${s.exitSignal})`); + forwards.closeWhere((f) => f.sessionId === id, "session ended"); + forgetExited(); + }, + deviceLabel, + }); + + /** Connects to a session's keeper and takes over its state; the control session is kept apart from the listed ones. */ + const attachSession = async (id: string, token: string, reattached: boolean, asControl = false): Promise => { + const { link, snapshot, ring } = await KeeperLink.connect(keeperEndpoint(keeperDir, id), token, { + timeoutMs: keeperLimits.connectMs, + maxLineBytes: options.sessionLimits?.maxLineBytes ?? SERVE_SESSION_LIMITS.maxLineBytes, + }); + const session = new ServeSession({ snapshot, ring, link, reattached, ...(asControl ? controlHooks(id) : sessionHooks(id)) }); + if (asControl) adoptControl(session, reattached); + else sessions.set(id, session); + return session; + }; + + /** Starts a keeper running a new session in `cwd` and attaches it; the caller counts it against the limit. */ + const spawnSession = async (cwd: string, sessionId: string | undefined, asControl: boolean): Promise => { + const id = `ses_${randomBytes(8).toString("hex")}`; + const token = newKeeperToken(); + const launch = options.launchSession({ cwd, ...(sessionId === undefined ? {} : { sessionId }) }); + try { + await spawnKeeper({ id, dir: keeperDir, token, launch, ...(options.sessionLimits ? { limits: options.sessionLimits } : {}), keeperLimits }); + // Its id beside the keepers: a later server knows it again as the control session, never as a listed one. + if (asControl) writeFileSync(controlFile, `${id}\n`, { mode: 0o600 }); + return await attachSession(id, token, false, asControl); + } catch (error) { + removeKeeperRecord(keeperDir, id); + if (asControl) forgetControlId(id); + const message = error instanceof Error ? error.message : String(error); + log(`[${id}] could not start: ${message}`); + throw new HttpError(503, "session_start_failed", `The session could not start: ${message}`); + } + }; + + const startSession = async (cwd: string, sessionId?: string): Promise => { + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + const running = [...sessions.values()].filter((s) => s.state === "running").length + starting; + if (running >= limits.maxSessions) throw new HttpError(429, "too_many_sessions", `At most ${limits.maxSessions} sessions run at once`); + starting += 1; + let session: ServeSession; + try { + session = await spawnSession(cwd, sessionId, false); + } finally { + starting -= 1; + } + // The server began stopping meanwhile: the session goes the way the others went. + if (closing) { + if (keepSessions) session.detach(); + else await session.stop(); + throw new HttpError(503, "shutting_down", "The server is stopping"); + } + log(`[${session.id}] started`); + return session; + }; + + // The control session: a session in the server user's home folder that answers `/api/desktop` (Desktop RPC + // without a session of the client's own) and never takes a model turn. Started on first use, kept while + // requests or event streams use it, stopped after `controlIdleMs` without either. It holds no user state and + // must run this server's code (a restart after `git pull` or an upgrade must not answer with the old one), so + // it ends with its server, unlike the listed sessions: the close stops it, and one a previous server left + // running (a crash, or a server from before this rule) is stopped through its keeper at start, never taken + // back. `/control` names it. It is not listed, not counted against `maxSessions`, and not + // reachable by id. + const controlFile = join(keeperDir, "control"); + let control: ServeSession | undefined; + let controlStarting: Promise | undefined; + let controlInFlight = 0; + let controlIdle: NodeJS.Timeout | undefined; + /** An idle control session on its way out; the server's close waits for it. */ + let controlStopping: Promise | undefined; + + const readControlId = (): string | undefined => { + try { + const id = readFileSync(controlFile, "utf8").trim(); + return /^ses_[A-Za-z0-9]{1,60}$/.test(id) ? id : undefined; + } catch { + return undefined; + } + }; + + /** Forgets the control session's id, unless a newer one took its place. */ + const forgetControlId = (id: string) => { + if (readControlId() === id) rmSync(controlFile, { force: true }); + }; + + const controlHooks = (id: string) => ({ + ...sessionHooks(id), + onExit: (s: ServeSession) => { + log(`[${id}] control session exited (code ${s.exitCode}, signal ${s.exitSignal})`); + if (control === s) control = undefined; + forgetControlId(id); + removeKeeperRecord(keeperDir, id); + }, + }); + + /** A control session a server started (`reattached` false) takes over; one a previous server left is stopped. */ + const adoptControl = (session: ServeSession, reattached: boolean) => { + // A keeper whose session ended while no server ran: its end is collected, and it is forgotten. + if (session.state !== "running") { + forgetControlId(session.id); + removeKeeperRecord(keeperDir, session.id); + return; + } + // It runs the code of the server that started it, maybe not this one's: the next use starts a fresh one. + if (reattached) return retireControl(session, "left by a previous server"); + control = session; + armControlIdle(); + }; + + /** Stops a control session, out of reach at once so no request lands on it meanwhile; its exit forgets it. The server's close waits for it. */ + const retireControl = (session: ServeSession, why: string) => { + if (control === session) control = undefined; + log(`[${session.id}] control session ${why}: stopping`); + const stopping = session.stop().catch(() => undefined); + const before = controlStopping; + controlStopping = before ? Promise.all([before, stopping]).then(() => undefined) : stopping; + }; + + /** Stops the control session after `controlIdleMs` with no request in flight and no open stream. */ + const armControlIdle = () => { + clearTimeout(controlIdle); + controlIdle = undefined; + const session = control; + if (!session || closing || session.subscriberCount > 0 || controlInFlight > 0) return; + controlIdle = setTimeout(() => { + controlIdle = undefined; + if (control !== session || closing || session.subscriberCount > 0 || controlInFlight > 0) return; + retireControl(session, "idle"); + }, limits.controlIdleMs); + controlIdle.unref(); + }; + + /** The running control session, started when there is none. */ + const ensureControl = (): Promise => { + if (control?.state === "running") return Promise.resolve(control); + if (closing) return Promise.reject(new HttpError(503, "shutting_down", "The server is stopping")); + return controlStarting ??= (async () => { + try { + const session = await spawnSession(homedir(), undefined, true); + // The server began stopping meanwhile: its close takes care of the session. + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + log(`[${session.id}] control session started`); + return session; + } finally { + controlStarting = undefined; + } + })(); + }; + + /** Runs `work` with the control session, which stays up (no idle stop) meanwhile. */ + const withControl = async (work: (session: ServeSession) => Promise): Promise => { + controlInFlight += 1; + clearTimeout(controlIdle); + try { + return await work(await ensureControl()); + } finally { + controlInFlight -= 1; + armControlIdle(); + } + }; + + /** At start: every keeper a previous server left is attached again; sessions that ended are listed from their records. */ + const reattach = async () => { + const controlId = readControlId(); + await Promise.all(readKeeperRecords(keeperDir).map(async (record: KeeperRecord) => { + const asControl = record.id === controlId; + // A keeper whose Pi already exited waits a minute for a server to collect the end of its stream. + if (record.state === "running" || keeperAlive(record.keeperPid)) { + try { + const session = await attachSession(record.id, record.token, true, asControl); + if (!asControl) log(`[${record.id}] reattached (seq ${session.seq}, ${session.state})`); + return; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (record.state === "running") { + // A keeper that is there but does not answer is left alone: it stops its session after a day without a server. + if (keeperAlive(record.keeperPid)) return log(`[${record.id}] its keeper (pid ${record.keeperPid}) did not answer: ${message}`); + record = { ...record, state: "exited", exitCode: null, exitSignal: null, exitedAt: now(), error: "keeper_lost" }; + writeKeeperRecord(keeperDir, record); + log(`[${record.id}] lost: its keeper is gone`); + } + } + } + // A control session that ended is forgotten, never listed. + if (asControl) { + forgetControlId(record.id); + removeKeeperRecord(keeperDir, record.id); + return; + } + sessions.set(record.id, new ServeSession({ snapshot: exitedSnapshot(record), ...sessionHooks(record.id) })); + })); + forgetExited(); + }; + const reattached = reattach().catch((error: unknown) => log(`reattaching sessions failed: ${error instanceof Error ? error.message : String(error)}`)); + + /** `after` from the query, or the `Last-Event-ID` header `EventSource` sends on reconnect. */ + const eventsAfter = (req: IncomingMessage, url: URL): number | undefined => { + const raw = url.searchParams.get("after") ?? (typeof req.headers["last-event-id"] === "string" ? req.headers["last-event-id"] : null); + if (raw === null || raw === "") return undefined; + if (!/^\d{1,15}$/.test(raw)) throw new HttpError(400, "invalid_after", "after must be a whole number"); + return Number(raw); + }; + + const openEvents = (req: IncomingMessage, res: ServerResponse, session: ServeSession, principal: Principal, after: number | undefined, filter?: (line: string) => boolean) => { + res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", Connection: "keep-alive", "X-Accel-Buffering": "no", ...SECURITY_HEADERS }); + res.flushHeaders(); + req.socket.setNoDelay(true); + deviceNames.set(principal.deviceId, principal.name); + session.subscribe(res, principal.deviceId, after, filter); + res.on("close", () => session.unsubscribe(res)); + }; + + /** `GET /api/desktop/events`: the control session's Desktop RPC events (and nothing else of its stream), by its `seq`. */ + const openControlEvents = async (req: IncomingMessage, res: ServerResponse, principal: Principal | undefined, url: URL) => { + const ticket = url.searchParams.get("ticket"); + let who: Principal; + if (ticket !== null) { + const holder = options.auth.redeemTicket(ticket, DESKTOP_STREAM); + if (!holder) throw new HttpError(401, "invalid_ticket", "Unknown, used or expired stream ticket"); + who = holder; + } else { + who = need(principal, "sessions:read"); + } + const after = eventsAfter(req, url); + await withControl(async (session) => { + // The client may have gone while the session started. + if (res.destroyed) return; + openEvents(req, res, session, who, after, isDesktopEventRecord); + // The last stream closing starts the idle wait. + res.on("close", armControlIdle); + }); + }; + + const forwardView = (f: ForwardInfo) => ({ + id: f.id, + port: f.port, + listenPort: f.listenPort, + sessionId: f.sessionId, + kind: f.kind, + createdAt: new Date(f.createdAt).toISOString(), + lastUsedAt: new Date(f.lastUsedAt).toISOString(), + }); + + /** A fresh single-use link to the forward, on the host name and scheme the client reached this server with. */ + const forwardLink = (req: IncomingMessage, forward: ForwardInfo, path: string) => { + const minted = forwards.mintTicket(forward.id); + const clientHost = (req.headers.host ?? "127.0.0.1").replace(/:\d+$/, ""); + return { url: forwards.urlFor(forward.id, clientHost, path, minted.ticket, requestScheme(req)), expiresAt: new Date(minted.expiresAt).toISOString() }; + }; + + /** A device sees and closes its own forwards; an admin token sees every one. */ + const ownsForward = (principal: Principal, forward: ForwardInfo) => forward.deviceId === principal.deviceId || hasScope(principal, "admin"); + + /** + * `/api/sessions/:id/forwards[/:fid]` (a session's, closed with it) and + * `/api/forwards[/:fid]` (`sessionId` null: the server's own, until closed, + * revoked, idle or the server stops). The server-level list and DELETE cover + * every forward the device owns. + */ + const forwardRoute = async (req: IncomingMessage, res: ServerResponse, method: string, principal: Principal | undefined, sessionId: string | null, forwardId: string | undefined) => { + const session = sessionId === null ? undefined : findSession(sessionId); + const inScope = (f: ForwardInfo) => session === undefined || f.sessionId === session.id; + if (forwardId !== undefined) { + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use DELETE"); + const who = need(principal, "sessions:operate"); + const forward = forwards.get(forwardId); + if (!forward || !inScope(forward) || !ownsForward(who, forward)) throw new HttpError(404, "not_found", "No such forward"); + forwards.close(forward.id); + return sendJson(res, 200, { closed: forward.id }); + } + if (method === "GET") { + const who = need(principal, "sessions:read"); + return sendJson(res, 200, { forwards: forwards.list().filter((f) => inScope(f) && ownsForward(who, f)).map(forwardView) }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use GET or POST"); + const who = need(principal, "sessions:operate"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const port = body.port; + if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) throw new HttpError(400, "invalid_port", "port must be a whole number 1-65535"); + // This server and the forwards themselves are never targets: a forward to a forward loops. + if (port === mainPort || forwards.listenPorts().includes(port)) throw new HttpError(400, "invalid_port", "That port is the server's own"); + const path = body.path ?? "/"; + if (typeof path !== "string" || path.length > 2048 || !/^\/(?!\/)[\x21-\x7e]*$/.test(path)) throw new HttpError(400, "invalid_path", "path must start with / and hold no spaces or control characters"); + if (session && session.state !== "running") throw new HttpError(409, "session_exited", "The session has ended"); + const opened = await forwards.open({ deviceId: who.deviceId, sessionId: session?.id ?? null, kind: session ? "session" : "server", port }); + return sendJson(res, opened.created ? 201 : 200, { ...forwardView(opened.forward), ...forwardLink(req, opened.forward, path) }); + }; + + /** Local services a client may want to open through a forward: Engram (when it answers) and Gentle Tower (when it runs). */ + const listServices = async () => { + const services: Array> = []; + const env = options.env ?? process.env; + let engram: URL | undefined; + try { engram = new URL(env.ENGRAM_URL || "http://127.0.0.1:7437"); } catch { /* not a URL: not listed */ } + if (engram && (engram.protocol === "http:" || engram.protocol === "https:")) { + // Never the URL's credentials in the answer; fetch refuses them in a URL, so they travel as Basic auth. + const base = `${engram.protocol}//${engram.host}${engram.pathname}`.replace(/\/+$/, ""); + const credentials = engram.username || engram.password ? `${decodeURIComponent(engram.username)}:${decodeURIComponent(engram.password)}` : undefined; + const available = await fetch(`${base}/health`, { + signal: AbortSignal.timeout(1500), + ...(credentials === undefined ? {} : { headers: { Authorization: `Basic ${Buffer.from(credentials).toString("base64")}` } }), + }).then((r) => r.ok, () => false); + const port = Number(engram.port || (engram.protocol === "https:" ? 443 : 80)); + // A forward reaches only this machine's loopback, over plain HTTP. + const forwardable = engram.protocol === "http:" && isLoopbackHost(engram.hostname) && port !== mainPort; + services.push({ id: "engram", name: "Engram", url: base, port, available, forwardable, ...(forwardable ? { via: "forwards" } : {}) }); + } + if (tower) services.push({ id: "tower", name: "Gentle Tower", port: tower.port, available: true, forwardable: true, via: "tower" }); + return services; + }; + + const ensureTower = async (): Promise<{ tower: ServeTower & { startedAt: number }; started: boolean }> => { + if (tower) return { tower, started: false }; + if (!options.startTower) throw new HttpError(501, "not_supported", "This server cannot start Gentle Tower"); + const start = options.startTower; + const pending = towerStarting ??= (async () => ({ ...(await start()), startedAt: now() }))(); + try { + const running = await pending; + const started = tower === undefined; + tower = running; + if (started) log(`tower started on loopback:${running.port}`); + return { tower: running, started }; + } catch (error) { + throw new HttpError(503, "tower_unavailable", error instanceof Error ? error.message : String(error)); + } finally { + towerStarting = undefined; + } + }; + + const stopTower = async (): Promise => { + const running = tower; + if (!running) return false; + tower = undefined; + forwards.closeWhere((f) => f.kind === "tower", "tower stopped"); + await running.close(); + log("tower stopped"); + return true; + }; + + const towerRoute = async (req: IncomingMessage, res: ServerResponse, method: string, principal: Principal | undefined) => { + if (method === "GET") { + need(principal, "sessions:read"); + return sendJson(res, 200, tower ? { running: true, startedAt: new Date(tower.startedAt).toISOString() } : { running: false }); + } + if (method === "DELETE") { + need(principal, "sessions:operate"); + return sendJson(res, 200, { stopped: await stopTower() }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use GET, POST or DELETE"); + // Tower can send messages to sessions and open new ones: operating, not reading. + const who = need(principal, "sessions:operate"); + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + const { tower: running, started } = await ensureTower(); + const opened = await forwards.open({ deviceId: who.deviceId, sessionId: null, kind: "tower", port: running.port }); + return sendJson(res, opened.created ? 201 : 200, { ...forwardView(opened.forward), ...forwardLink(req, opened.forward, running.path), started }); + }; + + const route = async (req: IncomingMessage, res: ServerResponse, url: URL): Promise => { + // Requests wait for the sessions a previous server left to be attached again. + await reattached; + const method = req.method ?? "GET"; + const path = url.pathname; + const principal = options.auth.authenticate(bearer(req)); + if (path.length > 256) throw new HttpError(404, "not_found", "Not found"); + + // Who answers here, without a token and without secrets: a client holding a + // connection code probes each advertised address and pairs only where the id matches. + if (path === SERVE_IDENTITY_PATH) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + return sendJson(res, 200, { schema: SERVE_IDENTITY_SCHEMA, serverId, name: hostname(), protocol: SERVE_PROTOCOL, version: options.version, + tls: options.tls !== undefined, ...(options.tls === undefined ? {} : { fp: options.tls.fingerprint }) }); + } + + // Before a client that found this server through discovery sends its code: one proof per live code that + // binds it to this certificate, which only a server knowing the code can make (docs/serve.md#pairing-proof). + if (path === "/api/pair/proof") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (!proofs) throw new HttpError(501, "not_supported", "This server has no certificate: it serves plain HTTP"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const nonce = typeof body.nonce === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(body.nonce) ? Buffer.from(body.nonce, "base64url") : undefined; + if (!nonce || nonce.length < PAIR_PROOF.nonceMinBytes || nonce.length > PAIR_PROOF.nonceMaxBytes) throw new HttpError(400, "invalid_nonce", `nonce must be ${PAIR_PROOF.nonceMinBytes}-${PAIR_PROOF.nonceMaxBytes} random bytes, base64url`); + if (!proofs.allow()) throw new HttpError(429, "rate_limited", "Too many proof requests; wait a minute"); + return sendJson(res, 200, { proofs: await proofs.proofs(options.auth.livePairingCodes(), nonce) }); + } + + if (path === "/api/pair") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const result = options.auth.redeem(body.code, body.name); + if ("error" in result) { + const status = result.error === "rate_limited" ? 429 : result.error === "too_many_devices" ? 409 : 403; + throw new HttpError(status, result.error, result.error === "invalid_code" ? "Unknown, used or expired pairing code" : result.error === "rate_limited" ? "Too many failed attempts; wait a minute" : "Too many paired devices; revoke one first"); + } + log(`paired device ${result.device.id} (${result.device.scopes.join(",")})`); + return sendJson(res, 201, { ...result.device, token: result.token }); + } + + // Streams opened by EventSource carry a single-use ticket instead of a header. + const events = /^\/api\/sessions\/([A-Za-z0-9_]{1,64})\/events$/.exec(path); + if (events) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + const session = findSessionFor(events[1], principal, url); + return openEvents(req, res, session.session, session.principal, eventsAfter(req, url)); + } + if (path === "/api/desktop/events") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + return openControlEvents(req, res, principal, url); + } + if (path === "/api/desktop") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + return controlDesktop(req, res, principal); + } + + if (path === "/api/server") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + const who = need(principal, "sessions:read"); + return sendJson(res, 200, { schema: SERVE_SCHEMA, protocol: SERVE_PROTOCOL, serverId, version: options.version, startedAt: new Date(startedAt).toISOString(), + capabilities: [...SERVE_CAPABILITIES, ...(uploads ? ["uploads"] : []), ...(terminals?.binary() ? ["terminals"] : []), ...(prints.available ? ["print"] : []), ...(keepSessions ? ["persistent-sessions"] : []), ...(upgrade ? ["upgrade"] : []), ...(upgrade?.canSetup() ? ["setup"] : [])], + device: { id: who.deviceId, name: who.name, scopes: who.scopes }, + // How to build paths for the file and session endpoints. + platform: process.platform, arch: arch(), pathSeparator: sep, + // The server user's home folder, a default for new sessions; only for a token that may start them. + ...(hasScope(who, "sessions:operate") ? { home: homedir() } : {}), + // The certificate devices pin on the network, and the relay registration. + ...(options.tls === undefined ? {} : { tls: { fingerprint: options.tls.fingerprint } }), + ...(relayLink === undefined ? {} : { relay: { url: relayLink.url, connected: relayLink.connected() } }) }); + } + if (path === "/api/server/stop") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const endSessions = body.endSessions === true; + sendJson(res, 202, { stopping: true, endSessions }); + setImmediate(() => options.onStopRequested?.({ endSessions })); + return; + } + if (path === "/api/upgrade") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + if (!upgrade) throw new HttpError(501, "not_supported", "This server cannot upgrade itself"); + const body = await readJsonBody(req, limits.smallBodyBytes); + if (Object.keys(body).some((key) => key !== "channel") || (body.channel !== undefined && !UPGRADE_CHANNELS.includes(body.channel as UpgradeChannel))) { + throw new HttpError(400, "invalid_request", `channel must be ${UPGRADE_CHANNELS.join(" or ")}`); + } + return sendJson(res, 202, upgrade.start(body.channel as UpgradeChannel | undefined)); + } + const upgradeStream = /^\/api\/upgrade\/(upg_[0-9a-f]{16})\/stream$/.exec(path); + if (upgradeStream) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "admin"); + if (!upgrade) throw new HttpError(501, "not_supported", "This server cannot upgrade itself"); + return upgrade.stream(req, res, upgradeStream[1]); + } + if (path === "/api/setup") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + if (!upgrade?.canSetup()) throw new HttpError(501, "not_supported", "This server cannot run setup"); + const body = await readJsonBody(req, limits.smallBodyBytes); + if (Object.keys(body).length > 0) throw new HttpError(400, "invalid_request", "setup takes no options"); + return sendJson(res, 202, upgrade.startSetup()); + } + const setupStream = /^\/api\/setup\/(setup_[0-9a-f]{16})\/stream$/.exec(path); + if (setupStream) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "admin"); + if (!upgrade?.canSetup()) throw new HttpError(501, "not_supported", "This server cannot run setup"); + return upgrade.stream(req, res, setupStream[1]); + } + if (path === "/api/pairing-codes") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + const body = await readJsonBody(req, limits.smallBodyBytes); + let scopes: ServeScope[] | undefined; + if (body.scopes !== undefined) { + if (!Array.isArray(body.scopes) || body.scopes.length === 0 || !body.scopes.every(isServeScope)) throw new HttpError(400, "invalid_scopes", "scopes must be a non-empty list of known scopes"); + scopes = body.scopes; + } + const minted = options.auth.mintPairingCode(scopes); + return sendJson(res, 201, { code: minted.code, scopes: minted.scopes, expiresAt: new Date(minted.expiresAt).toISOString() }); + } + if (path === "/api/devices") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "admin"); + return sendJson(res, 200, { devices: options.auth.listDevices() }); + } + if (path === "/api/devices/self") { + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use DELETE"); + // Any paired device may unpair itself, whatever its scopes; the server's own token is no device. + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + if (principal.deviceId === "local") throw new HttpError(400, "not_a_device", "The server's own token is no paired device"); + if (!options.auth.revoke(principal.deviceId)) throw new HttpError(404, "not_found", "No such device"); + log(`device ${principal.deviceId} unpaired itself`); + return sendJson(res, 200, { revoked: principal.deviceId }); + } + if (path === "/api/devices/self/replace") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + // A device paired again takes the place of its earlier pairing, whose token it shows: that + // device's terminals become this one's, then it is revoked (its streams close). + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + if (principal.deviceId === "local") throw new HttpError(400, "not_a_device", "The server's own token is no paired device"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const earlier = typeof body.token === "string" && body.token.length <= 256 ? options.auth.authenticate(body.token) : undefined; + if (!earlier || earlier.deviceId === "local") throw new HttpError(404, "not_found", "No paired device has that token"); + if (earlier.deviceId === principal.deviceId) throw new HttpError(400, "same_device", "That token is this device's own"); + terminals?.adopt(earlier.deviceId, principal.deviceId); + options.auth.revoke(earlier.deviceId); + log(`device ${principal.deviceId} replaced ${earlier.deviceId}`); + return sendJson(res, 200, { replaced: earlier.deviceId }); + } + const device = /^\/api\/devices\/([A-Za-z0-9_]{1,64})$/.exec(path); + if (device) { + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use DELETE"); + need(principal, "admin"); + if (!options.auth.revoke(device[1])) throw new HttpError(404, "not_found", "No such device"); + log(`revoked device ${device[1]}`); + return sendJson(res, 200, { revoked: device[1] }); + } + if (path === "/api/tickets") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + const who = need(principal, "sessions:read"); + const body = await readJsonBody(req, limits.smallBodyBytes); + // A ticket for one session's events, or for `GET /api/desktop/events` (`{ stream: "desktop" }`). + let target: string; + if (body.stream === "desktop" && body.sessionId === undefined) target = DESKTOP_STREAM; + else if (typeof body.sessionId === "string" && body.stream === undefined) target = findSession(body.sessionId).id; + else throw new HttpError(400, "invalid_request", "sessionId, or stream: \"desktop\", is required"); + const minted = options.auth.mintTicket(who, target); + return sendJson(res, 201, { ticket: minted.ticket, expiresAt: new Date(minted.expiresAt).toISOString() }); + } + if (path === "/api/sessions") { + if (method === "GET") { + const who = need(principal, "sessions:read"); + const listed = [...sessions.values()].map((s) => sessionView(s, who)); + // The control session only for an admin who asks for it. + const shown = url.searchParams.get("includeControl") === "1" && hasScope(who, "admin") ? control : undefined; + return sendJson(res, 200, { sessions: shown ? [...listed, { ...sessionView(shown, who), control: true }] : listed }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use GET or POST"); + const who = need(principal, "sessions:operate"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const cwd = realDirectory(body.cwd); + let sessionId: string | undefined; + if (body.sessionId !== undefined) { + // An id, never a path: Pi resolves it against its own session store. + if (typeof body.sessionId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(body.sessionId)) throw new HttpError(400, "invalid_session_id", "sessionId must be a Pi session id"); + sessionId = body.sessionId; + } + const started = await startSession(cwd, sessionId); + started.noteActivity(who.deviceId); + return sendJson(res, 201, { session: sessionView(started, who) }); + } + if (await files.route(req, res, method, path, url, principal)) return; + if (path === "/api/term-host" || path.startsWith("/api/terminals")) { + if (!terminals) throw new HttpError(501, "term_host_missing", "This server runs no terminals"); + if (await terminals.route(req, res, method, path, url, principal)) return; + } + if (path === "/api/uploads") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (!uploads) throw new HttpError(501, "not_supported", "This server takes no uploads"); + return uploads.upload(req, res, url, principal); + } + if (path === "/api/print") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + return prints.route(req, res, principal); + } + if (path === "/api/git") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + return git.route(req, res, principal); + } + if (path === "/api/tower") return towerRoute(req, res, method, principal); + if (path === "/api/checks") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "sessions:read"); + return sendJson(res, 200, { checks: await checks.checks() }); + } + if (path === "/api/services") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "sessions:read"); + return sendJson(res, 200, { services: await listServices() }); + } + const serverForward = /^\/api\/forwards(?:\/([A-Za-z0-9_]{1,64}))?$/.exec(path); + if (serverForward) return forwardRoute(req, res, method, principal, null, serverForward[1]); + const forward = /^\/api\/sessions\/([A-Za-z0-9_]{1,64})\/forwards(?:\/([A-Za-z0-9_]{1,64}))?$/.exec(path); + if (forward) return forwardRoute(req, res, method, principal, forward[1], forward[2]); + const one = /^\/api\/sessions\/([A-Za-z0-9_]{1,64})(\/rpc|\/desktop)?$/.exec(path); + if (one) { + const session = findSession(one[1]); + if (one[2] === undefined) { + if (method === "GET") return sendJson(res, 200, { session: sessionView(session, need(principal, "sessions:read")) }); + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use GET or DELETE"); + const who = need(principal, "sessions:operate"); + await session.stop(); + sessions.delete(session.id); + removeKeeperRecord(keeperDir, session.id); + return sendJson(res, 200, { session: sessionView(session, who) }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (one[2] === "/rpc") return forwardRpc(req, res, session, principal); + return forwardDesktop(req, res, session, principal); + } + throw new HttpError(404, "not_found", "Not found"); + }; + + const findSessionFor = (id: string, principal: Principal | undefined, url: URL): { session: ServeSession; principal: Principal } => { + const ticket = url.searchParams.get("ticket"); + if (ticket !== null) { + const holder = options.auth.redeemTicket(ticket, id); + if (!holder) throw new HttpError(401, "invalid_ticket", "Unknown, used or expired stream ticket"); + return { session: findSession(id), principal: holder }; + } + const who = need(principal, "sessions:read"); + return { session: findSession(id), principal: who }; + }; + + const forwardRpc = async (req: IncomingMessage, res: ServerResponse, session: ServeSession, principal: Principal | undefined) => { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const command = await readJsonBody(req, limits.rpcBodyBytes); + if (typeof command.type !== "string" || command.type.length > 64) throw new HttpError(400, "invalid_command", "A Pi RPC command needs a type"); + if (command.id !== undefined && (typeof command.id !== "string" || command.id.length > 128)) throw new HttpError(400, "invalid_command", "id must be a string up to 128 characters"); + if (command.type === "extension_ui_response") { + session.noteActivity(need(principal, "sessions:operate").deviceId); + const outcome = await session.answerDialog(command); + if (outcome === "unknown") throw new HttpError(404, "unknown_dialog", "No pending dialog with this id"); + if (outcome === "answered") throw new HttpError(409, "dialog_answered", "Another client already answered this dialog"); + return sendJson(res, 202, { accepted: true }); + } + if (typeof command.message === "string" && carriesHostToolRequest(command.message)) { + throw new HttpError(400, "use_desktop_endpoint", "Host tool requests (set_host_tools, host_tool_result, host_tool_progress, host_message, set_host_context) go through POST /api/sessions/:id/desktop"); + } + const scope = rpcCommandScope(command.type); + need(principal, scope); + if (scope === "sessions:operate") session.noteActivity(principal.deviceId); + const outcome = await session.rpc(command, limits.rpcTimeoutMs); + if ("timeout" in outcome) return sendJson(res, 202, { pending: true, id: outcome.id }); + return sendJson(res, 200, outcome.response); + }; + + /** + * `POST /api/desktop`: a Desktop RPC request answered by the control session, for a client with no + * session of its own (configuration, sign-in, packages). Scopes as `/desktop`; host tool methods are + * refused, since they belong to the agent session whose tools they are. + */ + const controlDesktop = async (req: IncomingMessage, res: ServerResponse, principal: Principal | undefined) => { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const body = await readJsonBody(req, limits.desktopBodyBytes); + if (typeof body.method !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(body.method)) throw new HttpError(400, "invalid_request", "method must be a Desktop RPC method name"); + const params = body.params ?? {}; + if (!params || typeof params !== "object" || Array.isArray(params)) throw new HttpError(400, "invalid_request", "params must be an object"); + if (Object.hasOwn(HOST_TOOL_METHODS, body.method)) throw new HttpError(400, "use_session_desktop", "Host tool methods belong to an agent session: POST /api/sessions/:id/desktop"); + need(principal, desktopMethodScope(body.method)); + const method = body.method; + const outcome = await withControl((session) => session.desktop(method, params as Record, limits.rpcTimeoutMs)); + if (outcome === undefined) throw new HttpError(504, "desktop_timeout", "The control session did not answer the Desktop RPC request in time"); + if ("prompt" in outcome) return sendJson(res, 502, { error: { code: "desktop_refused", message: "The control session refused the Desktop RPC request" }, response: outcome.prompt }); + return sendJson(res, 200, outcome.answer); + }; + + const forwardDesktop = async (req: IncomingMessage, res: ServerResponse, session: ServeSession, principal: Principal | undefined) => { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const body = await readJsonBody(req, Math.max(limits.desktopBodyBytes, limits.hostToolBodyBytes)); + if (typeof body.method !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(body.method)) throw new HttpError(400, "invalid_request", "method must be a Desktop RPC method name"); + // A progress heartbeat is small: only results, tool lists, messages and context get the large body. + const largeBody = Object.hasOwn(HOST_TOOL_METHODS, body.method) && body.method !== "host_tool_progress"; + if (!largeBody && Buffer.byteLength(JSON.stringify(body), "utf8") > limits.desktopBodyBytes) throw new HttpError(413, "too_large", `Body over ${limits.desktopBodyBytes} bytes`); + const params = body.params ?? {}; + if (!params || typeof params !== "object" || Array.isArray(params)) throw new HttpError(400, "invalid_request", "params must be an object"); + if (body.method === "set_host_activity") throw new HttpError(403, "forbidden", "set_host_activity is the server's own: it reports which devices are connected and active"); + const scope = desktopMethodScope(body.method); + need(principal, scope); + // A progress heartbeat is the client's machinery, not the person driving the session: it does not move last-active routing. + if (scope === "sessions:operate" && body.method !== "host_tool_progress") session.noteActivity(principal.deviceId); + let forwarded = params as Record; + if (body.method === "set_host_tools" || body.method === "set_host_context") { + // The provider is always the calling device: a client cannot register tools or context as another device. + forwarded = { ...forwarded, provider: principal.deviceId }; + if (body.method === "set_host_tools") deviceNames.set(principal.deviceId, principal.name); + } + const callId = (body.method === "host_tool_result" || body.method === "host_tool_progress") && typeof forwarded.callId === "string" ? forwarded.callId : undefined; + if (callId !== undefined) { + const owner = session.hostCallProvider(callId); + if (owner !== undefined && owner !== principal.deviceId) throw new HttpError(403, "forbidden", "Only the device that provides this host tool may answer or keep alive its call"); + } + const outcome = await session.desktop(body.method, forwarded, limits.rpcTimeoutMs); + if (outcome === undefined) throw new HttpError(504, "desktop_timeout", "The session did not answer the Desktop RPC request in time"); + if ("prompt" in outcome) return sendJson(res, 502, { error: { code: "desktop_refused", message: "The session refused the Desktop RPC request" }, response: outcome.prompt }); + if (callId !== undefined) { + const error = outcome.answer.error; + const code = error && typeof error === "object" && "code" in error ? error.code : undefined; + if (code === "unknown_call" || code === "already_answered") session.hostCallSettled(callId); + else if (outcome.answer.ok === true) { + if (body.method === "host_tool_progress") session.hostCallProgressed(callId); + else session.hostCallSettled(callId); + } + } + if (body.method === "set_host_tools" && outcome.answer.ok === true) { + const data = outcome.answer.data; + const registered = data && typeof data === "object" && "registered" in data && Array.isArray(data.registered) ? data.registered.length : Array.isArray(forwarded.tools) ? forwarded.tools.length : 0; + session.noteHostProvider(principal.deviceId, registered); + } + return sendJson(res, 200, outcome.answer); + }; + + const handler = (via: ConnectionVia) => (req: IncomingMessage, res: ServerResponse) => { + const host = req.headers.host; + // Through a relay the Host is whatever name the client used for it; no browser can speak the relay's handshake, so rebinding cannot reach here. + if (typeof host !== "string" || (via !== "relay" && !hostOk(host))) return sendError(res, 421, "bad_host", "Unexpected Host header"); + // Bearer tokens, not cookies, so a foreign page cannot ride a session; only this server's own origin is accepted. + const origin = req.headers.origin?.toLowerCase(); + if (origin !== undefined && origin !== `http://${host.toLowerCase()}` && origin !== `https://${host.toLowerCase()}`) return sendError(res, 403, "forbidden_origin", "Origin not allowed"); + let url: URL; + try { + url = new URL(req.url ?? "/", "http://serve.invalid"); + } catch { + return sendError(res, 400, "bad_request", "Bad request"); + } + route(req, res, url).catch((error: unknown) => { + if (error instanceof HttpError) return sendError(res, error.status, error.code, error.message); + if (error instanceof SessionError) return sendError(res, error.code === "session_busy" || error.code === "shutting_down" ? 503 : 409, error.code, error.message); + if (error instanceof ForwardError) return sendError(res, error.status, error.code, error.message); + log(`internal error: ${error instanceof Error ? error.message : String(error)}`); + sendError(res, 500, "internal_error", "Server error"); + }); + }; + + const listener = createServeListener({ + ...(options.tls === undefined ? {} : { tls: options.tls }), + setup: (http: HttpServer, via) => { + http.on("request", handler(via)); + http.headersTimeout = 20_000; + http.requestTimeout = 0; // SSE streams stay open + http.keepAliveTimeout = 5_000; + }, + }); + const server = listener.server; + const heartbeat = setInterval(() => { + for (const s of sessions.values()) s.heartbeat(); + control?.heartbeat(); + files.heartbeat(); + terminals?.heartbeat(); + }, limits.heartbeatMs); + heartbeat.unref(); + + const { promise, resolve, reject } = Promise.withResolvers(); + server.once("error", reject); + server.listen(options.port, options.host.replace(/^\[|\]$/g, ""), async () => { + server.off("error", reject); + const address = server.address(); + const port = typeof address === "object" && address ? address.port : options.port; + hostOk = allowedHosts(options.host, port, options.allowHosts); + mainPort = port; + const localHost = isUnspecified(options.host) ? "127.0.0.1" : options.host.includes(":") && !options.host.startsWith("[") ? `[${options.host}]` : options.host; + // Plain HTTP: this machine may always use it, also when the network gets TLS. + const url = `http://${localHost}:${port}`; + // On the network, also answer LAN discovery on the same port number (UDP); the HTTP server works without it. + let discovery: DiscoveryResponder | undefined; + if (!isLoopbackHost(options.host)) { + try { + discovery = await startDiscoveryResponder({ port, serverId, httpPort: port, name: hostname, log, ...(options.tls === undefined ? {} : { fingerprint: options.tls.fingerprint }) }); + } catch (error) { + log(`discovery off: could not bind UDP 0.0.0.0:${port}: ${error instanceof Error ? error.message : String(error)}`); + } + } + // Outside the network: a registration with the relay; each client it brings is one more TLS connection here (or to a forward's port). + const relay = relayLink = options.relay && options.tls ? startRelayLink({ + url: options.relay.url, + ...(options.relay.secret === undefined ? {} : { secret: options.relay.secret }), + ...(options.relay.retryMinMs === undefined ? {} : { retryMinMs: options.relay.retryMinMs }), + certDer: options.tls.der, + keyPem: options.tls.keyPem, + accept: (target) => (target === undefined || target === port ? (socket) => listener.acceptRelayed(socket) : forwards.relayTarget(target)), + log, + }) : undefined; + await reattached; + resolve({ + serverId, + host: options.host, + port, + url, + startedAt, + discovery: discovery !== undefined, + ...(options.tls === undefined ? {} : { fingerprint: options.tls.fingerprint }), + ...(relay === undefined ? {} : { relay }), + close: async (closeOptions?: { endSessions?: boolean }) => { + closing = true; + clearInterval(heartbeat); + relay?.close(); + await discovery?.close(); + forwards.closeAll(); + files.closeAll(); + git.closeAll(); + prints.closeAll(); + upgrade?.close(); + uploads?.close(); + terminals?.closeAll(); + await towerStarting?.catch(() => undefined); + await stopTower(); + // The control session ends with its server, whatever becomes of the others; one starting now is attached before that. + clearTimeout(controlIdle); + await controlStarting?.catch(() => undefined); + if (control) retireControl(control, "ends with the server"); + // Sessions keep running for the next server unless asked to end, or when no later server could find them. + if (keepSessions && closeOptions?.endSessions !== true) { + for (const s of sessions.values()) s.detach(); + } else { + await Promise.all([...sessions.values()].map((s) => s.stop())); + } + await controlStopping; + if (!keepSessions) removePrivateKeeperDir(keeperDir); + const closed = Promise.withResolvers(); + server.close(() => closed.resolve()); + listener.closeAllConnections(); + await closed.promise; + }, + }); + }); + return promise; +} diff --git a/lib/serve-session-keeper-main.ts b/lib/serve-session-keeper-main.ts new file mode 100644 index 000000000..50cffd141 --- /dev/null +++ b/lib/serve-session-keeper-main.ts @@ -0,0 +1,7 @@ +// The session keeper process `gentle-shell serve` starts for each session +// (lib/serve-session-keeper.ts); run as `node serve-session-keeper-main.mjs` +// with its config on stdin. + +import { runKeeperProcess } from "./serve-session-keeper.ts"; + +await runKeeperProcess(); diff --git a/lib/serve-session-keeper.ts b/lib/serve-session-keeper.ts new file mode 100644 index 000000000..03643fc37 --- /dev/null +++ b/lib/serve-session-keeper.ts @@ -0,0 +1,523 @@ +// The session keeper of `gentle-shell serve`: a small detached Node process per +// session that owns Pi's stdin and stdout, so the session outlives the server. +// It numbers Pi's records (`seq`), keeps the replay ring, the pending dialogs +// and open host tool calls (lib/serve-session.ts `SessionLog`) and listens on +// an owner-only Unix socket `/sessions/.sock` (on Windows the +// named pipe `\\.\pipe\gentle-shell-serve--`) for one server at a +// time, which proves itself with the token in the session's record file. A +// server that starts scans the folder and reattaches every live keeper. +// +// A keeper ends when its Pi exits (its record file stays, marked exited, for the +// server's listing) or when the server stops the session. A keeper no server +// came back to for 24 hours stops its session. + +import { spawn, type ChildProcess } from "node:child_process"; +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, type Server, type Socket } from "node:net"; +import { tmpdir, userInfo } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { isServerRecordType, JsonlDecoder, KEEPER_PROTOCOL, SERVE_SESSION_LIMITS, SessionLog, type ServeSessionLimits, type SessionLaunch, type SessionSnapshot } from "./serve-session.ts"; + +export const SERVE_KEEPER_LIMITS = { + /** A keeper no server is attached to stops its session after this long. */ + orphanMs: 24 * 60 * 60 * 1000, + /** After its Pi exited, how long a keeper with no server attached waits for one to collect the end of the stream. */ + lingerMs: 60_000, + /** How long a connection may take to send its hello. */ + helloMs: 5_000, + /** How long a server waits for a new keeper to report it started. */ + startMs: 10_000, + /** How long a server waits for a keeper's state when it connects. */ + connectMs: 5_000, + /** The most the server may keep with a keeper (`notes`). */ + notesBytes: 64 * 1024, +}; + +export const KEEPER_RECORD_SCHEMA = "gentle-shell.serve.session/v1"; + +/** `/sessions/.json` (`0600`): what a server needs to list a session and reach its keeper. */ +export interface KeeperRecord { + schema: typeof KEEPER_RECORD_SCHEMA; + id: string; + cwd: string; + startedAt: number; + keeperPid: number; + pid: number | null; + /** The secret a server proves itself with when it connects to the keeper. */ + token: string; + state: "running" | "exited"; + exitCode: number | null; + exitSignal: string | null; + exitedAt: number | null; + /** The last seq, once exited. */ + seq: number; + /** `keeper_lost`: the keeper ended without recording its session's exit. */ + error?: string; +} + +/** What a server hands a new keeper (on its stdin, never on the command line: the environment carries secrets). */ +export interface KeeperConfig { + id: string; + /** `/sessions`. */ + dir: string; + token: string; + launch: SessionLaunch; + limits?: Partial; + keeperLimits?: Partial; +} + +/** The keeper process's entry point (the runtime build points at the generated `.mjs`). */ +export const KEEPER_ENTRY = fileURLToPath(new URL("./serve-session-keeper-main.ts", import.meta.url)); + +/** `sun_path` fits 104 bytes on macOS and 108 on Linux; stay below both. */ +const UNIX_SOCKET_PATH_MAX = 96; + +export function keeperEndpoint(dir: string, id: string): string { + if (process.platform !== "win32") { + const direct = join(dir, `${id}.sock`); + if (Buffer.byteLength(direct) <= UNIX_SOCKET_PATH_MAX) return direct; + // A long serve dir (a deep checkout, a macOS temp home) would overflow + // sun_path and `listen` would fail with EINVAL: fall back to a short, + // stable folder under the temp dir, named after the real one. + const short = join(tmpdir(), `gs-keeper-${createHash("sha256").update(dir).digest("hex").slice(0, 12)}`); + mkdirSync(short, { recursive: true, mode: 0o700 }); + return join(short, `${id}.sock`); + } + const user = userInfo().username.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 64) || "user"; + return `\\\\.\\pipe\\gentle-shell-serve-${user}-${id}`; +} + +function recordPath(dir: string, id: string): string { + return join(dir, `${id}.json`); +} + +export function writeKeeperRecord(dir: string, record: KeeperRecord): void { + const path = recordPath(dir, record.id); + const temp = `${path}.${process.pid}.tmp`; + writeFileSync(temp, `${JSON.stringify(record, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } +} + +export function readKeeperRecord(dir: string, id: string): KeeperRecord | undefined { + try { + const record = JSON.parse(readFileSync(recordPath(dir, id), "utf8")) as KeeperRecord; + if (record?.schema !== KEEPER_RECORD_SCHEMA || record.id !== id || typeof record.token !== "string" || typeof record.cwd !== "string") return undefined; + return record; + } catch { + return undefined; + } +} + +/** Every session record in the folder, oldest first. */ +export function readKeeperRecords(dir: string): KeeperRecord[] { + let names: string[]; + try { + names = readdirSync(dir); + } catch { + return []; + } + const records: KeeperRecord[] = []; + for (const name of names) { + const m = /^(ses_[A-Za-z0-9]{1,60})\.json$/.exec(name); + const record = m ? readKeeperRecord(dir, m[1]) : undefined; + if (record) records.push(record); + } + return records.sort((a, b) => a.startedAt - b.startedAt); +} + +/** Forgets a session: its record and (a stale) socket. */ +export function removeKeeperRecord(dir: string, id: string): void { + rmSync(recordPath(dir, id), { force: true }); + if (process.platform !== "win32") rmSync(keeperEndpoint(dir, id), { force: true }); +} + +export function newKeeperToken(): string { + return randomBytes(32).toString("base64url"); +} + +/** For a server without a serve folder: its keepers live (and end) in a private temporary folder. */ +export function privateKeeperDir(): string { + return mkdtempSync(join(tmpdir(), "gentle-serve-")); +} + +export function removePrivateKeeperDir(dir: string): void { + rmSync(dir, { recursive: true, force: true }); +} + +export function keeperAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "EPERM"; + } +} + +/** A session whose keeper ended, as the server lists it: its record, no ring. */ +export function exitedSnapshot(record: KeeperRecord): SessionSnapshot { + return { + protocol: KEEPER_PROTOCOL, + id: record.id, + cwd: record.cwd, + startedAt: record.startedAt, + pid: record.pid, + state: "exited", + exitCode: record.exitCode, + exitSignal: record.exitSignal, + exitedAt: record.exitedAt ?? record.startedAt, + seq: record.seq, + invalidRecords: 0, + droppedRecords: 0, + dialogs: [], + answered: [], + hostCalls: [], + notes: null, + }; +} + +function sameToken(a: string, b: string): boolean { + const x = Buffer.from(a); + const y = Buffer.from(b); + return x.length === y.length && timingSafeEqual(x, y); +} + +/** + * Starts a keeper process for `config` (detached: it outlives this server) and + * waits until it listens, runs Pi and wrote its record. + */ +export async function spawnKeeper(config: KeeperConfig, options: { entry?: string; env?: NodeJS.ProcessEnv } = {}): Promise { + const limits = { ...SERVE_KEEPER_LIMITS, ...config.keeperLimits }; + mkdirSync(config.dir, { recursive: true, mode: 0o700 }); + try { chmodSync(config.dir, 0o700); } catch { /* Windows */ } + const child = spawn(process.execPath, [options.entry ?? KEEPER_ENTRY], { + cwd: config.dir, + detached: true, + stdio: ["pipe", "pipe", "ignore"], + env: options.env ?? process.env, + windowsHide: true, + }); + const { promise, resolve, reject } = Promise.withResolvers(); + const timer = setTimeout(() => reject(new Error("the session keeper did not start in time")), limits.startMs); + const decoder = new JsonlDecoder((line) => { + let answer: { ok?: unknown; error?: unknown }; + try { answer = JSON.parse(line) as { ok?: unknown; error?: unknown }; } catch { return reject(new Error("the session keeper did not start")); } + if (answer.ok === true) resolve(); + else reject(new Error(typeof answer.error === "string" ? answer.error : "the session keeper did not start")); + }, () => reject(new Error("the session keeper did not start")), 64 * 1024); + child.stdout!.on("data", (chunk: Buffer) => decoder.push(chunk)); + child.once("error", (error) => reject(error)); + child.once("exit", (code) => reject(new Error(`the session keeper exited (code ${code})`))); + child.stdin!.on("error", () => { /* it exited: the exit says why */ }); + child.stdin!.end(JSON.stringify(config)); + try { + await promise; + } catch (error) { + child.kill("SIGKILL"); + throw error; + } finally { + clearTimeout(timer); + child.removeAllListeners("exit"); + child.stdout!.destroy(); + child.unref(); + } +} + +export interface SessionKeeperOptions { + now?: () => number; + /** Called once the keeper is done (the process exits there). */ + onDone?: () => void; +} + +/** + * The keeper itself. It runs in its own process (`runKeeperProcess`); tests + * also run it in-process to drive its clock. + */ +export class SessionKeeper { + readonly config: KeeperConfig; + private readonly limits: ServeSessionLimits; + private readonly keeperLimits: typeof SERVE_KEEPER_LIMITS; + private readonly now: () => number; + private readonly onDone: () => void; + private readonly log: SessionLog; + private readonly endpoint: string; + private readonly server: Server; + private child?: ChildProcess; + private startedAt = 0; + /** The attached server's connection. */ + private serve?: Socket; + private notes: unknown = null; + private orphanTimer?: NodeJS.Timeout; + private lingerTimer?: NodeJS.Timeout; + private killTimer?: NodeJS.Timeout; + private done = false; + + constructor(config: KeeperConfig, options: SessionKeeperOptions = {}) { + this.config = config; + this.limits = { ...SERVE_SESSION_LIMITS, ...config.limits }; + this.keeperLimits = { ...SERVE_KEEPER_LIMITS, ...config.keeperLimits }; + this.now = options.now ?? Date.now; + this.onDone = options.onDone ?? (() => {}); + this.log = new SessionLog(this.limits, this.now); + this.endpoint = keeperEndpoint(config.dir, config.id); + this.server = createServer((socket) => this.onConnection(socket)); + } + + /** Listens, starts Pi and writes the session's record. */ + async start(): Promise { + mkdirSync(this.config.dir, { recursive: true, mode: 0o700 }); + if (process.platform !== "win32") rmSync(this.endpoint, { force: true }); + const listening = Promise.withResolvers(); + this.server.once("error", listening.reject); + this.server.listen(this.endpoint, () => listening.resolve()); + await listening.promise; + if (process.platform !== "win32") chmodSync(this.endpoint, 0o600); + this.startedAt = this.now(); + this.spawnPi(); + this.writeRecord(); + this.armOrphan(); + } + + private spawnPi(): void { + const { launch } = this.config; + const decoder = new JsonlDecoder((line) => this.onPiLine(line), () => { + this.emit({ type: "serve_record_dropped", reason: "too_large", maxBytes: this.limits.maxLineBytes }); + }, this.limits.maxLineBytes); + // stdin stays open for Pi's whole life: closing it asks Pi to shut down. + const child = spawn(launch.command, launch.args, { cwd: launch.cwd, env: launch.env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); + this.child = child; + child.stdout!.on("data", (chunk: Buffer) => decoder.push(chunk)); + child.stdout!.on("end", () => decoder.end()); + child.stderr!.on("data", (chunk: Buffer) => this.send(JSON.stringify({ t: "stderr", text: chunk.toString("utf8") }))); + // Pi exiting while we write must not end the keeper. + child.stdin!.on("error", () => {}); + let exited = false; + const finish = (code: number | null, signal: string | null, error?: string) => { + if (exited) return; + exited = true; + this.onPiExit(code, signal, error); + }; + child.once("error", (error) => finish(null, null, error.message)); + // `close` waits for stdout to drain, so every record lands before the exit record. + child.once("close", (code, signal) => finish(code, signal)); + } + + private writeRecord(): void { + const log = this.log; + writeKeeperRecord(this.config.dir, { + schema: KEEPER_RECORD_SCHEMA, + id: this.config.id, + cwd: this.config.launch.cwd, + startedAt: this.startedAt, + keeperPid: process.pid, + pid: this.child?.pid ?? null, + token: this.config.token, + state: log.state, + exitCode: log.exitCode, + exitSignal: log.exitSignal, + exitedAt: log.exitedAt ?? null, + seq: log.seq, + }); + } + + // --- Pi's output --- + + private onPiLine(line: string): void { + let record: unknown; + try { + record = JSON.parse(line); + } catch { + record = undefined; + } + // stdout is reserved for protocol records, and `serve_*` records are the server side's own. + if (!record || typeof record !== "object" || Array.isArray(record) || isServerRecordType((record as Record).type)) { + this.log.invalidRecords += 1; + this.send('{"t":"invalid"}'); + return; + } + this.append(line, record as Record); + } + + private append(line: string, record: Record): void { + const seq = this.log.seq + 1; + this.log.push(seq, line, record); + this.send(`${seq} ${line}`); + } + + /** Records the keeper adds to the stream itself; they share the session's `seq`. */ + private emit(record: Record): void { + this.append(JSON.stringify(record), record); + } + + private send(line: string): void { + this.serve?.write(`${line}\n`); + } + + // --- the server --- + + private onConnection(socket: Socket): void { + socket.setNoDelay(true); + let authenticated = false; + const hello = setTimeout(() => { if (!authenticated) socket.destroy(); }, this.keeperLimits.helloMs); + hello.unref?.(); + const decoder = new JsonlDecoder((line) => { + if (authenticated) return this.onServeLine(socket, line); + let message: Record | undefined; + try { message = JSON.parse(line) as Record; } catch { /* refused below */ } + if (message?.op !== "hello" || typeof message.token !== "string" || !sameToken(message.token, this.config.token)) return socket.destroy(); + authenticated = true; + clearTimeout(hello); + this.attach(socket); + }, () => socket.destroy(), this.limits.maxLineBytes + 64); + socket.on("data", (chunk: Buffer) => decoder.push(chunk)); + socket.on("error", () => { /* close follows */ }); + socket.on("close", () => { + clearTimeout(hello); + if (this.serve !== socket) return; + this.serve = undefined; + this.armOrphan(); + }); + } + + /** A server proved itself: it replaces any earlier one and gets the whole state, then the live stream. */ + private attach(socket: Socket): void { + const previous = this.serve; + this.serve = socket; + previous?.destroy(); + clearTimeout(this.orphanTimer); + this.orphanTimer = undefined; + const snapshot: SessionSnapshot & { t: "snapshot" } = { + t: "snapshot", + protocol: KEEPER_PROTOCOL, + id: this.config.id, + cwd: this.config.launch.cwd, + startedAt: this.startedAt, + pid: this.child?.pid ?? null, + ...this.log.snapshot(), + notes: this.notes, + }; + socket.write(`${JSON.stringify(snapshot)}\n`); + for (const record of this.log.ring.all()) socket.write(`${record.seq} ${record.line}\n`); + socket.write('{"t":"live"}\n'); + // Pi is gone and this server now has the end of the stream: the keeper's work is done. + if (this.log.state === "exited") this.finishAfter(socket); + } + + private onServeLine(socket: Socket, line: string): void { + if (line.startsWith(">")) return this.toPi(socket, line.slice(1)); + let op: Record; + try { op = JSON.parse(line) as Record; } catch { return; } + switch (op.op) { + case "answer": { + const answer = op.answer && typeof op.answer === "object" ? op.answer as Record : {}; + const id = typeof answer.id === "string" ? answer.id : ""; + const status = this.log.dialogStatus(id); + if (status === "pending") { + this.toPi(socket, JSON.stringify(answer)); + this.emit({ type: "serve_dialog_resolved", id }); + } + return this.send(JSON.stringify({ t: "reply", rid: op.rid, outcome: status === "pending" ? "accepted" : status })); + } + case "settled": + if (typeof op.callId === "string") this.log.settle(op.callId); + return; + case "progressed": + if (typeof op.callId === "string") this.log.progress(op.callId); + return; + case "notes": + if (Buffer.byteLength(JSON.stringify(op.notes ?? null)) <= this.keeperLimits.notesBytes) this.notes = op.notes ?? null; + return; + case "stop": + return this.stop(); + } + } + + /** One line for Pi's stdin; a Pi that stops reading holds back the server, which then refuses commands. */ + private toPi(socket: Socket, line: string): void { + const stdin = this.child?.stdin; + if (this.log.state !== "running" || !stdin?.writable) return; + stdin.write(`${line}\n`); + if (stdin.writableLength > this.limits.stdinBufferBytes && !socket.isPaused()) { + socket.pause(); + stdin.once("drain", () => socket.resume()); + } + } + + private armOrphan(): void { + if (this.serve || this.log.state !== "running" || this.orphanTimer) return; + this.orphanTimer = setTimeout(() => { + this.orphanTimer = undefined; + if (!this.serve) this.stop(); + }, this.keeperLimits.orphanMs); + this.orphanTimer.unref?.(); + } + + // --- the end --- + + /** Orderly stop: close Pi's stdin and send SIGTERM together (Pi treats them as one request), then SIGKILL. */ + stop(): void { + const child = this.child; + if (this.log.state !== "running" || !child || this.killTimer) return; + child.stdin!.end(); + child.kill("SIGTERM"); + this.killTimer = setTimeout(() => { if (this.log.state === "running") child.kill("SIGKILL"); }, this.limits.stopGraceMs); + this.killTimer.unref?.(); + } + + private onPiExit(code: number | null, signal: string | null, error?: string): void { + clearTimeout(this.killTimer); + clearTimeout(this.orphanTimer); + // The record says exited before the server can hear it: a server that forgets the session removes it for good. + const record = { type: "serve_session_exited", code, signal, ...(error ? { error: "spawn_failed" } : {}) }; + const line = JSON.stringify(record); + const seq = this.log.seq + 1; + this.log.push(seq, line, record); + this.writeRecord(); + this.send(`${seq} ${line}`); + if (this.serve) return this.finishAfter(this.serve); + this.lingerTimer = setTimeout(() => this.finish(), this.keeperLimits.lingerMs); + this.lingerTimer.unref?.(); + } + + /** Ends once everything written to the attached server has gone out. */ + private finishAfter(socket: Socket): void { + clearTimeout(this.lingerTimer); + socket.end(() => this.finish()); + socket.once("close", () => this.finish()); + } + + private finish(): void { + if (this.done) return; + this.done = true; + clearTimeout(this.lingerTimer); + clearTimeout(this.orphanTimer); + this.server.close(); + if (process.platform !== "win32") rmSync(this.endpoint, { force: true }); + this.onDone(); + } +} + +/** The keeper process: its config arrives on stdin; it answers `{ ok }` on stdout once it runs. */ +export async function runKeeperProcess(): Promise { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) chunks.push(chunk as Buffer); + const report = (answer: Record) => process.stdout.write(`${JSON.stringify(answer)}\n`); + let keeper: SessionKeeper; + try { + const config = JSON.parse(Buffer.concat(chunks).toString("utf8")) as KeeperConfig; + keeper = new SessionKeeper(config, { onDone: () => process.exit(0) }); + await keeper.start(); + } catch (error) { + report({ ok: false, error: error instanceof Error ? error.message : String(error) }); + process.exitCode = 1; + return; + } + // Detached from any terminal; only an explicit SIGTERM (a shutdown) stops the session. + process.on("SIGHUP", () => {}); + process.on("SIGINT", () => {}); + process.on("SIGTERM", () => keeper.stop()); + report({ ok: true, pid: process.pid }); +} diff --git a/lib/serve-session.ts b/lib/serve-session.ts new file mode 100644 index 000000000..0205f1785 --- /dev/null +++ b/lib/serve-session.ts @@ -0,0 +1,1197 @@ +// One server-owned agent session for `gentle-shell serve`. Pi runs under a +// detached session keeper (lib/serve-session-keeper.ts) that owns its stdin and +// stdout, numbers its JSONL output with a monotonic `seq` and keeps the replay +// ring, the dialogs still waiting for an answer and the host tool calls still +// open, so a session outlives a server restart. The server holds a mirror of +// that state, fed by the keeper over a Unix socket (a named pipe on Windows), +// plus what only it knows: the SSE subscribers, the requests waiting for an +// answer and which device runs host tools. A slow subscriber is dropped (it +// resyncs) instead of ever slowing the session. + +import { randomBytes } from "node:crypto"; +import { connect, type Socket } from "node:net"; + +export interface ServeSessionLimits { + /** A single stdout record larger than this is dropped (a marker record takes its place). */ + maxLineBytes: number; + /** Replay ring bounds: whichever is reached first evicts the oldest records. */ + ringRecords: number; + ringBytes: number; + /** Unsent bytes one subscriber may hold before it is dropped with a resync marker. */ + clientBufferBytes: number; + /** Bytes waiting on the session's input before new commands are refused. */ + stdinBufferBytes: number; + /** How long a stop waits after closing stdin and SIGTERM before SIGKILL. */ + stopGraceMs: number; + /** How long a dropped subscriber's final marker may take to flush. */ + dropFlushMs: number; + /** How long a host tool call waits for its device to reopen a stream after the device's last one closed. */ + hostToolGraceMs: number; + /** After the server reattached a session: how long its open host tool calls wait for their devices to reconnect. */ + hostToolReattachGraceMs: number; + /** How long the server remembers a host tool call it saw (the session itself gives up after 10 minutes). */ + hostToolTrackMs: number; + /** How long the server's own "not connected" answer may take to reach the session. */ + hostToolAnswerMs: number; +} + +export const SERVE_SESSION_LIMITS: ServeSessionLimits = { + maxLineBytes: 16 * 1024 * 1024, + ringRecords: 2000, + ringBytes: 8 * 1024 * 1024, + clientBufferBytes: 4 * 1024 * 1024, + stdinBufferBytes: 16 * 1024 * 1024, + stopGraceMs: 5000, + dropFlushMs: 5000, + hostToolGraceMs: 10_000, + hostToolReattachGraceMs: 30_000, + hostToolTrackMs: 11 * 60 * 1000, + hostToolAnswerMs: 30_000, +}; + +/** Pi RPC dialog methods: they block until one `extension_ui_response` answers them. */ +export const DIALOG_METHODS: Readonly> = { select: true, confirm: true, input: true, editor: true }; +export const DESKTOP_RPC_SCHEMA = "gentle-shell.desktop-rpc/v1"; +export const DESKTOP_RPC_WIDGET = "gentle-desktop-rpc"; +/** Desktop RPC methods that only a client's own `/desktop` request may carry (see lib/desktop-rpc-host-tools.ts). */ +export const HOST_TOOL_METHODS: Readonly> = { set_host_tools: true, host_tool_result: true, host_tool_progress: true, host_message: true, set_host_context: true, set_host_activity: true }; +/** The keeper protocol both ends speak; a keeper answering another one is not attached. */ +export const KEEPER_PROTOCOL = 1; + +// --- JSONL framing ------------------------------------------------------------- + +/** + * Splits a byte stream into records on LF only (an optional CR before it is + * stripped). Unlike `readline`, U+2028/U+2029 inside JSON strings never split a + * record. LF never occurs inside a multi-byte UTF-8 sequence, so decoding each + * complete record on its own is exact. + */ +export class JsonlDecoder { + private parts: Buffer[] = []; + private size = 0; + private discarding = false; + private readonly onLine: (line: string) => void; + private readonly onOversize: () => void; + private readonly maxLineBytes: number; + + constructor(onLine: (line: string) => void, onOversize: () => void, maxLineBytes: number = SERVE_SESSION_LIMITS.maxLineBytes) { + this.onLine = onLine; + this.onOversize = onOversize; + this.maxLineBytes = maxLineBytes; + } + + push(chunk: Buffer): void { + let start = 0; + while (start < chunk.length) { + const lf = chunk.indexOf(0x0a, start); + const end = lf === -1 ? chunk.length : lf; + if (!this.discarding) { + const piece = chunk.subarray(start, end); + if (this.size + piece.length > this.maxLineBytes) { + this.parts = []; + this.size = 0; + this.discarding = true; + } else if (piece.length > 0) { + this.parts.push(piece); + this.size += piece.length; + } + } + if (lf === -1) break; + this.finishRecord(); + start = lf + 1; + } + } + + /** Called when the stream ends: a last record without LF still counts. */ + end(): void { + if (this.size > 0 || this.discarding) this.finishRecord(); + } + + private finishRecord(): void { + if (this.discarding) { + this.discarding = false; + this.onOversize(); + return; + } + let bytes = this.parts.length === 1 ? this.parts[0] : Buffer.concat(this.parts, this.size); + this.parts = []; + this.size = 0; + if (bytes.length > 0 && bytes[bytes.length - 1] === 0x0d) bytes = bytes.subarray(0, bytes.length - 1); + if (bytes.length > 0) this.onLine(bytes.toString("utf8")); + } +} + +// --- replay ring --------------------------------------------------------------- + +export interface RingRecord { + seq: number; + line: string; + bytes: number; +} + +export type ReplayResult = { records: RingRecord[] } | { snapshotRequired: true; oldest: number }; + +/** Bounded by count and bytes; the newest record is always kept. */ +export class ReplayRing { + private records: RingRecord[] = []; + private head = 0; + private bytes = 0; + private readonly maxRecords: number; + private readonly maxBytes: number; + + constructor(maxRecords: number, maxBytes: number) { + this.maxRecords = Math.max(1, maxRecords); + this.maxBytes = maxBytes; + } + + get length(): number { + return this.records.length - this.head; + } + + /** Oldest seq still held, or undefined when empty. */ + get oldest(): number | undefined { + return this.length === 0 ? undefined : this.records[this.head].seq; + } + + push(record: RingRecord): void { + this.records.push(record); + this.bytes += record.bytes; + while (this.length > 1 && (this.length > this.maxRecords || this.bytes > this.maxBytes)) { + this.bytes -= this.records[this.head].bytes; + this.head += 1; + } + // Compact lazily so eviction stays O(1) amortized. + if (this.head > 1024 && this.head * 2 > this.records.length) { + this.records = this.records.slice(this.head); + this.head = 0; + } + } + + /** Every record held, oldest first. */ + all(): RingRecord[] { + return this.records.slice(this.head); + } + + /** + * Records after `after`, or `snapshotRequired` when the client's cursor is + * older than the ring (something it never saw was evicted) or newer than + * the stream (it belongs to another session lifetime). + */ + since(after: number, current: number): ReplayResult { + const oldest = this.oldest ?? current + 1; + if (!Number.isSafeInteger(after) || after < 0 || after > current || after < oldest - 1) return { snapshotRequired: true, oldest }; + const out: RingRecord[] = []; + for (let i = this.head; i < this.records.length; i += 1) if (this.records[i].seq > after) out.push(this.records[i]); + return { records: out }; + } +} + +// --- subscribers --------------------------------------------------------------- + +/** The part of an HTTP response an SSE subscriber needs (a fake in tests). */ +export interface StreamSink { + write(chunk: string): boolean; + end(chunk?: string): void; + destroy(): void; + readonly writableLength: number; + readonly destroyed?: boolean; +} + +export interface Subscriber { + sink: StreamSink; + /** The device that opened the stream; revoking it closes the stream. */ + deviceId: string; + /** Only the records it keeps reach this stream (the Desktop events of `GET /api/desktop/events`); every record without one. */ + filter?: (line: string) => boolean; +} + +export function sseRecord(seq: number, line: string): string { + return `id: ${seq}\ndata: ${line}\n\n`; +} + +export function sseEvent(event: string, data: unknown): string { + return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; +} + +// --- the session's record state ------------------------------------------------ + +export interface SessionLaunch { + command: string; + args: string[]; + cwd: string; + env: NodeJS.ProcessEnv; +} + +export type SessionState = "running" | "exited"; + +export interface PendingDialog { + id: string; + seq: number; + line: string; + expiresAt?: number; +} + +/** A `host_tool_call` the session emitted that no `host_tool_result` or `host_tool_cancel` settled yet. */ +export interface PendingHostCall { + callId: string; + /** In serve, always the id of the device that registered the tool. */ + provider: string; + tool: string; + seq: number; + line: string; + /** When the call was emitted, or last kept alive by a `host_tool_progress`. */ + at: number; +} + +/** What a record means to the session's state and to the requests waiting on it. */ +export type RecordEvent = + | { kind: "response"; id: string } + | { kind: "dialog"; id: string; timeout?: number } + | { kind: "dialog_resolved"; id: string } + | { kind: "desktop_response"; requestId: string; answer: Record } + | { kind: "host_tool_call"; callId: string; provider: string; tool: string } + | { kind: "host_tool_cancel"; callId: string } + | { kind: "dropped" } + | { kind: "exited"; code: number | null; signal: string | null } + | undefined; + +/** Records the server side adds to a stream; a session child may not print them. */ +export function isServerRecordType(type: unknown): boolean { + return typeof type === "string" && type.startsWith("serve_"); +} + +export function classifyRecord(record: Record): RecordEvent { + switch (record.type) { + case "response": + return typeof record.id === "string" ? { kind: "response", id: record.id } : undefined; + case "serve_dialog_resolved": + return typeof record.id === "string" ? { kind: "dialog_resolved", id: record.id } : undefined; + case "serve_record_dropped": + return { kind: "dropped" }; + case "serve_session_exited": + return { kind: "exited", code: typeof record.code === "number" ? record.code : null, signal: typeof record.signal === "string" ? record.signal : null }; + case "extension_ui_request": + break; + default: + return undefined; + } + if (typeof record.id !== "string") return undefined; + const method = record.method; + if (typeof method === "string" && Object.hasOwn(DIALOG_METHODS, method)) { + return { kind: "dialog", id: record.id, ...(typeof record.timeout === "number" && record.timeout > 0 ? { timeout: record.timeout } : {}) }; + } + if (method !== "setWidget" || record.widgetKey !== DESKTOP_RPC_WIDGET || !Array.isArray(record.widgetLines) || typeof record.widgetLines[0] !== "string") return undefined; + let answer: unknown; + try { + answer = JSON.parse(record.widgetLines[0]); + } catch { + return undefined; + } + if (!answer || typeof answer !== "object") return undefined; + const a = answer as Record; + if (a.kind === "response") return typeof a.requestId === "string" ? { kind: "desktop_response", requestId: a.requestId, answer: a } : undefined; + if (a.kind !== "event") return undefined; + const data = a.data; + if (!data || typeof data !== "object" || !("callId" in data) || typeof data.callId !== "string") return undefined; + if (a.event === "host_tool_cancel") return { kind: "host_tool_cancel", callId: data.callId }; + if (a.event !== "host_tool_call" || !("provider" in data) || typeof data.provider !== "string" || !("tool" in data) || typeof data.tool !== "string") return undefined; + return { kind: "host_tool_call", callId: data.callId, provider: data.provider, tool: data.tool }; +} + +/** Whether `line` is a Desktop RPC event record (a `gentle-desktop-rpc` widget whose payload is `kind: "event"`), the only records `GET /api/desktop/events` carries. */ +export function isDesktopEventRecord(line: string): boolean { + let record: unknown; + try { + record = JSON.parse(line); + } catch { + return false; + } + if (!record || typeof record !== "object") return false; + const r = record as Record; + if (r.type !== "extension_ui_request" || r.method !== "setWidget" || r.widgetKey !== DESKTOP_RPC_WIDGET || !Array.isArray(r.widgetLines) || typeof r.widgetLines[0] !== "string") return false; + try { + const payload = JSON.parse(r.widgetLines[0]) as unknown; + return !!payload && typeof payload === "object" && (payload as Record).kind === "event"; + } catch { + return false; + } +} + +/** The state a keeper hands the server when it attaches; the ring's records follow it on the wire. */ +export interface SessionSnapshot { + protocol: number; + id: string; + cwd: string; + startedAt: number; + pid: number | null; + state: SessionState; + exitCode: number | null; + exitSignal: string | null; + exitedAt: number | null; + seq: number; + invalidRecords: number; + droppedRecords: number; + dialogs: PendingDialog[]; + answered: string[]; + hostCalls: PendingHostCall[]; + /** What the server keeps with the keeper so a restarted server knows it (host tool providers, activity). */ + notes: unknown; +} + +const ANSWERED_MEMORY = 256; + +/** + * The session's stream and what it implies: `seq`, the replay ring, pending + * dialogs (with the ids answered lately) and open host tool calls, and whether + * it exited. The keeper holds the authoritative one; the server a mirror fed + * with the same records, so both always agree. + */ +export class SessionLog { + seq = 0; + state: SessionState = "running"; + exitCode: number | null = null; + exitSignal: string | null = null; + exitedAt?: number; + invalidRecords = 0; + droppedRecords = 0; + readonly ring: ReplayRing; + private readonly dialogs = new Map(); + private readonly answered: string[] = []; + private readonly hostCalls = new Map(); + private readonly limits: Pick; + private readonly now: () => number; + + constructor(limits: Pick, now: () => number) { + this.limits = limits; + this.now = now; + this.ring = new ReplayRing(limits.ringRecords, limits.ringBytes); + } + + /** Takes `record` (the parsed `line`) as record `seq` and applies what it means. */ + push(seq: number, line: string, record: Record): RecordEvent { + this.seq = seq; + this.ring.push({ seq, line, bytes: Buffer.byteLength(line) }); + const event = classifyRecord(record); + switch (event?.kind) { + case "dialog": + if (this.state === "running") this.dialogs.set(event.id, { id: event.id, seq, line, ...(event.timeout === undefined ? {} : { expiresAt: this.now() + event.timeout }) }); + break; + case "dialog_resolved": + this.dialogs.delete(event.id); + this.answered.push(event.id); + if (this.answered.length > ANSWERED_MEMORY) this.answered.shift(); + break; + case "host_tool_call": { + const now = this.now(); + for (const [id, call] of this.hostCalls) if (now - call.at > this.limits.hostToolTrackMs) this.hostCalls.delete(id); + if (this.state === "running") this.hostCalls.set(event.callId, { callId: event.callId, provider: event.provider, tool: event.tool, seq, line, at: now }); + break; + } + case "host_tool_cancel": + this.hostCalls.delete(event.callId); + break; + case "dropped": + this.droppedRecords += 1; + break; + case "exited": + this.state = "exited"; + this.exitCode = event.code; + this.exitSignal = event.signal; + this.exitedAt = this.now(); + this.dialogs.clear(); + this.hostCalls.clear(); + break; + } + return event; + } + + pendingDialogs(): PendingDialog[] { + const now = this.now(); + for (const [id, dialog] of this.dialogs) if (dialog.expiresAt !== undefined && dialog.expiresAt <= now) this.dialogs.delete(id); + return [...this.dialogs.values()]; + } + + dialogStatus(id: string): "pending" | "answered" | "unknown" { + if (this.pendingDialogs().some((dialog) => dialog.id === id)) return "pending"; + return this.answered.includes(id) ? "answered" : "unknown"; + } + + hostCall(callId: string): PendingHostCall | undefined { + return this.hostCalls.get(callId); + } + + pendingHostCalls(): PendingHostCall[] { + return [...this.hostCalls.values()]; + } + + settle(callId: string): void { + this.hostCalls.delete(callId); + } + + /** A `host_tool_progress` kept the call alive: tracking it starts over. */ + progress(callId: string): void { + const call = this.hostCalls.get(callId); + if (call) call.at = this.now(); + } + + snapshot(): Pick { + return { + state: this.state, + exitCode: this.exitCode, + exitSignal: this.exitSignal, + exitedAt: this.exitedAt ?? null, + seq: this.seq, + invalidRecords: this.invalidRecords, + droppedRecords: this.droppedRecords, + dialogs: this.pendingDialogs(), + answered: [...this.answered], + hostCalls: this.pendingHostCalls(), + }; + } + + /** Takes over a keeper's state (its ring records are pushed into `ring` as they arrive). */ + restore(snapshot: SessionSnapshot): void { + this.seq = snapshot.seq; + this.state = snapshot.state; + this.exitCode = snapshot.exitCode; + this.exitSignal = snapshot.exitSignal; + if (snapshot.exitedAt !== null) this.exitedAt = snapshot.exitedAt; + this.invalidRecords = snapshot.invalidRecords; + this.droppedRecords = snapshot.droppedRecords; + for (const dialog of snapshot.dialogs) this.dialogs.set(dialog.id, dialog); + this.answered.push(...snapshot.answered.slice(-ANSWERED_MEMORY)); + for (const call of snapshot.hostCalls) this.hostCalls.set(call.callId, call); + } +} + +// --- the link to a keeper -------------------------------------------------------- + +/** + * Wire format, both ways one record per LF-terminated line. Keeper → server: + * ` ` for each stream record, or a JSON control object + * (`{"t":"snapshot",…}` then the ring as records then `{"t":"live"}` when the + * server attaches; `{"t":"invalid"}`, `{"t":"stderr","text"}`, + * `{"t":"reply","rid","outcome"}`). Server → keeper: `{"op":"hello","token","protocol"}` + * first, then `>` followed by one Pi RPC command for the session's stdin, or a + * JSON op (`answer`, `settled`, `progressed`, `notes`, `stop`). + */ +interface LinkHandlers { + record: (seq: number, line: string) => void; + message: (message: Record) => void; + close: () => void; +} + +export class KeeperLink { + private readonly socket: Socket; + private handlers?: LinkHandlers; + private readonly early: Array<() => void> = []; + private readonly replies = new Map void; reject: (error: Error) => void }>(); + private nextRid = 0; + closed = false; + + private constructor(socket: Socket) { + this.socket = socket; + } + + /** Connects to a keeper and receives its state: the snapshot and the ring, then the link is live. */ + static connect(endpoint: string, token: string, options: { timeoutMs: number; maxLineBytes: number }): Promise<{ link: KeeperLink; snapshot: SessionSnapshot; ring: RingRecord[] }> { + const { promise, resolve, reject } = Promise.withResolvers<{ link: KeeperLink; snapshot: SessionSnapshot; ring: RingRecord[] }>(); + const socket = connect(endpoint); + const link = new KeeperLink(socket); + let snapshot: SessionSnapshot | undefined; + const ring: RingRecord[] = []; + let live = false; + const fail = (message: string) => { + if (live) return; + live = true; + clearTimeout(timer); + socket.destroy(); + reject(Object.assign(new Error(message), { code: "keeper_unavailable" })); + }; + const timer = setTimeout(() => fail("the session keeper did not answer"), options.timeoutMs); + const decoder = new JsonlDecoder((line) => { + if (live) return link.receive(line); + if (line.startsWith("{")) { + let message: Record; + try { message = JSON.parse(line) as Record; } catch { return fail("the session keeper sent a malformed line"); } + if (message.t === "snapshot") { + if (message.protocol !== KEEPER_PROTOCOL) return fail(`the session keeper speaks protocol ${String(message.protocol)}`); + snapshot = message as unknown as SessionSnapshot; + return; + } + if (message.t !== "live" || !snapshot) return fail("the session keeper sent an unexpected line"); + live = true; + clearTimeout(timer); + return resolve({ link, snapshot, ring }); + } + const record = parseRecordLine(line); + if (!record || !snapshot) return fail("the session keeper sent a malformed line"); + ring.push({ ...record, bytes: Buffer.byteLength(record.line) }); + }, () => fail("the session keeper sent an oversize line"), options.maxLineBytes + 64); + socket.setNoDelay(true); + socket.on("connect", () => socket.write(`${JSON.stringify({ op: "hello", token, protocol: KEEPER_PROTOCOL })}\n`)); + socket.on("data", (chunk: Buffer) => decoder.push(chunk)); + socket.on("error", (error) => fail(error.message)); + socket.on("close", () => { + fail("the session keeper closed the connection"); + link.onClose(); + }); + return promise; + } + + /** Starts delivering what arrived since the handshake, then everything live. */ + attach(handlers: LinkHandlers): void { + this.handlers = handlers; + for (const deliver of this.early.splice(0)) deliver(); + } + + private dispatch(deliver: () => void): void { + if (this.handlers) deliver(); + else this.early.push(deliver); + } + + private receive(line: string): void { + if (!line.startsWith("{")) { + const record = parseRecordLine(line); + if (record) this.dispatch(() => this.handlers!.record(record.seq, record.line)); + return; + } + let message: Record; + try { message = JSON.parse(line) as Record; } catch { return; } + if (message.t === "reply" && typeof message.rid === "number") { + const reply = this.replies.get(message.rid); + this.replies.delete(message.rid); + reply?.resolve(message.outcome); + return; + } + this.dispatch(() => this.handlers!.message(message)); + } + + private onClose(): void { + this.closed = true; + const gone = new SessionError("session_exited", "The session has exited"); + for (const reply of this.replies.values()) reply.reject(gone); + this.replies.clear(); + this.dispatch(() => this.handlers!.close()); + } + + get writableLength(): number { + return this.socket.writableLength; + } + + /** One line to the keeper (a `>` stdin line or a JSON op). */ + send(line: string): void { + if (!this.closed) this.socket.write(`${line}\n`); + } + + /** A JSON op the keeper answers with a `reply`. */ + request(op: Record): Promise { + if (this.closed) return Promise.reject(new SessionError("session_exited", "The session has exited")); + this.nextRid += 1; + const rid = this.nextRid; + const { promise, resolve, reject } = Promise.withResolvers(); + this.replies.set(rid, { resolve, reject }); + this.send(JSON.stringify({ ...op, rid })); + return promise; + } + + /** Closes the connection; the keeper and its session keep running. */ + close(): void { + this.closed = true; + this.socket.destroy(); + } +} + +/** ` ` → its parts. */ +export function parseRecordLine(line: string): { seq: number; line: string } | undefined { + const space = line.indexOf(" "); + const seq = Number(line.slice(0, space)); + return space > 0 && Number.isSafeInteger(seq) && seq > 0 ? { seq, line: line.slice(space + 1) } : undefined; +} + +// --- the session, as the server holds it ----------------------------------------- + +export type RpcOutcome = { response: Record } | { timeout: true; id: string }; +export type DialogAnswer = "accepted" | "unknown" | "answered"; + +export class SessionError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + this.name = "SessionError"; + } +} + +export interface ServeSessionOptions { + /** The keeper's state at attach time; for a session listed from its record, a snapshot without a link. */ + snapshot: SessionSnapshot; + /** The keeper's ring, oldest first. */ + ring?: readonly RingRecord[]; + /** The live link to the keeper; none for a session whose keeper already ended. */ + link?: KeeperLink; + /** The server attached to a keeper a previous server started: open host tool calls wait for their devices to come back. */ + reattached?: boolean; + limits?: Partial; + now?: () => number; + /** The child's stderr, for the server log; never part of the protocol. */ + onStderr?: (text: string) => void; + onExit?: (session: ServeSession) => void; + /** A device's name for the model-facing "not connected" answer; the id when unknown. */ + deviceLabel?: (deviceId: string) => string | undefined; +} + +interface Waiter { + /** `undefined` means the wait was given up (timeout or cancel). */ + resolve: (record: Record | undefined) => void; + reject: (error: Error) => void; +} + +/** Notes the server keeps with the keeper (see `SessionSnapshot.notes`). */ +interface SessionNotes { + /** Devices that registered host tools. */ + providers: string[]; + /** Devices that drove the session, most recent first. */ + recent: string[]; + /** The providers order last sent with `set_host_activity`, serialized. */ + sent: string; +} + +function readNotes(notes: unknown): SessionNotes | undefined { + if (!notes || typeof notes !== "object") return undefined; + const n = notes as Record; + const strings = (value: unknown) => Array.isArray(value) && value.every((v) => typeof v === "string") ? value as string[] : undefined; + const providers = strings(n.providers); + const recent = strings(n.recent); + if (!providers || !recent || typeof n.sent !== "string") return undefined; + return { providers, recent, sent: n.sent }; +} + +export class ServeSession { + readonly id: string; + readonly cwd: string; + readonly startedAt: number; + readonly pid: number | undefined; + + private readonly limits: ServeSessionLimits; + private readonly now: () => number; + private readonly log: SessionLog; + private readonly link?: KeeperLink; + private readonly rpcWaiters = new Map(); + private readonly desktopWaiters = new Map(); + private readonly subscribers = new Set(); + private readonly exited: Promise; + private readonly markExited: () => void; + private readonly onStderr?: (text: string) => void; + private readonly onExit?: (session: ServeSession) => void; + /** Request ids are unique per server run: a late response to a previous run's request never matches. */ + private readonly epoch = randomBytes(4).toString("hex"); + private nextRpc = 0; + private nextDesktop = 0; + private detached = false; + /** Devices whose last stream closed while they owed host tool results, and the timer that fails those calls. */ + private readonly graceTimers = new Map(); + private readonly deviceLabel: (deviceId: string) => string | undefined; + /** When each device last drove this session (an operate request). */ + private readonly activity = new Map(); + private activitySeq = 0; + /** Devices that registered host tools in this session: only their order matters to the session. */ + private readonly hostProviders = new Set(); + /** The connected-providers order last sent with `set_host_activity`, serialized. */ + private sentActivity = "[]"; + private sentNotes = ""; + + constructor(options: ServeSessionOptions) { + const snapshot = options.snapshot; + this.id = snapshot.id; + this.cwd = snapshot.cwd; + this.startedAt = snapshot.startedAt; + this.pid = snapshot.pid ?? undefined; + this.deviceLabel = options.deviceLabel ?? (() => undefined); + this.limits = { ...SERVE_SESSION_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.onStderr = options.onStderr; + this.onExit = options.onExit; + this.log = new SessionLog(this.limits, this.now); + this.log.restore(snapshot); + for (const record of options.ring ?? []) this.log.ring.push(record); + const notes = readNotes(snapshot.notes); + if (notes) { + for (const provider of notes.providers) this.hostProviders.add(provider); + for (const deviceId of [...notes.recent].reverse()) this.activity.set(deviceId, (this.activitySeq += 1)); + this.sentActivity = notes.sent; + } + this.sentNotes = JSON.stringify(this.notes()); + const exited = Promise.withResolvers(); + this.exited = exited.promise; + this.markExited = exited.resolve; + if (this.log.state === "exited") exited.resolve(); + this.link = options.link; + if (this.link) { + this.link.attach({ + record: (seq, line) => this.onRecord(seq, line), + message: (message) => { + if (message.t === "invalid") this.log.invalidRecords += 1; + else if (message.t === "stderr" && typeof message.text === "string") this.onStderr?.(message.text); + }, + close: () => this.onLinkClosed(), + }); + } else if (this.log.state === "running") { + this.onLinkClosed(); + } + if (options.reattached && this.log.state === "running") { + // Nobody is connected yet: each device gets a while to come back for the calls it owes. + for (const provider of new Set(this.log.pendingHostCalls().map((call) => call.provider))) this.armGrace(provider, this.limits.hostToolReattachGraceMs); + } + } + + get state(): SessionState { + return this.log.state; + } + + get seq(): number { + return this.log.seq; + } + + get exitCode(): number | null { + return this.log.exitCode; + } + + get exitSignal(): string | null { + return this.log.exitSignal; + } + + get exitedAt(): number | undefined { + return this.log.exitedAt; + } + + get invalidRecords(): number { + return this.log.invalidRecords; + } + + get droppedRecords(): number { + return this.log.droppedRecords; + } + + get subscriberCount(): number { + return this.subscribers.size; + } + + pendingDialogs(): PendingDialog[] { + return this.log.pendingDialogs(); + } + + // --- output --- + + private onRecord(seq: number, line: string): void { + let record: Record; + try { + record = JSON.parse(line) as Record; + } catch { + return; + } + const event = this.log.push(seq, line, record); + this.broadcast(seq, line); + switch (event?.kind) { + case "response": { + const waiter = this.rpcWaiters.get(event.id); + if (waiter) { + this.rpcWaiters.delete(event.id); + waiter.resolve(record); + } + return; + } + case "desktop_response": { + const waiter = this.desktopWaiters.get(event.requestId); + if (waiter) { + this.desktopWaiters.delete(event.requestId); + waiter.resolve(event.answer); + } + return; + } + case "host_tool_call": { + // Routed to the device that provides the tool: every subscriber sees the record (clients + // filter by `provider`), and when that device has no open stream the server answers for it + // at once with an error result the model can read, instead of letting the turn hang. + const call = this.log.hostCall(event.callId); + if (call && !this.hasStream(call.provider)) this.failHostCall(call); + return; + } + case "exited": + this.onExited(); + return; + } + } + + /** The keeper went away without the session's exit record: it ended (or was killed) with its session. */ + private onLinkClosed(): void { + if (this.detached || this.log.state === "exited") return; + const line = JSON.stringify({ type: "serve_session_exited", code: null, signal: null, error: "keeper_lost" }); + this.onRecord(this.log.seq + 1, line); + } + + // --- host tools --- + + private hasStream(deviceId: string): boolean { + for (const sub of this.subscribers) if (sub.deviceId === deviceId && !sub.sink.destroyed) return true; + return false; + } + + /** Answers the call on its device's behalf: the tool's device is not connected. */ + private failHostCall(call: PendingHostCall): void { + if (this.log.hostCall(call.callId) !== call) return; + this.hostCallSettled(call.callId); + const label = this.deviceLabel(call.provider) ?? call.provider; + const text = `${call.tool} runs in ${label}, which isn't connected right now.`; + // A result the device sent meanwhile wins; the session answers this one `already_answered`. + this.desktop("host_tool_result", { callId: call.callId, content: [{ type: "text", text }], isError: true }, this.limits.hostToolAnswerMs).catch(() => {}); + } + + /** A device sent an operate request (a prompt, a steer, a dialog answer, a Desktop write): it becomes the first to run host tool calls. */ + noteActivity(deviceId: string): void { + this.activitySeq += 1; + this.activity.set(deviceId, this.activitySeq); + this.syncActivity(); + this.saveNotes(); + } + + /** A device registered host tools (`tools` > 0) or withdrew them all. */ + noteHostProvider(deviceId: string, tools: number): void { + if (tools > 0) this.hostProviders.add(deviceId); + else this.hostProviders.delete(deviceId); + this.syncActivity(); + this.saveNotes(); + } + + /** The device that most recently drove this session, if any did. */ + lastActiveDevice(): string | undefined { + let last: string | undefined; + let at = 0; + for (const [deviceId, seq] of this.activity) if (seq > at) [last, at] = [deviceId, seq]; + return last; + } + + private notes(): SessionNotes { + const recent = [...this.activity].sort((a, b) => b[1] - a[1]).map(([deviceId]) => deviceId); + return { providers: [...this.hostProviders], recent, sent: this.sentActivity }; + } + + /** Hands the keeper what a restarted server must know, when it changed. */ + private saveNotes(): void { + const notes = JSON.stringify(this.notes()); + if (notes === this.sentNotes || this.log.state !== "running") return; + this.sentNotes = notes; + this.link?.send(`{"op":"notes","notes":${notes}}`); + } + + /** + * Tells the session which host tool providers are connected, most recently + * active first (`set_host_activity`), whenever that order changes: a host + * tool several devices provide goes to the first of them. Written to the + * session before any command the same request forwards, so a prompt's tool + * calls see its device. Sessions without host tools never get one. + */ + private syncActivity(): void { + if (this.log.state !== "running" || this.detached) return; + const connected = new Set(); + for (const sub of this.subscribers) if (!sub.sink.destroyed && this.hostProviders.has(sub.deviceId)) connected.add(sub.deviceId); + const providers = [...connected].sort((a, b) => (this.activity.get(b) ?? 0) - (this.activity.get(a) ?? 0)); + const serialized = JSON.stringify(providers); + if (serialized === this.sentActivity) return; + this.sentActivity = serialized; + this.saveNotes(); + this.desktop("set_host_activity", { providers }, this.limits.hostToolAnswerMs).catch(() => {}); + } + + /** After a device's last stream closed: its calls fail unless it reconnects within the grace period (at once when revoked). */ + private deviceLeft(deviceId: string, immediately = false): void { + this.syncActivity(); + if (this.log.state !== "running" || this.detached || this.hasStream(deviceId) || this.graceTimers.has(deviceId)) return; + if (immediately) { + for (const call of this.owed(deviceId)) this.failHostCall(call); + return; + } + this.armGrace(deviceId, this.limits.hostToolGraceMs); + } + + private owed(deviceId: string): PendingHostCall[] { + return this.log.pendingHostCalls().filter((call) => call.provider === deviceId); + } + + private armGrace(deviceId: string, ms: number): void { + if (this.owed(deviceId).length === 0 || this.graceTimers.has(deviceId)) return; + const timer = setTimeout(() => { + this.graceTimers.delete(deviceId); + if (this.hasStream(deviceId)) return; + for (const call of this.owed(deviceId)) this.failHostCall(call); + }, ms); + timer.unref?.(); + this.graceTimers.set(deviceId, timer); + } + + /** The device that must answer `callId`, if the server saw that call and it is still open. */ + hostCallProvider(callId: string): string | undefined { + return this.log.hostCall(callId)?.provider; + } + + /** A `host_tool_result` reached the session and settled (or could no longer settle) the call. */ + hostCallSettled(callId: string): void { + if (!this.log.hostCall(callId)) return; + this.log.settle(callId); + this.link?.send(JSON.stringify({ op: "settled", callId })); + } + + /** A `host_tool_progress` reached the session and restarted the call's deadline: keep tracking it as long. */ + hostCallProgressed(callId: string): void { + if (!this.log.hostCall(callId)) return; + this.log.progress(callId); + this.link?.send(JSON.stringify({ op: "progressed", callId })); + } + + pendingHostCalls(): PendingHostCall[] { + return this.log.pendingHostCalls(); + } + + private broadcast(seq: number, line: string): void { + const frame = sseRecord(seq, line); + for (const sub of this.subscribers) { + if (sub.sink.destroyed) { + this.subscribers.delete(sub); + this.deviceLeft(sub.deviceId); + continue; + } + if (sub.filter && !sub.filter(line)) continue; + if (sub.sink.writableLength > this.limits.clientBufferBytes) { + this.drop(sub, "slow_client"); + continue; + } + sub.sink.write(frame); + } + } + + /** Ends a subscriber's stream with a resync marker; it reconnects with its last seq. */ + drop(sub: Subscriber, reason: string): void { + if (!this.subscribers.delete(sub)) return; + this.deviceLeft(sub.deviceId); + try { + sub.sink.end(sseEvent("resync", { reason, seq: this.log.seq })); + } catch { + sub.sink.destroy(); + return; + } + // A client that never reads would hold the marker (and its buffer) forever. + const timer = setTimeout(() => sub.sink.destroy(), this.limits.dropFlushMs); + timer.unref?.(); + } + + /** Closes every stream opened by `deviceId` (a revoked device); the host tool calls it owed fail now. */ + dropDevice(deviceId: string): void { + for (const sub of [...this.subscribers]) { + if (sub.deviceId !== deviceId) continue; + this.subscribers.delete(sub); + sub.sink.destroy(); + } + this.deviceLeft(deviceId, true); + } + + heartbeat(): void { + for (const sub of this.subscribers) { + if (sub.sink.writableLength > this.limits.clientBufferBytes) this.drop(sub, "slow_client"); + else sub.sink.write(": ping\n\n"); + } + } + + /** + * Attaches an SSE subscriber: a `hello`, then either the records after + * `after` or `snapshot-required`, then every dialog still waiting that the + * replay did not carry, then (to the device that provides them) the host + * tool calls still waiting that the replay did not carry, then the live + * stream. An exited session's stream ends after that. With a `filter`, + * only the records (replayed or live) it keeps are sent, and no dialog or + * host tool call is re-sent. + */ + subscribe(sink: StreamSink, deviceId: string, after?: number, filter?: (line: string) => boolean): void { + const ring = this.log.ring; + const hello = { session: this.id, state: this.log.state, seq: this.log.seq, oldest: ring.oldest ?? null }; + sink.write(`retry: 3000\n\n${sseEvent("hello", hello)}`); + let replayedFrom = Number.POSITIVE_INFINITY; + if (after !== undefined) { + const replay = ring.since(after, this.log.seq); + if ("snapshotRequired" in replay) { + sink.write(sseEvent("snapshot-required", { after, oldest: replay.oldest, seq: this.log.seq })); + } else { + replayedFrom = after; + for (const r of replay.records) if (!filter || filter(r.line)) sink.write(sseRecord(r.seq, r.line)); + } + } + for (const dialog of filter ? [] : this.pendingDialogs()) { + if (dialog.seq > replayedFrom) continue; + sink.write(`event: dialog\ndata: ${dialog.line}\n\n`); + } + for (const call of filter ? [] : this.log.pendingHostCalls()) { + if (call.provider !== deviceId || call.seq > replayedFrom) continue; + sink.write(`event: host_tool_call\ndata: ${call.line}\n\n`); + } + if (this.log.state === "exited" || this.detached) { + sink.end(); + return; + } + this.subscribers.add({ sink, deviceId, ...(filter ? { filter } : {}) }); + const grace = this.graceTimers.get(deviceId); + if (grace !== undefined) { + clearTimeout(grace); + this.graceTimers.delete(deviceId); + } + this.syncActivity(); + } + + unsubscribe(sink: StreamSink): void { + for (const sub of this.subscribers) { + if (sub.sink !== sink) continue; + this.subscribers.delete(sub); + this.deviceLeft(sub.deviceId); + } + } + + // --- input --- + + private write(record: Record): void { + if (this.log.state !== "running") throw new SessionError("session_exited", "The session has exited"); + const link = this.link; + if (!link || link.closed || this.detached) throw new SessionError("session_exited", "The session's input is closed"); + if (link.writableLength > this.limits.stdinBufferBytes) throw new SessionError("session_busy", "The session is not reading its input; try again later"); + link.send(`>${JSON.stringify(record)}`); + } + + /** + * Sends one Pi RPC command under a server-assigned id (clients may share a + * session, so their own ids could collide) and waits for its response. The + * caller's `id` is put back on the response it gets. + */ + async rpc(command: Record, timeoutMs: number): Promise { + this.nextRpc += 1; + const id = `serve-rpc-${this.epoch}-${this.nextRpc}`; + const response = this.waitFor(this.rpcWaiters, id, timeoutMs); + try { + this.write({ ...command, id }); + } catch (error) { + this.cancelWait(this.rpcWaiters, id); + throw error; + } + const record = await response; + if (record === undefined) return { timeout: true, id }; + const { id: _server, ...rest } = record; + return { response: command.id === undefined ? rest : { ...rest, id: command.id } }; + } + + /** Forwards an `extension_ui_response`; only the first answer to a dialog reaches Pi (the keeper decides). */ + async answerDialog(answer: Record): Promise { + const id = answer.id; + if (typeof id !== "string") return "unknown"; + const status = this.log.dialogStatus(id); + if (status !== "pending") return status; + if (this.log.state !== "running" || !this.link || this.detached) throw new SessionError("session_exited", "The session has exited"); + const outcome = await this.link.request({ op: "answer", answer }); + return outcome === "accepted" || outcome === "answered" ? outcome : "unknown"; + } + + /** + * One Desktop RPC request through `/gentle:desktop`, answered by the matching + * `gentle-desktop-rpc` widget. Returns the Desktop RPC response object, or + * undefined on timeout. A refused prompt is reported as its Pi response. + */ + async desktop(method: string, params: Record, timeoutMs: number): Promise<{ answer: Record } | { prompt: Record } | undefined> { + this.nextDesktop += 1; + const requestId = `serve-desktop-${this.epoch}-${this.nextDesktop}`; + const message = `/gentle:desktop ${JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId, method, params })}`; + const answer = this.waitFor(this.desktopWaiters, requestId, timeoutMs); + // The session can exit while the prompt is in flight: that rejection is rethrown below, never unhandled. + answer.catch(() => {}); + let prompt: RpcOutcome; + try { + prompt = await this.rpc({ type: "prompt", message }, timeoutMs); + } catch (error) { + this.cancelWait(this.desktopWaiters, requestId); + throw error; + } + if ("response" in prompt && prompt.response.success !== true) { + this.cancelWait(this.desktopWaiters, requestId); + return { prompt: prompt.response }; + } + const result = await answer; + return result === undefined ? undefined : { answer: result }; + } + + private waitFor(waiters: Map, id: string, timeoutMs: number): Promise | undefined> { + const { promise, resolve, reject } = Promise.withResolvers | undefined>(); + const timer = setTimeout(() => { + waiters.delete(id); + resolve(undefined); + }, timeoutMs); + timer.unref?.(); + waiters.set(id, { + resolve: (record) => { clearTimeout(timer); resolve(record); }, + reject: (error) => { clearTimeout(timer); reject(error); }, + }); + return promise; + } + + private cancelWait(waiters: Map, id: string): void { + waiters.get(id)?.resolve(undefined); + waiters.delete(id); + } + + // --- lifecycle --- + + private failWaiters(error: Error): void { + for (const waiters of [this.rpcWaiters, this.desktopWaiters]) { + for (const waiter of waiters.values()) waiter.reject(error); + waiters.clear(); + } + } + + private onExited(): void { + for (const timer of this.graceTimers.values()) clearTimeout(timer); + this.graceTimers.clear(); + this.failWaiters(new SessionError("session_exited", "The session has exited")); + for (const sub of this.subscribers) sub.sink.end(); + this.subscribers.clear(); + this.onExit?.(this); + this.markExited(); + } + + /** + * Orderly stop: the keeper closes the session's stdin and sends SIGTERM + * together (Pi treats them as one request), then SIGKILL, and ends. + */ + async stop(): Promise { + if (this.log.state === "exited") return; + if (!this.link || this.link.closed) return this.exited; + this.link.send(JSON.stringify({ op: "stop" })); + // A keeper that never reports the exit is given up on: the link closes and the session counts as lost. + const timer = setTimeout(() => this.link!.close(), this.limits.stopGraceMs + 5000); + timer.unref?.(); + await this.exited; + clearTimeout(timer); + } + + /** + * Lets go of the session without stopping it (the server is stopping and a + * later one reattaches): streams end (clients reconnect to the next server + * with their last seq), waiting requests fail, the keeper keeps running. + */ + detach(): void { + if (this.detached) return; + this.detached = true; + for (const timer of this.graceTimers.values()) clearTimeout(timer); + this.graceTimers.clear(); + this.failWaiters(new SessionError("shutting_down", "The server is stopping")); + for (const sub of this.subscribers) sub.sink.end(); + this.subscribers.clear(); + this.link?.close(); + } + + whenExited(): Promise { + return this.exited; + } +} diff --git a/lib/serve-share.ts b/lib/serve-share.ts new file mode 100644 index 000000000..fbde38d75 --- /dev/null +++ b/lib/serve-share.ts @@ -0,0 +1,322 @@ +// `gentle-shell serve share`: the connection code a desktop client pastes when +// LAN discovery cannot find this server, the addresses that +// code advertises, the firewall hint, and the login autostart (a systemd user +// unit or a macOS LaunchAgent) that keeps the network server running. + +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, openSync, closeSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { homedir, hostname, networkInterfaces, type NetworkInterfaceInfo } from "node:os"; +import { delimiter, dirname, isAbsolute, join } from "node:path"; + +export const CONNECTION_CODE_PREFIX = "gsc1."; +export const SHARE_DEFAULT_PORT = 8787; +/** Ports tried after the requested one when it is taken. */ +export const SHARE_PORT_ATTEMPTS = 10; +const MAX_ADDRESSES = 8; + +// One DNS name (no port, no trailing dot) a client may put in the Host header. +export const HOST_NAME = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; + +// --- connection code --------------------------------------------------------------- + +export interface ConnectionCode { + /** Server id; a client pairs only at an address whose identity names it. */ + id: string; + /** Server name (its hostname), for display. */ + n: string; + p: number; + /** Addresses to probe, best first. */ + a: string[]; + /** Pairing code: single use, 5 minutes. */ + c: string; + /** The certificate's fingerprint (base64url SHA-256 of its DER) when the server serves HTTPS: pin it, no pairing proof needed. */ + fp?: string; + /** The relay that reaches the server from anywhere (`gsr://host:port`), routed by `fp`. */ + r?: string; +} + +/** `gsc1.` + base64url (no padding) of `{"v":1,"id","n","p","a","c"[,"fp"][,"r"]}`. A secret while its pairing code is valid. */ +export function encodeConnectionCode(code: ConnectionCode): string { + const json = JSON.stringify({ v: 1, id: code.id, n: code.n, p: code.p, a: code.a, c: code.c, ...(code.fp === undefined ? {} : { fp: code.fp }), ...(code.r === undefined ? {} : { r: code.r }) }); + return `${CONNECTION_CODE_PREFIX}${Buffer.from(json, "utf8").toString("base64url")}`; +} + +// --- addresses --------------------------------------------------------------------- + +// Container, VM and bridge interfaces: reachable from this machine only, so last. +const VIRTUAL_INTERFACE = /^(?:docker|br-|veth|virbr|vmnet|vboxnet|cni|flannel|podman|lxcbr|lxdbr|bridge)/i; + +function privateIPv4(address: string): boolean { + const [a, b] = address.split(".").map(Number); + return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168); +} + +/** This machine's own names a client may use: the hostname and `.local` (the names a `0.0.0.0` bind admits). */ +export function ownHostNames(name: string): string[] { + const own = name.toLowerCase(); + if (!HOST_NAME.test(own)) return []; + return own.endsWith(".local") ? [own] : [own, `${own}.local`]; +} + +/** + * The addresses a connection code advertises: this machine's IPv4 addresses + * other than loopback and link-local (private LAN ranges first, then others such + * as a tailnet's, then container and VM bridges), then its own names as + * fallbacks. At most 8; the names always keep their places. + */ +export function shareAddresses(interfaces: NodeJS.Dict, name: string): string[] { + const names = ownHostNames(name); + const ranked: Array<{ address: string; rank: number }> = []; + for (const [iface, infos] of Object.entries(interfaces)) { + for (const info of infos ?? []) { + // Node < 18.4 reported the family as a number. + if ((info.family as string | number) !== "IPv4" && (info.family as string | number) !== 4) continue; + const address = info.address; + if (info.internal || address.startsWith("127.") || address.startsWith("169.254.") || address === "0.0.0.0") continue; + if (ranked.some((r) => r.address === address)) continue; + ranked.push({ address, rank: VIRTUAL_INTERFACE.test(iface) ? 2 : privateIPv4(address) ? 0 : 1 }); + } + } + const addresses = ranked.sort((x, y) => x.rank - y.rank).map((r) => r.address); + return [...addresses.slice(0, Math.max(0, MAX_ADDRESSES - names.length)), ...names]; +} + +// --- firewall ---------------------------------------------------------------------- + +/** Whether `command` is on PATH (plus the sbin folders a user PATH may lack). */ +export function commandExists(command: string, env: NodeJS.ProcessEnv): boolean { + const dirs = [...(env.PATH ?? "").split(delimiter), "/usr/sbin", "/sbin", "/usr/local/sbin"]; + return dirs.some((dir) => dir !== "" && isAbsolute(dir) && existsSync(join(dir, command))); +} + +/** Inclusive listen ports for forwarded pages. */ +export interface PortRange { + from: number; + to: number; +} + +/** The ports `share` gives forwarded pages, so one firewall rule covers them all. */ +export const SHARE_FORWARD_PORTS: PortRange = { from: 8800, to: 8899 }; + +/** + * The command that opens `port` in the local firewall for TCP (HTTP) and UDP (LAN discovery), plus the + * forwarded pages' TCP range when the server has one, on Linux with ufw or firewalld; never run for the user. + */ +export function firewallHint(platform: NodeJS.Platform, port: number, has: (command: string) => boolean, forwardPorts?: PortRange): string | undefined { + if (platform !== "linux") return undefined; + if (has("ufw")) return `sudo ufw allow ${port}${forwardPorts ? ` && sudo ufw allow ${forwardPorts.from}:${forwardPorts.to}/tcp` : ""}`; + if (has("firewall-cmd")) return `sudo firewall-cmd --permanent --add-port=${port}/tcp --add-port=${port}/udp${forwardPorts ? ` --add-port=${forwardPorts.from}-${forwardPorts.to}/tcp` : ""} && sudo firewall-cmd --reload`; + return undefined; +} + +// --- autostart --------------------------------------------------------------------- + +export const AUTOSTART_UNIT = "gentle-shell-serve.service"; +export const AUTOSTART_LABEL = "com.gentle-shell.serve"; +/** Environment an autostarted server keeps from the invocation that installed it. */ +const AUTOSTART_ENV = ["PATH", "GENTLE_SHELL_NO_AUTO_SETUP", "GENTLE_SHELL_HOME", "GENTLE_SHELL_CONFIG", "GENTLE_PI_CONFIG_HOME", "GENTLE_SHELL_PI", "PI_CODING_AGENT_DIR"]; + +export interface AutostartCommand { + command: string; + args: string[]; + env: Record; + /** macOS: launchd writes the server's output here (systemd uses the journal). */ + logFile: string; +} + +/** The same launcher, home flags and kept environment as this invocation, serving the network in the foreground. */ +export function autostartCommand(input: { nodePath: string; launcher: string; homeFlags: readonly string[]; port: number; allowHosts: readonly string[]; forwardPorts?: PortRange; noTls?: boolean; relay?: string; env: NodeJS.ProcessEnv; logFile: string }): AutostartCommand { + const env: Record = {}; + for (const key of AUTOSTART_ENV) { + const value = input.env[key]; + if (value !== undefined && value !== "" && !/[\r\n]/.test(value)) env[key] = value; + } + return { + command: input.nodePath, + args: [input.launcher, ...input.homeFlags, "serve", "--foreground", "--listen", `0.0.0.0:${input.port}`, ...input.allowHosts.flatMap((name) => ["--allow-host", name]), + ...(input.forwardPorts ? ["--forward-ports", `${input.forwardPorts.from}-${input.forwardPorts.to}`] : []), + ...(input.noTls ? ["--no-tls"] : []), ...(input.relay === undefined ? [] : ["--relay", input.relay])], + env, + logFile: input.logFile, + }; +} + +// systemd unit quoting: `%` is a specifier and `$` a variable in ExecStart. +function systemdArg(value: string): string { + if (value !== "" && !/[\s"'\\%$;]/.test(value)) return value; + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`; +} + +export function systemdUnit(spec: AutostartCommand): string { + const env = Object.entries(spec.env).map(([key, value]) => `Environment="${key}=${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`); + return [ + "# Written by 'gentle-shell serve share --always'; remove with 'gentle-shell serve share --off'.", + "[Unit]", + "Description=Gentle Shell server for the local network", + // Gives up after 5 failed starts in a minute (for example another server already holds this home). + "StartLimitIntervalSec=60", + "StartLimitBurst=5", + "", + "[Service]", + "Type=simple", + ...env, + `ExecStart=${[spec.command, ...spec.args].map(systemdArg).join(" ")}`, + "Restart=on-failure", + "RestartSec=5", + "TimeoutStopSec=30", + // Stopping or restarting the server (an upgrade exits for a restart) ends only the server: + // session keepers and the terminal host it started live on, and the next server reattaches them. + "KillMode=process", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); +} + +function xml(value: string): string { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} + +export function launchAgentPlist(spec: AutostartCommand): string { + return [ + '', + '', + "", + '', + "", + "\tLabel", + `\t${AUTOSTART_LABEL}`, + "\tProgramArguments", + "\t", + ...[spec.command, ...spec.args].map((arg) => `\t\t${xml(arg)}`), + "\t", + "\tEnvironmentVariables", + "\t", + ...Object.entries(spec.env).flatMap(([key, value]) => [`\t\t${xml(key)}`, `\t\t${xml(value)}`]), + "\t", + "\tRunAtLoad", + "\t", + // Restarted after a crash, not after `serve stop`. + "\tKeepAlive", + "\t", + "\t\tSuccessfulExit", + "\t\t", + "\t", + "\tStandardOutPath", + `\t${xml(spec.logFile)}`, + "\tStandardErrorPath", + `\t${xml(spec.logFile)}`, + "", + "", + "", + ].join("\n"); +} + +/** Runs a command to completion; ENOENT is status 127. */ +export type CommandRunner = (command: string, args: readonly string[]) => Promise<{ status: number; output: string }>; + +export function commandRunner(env: NodeJS.ProcessEnv): CommandRunner { + return (command, args) => { + const { promise, resolve } = Promise.withResolvers<{ status: number; output: string }>(); + let output = ""; + const child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + child.stdout.on("data", (d) => { output += d; }); + child.stderr.on("data", (d) => { output += d; }); + child.once("error", (error) => resolve({ status: (error as NodeJS.ErrnoException).code === "ENOENT" ? 127 : 1, output: `${output}${error.message}` })); + child.once("close", (code) => resolve({ status: code ?? 1, output })); + return promise; + }; +} + +/** Machine facts and the command runner `serve share` uses; tests replace them. */ +export interface ShareSystem { + platform: NodeJS.Platform; + hostname: () => string; + networkInterfaces: () => NodeJS.Dict; + userHome: string; + /** XDG_CONFIG_HOME when set (systemd reads user units there). */ + configHome?: string; + uid: number; + user: string; + run: CommandRunner; + has: (command: string) => boolean; +} + +export function defaultShareSystem(env: NodeJS.ProcessEnv): ShareSystem { + const userHome = homedir(); + return { + platform: process.platform, + hostname, + networkInterfaces, + userHome, + ...(env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME) ? { configHome: env.XDG_CONFIG_HOME } : {}), + uid: process.getuid?.() ?? 0, + user: env.USER ?? env.LOGNAME ?? "$USER", + run: commandRunner(env), + has: (command) => commandExists(command, env), + }; +} + +/** Where autostart lives on this platform, or undefined where it is not supported (Windows). */ +export function autostartFile(system: Pick): string | undefined { + if (system.platform === "linux") return join(system.configHome ?? join(system.userHome, ".config"), "systemd", "user", AUTOSTART_UNIT); + if (system.platform === "darwin") return join(system.userHome, "Library", "LaunchAgents", `${AUTOSTART_LABEL}.plist`); + return undefined; +} + +export function autostartContent(system: Pick, spec: AutostartCommand): string { + return system.platform === "darwin" ? launchAgentPlist(spec) : systemdUnit(spec); +} + +/** Whether the installed autostart is exactly this one. */ +export function autostartInstalled(system: Pick, spec: AutostartCommand): boolean { + const file = autostartFile(system); + try { + return file !== undefined && readFileSync(file, "utf8") === autostartContent(system, spec); + } catch { + return false; + } +} + +/** Writes the unit or agent and starts it now through the service manager. An error removes what was written. */ +export async function installAutostart(system: ShareSystem, spec: AutostartCommand): Promise<{ file: string } | { error: string }> { + const file = autostartFile(system); + if (!file) return { error: `autostart is not supported on ${system.platform} yet` }; + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, autostartContent(system, spec), { mode: 0o644 }); + const steps: Array<[string, string[]]> = system.platform === "darwin" + ? [["launchctl", ["bootstrap", `gui/${system.uid}`, file]]] + : [["systemctl", ["--user", "daemon-reload"]], ["systemctl", ["--user", "enable", "--now", AUTOSTART_UNIT]]]; + if (system.platform === "darwin") { + // launchd opens the log before the server runs: create it owner-only first. + mkdirSync(dirname(spec.logFile), { recursive: true, mode: 0o700 }); + closeSync(openSync(spec.logFile, "a", 0o600)); + // A previous version of the agent may still be loaded. + await system.run("launchctl", ["bootout", `gui/${system.uid}/${AUTOSTART_LABEL}`]); + } + for (const [command, args] of steps) { + const result = await system.run(command, args); + if (result.status !== 0) { + rmSync(file, { force: true }); + if (system.platform !== "darwin") await system.run("systemctl", ["--user", "daemon-reload"]); + return { error: `${command} ${args.join(" ")} failed (${result.status})${result.output.trim() ? `: ${result.output.trim()}` : ""}` }; + } + } + return { file }; +} + +/** Stops the autostarted server and removes the unit or agent. */ +export async function removeAutostart(system: ShareSystem): Promise<{ file: string; removed: boolean }> { + const file = autostartFile(system); + if (!file || !existsSync(file)) return { file: file ?? "", removed: false }; + if (system.platform === "darwin") { + await system.run("launchctl", ["bootout", `gui/${system.uid}/${AUTOSTART_LABEL}`]); + rmSync(file, { force: true }); + } else { + await system.run("systemctl", ["--user", "disable", "--now", AUTOSTART_UNIT]); + rmSync(file, { force: true }); + await system.run("systemctl", ["--user", "daemon-reload"]); + } + return { file, removed: true }; +} diff --git a/lib/serve-terminals.ts b/lib/serve-terminals.ts new file mode 100644 index 000000000..1cc8c22ac --- /dev/null +++ b/lib/serve-terminals.ts @@ -0,0 +1,626 @@ +// Persistent terminals for `gentle-shell serve`, over a native terminal host +// (`gentle-term-host`): the host owns the PTYs and keeps them alive while no +// client is connected (and across serve restarts); serve starts it on first +// use, talks to it in JSON Lines over its owner-only Unix socket (on Windows, +// loopback TCP with a token from an owner-only file), and exposes the +// terminals to paired devices over HTTP + SSE. One host connection is the +// control connection; every SSE stream gets its own, so each stream has its +// own attachment and backpressure. + +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { accessSync, closeSync, constants as fsConstants, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { chmod, mkdir, readdir, rename, rm } from "node:fs/promises"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import { connect, type Socket } from "node:net"; +import { delimiter, join } from "node:path"; +import { StringDecoder } from "node:string_decoder"; +import { hasScope, type Principal } from "./serve-auth.ts"; +import { fsHttpError, HttpError, need, ownsOrAdmin, readJsonBody, realDirectory, receiveBodyToFile, sendJson, sseEvent, startSse } from "./serve-http.ts"; + +export const TERM_HOST_PROTOCOL = 1; +export const TERM_HOST_BINARY = process.platform === "win32" ? "gentle-term-host.exe" : "gentle-term-host"; +/** Where a host started with `--tcp` writes `{ port, token, pid }`, in its state folder. */ +export const TERM_HOST_TCP_FILE = "term-host.json"; +const OWNERS_SCHEMA = "gentle-shell.serve.terminals/v1"; + +/** How serve reaches the host: its Unix socket, or loopback TCP with the token the host wrote. */ +export type TermHostEndpoint = { path: string } | { port: number; token: string }; +export type TermHostTransport = "unix" | "tcp"; + +/** TCP on Windows (no Unix sockets for the host there); `GENTLE_TERM_HOST_TRANSPORT=tcp` picks it anywhere. */ +export function termHostTransport(env: NodeJS.ProcessEnv, platform: NodeJS.Platform = process.platform): TermHostTransport { + return platform === "win32" || env.GENTLE_TERM_HOST_TRANSPORT === "tcp" ? "tcp" : "unix"; +} + +const ASSET_OS: Partial> = { linux: "linux", darwin: "macos", win32: "windows" }; +const ASSET_ARCHS: Partial> = { linux: ["x64", "arm64"], darwin: ["x64", "arm64"], win32: ["x64"] }; + +/** The Gentle Shell GPUI release asset with the host for this system, `gentle-term-host--[.exe]`; null when none is built for it. */ +export function termHostAsset(platform: NodeJS.Platform = process.platform, arch: string = process.arch): string | null { + const os = ASSET_OS[platform]; + if (!os || !ASSET_ARCHS[platform]?.includes(arch)) return null; + return `gentle-term-host-${os}-${arch}${platform === "win32" ? ".exe" : ""}`; +} + +export const SERVE_TERM_LIMITS = { + /** One request to the host. */ + requestTimeoutMs: 10_000, + /** A freshly started host opening its socket. */ + startTimeoutMs: 5_000, + /** `input` bodies (base64 in JSON). */ + inputBodyBytes: 4 * 1024 * 1024, + /** A host binary sent with `PUT /api/term-host`. */ + installBytes: 64 * 1024 * 1024, + /** Unsent bytes of one stream; past it the stream ends with `overflow`. */ + streamQueueBytes: 8 * 1024 * 1024, + maxCols: 1000, + maxRows: 500, + smallBodyBytes: 64 * 1024, +}; + +/** An error answer from the host: `{ ok: false, error: { code, message } }`. */ +export class TermHostError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +function hostHttpError(error: unknown): unknown { + if (!(error instanceof TermHostError)) return error; + switch (error.code) { + case "not_found": return new HttpError(404, "not_found", "No such terminal"); + case "bad_request": return new HttpError(400, "invalid_request", error.message); + case "exited": + case "alive": return new HttpError(409, `terminal_${error.code}`, error.message); + case "spawn_failed": return new HttpError(502, "term_spawn_failed", error.message); + default: return new HttpError(502, "term_host_error", `${error.code}: ${error.message}`); + } +} + +type HostMessage = Record; + +/** One connection to the host: requests with ids and their replies, plus unsolicited events. */ +export class HostConnection { + private readonly socket: Socket; + private readonly decoder = new StringDecoder("utf8"); + private buffered = ""; + private nextId = 1; + private readonly pending = new Map void; reject: (error: Error) => void; timer: NodeJS.Timeout }>(); + private readonly eventListeners: Array<(event: HostMessage) => void> = []; + private readonly closeListeners: Array<() => void> = []; + closed = false; + + private constructor(socket: Socket) { + this.socket = socket; + socket.setNoDelay(true); + socket.on("data", (chunk: Buffer) => this.receive(this.decoder.write(chunk))); + socket.on("error", () => { /* close follows */ }); + socket.on("close", () => { + this.closed = true; + for (const [id, entry] of this.pending) { + clearTimeout(entry.timer); + entry.reject(new HttpError(502, "term_host_gone", "The terminal host closed the connection")); + this.pending.delete(id); + } + for (const listener of this.closeListeners) listener(); + }); + } + + /** Connects, and over TCP authenticates first (`{ op: "auth", token }`); rejects when the host refuses the token. */ + static open(endpoint: TermHostEndpoint, timeoutMs: number): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const socket = "path" in endpoint ? connect(endpoint.path) : connect({ host: "127.0.0.1", port: endpoint.port }); + const timer = setTimeout(() => { socket.destroy(); reject(Object.assign(new Error("connect timeout"), { code: "ETIMEDOUT" })); }, timeoutMs); + socket.once("error", (error) => { clearTimeout(timer); reject(error); }); + socket.once("connect", () => { + clearTimeout(timer); + const conn = new HostConnection(socket); + if ("path" in endpoint) return resolve(conn); + conn.request("auth", { token: endpoint.token }, timeoutMs).then(() => resolve(conn), (error: unknown) => { + conn.close(); + reject(error); + }); + }); + return promise; + } + + private receive(text: string): void { + this.buffered += text; + let newline = this.buffered.indexOf("\n"); + while (newline !== -1) { + const line = this.buffered.slice(0, newline).replace(/\r$/, ""); + this.buffered = this.buffered.slice(newline + 1); + newline = this.buffered.indexOf("\n"); + if (line.trim() === "") continue; + let message: unknown; + try { message = JSON.parse(line); } catch { continue; } + if (!message || typeof message !== "object" || Array.isArray(message)) continue; + const record = message as HostMessage; + if (typeof record.ev === "string") { + for (const listener of this.eventListeners) listener(record); + continue; + } + const entry = typeof record.id === "number" ? this.pending.get(record.id) : undefined; + if (!entry) continue; + this.pending.delete(record.id as number); + clearTimeout(entry.timer); + if (record.ok === true) entry.resolve(record); + else { + const error = record.error && typeof record.error === "object" ? record.error as { code?: unknown; message?: unknown } : {}; + entry.reject(new TermHostError(typeof error.code === "string" ? error.code : "error", typeof error.message === "string" ? error.message : "The terminal host refused the request")); + } + } + } + + request(op: string, params: HostMessage, timeoutMs: number): Promise { + if (this.closed) return Promise.reject(new HttpError(502, "term_host_gone", "The terminal host closed the connection")); + const { promise, resolve, reject } = Promise.withResolvers(); + const id = this.nextId++; + const timer = setTimeout(() => { + this.pending.delete(id); + reject(new HttpError(504, "term_host_timeout", `The terminal host did not answer ${op} in time`)); + }, timeoutMs); + this.pending.set(id, { resolve, reject, timer }); + this.socket.write(`${JSON.stringify({ ...params, id, op })}\n`); + return promise; + } + + onEvent(listener: (event: HostMessage) => void): void { + this.eventListeners.push(listener); + } + + onClose(listener: () => void): void { + this.closeListeners.push(listener); + } + + close(): void { + this.socket.destroy(); + } +} + +/** Whether `path` is a file this process may execute. */ +function executable(path: string): boolean { + try { + if (!statSync(path).isFile()) return false; + accessSync(path, process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK); + return true; + } catch { + return false; + } +} + +interface TermStream { + deviceId: string; + res: ServerResponse; + conn: HostConnection; +} + +export interface TerminalServiceOptions { + /** `/serve`: the socket (or `term/term-host.json` over TCP), the installed binary, the ownership file and the host's log live here. */ + serveDir: string; + /** The environment the host starts with, and where `GENTLE_TERM_HOST`, `GENTLE_TERM_HOST_TRANSPORT` and `PATH` are read. */ + env: NodeJS.ProcessEnv; + limits?: Partial; + log?: (line: string) => void; +} + +export class TerminalService { + private readonly serveDir: string; + private readonly env: NodeJS.ProcessEnv; + private readonly limits: typeof SERVE_TERM_LIMITS; + private readonly log: (line: string) => void; + readonly transport: TermHostTransport; + readonly socketPath: string; + private readonly stateDir: string; + /** Where a TCP host writes its port and token. */ + private readonly tcpFile: string; + private readonly ownersFile: string; + /** Which device opened each terminal; kept on disk because terminals outlive this process. */ + private owners: Record; + private control?: HostConnection; + private hello?: HostMessage; + private connecting?: Promise; + private readonly streams = new Set(); + private closed = false; + + constructor(options: TerminalServiceOptions) { + this.serveDir = options.serveDir; + this.env = options.env; + this.limits = { ...SERVE_TERM_LIMITS, ...options.limits }; + this.log = options.log ?? (() => {}); + this.transport = termHostTransport(this.env); + this.socketPath = join(this.serveDir, "term.sock"); + this.stateDir = join(this.serveDir, "term"); + this.tcpFile = join(this.stateDir, TERM_HOST_TCP_FILE); + this.ownersFile = join(this.serveDir, "terminals.json"); + this.owners = this.readOwners(); + } + + /** Where the installed binary goes. */ + installPath(): string { + return join(this.serveDir, "bin", TERM_HOST_BINARY); + } + + /** The host binary: `$GENTLE_TERM_HOST`, else the installed one, else the first on `PATH`; undefined when there is none. */ + binary(): string | undefined { + const configured = this.env.GENTLE_TERM_HOST; + if (configured) return executable(configured) ? configured : undefined; + if (executable(this.installPath())) return this.installPath(); + for (const dir of (this.env.PATH ?? "").split(delimiter)) { + if (dir && executable(join(dir, TERM_HOST_BINARY))) return join(dir, TERM_HOST_BINARY); + } + return undefined; + } + + /** Where the host is reached: its socket, or the port and token it wrote (undefined before it has). */ + private endpoint(): TermHostEndpoint | undefined { + if (this.transport === "unix") return { path: this.socketPath }; + try { + const parsed = JSON.parse(readFileSync(this.tcpFile, "utf8")) as { port?: unknown; token?: unknown }; + const port = parsed.port; + if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535 || typeof parsed.token !== "string" || parsed.token === "") return undefined; + return { port, token: parsed.token }; + } catch { + return undefined; + } + } + + /** Whether a host may be running: its socket or its port file is there. */ + private hostMayRun(): boolean { + return existsSync(this.transport === "unix" ? this.socketPath : this.tcpFile); + } + + private readOwners(): Record { + try { + const parsed = JSON.parse(readFileSync(this.ownersFile, "utf8")) as { schema?: unknown; owners?: unknown }; + if (parsed.schema !== OWNERS_SCHEMA || !parsed.owners || typeof parsed.owners !== "object") return {}; + return Object.fromEntries(Object.entries(parsed.owners).filter((e): e is [string, string] => typeof e[1] === "string")); + } catch { + return {}; + } + } + + private saveOwners(): void { + mkdirSync(this.serveDir, { recursive: true, mode: 0o700 }); + const temp = `${this.ownersFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + writeFileSync(temp, `${JSON.stringify({ schema: OWNERS_SCHEMA, owners: this.owners }, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, this.ownersFile); + } + + /** The control connection, starting the host when nothing answers on the socket (or port). */ + private ensureHost(): Promise { + if (this.closed) return Promise.reject(new HttpError(503, "shutting_down", "The server is stopping")); + if (this.control && !this.control.closed) return Promise.resolve(this.control); + this.connecting ??= this.connectOrStart().finally(() => { this.connecting = undefined; }); + return this.connecting; + } + + private async connectOrStart(): Promise { + let stale = false; + const endpoint = this.endpoint(); + let conn = endpoint && await HostConnection.open(endpoint, this.limits.requestTimeoutMs).catch((error: NodeJS.ErrnoException) => { + stale = error.code === "ECONNREFUSED" || error instanceof TermHostError; + return undefined; + }); + if (!conn) { + const bin = this.binary(); + if (!bin) throw new HttpError(501, "term_host_missing", `No terminal host on the server: install ${TERM_HOST_BINARY} (PUT /api/term-host) or set GENTLE_TERM_HOST`); + // A socket nothing listens on, or a port file whose host is gone (or refuses its token), is left from a host that died. + if (stale) rmSync(this.transport === "unix" ? this.socketPath : this.tcpFile, { force: true }); + conn = await this.start(bin); + } + const hello = await conn.request("hello", {}, this.limits.requestTimeoutMs); + if (hello.protocol !== TERM_HOST_PROTOCOL) { + conn.close(); + throw new HttpError(502, "term_host_protocol", `The terminal host speaks protocol ${String(hello.protocol)}, not ${TERM_HOST_PROTOCOL}`); + } + this.hello = hello; + this.control = conn; + conn.onClose(() => { + if (this.control === conn) { + this.control = undefined; + this.hello = undefined; + } + }); + return conn; + } + + /** Starts the host detached (it outlives this server) and waits for its socket (or port file). */ + private async start(bin: string): Promise { + mkdirSync(this.serveDir, { recursive: true, mode: 0o700 }); + mkdirSync(this.stateDir, { recursive: true, mode: 0o700 }); + // The host keeps its own log in the state folder; this catches what it prints before it opens it. + const logPath = join(this.stateDir, "term-host.log"); + const logFd = openSync(logPath, "a", 0o600); + const listen = this.transport === "unix" ? ["--socket", this.socketPath] : ["--tcp"]; + const child = spawn(bin, [...listen, "--state-dir", this.stateDir], { detached: true, stdio: ["ignore", logFd, logFd], env: this.env, windowsHide: true }); + closeSync(logFd); + let failure: Error | undefined; + child.once("error", (error) => { failure = error; }); + child.unref(); + this.log(`terminal host started: ${bin} (pid ${child.pid ?? "?"})`); + const deadline = Date.now() + this.limits.startTimeoutMs; + while (Date.now() < deadline) { + if (failure || child.exitCode !== null || child.signalCode !== null) break; + const endpoint = this.endpoint(); + const conn = endpoint && await HostConnection.open(endpoint, 1000).catch(() => undefined); + if (conn) return conn; + await new Promise((r) => setTimeout(r, 50)); + } + let tail = ""; + try { tail = readFileSync(logPath, "utf8").slice(-1000).trim(); } catch { /* no log */ } + throw new HttpError(503, "term_host_failed", `The terminal host did not start${failure ? `: ${failure.message}` : ""}${tail ? `\n${tail}` : ""}`); + } + + private async call(op: string, params: HostMessage = {}): Promise { + const conn = await this.ensureHost(); + try { + return await conn.request(op, params, this.limits.requestTimeoutMs); + } catch (error) { + throw hostHttpError(error); + } + } + + /** `/api/term-host` and `/api/terminals/*`; false for any other path. */ + async route(req: IncomingMessage, res: ServerResponse, method: string, path: string, url: URL, principal: Principal | undefined): Promise { + if (path === "/api/term-host") { + if (method === "PUT") await this.install(req, res, need(principal, "admin")); + else if (method === "GET") await this.status(res, need(principal, "terminal")); + else throw new HttpError(405, "method_not_allowed", "Use GET or PUT"); + return true; + } + if (path === "/api/terminals") { + if (method === "GET") await this.list(res, need(principal, "terminal")); + else if (method === "POST") await this.open(req, res, need(principal, "terminal")); + else throw new HttpError(405, "method_not_allowed", "Use GET or POST"); + return true; + } + const one = /^\/api\/terminals\/(t_[A-Za-z0-9]{1,64})(?:\/(input|resize|stream))?$/.exec(path); + if (!one) return false; + const who = need(principal, "terminal"); + const term = one[1]; + if (!ownsOrAdmin(who, this.owners[term] ?? "")) throw new HttpError(404, "not_found", "No such terminal"); + const expect = (wanted: string) => { if (method !== wanted) throw new HttpError(405, "method_not_allowed", `Use ${wanted}`); }; + switch (one[2]) { + case undefined: expect("DELETE"); await this.remove(res, term); break; + case "input": expect("POST"); await this.input(req, res, term); break; + case "resize": expect("POST"); await this.resize(req, res, term); break; + default: expect("GET"); await this.stream(req, res, url, term, who); break; + } + return true; + } + + private view(entry: HostMessage) { + const term = String(entry.term); + return { + id: term, + pid: entry.pid, + cwd: entry.cwd, + argv: entry.argv, + cols: entry.cols, + rows: entry.rows, + title: entry.title ?? "", + alive: entry.alive, + ...(entry.exitCode === undefined || entry.exitCode === null ? {} : { exitCode: entry.exitCode }), + createdAt: entry.createdAt, + offset: entry.offset, + owner: this.owners[term] ?? null, + }; + } + + /** Every terminal the host has, with owners no longer on the host forgotten. */ + private async hostTerms(): Promise { + const listed = await this.call("list"); + const terms = Array.isArray(listed.terms) ? listed.terms.filter((t): t is HostMessage => !!t && typeof t === "object" && typeof (t as HostMessage).term === "string") : []; + const known = new Set(terms.map((t) => String(t.term))); + const stale = Object.keys(this.owners).filter((term) => !known.has(term)); + if (stale.length > 0) { + for (const term of stale) delete this.owners[term]; + this.saveOwners(); + } + return terms; + } + + private async list(res: ServerResponse, who: Principal): Promise { + const terms = await this.hostTerms(); + sendJson(res, 200, { terminals: terms.filter((t) => ownsOrAdmin(who, this.owners[String(t.term)] ?? "")).map((t) => this.view(t)) }); + } + + private async open(req: IncomingMessage, res: ServerResponse, who: Principal): Promise { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const cwd = realDirectory(body.cwd); + const cols = size(body.cols, "cols", this.limits.maxCols); + const rows = size(body.rows, "rows", this.limits.maxRows); + const params: HostMessage = { cwd, cols, rows }; + if (body.argv !== undefined) { + if (!Array.isArray(body.argv) || body.argv.length === 0 || body.argv.length > 256 || !body.argv.every((a) => typeof a === "string" && !a.includes("\0") && a.length <= 32_768)) { + throw new HttpError(400, "invalid_argv", "argv must be 1-256 strings without NUL"); + } + params.argv = body.argv; + } + if (body.env !== undefined) { + if (!body.env || typeof body.env !== "object" || Array.isArray(body.env)) throw new HttpError(400, "invalid_env", "env must be an object of strings"); + const entries = Object.entries(body.env); + if (entries.length > 128 || !entries.every(([k, v]) => /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(k) && typeof v === "string" && !v.includes("\0") && v.length <= 32_768)) { + throw new HttpError(400, "invalid_env", "env must map at most 128 variable names to strings"); + } + params.env = body.env; + } + const opened = await this.call("open", params); + const term = String(opened.term); + this.owners[term] = who.deviceId; + this.saveOwners(); + this.log(`terminal ${term} opened for ${who.deviceId} in ${cwd}`); + const entry = (await this.hostTerms()).find((t) => t.term === term) ?? { term, pid: opened.pid, cwd, argv: params.argv ?? null, cols, rows, alive: true, offset: 0 }; + sendJson(res, 201, { terminal: this.view(entry) }); + } + + private async input(req: IncomingMessage, res: ServerResponse, term: string): Promise { + const body = await readJsonBody(req, this.limits.inputBodyBytes); + if (typeof body.data !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(body.data)) throw new HttpError(400, "invalid_data", "data must be base64"); + await this.call("write", { term, data: body.data }); + sendJson(res, 200, { ok: true }); + } + + private async resize(req: IncomingMessage, res: ServerResponse, term: string): Promise { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + await this.call("resize", { term, cols: size(body.cols, "cols", this.limits.maxCols), rows: size(body.rows, "rows", this.limits.maxRows) }); + sendJson(res, 200, { ok: true }); + } + + /** Closes a running terminal (SIGHUP, then a kill of its process group after 3 s) or forgets an exited one. */ + private async remove(res: ServerResponse, term: string): Promise { + await this.closeTerm(term); + sendJson(res, 200, { closed: term }); + } + + private async closeTerm(term: string): Promise { + const entry = (await this.hostTerms()).find((t) => t.term === term); + if (entry) { + await this.call(entry.alive === true ? "close" : "forget", { term }).catch((error: unknown) => { + if (!(error instanceof HttpError && error.status === 404)) throw error; + }); + } + delete this.owners[term]; + this.saveOwners(); + } + + private async stream(req: IncomingMessage, res: ServerResponse, url: URL, term: string, who: Principal): Promise { + const raw = url.searchParams.get("from") ?? (typeof req.headers["last-event-id"] === "string" ? req.headers["last-event-id"] : null); + let from: number | undefined; + if (raw !== null && raw !== "") { + if (!/^\d{1,15}$/.test(raw)) throw new HttpError(400, "invalid_from", "from must be a byte offset"); + from = Number(raw); + } + await this.ensureHost(); + const endpoint = this.endpoint(); + const conn = endpoint && await HostConnection.open(endpoint, this.limits.requestTimeoutMs).catch(() => undefined); + if (!conn) throw new HttpError(502, "term_host_gone", "The terminal host is not answering"); + const entry: TermStream = { deviceId: who.deviceId, res, conn }; + // Events that arrive before the attach reply wait for it, so `attached` always comes first. + const early: HostMessage[] = []; + let attached = false; + const forward = (event: HostMessage) => { + if (event.term !== term || res.writableEnded) return; + if (!attached) return void early.push(event); + if (res.writableLength > this.limits.streamQueueBytes || event.ev === "overflow") { + return this.stopStream(entry, sseEvent("overflow", { reason: event.ev === "overflow" ? "host" : "slow_client" })); + } + switch (event.ev) { + case "output": res.write(sseEvent("output", { offset: event.offset, data: event.data }, String(event.offset))); break; + case "title": res.write(sseEvent("title", { title: event.title })); break; + case "resized": res.write(sseEvent("resized", { cols: event.cols, rows: event.rows })); break; + case "exit": this.stopStream(entry, sseEvent("exit", { code: event.code ?? null })); break; + default: break; + } + }; + conn.onEvent(forward); + let reply: HostMessage; + try { + reply = await conn.request("attach", { term, ...(from === undefined ? {} : { from }) }, this.limits.requestTimeoutMs); + } catch (error) { + conn.close(); + throw hostHttpError(error); + } + this.streams.add(entry); + startSse(req, res); + res.write(`retry: 3000\n\n${sseEvent("attached", { offset: reply.offset, ...(typeof reply.snapshot === "string" ? { snapshot: reply.snapshot } : {}) }, String(reply.offset))}`); + attached = true; + for (const event of early.splice(0)) forward(event); + conn.onClose(() => this.stopStream(entry, sseEvent("error", { code: "term_host_gone", message: "The terminal host closed the connection" }))); + res.on("close", () => this.stopStream(entry)); + } + + private stopStream(entry: TermStream, last?: string): void { + if (!this.streams.delete(entry)) return; + entry.conn.close(); + if (!entry.res.writableEnded) entry.res.end(last); + } + + /** `GET /api/term-host`: whether a binary is there and whether the host runs (connecting, never starting it), and which release asset fits this server. */ + private async status(res: ServerResponse, who: Principal): Promise { + const bin = this.binary(); + if (!(this.control && !this.control.closed) && this.hostMayRun()) await this.ensureHost().catch(() => undefined); + const running = !!(this.control && !this.control.closed); + sendJson(res, 200, { + available: bin !== undefined, + // The binary's location is the server's business: only for an admin. + ...(bin !== undefined && hasScope(who, "admin") ? { path: bin } : {}), + running, + ...(running && this.hello ? { version: this.hello.version ?? null, pid: this.hello.pid ?? null, protocol: this.hello.protocol } : {}), + platform: process.platform, + arch: process.arch, + asset: termHostAsset(), + transport: this.transport, + }); + } + + /** `PUT /api/term-host`: installs a host binary into `/bin`, checked against `x-sha256`. */ + private async install(req: IncomingMessage, res: ServerResponse, who: Principal): Promise { + const expected = req.headers["x-sha256"]; + if (typeof expected !== "string" || !/^[0-9a-fA-F]{64}$/.test(expected)) { + req.resume(); + throw new HttpError(400, "invalid_sha256", "The x-sha256 header must carry the binary's sha256 (64 hex digits)"); + } + const target = this.installPath(); + const dir = join(this.serveDir, "bin"); + await mkdir(dir, { recursive: true, mode: 0o700 }); + const temp = join(dir, `.${TERM_HOST_BINARY}.${randomBytes(6).toString("hex")}.tmp`); + try { + const received = await receiveBodyToFile(req, temp, this.limits.installBytes, 0o700).catch((error: unknown) => { throw fsHttpError(error, target); }); + if (received.size === 0) throw new HttpError(400, "empty", "The body is empty"); + if (received.sha256 !== expected.toLowerCase()) throw new HttpError(400, "sha256_mismatch", `The body's sha256 is ${received.sha256}`); + await chmod(temp, 0o755); + // Windows won't replace a running .exe but lets it be renamed: the old one moves aside, and goes on a later install once nothing runs it. + if (process.platform === "win32") { + for (const name of await readdir(dir)) if (name.endsWith(".old")) await rm(join(dir, name), { force: true }).catch(() => undefined); + await rename(target, `${target}.${randomBytes(6).toString("hex")}.old`).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; }); + } + await rename(temp, target); + this.log(`terminal host installed by ${who.deviceId}: ${target} (${received.size} bytes, sha256 ${received.sha256})`); + sendJson(res, 201, { path: target, sha256: received.sha256, size: received.size, active: this.binary() === target }); + } finally { + await rm(temp, { force: true }); + } + } + + heartbeat(): void { + for (const entry of this.streams) entry.res.write(": ping\n\n"); + } + + /** A revoked device: its streams end and its terminals are closed. */ + closeDevice(deviceId: string): void { + for (const entry of [...this.streams]) if (entry.deviceId === deviceId) this.stopStream(entry); + // Its terminals live only in a running host: never start one just to close nothing. + const terms = this.hostMayRun() ? Object.entries(this.owners).filter(([, owner]) => owner === deviceId).map(([term]) => term) : []; + for (const term of terms) { + void this.closeTerm(term).catch((error: unknown) => this.log(`terminal ${term}: close on revoke failed: ${error instanceof Error ? error.message : String(error)}`)); + } + } + + /** A device paired again replaces its earlier pairing `from`: the terminals `from` opened are `to`'s now. */ + adopt(from: string, to: string): void { + let moved = false; + for (const [term, owner] of Object.entries(this.owners)) { + if (owner !== from) continue; + this.owners[term] = to; + moved = true; + } + if (moved) this.saveOwners(); + } + + /** The server is stopping: streams and connections close; the host and its terminals keep running. */ + closeAll(): void { + this.closed = true; + for (const entry of [...this.streams]) this.stopStream(entry); + this.control?.close(); + } +} + +function size(value: unknown, name: string, max: number): number { + if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max) throw new HttpError(400, `invalid_${name}`, `${name} must be a whole number 1-${max}`); + return value; +} diff --git a/lib/serve-tls.ts b/lib/serve-tls.ts new file mode 100644 index 000000000..5e61a1279 --- /dev/null +++ b/lib/serve-tls.ts @@ -0,0 +1,450 @@ +// TLS for `gentle-shell serve` on the network: a self-signed ECDSA P-256 +// certificate made on first run (a minimal DER encoder builds the X.509 here, +// no dependencies), kept owner-only in `/serve/tls/`, and pinned by +// clients through its SHA-256 fingerprint. A client that found the server +// through untrusted discovery checks a pairing proof before it sends the +// pairing code: only a server that knows the code can bind it to the +// fingerprint the client saw in the handshake. Listeners here speak TLS to the +// network and keep plain HTTP for connections from this machine. + +import { createHash, createHmac, createPrivateKey, generateKeyPairSync, randomBytes, scrypt, sign, timingSafeEqual, X509Certificate } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { createServer as createHttpServer, type IncomingMessage, type Server as HttpServer } from "node:http"; +import { createServer as createHttpsServer, type Server as HttpsServer } from "node:https"; +import { createServer as createNetServer, isIPv4, isIPv6, type Server as NetServer, type Socket } from "node:net"; +import { connect as tlsConnect, type TLSSocket } from "node:tls"; +import { join } from "node:path"; +import { normalizePairingCode } from "./serve-auth.ts"; + +// --- DER --------------------------------------------------------------------------- + +function derLength(length: number): Buffer { + if (length < 0x80) return Buffer.from([length]); + const bytes: number[] = []; + for (let n = length; n > 0; n >>= 8) bytes.unshift(n & 0xff); + return Buffer.from([0x80 | bytes.length, ...bytes]); +} + +/** One DER TLV: tag, length, the concatenated content. */ +export function der(tag: number, ...content: Buffer[]): Buffer { + const body = Buffer.concat(content); + return Buffer.concat([Buffer.from([tag]), derLength(body.length), body]); +} + +const sequence = (...content: Buffer[]) => der(0x30, ...content); +const set = (...content: Buffer[]) => der(0x31, ...content); +const octets = (value: Buffer) => der(0x04, value); +const bits = (value: Buffer, unused = 0) => der(0x03, Buffer.from([unused]), value); +const bool = (value: boolean) => der(0x01, Buffer.from([value ? 0xff : 0x00])); +const explicit = (n: number, content: Buffer) => der(0xa0 + n, content); + +function oid(dotted: string): Buffer { + const arcs = dotted.split(".").map(Number); + const out = [arcs[0] * 40 + arcs[1]]; + for (const arc of arcs.slice(2)) { + const chunk = [arc & 0x7f]; + for (let n = Math.floor(arc / 128); n > 0; n = Math.floor(n / 128)) chunk.unshift(0x80 | (n & 0x7f)); + out.push(...chunk); + } + return der(0x06, Buffer.from(out)); +} + +/** A non-negative INTEGER from big-endian bytes: leading zeros dropped, one added when the high bit is set. */ +function integer(value: Buffer): Buffer { + let start = 0; + while (start < value.length - 1 && value[start] === 0) start += 1; + const trimmed = value.subarray(start); + return der(0x02, trimmed[0] & 0x80 ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed); +} + +/** UTCTime through 2049, GeneralizedTime after (RFC 5280 §4.1.2.5). */ +function time(date: Date): Buffer { + const two = (n: number) => String(n).padStart(2, "0"); + const rest = `${two(date.getUTCMonth() + 1)}${two(date.getUTCDate())}${two(date.getUTCHours())}${two(date.getUTCMinutes())}${two(date.getUTCSeconds())}Z`; + const year = date.getUTCFullYear(); + return year < 2050 ? der(0x17, Buffer.from(`${two(year % 100)}${rest}`, "ascii")) : der(0x18, Buffer.from(`${year}${rest}`, "ascii")); +} + +/** The 4 or 16 bytes of an IP literal (brackets and an IPv6 zone ignored); undefined for anything else. */ +export function ipBytes(address: string): Buffer | undefined { + const ip = address.replace(/^\[|\]$/g, "").replace(/%.*$/, ""); + if (isIPv4(ip)) return Buffer.from(ip.split(".").map(Number)); + if (!isIPv6(ip)) return undefined; + let text = ip; + const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(text); + if (v4) { + const [a, b, c, d] = v4[1].split(".").map(Number); + text = `${text.slice(0, -v4[1].length)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; + } + const [head, tail] = text.split("::"); + const left = head ? head.split(":") : []; + const right = tail === undefined ? [] : tail ? tail.split(":") : []; + const groups = tail === undefined ? left : [...left, ...Array(8 - left.length - right.length).fill("0"), ...right]; + const out = Buffer.alloc(16); + groups.forEach((g, i) => out.writeUInt16BE(Number.parseInt(g, 16), i * 2)); + return out; +} + +// --- certificate ------------------------------------------------------------------- + +export const SERVE_TLS_LIMITS = { + validityYears: 10, + /** A certificate this close to its end is replaced at start. */ + renewBeforeMs: 30 * 24 * 60 * 60_000, +}; + +const OID = { + ecdsaWithSha256: "1.2.840.10045.4.3.2", + commonName: "2.5.4.3", + basicConstraints: "2.5.29.19", + keyUsage: "2.5.29.15", + extKeyUsage: "2.5.29.37", + subjectAltName: "2.5.29.17", + serverAuth: "1.3.6.1.5.5.7.3.1", +}; + +export interface CertificateRequest { + commonName: string; + /** DNS names for the subjectAltName. */ + dnsNames: readonly string[]; + /** IP literals for the subjectAltName. */ + ips: readonly string[]; + now?: Date; +} + +/** Base64url (no padding) SHA-256 of the certificate's DER: what clients pin. */ +export function certificateFingerprint(derBytes: Buffer): string { + return createHash("sha256").update(derBytes).digest("base64url"); +} + +function pem(label: string, body: Buffer): string { + const lines = body.toString("base64").match(/.{1,64}/g) ?? []; + return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`; +} + +/** + * A self-signed X.509 v3 server certificate on a fresh P-256 key: a random + * serial, valid from an hour ago for ten years, CA false, digitalSignature, + * serverAuth, and every name and address given as subjectAltName. + */ +export function createSelfSignedCertificate(request: CertificateRequest): { certPem: string; keyPem: string; der: Buffer } { + const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" }); + const serial = randomBytes(16); + serial[0] = (serial[0] & 0x7f) | 0x01; + const algorithm = sequence(oid(OID.ecdsaWithSha256)); + const name = sequence(set(sequence(oid(OID.commonName), der(0x0c, Buffer.from(request.commonName.slice(0, 64), "utf8"))))); + const notBefore = new Date((request.now ?? new Date()).getTime() - 60 * 60_000); + const notAfter = new Date(notBefore); + notAfter.setUTCFullYear(notAfter.getUTCFullYear() + SERVE_TLS_LIMITS.validityYears); + const names: Buffer[] = []; + for (const dns of new Set(request.dnsNames.map((n) => n.toLowerCase()))) if (/^[\x21-\x7e]{1,253}$/.test(dns)) names.push(der(0x82, Buffer.from(dns, "ascii"))); + const seen = new Set(); + for (const ip of request.ips) { + const raw = ipBytes(ip); + if (raw && !seen.has(raw.toString("hex"))) { + seen.add(raw.toString("hex")); + names.push(der(0x87, raw)); + } + } + const extensions = sequence( + sequence(oid(OID.basicConstraints), bool(true), octets(sequence())), + sequence(oid(OID.keyUsage), bool(true), octets(bits(Buffer.from([0x80]), 7))), + sequence(oid(OID.extKeyUsage), octets(sequence(oid(OID.serverAuth)))), + ...(names.length > 0 ? [sequence(oid(OID.subjectAltName), octets(sequence(...names)))] : []), + ); + const tbs = sequence( + explicit(0, integer(Buffer.from([2]))), + integer(serial), + algorithm, + name, + sequence(time(notBefore), time(notAfter)), + name, + publicKey.export({ type: "spki", format: "der" }), + explicit(3, extensions), + ); + const certificate = sequence(tbs, algorithm, bits(sign("sha256", tbs, privateKey))); + return { certPem: pem("CERTIFICATE", certificate), keyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(), der: certificate }; +} + +/** The server's TLS identity: PEMs for the listeners, the DER and its fingerprint for clients. */ +export interface ServeTlsIdentity { + certPem: string; + keyPem: string; + der: Buffer; + /** Base64url SHA-256 of `der`. */ + fingerprint: string; + notAfter: Date; + /** Whether this run made it (first run, or the old one was unusable or near its end). */ + created: boolean; +} + +export function serveTlsFiles(serveDir: string) { + const dir = join(serveDir, "tls"); + return { dir, cert: join(dir, "cert.pem"), key: join(dir, "key.pem") }; +} + +function writePrivate(path: string, text: string): void { + const temp = `${path}.${process.pid}.tmp`; + writeFileSync(temp, text, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } +} + +function readIdentity(certPath: string, keyPath: string, now: number): ServeTlsIdentity | undefined { + if (!existsSync(certPath) || !existsSync(keyPath)) return undefined; + try { + const certPem = readFileSync(certPath, "utf8"); + const keyPem = readFileSync(keyPath, "utf8"); + const cert = new X509Certificate(certPem); + const notAfter = new Date(cert.validTo); + if (!cert.checkPrivateKey(createPrivateKey(keyPem)) || notAfter.getTime() - now < SERVE_TLS_LIMITS.renewBeforeMs) return undefined; + return { certPem, keyPem, der: cert.raw, fingerprint: certificateFingerprint(cert.raw), notAfter, created: false }; + } catch { + return undefined; + } +} + +/** + * The certificate in `/tls/`, made when missing, unreadable, not + * matching its key, or within 30 days of its end. Names and addresses are a + * snapshot of the first run: clients pin the fingerprint, not the names, so a + * changed address never replaces it (that would break every paired device). + */ +export function loadOrCreateServeTls(serveDir: string, request: Omit, now: () => number = Date.now): ServeTlsIdentity { + const files = serveTlsFiles(serveDir); + const existing = readIdentity(files.cert, files.key, now()); + if (existing) return existing; + mkdirSync(files.dir, { recursive: true, mode: 0o700 }); + try { chmodSync(files.dir, 0o700); } catch { /* Windows */ } + const made = createSelfSignedCertificate({ ...request, now: new Date(now()) }); + writePrivate(files.key, made.keyPem); + writePrivate(files.cert, made.certPem); + const cert = new X509Certificate(made.der); + return { certPem: made.certPem, keyPem: made.keyPem, der: made.der, fingerprint: certificateFingerprint(made.der), notAfter: new Date(cert.validTo), created: true }; +} + +// --- pairing proof ----------------------------------------------------------------- + +/** + * `POST /api/pair/proof`. The key is stretched with scrypt because a proof is + * a function of a 40-bit code: with plain HMAC anyone could ask for one and + * search every code offline in minutes. Every number here is part of the contract. + */ +export const PAIR_PROOF = { + salt: "gentle-shell/pair-proof/v1", + N: 32768, + r: 8, + p: 1, + keyBytes: 32, + /** Nonce bytes after base64url decoding. */ + nonceMinBytes: 16, + nonceMaxBytes: 64, + /** Proof requests answered per window across all callers (like failed pairings). */ + perWindow: 20, + windowMs: 60_000, +}; + +/** scrypt(P = normalized code as ASCII, S = "gentle-shell/pair-proof/v1" || raw fingerprint, N=32768, r=8, p=1, 32 bytes). */ +export function pairProofKey(code: string, fingerprint: Buffer): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + scrypt(Buffer.from(normalizePairingCode(code), "ascii"), Buffer.concat([Buffer.from(PAIR_PROOF.salt, "ascii"), fingerprint]), PAIR_PROOF.keyBytes, + { N: PAIR_PROOF.N, r: PAIR_PROOF.r, p: PAIR_PROOF.p, maxmem: 64 * 1024 * 1024 }, (error, key) => (error ? reject(error) : resolve(key))); + return promise; +} + +/** HMAC-SHA256(key, raw fingerprint || nonce). */ +export function pairProof(key: Buffer, fingerprint: Buffer, nonce: Buffer): Buffer { + return createHmac("sha256", key).update(fingerprint).update(nonce).digest(); +} + +/** Decodes a base64url fingerprint; undefined unless it is 32 bytes. */ +export function fingerprintBytes(fingerprint: string): Buffer | undefined { + if (!/^[A-Za-z0-9_-]{43}$/.test(fingerprint)) return undefined; + const raw = Buffer.from(fingerprint, "base64url"); + return raw.length === 32 ? raw : undefined; +} + +/** The client's check: one of `proofs` binds `code` to the fingerprint it saw in the handshake. */ +export async function verifyPairProof(input: { code: string; fingerprint: string; nonce: Buffer; proofs: readonly unknown[] }): Promise { + const fp = fingerprintBytes(input.fingerprint); + if (!fp) return false; + const expected = pairProof(await pairProofKey(input.code, fp), fp, input.nonce); + let match = false; + for (const proof of input.proofs) { + if (typeof proof !== "string") continue; + const given = Buffer.from(proof, "base64url"); + if (given.length === expected.length && timingSafeEqual(given, expected)) match = true; + } + return match; +} + +/** Proof keys for the live codes (one scrypt per code, cached) and the global request budget. */ +export class PairProofs { + private readonly fingerprint: Buffer; + private readonly now: () => number; + private readonly keys = new Map>(); + private requests: number[] = []; + constructor(fingerprint: string, now: () => number = Date.now) { + const fp = fingerprintBytes(fingerprint); + if (!fp) throw new Error("bad certificate fingerprint"); + this.fingerprint = fp; + this.now = now; + } + + /** False once `perWindow` requests came within the window. */ + allow(): boolean { + const now = this.now(); + this.requests = this.requests.filter((t) => now - t < PAIR_PROOF.windowMs); + if (this.requests.length >= PAIR_PROOF.perWindow) return false; + this.requests.push(now); + return true; + } + + /** One base64url proof per live code, in random order. */ + async proofs(codes: readonly string[], nonce: Buffer): Promise { + const live = new Set(codes.map(normalizePairingCode)); + for (const code of this.keys.keys()) if (!live.has(code)) this.keys.delete(code); + const keys = await Promise.all([...live].map((code) => { + let key = this.keys.get(code); + if (!key) this.keys.set(code, (key = pairProofKey(code, this.fingerprint))); + return key; + })); + const out = keys.map((key) => pairProof(key, this.fingerprint, nonce).toString("base64url")); + for (let i = out.length - 1; i > 0; i -= 1) { + const j = randomBytes(4).readUInt32BE() % (i + 1); + [out[i], out[j]] = [out[j], out[i]]; + } + return out; + } +} + +// --- listeners --------------------------------------------------------------------- + +/** How a connection reached a listener: plain HTTP from this machine, TLS, or TLS through a relay. */ +export type ConnectionVia = "plain" | "tls" | "relay"; + +export interface ServeTlsMaterial { + certPem: string; + keyPem: string; +} + +/** `https` when the request came over TLS (directly or through a relay), else `http`. */ +export function requestScheme(req: IncomingMessage): "http" | "https" { + return "encrypted" in req.socket && req.socket.encrypted === true ? "https" : "http"; +} + +/** Whether the peer is this machine: a loopback address, or the address it connected to (a remote host cannot have ours). */ +export function isLocalPeer(socket: Pick): boolean { + const remote = (socket.remoteAddress ?? "").replace(/^::ffff:/i, ""); + const local = (socket.localAddress ?? "").replace(/^::ffff:/i, ""); + if (remote === "") return false; + return remote === "::1" || /^127\./.test(remote) || remote === local; +} + +/** The first byte of a TLS ClientHello record. */ +const TLS_HANDSHAKE = 0x16; +const SNIFF_TIMEOUT_MS = 20_000; +const TLS_REQUIRED = JSON.stringify({ error: { code: "tls_required", message: "This server speaks HTTPS on the network: connect with https:// and pin its certificate fingerprint" } }); + +export interface ServeListener { + /** Listen, address and close on this one. */ + server: NetServer; + /** A connection a relay spliced to this listener: always TLS, never plain. */ + acceptRelayed(socket: Socket): void; + /** Ends every open connection (after `server.close()`). */ + closeAllConnections(): void; +} + +/** + * One listening socket for an HTTP API: without `tls`, plain HTTP for every + * peer; with it, TLS for every peer, plus plain HTTP from this machine (the + * first byte tells them apart), so local tools keep `http://127.0.0.1`. A + * network peer that speaks plain HTTP gets `400 tls_required`. `setup` gets + * each underlying HTTP server once, with how its connections arrive. + */ +export function createServeListener(options: { tls?: ServeTlsMaterial; setup: (server: HttpServer | HttpsServer, via: ConnectionVia) => void; onConnection?: (socket: Socket) => void }): ServeListener { + const sockets = new Set(); + const plain = createHttpServer(); + options.setup(plain, "plain"); + const tlsOptions = options.tls ? { key: options.tls.keyPem, cert: options.tls.certPem, minVersion: "TLSv1.2" as const, ALPNProtocols: ["http/1.1"] } : undefined; + const secure = tlsOptions ? createHttpsServer(tlsOptions) : undefined; + if (secure) options.setup(secure, "tls"); + let relayed: HttpsServer | undefined; + const track = (socket: Socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + options.onConnection?.(socket); + }; + const server = createNetServer({ pauseOnConnect: false }, (socket) => { + track(socket); + socket.on("error", () => socket.destroy()); + if (!secure) return void plain.emit("connection", socket); + const local = isLocalPeer(socket); + const timer = setTimeout(() => socket.destroy(), SNIFF_TIMEOUT_MS); + socket.once("data", (chunk: Buffer) => { + clearTimeout(timer); + socket.pause(); + socket.unshift(chunk); + if (chunk[0] === TLS_HANDSHAKE) secure.emit("connection", socket); + else if (local) plain.emit("connection", socket); + else return void socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(TLS_REQUIRED)}\r\nConnection: close\r\n\r\n${TLS_REQUIRED}`); + process.nextTick(() => socket.resume()); + }); + }); + return { + server, + acceptRelayed(socket) { + if (!tlsOptions) return void socket.destroy(); + if (!relayed) { + relayed = createHttpsServer(tlsOptions); + options.setup(relayed, "relay"); + } + track(socket); + socket.on("error", () => socket.destroy()); + relayed.emit("connection", socket); + }, + closeAllConnections() { + for (const s of [plain, secure, relayed]) { + if (!s) continue; + s.closeAllConnections(); + s.close(() => {}); + } + for (const socket of sockets) socket.destroy(); + }, + }; +} + +// --- client side ------------------------------------------------------------------- + +/** + * A TLS connection that ends unless the server's certificate has `fingerprint` + * (base64url SHA-256 of its DER): the check is the certificate, not a CA or a + * name. Resolves after the handshake, before a byte of the request is sent. + */ +export function connectPinned(target: { host: string; port: number } | { socket: Socket }, fingerprint: string): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const socket = tlsConnect({ ...target, rejectUnauthorized: false, ALPNProtocols: ["http/1.1"] }); + socket.once("error", reject); + socket.once("secureConnect", () => { + const seen = certificateFingerprint(socket.getPeerCertificate(false).raw); + if (seen !== fingerprint) { + socket.destroy(); + return reject(Object.assign(new Error(`certificate fingerprint ${seen} is not the pinned ${fingerprint}`), { code: "fingerprint_mismatch", seen })); + } + socket.off("error", reject); + resolve(socket); + }); + return promise; +} + +/** The fingerprint a TLS server presents, trusting nothing yet (first contact, before a pairing proof). */ +export function peekFingerprint(target: { host: string; port: number } | { socket: Socket }): Promise<{ socket: TLSSocket; fingerprint: string }> { + const { promise, resolve, reject } = Promise.withResolvers<{ socket: TLSSocket; fingerprint: string }>(); + const socket = tlsConnect({ ...target, rejectUnauthorized: false, ALPNProtocols: ["http/1.1"] }); + socket.once("error", reject); + socket.once("secureConnect", () => { + socket.off("error", reject); + resolve({ socket, fingerprint: certificateFingerprint(socket.getPeerCertificate(false).raw) }); + }); + return promise; +} diff --git a/lib/serve-upgrade.ts b/lib/serve-upgrade.ts new file mode 100644 index 000000000..8b4357d7c --- /dev/null +++ b/lib/serve-upgrade.ts @@ -0,0 +1,238 @@ +// `gentle-shell serve`'s self-upgrade (`POST /api/upgrade`, admin): runs the +// same `gentle-shell upgrade` a person would on this machine, streams its +// output to admin clients (`GET /api/upgrade/:jobId/stream`, SSE `line` and +// `finished`), and on success asks the server to restart itself on the new +// version. Session keepers and the terminal host are separate processes and +// keep running; the next server reattaches them. +// +// The same runner also runs Gentle Shell's own setup for the server's home +// (`POST /api/setup`, admin; `GET /api/setup/:jobId/stream`): the companion +// packages a `gentle-shell setup` installs there. Setup never replaces the +// launcher, so it never restarts the server. One job at a time, upgrade or setup. + +import { spawn, type ChildProcess } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import { HttpError, sseEvent, startSse } from "./serve-http.ts"; +import type { SessionLaunch } from "./serve-session.ts"; + +export const SERVE_UPGRADE_LIMITS = { + /** Output lines kept for a stream that connects late; older ones are dropped. */ + lines: 2000, + line: 2000, + error: 300, + /** An upgrade still running then is stopped. */ + timeoutMs: 30 * 60_000, + /** Time for the `finished` event to reach clients before the server restarts. */ + restartDelayMs: 500, + heartbeatMs: 20_000, +}; + +export const UPGRADE_CHANNELS = ["release", "main"] as const; +export type UpgradeChannel = (typeof UPGRADE_CHANNELS)[number]; + +export interface ServeUpgradeOptions { + /** The upgrade command: `gentle-shell upgrade [--channel ]` in production. */ + launch: (channel: UpgradeChannel | undefined) => SessionLaunch; + /** The version installed after a successful upgrade, when it can be read. */ + installedVersion?: () => string | undefined; + /** A successful upgrade's `finished` was sent: restart on the new version. */ + onUpgraded: () => void; + /** The setup command: `gentle-shell [home flags] setup` in production. Without it the server has no `setup` capability. */ + setup?: () => SessionLaunch; + /** A job ended, before its `finished` is sent (the server forgets its cached readiness checks). */ + onFinished?: (kind: ServeJobKind) => void; + limits?: Partial; + log?: (line: string) => void; +} + +export interface UpgradeFinished { + ok: boolean; + error?: string; + version?: string; +} + +export type ServeJobKind = "upgrade" | "setup"; + +interface UpgradeJob { + kind: ServeJobKind; + jobId: string; + lines: string[]; + finished?: UpgradeFinished; + streams: Set; + child?: ChildProcess; +} + +export const UPGRADE_JOB_ID = /^upg_[0-9a-f]{16}$/; +export const SETUP_JOB_ID = /^setup_[0-9a-f]{16}$/; +const JOB_ID_PREFIX: Record = { upgrade: "upg_", setup: "setup_" }; + +// eslint-disable-next-line no-control-regex +const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-Z\\-_]/g; + +/** Output text as lines: no color codes, no control characters, no blank lines, each bounded. */ +export function upgradeLines(text: string, limit: number = SERVE_UPGRADE_LIMITS.line): string[] { + const lines: string[] = []; + for (const raw of text.replace(ANSI, "").split(/\r\n|\r|\n/)) { + // eslint-disable-next-line no-control-regex + const line = raw.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "").trimEnd(); + if (line.trim().length > 0) lines.push(line.length > limit ? `${line.slice(0, limit - 1)}…` : line); + } + return lines; +} + +export class UpgradeService { + private job: UpgradeJob | undefined; + private readonly limits: typeof SERVE_UPGRADE_LIMITS; + private readonly heartbeat: NodeJS.Timeout; + private readonly options: ServeUpgradeOptions; + private closed = false; + + constructor(options: ServeUpgradeOptions) { + this.options = options; + this.limits = { ...SERVE_UPGRADE_LIMITS, ...options.limits }; + this.heartbeat = setInterval(() => { + for (const res of this.job?.streams ?? []) res.write(": ping\n\n"); + }, this.limits.heartbeatMs); + this.heartbeat.unref(); + } + + running(): boolean { + return this.job !== undefined && this.job.finished === undefined; + } + + /** Whether this server can run setup (the `setup` capability). */ + canSetup(): boolean { + return this.options.setup !== undefined; + } + + /** Starts the upgrade; `409 upgrade_running` / `setup_running` while a job runs. */ + start(channel: UpgradeChannel | undefined): { jobId: string } { + this.claim(); + return this.run("upgrade", this.options.launch(channel), channel === undefined ? "" : ` (channel ${channel})`); + } + + /** Starts Gentle Shell's setup for the server's home; same one-job rule as the upgrade. */ + startSetup(): { jobId: string } { + const setup = this.options.setup; + if (!setup) throw new HttpError(501, "not_supported", "This server cannot run setup"); + this.claim(); + return this.run("setup", setup(), ""); + } + + private claim(): void { + if (this.closed) throw new HttpError(503, "server_stopping", "The server is stopping"); + const job = this.job; + if (job && job.finished === undefined) { + throw new HttpError(409, `${job.kind}_running`, job.kind === "upgrade" ? "An upgrade is already running" : "Setup is already running"); + } + } + + private run(kind: ServeJobKind, launch: SessionLaunch, detail: string): { jobId: string } { + const previous = this.job; + for (const res of previous?.streams ?? []) res.end(); + const job: UpgradeJob = { kind, jobId: `${JOB_ID_PREFIX[kind]}${randomBytes(8).toString("hex")}`, lines: [], streams: new Set() }; + this.job = job; + this.options.log?.(`${kind} ${job.jobId}: started${detail}`); + let child: ChildProcess; + try { + child = spawn(launch.command, launch.args, { cwd: launch.cwd, env: launch.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + } catch (error) { + queueMicrotask(() => this.finish(job, { ok: false, error: error instanceof Error ? error.message : String(error) })); + return { jobId: job.jobId }; + } + job.child = child; + const errors: string[] = []; + const read = (stream: NodeJS.ReadableStream | null, isError: boolean) => { + let rest = ""; + const emit = (text: string) => { + for (const line of upgradeLines(text, this.limits.line)) { + if (isError) errors.push(line); + this.line(job, line); + } + }; + stream?.setEncoding("utf8"); + stream?.on("data", (chunk: string) => { + const text = rest + chunk; + const cut = Math.max(text.lastIndexOf("\n"), text.lastIndexOf("\r")); + rest = cut === -1 ? text : text.slice(cut + 1); + if (cut !== -1) emit(text.slice(0, cut + 1)); + }); + stream?.on("end", () => { + emit(rest); + rest = ""; + }); + }; + read(child.stdout, false); + read(child.stderr, true); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGTERM"); + setTimeout(() => child.kill("SIGKILL"), 5000).unref(); + }, this.limits.timeoutMs); + timer.unref(); + child.once("error", (error) => { + clearTimeout(timer); + this.finish(job, { ok: false, error: error.message }); + }); + child.once("close", (code, signal) => { + clearTimeout(timer); + if (code === 0) { + let version: string | undefined; + try { + if (job.kind === "upgrade") version = this.options.installedVersion?.(); + } catch { /* unknown until the new server answers GET /api/server */ } + this.finish(job, { ok: true, ...(version === undefined ? {} : { version }) }); + return; + } + const last = errors.at(-1) ?? job.lines.at(-1); + const error = timedOut ? `The ${job.kind} ran past its time limit` : last ?? (signal ? `Stopped by ${signal}` : `Exited with code ${code}`); + this.finish(job, { ok: false, error: error.length > this.limits.error ? `${error.slice(0, this.limits.error - 1)}…` : error }); + }); + return { jobId: job.jobId }; + } + + private line(job: UpgradeJob, line: string): void { + job.lines.push(line); + if (job.lines.length > this.limits.lines) job.lines.shift(); + const event = sseEvent("line", { line }); + for (const res of job.streams) res.write(event); + } + + private finish(job: UpgradeJob, finished: UpgradeFinished): void { + if (job.finished) return; + job.finished = finished; + job.child = undefined; + this.options.log?.(`${job.kind} ${job.jobId}: ${finished.ok ? `done${finished.version === undefined ? "" : ` (${finished.version})`}` : `failed: ${finished.error}`}`); + // Before `finished` reaches a client, so what it asks next reflects the job. + this.options.onFinished?.(job.kind); + const event = sseEvent("finished", finished); + for (const res of job.streams) res.end(event); + job.streams.clear(); + if (job.kind === "upgrade" && finished.ok && !this.closed) setTimeout(() => this.options.onUpgraded(), this.limits.restartDelayMs).unref(); + } + + /** SSE: the lines so far, then live ones, then `finished`, then the stream ends. */ + stream(req: IncomingMessage, res: ServerResponse, jobId: string): void { + const job = this.job; + if (!job || job.jobId !== jobId) throw new HttpError(404, "not_found", "No such job"); + startSse(req, res); + res.write("retry: 3000\n\n"); + for (const line of job.lines) res.write(sseEvent("line", { line })); + if (job.finished) { + res.end(sseEvent("finished", job.finished)); + return; + } + job.streams.add(res); + res.on("close", () => job.streams.delete(res)); + } + + /** The server is stopping: streams end; a running job goes on to its end, as a CLI one would. */ + close(): void { + this.closed = true; + clearInterval(this.heartbeat); + for (const res of this.job?.streams ?? []) res.end(); + this.job?.streams.clear(); + } +} diff --git a/lib/serve-uploads.ts b/lib/serve-uploads.ts new file mode 100644 index 000000000..df3dcee98 --- /dev/null +++ b/lib/serve-uploads.ts @@ -0,0 +1,97 @@ +// Uploads for `gentle-shell serve`: a client sends a file it wants the agent +// to see (a chat attachment, a screenshot, a log) and gets back its path on +// the server, under `/serve/uploads///`. +// Uploads are owner-only and removed after 7 days. + +import { randomBytes } from "node:crypto"; +import { mkdir, readdir, rm, rmdir, stat } from "node:fs/promises"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import { join } from "node:path"; +import type { Principal } from "./serve-auth.ts"; +import { fsHttpError, need, receiveBodyToFile, sendJson } from "./serve-http.ts"; + +export const SERVE_UPLOAD_LIMITS = { + bytes: 64 * 1024 * 1024, + /** An upload older than this is removed. */ + maxAgeMs: 7 * 24 * 60 * 60_000, + sweepMs: 60 * 60_000, + /** UTF-8 bytes of a file name. */ + nameBytes: 200, +}; + +/** + * A file name from a client: its last path component, without control + * characters or characters Windows forbids, at most `maxBytes` UTF-8 bytes; + * `upload` when nothing usable is left. + */ +export function cleanUploadName(raw: string | null, maxBytes = SERVE_UPLOAD_LIMITS.nameBytes): string { + const last = (raw ?? "").split(/[/\\]/).pop() ?? ""; + let name = last.replace(/[\u0000-\u001f\u007f<>:"|?*]/g, "_").trim(); + while (Buffer.byteLength(name, "utf8") > maxBytes) name = name.slice(0, -1); + return name === "" || name === "." || name === ".." ? "upload" : name; +} + +export interface UploadStoreOptions { + /** `/serve/uploads`. */ + dir: string; + limits?: Partial; + now?: () => number; + log?: (line: string) => void; +} + +export class UploadStore { + private readonly dir: string; + private readonly limits: typeof SERVE_UPLOAD_LIMITS; + private readonly now: () => number; + private readonly log: (line: string) => void; + private readonly timer: NodeJS.Timeout; + + constructor(options: UploadStoreOptions) { + this.dir = options.dir; + this.limits = { ...SERVE_UPLOAD_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.log = options.log ?? (() => {}); + this.timer = setInterval(() => void this.sweep(), this.limits.sweepMs); + this.timer.unref(); + void this.sweep(); + } + + /** `POST /api/uploads?name=`: the raw body becomes a new file; answers its path. */ + async upload(req: IncomingMessage, res: ServerResponse, url: URL, principal: Principal | undefined): Promise { + const who = need(principal, "sessions:operate"); + const name = cleanUploadName(url.searchParams.get("name")); + const folder = join(this.dir, who.deviceId, randomBytes(8).toString("hex")); + await mkdir(folder, { recursive: true, mode: 0o700 }).catch((error: unknown) => { throw fsHttpError(error, folder); }); + const path = join(folder, name); + try { + const { size, sha256 } = await receiveBodyToFile(req, path, this.limits.bytes, 0o600); + sendJson(res, 201, { path, name, size, sha256, expiresAt: new Date(this.now() + this.limits.maxAgeMs).toISOString() }); + } catch (error) { + await rm(folder, { recursive: true, force: true }); + throw fsHttpError(error, path); + } + } + + /** Removes uploads older than `maxAgeMs`, then device folders left empty. */ + async sweep(): Promise { + const cutoff = this.now() - this.limits.maxAgeMs; + const devices = await readdir(this.dir).catch(() => [] as string[]); + for (const device of devices) { + const deviceDir = join(this.dir, device); + const uploads = await readdir(deviceDir).catch(() => [] as string[]); + for (const upload of uploads) { + const folder = join(deviceDir, upload); + const stats = await stat(folder).catch(() => undefined); + if (stats && stats.mtimeMs < cutoff) { + await rm(folder, { recursive: true, force: true }); + this.log(`upload ${device}/${upload} expired`); + } + } + await rmdir(deviceDir).catch(() => { /* not empty */ }); + } + } + + close(): void { + clearInterval(this.timer); + } +} diff --git a/runtime/gentle-shell-launcher.mjs b/runtime/gentle-shell-launcher.mjs index 4a3f546dc..33c9044ec 100644 --- a/runtime/gentle-shell-launcher.mjs +++ b/runtime/gentle-shell-launcher.mjs @@ -153,8 +153,10 @@ export function parseLauncherArgs(argv ) { // token — once a pi subcommand (or any other passthrough token) has // already started, a later "setup" is just an ordinary passthrough // argument, same as "home" is. - if (arg === "setup" && command === undefined && passthrough.length === 0) { - command = "setup"; + // `serve` takes them too: one server per agent home, and its sessions + // run against the home those selectors resolve to. So does `relay`, whose secret lives in the home. + if ((arg === "setup" || arg === "serve" || arg === "relay") && command === undefined && passthrough.length === 0) { + command = arg; commandArgs = argv.slice(i + 1); break; } @@ -1480,6 +1482,8 @@ export function helpText() { " gentle-shell self-uninstall [--dry-run] [--yes] [--include-shared]", " gentle-shell desktop [--yes] [--no-open] | --status | --uninstall", " gentle-shell tower [--no-open] [--port ] [--json]", + " gentle-shell [home selectors] serve [--listen :] [--allow-host ]... [--foreground] | share | status | stop | pair | devices", + " gentle-shell [home selectors] relay --listen : [--secret-file ] [--json]", "", "Opens pi with the Gentle Shell package loaded, without touching your", "vanilla pi installation.", @@ -1536,6 +1540,15 @@ export function helpText() { " as a floor, in your browser. Prints the local URL and serves until Ctrl+C.", " --no-open only prints the URL; --port fixes the port (127.0.0.1 only);", " --json prints one JSON line with the URL instead, for programs.", + " serve Run a per-user server that owns Gentle Shell sessions (one '--mode rpc' child", + " each) so paired devices drive them over HTTP + Server-Sent Events, and they", + " outlive the client. 127.0.0.1 on a random port by default; every request", + " needs a device token. 'serve share' opens it to your network and prints one", + " code to paste in Gentle Shell GPUI. 'serve status', 'serve stop', 'serve pair", + " [--scope …]', 'serve devices [--revoke ]'; 'gentle-shell serve --help'.", + " relay Run a relay that lets devices outside a server's network reach it: servers", + " connect out to it ('serve share --relay gsr://host:port'), it splices raw TLS", + " streams and never sees their content. 'gentle-shell relay --help'.", "", "Managing packages:", " gentle-shell install npm: Run pi's own 'install' against the resolved home.", diff --git a/runtime/rpc-host.mjs b/runtime/rpc-host.mjs new file mode 100644 index 000000000..67eb96780 --- /dev/null +++ b/runtime/rpc-host.mjs @@ -0,0 +1,37 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// Interactive RPC host signal: the desktop app sets this environment variable +// on the pi process it spawns directly (`--mode rpc`), letting Gentle answer +// ask-user tools through pi's RPC dialogs and publish live subagent state. +// `lib/agents-runner.ts` strips it from every subagent child env so headless +// RPC children never see it and stay unaffected by this feature. + +/** Environment variable the desktop app sets on its own interactive pi process. */ +export const INTERACTIVE_HOST_ENV = "GENTLE_SHELL_INTERACTIVE_HOST"; + +/** + * True only when running under `--mode rpc` with the interactive host + * variable set to exactly `"1"`. Any other value, or its absence, keeps RPC + * headless (the existing subagent behaviour). + */ +export function isInteractiveRpcHost(mode , env = process.env) { + return mode === "rpc" && env[INTERACTIVE_HOST_ENV] === "1"; +} + +/** + * True for the interactive TUI, or for an interactive RPC host. Extensions + * use this to offer dialog-capable behaviour without special-casing RPC. + */ +export function isInteractiveMode(mode , env = process.env) { + return mode === "tui" || isInteractiveRpcHost(mode, env); +} + +/** + * Copy of `env` with the interactive host variable removed. Used when + * assembling a subagent child's environment so it never inherits the + * parent's interactive-host signal, even when the parent itself is one. + */ +export function withoutInteractiveHost(env ) { + const next = { ...env }; + delete next[INTERACTIVE_HOST_ENV]; + return next; +} diff --git a/runtime/serve-auth.mjs b/runtime/serve-auth.mjs new file mode 100644 index 000000000..cecc0f593 --- /dev/null +++ b/runtime/serve-auth.mjs @@ -0,0 +1,292 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// Authentication for `gentle-shell serve`: one-time pairing codes, per-device +// bearer tokens stored only as hashes in an owner-only file, short-lived +// single-use stream tickets for EventSource (which cannot send headers), and +// the local admin token the CLI reads from the owner-only server file. + +import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; + +export const SERVE_SCOPES = ["sessions:read", "sessions:operate", "terminal", "admin"] ; + +export const DEFAULT_PAIR_SCOPES = ["sessions:read", "sessions:operate", "terminal"]; + +export const SERVE_AUTH_LIMITS = { + pairingCodeTtlMs: 5 * 60_000, + ticketTtlMs: 60_000, + /** Failed `POST /api/pair` attempts allowed per window, across all callers. */ + pairFailures: 10, + pairFailureWindowMs: 60_000, + /** Live pairing codes and tickets held at once; the oldest is dropped past this. */ + maxCodes: 16, + maxTickets: 256, + maxDevices: 64, + deviceNameChars: 64, + /** `lastUsedAt` is persisted at most this often per device. */ + lastUsedPersistMs: 60_000, +}; + +const DEVICES_SCHEMA = "gentle-shell.serve.devices/v1"; +const CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // Crockford base32: no I, L, O, U + +export function isServeScope(value ) { + return typeof value === "string" && (SERVE_SCOPES ).includes(value); +} + +export function hashSecret(secret ) { + return createHash("sha256").update(secret, "utf8").digest(); +} + +/** Constant-time over equal-length digests, so neither length nor content leaks. */ +export function sameSecret(given , expected ) { + if (typeof given !== "string" || given.length === 0) return false; + return timingSafeEqual(hashSecret(given), hashSecret(expected)); +} + +function matchesHash(given , storedHex ) { + const stored = Buffer.from(storedHex, "hex"); + return stored.length === given.length && timingSafeEqual(stored, given); +} + + + + + + + + + + + + + + + + + + + + +export function hasScope(principal , scope ) { + return principal.scopes.includes(scope); +} + +/** Normalizes a typed code: case-insensitive, separators ignored, O/I/L read as 0/1/1. */ +export function normalizePairingCode(code ) { + return code.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1"); +} + +function newPairingCode() { + const bytes = randomBytes(8); + let out = ""; + for (const b of bytes) out += CODE_ALPHABET[b & 31]; + return `${out.slice(0, 4)}-${out.slice(4)}`; +} + +function writePrivateJson(path , value ) { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + writeFileSync(temp, `${JSON.stringify(value, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } +} + +function parseDevices(text ) { + const parsed = JSON.parse(text) ; + if (parsed?.schema !== DEVICES_SCHEMA || !Array.isArray(parsed.devices)) throw new Error("unrecognized devices file"); + return parsed.devices.filter((d) => !!d && typeof d === "object" + && typeof d.id === "string" && typeof d.name === "string" && typeof d.tokenHash === "string" && /^[0-9a-f]{64}$/.test(d.tokenHash) + && typeof d.createdAt === "string" && Array.isArray(d.scopes) && d.scopes.every(isServeScope)); +} + +/** Reads the devices file; a missing file is no devices. */ +export function readDevicesFile(path ) { + if (!existsSync(path)) return []; + return parseDevices(readFileSync(path, "utf8")); +} + +export function writeDevicesFile(path , devices ) { + writePrivateJson(path, { schema: DEVICES_SCHEMA, devices }); +} + +export function publicDevice(device ) { + const { tokenHash: _hash, ...rest } = device; + return rest; +} + + + + + + + + + + + + + + + + + + + + + + + + + +export class ServeAuth { + devicesFile ; + adminToken ; + now ; + limits ; + devices ; + /** Keyed by the code's hash, so a lookup never compares the code itself. */ + codes = new Map (); + tickets = new Map (); + persistedUse = new Map (); + revokeListeners = []; + failures = []; + + constructor(options ) { + this.devicesFile = options.devicesFile; + this.adminToken = options.adminToken; + this.now = options.now ?? Date.now; + this.limits = { ...SERVE_AUTH_LIMITS, ...options.limits }; + this.devices = readDevicesFile(this.devicesFile); + } + + onRevoke(listener ) { + this.revokeListeners.push(listener); + } + + /** Resolves a bearer token: the local admin token, or a paired device's. */ + authenticate(token ) { + if (!token) return undefined; + if (sameSecret(token, this.adminToken)) return { deviceId: "local", name: "local", scopes: SERVE_SCOPES }; + const digest = hashSecret(token); + let found ; + // Every stored hash is compared, so the time taken does not depend on which one matched. + for (const device of this.devices) if (matchesHash(digest, device.tokenHash)) found = device; + if (!found) return undefined; + this.touch(found); + return { deviceId: found.id, name: found.name, scopes: [...found.scopes] }; + } + + touch(device ) { + const now = this.now(); + device.lastUsedAt = new Date(now).toISOString(); + const last = this.persistedUse.get(device.id) ?? 0; + if (now - last < this.limits.lastUsedPersistMs) return; + this.persistedUse.set(device.id, now); + try { this.save(); } catch { /* usage time is advisory; auth never fails on it */ } + } + + save() { + writeDevicesFile(this.devicesFile, this.devices); + } + + mintPairingCode(scopes = DEFAULT_PAIR_SCOPES) { + this.prune(); + const code = newPairingCode(); + const entry = { scopes: [...new Set(scopes)], expiresAt: this.now() + this.limits.pairingCodeTtlMs }; + this.codes.set(hashSecret(normalizePairingCode(code)).toString("hex"), { ...entry, code: normalizePairingCode(code) }); + while (this.codes.size > this.limits.maxCodes) this.codes.delete(this.codes.keys().next().value ); + return { code, ...entry }; + } + + /** The live pairing codes, normalized: the pairing proof binds each to the server's certificate. */ + livePairingCodes() { + this.prune(); + return [...this.codes.values()].map((entry) => entry.code); + } + + /** Single use: the code is gone after the first attempt that names it, success or not. */ + redeem(code , name ) { + this.prune(); + const now = this.now(); + this.failures = this.failures.filter((t) => now - t < this.limits.pairFailureWindowMs); + if (this.failures.length >= this.limits.pairFailures) return { error: "rate_limited" }; + const key = typeof code === "string" && code.length <= 32 ? hashSecret(normalizePairingCode(code)).toString("hex") : undefined; + const entry = key === undefined ? undefined : this.codes.get(key); + if (!entry || key === undefined) { + this.failures.push(now); + return { error: "invalid_code" }; + } + this.codes.delete(key); + if (this.devices.length >= this.limits.maxDevices) return { error: "too_many_devices" }; + const token = `gss_${randomBytes(32).toString("base64url")}`; + const device = { + id: `dev_${randomUUID().replace(/-/g, "").slice(0, 16)}`, + name: cleanDeviceName(name), + scopes: entry.scopes, + tokenHash: hashSecret(token).toString("hex"), + createdAt: new Date(now).toISOString(), + }; + this.devices.push(device); + this.save(); + return { device: publicDevice(device), token }; + } + + listDevices() { + return this.devices.map(publicDevice); + } + + /** Takes effect at once: the token stops working, its tickets die and listeners close its streams. */ + revoke(deviceId ) { + const before = this.devices.length; + this.devices = this.devices.filter((d) => d.id !== deviceId); + if (this.devices.length === before) return false; + this.save(); + for (const [key, ticket] of this.tickets) if (ticket.principal.deviceId === deviceId) this.tickets.delete(key); + for (const listener of this.revokeListeners) listener(deviceId); + return true; + } + + mintTicket(principal , sessionId ) { + this.prune(); + const ticket = randomBytes(24).toString("base64url"); + const expiresAt = this.now() + this.limits.ticketTtlMs; + this.tickets.set(hashSecret(ticket).toString("hex"), { principal, sessionId, expiresAt }); + while (this.tickets.size > this.limits.maxTickets) this.tickets.delete(this.tickets.keys().next().value ); + return { ticket, expiresAt }; + } + + /** Single use and bound to one session. */ + redeemTicket(ticket , sessionId ) { + if (!ticket || ticket.length > 64) return undefined; + this.prune(); + const key = hashSecret(ticket).toString("hex"); + const entry = this.tickets.get(key); + if (!entry) return undefined; + this.tickets.delete(key); + return entry.sessionId === sessionId ? entry.principal : undefined; + } + + prune() { + const now = this.now(); + for (const [key, entry] of this.codes) if (entry.expiresAt <= now) this.codes.delete(key); + for (const [key, entry] of this.tickets) if (entry.expiresAt <= now) this.tickets.delete(key); + } +} + +export function cleanDeviceName(name ) { + const text = typeof name === "string" ? name.replace(/[\u0000-\u001f\u007f]/g, " ").trim() : ""; + return (text || "device").slice(0, SERVE_AUTH_LIMITS.deviceNameChars); +} + +/** Parses `--scope` values: comma lists, repeated flags; unknown names are an error. */ +export function parseScopes(values ) { + const scopes = []; + for (const value of values.flatMap((v) => v.split(","))) { + const scope = value.trim(); + if (!scope) continue; + if (!isServeScope(scope)) return { error: `unknown scope "${scope}" (expected ${SERVE_SCOPES.join(", ")})` }; + if (!scopes.includes(scope)) scopes.push(scope); + } + return scopes.length === 0 ? { error: "--scope needs at least one scope" } : { scopes }; +} diff --git a/runtime/serve-checks.mjs b/runtime/serve-checks.mjs new file mode 100644 index 000000000..f989f2fb9 --- /dev/null +++ b/runtime/serve-checks.mjs @@ -0,0 +1,290 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `GET /api/checks` for `gentle-shell serve` (`sessions:read`): whether this +// server has what its sessions need, the four rows Gentle Shell GPUI's own +// setup checklist shows (crates/app/src/features/setup: `extras.rs`, +// `gentle.rs`), with the same rules, so a device shows the server's setup the +// way it shows its own: Node.js (22.19.0 or newer, with npm), Git (not macOS's +// stub without the Command Line Tools), Engram (3.0.0 or newer; a broken +// `ENGRAM_BIN` override is reported) and the companion setup (the launcher's +// own `setup --check`). Each tool runs with a short timeout, all at once, +// never through a shell; one result is kept for `cacheMs`. + +import { execFile } from "node:child_process"; +import { constants as fsConstants, realpathSync } from "node:fs"; +import { access, readFile, stat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { delimiter, dirname, isAbsolute, join } from "node:path"; +import { launcherConfigPath, parseRawLauncherConfig, provisionedEntry } from "./gentle-shell-launcher.mjs"; + + +export const SERVE_CHECK_LIMITS = { + /** How long one result answers every request. */ + cacheMs: 10_000, + /** A tool's `--version` still running then is killed (and counts as not running). */ + toolTimeoutMs: 5_000, + /** `gentle-shell setup --check` starts Node and reads the home. */ + companionTimeoutMs: 15_000, + outputBytes: 64 * 1024, + detail: 300, +}; + +/** gentle-pi `engines.node`, as the app's `MIN_NODE`. */ +export const MIN_NODE = [22, 19, 0]; +/** gentle-engram accepts a stable Engram core from 3.0.0 (the app's `MIN_ENGRAM`). */ +export const MIN_ENGRAM = [3, 0, 0]; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** `v22.19.0`, `22.19`, `3.0.0-beta`: the leading numbers, as the app's `parse_version`. */ +export function parseVersion(text ) { + let rest = text.trim(); + if (rest.startsWith("go")) rest = rest.slice(2); + if (rest.startsWith("v")) rest = rest.slice(1); + const parts = [0, 0, 0]; + let found = 0; + for (const [i, part] of rest.split(".").slice(0, 3).entries()) { + const digits = /^\d*/.exec(part) [0]; + if (digits === "") break; + parts[i] = Number(digits); + found = i + 1; + if (digits.length !== part.length) break; + } + return found > 0 ? parts : undefined; +} + +export function showVersion(version ) { + return version.join("."); +} + +function older(a , b ) { + for (let i = 0; i < 3; i += 1) if (a[i] !== b[i]) return a[i] < b[i]; + return false; +} + +/** An executable named `name` (a path, or looked up on `env`'s PATH with Windows' extensions), or undefined. */ +export async function findProgram(name , env , platform = process.platform) { + const windows = platform === "win32"; + const extensions = windows ? ["", ...(env.PATHEXT ?? env.Pathext ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const runnable = async (path ) => { + try { + if (!(await stat(path)).isFile()) return false; + if (!windows) await access(path, fsConstants.X_OK); + return true; + } catch { + return false; + } + }; + const candidates = (base ) => extensions.map((ext) => base + ext); + if (isAbsolute(name) || name.includes("/") || (windows && name.includes("\\"))) { + for (const path of candidates(name)) if (await runnable(path)) return path; + return undefined; + } + const pathVar = env.PATH ?? env.Path ?? ""; + for (const dir of pathVar.split(windows ? ";" : delimiter)) { + if (dir === "") continue; + for (const path of candidates(join(dir, name))) if (await runnable(path)) return path; + } + return undefined; +} + + + + + + + + + +function run(command , args , options ) { + const { promise, resolve } = Promise.withResolvers (); + execFile(command, args, { env: options.env, cwd: options.cwd ?? homedir(), timeout: options.timeoutMs, killSignal: "SIGKILL", maxBuffer: options.outputBytes, windowsHide: true, encoding: "utf8" }, + (error, stdout) => { + const code = error ? (typeof error.code === "number" ? error.code : null) : 0; + resolve({ ok: !error, code, stdout: typeof stdout === "string" ? stdout : "" }); + }).stdin?.end(); + return promise; +} + +/** `settings.json` `packages` lists `name` (string or `{source}` entries, `npm:[@version]`), as the app's `settings_list`. */ +export function settingsList(settings , name ) { + const packages = (settings )?.packages; + if (!Array.isArray(packages)) return false; + return packages.some((entry) => { + const source = typeof entry === "string" ? entry : (entry )?.source; + if (typeof source !== "string" || !source.startsWith("npm:")) return false; + const spec = source.slice(4); + const at = spec.startsWith("@") ? spec.indexOf("@", 1) : spec.indexOf("@"); + return (at === -1 ? spec : spec.slice(0, at)) === name; + }); +} + +export class ServeChecks { + env ; + platform ; + limits ; + now ; + companionLaunch ; + agentHome ; + version ; + cached ; + + constructor(options ) { + this.env = options.env; + this.platform = options.platform ?? process.platform; + this.limits = { ...SERVE_CHECK_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.companionLaunch = options.companion; + this.agentHome = options.agentHome; + this.version = options.version; + } + + /** Every row, in the app's order; requests within `cacheMs` (and while one runs) share one result. */ + checks() { + const now = this.now(); + if (this.cached && now - this.cached.at < this.limits.cacheMs) return this.cached.checks; + const checks = Promise.all([this.node(), this.companion(), this.git(), this.engram()]); + this.cached = { at: now, checks }; + return checks; + } + + /** The next request runs the checks again (after a setup or upgrade job). */ + forget() { + this.cached = undefined; + } + + tool(command , args ) { + return run(command, args, { env: this.env, timeoutMs: this.limits.toolTimeoutMs, outputBytes: this.limits.outputBytes }); + } + + row(id , state , version , detail ) { + const clip = (text ) => (text === null || text.length <= this.limits.detail ? text : `${text.slice(0, this.limits.detail - 1)}…`); + return { id, state, version: clip(version), detail: clip(detail) }; + } + + async node() { + const node = await findProgram("node", this.env, this.platform); + if (!node) return this.row("node", "missing", null, "Node.js isn't installed"); + const result = await this.tool(node, ["--version"]); + const text = result.stdout.trim(); + if (!result.ok) return this.row("node", "error", null, `${node} doesn't run`); + const parsed = parseVersion(text); + if (!parsed) return this.row("node", "error", null, `Unexpected \`node --version\`: ${text}`); + const version = showVersion(parsed); + if (older(parsed, MIN_NODE)) return this.row("node", "error", version, `Node ${version} — needs ${showVersion(MIN_NODE)} or newer`); + const npm = await this.npm(node); + return npm === undefined + ? this.row("node", "missing", version, `Node ${version} found, but not npm`) + : this.row("node", "ok", version, `npm ${npm}`); + } + + /** `npm --version`; on Windows npm is a `.cmd`, which only a shell runs, so its `npm-cli.js` runs under `node` instead. */ + async npm(node ) { + const npm = await findProgram("npm", this.env, this.platform); + if (!npm) return undefined; + const result = this.platform === "win32" && /\.(cmd|bat)$/i.test(npm) + ? await this.tool(node, [join(dirname(npm), "node_modules", "npm", "bin", "npm-cli.js"), "--version"]) + : await this.tool(npm, ["--version"]); + const version = result.stdout.trim(); + return result.ok && version !== "" ? version : undefined; + } + + async git() { + const missing = this.row("git", "missing", null, "Git isn't installed"); + const git = await findProgram("git", this.env, this.platform); + if (!git) return missing; + // macOS's /usr/bin/git is a stub that offers the Command Line Tools until they are installed. + if (this.platform === "darwin" && git === "/usr/bin/git" && !(await this.tool("/usr/bin/xcode-select", ["-p"])).ok) return missing; + const result = await this.tool(git, ["--version"]); + if (!result.ok) return missing; + const version = result.stdout.trim().replace(/^git version /, "").trim(); + return this.row("git", "ok", version || null, null); + } + + async engram() { + const override = this.env.ENGRAM_BIN; + let engram ; + if (override) { + engram = await findProgram(override, this.env, this.platform); + if (!engram) return this.row("engram", "error", null, `ENGRAM_BIN points to ${override}, which can't be run. Fix or remove it.`); + } else { + engram = await findProgram("engram", this.env, this.platform); + } + const result = engram ? await this.tool(engram, ["version"]) : undefined; + if (!result?.ok) return this.row("engram", "missing", null, "Not installed"); + // `engram 1.18.0`, then maybe an update notice: the first line's last word. + const line = result.stdout.trim().split(/\r?\n/, 1)[0].trim() || "installed"; + const word = line.split(/\s+/).at(-1) ?? ""; + const parsed = parseVersion(word); + if (parsed && older(parsed, MIN_ENGRAM)) { + return this.row("engram", "error", showVersion(parsed), `Engram ${showVersion(parsed)} — needs ${showVersion(MIN_ENGRAM)} or newer`); + } + return this.row("engram", "ok", parsed ? showVersion(parsed) : null, line); + } + + /** The launcher's own `setup --check --json` for this home; a `--link` home is set up once it lists gentle-engram. */ + async companion() { + if (!this.companionLaunch) return this.row("companion", "error", null, "This server can't check its setup"); + const launch = this.companionLaunch(); + const result = await run(launch.command, launch.args, { env: launch.env, cwd: launch.cwd, timeoutMs: this.limits.companionTimeoutMs, outputBytes: this.limits.outputBytes }); + let report ; + try { + report = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1) ?? ""); + } catch { /* reported below */ } + if (!report || typeof report !== "object" || (result.code !== 0 && result.code !== 1)) { + const why = typeof report?.error === "string" ? report.error : result.code === null ? "it didn't finish" : `it exited with ${result.code}`; + return this.row("companion", "error", null, `\`gentle-shell setup --check\` failed: ${why}`); + } + const home = this.agentHome; + if (report.home?.mode === "link" && home !== undefined) { + let settings ; + try { settings = JSON.parse(await readFile(join(home, "settings.json"), "utf8")); } catch { /* not set up */ } + return settingsList(settings, "gentle-engram") + ? this.row("companion", "ok", null, `Linked to ${home}`) + : this.row("companion", "missing", null, `${home} isn't set up yet`); + } + const entry = await this.marker(); + if (report.needsSetup === false) return this.row("companion", "ok", entry?.gentleAi ?? null, entry ? `Set up ${entry.at.slice(0, 10)}` : null); + const reasons = Array.isArray(report.reasons) ? report.reasons : []; + if (!entry || reasons.includes("never-provisioned")) return this.row("companion", "missing", null, "Not set up yet — the first chat would do it silently"); + if (reasons.includes("gentle-ai-changed")) return this.row("companion", "error", entry.gentleAi, `Set up with Gentle AI ${entry.gentleAi}`); + return this.row("companion", "error", entry.gentleAi, + `Set up with gentle-pi ${entry.gentlePi ?? "an older version"}; ${this.version ?? "another version"} is installed`); + } + + /** This home's setup record in the launcher config (`GENTLE_SHELL_CONFIG`, else `~/.gentle-shell/config.json`). */ + async marker() { + if (this.agentHome === undefined) return undefined; + const path = this.env.GENTLE_SHELL_CONFIG || launcherConfigPath(homedir()); + let text ; + try { text = await readFile(path, "utf8"); } catch { return undefined; } + let key = this.agentHome; + try { key = realpathSync(key); } catch { /* as given */ } + return provisionedEntry(parseRawLauncherConfig(text), key); + } +} diff --git a/runtime/serve-cli.mjs b/runtime/serve-cli.mjs new file mode 100644 index 000000000..faad411ae --- /dev/null +++ b/runtime/serve-cli.mjs @@ -0,0 +1,931 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `gentle-shell serve`: argument parsing, the per-user server file and lock +// under `/serve`, the foreground server, the detached daemon, the +// local CLI client (`status`, `stop`, `pair`, `devices`) that talks to the +// running server with the owner-only admin token from the server file, and +// `share`, which opens the server to the local network (answering LAN +// discovery) and prints the short pairing code plus a connection code fallback. + +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs"; +import { createServer as createNetServer } from "node:net"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { INTERACTIVE_HOST_ENV } from "./rpc-host.mjs"; +import { DEFAULT_PAIR_SCOPES, parseScopes, readDevicesFile, ServeAuth, writeDevicesFile, } from "./serve-auth.mjs"; +import { isLoopbackHost, isUnspecified, SERVE_PROTOCOL, startServeServer, } from "./serve-server.mjs"; +import { parseRelayUrl } from "./serve-relay.mjs"; +import { loadOrCreateServeTls, } from "./serve-tls.mjs"; + +import { AUTOSTART_LABEL, autostartCommand, autostartFile, autostartInstalled, defaultShareSystem, encodeConnectionCode, firewallHint, HOST_NAME, installAutostart, ownHostNames, + removeAutostart, SHARE_DEFAULT_PORT, SHARE_FORWARD_PORTS, SHARE_PORT_ATTEMPTS, shareAddresses, } from "./serve-share.mjs"; + +import { openTowerServer } from "./tower-open.mjs"; + +export const SERVE_SERVER_FILE_SCHEMA = "gentle-shell.serve.server/v1"; +const DEFAULT_LISTEN = { host: "127.0.0.1", port: 0 }; +const DAEMON_START_TIMEOUT_MS = 15_000; +const STOP_TIMEOUT_MS = 15_000; + +// --- arguments ----------------------------------------------------------------- + + + + + + + + + + + +export function parseListen(value ) { + const m = /^(?:\[([0-9A-Fa-f:.]+)\]|([^:\s[\]]+))?:(\d{1,5})$/.exec(value) ?? (/^\d{1,5}$/.test(value) ? [value, undefined, undefined, value] : null); + if (!m) return { error: `--listen needs : (got "${value}")` }; + const port = Number(m[3]); + if (!(port >= 0 && port <= 65535)) return { error: `--listen port must be 0-65535 (got "${m[3]}")` }; + const host = m[1] !== undefined ? m[1] : m[2] ?? DEFAULT_LISTEN.host; + return { host: host.toLowerCase() === "localhost" ? "127.0.0.1" : host, port }; +} + +export function parseServeArgs(args ) { + const first = args[0]; + const sub = first === "status" || first === "stop" || first === "pair" || first === "devices" || first === "share" ? first : undefined; + const rest = sub ? args.slice(1) : args; + let json = false; + let foreground = false; + let listen = DEFAULT_LISTEN; + let revoke ; + let sharePort ; + let always = false; + let off = false; + let endSessions = false; + let forwardPorts ; + let noTls = false; + let relay ; + const scopeValues = []; + const allowHosts = []; + for (let i = 0; i < rest.length; i += 1) { + const arg = rest[i]; + const value = (flag ) => { + if (arg === flag) return rest[(i += 1)]; + return arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : undefined; + }; + if (arg === "--help" || arg === "-h") return { action: "help" }; + if (arg === "--json" && sub !== "stop") { json = true; continue; } + if (sub === undefined && arg === "--foreground") { foreground = true; continue; } + if ((sub === undefined || sub === "share") && arg === "--no-tls") { noTls = true; continue; } + if ((sub === undefined || sub === "share") && (arg === "--relay" || arg.startsWith("--relay="))) { + const parsed = parseRelayUrl(value("--relay") ?? ""); + if ("error" in parsed) return { error: `--relay: ${parsed.error}` }; + relay = parsed.url; + continue; + } + if (sub === undefined && (arg === "--listen" || arg.startsWith("--listen="))) { + const v = value("--listen"); + if (v === undefined) return { error: "--listen needs :" }; + const parsed = parseListen(v); + if ("error" in parsed) return parsed; + listen = parsed; + continue; + } + if (sub === undefined && (arg === "--allow-host" || arg.startsWith("--allow-host="))) { + const v = value("--allow-host")?.toLowerCase(); + if (v === undefined || !HOST_NAME.test(v)) return { error: `--allow-host needs a DNS name without a port (got "${v ?? ""}")` }; + if (!allowHosts.includes(v)) allowHosts.push(v); + continue; + } + if (sub === undefined && (arg === "--forward-ports" || arg.startsWith("--forward-ports="))) { + const v = value("--forward-ports"); + const parsed = v === undefined ? undefined : parsePortRange(v); + if (!parsed) return { error: `--forward-ports needs a port range like 8800-8899 (got "${v ?? ""}")` }; + forwardPorts = parsed; + continue; + } + if (sub === "pair" && (arg === "--scope" || arg.startsWith("--scope="))) { + const v = value("--scope"); + if (v === undefined) return { error: "--scope needs a scope list" }; + scopeValues.push(v); + continue; + } + if (sub === "devices" && (arg === "--revoke" || arg.startsWith("--revoke="))) { + const v = value("--revoke"); + if (!v || !/^[A-Za-z0-9_]{1,64}$/.test(v)) return { error: "--revoke needs a device id" }; + revoke = v; + continue; + } + if (sub === "share" && (arg === "--port" || arg.startsWith("--port="))) { + const v = value("--port"); + if (v === undefined || !/^\d{1,5}$/.test(v) || Number(v) < 1 || Number(v) > 65535) return { error: `--port needs a port 1-65535 (got "${v ?? ""}")` }; + sharePort = Number(v); + continue; + } + if (sub === "share" && arg === "--always") { always = true; continue; } + if (sub === "share" && arg === "--off") { off = true; continue; } + if (sub === "stop" && arg === "--sessions") { endSessions = true; continue; } + return { error: `unknown serve${sub ? ` ${sub}` : ""} argument "${arg}"` }; + } + if (noTls && relay !== undefined) return { error: "--relay needs TLS (the relay must only see ciphertext): leave out --no-tls" }; + const network = { ...(noTls ? { noTls: true } : {}), ...(relay === undefined ? {} : { relay }) }; + if (sub === "status") return { action: "status", json }; + if (sub === "stop") return { action: "stop", endSessions }; + if (sub === "devices") return { action: "devices", json, ...(revoke === undefined ? {} : { revoke }) }; + if (sub === "share") { + if (off) return always || json || sharePort !== undefined || noTls || relay !== undefined ? { error: "serve share --off takes no other argument" } : { action: "share-off" }; + return { action: "share", port: sharePort ?? SHARE_DEFAULT_PORT, always, json, ...network }; + } + if (sub === "pair") { + if (scopeValues.length === 0) return { action: "pair", scopes: [...DEFAULT_PAIR_SCOPES], json }; + const parsed = parseScopes(scopeValues); + return "error" in parsed ? parsed : { action: "pair", scopes: parsed.scopes, json }; + } + return { action: "start", host: listen.host, port: listen.port, foreground, json, ...(allowHosts.length === 0 ? {} : { allowHosts }), ...(forwardPorts ? { forwardPorts } : {}), ...network }; +} + +/** `-`, both 1-65535, from ≤ to, at most 1000 ports. */ +export function parsePortRange(value ) { + const m = /^(\d{1,5})-(\d{1,5})$/.exec(value); + if (!m) return undefined; + const from = Number(m[1]); + const to = Number(m[2]); + return from >= 1 && to <= 65535 && from <= to && to - from < 1000 ? { from, to } : undefined; +} + +export const SERVE_HELP = [ + "Usage: gentle-shell [home selectors] serve share [--port ] [--always] [--no-tls] [--relay gsr://:] [--json]", + " gentle-shell [home selectors] serve share --off", + " gentle-shell [home selectors] serve [--listen :] [--allow-host ]... [--forward-ports -] [--no-tls] [--relay gsr://:] [--foreground] [--json]", + " gentle-shell [home selectors] serve status [--json]", + " gentle-shell [home selectors] serve stop [--sessions]", + " gentle-shell [home selectors] serve pair [--scope ] [--json]", + " gentle-shell [home selectors] serve devices [--revoke ] [--json]", + "", + "Runs one server per agent home that owns Gentle Shell sessions (one `--mode rpc` child each)", + "and lets paired devices drive them over HTTP + Server-Sent Events. Sessions keep running when", + "clients disconnect. Binds 127.0.0.1 on a random port unless --listen says otherwise; every", + "request needs a device token (there is no unauthenticated mode). A non-loopback --listen", + "serves HTTPS with a self-signed certificate made on first run (/serve/tls/); devices pin", + "its fingerprint. This computer itself may keep using plain http://127.0.0.1.", + "", + " serve share The easy way to connect Gentle Shell GPUI from another computer on your", + " network: opens the server to the network (HTTPS, port 8787 or the next", + " free one; --port picks another) and prints a short code to enter in the app", + " (valid 5 minutes, once). The app finds this computer on the network by itself", + " (UDP broadcast on the same port); where it cannot (another subnet, a tailnet,", + " client isolation, a relay), paste the long gsc1. code printed under it. Reuses", + " a server already on the network; one on this computer only (or with other", + " TLS or relay settings) is reopened when it runs no sessions. Pages it forwards", + " to the app (dev servers, the design canvas, Gentle Tower) take ports 8800-8899.", + " --always Also start that server at every login (systemd user unit on Linux, a", + " LaunchAgent on macOS). 'serve share --off' turns it off and stops it.", + " serve Start the server in the background (--foreground keeps it in this terminal).", + " serve status Show whether the server runs, its URL and its sessions.", + " serve stop Stop the server. Its sessions keep running and the next server picks them", + " up (a session no server came back to stops after 24 hours); --sessions", + " stops them too.", + " serve pair Print a one-time pairing code (single use, 5 minutes). Scopes default to", + " sessions:read,sessions:operate,terminal; leave terminal out (--scope", + " sessions:read,sessions:operate) for a device that must not open shells, and", + " add admin only for a device you fully trust.", + " serve devices List paired devices; --revoke removes one at once (its streams close).", + "", + " --allow-host One more name clients may use in the Host header, for example a tailnet", + " MagicDNS name (repeatable). Names not allowed are refused (DNS rebinding).", + " --forward-ports Listen ports for forwarded pages (for example 8800-8899), so a firewall can", + " open one range; without it each forward takes a random port.", + " --no-tls Plain HTTP on the network, as before TLS existed: tokens and traffic cross", + " the network unencrypted. Only for a network that encrypts by itself.", + " --relay Also register with a relay (gentle-shell relay), so devices outside this", + " network reach the server through it with the long code. The relay sees only", + " TLS ciphertext. Its secret comes from GENTLE_SHELL_RELAY_SECRET or", + " /serve/relay-secret.", + "", + "Paired devices can also read and write files, run git and open persistent terminals here,", + "all as the user the server runs as. Terminals run in gentle-term-host ($GENTLE_TERM_HOST,", + "/serve/bin/gentle-term-host or on PATH), which keeps them alive across clients and", + "server restarts.", + "", + "Protocol, endpoints and security model: docs/serve.md.", +].join("\n"); + +// --- server file and lock -------------------------------------------------------- + + + + + + + + + + + + + + + + + + + + + + +export function serveDir(agentHome ) { + return join(agentHome, "serve"); +} + +export function serveFiles(agentHome ) { + const dir = serveDir(agentHome); + return { dir, server: join(dir, "server.json"), lock: join(dir, "server.lock"), devices: join(dir, "devices.json"), log: join(dir, "server.log") }; +} + +function privateDir(dir ) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + try { chmodSync(dir, 0o700); } catch { /* Windows: ACLs, not modes */ } +} + +export function readServerFile(path ) { + try { + const parsed = JSON.parse(readFileSync(path, "utf8")) ; + if (parsed?.schema !== SERVE_SERVER_FILE_SCHEMA || typeof parsed.url !== "string" || typeof parsed.pid !== "number" || typeof parsed.adminToken !== "string") return undefined; + return parsed; + } catch { + return undefined; + } +} + +function writeServerFile(path , file ) { + const temp = `${path}.${process.pid}.tmp`; + writeFileSync(temp, `${JSON.stringify(file, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows */ } +} + +export function processAlive(pid ) { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error ).code === "EPERM"; + } +} + +/** + * Single instance per agent home: an exclusive create of the lock file, which + * names its pid. A lock whose pid is gone is stale and is taken over once. + */ +export function acquireServeLock(lockPath , pid = process.pid) { + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + const fd = openSync(lockPath, "wx", 0o600); + writeSync(fd, `${pid}\n`); + closeSync(fd); + return { acquired: true }; + } catch (error) { + if ((error ).code !== "EEXIST") throw error; + let holder = NaN; + try { holder = Number(readFileSync(lockPath, "utf8").trim()); } catch { /* vanished: retry */ } + if (Number.isInteger(holder) && holder !== pid && processAlive(holder)) return { heldBy: holder }; + rmSync(lockPath, { force: true }); + } + } + return { heldBy: NaN }; +} + +function releaseServeLock(lockPath , pid = process.pid) { + try { + if (Number(readFileSync(lockPath, "utf8").trim()) === pid) rmSync(lockPath, { force: true }); + } catch { /* already gone */ } +} + +/** The server file of a live server, or undefined (a stale file is ignored). */ +export function liveServer(agentHome ) { + const file = readServerFile(serveFiles(agentHome).server); + return file && processAlive(file.pid) ? file : undefined; +} + +// --- running ----------------------------------------------------------------------- + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** The exit code that asks a service manager (systemd `Restart=on-failure`, launchd `KeepAlive`) to start the upgraded server. */ +export const SERVE_RESTART_EXIT = 75; + +/** + * Whether a service manager runs this server (`serve share --always`): systemd + * names this process in `SYSTEMD_EXEC_PID`, launchd sets its job label. + */ +export function supervisedServe(env , pid = process.pid) { + return env.SYSTEMD_EXEC_PID === String(pid) || env.XPC_SERVICE_NAME === AUTOSTART_LABEL; +} + +/** `gentle-shell upgrade [--channel ]`, run by this launcher outside any session, never prompting. */ +export function upgradeLaunch(ctx , channel ) { + const env = { ...ctx.env, NO_COLOR: "1", FORCE_COLOR: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + delete env[INTERACTIVE_HOST_ENV]; + return { command: ctx.nodePath, args: [ctx.launcher, "upgrade", ...(channel === undefined ? [] : ["--channel", channel])], cwd: homedir(), env }; +} + +/** `gentle-shell [home flags] setup` for this server's home, run by this launcher outside any session, never prompting. */ +export function setupLaunch(ctx , args = []) { + const env = { ...ctx.env, NO_COLOR: "1", FORCE_COLOR: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + delete env[INTERACTIVE_HOST_ENV]; + return { command: ctx.nodePath, args: [ctx.launcher, ...ctx.homeFlags, "setup", ...args], cwd: homedir(), env }; +} + +/** The version the launcher's package now holds, read after an upgrade. */ +function launcherVersion(launcher ) { + try { + const version = JSON.parse(readFileSync(join(dirname(dirname(launcher)), "package.json"), "utf8"))?.version; + return typeof version === "string" && version.length <= 64 ? version : undefined; + } catch { + return undefined; + } +} + +/** + * The child for one session: this same launcher, same home, Pi RPC mode, Desktop RPC on. + * `sessionId` resumes by exact id (`--session-id`): the project's session with that id, or a + * new one under it when Pi never wrote it (a conversation with no messages yet has no file). + * `--session` would fail then, and could stop to ask about forking another project's session. + */ +export function sessionLaunch(ctx , input ) { + const env = { ...ctx.env, [INTERACTIVE_HOST_ENV]: "1", GENTLE_DESIGN_OPEN_BROWSER: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + return { + command: ctx.nodePath, + args: [ctx.launcher, ...ctx.homeFlags, "--mode", "rpc", ...(input.sessionId === undefined ? [] : ["--session-id", input.sessionId])], + cwd: input.cwd, + env, + }; +} + +/** + * A one-shot prompt (`POST /api/print`): this same launcher and home, run the way the app runs + * it for commit messages (`--print --no-session --no-tools`), with the prompt on stdin. Never the + * interactive host: nothing answers its dialogs in a one-shot run. + */ +export function printLaunch(ctx , input ) { + const env = { ...ctx.env, GENTLE_DESIGN_OPEN_BROWSER: "0", GENTLE_SHELL_SKIP_STARTUP_UPDATE: "1" }; + delete env[INTERACTIVE_HOST_ENV]; + return { + command: ctx.nodePath, + args: [ctx.launcher, ...ctx.homeFlags, "--print", "--no-session", "--no-tools", ...(input.model === undefined ? [] : ["--model", input.model])], + cwd: input.cwd, + env, + }; +} + +function untilSignal(stopRequested ) { + const { promise, resolve } = Promise.withResolvers (); + const done = () => { + process.off("SIGINT", done); + process.off("SIGTERM", done); + process.off("SIGHUP", done); + resolve(); + }; + process.on("SIGINT", done); + process.on("SIGTERM", done); + if (process.platform !== "win32") process.on("SIGHUP", done); + stopRequested.then(done); + return promise; +} + +function plainHttpWarning(host ) { + return `gentle-shell serve: warning: listening on ${host} over plain HTTP (--no-tls). Device tokens and session traffic cross the network unencrypted; use it only on a network that encrypts by itself, such as a tailnet.\n`; +} + + + +/** The relay secret a server presents: `GENTLE_SHELL_RELAY_SECRET`, else the first line of `/serve/relay-secret`. */ +export function relaySecret(env , serveDirectory ) { + const fromEnv = env.GENTLE_SHELL_RELAY_SECRET?.trim(); + if (fromEnv) return fromEnv; + try { + return readFileSync(join(serveDirectory, "relay-secret"), "utf8").split(/\r?\n/)[0].trim() || undefined; + } catch { + return undefined; + } +} + +/** HTTPS on a network listen (unless --no-tls) and always with a relay: the certificate, made on first run. */ +function serverTls(ctx , args , serveDirectory ) { + if (args.noTls || (isLoopbackHost(args.host) && args.relay === undefined)) return undefined; + const system = ctx.system ?? defaultShareSystem(ctx.env); + const name = system.hostname(); + const addresses = isUnspecified(args.host) ? shareAddresses(system.networkInterfaces(), name) : [args.host]; + return loadOrCreateServeTls(serveDirectory, { + commonName: `gentle-shell serve ${name}`, + dnsNames: ["localhost", ...ownHostNames(name), ...(args.allowHosts ?? [])], + ips: ["127.0.0.1", "::1", ...addresses], + }); +} + +/** Gentle Tower in this process, on 127.0.0.1 with a fresh token: what `gentle-shell tower` runs, never a browser. */ +async function startTower(env ) { + const tower = await openTowerServer(env); + return { port: tower.port, path: new URL(tower.url).pathname, close: () => tower.close() }; +} + +async function runForeground(ctx , args ) { + const result = await serveForeground(ctx, args); + if (result.restartPort === undefined) return result.code; + return restartServer(ctx, { ...args, port: result.restartPort }); +} + +/** Serves until stopped; `restartPort` when it stopped for an upgrade, so the next server takes the same address. */ +async function serveForeground(ctx , args ) { + const files = serveFiles(ctx.agentHome); + privateDir(files.dir); + const lock = acquireServeLock(files.lock); + if ("heldBy" in lock) { + const running = readServerFile(files.server); + ctx.stderr(`gentle-shell serve: already running${Number.isNaN(lock.heldBy) ? "" : ` (pid ${lock.heldBy})`}${running ? ` at ${running.url}` : ""}\n`); + return { code: 1 }; + } + let server ; + let endSessions = false; + let restart = false; + try { + const tls = serverTls(ctx, args, files.dir); + if (!isLoopbackHost(args.host) && !tls) ctx.stderr(plainHttpWarning(args.host)); + const secret = args.relay === undefined ? undefined : relaySecret(ctx.env, files.dir); + const adminToken = `gsa_${randomBytes(32).toString("base64url")}`; + const auth = new ServeAuth({ devicesFile: files.devices, adminToken }); + const stop = Promise.withResolvers (); + const log = (line ) => ctx.stderr(`${new Date().toISOString()} ${line}\n`); + server = await startServeServer({ + host: args.host, + port: args.port, + allowHosts: args.allowHosts ?? [], + ...(args.forwardPorts ? { forwardPorts: args.forwardPorts } : {}), + ...(tls ? { tls } : {}), + ...(args.relay === undefined ? {} : { relay: { url: args.relay, ...(secret === undefined ? {} : { secret }) } }), + startTower: () => startTower(ctx.env), + serveDir: files.dir, + env: ctx.env, + auth, + version: ctx.version, + launchSession: (input) => sessionLaunch(ctx, input), + launchPrint: (input) => printLaunch(ctx, input), + log, + onStopRequested: (request) => { endSessions = request.endSessions; stop.resolve(); }, + upgrade: { + launch: (channel) => (ctx.upgradeCommand ?? ((chosen ) => upgradeLaunch(ctx, chosen)))(channel), + installedVersion: () => launcherVersion(ctx.restartLauncher?.() ?? ctx.launcher), + // Sessions keep running under their keepers; the next server reattaches them. + onUpgraded: () => { restart = true; stop.resolve(); }, + // Setup installs the home's companion packages, never the launcher: no restart. + setup: () => (ctx.setupCommand ?? (() => setupLaunch(ctx)))(), + }, + // `GET /api/checks`: the companion row is the launcher's own read-only `setup --check`. + checks: { companion: () => setupLaunch(ctx, ["--check", "--json"]), agentHome: ctx.agentHome }, + }); + const file = { + schema: SERVE_SERVER_FILE_SCHEMA, + protocol: SERVE_PROTOCOL, + serverId: server.serverId, + url: server.url, + listen: { host: args.host, port: server.port }, + pid: process.pid, + startedAt: new Date(server.startedAt).toISOString(), + version: ctx.version, + adminToken, + discovery: server.discovery, + ...(args.forwardPorts ? { forwardPorts: args.forwardPorts } : {}), + ...(server.fingerprint === undefined ? {} : { fingerprint: server.fingerprint }), + ...(args.relay === undefined ? {} : { relay: args.relay }), + }; + writeServerFile(files.server, file); + if (tls) log(`HTTPS for the network: certificate ${tls.fingerprint}${tls.created ? " (new)" : ""}`); + if (args.relay !== undefined && secret === undefined) log(`relay: no relay secret (GENTLE_SHELL_RELAY_SECRET or ${join(files.dir, "relay-secret")}); a relay that has one refuses this server`); + ctx.stdout(args.json + ? `${JSON.stringify({ schema: "gentle-shell.serve/v1", url: server.url, pid: process.pid, serverId: server.serverId, ...(server.fingerprint === undefined ? {} : { fingerprint: server.fingerprint }), ...(args.relay === undefined ? {} : { relay: args.relay }) })}\n` + : `Gentle Shell server: ${server.url} (pid ${process.pid})\n${server.fingerprint === undefined ? "" : `HTTPS on the network, certificate fingerprint ${server.fingerprint}\n`}${args.relay === undefined ? "" : `Relay: ${args.relay}\n`}Pair a device with 'gentle-shell serve pair'. Press Ctrl+C to stop.\n`); + await (ctx.untilStopped ?? untilSignal)(stop.promise); + log(restart ? "stopping to restart on the upgraded version" : "stopping"); + return restart ? { code: 0, restartPort: server.port } : { code: 0 }; + } catch (error) { + ctx.stderr(`gentle-shell serve: could not start: ${error instanceof Error ? error.message : String(error)}\n`); + return { code: 1 }; + } finally { + await server?.close({ endSessions }); + if (readServerFile(files.server)?.pid === process.pid) rmSync(files.server, { force: true }); + releaseServeLock(files.lock); + } +} + +/** + * After an upgrade, once this server let go of its lock and server file: a + * service manager starts the upgraded server itself (this process exits with + * `SERVE_RESTART_EXIT`); otherwise a detached `serve --foreground` on the new + * version takes the same address, logging to `server.log`. + */ +function restartServer(ctx , args ) { + const stamp = () => new Date().toISOString(); + if (supervisedServe(ctx.env)) { + ctx.stderr(`${stamp()} exiting with ${SERVE_RESTART_EXIT}: the service manager starts the upgraded server\n`); + return SERVE_RESTART_EXIT; + } + const files = serveFiles(ctx.agentHome); + const logFd = openSync(files.log, "a", 0o600); + try { + const child = spawn(ctx.nodePath, [ctx.restartLauncher?.() ?? ctx.launcher, ...ctx.homeFlags, ...foregroundArgs(args)], { + detached: true, + stdio: ["ignore", logFd, logFd], + env: ctx.env, + windowsHide: true, + }); + child.once("error", (error) => ctx.stderr(`${stamp()} could not restart: ${error.message}\n`)); + child.unref(); + ctx.stderr(`${stamp()} restarted on the upgraded version as pid ${child.pid} (log: ${files.log})\n`); + return 0; + } catch (error) { + ctx.stderr(`${stamp()} could not restart: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } finally { + closeSync(logFd); + } +} + +/** `serve --foreground` with the same listen address, hosts, forward ports, TLS choice and relay. */ +function foregroundArgs(args ) { + const listen = `${args.host.includes(":") ? `[${args.host}]` : args.host}:${args.port}`; + const allow = (args.allowHosts ?? []).flatMap((name) => ["--allow-host", name]); + const ports = args.forwardPorts ? ["--forward-ports", `${args.forwardPorts.from}-${args.forwardPorts.to}`] : []; + const network = [...(args.noTls ? ["--no-tls"] : []), ...(args.relay === undefined ? [] : ["--relay", args.relay])]; + return ["serve", "--foreground", "--listen", listen, ...allow, ...ports, ...network]; +} + +async function startDaemon(ctx , args ) { + const files = serveFiles(ctx.agentHome); + const running = liveServer(ctx.agentHome); + if (running) { + ctx.stderr(`gentle-shell serve: already running at ${running.url} (pid ${running.pid})\n`); + return 1; + } + const started = await spawnDaemon(ctx, args); + if ("log" in started) { + ctx.stderr(`gentle-shell serve: the server did not start.${started.log ? `\n${started.log}` : ""}\n`); + return 1; + } + const file = started.file; + ctx.stdout(args.json + ? `${JSON.stringify({ schema: "gentle-shell.serve/v1", url: file.url, pid: file.pid, serverId: file.serverId })}\n` + : `Gentle Shell server: ${file.url} (pid ${file.pid})\nLog: ${files.log}\nPair a device with 'gentle-shell serve pair'; stop with 'gentle-shell serve stop'.\n`); + return 0; +} + +/** Starts `serve --foreground` detached, logging to `server.log`; on failure, the log's tail. */ +async function spawnDaemon(ctx , args ) { + const files = serveFiles(ctx.agentHome); + privateDir(files.dir); + const logFd = openSync(files.log, "w", 0o600); + const child = spawn(ctx.nodePath, [ctx.launcher, ...ctx.homeFlags, ...foregroundArgs(args)], { + detached: true, + stdio: ["ignore", logFd, logFd], + env: ctx.env, + windowsHide: true, + }); + closeSync(logFd); + child.unref(); + const deadline = Date.now() + DAEMON_START_TIMEOUT_MS; + while (Date.now() < deadline) { + const file = readServerFile(files.server); + if (file?.pid === child.pid) return { file }; + if (child.exitCode !== null || child.signalCode !== null) break; + await new Promise((r) => setTimeout(r, 100)); + } + let log = ""; + try { log = readFileSync(files.log, "utf8").slice(-2000); } catch { /* no log */ } + return { log }; +} + + + + + + + + + + + + + + + + +async function api (server , method , path , body ) { + const response = await fetch(`${server.url}${path}`, { + method, + headers: { Authorization: `Bearer ${server.adminToken}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + signal: AbortSignal.timeout(10_000), + }); + const text = await response.text(); + let data ; + try { data = text ? JSON.parse(text) : {}; } catch { data = undefined; } + // The server owning this home's server file answers in its own documented shapes; fields stay optional. + const shaped = data && typeof data === "object" ? data : { error: { message: text.slice(0, 200) } }; + return { status: response.status, data: shaped }; +} + +function apiFailure(ctx , what , result ) { + const error = result.data.error; + ctx.stderr(`gentle-shell serve: ${what} failed (${result.status}${error?.code ? ` ${error.code}` : ""}): ${error?.message ?? "no details"}\n`); + return 1; +} + +function formatDevices(devices ) { + if (devices.length === 0) return "No paired devices.\n"; + return devices.map((d) => `${d.id} ${d.name} [${d.scopes.join(",")}] paired ${d.createdAt}${d.lastUsedAt ? `, last used ${d.lastUsedAt}` : ""}`).join("\n") + "\n"; +} + +async function waitForExit(pid , timeoutMs ) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (!processAlive(pid)) return true; + await new Promise((r) => setTimeout(r, 100)); + } + return !processAlive(pid); +} + +async function stopServer(ctx , server , endSessions = false) { + const result = await api(server, "POST", "/api/server/stop", { endSessions }); + if (result.status !== 202) process.kill(server.pid, "SIGTERM"); + if (await waitForExit(server.pid, STOP_TIMEOUT_MS)) return true; + ctx.stderr(`gentle-shell serve: pid ${server.pid} is still running\n`); + return false; +} + +// --- share ------------------------------------------------------------------------- + +const LAN_HOST = "0.0.0.0"; + +function canBind(port , host ) { + const { promise, resolve } = Promise.withResolvers (); + const probe = createNetServer(); + probe.once("error", () => resolve(false)); + probe.listen(port, host, () => probe.close(() => resolve(true))); + return promise; +} + +/** + * Whether nothing listens on `port` (a quick probe; the bind can still race). + * Loopback too: macOS lets a wildcard bind share a port that another server + * holds on 127.0.0.1, which would then answer this machine's own requests. + */ +async function portFree(port ) { + return (await canBind(port, LAN_HOST)) && (await canBind(port, "127.0.0.1")); +} + +async function runningSessions(server ) { + const list = await api (server, "GET", "/api/sessions"); + if (list.status !== 200 || !Array.isArray(list.data.sessions)) throw new Error(`listing its sessions failed (${list.status})`); + return list.data.sessions.filter((s) => s.state === "running").length; +} + +async function waitForServer(agentHome , timeoutMs , accept ) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const file = liveServer(agentHome); + if (file && accept(file)) return file; + await new Promise((r) => setTimeout(r, 100)); + } + return undefined; +} + +/** + * `serve share`: make sure this home's server listens on the local network + * (start it, reopen a loopback one that runs no sessions, or reuse one already + * there), mint a pairing code and print the connection code that carries it. + */ +async function runShare(ctx , args ) { + const system = ctx.system ?? defaultShareSystem(ctx.env); + const files = serveFiles(ctx.agentHome); + const fail = (message ) => { ctx.stderr(`gentle-shell serve share: ${message}\n`); return 1; }; + if (args.always && !autostartFile(system)) return fail(`--always (start at login) is not supported on ${system.platform === "win32" ? "Windows" : system.platform} yet; run 'gentle-shell serve share' without it.`); + const allowHosts = ownHostNames(system.hostname()); + const autostartFor = (port ) => autostartCommand({ nodePath: ctx.nodePath, launcher: ctx.launcher, homeFlags: ctx.homeFlags, port, allowHosts, forwardPorts: SHARE_FORWARD_PORTS, + ...(args.noTls ? { noTls: true } : {}), ...(args.relay === undefined ? {} : { relay: args.relay }), env: ctx.env, logFile: files.log }); + let server = liveServer(ctx.agentHome); + let opened = "started"; + let atLogin = false; + try { + if (server) { + const lan = !isLoopbackHost(server.listen.host); + // TLS as asked (a server from before TLS is reopened with it); the relay asked for, when one is (none asked keeps the one it has). + const sameNetwork = (server.fingerprint !== undefined) === !args.noTls && (args.relay === undefined || server.relay === args.relay); + atLogin = lan && autostartInstalled(system, autostartFor(server.listen.port)); + if (lan && sameNetwork && (!args.always || atLogin)) { + opened = "reused"; + } else { + // Reopening it on the network, or under the service manager, would end its sessions. + const busy = await runningSessions(server); + if (busy > 0) { + return fail(!lan + ? `the server here is reachable from this computer only and has ${busy} running session(s); stop them or run 'gentle-shell serve stop', then run share again to open it to your network.` + : !sameNetwork + ? `the server has ${busy} running session(s), and changing its TLS or relay settings has to restart it; stop them or run 'gentle-shell serve stop', then try again.` + : `the server has ${busy} running session(s), and --always has to restart it; stop them or run 'gentle-shell serve stop', then try again.`); + } + if (!(await stopServer(ctx, server))) return 1; + if (!lan) opened = "reopened"; + server = undefined; + } + } + if (!server) { + const ports = Array.from({ length: SHARE_PORT_ATTEMPTS }, (_, i) => args.port + i).filter((port) => port <= 65535); + const busyPorts = `port${ports.length > 1 ? `s ${ports[0]}-${ports.at(-1)} are` : ` ${ports[0]} is`} in use; choose another with --port`; + if (args.always) { + let port ; + for (const candidate of ports) if (await portFree(candidate)) { port = candidate; break; } + if (port === undefined) return fail(busyPorts); + const installed = await installAutostart(system, autostartFor(port)); + if ("error" in installed) return fail(`could not turn on start at login: ${installed.error}`); + server = await waitForServer(ctx.agentHome, DAEMON_START_TIMEOUT_MS, (file) => !isLoopbackHost(file.listen.host)); + if (!server) return fail(`start at login is on (${installed.file}), but the server did not start; see ${system.platform === "darwin" ? files.log : "journalctl --user -u gentle-shell-serve"}.`); + atLogin = true; + } else { + for (const port of ports) { + if (!(await portFree(port))) continue; + const started = await spawnDaemon(ctx, { host: LAN_HOST, port, allowHosts, forwardPorts: SHARE_FORWARD_PORTS, ...(args.noTls ? { noTls: true } : {}), ...(args.relay === undefined ? {} : { relay: args.relay }) }); + if ("file" in started) { server = started.file; break; } + // Taken between the probe and the bind: try the next one. + if (!started.log.includes("EADDRINUSE")) return fail(`the server did not start.${started.log ? `\n${started.log}` : ""}`); + } + if (!server) return fail(busyPorts); + } + } + + const minted = await api (server, "POST", "/api/pairing-codes", {}); + if (minted.status !== 201 || typeof minted.data.code !== "string") return apiFailure(ctx, "pair", minted); + const port = server.listen.port; + const host = server.listen.host; + const addresses = isUnspecified(host) ? shareAddresses(system.networkInterfaces(), system.hostname()) : [host.includes(":") ? `[${host}]` : host]; + const pairingCode = minted.data.code; + const fingerprint = server.fingerprint; + const code = encodeConnectionCode({ id: server.serverId, n: system.hostname(), p: port, a: addresses, c: pairingCode, + ...(fingerprint === undefined ? {} : { fp: fingerprint }), ...(server.relay === undefined ? {} : { r: server.relay }) }); + // A server file from before discovery existed has no flag: that server does not answer it. + const discovery = server.discovery === true; + if (args.json) { + ctx.stdout(`${JSON.stringify({ code, pairingCode, port, addresses, expiresAt: minted.data.expiresAt, serverId: server.serverId, discovery, tls: fingerprint !== undefined, + ...(fingerprint === undefined ? {} : { fingerprint }), ...(server.relay === undefined ? {} : { relay: server.relay }) })}\n`); + return 0; + } + const firewall = firewallHint(system.platform, port, system.has, server.forwardPorts); + ctx.stdout([ + opened === "reused" ? `The Gentle Shell server is already open to your network on port ${port}.` + : opened === "reopened" ? `Opened the Gentle Shell server to your network on port ${port} (it was reachable from this computer only).` + : `Started the Gentle Shell server for your network on port ${port}.`, + "", + ` Code: ${pairingCode}`, + "", + "In Gentle Shell GPUI → Configuration → Where agents run → Gentle Shell server, enter this code. Valid for 5 minutes, once.", + "If the app can't find this computer, paste this instead:", + code, + "", + ...(discovery ? [] : [`Discovery is off on this server (UDP port ${port} could not be opened), so the app cannot find this computer by itself: paste the long code.`]), + ...(server.relay === undefined ? [] : [`Outside this network the app reaches it through the relay ${server.relay} with the long code (the short code works on this network only).`]), + fingerprint === undefined + ? "It uses plain HTTP on your network (--no-tls): share only on a network that encrypts by itself." + : `It uses HTTPS; the app checks this computer's certificate, fingerprint ${fingerprint}.`, + ...(firewall ? [`If the app cannot find or reach this computer, or a page it opens from here, open the ports in the firewall: ${firewall}`] : []), + ...(firewall && !server.forwardPorts ? ["This server gives forwarded pages random ports; to keep them in one range (8800-8899), run 'gentle-shell serve stop' and then 'gentle-shell serve share'."] : []), + ...(atLogin ? ["It starts at every login; turn that off with 'gentle-shell serve share --off'."] : []), + ...(atLogin && system.platform === "linux" ? [`To start it at boot, before anyone logs in: sudo loginctl enable-linger ${system.user}`] : []), + "", + ].join("\n")); + return 0; + } catch (error) { + return fail(`could not reach the server${server ? ` at ${server.url}` : ""}: ${error instanceof Error ? error.message : String(error)}`); + } +} + +async function runShareOff(ctx ) { + const system = ctx.system ?? defaultShareSystem(ctx.env); + if (!autostartFile(system)) { + ctx.stdout("Start at login was not on.\n"); + return 0; + } + const removed = await removeAutostart(system); + ctx.stdout(removed.removed ? `Start at login is off (removed ${removed.file}); the server it started has stopped.\n` : "Start at login was not on.\n"); + return 0; +} + +export async function runServeCommand(args , ctx ) { + if (args.action === "help") { + ctx.stdout(`${SERVE_HELP}\n`); + return 0; + } + if (args.action === "start") return args.foreground ? runForeground(ctx, args) : startDaemon(ctx, args); + if (args.action === "share") return runShare(ctx, args); + if (args.action === "share-off") return runShareOff(ctx); + const files = serveFiles(ctx.agentHome); + const server = liveServer(ctx.agentHome); + + if (args.action === "devices" && !server) { + // Without a server the file is the whole state: list or revoke there. + const devices = readDevicesFile(files.devices); + if (args.revoke !== undefined) { + if (!devices.some((d) => d.id === args.revoke)) { ctx.stderr(`gentle-shell serve: no device ${args.revoke}\n`); return 1; } + writeDevicesFile(files.devices, devices.filter((d) => d.id !== args.revoke)); + ctx.stdout(`Revoked ${args.revoke}.\n`); + return 0; + } + const list = devices.map(({ tokenHash: _h, ...d }) => d); + ctx.stdout(args.json ? `${JSON.stringify({ devices: list })}\n` : formatDevices(list)); + return 0; + } + if (!server) { + if (args.action === "status" && args.json) ctx.stdout(`${JSON.stringify({ running: false })}\n`); + else ctx.stderr("gentle-shell serve: not running\n"); + return args.action === "stop" ? 0 : 1; + } + + try { + if (args.action === "status") { + const info = await api (server, "GET", "/api/server"); + const list = await api (server, "GET", "/api/sessions"); + if (info.status !== 200) return apiFailure(ctx, "status", info); + const sessions = Array.isArray(list.data.sessions) ? list.data.sessions : []; + if (args.json) { + ctx.stdout(`${JSON.stringify({ running: true, url: server.url, pid: server.pid, serverId: server.serverId, protocol: server.protocol, startedAt: server.startedAt, version: server.version, + ...(info.data.tls ? { tls: info.data.tls } : {}), ...(info.data.relay ? { relay: info.data.relay } : {}), sessions })}\n`); + } else { + ctx.stdout(`Running at ${server.url} (pid ${server.pid}, since ${server.startedAt}, protocol ${server.protocol})\n`); + if (info.data.tls) ctx.stdout(`HTTPS on the network, certificate fingerprint ${info.data.tls.fingerprint}\n`); + if (info.data.relay) ctx.stdout(`Relay ${info.data.relay.url}: ${info.data.relay.connected ? "connected" : "not connected (retrying)"}\n`); + ctx.stdout(sessions.length === 0 ? "No sessions.\n" : sessions.map((s) => `${s.id} ${s.state} ${s.cwd ?? s.name} seq ${s.seq}, ${s.subscribers} subscriber(s)${s.pendingDialogs ? `, ${s.pendingDialogs} dialog(s) waiting` : ""}`).join("\n") + "\n"); + } + return 0; + } + if (args.action === "stop") { + if (!(await stopServer(ctx, server, args.endSessions))) return 1; + ctx.stdout("Stopped.\n"); + return 0; + } + if (args.action === "pair") { + const result = await api (server, "POST", "/api/pairing-codes", { scopes: args.scopes }); + if (result.status !== 201) return apiFailure(ctx, "pair", result); + const { code, scopes = [], expiresAt } = result.data; + if (args.json) { + ctx.stdout(`${JSON.stringify({ code, scopes, expiresAt, url: server.url })}\n`); + } else { + ctx.stdout([ + `Pairing code: ${code}`, + `Server: ${server.url}`, + `Scopes: ${scopes.join(", ")}`, + `Expires: ${expiresAt} (single use)`, + "", + "Redeem it from the device:", + ` curl -X POST ${server.url}/api/pair -H 'Content-Type: application/json' -d '{"code":"${code}","name":"my-device"}'`, + "", + ].join("\n")); + } + return 0; + } + if (args.revoke !== undefined) { + const result = await api(server, "DELETE", `/api/devices/${args.revoke}`); + if (result.status !== 200) return apiFailure(ctx, "revoke", result); + ctx.stdout(`Revoked ${args.revoke}.\n`); + return 0; + } + const result = await api (server, "GET", "/api/devices"); + if (result.status !== 200) return apiFailure(ctx, "devices", result); + ctx.stdout(args.json ? `${JSON.stringify({ devices: result.data.devices ?? [] })}\n` : formatDevices(result.data.devices ?? [])); + return 0; + } catch (error) { + ctx.stderr(`gentle-shell serve: could not reach the server at ${server.url}: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +} diff --git a/runtime/serve-discovery.mjs b/runtime/serve-discovery.mjs new file mode 100644 index 000000000..ef77f61fd --- /dev/null +++ b/runtime/serve-discovery.mjs @@ -0,0 +1,115 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// LAN discovery for `gentle-shell serve`: a server open to the network answers a +// UDP broadcast query with its id, name and HTTP port, so a client that holds +// only the short pairing code can find it. Replies carry no secrets; a client +// still checks `/.well-known/gentle-shell` at the reply's source address before +// it sends the pairing code there. Zero dependencies (node:dgram). + +import { createSocket, } from "node:dgram"; + +export const DISCOVERY_QUERY = "gentle-shell/discover"; +export const DISCOVERY_REPLY = "gentle-shell/here"; +export const DISCOVERY_VERSION = 1; +/** Larger datagrams are dropped unread. */ +export const DISCOVERY_MAX_DATAGRAM = 512; +export const DISCOVERY_LIMITS = { globalPerSecond: 20, perSourcePerSecond: 4 }; + +/** Whether `datagram` is a discovery query: `{"t":"gentle-shell/discover","v":1}` (other keys ignored). */ +export function isDiscoveryQuery(datagram ) { + if (datagram.length === 0 || datagram.length > DISCOVERY_MAX_DATAGRAM) return false; + try { + const value = JSON.parse(datagram.toString("utf8")) ; + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const query = value ; + return query.t === DISCOVERY_QUERY && query.v === DISCOVERY_VERSION; + } catch { + return false; + } +} + +/** `{"t":"gentle-shell/here","v":1,"id","n","p"}`, plus `"tls":true,"fp"` when the server serves HTTPS: a hint only, the client pins what the handshake shows after a pairing proof. */ +export function discoveryReply(server ) { + return Buffer.from(JSON.stringify({ t: DISCOVERY_REPLY, v: DISCOVERY_VERSION, id: server.id, n: server.name, p: server.port, ...(server.fingerprint === undefined ? {} : { tls: true, fp: server.fingerprint }) }), "utf8"); +} + +/** + * Replies allowed per one-second window, overall and per source address. The + * global cap is checked first, so a window tracks at most that many sources. + */ +export class DiscoveryRateLimiter { + windowStart = Number.NEGATIVE_INFINITY; + total = 0; + perSource = new Map (); + limits ; + constructor(limits = DISCOVERY_LIMITS) { + this.limits = limits; + } + + allow(source , now ) { + if (now - this.windowStart >= 1000 || now < this.windowStart) { + this.windowStart = now; + this.total = 0; + this.perSource.clear(); + } + if (this.total >= this.limits.globalPerSecond) return false; + const count = this.perSource.get(source) ?? 0; + if (count >= this.limits.perSourcePerSecond) return false; + this.perSource.set(source, count + 1); + this.total += 1; + return true; + } +} + + + + + + + + + + + + + + + + + + + + +/** Binds UDP `0.0.0.0:` and answers discovery queries by unicast to their sender; rejects when the bind fails. */ +export function startDiscoveryResponder(options ) { + const now = options.now ?? Date.now; + const log = options.log ?? (() => {}); + const limiter = new DiscoveryRateLimiter(options.limits); + const socket = createSocket({ type: "udp4" }); + const { promise, resolve, reject } = Promise.withResolvers (); + let bound = false; + socket.on("error", (error) => { + if (!bound) { + socket.close(); + reject(error); + return; + } + log(`discovery: ${error.message}`); + }); + socket.on("message", (datagram , from ) => { + if (!isDiscoveryQuery(datagram) || !limiter.allow(from.address, now())) return; + const reply = discoveryReply({ id: options.serverId, name: options.name(), port: options.httpPort, ...(options.fingerprint === undefined ? {} : { fingerprint: options.fingerprint }) }); + socket.send(reply, from.port, from.address, (error) => { if (error) log(`discovery: reply to ${from.address}:${from.port} failed: ${error.message}`); }); + }); + socket.bind({ port: options.port, address: "0.0.0.0", exclusive: true }, () => { + bound = true; + resolve({ + port: socket.address().port, + close: () => { + const closed = Promise.withResolvers (); + socket.close(() => closed.resolve()); + return closed.promise; + }, + }); + }); + return promise; +} diff --git a/runtime/serve-files.mjs b/runtime/serve-files.mjs new file mode 100644 index 000000000..207a04238 --- /dev/null +++ b/runtime/serve-files.mjs @@ -0,0 +1,423 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// Files on the server for `gentle-shell serve`: list, stat, read, write, +// mkdir, rename, remove, filename search and change streams, so a client +// can browse and edit a project that lives on the server. Paths are absolute +// server paths; every operation runs as the server user, so `sessions:operate` +// is that user's file authority (the same as a session's own tools): it reads +// and changes files. `sessions:read` lists, stats, searches names and watches. + +import { randomBytes } from "node:crypto"; +import { constants as fsConstants, realpathSync, statSync, watch, } from "node:fs"; +import { chmod, copyFile, link, lstat, mkdir, open, opendir, readlink, realpath, rename, rm, rmdir, stat, unlink } from "node:fs/promises"; + +import { homedir } from "node:os"; +import { basename, dirname, join, parse, relative, sep } from "node:path"; + +import { absolutePath, fsHttpError, HttpError, need, readJsonBody, realDirectory, receiveBodyToFile, SECURITY_HEADERS, sendJson, sseEvent, startSse } from "./serve-http.mjs"; + +export const SERVE_FS_LIMITS = { + /** Entries one `list` returns; `truncated` past this. */ + listEntries: 5000, + /** Bytes one `read` returns. */ + readBytes: 8 * 1024 * 1024, + /** Bytes one `write` accepts. */ + writeBytes: 64 * 1024 * 1024, + searchDefault: 100, + searchMax: 1000, + /** Directory entries one search looks at, and how long it may walk. */ + searchVisit: 200_000, + searchMs: 5_000, + /** Quiet time before a batch of changes is sent, and the longest a change waits. */ + watchDebounceMs: 150, + watchMaxDelayMs: 1_000, + watchersPerDevice: 32, + /** Paths one change batch names; past this it says `overflow` (rescan). */ + watchBatchPaths: 1000, + smallBodyBytes: 16 * 1024, +}; + +/** Folders a search never enters. */ +const SEARCH_SKIP = { ".git": true, "node_modules": true }; + + + +function kindOf(stats ) { + if (stats.isSymbolicLink()) return "symlink"; + if (stats.isDirectory()) return "dir"; + if (stats.isFile()) return "file"; + return "other"; +} + +/** A validator for a file's version: size and modification time (µs). */ +export function fileEtag(stats ) { + return `"${stats.size.toString(36)}-${Math.round(stats.mtimeMs * 1000).toString(36)}"`; +} + +async function linkKind(path ) { + try { + const target = await stat(path); + return target.isDirectory() ? "dir" : target.isFile() ? "file" : "other"; + } catch { + return null; // dangling + } +} + +/** + * Scores a filename against a lowercase query: exact name 100, name prefix 80, + * name substring 60, relative path substring 40, the query's characters in + * order in the name 10; 0 is no match. + */ +export function searchScore(name , relativePath , needle ) { + const lower = name.toLowerCase(); + if (lower === needle) return 100; + if (lower.startsWith(needle)) return 80; + if (lower.includes(needle)) return 60; + if (relativePath.toLowerCase().replaceAll("\\", "/").includes(needle)) return 40; + let at = 0; + for (const ch of lower) if (ch === needle[at]) at += 1; + return at === needle.length ? 10 : 0; +} + + + + + + + + + + + + + + + + +export class FileService { + limits ; + now ; + log ; + watches = new Set (); + /** The server user's home, symlinks resolved: never removed or renamed, nor any folder above it. */ + home ; + + constructor(options = {}) { + this.limits = { ...SERVE_FS_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.log = options.log ?? (() => {}); + let home = homedir(); + try { home = realpathSync(home); } catch { /* keep as is */ } + this.home = home; + } + + /** Answers `/api/fs/*`; false for any other path. */ + async route(req , res , method , path , url , principal ) { + if (!path.startsWith("/api/fs/")) return false; + const op = path.slice("/api/fs/".length); + const expect = (wanted ) => { if (method !== wanted) throw new HttpError(405, "method_not_allowed", `Use ${wanted}`); }; + switch (op) { + case "list": expect("GET"); need(principal, "sessions:read"); await this.list(res, url); return true; + case "stat": expect("GET"); need(principal, "sessions:read"); await this.stat(res, url); return true; + // Contents need `sessions:operate`: a device that only watches would otherwise read secrets (mcp.json, auth.json). + case "read": expect("GET"); need(principal, "sessions:operate"); await this.read(req, res, url); return true; + case "search": expect("GET"); need(principal, "sessions:read"); await this.search(res, url); return true; + case "watch": expect("GET"); this.watch(req, res, url, need(principal, "sessions:read")); return true; + case "write": expect("PUT"); need(principal, "sessions:operate"); await this.write(req, res, url); return true; + case "mkdir": expect("POST"); need(principal, "sessions:operate"); await this.mkdir(req, res); return true; + case "rename": expect("POST"); need(principal, "sessions:operate"); await this.rename(req, res); return true; + case "remove": expect("POST"); need(principal, "sessions:operate"); await this.remove(req, res); return true; + default: throw new HttpError(404, "not_found", "Not found"); + } + } + + async list(res , url ) { + const dirPath = absolutePath(url.searchParams.get("path")); + const names = []; + let truncated = false; + try { + const dir = await opendir(dirPath); + for await (const entry of dir) { + if (names.length >= this.limits.listEntries) { truncated = true; break; } + names.push(entry.name); + } + } catch (error) { + throw fsHttpError(error, dirPath); + } + const entries = []; + for (let i = 0; i < names.length; i += 128) { + const batch = await Promise.all(names.slice(i, i + 128).map(async (name) => { + const full = join(dirPath, name); + try { + const stats = await lstat(full); + const kind = kindOf(stats); + return { name, kind, size: stats.size, mtime: Math.floor(stats.mtimeMs), ...(kind === "symlink" ? { linkKind: await linkKind(full) } : {}) }; + } catch { + return undefined; // removed while listing + } + })); + for (const entry of batch) if (entry) entries.push(entry); + } + entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + sendJson(res, 200, { path: dirPath, entries, truncated }); + } + + async stat(res , url ) { + const path = absolutePath(url.searchParams.get("path")); + let stats ; + try { stats = await lstat(path); } catch (error) { throw fsHttpError(error, path); } + const kind = kindOf(stats); + let real ; + try { real = await realpath(path); } catch { /* dangling link */ } + const followed = kind === "symlink" && real !== undefined ? await stat(real).catch(() => undefined) : undefined; + sendJson(res, 200, { + path, + name: basename(path), + kind, + size: stats.size, + mtime: Math.floor(stats.mtimeMs), + mode: stats.mode & 0o7777, + ...(kind === "file" ? { etag: fileEtag(stats) } : {}), + ...(kind === "symlink" ? { linkTarget: await readlink(path).catch(() => null), linkKind: await linkKind(path) } : {}), + ...(followed?.isFile() ? { etag: fileEtag(followed), size: followed.size } : {}), + ...(real === undefined ? {} : { realPath: real }), + }); + } + + async read(req , res , url ) { + const path = absolutePath(url.searchParams.get("path")); + const offset = wholeNumber(url.searchParams.get("offset"), "offset") ?? 0; + const asked = wholeNumber(url.searchParams.get("length"), "length"); + // O_NONBLOCK: opening a FIFO never waits for a writer. + const handle = await open(path, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0)).catch((error ) => { throw fsHttpError(error, path); }); + try { + const stats = await handle.stat(); + if (!stats.isFile()) throw new HttpError(400, "not_a_file", `${path} is not a regular file`); + const etag = fileEtag(stats); + const headers = { ETag: etag, "Last-Modified": new Date(stats.mtimeMs).toUTCString(), "X-File-Size": String(stats.size), "X-File-Mtime": String(Math.floor(stats.mtimeMs)) }; + const inm = req.headers["if-none-match"]; + const ims = req.headers["if-modified-since"]; + const unchanged = typeof inm === "string" ? inm.split(",").some((tag) => tag.trim() === etag) + : typeof ims === "string" && Number.isFinite(Date.parse(ims)) && Math.floor(stats.mtimeMs / 1000) * 1000 <= Date.parse(ims); + if (unchanged) { + res.writeHead(304, { ...SECURITY_HEADERS, ...headers }); + return void res.end(); + } + const length = Math.max(0, Math.min(asked ?? this.limits.readBytes, this.limits.readBytes, stats.size - offset)); + const buffer = Buffer.allocUnsafe(length); + let got = 0; + while (got < length) { + const { bytesRead } = await handle.read(buffer, got, length - got, offset + got); + if (bytesRead === 0) break; + got += bytesRead; + } + res.writeHead(200, { ...SECURITY_HEADERS, ...headers, "Content-Type": "application/octet-stream", "Content-Length": got, "X-Offset": String(offset), + "X-Truncated": offset + got < stats.size ? "1" : "0" }); + res.end(got === length ? buffer : buffer.subarray(0, got)); + } finally { + await handle.close(); + } + } + + async write(req , res , url ) { + const target = absolutePath(url.searchParams.get("path")); + const createOnly = url.searchParams.get("create_only") === "1" || url.searchParams.get("create_only") === "true"; + // A save through a symlink replaces the file it points to and keeps the link. + let real ; + let existing ; + try { + real = await realpath(target); + existing = await stat(real); + } catch (error) { + if ((error ).code !== "ENOENT") throw fsHttpError(error, target); + if (await lstat(target).then((s) => s.isSymbolicLink(), () => false)) throw new HttpError(409, "dangling_symlink", `${target} is a link to a file that does not exist`); + const parent = await realpath(dirname(target)).catch((e ) => { throw fsHttpError(e, dirname(target)); }); + real = join(parent, basename(target)); + } + if (existing && createOnly) throw new HttpError(409, "exists", `${target} already exists`); + if (existing && !existing.isFile()) throw new HttpError(400, "not_a_file", `${target} is not a regular file`); + const ifMatch = req.headers["if-match"]; + if (typeof ifMatch === "string" && (!existing || !ifMatch.split(",").some((tag) => tag.trim() === fileEtag(existing)))) { + throw new HttpError(412, "changed", `${target} changed since it was read`); + } + const temp = join(dirname(real), `.${basename(real)}.gs-${randomBytes(6).toString("hex")}.tmp`); + const mode = existing ? existing.mode & 0o7777 : 0o666; + try { + await receiveBodyToFile(req, temp, this.limits.writeBytes, mode).catch((error ) => { throw fsHttpError(error, target); }); + if (existing) await chmod(temp, mode); + if (createOnly) { + try { + await link(temp, real); + } catch (error) { + if ((error ).code === "EEXIST") throw new HttpError(409, "exists", `${target} already exists`); + // No hard links here (some network and FAT volumes): an exclusive copy. + await copyFile(temp, real, fsConstants.COPYFILE_EXCL).catch((e ) => { throw fsHttpError(e, target); }); + } + } else { + await rename(temp, real).catch((error ) => { throw fsHttpError(error, target); }); + } + } finally { + await rm(temp, { force: true }); + } + const stats = await stat(real); + sendJson(res, existing ? 200 : 201, { path: target, size: stats.size, mtime: Math.floor(stats.mtimeMs), etag: fileEtag(stats), created: !existing }); + } + + async mkdir(req , res ) { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const path = absolutePath(body.path); + const first = await mkdir(path, { recursive: true }).catch((error ) => { throw fsHttpError(error, path); }); + sendJson(res, first === undefined ? 200 : 201, { path, created: first !== undefined }); + } + + /** The entry itself (its folder's symlinks resolved, the last component kept), refused when it is a root, the home or a folder above it. */ + async entry(path ) { + const root = parse(path).root; + const canonical = path === root ? root : join(await realpath(dirname(path)).catch((e ) => { throw fsHttpError(e, path); }), basename(path)); + if (canonical === parse(canonical).root || canonical === this.home || this.home.startsWith(canonical.endsWith(sep) ? canonical : canonical + sep)) { + throw new HttpError(403, "protected_path", `${path} is the file system root, the home folder or a folder that holds it`); + } + return canonical; + } + + async rename(req , res ) { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const from = absolutePath(body.from, "from"); + const to = absolutePath(body.to, "to"); + const source = await this.entry(from); + const dest = await this.entry(to); + const sourceStats = await lstat(source).catch((error ) => { throw fsHttpError(error, from); }); + if (body.overwrite !== true) { + const there = await lstat(dest).catch(() => undefined); + // The same entry (a case-only rename on a case-insensitive volume) is not a clash. + if (there && !(there.ino === sourceStats.ino && there.dev === sourceStats.dev)) throw new HttpError(409, "exists", `${to} already exists`); + } + await rename(source, dest).catch((error ) => { throw fsHttpError(error, to); }); + sendJson(res, 200, { from, to }); + } + + async remove(req , res ) { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const path = absolutePath(body.path); + const canonical = await this.entry(path); + const stats = await lstat(canonical).catch((error ) => { throw fsHttpError(error, path); }); + try { + if (stats.isDirectory()) { + if (body.recursive === true) await rm(canonical, { recursive: true }); + else await rmdir(canonical); + } else { + await unlink(canonical); + } + } catch (error) { + throw fsHttpError(error, path); + } + sendJson(res, 200, { removed: path }); + } + + async search(res , url ) { + const root = realDirectory(url.searchParams.get("root")); + const q = url.searchParams.get("q") ?? ""; + if (q.length === 0 || q.length > 256 || q.includes("\0")) throw new HttpError(400, "invalid_query", "q must be 1-256 characters"); + const limit = Math.min(wholeNumber(url.searchParams.get("limit"), "limit") ?? this.limits.searchDefault, this.limits.searchMax); + const needle = q.toLowerCase(); + const deadline = this.now() + this.limits.searchMs; + const matches = []; + const queue = [root]; + let visited = 0; + let truncated = false; + walk: while (queue.length > 0) { + const dir = queue.shift() ; + let handle; + try { handle = await opendir(dir); } catch { continue; } + for await (const entry of handle) { + visited += 1; + if (visited > this.limits.searchVisit || this.now() > deadline) { truncated = true; break walk; } + const full = join(dir, entry.name); + if (entry.isDirectory()) { + if (Object.hasOwn(SEARCH_SKIP, entry.name)) continue; + queue.push(full); + } + const score = searchScore(entry.name, relative(root, full), needle); + if (score > 0) matches.push({ path: full, name: entry.name, kind: entry.isSymbolicLink() ? "symlink" : entry.isDirectory() ? "dir" : entry.isFile() ? "file" : "other", score }); + } + } + matches.sort((a, b) => b.score - a.score || a.path.length - b.path.length || (a.path < b.path ? -1 : 1)); + sendJson(res, 200, { root, results: matches.slice(0, limit), truncated }); + } + + watch(req , res , url , principal ) { + const path = absolutePath(url.searchParams.get("path")); + let stats ; + try { + stats = statSync(path); + } catch (error) { + throw fsHttpError(error, path); + } + const own = [...this.watches].filter((w) => w.deviceId === principal.deviceId).length; + if (own >= this.limits.watchersPerDevice) throw new HttpError(429, "too_many_watchers", `At most ${this.limits.watchersPerDevice} change streams per device`); + const isDir = stats.isDirectory(); + let watcher ; + let recursive = isDir; + try { + try { + watcher = watch(path, { recursive }); + } catch (error) { + if ((error ).code !== "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM") throw error; + recursive = false; + watcher = watch(path); + } + } catch (error) { + throw fsHttpError(error, path); + } + const base = isDir ? path : dirname(path); + const entry = { deviceId: principal.deviceId, res, watcher, pending: new Set(), firstAt: 0 }; + this.watches.add(entry); + startSse(req, res); + res.write(`retry: 3000\n\n${sseEvent("ready", { path, recursive })}`); + const flush = () => { + entry.timer = undefined; + const paths = [...entry.pending]; + entry.pending.clear(); + if (paths.length === 0) return; + res.write(sseEvent("changes", paths.length > this.limits.watchBatchPaths ? { paths: [], overflow: true } : { paths })); + }; + watcher.on("change", (_type, filename) => { + const name = filename === null || filename === undefined ? "" : filename.toString(); + if (entry.pending.size === 0) entry.firstAt = this.now(); + entry.pending.add(name === "" ? path : isDir ? join(base, name) : path); + clearTimeout(entry.timer); + const wait = Math.max(0, Math.min(this.limits.watchDebounceMs, entry.firstAt + this.limits.watchMaxDelayMs - this.now())); + entry.timer = setTimeout(flush, wait); + }); + watcher.on("error", (error) => { + res.end(sseEvent("error", { message: error.message })); + }); + res.on("close", () => this.stopWatch(entry)); + this.log(`watch ${path} for ${principal.deviceId}${recursive ? " (recursive)" : ""}`); + } + + stopWatch(entry ) { + if (!this.watches.delete(entry)) return; + clearTimeout(entry.timer); + entry.watcher.close(); + if (!entry.res.writableEnded) entry.res.end(); + } + + heartbeat() { + for (const entry of this.watches) entry.res.write(": ping\n\n"); + } + + /** Ends a device's change streams (revoked). */ + closeDevice(deviceId ) { + for (const entry of [...this.watches]) if (entry.deviceId === deviceId) this.stopWatch(entry); + } + + closeAll() { + for (const entry of [...this.watches]) this.stopWatch(entry); + } +} + +function wholeNumber(raw , name ) { + if (raw === null || raw === "") return undefined; + if (!/^\d{1,15}$/.test(raw)) throw new HttpError(400, `invalid_${name}`, `${name} must be a whole number`); + return Number(raw); +} diff --git a/runtime/serve-forward.mjs b/runtime/serve-forward.mjs new file mode 100644 index 000000000..046fdf227 --- /dev/null +++ b/runtime/serve-forward.mjs @@ -0,0 +1,514 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// Authenticated port forwarding for `gentle-shell serve`: a web page that +// lives on the server's loopback (the design canvas, a dev server the agent +// started, Gentle Tower) opened from another machine. Each forward is its own +// listener on the server's listen address, so the page's absolute paths keep +// working, and it proxies only to 127.0.0.1: or [::1]:. +// +// A forward belongs to one device. Its first request carries a single-use +// ticket (`gs_ticket`, 60 s); the listener answers with a redirect that drops +// the ticket and sets a per-forward cookie (`gs_fwd_`), which every later +// request needs. Browsers share cookies across ports, so the name is the +// forward's own and the proxy strips every `gs_fwd_*` cookie and the ticket +// before the target sees the request. Zero dependencies: `http` and `net`. + +import { randomBytes } from "node:crypto"; +import { request as httpRequest, } from "node:http"; +import { connect, } from "node:net"; +import { hashSecret } from "./serve-auth.mjs"; +import { createServeListener, requestScheme, } from "./serve-tls.mjs"; + +export const SERVE_FORWARD_LIMITS = { + ticketTtlMs: 60_000, + maxTickets: 256, + /** A forward with no open connection and no request for this long is closed. */ + idleMs: 12 * 60 * 60_000, + sweepMs: 60_000, + /** Forwards open at once, across devices. */ + maxForwards: 32, + /** Open client connections per forward; more are refused at accept. */ + maxConnections: 64, + /** Browser sessions (cookies) one forward keeps; the oldest is dropped past this. */ + maxCookies: 32, + /** Connecting to the page on the server. */ + connectTimeoutMs: 10_000, + /** The browser sending a request's headers. */ + headersTimeoutMs: 20_000, + /** An idle keep-alive connection from the browser. */ + keepAliveTimeoutMs: 5_000, +}; + +export const FORWARD_TICKET_PARAM = "gs_ticket"; +export const FORWARD_COOKIE_PREFIX = "gs_fwd_"; + +/** A session's page (closed with it), Gentle Tower, or a server-level page such as Engram (`POST /api/forwards`). */ + + + + + + + + + + + + + + + + +export class ForwardError extends Error { + status ; + code ; + constructor(status , code , message ) { + super(message); + this.status = status; + this.code = code; + } +} + + + + + + + + + + + + + + + +/** Hop-by-hop headers (RFC 9110 §7.6.1), never passed through a proxy. */ +const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"]); + +const OWN_HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer" }; + + +const literal = (host ) => (host === "::1" ? "[::1]" : host); + + + + + + + + + + + + + + + + + + + +/** The Connection header's own hop-by-hop names, plus the fixed ones. */ +function hopHeaders(headers ) { + const names = new Set(HOP_BY_HOP); + const connection = headers.connection; + if (typeof connection === "string") for (const token of connection.split(",")) if (token.trim()) names.add(token.trim().toLowerCase()); + return names; +} + +/** Every cookie except the forwards' own, joined as the browser sent them; undefined when none is left. */ +export function stripForwardCookies(header ) { + if (!header) return undefined; + const kept = header.split(";").map((c) => c.trim()).filter((c) => c && !c.startsWith(FORWARD_COOKIE_PREFIX)); + return kept.length === 0 ? undefined : kept.join("; "); +} + +function cookieValue(header , name ) { + if (!header) return undefined; + for (const part of header.split(";")) { + const eq = part.indexOf("="); + if (eq !== -1 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim(); + } + return undefined; +} + +/** The request target without the ticket parameter, and the ticket (when present). */ +export function splitTicket(rawUrl ) { + const q = rawUrl.indexOf("?"); + if (q === -1) return { path: rawUrl }; + let ticket ; + const kept = []; + for (const param of rawUrl.slice(q + 1).split("&")) { + if (param.startsWith(`${FORWARD_TICKET_PARAM}=`)) ticket = param.slice(FORWARD_TICKET_PARAM.length + 1); + else if (param !== "") kept.push(param); + } + return { path: rawUrl.slice(0, q) + (kept.length ? `?${kept.join("&")}` : ""), ...(ticket === undefined ? {} : { ticket }) }; +} + +function plain(res , status , text , extra = {}) { + if (res.headersSent) { res.destroy(); return; } + res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8", "Content-Length": Buffer.byteLength(text), ...OWN_HEADERS, ...extra }); + res.end(text); +} + +function refuseUpgrade(socket , status , reason ) { + socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); +} + +function listenOn(server , port , host ) { + const { promise, resolve, reject } = Promise.withResolvers (); + const onError = (error ) => reject(error); + server.once("error", onError); + server.listen(port, host, () => { + server.off("error", onError); + const address = server.address(); + resolve(typeof address === "object" && address ? address.port : port); + }); + return promise; +} + +function canConnect(host , port , timeoutMs ) { + const { promise, resolve } = Promise.withResolvers (); + const socket = connect({ host, port }); + const timer = setTimeout(() => { socket.destroy(); resolve(false); }, timeoutMs); + socket.once("connect", () => { clearTimeout(timer); socket.destroy(); resolve(true); }); + socket.once("error", () => { clearTimeout(timer); resolve(false); }); + return promise; +} + +export class ForwardManager { + options ; + limits ; + now ; + log ; + forwards = new Map (); + /** Keyed by the ticket's hash. */ + tickets = new Map (); + sweep ; + closed = false; + + constructor(options ) { + this.options = options; + this.limits = { ...SERVE_FORWARD_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.log = options.log ?? (() => {}); + this.sweep = setInterval(() => this.closeIdle(), this.limits.sweepMs); + this.sweep.unref(); + } + + /** Ports the forwards listen on: never a target (a forward to a forward loops). */ + listenPorts() { + return [...this.forwards.values()].map((f) => f.info.listenPort); + } + + list(filter = {}) { + return [...this.forwards.values()].map((f) => f.info).filter((f) => + (filter.deviceId === undefined || f.deviceId === filter.deviceId) + && (filter.sessionId === undefined || f.sessionId === filter.sessionId) + && (filter.kind === undefined || f.kind === filter.kind)); + } + + get(id ) { + return this.forwards.get(id)?.info; + } + + /** + * The device's forward to `port` for this session (or Gentle Tower), opened + * when it has none. A forward belongs to one session so that it closes with it. + */ + async open(input ) { + if (this.closed) throw new ForwardError(503, "shutting_down", "The server is stopping"); + const existing = this.list({ deviceId: input.deviceId, sessionId: input.sessionId, kind: input.kind }).find((f) => f.port === input.port); + if (existing) { + existing.lastUsedAt = this.now(); + return { forward: existing, created: false }; + } + if (this.forwards.size >= this.limits.maxForwards) throw new ForwardError(429, "too_many_forwards", `At most ${this.limits.maxForwards} forwards are open at once; close one first`); + const id = `fwd_${randomBytes(8).toString("hex")}`; + const info = { id, port: input.port, listenPort: 0, deviceId: input.deviceId, sessionId: input.sessionId, kind: input.kind, createdAt: this.now(), lastUsedAt: this.now() }; + const sockets = new Set (); + const listener = createServeListener({ + ...(this.options.tls === undefined ? {} : { tls: this.options.tls }), + setup: (http, via) => { + http.headersTimeout = this.limits.headersTimeoutMs; + http.requestTimeout = 0; // streams (SSE) stay open + http.keepAliveTimeout = this.limits.keepAliveTimeoutMs; + http.on("request", (req , res ) => this.handle(state, req, res, via)); + http.on("upgrade", (req , socket , head ) => this.upgrade(state, req, socket, head, via)); + http.on("clientError", (_error, socket ) => { if (socket.writable) socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"); else socket.destroy(); }); + }, + onConnection: (socket) => { + sockets.add(socket); + socket.on("close", () => sockets.delete(socket)); + }, + }); + const state = { info, server: listener.server, listener, hostOk: () => false, sockets, cookies: new Set() }; + const server = state.server; + server.maxConnections = this.limits.maxConnections; + const host = this.options.bindHost.replace(/^\[|\]$/g, ""); + state.info.listenPort = await this.bind(server, host); + if (this.closed) { + server.close(); + throw new ForwardError(503, "shutting_down", "The server is stopping"); + } + state.hostOk = this.options.hostCheck(state.info.listenPort); + this.forwards.set(id, state); + this.log(`forward ${id}: :${state.info.listenPort} → loopback:${input.port} for ${input.deviceId}${input.sessionId ? ` (${input.sessionId})` : ` (${input.kind})`}`); + return { forward: state.info, created: true }; + } + + async bind(server , host ) { + const range = this.options.portRange; + if (!range) return listenOn(server, 0, host); + const taken = new Set(this.listenPorts()); + for (let port = range.from; port <= range.to; port += 1) { + if (taken.has(port)) continue; + try { + return await listenOn(server, port, host); + } catch (error) { + const code = (error ).code; + if (code !== "EADDRINUSE" && code !== "EACCES") throw error; + } + } + throw new ForwardError(503, "no_forward_port", `Every port in the forward range ${range.from}-${range.to} is in use`); + } + + /** A single-use ticket for the forward's first request, bound to the forward and its device. */ + mintTicket(forwardId ) { + const state = this.forwards.get(forwardId); + if (!state) throw new ForwardError(404, "not_found", "No such forward"); + this.pruneTickets(); + const ticket = randomBytes(24).toString("base64url"); + const expiresAt = this.now() + this.limits.ticketTtlMs; + this.tickets.set(hashSecret(ticket).toString("hex"), { forwardId, deviceId: state.info.deviceId, expiresAt }); + while (this.tickets.size > this.limits.maxTickets) this.tickets.delete(this.tickets.keys().next().value ); + return { ticket, expiresAt }; + } + + /** Where a relayed connection for a forward's listen port goes; undefined when no forward listens there. */ + relayTarget(listenPort ) { + const state = [...this.forwards.values()].find((f) => f.info.listenPort === listenPort); + if (!state) return undefined; + return (socket) => { + if (state.sockets.size >= this.limits.maxConnections) return void socket.destroy(); + state.listener.acceptRelayed(socket); + }; + } + + /** The URL a browser opens: the host and scheme the client used, the forward's port, the page's path and the ticket. */ + urlFor(forwardId , clientHost , path , ticket , scheme = "http") { + const state = this.forwards.get(forwardId); + if (!state) throw new ForwardError(404, "not_found", "No such forward"); + const hash = path.indexOf("#"); + const target = hash === -1 ? path : path.slice(0, hash); + const fragment = hash === -1 ? "" : path.slice(hash); + return `${scheme}://${clientHost}:${state.info.listenPort}${target}${target.includes("?") ? "&" : "?"}${FORWARD_TICKET_PARAM}=${ticket}${fragment}`; + } + + redeemTicket(ticket , state ) { + if (ticket.length === 0 || ticket.length > 64) return false; + this.pruneTickets(); + const key = hashSecret(ticket).toString("hex"); + const entry = this.tickets.get(key); + if (!entry) return false; + this.tickets.delete(key); + return entry.forwardId === state.info.id && entry.deviceId === state.info.deviceId; + } + + pruneTickets() { + const now = this.now(); + for (const [key, entry] of this.tickets) if (entry.expiresAt <= now) this.tickets.delete(key); + } + + cookieName(state ) { + return `${FORWARD_COOKIE_PREFIX}${state.info.id}`; + } + + hasCookie(state , req ) { + const value = cookieValue(req.headers.cookie, this.cookieName(state)); + if (!value || value.length > 128) return false; + return state.cookies.has(hashSecret(value).toString("hex")); + } + + /** Host and Origin, as the main server checks them (no Host check through a relay); a message when refused. */ + refused(state , req , via ) { + const host = req.headers.host; + if (typeof host !== "string" || (via !== "relay" && !state.hostOk(host))) return { status: 421, reason: "Misdirected Request", message: "Unexpected Host header" }; + // Another page (another forward on this host is the same site) never drives this one; no CORS is added either. + const origin = req.headers.origin?.toLowerCase(); + if (origin !== undefined && origin !== `http://${host.toLowerCase()}` && origin !== `https://${host.toLowerCase()}`) return { status: 403, reason: "Forbidden", message: "Origin not allowed" }; + if (!(req.url ?? "").startsWith("/")) return { status: 400, reason: "Bad Request", message: "Bad request" }; + return undefined; + } + + handle(state , req , res , via ) { + const refused = this.refused(state, req, via); + if (refused) return plain(res, refused.status, refused.message); + const { path, ticket } = splitTicket(req.url ?? "/"); + if (ticket !== undefined) { + if (req.method !== "GET" && req.method !== "HEAD") return plain(res, 405, "A forward link opens with GET"); + const headers = { Location: path }; + if (this.redeemTicket(ticket, state)) { + const secret = randomBytes(32).toString("base64url"); + state.cookies.add(hashSecret(secret).toString("hex")); + while (state.cookies.size > this.limits.maxCookies) state.cookies.delete(state.cookies.values().next().value ); + headers["Set-Cookie"] = `${this.cookieName(state)}=${secret}; HttpOnly; SameSite=Strict; Path=/`; + } else if (!this.hasCookie(state, req)) { + return plain(res, 401, "This link expired or was already used. Open the page again from Gentle Shell."); + } + state.info.lastUsedAt = this.now(); + res.writeHead(303, { ...OWN_HEADERS, ...headers, "Content-Length": 0 }); + return void res.end(); + } + if (!this.hasCookie(state, req)) return plain(res, 401, "Open this page from Gentle Shell: it needs a fresh link."); + state.info.lastUsedAt = this.now(); + void this.proxy(state, req, res, path); + } + + /** Which loopback address answers on the port: 127.0.0.1 first, then [::1] (servers that bound `localhost` on IPv6 only). */ + async upstream(state ) { + if (state.upstream) return state.upstream; + for (const host of ["127.0.0.1", "::1"] ) { + if (await canConnect(host, state.info.port, this.limits.connectTimeoutMs)) return (state.upstream = host); + } + return undefined; + } + + /** The request's headers for the page: hop-by-hop gone, Host the page's own, Origin and Referer translated, forward cookies stripped. */ + upstreamHeaders(state , req , upstream , keepUpgrade ) { + const own = `${requestScheme(req)}://${req.headers.host}`; + const target = `http://${literal(upstream)}:${state.info.port}`; + const drop = hopHeaders(req.headers); + const headers = {}; + for (const [name, value] of Object.entries(req.headers)) { + if (value === undefined || name === "host" || name === "cookie") continue; + if (drop.has(name) && !(keepUpgrade && (name === "connection" || name === "upgrade"))) continue; + headers[name] = value; + } + headers.host = `${literal(upstream)}:${state.info.port}`; + const cookie = stripForwardCookies(req.headers.cookie); + if (cookie !== undefined) headers.cookie = cookie; + if (typeof headers.origin === "string") headers.origin = target; + if (typeof headers.referer === "string" && (headers.referer === own || headers.referer.startsWith(`${own}/`))) headers.referer = target + headers.referer.slice(own.length); + return headers; + } + + /** The page's response headers for the browser: hop-by-hop gone, loopback redirects pointed back at the forward, no `gs_fwd_*` cookie. */ + downstreamHeaders(state , req , upRes ) { + const drop = hopHeaders(upRes.headers); + const loopback = new RegExp(`^https?://(?:127\\.0\\.0\\.1|localhost|\\[::1\\]):${state.info.port}(?=[/?#]|$)`, "i"); + const out = []; + const raw = upRes.rawHeaders; + for (let i = 0; i + 1 < raw.length; i += 2) { + const name = raw[i]; + let value = raw[i + 1]; + const lower = name.toLowerCase(); + if (drop.has(lower)) continue; + if (lower === "set-cookie" && value.trimStart().startsWith(FORWARD_COOKIE_PREFIX)) continue; + if (lower === "location" || lower === "content-location") value = value.replace(loopback, `${requestScheme(req)}://${req.headers.host}`); + out.push(name, value); + } + return out; + } + + async proxy(state , req , res , path ) { + const upstream = await this.upstream(state); + if (res.destroyed) return; + if (!upstream) return plain(res, 502, `Nothing answers on port ${state.info.port} of the server.`); + const up = httpRequest({ host: upstream, port: state.info.port, method: req.method, path, headers: this.upstreamHeaders(state, req, upstream, false), agent: false }); + const connectTimer = setTimeout(() => up.destroy(new Error("connect timeout")), this.limits.connectTimeoutMs); + up.once("socket", (socket ) => { + socket.setNoDelay(true); + if (!socket.connecting) clearTimeout(connectTimer); + else socket.once("connect", () => clearTimeout(connectTimer)); + }); + up.on("response", (upRes ) => { + res.writeHead(upRes.statusCode ?? 502, upRes.statusMessage, this.downstreamHeaders(state, req, upRes)); + // Headers now, so a stream (SSE) starts before its first event; the body is never buffered. + res.flushHeaders(); + upRes.pipe(res); + upRes.on("error", () => res.destroy()); + upRes.on("aborted", () => res.destroy()); + }); + up.on("error", (error ) => { + clearTimeout(connectTimer); + if (error.code === "ECONNREFUSED") state.upstream = undefined; + if (!res.headersSent) plain(res, 502, `The page on port ${state.info.port} did not answer.`); + else res.destroy(); + }); + res.on("close", () => { + clearTimeout(connectTimer); + if (!res.writableFinished) up.destroy(); + }); + req.pipe(up); + } + + upgrade(state , req , socket , head , via ) { + socket.on("error", () => socket.destroy()); + const refused = this.refused(state, req, via); + if (refused) return refuseUpgrade(socket, refused.status, refused.reason); + // A WebSocket opens from a page already loaded through the forward: the cookie, never a ticket. + if (!this.hasCookie(state, req)) return refuseUpgrade(socket, 401, "Unauthorized"); + state.info.lastUsedAt = this.now(); + const { path } = splitTicket(req.url ?? "/"); + void this.upstream(state).then((upstream) => { + if (socket.destroyed) return; + if (!upstream) return refuseUpgrade(socket, 502, "Bad Gateway"); + const headers = this.upstreamHeaders(state, req, upstream, true); + const lines = [`${req.method} ${path} HTTP/1.1`]; + for (const [name, value] of Object.entries(headers)) for (const v of Array.isArray(value) ? value : [value]) lines.push(`${name}: ${v}`); + const target = connect({ host: upstream, port: state.info.port }); + const connectTimer = setTimeout(() => target.destroy(new Error("connect timeout")), this.limits.connectTimeoutMs); + let connected = false; + target.once("connect", () => { + connected = true; + clearTimeout(connectTimer); + target.setNoDelay(true); + socket.setNoDelay(true); + target.write(`${lines.join("\r\n")}\r\n\r\n`); + if (head.length > 0) target.write(head); + target.pipe(socket); + socket.pipe(target); + }); + target.on("error", (error ) => { + clearTimeout(connectTimer); + if (error.code === "ECONNREFUSED") state.upstream = undefined; + if (!connected) refuseUpgrade(socket, 502, "Bad Gateway"); + }); + target.on("close", () => { if (connected) socket.destroy(); }); + socket.on("close", () => target.destroy()); + }); + } + + /** Closes one forward: its listener, its open connections (WebSockets included) and its tickets. */ + close(id , reason = "closed") { + const state = this.forwards.get(id); + if (!state) return false; + this.forwards.delete(id); + for (const [key, entry] of this.tickets) if (entry.forwardId === id) this.tickets.delete(key); + state.server.close(); + state.listener.closeAllConnections(); + for (const socket of state.sockets) socket.destroy(); + this.log(`forward ${id}: ${reason}`); + return true; + } + + closeWhere(predicate , reason ) { + let count = 0; + for (const forward of this.list()) if (predicate(forward) && this.close(forward.id, reason)) count += 1; + return count; + } + + closeIdle() { + const now = this.now(); + for (const state of [...this.forwards.values()]) { + if (state.sockets.size === 0 && now - state.info.lastUsedAt >= this.limits.idleMs) this.close(state.info.id, "idle"); + } + } + + closeAll() { + this.closed = true; + clearInterval(this.sweep); + for (const id of [...this.forwards.keys()]) this.close(id, "server stopping"); + } +} diff --git a/runtime/serve-git.mjs b/runtime/serve-git.mjs new file mode 100644 index 000000000..9cc7bb96e --- /dev/null +++ b/runtime/serve-git.mjs @@ -0,0 +1,299 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `POST /api/git` for `gentle-shell serve`: one `git` command in a folder on +// the server (no shell), with its exit code and output, so a client shows +// and drives a repository that lives there. Commands that only read and print +// no file contents (status, branches, the log, changed paths and line counts) +// need `sessions:read`; anything else, contents included (`show`, a patch, a +// blob, `blame`, `grep`), `sessions:operate`, which is the server user's own +// authority: a device that only watches could otherwise read secrets the +// repository holds. Configuration and arguments that make git run another +// program are refused, so a read-only token cannot turn a read into a command. + +import { spawn, } from "node:child_process"; + + +import { HttpError, need, readJsonBody, realDirectory, sendJson } from "./serve-http.mjs"; + +export const SERVE_GIT_LIMITS = { + /** Default run time, and the most a request may ask for. */ + timeoutMs: 120_000, + /** The most a fetch, push, clone, pull, ls-remote or submodule may ask for. */ + networkTimeoutMs: 600_000, + stdoutBytes: 32 * 1024 * 1024, + stderrBytes: 1024 * 1024, + stdinBytes: 8 * 1024 * 1024, + /** The JSON body: base64 stdin plus arguments. */ + bodyBytes: 12 * 1024 * 1024, + maxArgs: 256, + argChars: 32 * 1024, + /** git processes at once, across devices. */ + maxRunning: 16, + /** After a timeout or truncation, SIGTERM; SIGKILL this much later. */ + killGraceMs: 2_000, +}; + +/** Global options that take the next argument as their value. */ +const GLOBAL_WITH_VALUE = { "-C": true, "-c": true, "--git-dir": true, "--work-tree": true, "--namespace": true, "--super-prefix": true, "--config-env": true }; + +/** Configuration keys (lowercase) that run a program or redirect what git runs. */ +const BLOCKED_CONFIG = [/^core\.sshcommand$/, /^core\.fsmonitor$/, /^core\.hookspath$/, /^core\.gitproxy$/, /^uploadpack\./, /^alias\./, + /^remote\..+\.(uploadpack|receivepack)$/, /^protocol\.ext\.allow$/]; + +/** Subcommands that only read and never print a file's contents. */ +const READ_SUBCOMMANDS = { + status: true, "rev-parse": true, "ls-files": true, "for-each-ref": true, "ls-tree": true, "rev-list": true, "merge-base": true, describe: true, + shortlog: true, "name-rev": true, "check-ignore": true, "check-attr": true, "show-ref": true, "count-objects": true, version: true, "ls-remote": true, +}; + +/** Reads that print commits or changed paths, and contents (a patch) only when asked; `diff` prints one unless told not to. */ +const DIFF_SUBCOMMANDS = { log: true, diff: true, "diff-tree": true, "diff-files": true, "diff-index": true }; + +/** Long options that print file contents (a patch, changed lines) or search them (a read-only token could guess a secret). */ +const CONTENT_OPTIONS = ["--patch", "--patch-with-raw", "--patch-with-stat", "--unified", "--cc", "--dd", "--word-diff", "--word-diff-regex", "--color-words", + "--function-context", "--binary", "--check", "--pickaxe-regex", "--pickaxe-all", "--find-object", "--diff-merges", "--remerge-diff", "--ext-diff", "--textconv"]; + +/** Short options (alone or bundled, `-pM`, `-U5`) that do the same: patch, unified context, combined diffs, -m, -W, -L, -S, -G. */ +const CONTENT_SHORT = /^-[^-]*[pucmWLSGU]/; + +/** `diff` options that print paths, counts or nothing instead of its patch. */ +const NO_PATCH_OPTIONS = ["--name-only", "--name-status", "--numstat", "--stat", "--shortstat", "--compact-summary", "--dirstat", "--dirstat-by-file", + "--summary", "--raw", "-s", "--no-patch", "--quiet"]; + +/** Subcommands that talk to a remote and may run up to `networkTimeoutMs`. */ +const NETWORK_SUBCOMMANDS = { fetch: true, push: true, clone: true, pull: true, "ls-remote": true, submodule: true }; + +/** Variables a request may set; the rest of the environment is the server's. */ +const ALLOWED_ENV = { + GIT_AUTHOR_NAME: true, GIT_AUTHOR_EMAIL: true, GIT_AUTHOR_DATE: true, GIT_COMMITTER_NAME: true, GIT_COMMITTER_EMAIL: true, GIT_COMMITTER_DATE: true, + GIT_DIR: true, GIT_WORK_TREE: true, GIT_INDEX_FILE: true, GIT_NAMESPACE: true, GIT_LITERAL_PATHSPECS: true, GIT_GLOB_PATHSPECS: true, + GIT_NOGLOB_PATHSPECS: true, GIT_ICASE_PATHSPECS: true, GIT_REFLOG_ACTION: true, GIT_MERGE_AUTOEDIT: true, GIT_MERGE_VERBOSITY: true, GIT_OPTIONAL_LOCKS: true, +}; + +/** Inherited variables that would point git at another repository than the request's. */ +const DROPPED_ENV = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_PREFIX"]; + + +   + + + + + +function blockedConfig(entry ) { + const key = entry.split("=", 1)[0].trim().toLowerCase(); + return BLOCKED_CONFIG.some((pattern) => pattern.test(key)); +} + +const refuse = (message ) => new HttpError(400, "git_refused", message); + +/** + * What a git argument list does: its subcommand, whether it only reads, and + * whether it is a network command. Throws `400 git_refused` for configuration + * or options that make git run another program. + */ +export function classifyGitArgs(args ) { + let i = 0; + let configured = false; + for (; i < args.length; i += 1) { + const arg = args[i]; + if (!arg.startsWith("-")) break; + if (arg.startsWith("--exec-path=")) throw refuse("--exec-path= is refused: it chooses which programs git runs"); + const config = arg === "-c" || arg === "--config-env" ? args[i + 1] ?? "" : arg.startsWith("--config-env=") ? arg.slice("--config-env=".length) : undefined; + if (config !== undefined) { + if (blockedConfig(config)) throw refuse(`-c ${config.split("=", 1)[0]} is refused: it makes git run a program`); + configured = true; + } + if (Object.hasOwn(GLOBAL_WITH_VALUE, arg)) i += 1; + } + const subcommand = args[i]; + const rest = args.slice(i + 1); + const end = rest.indexOf("--"); + const options = end === -1 ? rest : rest.slice(0, end); + for (let j = 0; j < options.length; j += 1) { + const arg = options[j]; + if (/^--(upload-pack|receive-pack|exec)(=|$)/.test(arg)) throw refuse(`${arg.split("=", 1)[0]} is refused: it makes git run a program`); + if ((subcommand === "clone" || subcommand === "ls-remote") && /^-u/.test(arg)) throw refuse("-u (upload-pack) is refused: it makes git run a program"); + if (subcommand === "clone") { + const value = arg === "-c" || arg === "--config" ? options[j + 1] ?? "" : arg.startsWith("--config=") ? arg.slice("--config=".length) : arg.startsWith("-c") && arg.length > 2 ? arg.slice(2) : undefined; + if (value !== undefined && blockedConfig(value)) throw refuse(`--config ${value.split("=", 1)[0]} is refused: it makes git run a program`); + } + } + const network = subcommand !== undefined && Object.hasOwn(NETWORK_SUBCOMMANDS, subcommand); + // A configuration override can change what any command does: only a token that operates may set one. + const read = !configured && (subcommand === undefined || readOnly(subcommand, options)); + return { ...(subcommand === undefined ? {} : { subcommand }), scope: read ? "sessions:read" : "sessions:operate", network }; +} + +function readOnly(subcommand , options ) { + const flags = options.filter((a) => a.startsWith("-")); + const positionals = options.filter((a) => !a.startsWith("-")); + const has = (...names ) => flags.some((f) => names.includes(f.split("=", 1)[0])); + if (has("--output")) return false; + if (Object.hasOwn(READ_SUBCOMMANDS, subcommand)) return true; + const content = has(...CONTENT_OPTIONS) || flags.some((f) => CONTENT_SHORT.test(f)); + if (Object.hasOwn(DIFF_SUBCOMMANDS, subcommand)) return !content && (subcommand !== "diff" || has(...NO_PATCH_OPTIONS)); + switch (subcommand) { + case "branch": + return !has("-d", "-D", "--delete", "-m", "-M", "--move", "-c", "-C", "--copy", "-f", "--force", "--set-upstream-to", "-u", "--unset-upstream", + "--edit-description", "-t", "--track", "--no-track", "--create-reflog") + && (positionals.length === 0 || has("-l", "--list", "--show-current", "--contains", "--no-contains", "--merged", "--no-merged", "--points-at")); + case "tag": + return !has("-a", "--annotate", "-s", "--sign", "-u", "--local-user", "-f", "--force", "-d", "--delete", "-m", "--message", "-F", "--file", "-e", "--edit", "--create-reflog") + && (positionals.length === 0 || has("-l", "--list", "--contains", "--no-contains", "--merged", "--no-merged", "--points-at") || flags.some((f) => /^-n\d*$/.test(f))); + case "config": + if (positionals[0] === "get" || positionals[0] === "list") return !has("-e", "--edit"); + return has("--get", "--get-all", "--get-regexp", "--get-urlmatch", "--get-color", "--get-colorbool", "-l", "--list") + && !has("--add", "--unset", "--unset-all", "--replace-all", "--rename-section", "--remove-section", "-e", "--edit"); + case "remote": + return positionals.length === 0 || positionals[0] === "get-url" || positionals[0] === "show"; + case "stash": + // `stash show` prints a diffstat, `stash list` the log; either prints a patch when asked. + return (positionals[0] === "list" || positionals[0] === "show") && !content; + case "cat-file": + // An object's type, size or existence; never its contents (`-p`, `blob`, `--batch`). + return has("-t", "-s", "-e", "--batch-check") && !has("-p", "--batch", "--batch-command", "--textconv", "--filters"); + case "worktree": + return positionals[0] === "list"; + case "symbolic-ref": + return positionals.length <= 1 && !has("-d", "--delete"); + default: + return false; + } +} + + + + + + + + +export class GitService { + env ; + limits ; + log ; + running = new Set (); + + constructor(options ) { + this.env = options.env; + this.limits = { ...SERVE_GIT_LIMITS, ...options.limits }; + this.log = options.log ?? (() => {}); + } + + async route(req , res , principal ) { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const body = await readJsonBody(req, this.limits.bodyBytes); + const args = body.args; + if (!Array.isArray(args) || args.length === 0 || args.length > this.limits.maxArgs + || !args.every((a) => typeof a === "string" && a.length <= this.limits.argChars && !a.includes("\0"))) { + throw new HttpError(400, "invalid_args", `args must be 1-${this.limits.maxArgs} strings without NUL`); + } + const command = classifyGitArgs(args); + need(principal, command.scope); + const cwd = realDirectory(body.cwd); + let stdin ; + if (body.stdin !== undefined) { + if (typeof body.stdin !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(body.stdin)) throw new HttpError(400, "invalid_stdin", "stdin must be base64"); + stdin = Buffer.from(body.stdin, "base64"); + if (stdin.length > this.limits.stdinBytes) throw new HttpError(413, "too_large", `stdin over ${this.limits.stdinBytes} bytes`); + } + const extraEnv = {}; + if (body.env !== undefined) { + if (!body.env || typeof body.env !== "object" || Array.isArray(body.env)) throw new HttpError(400, "invalid_env", "env must be an object of strings"); + for (const [name, value] of Object.entries(body.env)) { + if (!Object.hasOwn(ALLOWED_ENV, name)) throw new HttpError(400, "env_not_allowed", `${name} may not be set (allowed: ${Object.keys(ALLOWED_ENV).join(", ")})`); + if (typeof value !== "string" || value.includes("\0") || value.length > 4096) throw new HttpError(400, "invalid_env", `${name} must be a string`); + extraEnv[name] = value; + } + } + const ceiling = command.network ? this.limits.networkTimeoutMs : this.limits.timeoutMs; + let timeoutMs = this.limits.timeoutMs; + if (body.timeoutMs !== undefined) { + if (typeof body.timeoutMs !== "number" || !Number.isInteger(body.timeoutMs) || body.timeoutMs < 1000 || body.timeoutMs > ceiling) { + throw new HttpError(400, "invalid_timeout", `timeoutMs must be a whole number from 1000 to ${ceiling} for git ${command.subcommand ?? ""}`.trimEnd()); + } + timeoutMs = body.timeoutMs; + } + if (this.running.size >= this.limits.maxRunning) throw new HttpError(429, "too_many_git", `At most ${this.limits.maxRunning} git commands run at once`); + const env = { ...this.env }; + for (const name of DROPPED_ENV) delete env[name]; + Object.assign(env, { + GIT_TERMINAL_PROMPT: "0", + GCM_INTERACTIVE: "never", + GIT_PAGER: "cat", + PAGER: "cat", + // Nothing can answer an editor: a commit without a message aborts instead of waiting. + GIT_EDITOR: "true", + GIT_MERGE_AUTOEDIT: "no", + ...(command.scope === "sessions:read" ? { GIT_OPTIONAL_LOCKS: "0" } : {}), + }, extraEnv); + const result = await this.run(args, cwd, env, stdin, timeoutMs); + sendJson(res, 200, result); + } + + run(args , cwd , env , stdin , timeoutMs ) { + const { promise, resolve, reject } = Promise.withResolvers (); + // Its own process group (POSIX), so a timeout ends git's helpers too, and no controlling terminal for ssh to prompt on. + const child = spawn("git", args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true }); + this.running.add(child); + const stdout = []; + const stderr = []; + let outBytes = 0; + let errBytes = 0; + let truncated = false; + let timedOut = false; + let killTimer ; + const stop = () => { + if (killTimer || child.exitCode !== null) return; + this.signal(child, "SIGTERM"); + killTimer = setTimeout(() => this.signal(child, "SIGKILL"), this.limits.killGraceMs); + }; + const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs); + child.stdout .on("data", (chunk ) => { + if (truncated) return; + const room = this.limits.stdoutBytes - outBytes; + if (chunk.length > room) { + stdout.push(chunk.subarray(0, room)); + outBytes += room; + truncated = true; + return stop(); + } + stdout.push(chunk); + outBytes += chunk.length; + }); + child.stderr .on("data", (chunk ) => { + const room = this.limits.stderrBytes - errBytes; + if (room <= 0) return; + stderr.push(chunk.length > room ? chunk.subarray(0, room) : chunk); + errBytes += Math.min(room, chunk.length); + }); + child.stdin .on("error", () => { /* git exited before reading all of stdin */ }); + child.stdin .end(stdin); + child.on("error", (error ) => { + clearTimeout(timer); + clearTimeout(killTimer); + this.running.delete(child); + reject(error.code === "ENOENT" ? new HttpError(501, "git_missing", "git is not installed on the server (not on its PATH)") : error); + }); + child.on("close", (code, signal) => { + clearTimeout(timer); + clearTimeout(killTimer); + this.running.delete(child); + if (timedOut) this.log(`git ${args[0]} timed out after ${timeoutMs} ms`); + resolve({ code, signal, stdout: Buffer.concat(stdout).toString("base64"), stderr: Buffer.concat(stderr).toString("base64"), truncated, timedOut }); + }); + return promise; + } + + signal(child , signal ) { + try { + if (process.platform !== "win32" && child.pid !== undefined) process.kill(-child.pid, signal); + else child.kill(signal); + } catch { /* already gone */ } + } + + /** Ends every running git command (the server is stopping). */ + closeAll() { + for (const child of this.running) this.signal(child, "SIGKILL"); + } +} diff --git a/runtime/serve-http.mjs b/runtime/serve-http.mjs new file mode 100644 index 000000000..fb3270802 --- /dev/null +++ b/runtime/serve-http.mjs @@ -0,0 +1,179 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// HTTP helpers shared by `gentle-shell serve`'s endpoints: the error type every +// route throws, JSON and SSE answers with the server's security headers, +// bounded JSON and raw bodies, scope checks, and path validation. + +import { createHash } from "node:crypto"; +import { createWriteStream, realpathSync, rmSync, statSync } from "node:fs"; + +import { isAbsolute, resolve } from "node:path"; +import { hasScope, } from "./serve-auth.mjs"; + +export class HttpError extends Error { + status ; + code ; + constructor(status , code , message ) { + super(message); + this.status = status; + this.code = code; + } +} + +export const SECURITY_HEADERS = { + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "Cache-Control": "no-store", + "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'", +}; + +export function sendJson(res , status , body ) { + if (res.headersSent) return; + const text = JSON.stringify(body); + res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(text), ...SECURITY_HEADERS }); + res.end(text); +} + +export function sendError(res , status , code , message ) { + sendJson(res, status, { error: { code, message } }); +} + +/** Starts an SSE answer: headers flushed, Nagle off. */ +export function startSse(req , res ) { + res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", Connection: "keep-alive", "X-Accel-Buffering": "no", ...SECURITY_HEADERS }); + res.flushHeaders(); + req.socket.setNoDelay(true); +} + +/** One SSE message; `data` is JSON. */ +export function sseEvent(event , data , id ) { + return `${id === undefined ? "" : `id: ${id}\n`}event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; +} + +/** The principal when it holds `scope`; 401 without a token, 403 without the scope. */ +export function need(principal , scope ) { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + if (!hasScope(principal, scope)) throw new HttpError(403, "forbidden", `This token lacks the ${scope} scope`); + return principal; +} + +export function readJsonBody(req , limit ) { + const { promise, resolve: done, reject } = Promise.withResolvers (); + const declared = Number(req.headers["content-length"]); + if (Number.isFinite(declared) && declared > limit) { + reject(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + req.resume(); + return promise; + } + const chunks = []; + let size = 0; + let over = false; + req.on("data", (chunk ) => { + size += chunk.length; + if (size > limit) over = true; + else chunks.push(chunk); + }); + req.on("error", reject); + req.on("end", () => { + if (over) return reject(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + if (size === 0) return done({}); + try { + const value = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("not an object"); + done(value); + } catch { + reject(new HttpError(400, "invalid_json", "The body must be one JSON object")); + } + }); + return promise; +} + +/** + * Streams a raw request body into a new file (`wx`, so it never follows or + * replaces anything at `path`), at most `limit` bytes; the file is removed on + * any failure. Returns its size and sha256 (hex). + */ +export function receiveBodyToFile(req , path , limit , mode ) { + const { promise, resolve: done, reject } = Promise.withResolvers (); + const declared = Number(req.headers["content-length"]); + if (Number.isFinite(declared) && declared > limit) { + req.resume(); + reject(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + return promise; + } + const hash = createHash("sha256"); + let size = 0; + let failed = false; + let opened = false; + const out = createWriteStream(path, { flags: "wx", mode }); + out.on("open", () => { opened = true; }); + const fail = (error ) => { + if (failed) return; + failed = true; + req.unpipe(out); + req.resume(); + out.destroy(); + out.once("close", () => { + if (opened) rmSync(path, { force: true }); + reject(error); + }); + }; + req.on("data", (chunk ) => { + size += chunk.length; + if (size > limit) return fail(new HttpError(413, "too_large", `Body over ${limit} bytes`)); + hash.update(chunk); + }); + req.on("aborted", () => fail(new HttpError(400, "aborted", "The upload was cut short"))); + req.on("error", (error) => fail(error)); + out.on("error", (error) => fail(error)); + out.on("close", () => { if (!failed) done({ size, sha256: hash.digest("hex") }); }); + req.pipe(out); + return promise; +} + +/** A path from a request: absolute, no NUL, at most 4096 characters; normalized (`..` resolved lexically). */ +export function absolutePath(value , name = "path") { + if (typeof value !== "string" || value.length === 0 || value.length > 4096 || value.includes("\0") || !isAbsolute(value)) { + throw new HttpError(400, "invalid_path", `${name} must be an absolute path on the server`); + } + return resolve(value); +} + +/** An existing folder, symlinks resolved. */ +export function realDirectory(cwd ) { + if (typeof cwd !== "string" || cwd.length === 0 || cwd.length > 4096 || cwd.includes("\0") || !isAbsolute(cwd)) { + throw new HttpError(400, "invalid_cwd", "cwd must be an absolute path to a folder"); + } + try { + const real = realpathSync(cwd); + if (!statSync(real).isDirectory()) throw new Error("not a folder"); + return real; + } catch { + throw new HttpError(400, "invalid_cwd", "cwd must be an absolute path to an existing folder"); + } +} + +/** A file system error as the HTTP answer a client can act on. */ +export function fsHttpError(error , path ) { + if (error instanceof HttpError) return error; + const code = (error )?.code; + switch (code) { + case "ENOENT": return new HttpError(404, "not_found", `${path} does not exist`); + case "ENOTDIR": return new HttpError(400, "not_a_directory", `A part of ${path} is not a folder`); + case "EISDIR": return new HttpError(400, "is_a_directory", `${path} is a folder`); + case "EACCES": + case "EPERM": return new HttpError(403, "permission_denied", `The server user may not access ${path}`); + case "EEXIST": return new HttpError(409, "exists", `${path} already exists`); + case "ENOTEMPTY": return new HttpError(409, "not_empty", `${path} is not empty`); + case "EXDEV": return new HttpError(409, "cross_device", "Source and destination are on different file systems"); + case "EINVAL": return new HttpError(400, "invalid_operation", `The operation is not possible on ${path}`); + case "ENAMETOOLONG": return new HttpError(400, "invalid_path", `${path} is too long`); + case "ELOOP": return new HttpError(400, "symlink_loop", `${path} has too many levels of symbolic links`); + case "ENOSPC": return new HttpError(507, "no_space", "The server's disk is full"); + default: return new HttpError(500, "fs_error", `${code ?? "error"} on ${path}`); + } +} + +/** Whether the principal is the given device or holds `admin`. */ +export function ownsOrAdmin(principal , deviceId ) { + return principal.deviceId === deviceId || hasScope(principal, "admin"); +} diff --git a/runtime/serve-print.mjs b/runtime/serve-print.mjs new file mode 100644 index 000000000..e2f0987c5 --- /dev/null +++ b/runtime/serve-print.mjs @@ -0,0 +1,144 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `POST /api/print` for `gentle-shell serve`: one one-shot prompt (a commit +// message, a title) answered by this machine's Gentle Shell, the way the app +// runs it locally: `gentle-shell --print --no-session --no-tools` in a folder, +// no session written, no tools, no interactive host. The prompt goes on stdin +// (Pi reads piped stdin as the message), so its size is not bound by the +// command line and it never shows in the process list. + +import { spawn, } from "node:child_process"; + + +import { HttpError, need, readJsonBody, realDirectory, sendJson } from "./serve-http.mjs"; + + +export const SERVE_PRINT_LIMITS = { + timeoutMs: 120_000, + promptBytes: 256 * 1024, + bodyBytes: 512 * 1024, + stdoutBytes: 1024 * 1024, + /** The end of stderr a failure reports. */ + stderrChars: 2000, + /** One-shot runs at once, across devices. */ + maxRunning: 4, + /** After a timeout, an oversize answer or a client that left: SIGTERM, then SIGKILL this much later. */ + killGraceMs: 2_000, +}; + +/** Pi's `--model` pattern: `provider/id` or `id`, optionally `:thinking`; never an option. */ +const MODEL = /^(?!-)[^\s\0-\x1f\x7f]{1,200}$/; + + + + + + + + + + +export class PrintService { + options ; + limits ; + running = new Set (); + + constructor(options ) { + this.options = options; + this.limits = { ...SERVE_PRINT_LIMITS, ...options.limits }; + } + + get available() { + return this.options.launchPrint !== undefined; + } + + async route(req , res , principal ) { + need(principal, "sessions:operate"); + const launchPrint = this.options.launchPrint; + if (!launchPrint) throw new HttpError(501, "not_supported", "This server cannot run one-shot prompts"); + const body = await readJsonBody(req, this.limits.bodyBytes); + const cwd = realDirectory(body.cwd); + const prompt = body.prompt; + if (typeof prompt !== "string" || prompt.trim() === "") throw new HttpError(400, "invalid_prompt", "prompt must be a non-empty string"); + if (Buffer.byteLength(prompt, "utf8") > this.limits.promptBytes) throw new HttpError(400, "invalid_prompt", `prompt over ${this.limits.promptBytes} bytes`); + const model = body.model; + if (model !== undefined && (typeof model !== "string" || !MODEL.test(model))) throw new HttpError(400, "invalid_model", "model must be a model name such as provider/id"); + if (this.running.size >= this.limits.maxRunning) throw new HttpError(429, "too_many_prints", `At most ${this.limits.maxRunning} one-shot prompts run at once`); + const launch = launchPrint({ cwd, ...(typeof model === "string" ? { model } : {}) }); + const outcome = await this.run(launch, prompt, res); + if ("text" in outcome) return sendJson(res, 200, { text: outcome.text }); + const { error, exitCode } = outcome; + return sendJson(res, error.status, { error: { code: error.code, message: error.message }, ...(exitCode === undefined ? {} : { exitCode }) }); + } + + run(launch , prompt , res ) { + const { promise, resolve } = Promise.withResolvers (); + // Its own process group (POSIX): the launcher starts Pi as its child, and a stop must end both. + const child = spawn(launch.command, launch.args, { cwd: launch.cwd, env: launch.env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true }); + this.running.add(child); + const stdout = []; + let outBytes = 0; + let stderr = ""; + let ended ; + let killTimer ; + const stop = (why ) => { + ended ??= why; + // The group, even when the launcher already exited: Pi may still hold stdout. + if (killTimer) return; + this.signal(child, "SIGTERM"); + killTimer = setTimeout(() => this.signal(child, "SIGKILL"), this.limits.killGraceMs); + killTimer.unref?.(); + }; + const timer = setTimeout(() => stop("timeout"), this.limits.timeoutMs); + // A client that hangs up does not keep the model running. + const left = () => { if (!res.writableEnded) stop("client_left"); }; + res.once("close", left); + child.stdout .on("data", (chunk ) => { + if (ended) return; + outBytes += chunk.length; + if (outBytes > this.limits.stdoutBytes) return stop("too_large"); + stdout.push(chunk); + }); + child.stderr .on("data", (chunk ) => { stderr = (stderr + chunk.toString("utf8")).slice(-this.limits.stderrChars); }); + child.stdin .on("error", () => { /* it exited before reading the prompt */ }); + child.stdin .end(prompt); + let settled = false; + const finish = (outcome ) => { + if (settled) return; + settled = true; + clearTimeout(timer); + clearTimeout(killTimer); + res.off("close", left); + this.running.delete(child); + resolve(outcome); + }; + child.once("error", (error) => finish({ error: new HttpError(502, "print_failed", `Could not start gentle-shell: ${error.message}`) })); + child.once("close", (code, signal) => { + if (ended === "timeout") { + this.options.log(`print timed out after ${this.limits.timeoutMs} ms`); + return finish({ error: new HttpError(504, "print_timeout", `No answer within ${this.limits.timeoutMs / 1000} s`) }); + } + if (ended === "too_large") return finish({ error: new HttpError(502, "output_too_large", `The answer is over ${this.limits.stdoutBytes} bytes`) }); + if (ended === "client_left") return finish({ error: new HttpError(499, "client_left", "The client closed the request") }); + if (code !== 0) { + const detail = stderr.trim() || Buffer.concat(stdout).toString("utf8").trim().slice(-this.limits.stderrChars); + return finish({ error: new HttpError(502, "print_failed", detail || `gentle-shell exited with ${signal ?? `code ${code}`}`), exitCode: code }); + } + finish({ text: Buffer.concat(stdout).toString("utf8") }); + }); + return promise; + } + + signal(child , signal ) { + if (child.pid === undefined) return; + try { + if (process.platform !== "win32") process.kill(-child.pid, signal); + // Windows has no process groups: end the launcher and the Pi it started. + else spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => child.kill()); + } catch { /* already gone */ } + } + + /** Ends every one-shot run (the server is stopping). */ + closeAll() { + for (const child of this.running) this.signal(child, "SIGKILL"); + } +} diff --git a/runtime/serve-relay-cli.mjs b/runtime/serve-relay-cli.mjs new file mode 100644 index 000000000..dfa3ac7b3 --- /dev/null +++ b/runtime/serve-relay-cli.mjs @@ -0,0 +1,134 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `gentle-shell relay --listen :`: runs the rendezvous servers +// connect out to (lib/serve-relay.ts) in the foreground, with the secret a +// server must present to register. The secret comes from +// GENTLE_SHELL_RELAY_SECRET, --secret-file, or `/relay/secret` (made on +// first run, owner-only). Run it under a service manager to keep it up. + +import { randomBytes } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { parseListen } from "./serve-cli.mjs"; +import { startRelay, } from "./serve-relay.mjs"; + + + + + +export const RELAY_HELP = [ + "Usage: gentle-shell [home selectors] relay --listen : [--secret-file ] [--json]", + "", + "Runs a relay that lets devices outside a Gentle Shell server's network reach it. Servers connect", + "out to the relay ('gentle-shell serve share --relay gsr://:'), so they need no", + "open port; a device asks the relay for a server and the relay joins the two TCP streams. TLS runs", + "end to end between the device and the server, which the device pins: the relay sees only", + "ciphertext and logs byte counts, never content.", + "", + "A server must present the relay secret to register: GENTLE_SHELL_RELAY_SECRET, else the file", + "--secret-file names, else /relay/secret (made on first run, owner-only). Give it to each", + "server's owner, who puts it in /serve/relay-secret or GENTLE_SHELL_RELAY_SECRET.", + "", + " --listen Address and port to listen on, for example 0.0.0.0:7700 (required).", + " --secret-file A file whose first line is the secret.", + " --json Print one JSON line when listening, for programs.", + "", + "It runs in the foreground until Ctrl+C. Protocol and limits: docs/serve.md#relay.", +].join("\n"); + +export function parseRelayArgs(args ) { + let listen ; + let secretFile ; + let json = false; + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + const value = (flag ) => { + if (arg === flag) return args[(i += 1)]; + return arg.startsWith(`${flag}=`) ? arg.slice(flag.length + 1) : undefined; + }; + if (arg === "--help" || arg === "-h") return { action: "help" }; + if (arg === "--json") { json = true; continue; } + if (arg === "--listen" || arg.startsWith("--listen=")) { + const parsed = parseListen(value("--listen") ?? ""); + if ("error" in parsed) return parsed; + listen = parsed; + continue; + } + if (arg === "--secret-file" || arg.startsWith("--secret-file=")) { + secretFile = value("--secret-file"); + if (!secretFile) return { error: "--secret-file needs a path" }; + continue; + } + return { error: `unknown relay argument "${arg}"` }; + } + if (!listen) return { error: "relay needs --listen :, for example --listen 0.0.0.0:7700" }; + return { action: "run", host: listen.host, port: listen.port, json, ...(secretFile === undefined ? {} : { secretFile }) }; +} + + + + + + + + + + +/** The secret and where it came from; the default file is made on first run. */ +export function relayServerSecret(ctx , secretFile ) { + const fromEnv = ctx.env.GENTLE_SHELL_RELAY_SECRET?.trim(); + if (fromEnv) return { secret: fromEnv, source: "GENTLE_SHELL_RELAY_SECRET" }; + const path = secretFile ?? join(ctx.agentHome, "relay", "secret"); + if (secretFile !== undefined || existsSync(path)) { + const secret = readFileSync(path, "utf8").split(/\r?\n/)[0].trim(); + if (!secret) throw new Error(`${path} holds no secret on its first line`); + return { secret, source: path }; + } + mkdirSync(join(ctx.agentHome, "relay"), { recursive: true, mode: 0o700 }); + const secret = randomBytes(24).toString("base64url"); + writeFileSync(path, `${secret}\n`, { mode: 0o600, flag: "wx" }); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } + return { secret, source: path }; +} + +function untilSignal() { + const { promise, resolve } = Promise.withResolvers (); + const done = () => { + process.off("SIGINT", done); + process.off("SIGTERM", done); + resolve(); + }; + process.on("SIGINT", done); + process.on("SIGTERM", done); + return promise; +} + +export async function runRelayCommand(args , ctx ) { + if (args.action === "help") { + ctx.stdout(`${RELAY_HELP}\n`); + return 0; + } + let relay ; + try { + const { secret, source } = relayServerSecret(ctx, args.secretFile); + const log = (line ) => ctx.stderr(`${new Date().toISOString()} ${line}\n`); + relay = await startRelay({ host: args.host, port: args.port, secret, log }); + const host = args.host.includes(":") ? `[${args.host}]` : args.host; + ctx.stdout(args.json + ? `${JSON.stringify({ schema: "gentle-shell.relay/v1", host: args.host, port: relay.port, secretSource: source })}\n` + : [ + `Gentle Shell relay listening on ${host}:${relay.port}.`, + `Servers register with: gentle-shell serve share --relay gsr://:${relay.port}`, + `They need the relay secret from ${source}${source === "GENTLE_SHELL_RELAY_SECRET" ? "" : " (copy its first line)"}, in their /serve/relay-secret or GENTLE_SHELL_RELAY_SECRET.`, + "Press Ctrl+C to stop.", + "", + ].join("\n")); + await (ctx.untilStopped ?? untilSignal)(); + log("relay stopping"); + return 0; + } catch (error) { + ctx.stderr(`gentle-shell relay: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } finally { + await relay?.close(); + } +} diff --git a/runtime/serve-relay.mjs b/runtime/serve-relay.mjs new file mode 100644 index 000000000..381b3e075 --- /dev/null +++ b/runtime/serve-relay.mjs @@ -0,0 +1,555 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// A self-hostable rendezvous for reaching `gentle-shell serve` from outside its +// network (`gentle-shell relay`). Servers connect out to the relay and keep a +// control connection; a client asks the relay for a server by its certificate +// fingerprint; the relay asks that server to open one more outbound data +// connection and splices the two TCP streams. TLS runs end to end between the +// client and serve (the client pins the fingerprint), so the relay only ever +// sees ciphertext and logs byte counts, never content. Zero dependencies. +// +// Every message before the splice is one JSON object on one line ending in +// `\n` (at most 4 KiB); after the client's `{"t":"ok"}` line the connection +// carries raw bytes. + +import { createHash, createPrivateKey, randomBytes, sign, timingSafeEqual, verify, X509Certificate } from "node:crypto"; +import { connect, createServer, } from "node:net"; +import { certificateFingerprint, fingerprintBytes } from "./serve-tls.mjs"; + +export const RELAY_PROTOCOL = 1; +export const RELAY_URL_SCHEME = "gsr:"; +/** What a server signs, followed by the relay's nonce (base64url text), to prove it holds the certificate's key. */ +export const RELAY_SIGNATURE_PREFIX = "gentle-shell/relay-register/v1 "; + +export const RELAY_LIMITS = { + /** One handshake line, newline included. */ + lineBytes: 4096, + /** A connection that has not finished its handshake by then is closed. */ + helloTimeoutMs: 10_000, + /** How long a client waits for the server's data connection. */ + openTimeoutMs: 10_000, + maxServers: 256, + /** Spliced plus waiting connections per server. */ + maxConnectionsPerServer: 32, + /** A spliced pair with no byte either way for this long is closed. */ + idleMs: 30 * 60_000, + /** The relay pings each server's control connection this often... */ + pingMs: 25_000, + /** ...and drops one that has said nothing for this long. */ + deadMs: 75_000, + /** Per-server byte rates are logged this often while connections are open. */ + logEveryMs: 60_000, +}; + + + +/** `gsr://:`: host and port, nothing else. */ +export function parseRelayUrl(value ) { + let url ; + try { + url = new URL(value); + } catch { + return { error: `a relay URL looks like gsr://relay.example.com:7700 (got "${value}")` }; + } + if (url.protocol !== RELAY_URL_SCHEME) return { error: `a relay URL starts with gsr:// (got "${value}")` }; + if (url.username || url.password || (url.pathname !== "" && url.pathname !== "/") || url.search || url.hash) return { error: `a relay URL is only gsr://:; the relay secret goes in GENTLE_SHELL_RELAY_SECRET or the relay-secret file (got "${value}")` }; + if (!url.port) return { error: `a relay URL needs a port, as in gsr://relay.example.com:7700 (got "${value}")` }; + const host = url.hostname.replace(/^\[|\]$/g, ""); + return { url: `gsr://${url.host}`, host, port: Number(url.port) }; +} + +function send(socket , message ) { + if (socket.writable) socket.write(`${JSON.stringify(message)}\n`); +} + +function fail(socket , code , message ) { + if (socket.writable) socket.end(`${JSON.stringify({ t: "error", code, message })}\n`); + else socket.destroy(); +} + +/** One handshake line, parsed, and the bytes that came after it. */ + + + + + +/** Reads one handshake line; resolves with the parsed object and any bytes after it, which stay unread by the socket. */ +function readLine(socket , limits , initial = Buffer.alloc(0)) { + const { promise, resolve, reject } = Promise.withResolvers (); + let buffer = initial; + const done = (error ) => { + clearTimeout(timer); + socket.off("data", onData); + socket.off("close", onClose); + if (error) reject(error); + }; + const parse = () => { + const end = buffer.indexOf(0x0a); + if (end === -1) { + if (buffer.length >= limits.lineBytes) done(new Error("line too long")); + return; + } + if (end + 1 > limits.lineBytes) return done(new Error("line too long")); + let message ; + try { message = JSON.parse(buffer.subarray(0, end).toString("utf8")); } catch { return done(new Error("not JSON")); } + if (!message || typeof message !== "object" || Array.isArray(message) || !("t" in message) || typeof message.t !== "string") return done(new Error("not a message")); + socket.pause(); + done(); + resolve({ message: message , rest: buffer.subarray(end + 1) }); + }; + const onData = (chunk ) => { + buffer = Buffer.concat([buffer, chunk]); + parse(); + }; + const onClose = () => done(new Error("closed")); + const timer = setTimeout(() => done(new Error("timeout")), limits.helloTimeoutMs); + socket.on("data", onData); + socket.once("close", onClose); + if (buffer.length > 0) parse(); + if (socket.isPaused()) socket.resume(); + return promise; +} + +/** Calls `onLine` for each line until the socket ends; a line over the limit or not JSON closes it. */ +function readLines(socket , lineBytes , initial , onLine ) { + let buffer = initial; + const drain = () => { + for (let end = buffer.indexOf(0x0a); end !== -1; end = buffer.indexOf(0x0a)) { + const line = buffer.subarray(0, end); + buffer = buffer.subarray(end + 1); + let message ; + try { message = JSON.parse(line.toString("utf8")); } catch { return void socket.destroy(); } + if (message && typeof message === "object" && !Array.isArray(message)) onLine(message ); + } + if (buffer.length >= lineBytes) socket.destroy(); + }; + socket.on("data", (chunk ) => { + buffer = Buffer.concat([buffer, chunk]); + drain(); + }); + drain(); + socket.resume(); +} + +const sameSecret = (given , expected ) => typeof given === "string" + && timingSafeEqual(createHash("sha256").update(given).digest(), createHash("sha256").update(expected).digest()); + +const shortId = (id ) => id.slice(0, 8); + +// --- the relay --------------------------------------------------------------------- + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +export function startRelay(options ) { + const limits = { ...RELAY_LIMITS, ...options.limits }; + const now = options.now ?? Date.now; + const log = options.log ?? (() => {}); + const registrations = new Map (); + const pendingByCid = new Map (); + const sockets = new Set (); + + const unregister = (registration , reason ) => { + if (registrations.get(registration.id) !== registration) return; + registrations.delete(registration.id); + clearInterval(registration.ping); + for (const pending of registration.pending.values()) { + clearTimeout(pending.timer); + pendingByCid.delete(pending.cid); + fail(pending.client, "offline", "The server left the relay"); + } + registration.control.destroy(); + log(`relay: server ${shortId(registration.id)} left (${reason})`); + }; + + const registerServer = async (socket , hello , rest ) => { + const id = typeof hello.id === "string" ? hello.id : ""; + if (!fingerprintBytes(id)) return fail(socket, "bad_request", "id must be the server certificate's base64url SHA-256 fingerprint"); + if (options.secret !== undefined && !sameSecret(hello.secret, options.secret)) { + log(`relay: refused server ${shortId(id)} from ${socket.remoteAddress}: wrong relay secret`); + return fail(socket, "unauthorized", "Wrong or missing relay secret"); + } + if (!registrations.has(id) && registrations.size >= limits.maxServers) return fail(socket, "full", "This relay serves as many servers as it can"); + const nonce = randomBytes(32).toString("base64url"); + send(socket, { t: "challenge", nonce }); + const auth = await readLine(socket, limits, rest); + if (auth.message.t !== "auth" || typeof auth.message.cert !== "string" || typeof auth.message.sig !== "string") return fail(socket, "bad_request", "Expected the auth line"); + let proven = false; + try { + const cert = new X509Certificate(Buffer.from(auth.message.cert, "base64url")); + proven = certificateFingerprint(cert.raw) === id && verify("sha256", Buffer.from(`${RELAY_SIGNATURE_PREFIX}${nonce}`, "ascii"), cert.publicKey, Buffer.from(auth.message.sig, "base64url")); + } catch { /* not a certificate or not a signature */ } + if (!proven) { + log(`relay: refused server ${shortId(id)} from ${socket.remoteAddress}: no proof of the certificate's key`); + return fail(socket, "unauthorized", "The signature does not prove this certificate"); + } + const previous = registrations.get(id); + if (previous) { + fail(previous.control, "replaced", "The same server registered again"); + unregister(previous, "replaced by a new connection"); + } + if (registrations.size >= limits.maxServers) return fail(socket, "full", "This relay serves as many servers as it can"); + const registration = { id, control: socket, pending: new Map(), pairs: new Set(), lastHeard: now(), ping: setInterval(() => { + if (now() - registration.lastHeard > limits.deadMs) return unregister(registration, "no answer to pings"); + send(socket, { t: "ping" }); + }, limits.pingMs) }; + registration.ping.unref(); + registrations.set(id, registration); + socket.setKeepAlive(true, limits.pingMs); + socket.once("close", () => unregister(registration, "control connection closed")); + send(socket, { t: "ready", v: RELAY_PROTOCOL }); + log(`relay: server ${shortId(id)} registered from ${socket.remoteAddress}`); + readLines(socket, limits.lineBytes, auth.rest, (message) => { + registration.lastHeard = now(); + if (message.t === "refuse" && typeof message.cid === "string") { + const pending = registration.pending.get(message.cid); + if (!pending) return; + registration.pending.delete(message.cid); + pendingByCid.delete(message.cid); + clearTimeout(pending.timer); + fail(pending.client, "refused", "The server has nothing on that port"); + } + }); + }; + + const openForClient = (client , hello , rest , helloBytes ) => { + const id = typeof hello.id === "string" ? hello.id : ""; + const port = hello.port; + if (!fingerprintBytes(id)) return fail(client, "bad_request", "id must be the server certificate's base64url SHA-256 fingerprint"); + if (port !== undefined && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)) return fail(client, "bad_request", "port must be a whole number 1-65535"); + const registration = registrations.get(id); + if (!registration) return fail(client, "offline", "That server is not connected to this relay"); + if (registration.pending.size + registration.pairs.size >= limits.maxConnectionsPerServer) return fail(client, "busy", "That server has as many relayed connections as it may"); + const cid = randomBytes(12).toString("base64url"); + const key = randomBytes(16).toString("base64url"); + const pending = { cid, key, client, rest, helloBytes, timer: setTimeout(() => { + registration.pending.delete(cid); + pendingByCid.delete(cid); + fail(client, "timeout", "The server did not open a connection in time"); + }, limits.openTimeoutMs) }; + registration.pending.set(cid, pending); + pendingByCid.set(cid, { registration, pending }); + client.once("close", () => { + if (!registration.pending.delete(cid)) return; + pendingByCid.delete(cid); + clearTimeout(pending.timer); + }); + send(registration.control, { t: "open", cid, key, ...(port === undefined ? {} : { port }) }); + }; + + const splice = (data , hello , rest , helloBytes ) => { + const found = typeof hello.cid === "string" ? pendingByCid.get(hello.cid) : undefined; + if (!found || !sameSecret(hello.key, found.pending.key)) return fail(data, "unauthorized", "Unknown or expired connection"); + const { registration, pending } = found; + registration.pending.delete(pending.cid); + pendingByCid.delete(pending.cid); + clearTimeout(pending.timer); + const client = pending.client; + if (client.destroyed) return void data.destroy(); + const pair = { client, data, clientHello: pending.helloBytes, dataHello: helloBytes, startedAt: now(), sampledUp: 0, sampledDown: 0 }; + registration.pairs.add(pair); + const end = () => { + if (!registration.pairs.delete(pair)) return; + client.destroy(); + data.destroy(); + const up = Math.max(0, client.bytesRead - pair.clientHello); + const down = Math.max(0, data.bytesRead - pair.dataHello); + log(`relay: server ${shortId(registration.id)}: connection closed after ${Math.round((now() - pair.startedAt) / 1000)} s, ${up} B up, ${down} B down`); + }; + for (const socket of [client, data]) { + socket.setNoDelay(true); + socket.setTimeout(limits.idleMs, end); + socket.once("close", end); + } + client.write(`${JSON.stringify({ t: "ok" })}\n`); + if (pending.rest.length > 0) data.write(pending.rest); + if (rest.length > 0) client.write(rest); + client.pipe(data); + data.pipe(client); + client.resume(); + data.resume(); + }; + + const rates = setInterval(() => { + for (const registration of registrations.values()) { + if (registration.pairs.size === 0) continue; + let up = 0; + let down = 0; + for (const pair of registration.pairs) { + const u = pair.client.bytesRead; + const d = pair.data.bytesRead; + up += u - Math.max(pair.sampledUp, pair.clientHello); + down += d - Math.max(pair.sampledDown, pair.dataHello); + pair.sampledUp = u; + pair.sampledDown = d; + } + const seconds = limits.logEveryMs / 1000; + log(`relay: server ${shortId(registration.id)}: ${registration.pairs.size} connection(s), ${Math.round(up / seconds)} B/s up, ${Math.round(down / seconds)} B/s down`); + } + }, limits.logEveryMs); + rates.unref(); + + const server = createServer((socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + socket.on("error", () => socket.destroy()); + readLine(socket, limits).then(({ message, rest }) => { + const helloBytes = socket.bytesRead - rest.length; + if (message.v !== RELAY_PROTOCOL) return fail(socket, "unsupported_version", `This relay speaks version ${RELAY_PROTOCOL}`); + if (message.t === "gsr/server") return registerServer(socket, message, rest); + if (message.t === "gsr/client") return openForClient(socket, message, rest, helloBytes); + if (message.t === "gsr/data") return splice(socket, message, rest, helloBytes); + fail(socket, "bad_request", "Unknown hello"); + }).catch(() => socket.destroy()); + }); + + const { promise, resolve, reject } = Promise.withResolvers (); + server.once("error", reject); + server.listen(options.port, options.host.replace(/^\[|\]$/g, ""), () => { + server.off("error", reject); + const address = server.address(); + resolve({ + host: options.host, + port: typeof address === "object" && address ? address.port : options.port, + servers: () => [...registrations.keys()], + close: async () => { + clearInterval(rates); + for (const registration of [...registrations.values()]) unregister(registration, "relay stopping"); + const closed = Promise.withResolvers (); + server.close(() => closed.resolve()); + for (const socket of sockets) socket.destroy(); + await closed.promise; + }, + }); + }); + return promise; +} + +// --- a server's link to the relay -------------------------------------------------- + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** Keeps a registration with the relay: connects out, proves the certificate, opens a data connection per client, reconnects with backoff. */ +export function startRelayLink(options ) { + const parsed = parseRelayUrl(options.url); + if ("error" in parsed) throw new Error(parsed.error); + const limits = { ...RELAY_LIMITS, ...options.limits }; + const log = options.log ?? (() => {}); + const id = certificateFingerprint(options.certDer); + const key = createPrivateKey(options.keyPem); + const retryMin = options.retryMinMs ?? 1000; + const retryMax = options.retryMaxMs ?? 60_000; + let delay = retryMin; + let control ; + let registered = false; + let closed = false; + let retry ; + let waiters = []; + const dataSockets = new Set (); + + const openData = (message ) => { + const cid = message.cid; + const dataKey = message.key; + if (typeof cid !== "string" || typeof dataKey !== "string") return; + const port = typeof message.port === "number" ? message.port : undefined; + const target = options.accept(port); + if (!target) { + if (control) send(control, { t: "refuse", cid }); + return; + } + const data = connect({ host: parsed.host, port: parsed.port }); + dataSockets.add(data); + data.once("close", () => dataSockets.delete(data)); + data.on("error", () => data.destroy()); + data.setTimeout(limits.openTimeoutMs, () => data.destroy()); + data.once("connect", () => { + data.setTimeout(0); + data.setNoDelay(true); + data.write(`${JSON.stringify({ t: "gsr/data", v: RELAY_PROTOCOL, cid, key: dataKey })}\n`); + target(data); + }); + }; + + const schedule = () => { + if (closed || retry) return; + retry = setTimeout(() => { + retry = undefined; + attempt(); + }, delay); + retry.unref(); + delay = Math.min(retryMax, delay * 2); + }; + + const attempt = () => { + if (closed) return; + const socket = connect({ host: parsed.host, port: parsed.port }); + control = socket; + socket.on("error", () => socket.destroy()); + socket.once("close", () => { + if (control === socket) control = undefined; + if (registered) log(`relay: disconnected from ${parsed.url}`); + registered = false; + schedule(); + }); + socket.once("connect", async () => { + try { + socket.setNoDelay(true); + socket.setKeepAlive(true, limits.pingMs); + send(socket, { t: "gsr/server", v: RELAY_PROTOCOL, id, ...(options.secret === undefined ? {} : { secret: options.secret }) }); + const challenge = await readLine(socket, limits); + if (challenge.message.t === "error") throw new Error(`${challenge.message.code}: ${challenge.message.message}`); + if (challenge.message.t !== "challenge" || typeof challenge.message.nonce !== "string") throw new Error("unexpected answer"); + const sig = sign("sha256", Buffer.from(`${RELAY_SIGNATURE_PREFIX}${challenge.message.nonce}`, "ascii"), key); + send(socket, { t: "auth", cert: options.certDer.toString("base64url"), sig: sig.toString("base64url") }); + const ready = await readLine(socket, limits, challenge.rest); + if (ready.message.t === "error") throw new Error(`${ready.message.code}: ${ready.message.message}`); + if (ready.message.t !== "ready") throw new Error("unexpected answer"); + registered = true; + delay = retryMin; + log(`relay: registered with ${parsed.url} as ${shortId(id)}`); + for (const done of waiters) done(); + waiters = []; + let heard = Date.now(); + const watchdog = setInterval(() => { if (Date.now() - heard > limits.deadMs) socket.destroy(); }, limits.pingMs); + watchdog.unref(); + socket.once("close", () => clearInterval(watchdog)); + readLines(socket, limits.lineBytes, ready.rest, (message) => { + heard = Date.now(); + if (message.t === "ping") send(socket, { t: "pong" }); + else if (message.t === "open") openData(message); + }); + } catch (error) { + log(`relay: ${parsed.url} refused the registration: ${error instanceof Error ? error.message : String(error)}`); + socket.destroy(); + } + }); + }; + + attempt(); + return { + url: parsed.url, + id, + connected: () => registered, + ready: () => { + if (registered) return Promise.resolve(); + const { promise, resolve } = Promise.withResolvers (); + waiters.push(resolve); + return promise; + }, + close: () => { + closed = true; + clearTimeout(retry); + control?.destroy(); + for (const socket of dataSockets) socket.destroy(); + }, + }; +} + +// --- a client through the relay ---------------------------------------------------- + +export class RelayError extends Error { + code ; + constructor(code , message ) { + super(message); + this.code = code; + } +} + +/** + * A TCP stream to the server with fingerprint `id` through the relay at `url` + * (to its listener on `port`, the API when absent). The caller runs TLS over it + * and pins `id`; the relay never sees the plaintext. + */ +export async function connectThroughRelay(url , id , options = {}) { + const parsed = parseRelayUrl(url); + if ("error" in parsed) throw new RelayError("bad_request", parsed.error); + const socket = connect({ host: parsed.host, port: parsed.port }); + const { promise, resolve, reject } = Promise.withResolvers (); + socket.once("connect", () => resolve()); + socket.once("error", reject); + await promise; + socket.off("error", reject); + socket.on("error", () => socket.destroy()); + socket.setNoDelay(true); + send(socket, { t: "gsr/client", v: RELAY_PROTOCOL, id, ...(options.port === undefined ? {} : { port: options.port }) }); + const limits = { ...RELAY_LIMITS, helloTimeoutMs: options.timeoutMs ?? RELAY_LIMITS.openTimeoutMs + 5_000 }; + let answer ; + try { + answer = await readLine(socket, limits); + } catch (error) { + socket.destroy(); + throw new RelayError("timeout", `The relay did not answer: ${error instanceof Error ? error.message : String(error)}`); + } + if (answer.message.t !== "ok") { + socket.destroy(); + throw new RelayError(typeof answer.message.code === "string" ? answer.message.code : "bad_request", typeof answer.message.message === "string" ? answer.message.message : "The relay refused"); + } + if (answer.rest.length > 0) socket.unshift(answer.rest); + return socket; +} diff --git a/runtime/serve-server.mjs b/runtime/serve-server.mjs new file mode 100644 index 000000000..b7589e7f0 --- /dev/null +++ b/runtime/serve-server.mjs @@ -0,0 +1,1133 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `gentle-shell serve`'s HTTP API: JSON endpoints plus Server-Sent Events, +// hardened like the Tower server (lib/tower-server.ts): no cookies, a bearer +// token on every authenticated request, any foreign Origin refused, the Host +// header checked against the listen address, bounded bodies, and CSP/no-store +// headers. Zero dependencies: SSE works from browsers, phones and curl; a +// WebSocket transport can come later behind the same contract. + +import { randomBytes } from "node:crypto"; +import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; + +import { arch, homedir, hostname } from "node:os"; +import { basename, join, sep } from "node:path"; +import { hasScope, isServeScope, } from "./serve-auth.mjs"; +import { startDiscoveryResponder, } from "./serve-discovery.mjs"; +import { FileService, } from "./serve-files.mjs"; +import { GitService, } from "./serve-git.mjs"; +import { ServeChecks, } from "./serve-checks.mjs"; +import { ForwardError, ForwardManager, } from "./serve-forward.mjs"; +import { HttpError, need, readJsonBody, realDirectory, SECURITY_HEADERS, sendError, sendJson } from "./serve-http.mjs"; +import { UploadStore, } from "./serve-uploads.mjs"; +import { PrintService, } from "./serve-print.mjs"; +import { UPGRADE_CHANNELS, UpgradeService, } from "./serve-upgrade.mjs"; +import { TerminalService, } from "./serve-terminals.mjs"; +import { HOST_TOOL_METHODS, isDesktopEventRecord, KeeperLink, SERVE_SESSION_LIMITS, ServeSession, SessionError, } from "./serve-session.mjs"; +import { exitedSnapshot, keeperAlive, keeperEndpoint, newKeeperToken, privateKeeperDir, readKeeperRecords, removeKeeperRecord, removePrivateKeeperDir, SERVE_KEEPER_LIMITS, spawnKeeper, writeKeeperRecord, } from "./serve-session-keeper.mjs"; +import { startRelayLink, } from "./serve-relay.mjs"; +import { createServeListener, PairProofs, PAIR_PROOF, requestScheme, } from "./serve-tls.mjs"; + +export const SERVE_SCHEMA = "gentle-shell.serve/v1"; +export const SERVE_PROTOCOL = 1; +export const SERVE_IDENTITY_SCHEMA = "gentle-shell.serve.identity/v1"; +/** Public identity path: a client holding a connection code probes it to find the address that reaches this server. */ +export const SERVE_IDENTITY_PATH = "/.well-known/gentle-shell"; +export const SERVE_CAPABILITIES = ["sessions", "pi-rpc", "desktop-rpc", "desktop", "sse", "stream-tickets", "pairing", "devices", "forwards", "server-forwards", "services", "tower", "files", "git", "unpair", "checks"] ; + +export const SERVE_SERVER_LIMITS = { + heartbeatMs: 20_000, + smallBodyBytes: 16 * 1024, + desktopBodyBytes: 80 * 1024, + /** Host tool methods (`host_tool_result` carries screenshots); the session caps the result's content at 8 MiB plus 1 MiB of details and the request at 10 MiB, envelope included. */ + hostToolBodyBytes: 10 * 1024 * 1024 - 1024, + /** Pi RPC commands may carry images. */ + rpcBodyBytes: 8 * 1024 * 1024, + rpcTimeoutMs: 30_000, + maxSessions: 16, + /** Exited sessions kept (with their replay ring) until deleted. */ + keepExited: 16, + /** The control session behind `/api/desktop` stops after this long with no request and no open stream. */ + controlIdleMs: 10 * 60_000, +}; + +/** What a stream ticket for `GET /api/desktop/events` is bound to (never a session id: those match `[A-Za-z0-9_]`). */ +const DESKTOP_STREAM = ":desktop"; + +/** Pi RPC commands that only read; every other command needs `sessions:operate`. */ +const READ_COMMANDS = new Set(["get_state", "get_messages", "get_available_models", "get_available_thinking_levels", "get_session_stats", + "get_fork_messages", "get_entries", "get_tree", "get_last_assistant_text", "get_commands"]); + +/** Desktop RPC reads (`capabilities`, `get_*`, `list_*`) need `sessions:read`; anything else operates. */ +export function desktopMethodScope(method ) { + return method === "capabilities" || method.startsWith("get_") || method.startsWith("list_") ? "sessions:read" : "sessions:operate"; +} + +export function rpcCommandScope(type ) { + return READ_COMMANDS.has(type) ? "sessions:read" : "sessions:operate"; +} + +/** + * Whether a Pi RPC message is a `/gentle:desktop` request for a host tool + * method (`set_host_tools`, `host_tool_result`, `host_tool_progress`, + * `host_message`, `set_host_context`). Those go only through `/desktop`, where the server sets + * the provider to the calling device and checks who answers a call; through + * `/rpc` a client could otherwise register as, or answer for, another device. + * Pi takes the command's arguments after the first space and the router parses + * them with `JSON.parse`, exactly as here. + */ +export function carriesHostToolRequest(message ) { + if (!message.startsWith("/gentle:desktop")) return false; + const space = message.indexOf(" "); + if (space === -1) return false; + let request ; + try { + request = JSON.parse(message.slice(space + 1)); + } catch { + return false; + } + return !!request && typeof request === "object" && "method" in request && typeof request.method === "string" && Object.hasOwn(HOST_TOOL_METHODS, request.method); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** A running Gentle Tower: its loopback port, the path that carries its token, and how to stop it. */ + + + + + + + + + + + + + + + + + + + + + + + +export function isLoopbackHost(host ) { + const h = host.replace(/^\[|\]$/g, "").toLowerCase(); + return h === "localhost" || h === "::1" || /^127(\.\d{1,3}){3}$/.test(h); +} + +export function isUnspecified(host ) { + return host === "0.0.0.0" || host === "::" || host === "[::]"; +} + +/** The Host header values a request may carry for this listen address (DNS-rebinding guard), plus `extra` names the operator allowed. */ +export function allowedHosts(bindHost , port , extra = []) { + const named = new Set (); + const add = (h ) => named.add(`${h.toLowerCase()}:${port}`); + const bare = bindHost.replace(/^\[|\]$/g, ""); + if (isLoopbackHost(bare) || isUnspecified(bindHost)) for (const h of ["127.0.0.1", "localhost", "[::1]"]) add(h); + if (!isUnspecified(bindHost)) add(bare.includes(":") ? `[${bare}]` : bare); + if (isUnspecified(bindHost)) { + const own = hostname().toLowerCase(); + add(own); + if (!own.endsWith(".local")) add(`${own}.local`); + } + for (const h of extra) add(h); + return (value ) => { + const host = value.toLowerCase(); + if (named.has(host)) return true; + // On an unspecified bind any of this machine's addresses can reach it; names other than its own cannot. + if (!isUnspecified(bindHost)) return false; + const m = /^(?:\[[0-9a-f:.]+\]|\d{1,3}(?:\.\d{1,3}){3}):(\d+)$/.exec(host); + return !!m && Number(m[1]) === port; + }; +} + +function bearer(req ) { + const header = req.headers.authorization; + if (typeof header !== "string") return undefined; + const m = /^Bearer\s+(\S{1,512})$/i.exec(header); + return m ? m[1] : undefined; +} + +/** + * The server's identity, minted once per agent home in `/server-id` + * (`0600`) and the same on every run, so a restart or upgrade keeps the id + * devices, connection codes and discovery replies know. Unreadable or + * malformed: minted again. + */ +export function stableServerId(serveDir ) { + const path = join(serveDir, "server-id"); + try { + const saved = readFileSync(path, "utf8").trim(); + if (/^srv_[0-9a-f]{16}$/.test(saved)) return saved; + } catch { /* none yet */ } + const minted = `srv_${randomBytes(8).toString("hex")}`; + mkdirSync(serveDir, { recursive: true, mode: 0o700 }); + writeFileSync(path, `${minted}\n`, { mode: 0o600 }); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } + return minted; +} + +export function startServeServer(options ) { + if (options.relay && !options.tls) return Promise.reject(new Error("a relay needs TLS: the relay must only ever see ciphertext")); + const limits = { ...SERVE_SERVER_LIMITS, ...options.limits }; + const now = options.now ?? Date.now; + const log = options.log ?? (() => {}); + const serverId = options.serveDir === undefined ? `srv_${randomBytes(8).toString("hex")}` : stableServerId(options.serveDir); + const startedAt = now(); + const sessions = new Map (); + let hostOk = () => false; + let closing = false; + // Device names for the model-facing "not connected" answer of a host tool call. + const deviceNames = new Map (); + const deviceLabel = (deviceId ) => deviceNames.get(deviceId) ?? options.auth.listDevices().find((d) => d.id === deviceId)?.name; + + let mainPort = options.port; + let relayLink ; + // Pages on this machine's loopback, opened from a device: one listener each on the same address as this server. + const forwards = new ForwardManager({ + bindHost: options.host, + hostCheck: (port) => allowedHosts(options.host, port, options.allowHosts), + ...(options.forwardPorts === undefined ? {} : { portRange: options.forwardPorts }), + ...(options.tls === undefined ? {} : { tls: options.tls }), + now, + log, + limits: options.forwardLimits, + }); + // Pairing proofs bind each live code to the certificate, for a client that found this server through discovery. + const proofs = options.tls === undefined ? undefined : new PairProofs(options.tls.fingerprint, now); + // Files on this machine, and their change streams. + const files = new FileService({ limits: options.fsLimits, now, log }); + // git commands in folders on this machine. + const git = new GitService({ env: options.env ?? process.env, limits: options.gitLimits, log }); + // Whether this machine has what sessions need (`GET /api/checks`). + const checks = new ServeChecks({ env: options.env ?? process.env, version: options.version, ...options.checks }); + // One-shot prompts (commit messages) answered by this machine's Gentle Shell. + const prints = new PrintService({ ...(options.launchPrint ? { launchPrint: options.launchPrint } : {}), limits: options.printLimits, log }); + // Upgrades of Gentle Shell itself, from an admin client. + // A finished setup or upgrade changes what the readiness checks see. + const upgrade = options.upgrade ? new UpgradeService({ ...options.upgrade, onFinished: () => checks.forget(), log }) : undefined; + // Files a client sends for the agent to see. + const uploads = options.serveDir === undefined ? undefined : new UploadStore({ dir: join(options.serveDir, "uploads"), limits: options.uploadLimits, now, log }); + // Persistent terminals in the native terminal host, which outlives this server. + const terminals = options.serveDir === undefined ? undefined : new TerminalService({ serveDir: options.serveDir, env: options.env ?? process.env, limits: options.termLimits, log }); + // Gentle Tower, when a device asked for it; stopped with the server. + let tower ; + let towerStarting ; + + options.auth.onRevoke((deviceId) => { + for (const s of sessions.values()) s.dropDevice(deviceId); + control?.dropDevice(deviceId); + forwards.closeWhere((f) => f.deviceId === deviceId, "device revoked"); + files.closeDevice(deviceId); + terminals?.closeDevice(deviceId); + }); + + const sessionView = (s , principal ) => ({ + id: s.id, + name: basename(s.cwd) || null, + // The absolute folder only for a token that may start sessions anyway. + ...(hasScope(principal, "sessions:operate") ? { cwd: s.cwd } : {}), + state: s.state, + startedAt: new Date(s.startedAt).toISOString(), + ...(s.exitedAt === undefined ? {} : { exitedAt: new Date(s.exitedAt).toISOString(), exitCode: s.exitCode, exitSignal: s.exitSignal }), + seq: s.seq, + subscribers: s.subscriberCount, + pendingDialogs: s.pendingDialogs().length, + // The device that most recently drove the session: host tool calls go to it first. + lastActiveDevice: s.lastActiveDevice() ?? null, + }); + + const findSession = (id ) => { + const s = sessions.get(id); + if (!s) throw new HttpError(404, "not_found", "No such session"); + return s; + }; + + // Sessions run under detached keepers (lib/serve-session-keeper.ts) that outlive this server; a later server + // reattaches them. Without a serve folder they live in a private temporary folder and end with the server. + const keepSessions = options.serveDir !== undefined; + const keeperDir = options.serveDir !== undefined ? join(options.serveDir, "sessions") : privateKeeperDir(); + const keeperLimits = { ...SERVE_KEEPER_LIMITS, ...options.keeperLimits }; + let starting = 0; + + const forgetExited = () => { + const exited = [...sessions.values()].filter((s) => s.state === "exited"); + for (const s of exited.slice(0, Math.max(0, exited.length - limits.keepExited))) { + sessions.delete(s.id); + removeKeeperRecord(keeperDir, s.id); + } + }; + + const sessionHooks = (id ) => ({ + limits: options.sessionLimits, + now, + onStderr: (text ) => { for (const line of text.split("\n")) if (line.trim()) log(`[${id}] ${line}`); }, + onExit: (s ) => { + log(`[${id}] exited (code ${s.exitCode}, signal ${s.exitSignal})`); + forwards.closeWhere((f) => f.sessionId === id, "session ended"); + forgetExited(); + }, + deviceLabel, + }); + + /** Connects to a session's keeper and takes over its state; the control session is kept apart from the listed ones. */ + const attachSession = async (id , token , reattached , asControl = false) => { + const { link, snapshot, ring } = await KeeperLink.connect(keeperEndpoint(keeperDir, id), token, { + timeoutMs: keeperLimits.connectMs, + maxLineBytes: options.sessionLimits?.maxLineBytes ?? SERVE_SESSION_LIMITS.maxLineBytes, + }); + const session = new ServeSession({ snapshot, ring, link, reattached, ...(asControl ? controlHooks(id) : sessionHooks(id)) }); + if (asControl) adoptControl(session, reattached); + else sessions.set(id, session); + return session; + }; + + /** Starts a keeper running a new session in `cwd` and attaches it; the caller counts it against the limit. */ + const spawnSession = async (cwd , sessionId , asControl ) => { + const id = `ses_${randomBytes(8).toString("hex")}`; + const token = newKeeperToken(); + const launch = options.launchSession({ cwd, ...(sessionId === undefined ? {} : { sessionId }) }); + try { + await spawnKeeper({ id, dir: keeperDir, token, launch, ...(options.sessionLimits ? { limits: options.sessionLimits } : {}), keeperLimits }); + // Its id beside the keepers: a later server knows it again as the control session, never as a listed one. + if (asControl) writeFileSync(controlFile, `${id}\n`, { mode: 0o600 }); + return await attachSession(id, token, false, asControl); + } catch (error) { + removeKeeperRecord(keeperDir, id); + if (asControl) forgetControlId(id); + const message = error instanceof Error ? error.message : String(error); + log(`[${id}] could not start: ${message}`); + throw new HttpError(503, "session_start_failed", `The session could not start: ${message}`); + } + }; + + const startSession = async (cwd , sessionId ) => { + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + const running = [...sessions.values()].filter((s) => s.state === "running").length + starting; + if (running >= limits.maxSessions) throw new HttpError(429, "too_many_sessions", `At most ${limits.maxSessions} sessions run at once`); + starting += 1; + let session ; + try { + session = await spawnSession(cwd, sessionId, false); + } finally { + starting -= 1; + } + // The server began stopping meanwhile: the session goes the way the others went. + if (closing) { + if (keepSessions) session.detach(); + else await session.stop(); + throw new HttpError(503, "shutting_down", "The server is stopping"); + } + log(`[${session.id}] started`); + return session; + }; + + // The control session: a session in the server user's home folder that answers `/api/desktop` (Desktop RPC + // without a session of the client's own) and never takes a model turn. Started on first use, kept while + // requests or event streams use it, stopped after `controlIdleMs` without either. It holds no user state and + // must run this server's code (a restart after `git pull` or an upgrade must not answer with the old one), so + // it ends with its server, unlike the listed sessions: the close stops it, and one a previous server left + // running (a crash, or a server from before this rule) is stopped through its keeper at start, never taken + // back. `/control` names it. It is not listed, not counted against `maxSessions`, and not + // reachable by id. + const controlFile = join(keeperDir, "control"); + let control ; + let controlStarting ; + let controlInFlight = 0; + let controlIdle ; + /** An idle control session on its way out; the server's close waits for it. */ + let controlStopping ; + + const readControlId = () => { + try { + const id = readFileSync(controlFile, "utf8").trim(); + return /^ses_[A-Za-z0-9]{1,60}$/.test(id) ? id : undefined; + } catch { + return undefined; + } + }; + + /** Forgets the control session's id, unless a newer one took its place. */ + const forgetControlId = (id ) => { + if (readControlId() === id) rmSync(controlFile, { force: true }); + }; + + const controlHooks = (id ) => ({ + ...sessionHooks(id), + onExit: (s ) => { + log(`[${id}] control session exited (code ${s.exitCode}, signal ${s.exitSignal})`); + if (control === s) control = undefined; + forgetControlId(id); + removeKeeperRecord(keeperDir, id); + }, + }); + + /** A control session a server started (`reattached` false) takes over; one a previous server left is stopped. */ + const adoptControl = (session , reattached ) => { + // A keeper whose session ended while no server ran: its end is collected, and it is forgotten. + if (session.state !== "running") { + forgetControlId(session.id); + removeKeeperRecord(keeperDir, session.id); + return; + } + // It runs the code of the server that started it, maybe not this one's: the next use starts a fresh one. + if (reattached) return retireControl(session, "left by a previous server"); + control = session; + armControlIdle(); + }; + + /** Stops a control session, out of reach at once so no request lands on it meanwhile; its exit forgets it. The server's close waits for it. */ + const retireControl = (session , why ) => { + if (control === session) control = undefined; + log(`[${session.id}] control session ${why}: stopping`); + const stopping = session.stop().catch(() => undefined); + const before = controlStopping; + controlStopping = before ? Promise.all([before, stopping]).then(() => undefined) : stopping; + }; + + /** Stops the control session after `controlIdleMs` with no request in flight and no open stream. */ + const armControlIdle = () => { + clearTimeout(controlIdle); + controlIdle = undefined; + const session = control; + if (!session || closing || session.subscriberCount > 0 || controlInFlight > 0) return; + controlIdle = setTimeout(() => { + controlIdle = undefined; + if (control !== session || closing || session.subscriberCount > 0 || controlInFlight > 0) return; + retireControl(session, "idle"); + }, limits.controlIdleMs); + controlIdle.unref(); + }; + + /** The running control session, started when there is none. */ + const ensureControl = () => { + if (control?.state === "running") return Promise.resolve(control); + if (closing) return Promise.reject(new HttpError(503, "shutting_down", "The server is stopping")); + return controlStarting ??= (async () => { + try { + const session = await spawnSession(homedir(), undefined, true); + // The server began stopping meanwhile: its close takes care of the session. + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + log(`[${session.id}] control session started`); + return session; + } finally { + controlStarting = undefined; + } + })(); + }; + + /** Runs `work` with the control session, which stays up (no idle stop) meanwhile. */ + const withControl = async (work ) => { + controlInFlight += 1; + clearTimeout(controlIdle); + try { + return await work(await ensureControl()); + } finally { + controlInFlight -= 1; + armControlIdle(); + } + }; + + /** At start: every keeper a previous server left is attached again; sessions that ended are listed from their records. */ + const reattach = async () => { + const controlId = readControlId(); + await Promise.all(readKeeperRecords(keeperDir).map(async (record ) => { + const asControl = record.id === controlId; + // A keeper whose Pi already exited waits a minute for a server to collect the end of its stream. + if (record.state === "running" || keeperAlive(record.keeperPid)) { + try { + const session = await attachSession(record.id, record.token, true, asControl); + if (!asControl) log(`[${record.id}] reattached (seq ${session.seq}, ${session.state})`); + return; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (record.state === "running") { + // A keeper that is there but does not answer is left alone: it stops its session after a day without a server. + if (keeperAlive(record.keeperPid)) return log(`[${record.id}] its keeper (pid ${record.keeperPid}) did not answer: ${message}`); + record = { ...record, state: "exited", exitCode: null, exitSignal: null, exitedAt: now(), error: "keeper_lost" }; + writeKeeperRecord(keeperDir, record); + log(`[${record.id}] lost: its keeper is gone`); + } + } + } + // A control session that ended is forgotten, never listed. + if (asControl) { + forgetControlId(record.id); + removeKeeperRecord(keeperDir, record.id); + return; + } + sessions.set(record.id, new ServeSession({ snapshot: exitedSnapshot(record), ...sessionHooks(record.id) })); + })); + forgetExited(); + }; + const reattached = reattach().catch((error ) => log(`reattaching sessions failed: ${error instanceof Error ? error.message : String(error)}`)); + + /** `after` from the query, or the `Last-Event-ID` header `EventSource` sends on reconnect. */ + const eventsAfter = (req , url ) => { + const raw = url.searchParams.get("after") ?? (typeof req.headers["last-event-id"] === "string" ? req.headers["last-event-id"] : null); + if (raw === null || raw === "") return undefined; + if (!/^\d{1,15}$/.test(raw)) throw new HttpError(400, "invalid_after", "after must be a whole number"); + return Number(raw); + }; + + const openEvents = (req , res , session , principal , after , filter ) => { + res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", Connection: "keep-alive", "X-Accel-Buffering": "no", ...SECURITY_HEADERS }); + res.flushHeaders(); + req.socket.setNoDelay(true); + deviceNames.set(principal.deviceId, principal.name); + session.subscribe(res, principal.deviceId, after, filter); + res.on("close", () => session.unsubscribe(res)); + }; + + /** `GET /api/desktop/events`: the control session's Desktop RPC events (and nothing else of its stream), by its `seq`. */ + const openControlEvents = async (req , res , principal , url ) => { + const ticket = url.searchParams.get("ticket"); + let who ; + if (ticket !== null) { + const holder = options.auth.redeemTicket(ticket, DESKTOP_STREAM); + if (!holder) throw new HttpError(401, "invalid_ticket", "Unknown, used or expired stream ticket"); + who = holder; + } else { + who = need(principal, "sessions:read"); + } + const after = eventsAfter(req, url); + await withControl(async (session) => { + // The client may have gone while the session started. + if (res.destroyed) return; + openEvents(req, res, session, who, after, isDesktopEventRecord); + // The last stream closing starts the idle wait. + res.on("close", armControlIdle); + }); + }; + + const forwardView = (f ) => ({ + id: f.id, + port: f.port, + listenPort: f.listenPort, + sessionId: f.sessionId, + kind: f.kind, + createdAt: new Date(f.createdAt).toISOString(), + lastUsedAt: new Date(f.lastUsedAt).toISOString(), + }); + + /** A fresh single-use link to the forward, on the host name and scheme the client reached this server with. */ + const forwardLink = (req , forward , path ) => { + const minted = forwards.mintTicket(forward.id); + const clientHost = (req.headers.host ?? "127.0.0.1").replace(/:\d+$/, ""); + return { url: forwards.urlFor(forward.id, clientHost, path, minted.ticket, requestScheme(req)), expiresAt: new Date(minted.expiresAt).toISOString() }; + }; + + /** A device sees and closes its own forwards; an admin token sees every one. */ + const ownsForward = (principal , forward ) => forward.deviceId === principal.deviceId || hasScope(principal, "admin"); + + /** + * `/api/sessions/:id/forwards[/:fid]` (a session's, closed with it) and + * `/api/forwards[/:fid]` (`sessionId` null: the server's own, until closed, + * revoked, idle or the server stops). The server-level list and DELETE cover + * every forward the device owns. + */ + const forwardRoute = async (req , res , method , principal , sessionId , forwardId ) => { + const session = sessionId === null ? undefined : findSession(sessionId); + const inScope = (f ) => session === undefined || f.sessionId === session.id; + if (forwardId !== undefined) { + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use DELETE"); + const who = need(principal, "sessions:operate"); + const forward = forwards.get(forwardId); + if (!forward || !inScope(forward) || !ownsForward(who, forward)) throw new HttpError(404, "not_found", "No such forward"); + forwards.close(forward.id); + return sendJson(res, 200, { closed: forward.id }); + } + if (method === "GET") { + const who = need(principal, "sessions:read"); + return sendJson(res, 200, { forwards: forwards.list().filter((f) => inScope(f) && ownsForward(who, f)).map(forwardView) }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use GET or POST"); + const who = need(principal, "sessions:operate"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const port = body.port; + if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) throw new HttpError(400, "invalid_port", "port must be a whole number 1-65535"); + // This server and the forwards themselves are never targets: a forward to a forward loops. + if (port === mainPort || forwards.listenPorts().includes(port)) throw new HttpError(400, "invalid_port", "That port is the server's own"); + const path = body.path ?? "/"; + if (typeof path !== "string" || path.length > 2048 || !/^\/(?!\/)[\x21-\x7e]*$/.test(path)) throw new HttpError(400, "invalid_path", "path must start with / and hold no spaces or control characters"); + if (session && session.state !== "running") throw new HttpError(409, "session_exited", "The session has ended"); + const opened = await forwards.open({ deviceId: who.deviceId, sessionId: session?.id ?? null, kind: session ? "session" : "server", port }); + return sendJson(res, opened.created ? 201 : 200, { ...forwardView(opened.forward), ...forwardLink(req, opened.forward, path) }); + }; + + /** Local services a client may want to open through a forward: Engram (when it answers) and Gentle Tower (when it runs). */ + const listServices = async () => { + const services = []; + const env = options.env ?? process.env; + let engram ; + try { engram = new URL(env.ENGRAM_URL || "http://127.0.0.1:7437"); } catch { /* not a URL: not listed */ } + if (engram && (engram.protocol === "http:" || engram.protocol === "https:")) { + // Never the URL's credentials in the answer; fetch refuses them in a URL, so they travel as Basic auth. + const base = `${engram.protocol}//${engram.host}${engram.pathname}`.replace(/\/+$/, ""); + const credentials = engram.username || engram.password ? `${decodeURIComponent(engram.username)}:${decodeURIComponent(engram.password)}` : undefined; + const available = await fetch(`${base}/health`, { + signal: AbortSignal.timeout(1500), + ...(credentials === undefined ? {} : { headers: { Authorization: `Basic ${Buffer.from(credentials).toString("base64")}` } }), + }).then((r) => r.ok, () => false); + const port = Number(engram.port || (engram.protocol === "https:" ? 443 : 80)); + // A forward reaches only this machine's loopback, over plain HTTP. + const forwardable = engram.protocol === "http:" && isLoopbackHost(engram.hostname) && port !== mainPort; + services.push({ id: "engram", name: "Engram", url: base, port, available, forwardable, ...(forwardable ? { via: "forwards" } : {}) }); + } + if (tower) services.push({ id: "tower", name: "Gentle Tower", port: tower.port, available: true, forwardable: true, via: "tower" }); + return services; + }; + + const ensureTower = async () => { + if (tower) return { tower, started: false }; + if (!options.startTower) throw new HttpError(501, "not_supported", "This server cannot start Gentle Tower"); + const start = options.startTower; + const pending = towerStarting ??= (async () => ({ ...(await start()), startedAt: now() }))(); + try { + const running = await pending; + const started = tower === undefined; + tower = running; + if (started) log(`tower started on loopback:${running.port}`); + return { tower: running, started }; + } catch (error) { + throw new HttpError(503, "tower_unavailable", error instanceof Error ? error.message : String(error)); + } finally { + towerStarting = undefined; + } + }; + + const stopTower = async () => { + const running = tower; + if (!running) return false; + tower = undefined; + forwards.closeWhere((f) => f.kind === "tower", "tower stopped"); + await running.close(); + log("tower stopped"); + return true; + }; + + const towerRoute = async (req , res , method , principal ) => { + if (method === "GET") { + need(principal, "sessions:read"); + return sendJson(res, 200, tower ? { running: true, startedAt: new Date(tower.startedAt).toISOString() } : { running: false }); + } + if (method === "DELETE") { + need(principal, "sessions:operate"); + return sendJson(res, 200, { stopped: await stopTower() }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use GET, POST or DELETE"); + // Tower can send messages to sessions and open new ones: operating, not reading. + const who = need(principal, "sessions:operate"); + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + const { tower: running, started } = await ensureTower(); + const opened = await forwards.open({ deviceId: who.deviceId, sessionId: null, kind: "tower", port: running.port }); + return sendJson(res, opened.created ? 201 : 200, { ...forwardView(opened.forward), ...forwardLink(req, opened.forward, running.path), started }); + }; + + const route = async (req , res , url ) => { + // Requests wait for the sessions a previous server left to be attached again. + await reattached; + const method = req.method ?? "GET"; + const path = url.pathname; + const principal = options.auth.authenticate(bearer(req)); + if (path.length > 256) throw new HttpError(404, "not_found", "Not found"); + + // Who answers here, without a token and without secrets: a client holding a + // connection code probes each advertised address and pairs only where the id matches. + if (path === SERVE_IDENTITY_PATH) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + return sendJson(res, 200, { schema: SERVE_IDENTITY_SCHEMA, serverId, name: hostname(), protocol: SERVE_PROTOCOL, version: options.version, + tls: options.tls !== undefined, ...(options.tls === undefined ? {} : { fp: options.tls.fingerprint }) }); + } + + // Before a client that found this server through discovery sends its code: one proof per live code that + // binds it to this certificate, which only a server knowing the code can make (docs/serve.md#pairing-proof). + if (path === "/api/pair/proof") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (!proofs) throw new HttpError(501, "not_supported", "This server has no certificate: it serves plain HTTP"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const nonce = typeof body.nonce === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(body.nonce) ? Buffer.from(body.nonce, "base64url") : undefined; + if (!nonce || nonce.length < PAIR_PROOF.nonceMinBytes || nonce.length > PAIR_PROOF.nonceMaxBytes) throw new HttpError(400, "invalid_nonce", `nonce must be ${PAIR_PROOF.nonceMinBytes}-${PAIR_PROOF.nonceMaxBytes} random bytes, base64url`); + if (!proofs.allow()) throw new HttpError(429, "rate_limited", "Too many proof requests; wait a minute"); + return sendJson(res, 200, { proofs: await proofs.proofs(options.auth.livePairingCodes(), nonce) }); + } + + if (path === "/api/pair") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const result = options.auth.redeem(body.code, body.name); + if ("error" in result) { + const status = result.error === "rate_limited" ? 429 : result.error === "too_many_devices" ? 409 : 403; + throw new HttpError(status, result.error, result.error === "invalid_code" ? "Unknown, used or expired pairing code" : result.error === "rate_limited" ? "Too many failed attempts; wait a minute" : "Too many paired devices; revoke one first"); + } + log(`paired device ${result.device.id} (${result.device.scopes.join(",")})`); + return sendJson(res, 201, { ...result.device, token: result.token }); + } + + // Streams opened by EventSource carry a single-use ticket instead of a header. + const events = /^\/api\/sessions\/([A-Za-z0-9_]{1,64})\/events$/.exec(path); + if (events) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + const session = findSessionFor(events[1], principal, url); + return openEvents(req, res, session.session, session.principal, eventsAfter(req, url)); + } + if (path === "/api/desktop/events") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + return openControlEvents(req, res, principal, url); + } + if (path === "/api/desktop") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + return controlDesktop(req, res, principal); + } + + if (path === "/api/server") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + const who = need(principal, "sessions:read"); + return sendJson(res, 200, { schema: SERVE_SCHEMA, protocol: SERVE_PROTOCOL, serverId, version: options.version, startedAt: new Date(startedAt).toISOString(), + capabilities: [...SERVE_CAPABILITIES, ...(uploads ? ["uploads"] : []), ...(terminals?.binary() ? ["terminals"] : []), ...(prints.available ? ["print"] : []), ...(keepSessions ? ["persistent-sessions"] : []), ...(upgrade ? ["upgrade"] : []), ...(upgrade?.canSetup() ? ["setup"] : [])], + device: { id: who.deviceId, name: who.name, scopes: who.scopes }, + // How to build paths for the file and session endpoints. + platform: process.platform, arch: arch(), pathSeparator: sep, + // The server user's home folder, a default for new sessions; only for a token that may start them. + ...(hasScope(who, "sessions:operate") ? { home: homedir() } : {}), + // The certificate devices pin on the network, and the relay registration. + ...(options.tls === undefined ? {} : { tls: { fingerprint: options.tls.fingerprint } }), + ...(relayLink === undefined ? {} : { relay: { url: relayLink.url, connected: relayLink.connected() } }) }); + } + if (path === "/api/server/stop") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const endSessions = body.endSessions === true; + sendJson(res, 202, { stopping: true, endSessions }); + setImmediate(() => options.onStopRequested?.({ endSessions })); + return; + } + if (path === "/api/upgrade") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + if (!upgrade) throw new HttpError(501, "not_supported", "This server cannot upgrade itself"); + const body = await readJsonBody(req, limits.smallBodyBytes); + if (Object.keys(body).some((key) => key !== "channel") || (body.channel !== undefined && !UPGRADE_CHANNELS.includes(body.channel ))) { + throw new HttpError(400, "invalid_request", `channel must be ${UPGRADE_CHANNELS.join(" or ")}`); + } + return sendJson(res, 202, upgrade.start(body.channel )); + } + const upgradeStream = /^\/api\/upgrade\/(upg_[0-9a-f]{16})\/stream$/.exec(path); + if (upgradeStream) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "admin"); + if (!upgrade) throw new HttpError(501, "not_supported", "This server cannot upgrade itself"); + return upgrade.stream(req, res, upgradeStream[1]); + } + if (path === "/api/setup") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + if (!upgrade?.canSetup()) throw new HttpError(501, "not_supported", "This server cannot run setup"); + const body = await readJsonBody(req, limits.smallBodyBytes); + if (Object.keys(body).length > 0) throw new HttpError(400, "invalid_request", "setup takes no options"); + return sendJson(res, 202, upgrade.startSetup()); + } + const setupStream = /^\/api\/setup\/(setup_[0-9a-f]{16})\/stream$/.exec(path); + if (setupStream) { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "admin"); + if (!upgrade?.canSetup()) throw new HttpError(501, "not_supported", "This server cannot run setup"); + return upgrade.stream(req, res, setupStream[1]); + } + if (path === "/api/pairing-codes") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + need(principal, "admin"); + const body = await readJsonBody(req, limits.smallBodyBytes); + let scopes ; + if (body.scopes !== undefined) { + if (!Array.isArray(body.scopes) || body.scopes.length === 0 || !body.scopes.every(isServeScope)) throw new HttpError(400, "invalid_scopes", "scopes must be a non-empty list of known scopes"); + scopes = body.scopes; + } + const minted = options.auth.mintPairingCode(scopes); + return sendJson(res, 201, { code: minted.code, scopes: minted.scopes, expiresAt: new Date(minted.expiresAt).toISOString() }); + } + if (path === "/api/devices") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "admin"); + return sendJson(res, 200, { devices: options.auth.listDevices() }); + } + if (path === "/api/devices/self") { + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use DELETE"); + // Any paired device may unpair itself, whatever its scopes; the server's own token is no device. + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + if (principal.deviceId === "local") throw new HttpError(400, "not_a_device", "The server's own token is no paired device"); + if (!options.auth.revoke(principal.deviceId)) throw new HttpError(404, "not_found", "No such device"); + log(`device ${principal.deviceId} unpaired itself`); + return sendJson(res, 200, { revoked: principal.deviceId }); + } + if (path === "/api/devices/self/replace") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + // A device paired again takes the place of its earlier pairing, whose token it shows: that + // device's terminals become this one's, then it is revoked (its streams close). + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + if (principal.deviceId === "local") throw new HttpError(400, "not_a_device", "The server's own token is no paired device"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const earlier = typeof body.token === "string" && body.token.length <= 256 ? options.auth.authenticate(body.token) : undefined; + if (!earlier || earlier.deviceId === "local") throw new HttpError(404, "not_found", "No paired device has that token"); + if (earlier.deviceId === principal.deviceId) throw new HttpError(400, "same_device", "That token is this device's own"); + terminals?.adopt(earlier.deviceId, principal.deviceId); + options.auth.revoke(earlier.deviceId); + log(`device ${principal.deviceId} replaced ${earlier.deviceId}`); + return sendJson(res, 200, { replaced: earlier.deviceId }); + } + const device = /^\/api\/devices\/([A-Za-z0-9_]{1,64})$/.exec(path); + if (device) { + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use DELETE"); + need(principal, "admin"); + if (!options.auth.revoke(device[1])) throw new HttpError(404, "not_found", "No such device"); + log(`revoked device ${device[1]}`); + return sendJson(res, 200, { revoked: device[1] }); + } + if (path === "/api/tickets") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + const who = need(principal, "sessions:read"); + const body = await readJsonBody(req, limits.smallBodyBytes); + // A ticket for one session's events, or for `GET /api/desktop/events` (`{ stream: "desktop" }`). + let target ; + if (body.stream === "desktop" && body.sessionId === undefined) target = DESKTOP_STREAM; + else if (typeof body.sessionId === "string" && body.stream === undefined) target = findSession(body.sessionId).id; + else throw new HttpError(400, "invalid_request", "sessionId, or stream: \"desktop\", is required"); + const minted = options.auth.mintTicket(who, target); + return sendJson(res, 201, { ticket: minted.ticket, expiresAt: new Date(minted.expiresAt).toISOString() }); + } + if (path === "/api/sessions") { + if (method === "GET") { + const who = need(principal, "sessions:read"); + const listed = [...sessions.values()].map((s) => sessionView(s, who)); + // The control session only for an admin who asks for it. + const shown = url.searchParams.get("includeControl") === "1" && hasScope(who, "admin") ? control : undefined; + return sendJson(res, 200, { sessions: shown ? [...listed, { ...sessionView(shown, who), control: true }] : listed }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use GET or POST"); + const who = need(principal, "sessions:operate"); + const body = await readJsonBody(req, limits.smallBodyBytes); + const cwd = realDirectory(body.cwd); + let sessionId ; + if (body.sessionId !== undefined) { + // An id, never a path: Pi resolves it against its own session store. + if (typeof body.sessionId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(body.sessionId)) throw new HttpError(400, "invalid_session_id", "sessionId must be a Pi session id"); + sessionId = body.sessionId; + } + const started = await startSession(cwd, sessionId); + started.noteActivity(who.deviceId); + return sendJson(res, 201, { session: sessionView(started, who) }); + } + if (await files.route(req, res, method, path, url, principal)) return; + if (path === "/api/term-host" || path.startsWith("/api/terminals")) { + if (!terminals) throw new HttpError(501, "term_host_missing", "This server runs no terminals"); + if (await terminals.route(req, res, method, path, url, principal)) return; + } + if (path === "/api/uploads") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (!uploads) throw new HttpError(501, "not_supported", "This server takes no uploads"); + return uploads.upload(req, res, url, principal); + } + if (path === "/api/print") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (closing) throw new HttpError(503, "shutting_down", "The server is stopping"); + return prints.route(req, res, principal); + } + if (path === "/api/git") { + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + return git.route(req, res, principal); + } + if (path === "/api/tower") return towerRoute(req, res, method, principal); + if (path === "/api/checks") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "sessions:read"); + return sendJson(res, 200, { checks: await checks.checks() }); + } + if (path === "/api/services") { + if (method !== "GET") throw new HttpError(405, "method_not_allowed", "Use GET"); + need(principal, "sessions:read"); + return sendJson(res, 200, { services: await listServices() }); + } + const serverForward = /^\/api\/forwards(?:\/([A-Za-z0-9_]{1,64}))?$/.exec(path); + if (serverForward) return forwardRoute(req, res, method, principal, null, serverForward[1]); + const forward = /^\/api\/sessions\/([A-Za-z0-9_]{1,64})\/forwards(?:\/([A-Za-z0-9_]{1,64}))?$/.exec(path); + if (forward) return forwardRoute(req, res, method, principal, forward[1], forward[2]); + const one = /^\/api\/sessions\/([A-Za-z0-9_]{1,64})(\/rpc|\/desktop)?$/.exec(path); + if (one) { + const session = findSession(one[1]); + if (one[2] === undefined) { + if (method === "GET") return sendJson(res, 200, { session: sessionView(session, need(principal, "sessions:read")) }); + if (method !== "DELETE") throw new HttpError(405, "method_not_allowed", "Use GET or DELETE"); + const who = need(principal, "sessions:operate"); + await session.stop(); + sessions.delete(session.id); + removeKeeperRecord(keeperDir, session.id); + return sendJson(res, 200, { session: sessionView(session, who) }); + } + if (method !== "POST") throw new HttpError(405, "method_not_allowed", "Use POST"); + if (one[2] === "/rpc") return forwardRpc(req, res, session, principal); + return forwardDesktop(req, res, session, principal); + } + throw new HttpError(404, "not_found", "Not found"); + }; + + const findSessionFor = (id , principal , url ) => { + const ticket = url.searchParams.get("ticket"); + if (ticket !== null) { + const holder = options.auth.redeemTicket(ticket, id); + if (!holder) throw new HttpError(401, "invalid_ticket", "Unknown, used or expired stream ticket"); + return { session: findSession(id), principal: holder }; + } + const who = need(principal, "sessions:read"); + return { session: findSession(id), principal: who }; + }; + + const forwardRpc = async (req , res , session , principal ) => { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const command = await readJsonBody(req, limits.rpcBodyBytes); + if (typeof command.type !== "string" || command.type.length > 64) throw new HttpError(400, "invalid_command", "A Pi RPC command needs a type"); + if (command.id !== undefined && (typeof command.id !== "string" || command.id.length > 128)) throw new HttpError(400, "invalid_command", "id must be a string up to 128 characters"); + if (command.type === "extension_ui_response") { + session.noteActivity(need(principal, "sessions:operate").deviceId); + const outcome = await session.answerDialog(command); + if (outcome === "unknown") throw new HttpError(404, "unknown_dialog", "No pending dialog with this id"); + if (outcome === "answered") throw new HttpError(409, "dialog_answered", "Another client already answered this dialog"); + return sendJson(res, 202, { accepted: true }); + } + if (typeof command.message === "string" && carriesHostToolRequest(command.message)) { + throw new HttpError(400, "use_desktop_endpoint", "Host tool requests (set_host_tools, host_tool_result, host_tool_progress, host_message, set_host_context) go through POST /api/sessions/:id/desktop"); + } + const scope = rpcCommandScope(command.type); + need(principal, scope); + if (scope === "sessions:operate") session.noteActivity(principal.deviceId); + const outcome = await session.rpc(command, limits.rpcTimeoutMs); + if ("timeout" in outcome) return sendJson(res, 202, { pending: true, id: outcome.id }); + return sendJson(res, 200, outcome.response); + }; + + /** + * `POST /api/desktop`: a Desktop RPC request answered by the control session, for a client with no + * session of its own (configuration, sign-in, packages). Scopes as `/desktop`; host tool methods are + * refused, since they belong to the agent session whose tools they are. + */ + const controlDesktop = async (req , res , principal ) => { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const body = await readJsonBody(req, limits.desktopBodyBytes); + if (typeof body.method !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(body.method)) throw new HttpError(400, "invalid_request", "method must be a Desktop RPC method name"); + const params = body.params ?? {}; + if (!params || typeof params !== "object" || Array.isArray(params)) throw new HttpError(400, "invalid_request", "params must be an object"); + if (Object.hasOwn(HOST_TOOL_METHODS, body.method)) throw new HttpError(400, "use_session_desktop", "Host tool methods belong to an agent session: POST /api/sessions/:id/desktop"); + need(principal, desktopMethodScope(body.method)); + const method = body.method; + const outcome = await withControl((session) => session.desktop(method, params , limits.rpcTimeoutMs)); + if (outcome === undefined) throw new HttpError(504, "desktop_timeout", "The control session did not answer the Desktop RPC request in time"); + if ("prompt" in outcome) return sendJson(res, 502, { error: { code: "desktop_refused", message: "The control session refused the Desktop RPC request" }, response: outcome.prompt }); + return sendJson(res, 200, outcome.answer); + }; + + const forwardDesktop = async (req , res , session , principal ) => { + if (!principal) throw new HttpError(401, "unauthorized", "A valid bearer token is required"); + const body = await readJsonBody(req, Math.max(limits.desktopBodyBytes, limits.hostToolBodyBytes)); + if (typeof body.method !== "string" || !/^[a-z][a-z0-9_]{0,63}$/.test(body.method)) throw new HttpError(400, "invalid_request", "method must be a Desktop RPC method name"); + // A progress heartbeat is small: only results, tool lists, messages and context get the large body. + const largeBody = Object.hasOwn(HOST_TOOL_METHODS, body.method) && body.method !== "host_tool_progress"; + if (!largeBody && Buffer.byteLength(JSON.stringify(body), "utf8") > limits.desktopBodyBytes) throw new HttpError(413, "too_large", `Body over ${limits.desktopBodyBytes} bytes`); + const params = body.params ?? {}; + if (!params || typeof params !== "object" || Array.isArray(params)) throw new HttpError(400, "invalid_request", "params must be an object"); + if (body.method === "set_host_activity") throw new HttpError(403, "forbidden", "set_host_activity is the server's own: it reports which devices are connected and active"); + const scope = desktopMethodScope(body.method); + need(principal, scope); + // A progress heartbeat is the client's machinery, not the person driving the session: it does not move last-active routing. + if (scope === "sessions:operate" && body.method !== "host_tool_progress") session.noteActivity(principal.deviceId); + let forwarded = params ; + if (body.method === "set_host_tools" || body.method === "set_host_context") { + // The provider is always the calling device: a client cannot register tools or context as another device. + forwarded = { ...forwarded, provider: principal.deviceId }; + if (body.method === "set_host_tools") deviceNames.set(principal.deviceId, principal.name); + } + const callId = (body.method === "host_tool_result" || body.method === "host_tool_progress") && typeof forwarded.callId === "string" ? forwarded.callId : undefined; + if (callId !== undefined) { + const owner = session.hostCallProvider(callId); + if (owner !== undefined && owner !== principal.deviceId) throw new HttpError(403, "forbidden", "Only the device that provides this host tool may answer or keep alive its call"); + } + const outcome = await session.desktop(body.method, forwarded, limits.rpcTimeoutMs); + if (outcome === undefined) throw new HttpError(504, "desktop_timeout", "The session did not answer the Desktop RPC request in time"); + if ("prompt" in outcome) return sendJson(res, 502, { error: { code: "desktop_refused", message: "The session refused the Desktop RPC request" }, response: outcome.prompt }); + if (callId !== undefined) { + const error = outcome.answer.error; + const code = error && typeof error === "object" && "code" in error ? error.code : undefined; + if (code === "unknown_call" || code === "already_answered") session.hostCallSettled(callId); + else if (outcome.answer.ok === true) { + if (body.method === "host_tool_progress") session.hostCallProgressed(callId); + else session.hostCallSettled(callId); + } + } + if (body.method === "set_host_tools" && outcome.answer.ok === true) { + const data = outcome.answer.data; + const registered = data && typeof data === "object" && "registered" in data && Array.isArray(data.registered) ? data.registered.length : Array.isArray(forwarded.tools) ? forwarded.tools.length : 0; + session.noteHostProvider(principal.deviceId, registered); + } + return sendJson(res, 200, outcome.answer); + }; + + const handler = (via ) => (req , res ) => { + const host = req.headers.host; + // Through a relay the Host is whatever name the client used for it; no browser can speak the relay's handshake, so rebinding cannot reach here. + if (typeof host !== "string" || (via !== "relay" && !hostOk(host))) return sendError(res, 421, "bad_host", "Unexpected Host header"); + // Bearer tokens, not cookies, so a foreign page cannot ride a session; only this server's own origin is accepted. + const origin = req.headers.origin?.toLowerCase(); + if (origin !== undefined && origin !== `http://${host.toLowerCase()}` && origin !== `https://${host.toLowerCase()}`) return sendError(res, 403, "forbidden_origin", "Origin not allowed"); + let url ; + try { + url = new URL(req.url ?? "/", "http://serve.invalid"); + } catch { + return sendError(res, 400, "bad_request", "Bad request"); + } + route(req, res, url).catch((error ) => { + if (error instanceof HttpError) return sendError(res, error.status, error.code, error.message); + if (error instanceof SessionError) return sendError(res, error.code === "session_busy" || error.code === "shutting_down" ? 503 : 409, error.code, error.message); + if (error instanceof ForwardError) return sendError(res, error.status, error.code, error.message); + log(`internal error: ${error instanceof Error ? error.message : String(error)}`); + sendError(res, 500, "internal_error", "Server error"); + }); + }; + + const listener = createServeListener({ + ...(options.tls === undefined ? {} : { tls: options.tls }), + setup: (http , via) => { + http.on("request", handler(via)); + http.headersTimeout = 20_000; + http.requestTimeout = 0; // SSE streams stay open + http.keepAliveTimeout = 5_000; + }, + }); + const server = listener.server; + const heartbeat = setInterval(() => { + for (const s of sessions.values()) s.heartbeat(); + control?.heartbeat(); + files.heartbeat(); + terminals?.heartbeat(); + }, limits.heartbeatMs); + heartbeat.unref(); + + const { promise, resolve, reject } = Promise.withResolvers (); + server.once("error", reject); + server.listen(options.port, options.host.replace(/^\[|\]$/g, ""), async () => { + server.off("error", reject); + const address = server.address(); + const port = typeof address === "object" && address ? address.port : options.port; + hostOk = allowedHosts(options.host, port, options.allowHosts); + mainPort = port; + const localHost = isUnspecified(options.host) ? "127.0.0.1" : options.host.includes(":") && !options.host.startsWith("[") ? `[${options.host}]` : options.host; + // Plain HTTP: this machine may always use it, also when the network gets TLS. + const url = `http://${localHost}:${port}`; + // On the network, also answer LAN discovery on the same port number (UDP); the HTTP server works without it. + let discovery ; + if (!isLoopbackHost(options.host)) { + try { + discovery = await startDiscoveryResponder({ port, serverId, httpPort: port, name: hostname, log, ...(options.tls === undefined ? {} : { fingerprint: options.tls.fingerprint }) }); + } catch (error) { + log(`discovery off: could not bind UDP 0.0.0.0:${port}: ${error instanceof Error ? error.message : String(error)}`); + } + } + // Outside the network: a registration with the relay; each client it brings is one more TLS connection here (or to a forward's port). + const relay = relayLink = options.relay && options.tls ? startRelayLink({ + url: options.relay.url, + ...(options.relay.secret === undefined ? {} : { secret: options.relay.secret }), + ...(options.relay.retryMinMs === undefined ? {} : { retryMinMs: options.relay.retryMinMs }), + certDer: options.tls.der, + keyPem: options.tls.keyPem, + accept: (target) => (target === undefined || target === port ? (socket) => listener.acceptRelayed(socket) : forwards.relayTarget(target)), + log, + }) : undefined; + await reattached; + resolve({ + serverId, + host: options.host, + port, + url, + startedAt, + discovery: discovery !== undefined, + ...(options.tls === undefined ? {} : { fingerprint: options.tls.fingerprint }), + ...(relay === undefined ? {} : { relay }), + close: async (closeOptions ) => { + closing = true; + clearInterval(heartbeat); + relay?.close(); + await discovery?.close(); + forwards.closeAll(); + files.closeAll(); + git.closeAll(); + prints.closeAll(); + upgrade?.close(); + uploads?.close(); + terminals?.closeAll(); + await towerStarting?.catch(() => undefined); + await stopTower(); + // The control session ends with its server, whatever becomes of the others; one starting now is attached before that. + clearTimeout(controlIdle); + await controlStarting?.catch(() => undefined); + if (control) retireControl(control, "ends with the server"); + // Sessions keep running for the next server unless asked to end, or when no later server could find them. + if (keepSessions && closeOptions?.endSessions !== true) { + for (const s of sessions.values()) s.detach(); + } else { + await Promise.all([...sessions.values()].map((s) => s.stop())); + } + await controlStopping; + if (!keepSessions) removePrivateKeeperDir(keeperDir); + const closed = Promise.withResolvers (); + server.close(() => closed.resolve()); + listener.closeAllConnections(); + await closed.promise; + }, + }); + }); + return promise; +} diff --git a/runtime/serve-session-keeper-main.mjs b/runtime/serve-session-keeper-main.mjs new file mode 100644 index 000000000..c02628e2c --- /dev/null +++ b/runtime/serve-session-keeper-main.mjs @@ -0,0 +1,8 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// The session keeper process `gentle-shell serve` starts for each session +// (lib/serve-session-keeper.ts); run as `node serve-session-keeper-main.mjs` +// with its config on stdin. + +import { runKeeperProcess } from "./serve-session-keeper.mjs"; + +await runKeeperProcess(); diff --git a/runtime/serve-session-keeper.mjs b/runtime/serve-session-keeper.mjs new file mode 100644 index 000000000..3e656f0d0 --- /dev/null +++ b/runtime/serve-session-keeper.mjs @@ -0,0 +1,524 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// The session keeper of `gentle-shell serve`: a small detached Node process per +// session that owns Pi's stdin and stdout, so the session outlives the server. +// It numbers Pi's records (`seq`), keeps the replay ring, the pending dialogs +// and open host tool calls (lib/serve-session.ts `SessionLog`) and listens on +// an owner-only Unix socket `/sessions/.sock` (on Windows the +// named pipe `\\.\pipe\gentle-shell-serve--`) for one server at a +// time, which proves itself with the token in the session's record file. A +// server that starts scans the folder and reattaches every live keeper. +// +// A keeper ends when its Pi exits (its record file stays, marked exited, for the +// server's listing) or when the server stops the session. A keeper no server +// came back to for 24 hours stops its session. + +import { spawn, } from "node:child_process"; +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, } from "node:net"; +import { tmpdir, userInfo } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { isServerRecordType, JsonlDecoder, KEEPER_PROTOCOL, SERVE_SESSION_LIMITS, SessionLog, } from "./serve-session.mjs"; + +export const SERVE_KEEPER_LIMITS = { + /** A keeper no server is attached to stops its session after this long. */ + orphanMs: 24 * 60 * 60 * 1000, + /** After its Pi exited, how long a keeper with no server attached waits for one to collect the end of the stream. */ + lingerMs: 60_000, + /** How long a connection may take to send its hello. */ + helloMs: 5_000, + /** How long a server waits for a new keeper to report it started. */ + startMs: 10_000, + /** How long a server waits for a keeper's state when it connects. */ + connectMs: 5_000, + /** The most the server may keep with a keeper (`notes`). */ + notesBytes: 64 * 1024, +}; + +export const KEEPER_RECORD_SCHEMA = "gentle-shell.serve.session/v1"; + +/** `/sessions/.json` (`0600`): what a server needs to list a session and reach its keeper. */ + + + + + + + + + + + + + + + + + + + +/** What a server hands a new keeper (on its stdin, never on the command line: the environment carries secrets). */ + + + + + + + + + + +/** The keeper process's entry point (the runtime build points at the generated `.mjs`). */ +export const KEEPER_ENTRY = fileURLToPath(new URL("./serve-session-keeper-main.mjs", import.meta.url)); + +/** `sun_path` fits 104 bytes on macOS and 108 on Linux; stay below both. */ +const UNIX_SOCKET_PATH_MAX = 96; + +export function keeperEndpoint(dir , id ) { + if (process.platform !== "win32") { + const direct = join(dir, `${id}.sock`); + if (Buffer.byteLength(direct) <= UNIX_SOCKET_PATH_MAX) return direct; + // A long serve dir (a deep checkout, a macOS temp home) would overflow + // sun_path and `listen` would fail with EINVAL: fall back to a short, + // stable folder under the temp dir, named after the real one. + const short = join(tmpdir(), `gs-keeper-${createHash("sha256").update(dir).digest("hex").slice(0, 12)}`); + mkdirSync(short, { recursive: true, mode: 0o700 }); + return join(short, `${id}.sock`); + } + const user = userInfo().username.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 64) || "user"; + return `\\\\.\\pipe\\gentle-shell-serve-${user}-${id}`; +} + +function recordPath(dir , id ) { + return join(dir, `${id}.json`); +} + +export function writeKeeperRecord(dir , record ) { + const path = recordPath(dir, record.id); + const temp = `${path}.${process.pid}.tmp`; + writeFileSync(temp, `${JSON.stringify(record, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } +} + +export function readKeeperRecord(dir , id ) { + try { + const record = JSON.parse(readFileSync(recordPath(dir, id), "utf8")) ; + if (record?.schema !== KEEPER_RECORD_SCHEMA || record.id !== id || typeof record.token !== "string" || typeof record.cwd !== "string") return undefined; + return record; + } catch { + return undefined; + } +} + +/** Every session record in the folder, oldest first. */ +export function readKeeperRecords(dir ) { + let names ; + try { + names = readdirSync(dir); + } catch { + return []; + } + const records = []; + for (const name of names) { + const m = /^(ses_[A-Za-z0-9]{1,60})\.json$/.exec(name); + const record = m ? readKeeperRecord(dir, m[1]) : undefined; + if (record) records.push(record); + } + return records.sort((a, b) => a.startedAt - b.startedAt); +} + +/** Forgets a session: its record and (a stale) socket. */ +export function removeKeeperRecord(dir , id ) { + rmSync(recordPath(dir, id), { force: true }); + if (process.platform !== "win32") rmSync(keeperEndpoint(dir, id), { force: true }); +} + +export function newKeeperToken() { + return randomBytes(32).toString("base64url"); +} + +/** For a server without a serve folder: its keepers live (and end) in a private temporary folder. */ +export function privateKeeperDir() { + return mkdtempSync(join(tmpdir(), "gentle-serve-")); +} + +export function removePrivateKeeperDir(dir ) { + rmSync(dir, { recursive: true, force: true }); +} + +export function keeperAlive(pid ) { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error ).code === "EPERM"; + } +} + +/** A session whose keeper ended, as the server lists it: its record, no ring. */ +export function exitedSnapshot(record ) { + return { + protocol: KEEPER_PROTOCOL, + id: record.id, + cwd: record.cwd, + startedAt: record.startedAt, + pid: record.pid, + state: "exited", + exitCode: record.exitCode, + exitSignal: record.exitSignal, + exitedAt: record.exitedAt ?? record.startedAt, + seq: record.seq, + invalidRecords: 0, + droppedRecords: 0, + dialogs: [], + answered: [], + hostCalls: [], + notes: null, + }; +} + +function sameToken(a , b ) { + const x = Buffer.from(a); + const y = Buffer.from(b); + return x.length === y.length && timingSafeEqual(x, y); +} + +/** + * Starts a keeper process for `config` (detached: it outlives this server) and + * waits until it listens, runs Pi and wrote its record. + */ +export async function spawnKeeper(config , options = {}) { + const limits = { ...SERVE_KEEPER_LIMITS, ...config.keeperLimits }; + mkdirSync(config.dir, { recursive: true, mode: 0o700 }); + try { chmodSync(config.dir, 0o700); } catch { /* Windows */ } + const child = spawn(process.execPath, [options.entry ?? KEEPER_ENTRY], { + cwd: config.dir, + detached: true, + stdio: ["pipe", "pipe", "ignore"], + env: options.env ?? process.env, + windowsHide: true, + }); + const { promise, resolve, reject } = Promise.withResolvers (); + const timer = setTimeout(() => reject(new Error("the session keeper did not start in time")), limits.startMs); + const decoder = new JsonlDecoder((line) => { + let answer ; + try { answer = JSON.parse(line) ; } catch { return reject(new Error("the session keeper did not start")); } + if (answer.ok === true) resolve(); + else reject(new Error(typeof answer.error === "string" ? answer.error : "the session keeper did not start")); + }, () => reject(new Error("the session keeper did not start")), 64 * 1024); + child.stdout .on("data", (chunk ) => decoder.push(chunk)); + child.once("error", (error) => reject(error)); + child.once("exit", (code) => reject(new Error(`the session keeper exited (code ${code})`))); + child.stdin .on("error", () => { /* it exited: the exit says why */ }); + child.stdin .end(JSON.stringify(config)); + try { + await promise; + } catch (error) { + child.kill("SIGKILL"); + throw error; + } finally { + clearTimeout(timer); + child.removeAllListeners("exit"); + child.stdout .destroy(); + child.unref(); + } +} + + + + + + + +/** + * The keeper itself. It runs in its own process (`runKeeperProcess`); tests + * also run it in-process to drive its clock. + */ +export class SessionKeeper { + config ; + limits ; + keeperLimits ; + now ; + onDone ; + log ; + endpoint ; + server ; + child ; + startedAt = 0; + /** The attached server's connection. */ + serve ; + notes = null; + orphanTimer ; + lingerTimer ; + killTimer ; + done = false; + + constructor(config , options = {}) { + this.config = config; + this.limits = { ...SERVE_SESSION_LIMITS, ...config.limits }; + this.keeperLimits = { ...SERVE_KEEPER_LIMITS, ...config.keeperLimits }; + this.now = options.now ?? Date.now; + this.onDone = options.onDone ?? (() => {}); + this.log = new SessionLog(this.limits, this.now); + this.endpoint = keeperEndpoint(config.dir, config.id); + this.server = createServer((socket) => this.onConnection(socket)); + } + + /** Listens, starts Pi and writes the session's record. */ + async start() { + mkdirSync(this.config.dir, { recursive: true, mode: 0o700 }); + if (process.platform !== "win32") rmSync(this.endpoint, { force: true }); + const listening = Promise.withResolvers (); + this.server.once("error", listening.reject); + this.server.listen(this.endpoint, () => listening.resolve()); + await listening.promise; + if (process.platform !== "win32") chmodSync(this.endpoint, 0o600); + this.startedAt = this.now(); + this.spawnPi(); + this.writeRecord(); + this.armOrphan(); + } + + spawnPi() { + const { launch } = this.config; + const decoder = new JsonlDecoder((line) => this.onPiLine(line), () => { + this.emit({ type: "serve_record_dropped", reason: "too_large", maxBytes: this.limits.maxLineBytes }); + }, this.limits.maxLineBytes); + // stdin stays open for Pi's whole life: closing it asks Pi to shut down. + const child = spawn(launch.command, launch.args, { cwd: launch.cwd, env: launch.env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); + this.child = child; + child.stdout .on("data", (chunk ) => decoder.push(chunk)); + child.stdout .on("end", () => decoder.end()); + child.stderr .on("data", (chunk ) => this.send(JSON.stringify({ t: "stderr", text: chunk.toString("utf8") }))); + // Pi exiting while we write must not end the keeper. + child.stdin .on("error", () => {}); + let exited = false; + const finish = (code , signal , error ) => { + if (exited) return; + exited = true; + this.onPiExit(code, signal, error); + }; + child.once("error", (error) => finish(null, null, error.message)); + // `close` waits for stdout to drain, so every record lands before the exit record. + child.once("close", (code, signal) => finish(code, signal)); + } + + writeRecord() { + const log = this.log; + writeKeeperRecord(this.config.dir, { + schema: KEEPER_RECORD_SCHEMA, + id: this.config.id, + cwd: this.config.launch.cwd, + startedAt: this.startedAt, + keeperPid: process.pid, + pid: this.child?.pid ?? null, + token: this.config.token, + state: log.state, + exitCode: log.exitCode, + exitSignal: log.exitSignal, + exitedAt: log.exitedAt ?? null, + seq: log.seq, + }); + } + + // --- Pi's output --- + + onPiLine(line ) { + let record ; + try { + record = JSON.parse(line); + } catch { + record = undefined; + } + // stdout is reserved for protocol records, and `serve_*` records are the server side's own. + if (!record || typeof record !== "object" || Array.isArray(record) || isServerRecordType((record ).type)) { + this.log.invalidRecords += 1; + this.send('{"t":"invalid"}'); + return; + } + this.append(line, record ); + } + + append(line , record ) { + const seq = this.log.seq + 1; + this.log.push(seq, line, record); + this.send(`${seq} ${line}`); + } + + /** Records the keeper adds to the stream itself; they share the session's `seq`. */ + emit(record ) { + this.append(JSON.stringify(record), record); + } + + send(line ) { + this.serve?.write(`${line}\n`); + } + + // --- the server --- + + onConnection(socket ) { + socket.setNoDelay(true); + let authenticated = false; + const hello = setTimeout(() => { if (!authenticated) socket.destroy(); }, this.keeperLimits.helloMs); + hello.unref?.(); + const decoder = new JsonlDecoder((line) => { + if (authenticated) return this.onServeLine(socket, line); + let message ; + try { message = JSON.parse(line) ; } catch { /* refused below */ } + if (message?.op !== "hello" || typeof message.token !== "string" || !sameToken(message.token, this.config.token)) return socket.destroy(); + authenticated = true; + clearTimeout(hello); + this.attach(socket); + }, () => socket.destroy(), this.limits.maxLineBytes + 64); + socket.on("data", (chunk ) => decoder.push(chunk)); + socket.on("error", () => { /* close follows */ }); + socket.on("close", () => { + clearTimeout(hello); + if (this.serve !== socket) return; + this.serve = undefined; + this.armOrphan(); + }); + } + + /** A server proved itself: it replaces any earlier one and gets the whole state, then the live stream. */ + attach(socket ) { + const previous = this.serve; + this.serve = socket; + previous?.destroy(); + clearTimeout(this.orphanTimer); + this.orphanTimer = undefined; + const snapshot = { + t: "snapshot", + protocol: KEEPER_PROTOCOL, + id: this.config.id, + cwd: this.config.launch.cwd, + startedAt: this.startedAt, + pid: this.child?.pid ?? null, + ...this.log.snapshot(), + notes: this.notes, + }; + socket.write(`${JSON.stringify(snapshot)}\n`); + for (const record of this.log.ring.all()) socket.write(`${record.seq} ${record.line}\n`); + socket.write('{"t":"live"}\n'); + // Pi is gone and this server now has the end of the stream: the keeper's work is done. + if (this.log.state === "exited") this.finishAfter(socket); + } + + onServeLine(socket , line ) { + if (line.startsWith(">")) return this.toPi(socket, line.slice(1)); + let op ; + try { op = JSON.parse(line) ; } catch { return; } + switch (op.op) { + case "answer": { + const answer = op.answer && typeof op.answer === "object" ? op.answer : {}; + const id = typeof answer.id === "string" ? answer.id : ""; + const status = this.log.dialogStatus(id); + if (status === "pending") { + this.toPi(socket, JSON.stringify(answer)); + this.emit({ type: "serve_dialog_resolved", id }); + } + return this.send(JSON.stringify({ t: "reply", rid: op.rid, outcome: status === "pending" ? "accepted" : status })); + } + case "settled": + if (typeof op.callId === "string") this.log.settle(op.callId); + return; + case "progressed": + if (typeof op.callId === "string") this.log.progress(op.callId); + return; + case "notes": + if (Buffer.byteLength(JSON.stringify(op.notes ?? null)) <= this.keeperLimits.notesBytes) this.notes = op.notes ?? null; + return; + case "stop": + return this.stop(); + } + } + + /** One line for Pi's stdin; a Pi that stops reading holds back the server, which then refuses commands. */ + toPi(socket , line ) { + const stdin = this.child?.stdin; + if (this.log.state !== "running" || !stdin?.writable) return; + stdin.write(`${line}\n`); + if (stdin.writableLength > this.limits.stdinBufferBytes && !socket.isPaused()) { + socket.pause(); + stdin.once("drain", () => socket.resume()); + } + } + + armOrphan() { + if (this.serve || this.log.state !== "running" || this.orphanTimer) return; + this.orphanTimer = setTimeout(() => { + this.orphanTimer = undefined; + if (!this.serve) this.stop(); + }, this.keeperLimits.orphanMs); + this.orphanTimer.unref?.(); + } + + // --- the end --- + + /** Orderly stop: close Pi's stdin and send SIGTERM together (Pi treats them as one request), then SIGKILL. */ + stop() { + const child = this.child; + if (this.log.state !== "running" || !child || this.killTimer) return; + child.stdin .end(); + child.kill("SIGTERM"); + this.killTimer = setTimeout(() => { if (this.log.state === "running") child.kill("SIGKILL"); }, this.limits.stopGraceMs); + this.killTimer.unref?.(); + } + + onPiExit(code , signal , error ) { + clearTimeout(this.killTimer); + clearTimeout(this.orphanTimer); + // The record says exited before the server can hear it: a server that forgets the session removes it for good. + const record = { type: "serve_session_exited", code, signal, ...(error ? { error: "spawn_failed" } : {}) }; + const line = JSON.stringify(record); + const seq = this.log.seq + 1; + this.log.push(seq, line, record); + this.writeRecord(); + this.send(`${seq} ${line}`); + if (this.serve) return this.finishAfter(this.serve); + this.lingerTimer = setTimeout(() => this.finish(), this.keeperLimits.lingerMs); + this.lingerTimer.unref?.(); + } + + /** Ends once everything written to the attached server has gone out. */ + finishAfter(socket ) { + clearTimeout(this.lingerTimer); + socket.end(() => this.finish()); + socket.once("close", () => this.finish()); + } + + finish() { + if (this.done) return; + this.done = true; + clearTimeout(this.lingerTimer); + clearTimeout(this.orphanTimer); + this.server.close(); + if (process.platform !== "win32") rmSync(this.endpoint, { force: true }); + this.onDone(); + } +} + +/** The keeper process: its config arrives on stdin; it answers `{ ok }` on stdout once it runs. */ +export async function runKeeperProcess() { + const chunks = []; + for await (const chunk of process.stdin) chunks.push(chunk ); + const report = (answer ) => process.stdout.write(`${JSON.stringify(answer)}\n`); + let keeper ; + try { + const config = JSON.parse(Buffer.concat(chunks).toString("utf8")) ; + keeper = new SessionKeeper(config, { onDone: () => process.exit(0) }); + await keeper.start(); + } catch (error) { + report({ ok: false, error: error instanceof Error ? error.message : String(error) }); + process.exitCode = 1; + return; + } + // Detached from any terminal; only an explicit SIGTERM (a shutdown) stops the session. + process.on("SIGHUP", () => {}); + process.on("SIGINT", () => {}); + process.on("SIGTERM", () => keeper.stop()); + report({ ok: true, pid: process.pid }); +} diff --git a/runtime/serve-session.mjs b/runtime/serve-session.mjs new file mode 100644 index 000000000..11bd0de3b --- /dev/null +++ b/runtime/serve-session.mjs @@ -0,0 +1,1198 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// One server-owned agent session for `gentle-shell serve`. Pi runs under a +// detached session keeper (lib/serve-session-keeper.ts) that owns its stdin and +// stdout, numbers its JSONL output with a monotonic `seq` and keeps the replay +// ring, the dialogs still waiting for an answer and the host tool calls still +// open, so a session outlives a server restart. The server holds a mirror of +// that state, fed by the keeper over a Unix socket (a named pipe on Windows), +// plus what only it knows: the SSE subscribers, the requests waiting for an +// answer and which device runs host tools. A slow subscriber is dropped (it +// resyncs) instead of ever slowing the session. + +import { randomBytes } from "node:crypto"; +import { connect, } from "node:net"; + + + + + + + + + + + + + + + + + + + + + + + + + +export const SERVE_SESSION_LIMITS = { + maxLineBytes: 16 * 1024 * 1024, + ringRecords: 2000, + ringBytes: 8 * 1024 * 1024, + clientBufferBytes: 4 * 1024 * 1024, + stdinBufferBytes: 16 * 1024 * 1024, + stopGraceMs: 5000, + dropFlushMs: 5000, + hostToolGraceMs: 10_000, + hostToolReattachGraceMs: 30_000, + hostToolTrackMs: 11 * 60 * 1000, + hostToolAnswerMs: 30_000, +}; + +/** Pi RPC dialog methods: they block until one `extension_ui_response` answers them. */ +export const DIALOG_METHODS = { select: true, confirm: true, input: true, editor: true }; +export const DESKTOP_RPC_SCHEMA = "gentle-shell.desktop-rpc/v1"; +export const DESKTOP_RPC_WIDGET = "gentle-desktop-rpc"; +/** Desktop RPC methods that only a client's own `/desktop` request may carry (see lib/desktop-rpc-host-tools.ts). */ +export const HOST_TOOL_METHODS = { set_host_tools: true, host_tool_result: true, host_tool_progress: true, host_message: true, set_host_context: true, set_host_activity: true }; +/** The keeper protocol both ends speak; a keeper answering another one is not attached. */ +export const KEEPER_PROTOCOL = 1; + +// --- JSONL framing ------------------------------------------------------------- + +/** + * Splits a byte stream into records on LF only (an optional CR before it is + * stripped). Unlike `readline`, U+2028/U+2029 inside JSON strings never split a + * record. LF never occurs inside a multi-byte UTF-8 sequence, so decoding each + * complete record on its own is exact. + */ +export class JsonlDecoder { + parts = []; + size = 0; + discarding = false; + onLine ; + onOversize ; + maxLineBytes ; + + constructor(onLine , onOversize , maxLineBytes = SERVE_SESSION_LIMITS.maxLineBytes) { + this.onLine = onLine; + this.onOversize = onOversize; + this.maxLineBytes = maxLineBytes; + } + + push(chunk ) { + let start = 0; + while (start < chunk.length) { + const lf = chunk.indexOf(0x0a, start); + const end = lf === -1 ? chunk.length : lf; + if (!this.discarding) { + const piece = chunk.subarray(start, end); + if (this.size + piece.length > this.maxLineBytes) { + this.parts = []; + this.size = 0; + this.discarding = true; + } else if (piece.length > 0) { + this.parts.push(piece); + this.size += piece.length; + } + } + if (lf === -1) break; + this.finishRecord(); + start = lf + 1; + } + } + + /** Called when the stream ends: a last record without LF still counts. */ + end() { + if (this.size > 0 || this.discarding) this.finishRecord(); + } + + finishRecord() { + if (this.discarding) { + this.discarding = false; + this.onOversize(); + return; + } + let bytes = this.parts.length === 1 ? this.parts[0] : Buffer.concat(this.parts, this.size); + this.parts = []; + this.size = 0; + if (bytes.length > 0 && bytes[bytes.length - 1] === 0x0d) bytes = bytes.subarray(0, bytes.length - 1); + if (bytes.length > 0) this.onLine(bytes.toString("utf8")); + } +} + +// --- replay ring --------------------------------------------------------------- + + + + + + + + + +/** Bounded by count and bytes; the newest record is always kept. */ +export class ReplayRing { + records = []; + head = 0; + bytes = 0; + maxRecords ; + maxBytes ; + + constructor(maxRecords , maxBytes ) { + this.maxRecords = Math.max(1, maxRecords); + this.maxBytes = maxBytes; + } + + get length() { + return this.records.length - this.head; + } + + /** Oldest seq still held, or undefined when empty. */ + get oldest() { + return this.length === 0 ? undefined : this.records[this.head].seq; + } + + push(record ) { + this.records.push(record); + this.bytes += record.bytes; + while (this.length > 1 && (this.length > this.maxRecords || this.bytes > this.maxBytes)) { + this.bytes -= this.records[this.head].bytes; + this.head += 1; + } + // Compact lazily so eviction stays O(1) amortized. + if (this.head > 1024 && this.head * 2 > this.records.length) { + this.records = this.records.slice(this.head); + this.head = 0; + } + } + + /** Every record held, oldest first. */ + all() { + return this.records.slice(this.head); + } + + /** + * Records after `after`, or `snapshotRequired` when the client's cursor is + * older than the ring (something it never saw was evicted) or newer than + * the stream (it belongs to another session lifetime). + */ + since(after , current ) { + const oldest = this.oldest ?? current + 1; + if (!Number.isSafeInteger(after) || after < 0 || after > current || after < oldest - 1) return { snapshotRequired: true, oldest }; + const out = []; + for (let i = this.head; i < this.records.length; i += 1) if (this.records[i].seq > after) out.push(this.records[i]); + return { records: out }; + } +} + +// --- subscribers --------------------------------------------------------------- + +/** The part of an HTTP response an SSE subscriber needs (a fake in tests). */ + + + + + + + + + + + + + + + + +export function sseRecord(seq , line ) { + return `id: ${seq}\ndata: ${line}\n\n`; +} + +export function sseEvent(event , data ) { + return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; +} + +// --- the session's record state ------------------------------------------------ + + + + + + + + + + + + + + + + + +/** A `host_tool_call` the session emitted that no `host_tool_result` or `host_tool_cancel` settled yet. */ + + + + + + + + + + + +/** What a record means to the session's state and to the requests waiting on it. */ + + + + + + + + + + + +/** Records the server side adds to a stream; a session child may not print them. */ +export function isServerRecordType(type ) { + return typeof type === "string" && type.startsWith("serve_"); +} + +export function classifyRecord(record ) { + switch (record.type) { + case "response": + return typeof record.id === "string" ? { kind: "response", id: record.id } : undefined; + case "serve_dialog_resolved": + return typeof record.id === "string" ? { kind: "dialog_resolved", id: record.id } : undefined; + case "serve_record_dropped": + return { kind: "dropped" }; + case "serve_session_exited": + return { kind: "exited", code: typeof record.code === "number" ? record.code : null, signal: typeof record.signal === "string" ? record.signal : null }; + case "extension_ui_request": + break; + default: + return undefined; + } + if (typeof record.id !== "string") return undefined; + const method = record.method; + if (typeof method === "string" && Object.hasOwn(DIALOG_METHODS, method)) { + return { kind: "dialog", id: record.id, ...(typeof record.timeout === "number" && record.timeout > 0 ? { timeout: record.timeout } : {}) }; + } + if (method !== "setWidget" || record.widgetKey !== DESKTOP_RPC_WIDGET || !Array.isArray(record.widgetLines) || typeof record.widgetLines[0] !== "string") return undefined; + let answer ; + try { + answer = JSON.parse(record.widgetLines[0]); + } catch { + return undefined; + } + if (!answer || typeof answer !== "object") return undefined; + const a = answer ; + if (a.kind === "response") return typeof a.requestId === "string" ? { kind: "desktop_response", requestId: a.requestId, answer: a } : undefined; + if (a.kind !== "event") return undefined; + const data = a.data; + if (!data || typeof data !== "object" || !("callId" in data) || typeof data.callId !== "string") return undefined; + if (a.event === "host_tool_cancel") return { kind: "host_tool_cancel", callId: data.callId }; + if (a.event !== "host_tool_call" || !("provider" in data) || typeof data.provider !== "string" || !("tool" in data) || typeof data.tool !== "string") return undefined; + return { kind: "host_tool_call", callId: data.callId, provider: data.provider, tool: data.tool }; +} + +/** Whether `line` is a Desktop RPC event record (a `gentle-desktop-rpc` widget whose payload is `kind: "event"`), the only records `GET /api/desktop/events` carries. */ +export function isDesktopEventRecord(line ) { + let record ; + try { + record = JSON.parse(line); + } catch { + return false; + } + if (!record || typeof record !== "object") return false; + const r = record ; + if (r.type !== "extension_ui_request" || r.method !== "setWidget" || r.widgetKey !== DESKTOP_RPC_WIDGET || !Array.isArray(r.widgetLines) || typeof r.widgetLines[0] !== "string") return false; + try { + const payload = JSON.parse(r.widgetLines[0]) ; + return !!payload && typeof payload === "object" && (payload ).kind === "event"; + } catch { + return false; + } +} + +/** The state a keeper hands the server when it attaches; the ring's records follow it on the wire. */ + + + + + + + + + + + + + + + + + + + + +const ANSWERED_MEMORY = 256; + +/** + * The session's stream and what it implies: `seq`, the replay ring, pending + * dialogs (with the ids answered lately) and open host tool calls, and whether + * it exited. The keeper holds the authoritative one; the server a mirror fed + * with the same records, so both always agree. + */ +export class SessionLog { + seq = 0; + state = "running"; + exitCode = null; + exitSignal = null; + exitedAt ; + invalidRecords = 0; + droppedRecords = 0; + ring ; + dialogs = new Map (); + answered = []; + hostCalls = new Map (); + limits ; + now ; + + constructor(limits , now ) { + this.limits = limits; + this.now = now; + this.ring = new ReplayRing(limits.ringRecords, limits.ringBytes); + } + + /** Takes `record` (the parsed `line`) as record `seq` and applies what it means. */ + push(seq , line , record ) { + this.seq = seq; + this.ring.push({ seq, line, bytes: Buffer.byteLength(line) }); + const event = classifyRecord(record); + switch (event?.kind) { + case "dialog": + if (this.state === "running") this.dialogs.set(event.id, { id: event.id, seq, line, ...(event.timeout === undefined ? {} : { expiresAt: this.now() + event.timeout }) }); + break; + case "dialog_resolved": + this.dialogs.delete(event.id); + this.answered.push(event.id); + if (this.answered.length > ANSWERED_MEMORY) this.answered.shift(); + break; + case "host_tool_call": { + const now = this.now(); + for (const [id, call] of this.hostCalls) if (now - call.at > this.limits.hostToolTrackMs) this.hostCalls.delete(id); + if (this.state === "running") this.hostCalls.set(event.callId, { callId: event.callId, provider: event.provider, tool: event.tool, seq, line, at: now }); + break; + } + case "host_tool_cancel": + this.hostCalls.delete(event.callId); + break; + case "dropped": + this.droppedRecords += 1; + break; + case "exited": + this.state = "exited"; + this.exitCode = event.code; + this.exitSignal = event.signal; + this.exitedAt = this.now(); + this.dialogs.clear(); + this.hostCalls.clear(); + break; + } + return event; + } + + pendingDialogs() { + const now = this.now(); + for (const [id, dialog] of this.dialogs) if (dialog.expiresAt !== undefined && dialog.expiresAt <= now) this.dialogs.delete(id); + return [...this.dialogs.values()]; + } + + dialogStatus(id ) { + if (this.pendingDialogs().some((dialog) => dialog.id === id)) return "pending"; + return this.answered.includes(id) ? "answered" : "unknown"; + } + + hostCall(callId ) { + return this.hostCalls.get(callId); + } + + pendingHostCalls() { + return [...this.hostCalls.values()]; + } + + settle(callId ) { + this.hostCalls.delete(callId); + } + + /** A `host_tool_progress` kept the call alive: tracking it starts over. */ + progress(callId ) { + const call = this.hostCalls.get(callId); + if (call) call.at = this.now(); + } + + snapshot() { + return { + state: this.state, + exitCode: this.exitCode, + exitSignal: this.exitSignal, + exitedAt: this.exitedAt ?? null, + seq: this.seq, + invalidRecords: this.invalidRecords, + droppedRecords: this.droppedRecords, + dialogs: this.pendingDialogs(), + answered: [...this.answered], + hostCalls: this.pendingHostCalls(), + }; + } + + /** Takes over a keeper's state (its ring records are pushed into `ring` as they arrive). */ + restore(snapshot ) { + this.seq = snapshot.seq; + this.state = snapshot.state; + this.exitCode = snapshot.exitCode; + this.exitSignal = snapshot.exitSignal; + if (snapshot.exitedAt !== null) this.exitedAt = snapshot.exitedAt; + this.invalidRecords = snapshot.invalidRecords; + this.droppedRecords = snapshot.droppedRecords; + for (const dialog of snapshot.dialogs) this.dialogs.set(dialog.id, dialog); + this.answered.push(...snapshot.answered.slice(-ANSWERED_MEMORY)); + for (const call of snapshot.hostCalls) this.hostCalls.set(call.callId, call); + } +} + +// --- the link to a keeper -------------------------------------------------------- + +/** + * Wire format, both ways one record per LF-terminated line. Keeper → server: + * ` ` for each stream record, or a JSON control object + * (`{"t":"snapshot",…}` then the ring as records then `{"t":"live"}` when the + * server attaches; `{"t":"invalid"}`, `{"t":"stderr","text"}`, + * `{"t":"reply","rid","outcome"}`). Server → keeper: `{"op":"hello","token","protocol"}` + * first, then `>` followed by one Pi RPC command for the session's stdin, or a + * JSON op (`answer`, `settled`, `progressed`, `notes`, `stop`). + */ + + + + + + +export class KeeperLink { + socket ; + handlers ; + early = []; + replies = new Map (); + nextRid = 0; + closed = false; + + constructor(socket ) { + this.socket = socket; + } + + /** Connects to a keeper and receives its state: the snapshot and the ring, then the link is live. */ + static connect(endpoint , token , options ) { + const { promise, resolve, reject } = Promise.withResolvers (); + const socket = connect(endpoint); + const link = new KeeperLink(socket); + let snapshot ; + const ring = []; + let live = false; + const fail = (message ) => { + if (live) return; + live = true; + clearTimeout(timer); + socket.destroy(); + reject(Object.assign(new Error(message), { code: "keeper_unavailable" })); + }; + const timer = setTimeout(() => fail("the session keeper did not answer"), options.timeoutMs); + const decoder = new JsonlDecoder((line) => { + if (live) return link.receive(line); + if (line.startsWith("{")) { + let message ; + try { message = JSON.parse(line) ; } catch { return fail("the session keeper sent a malformed line"); } + if (message.t === "snapshot") { + if (message.protocol !== KEEPER_PROTOCOL) return fail(`the session keeper speaks protocol ${String(message.protocol)}`); + snapshot = message ; + return; + } + if (message.t !== "live" || !snapshot) return fail("the session keeper sent an unexpected line"); + live = true; + clearTimeout(timer); + return resolve({ link, snapshot, ring }); + } + const record = parseRecordLine(line); + if (!record || !snapshot) return fail("the session keeper sent a malformed line"); + ring.push({ ...record, bytes: Buffer.byteLength(record.line) }); + }, () => fail("the session keeper sent an oversize line"), options.maxLineBytes + 64); + socket.setNoDelay(true); + socket.on("connect", () => socket.write(`${JSON.stringify({ op: "hello", token, protocol: KEEPER_PROTOCOL })}\n`)); + socket.on("data", (chunk ) => decoder.push(chunk)); + socket.on("error", (error) => fail(error.message)); + socket.on("close", () => { + fail("the session keeper closed the connection"); + link.onClose(); + }); + return promise; + } + + /** Starts delivering what arrived since the handshake, then everything live. */ + attach(handlers ) { + this.handlers = handlers; + for (const deliver of this.early.splice(0)) deliver(); + } + + dispatch(deliver ) { + if (this.handlers) deliver(); + else this.early.push(deliver); + } + + receive(line ) { + if (!line.startsWith("{")) { + const record = parseRecordLine(line); + if (record) this.dispatch(() => this.handlers .record(record.seq, record.line)); + return; + } + let message ; + try { message = JSON.parse(line) ; } catch { return; } + if (message.t === "reply" && typeof message.rid === "number") { + const reply = this.replies.get(message.rid); + this.replies.delete(message.rid); + reply?.resolve(message.outcome); + return; + } + this.dispatch(() => this.handlers .message(message)); + } + + onClose() { + this.closed = true; + const gone = new SessionError("session_exited", "The session has exited"); + for (const reply of this.replies.values()) reply.reject(gone); + this.replies.clear(); + this.dispatch(() => this.handlers .close()); + } + + get writableLength() { + return this.socket.writableLength; + } + + /** One line to the keeper (a `>` stdin line or a JSON op). */ + send(line ) { + if (!this.closed) this.socket.write(`${line}\n`); + } + + /** A JSON op the keeper answers with a `reply`. */ + request(op ) { + if (this.closed) return Promise.reject(new SessionError("session_exited", "The session has exited")); + this.nextRid += 1; + const rid = this.nextRid; + const { promise, resolve, reject } = Promise.withResolvers (); + this.replies.set(rid, { resolve, reject }); + this.send(JSON.stringify({ ...op, rid })); + return promise; + } + + /** Closes the connection; the keeper and its session keep running. */ + close() { + this.closed = true; + this.socket.destroy(); + } +} + +/** ` ` → its parts. */ +export function parseRecordLine(line ) { + const space = line.indexOf(" "); + const seq = Number(line.slice(0, space)); + return space > 0 && Number.isSafeInteger(seq) && seq > 0 ? { seq, line: line.slice(space + 1) } : undefined; +} + +// --- the session, as the server holds it ----------------------------------------- + + + + +export class SessionError extends Error { + code ; + constructor(code , message ) { + super(message); + this.code = code; + this.name = "SessionError"; + } +} + + + + + + + + + + + + + + + + + + + + + + + + + +/** Notes the server keeps with the keeper (see `SessionSnapshot.notes`). */ + + + + + + + + + +function readNotes(notes ) { + if (!notes || typeof notes !== "object") return undefined; + const n = notes ; + const strings = (value ) => Array.isArray(value) && value.every((v) => typeof v === "string") ? value : undefined; + const providers = strings(n.providers); + const recent = strings(n.recent); + if (!providers || !recent || typeof n.sent !== "string") return undefined; + return { providers, recent, sent: n.sent }; +} + +export class ServeSession { + id ; + cwd ; + startedAt ; + pid ; + + limits ; + now ; + log ; + link ; + rpcWaiters = new Map (); + desktopWaiters = new Map (); + subscribers = new Set (); + exited ; + markExited ; + onStderr ; + onExit ; + /** Request ids are unique per server run: a late response to a previous run's request never matches. */ + epoch = randomBytes(4).toString("hex"); + nextRpc = 0; + nextDesktop = 0; + detached = false; + /** Devices whose last stream closed while they owed host tool results, and the timer that fails those calls. */ + graceTimers = new Map (); + deviceLabel ; + /** When each device last drove this session (an operate request). */ + activity = new Map (); + activitySeq = 0; + /** Devices that registered host tools in this session: only their order matters to the session. */ + hostProviders = new Set (); + /** The connected-providers order last sent with `set_host_activity`, serialized. */ + sentActivity = "[]"; + sentNotes = ""; + + constructor(options ) { + const snapshot = options.snapshot; + this.id = snapshot.id; + this.cwd = snapshot.cwd; + this.startedAt = snapshot.startedAt; + this.pid = snapshot.pid ?? undefined; + this.deviceLabel = options.deviceLabel ?? (() => undefined); + this.limits = { ...SERVE_SESSION_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.onStderr = options.onStderr; + this.onExit = options.onExit; + this.log = new SessionLog(this.limits, this.now); + this.log.restore(snapshot); + for (const record of options.ring ?? []) this.log.ring.push(record); + const notes = readNotes(snapshot.notes); + if (notes) { + for (const provider of notes.providers) this.hostProviders.add(provider); + for (const deviceId of [...notes.recent].reverse()) this.activity.set(deviceId, (this.activitySeq += 1)); + this.sentActivity = notes.sent; + } + this.sentNotes = JSON.stringify(this.notes()); + const exited = Promise.withResolvers (); + this.exited = exited.promise; + this.markExited = exited.resolve; + if (this.log.state === "exited") exited.resolve(); + this.link = options.link; + if (this.link) { + this.link.attach({ + record: (seq, line) => this.onRecord(seq, line), + message: (message) => { + if (message.t === "invalid") this.log.invalidRecords += 1; + else if (message.t === "stderr" && typeof message.text === "string") this.onStderr?.(message.text); + }, + close: () => this.onLinkClosed(), + }); + } else if (this.log.state === "running") { + this.onLinkClosed(); + } + if (options.reattached && this.log.state === "running") { + // Nobody is connected yet: each device gets a while to come back for the calls it owes. + for (const provider of new Set(this.log.pendingHostCalls().map((call) => call.provider))) this.armGrace(provider, this.limits.hostToolReattachGraceMs); + } + } + + get state() { + return this.log.state; + } + + get seq() { + return this.log.seq; + } + + get exitCode() { + return this.log.exitCode; + } + + get exitSignal() { + return this.log.exitSignal; + } + + get exitedAt() { + return this.log.exitedAt; + } + + get invalidRecords() { + return this.log.invalidRecords; + } + + get droppedRecords() { + return this.log.droppedRecords; + } + + get subscriberCount() { + return this.subscribers.size; + } + + pendingDialogs() { + return this.log.pendingDialogs(); + } + + // --- output --- + + onRecord(seq , line ) { + let record ; + try { + record = JSON.parse(line) ; + } catch { + return; + } + const event = this.log.push(seq, line, record); + this.broadcast(seq, line); + switch (event?.kind) { + case "response": { + const waiter = this.rpcWaiters.get(event.id); + if (waiter) { + this.rpcWaiters.delete(event.id); + waiter.resolve(record); + } + return; + } + case "desktop_response": { + const waiter = this.desktopWaiters.get(event.requestId); + if (waiter) { + this.desktopWaiters.delete(event.requestId); + waiter.resolve(event.answer); + } + return; + } + case "host_tool_call": { + // Routed to the device that provides the tool: every subscriber sees the record (clients + // filter by `provider`), and when that device has no open stream the server answers for it + // at once with an error result the model can read, instead of letting the turn hang. + const call = this.log.hostCall(event.callId); + if (call && !this.hasStream(call.provider)) this.failHostCall(call); + return; + } + case "exited": + this.onExited(); + return; + } + } + + /** The keeper went away without the session's exit record: it ended (or was killed) with its session. */ + onLinkClosed() { + if (this.detached || this.log.state === "exited") return; + const line = JSON.stringify({ type: "serve_session_exited", code: null, signal: null, error: "keeper_lost" }); + this.onRecord(this.log.seq + 1, line); + } + + // --- host tools --- + + hasStream(deviceId ) { + for (const sub of this.subscribers) if (sub.deviceId === deviceId && !sub.sink.destroyed) return true; + return false; + } + + /** Answers the call on its device's behalf: the tool's device is not connected. */ + failHostCall(call ) { + if (this.log.hostCall(call.callId) !== call) return; + this.hostCallSettled(call.callId); + const label = this.deviceLabel(call.provider) ?? call.provider; + const text = `${call.tool} runs in ${label}, which isn't connected right now.`; + // A result the device sent meanwhile wins; the session answers this one `already_answered`. + this.desktop("host_tool_result", { callId: call.callId, content: [{ type: "text", text }], isError: true }, this.limits.hostToolAnswerMs).catch(() => {}); + } + + /** A device sent an operate request (a prompt, a steer, a dialog answer, a Desktop write): it becomes the first to run host tool calls. */ + noteActivity(deviceId ) { + this.activitySeq += 1; + this.activity.set(deviceId, this.activitySeq); + this.syncActivity(); + this.saveNotes(); + } + + /** A device registered host tools (`tools` > 0) or withdrew them all. */ + noteHostProvider(deviceId , tools ) { + if (tools > 0) this.hostProviders.add(deviceId); + else this.hostProviders.delete(deviceId); + this.syncActivity(); + this.saveNotes(); + } + + /** The device that most recently drove this session, if any did. */ + lastActiveDevice() { + let last ; + let at = 0; + for (const [deviceId, seq] of this.activity) if (seq > at) [last, at] = [deviceId, seq]; + return last; + } + + notes() { + const recent = [...this.activity].sort((a, b) => b[1] - a[1]).map(([deviceId]) => deviceId); + return { providers: [...this.hostProviders], recent, sent: this.sentActivity }; + } + + /** Hands the keeper what a restarted server must know, when it changed. */ + saveNotes() { + const notes = JSON.stringify(this.notes()); + if (notes === this.sentNotes || this.log.state !== "running") return; + this.sentNotes = notes; + this.link?.send(`{"op":"notes","notes":${notes}}`); + } + + /** + * Tells the session which host tool providers are connected, most recently + * active first (`set_host_activity`), whenever that order changes: a host + * tool several devices provide goes to the first of them. Written to the + * session before any command the same request forwards, so a prompt's tool + * calls see its device. Sessions without host tools never get one. + */ + syncActivity() { + if (this.log.state !== "running" || this.detached) return; + const connected = new Set (); + for (const sub of this.subscribers) if (!sub.sink.destroyed && this.hostProviders.has(sub.deviceId)) connected.add(sub.deviceId); + const providers = [...connected].sort((a, b) => (this.activity.get(b) ?? 0) - (this.activity.get(a) ?? 0)); + const serialized = JSON.stringify(providers); + if (serialized === this.sentActivity) return; + this.sentActivity = serialized; + this.saveNotes(); + this.desktop("set_host_activity", { providers }, this.limits.hostToolAnswerMs).catch(() => {}); + } + + /** After a device's last stream closed: its calls fail unless it reconnects within the grace period (at once when revoked). */ + deviceLeft(deviceId , immediately = false) { + this.syncActivity(); + if (this.log.state !== "running" || this.detached || this.hasStream(deviceId) || this.graceTimers.has(deviceId)) return; + if (immediately) { + for (const call of this.owed(deviceId)) this.failHostCall(call); + return; + } + this.armGrace(deviceId, this.limits.hostToolGraceMs); + } + + owed(deviceId ) { + return this.log.pendingHostCalls().filter((call) => call.provider === deviceId); + } + + armGrace(deviceId , ms ) { + if (this.owed(deviceId).length === 0 || this.graceTimers.has(deviceId)) return; + const timer = setTimeout(() => { + this.graceTimers.delete(deviceId); + if (this.hasStream(deviceId)) return; + for (const call of this.owed(deviceId)) this.failHostCall(call); + }, ms); + timer.unref?.(); + this.graceTimers.set(deviceId, timer); + } + + /** The device that must answer `callId`, if the server saw that call and it is still open. */ + hostCallProvider(callId ) { + return this.log.hostCall(callId)?.provider; + } + + /** A `host_tool_result` reached the session and settled (or could no longer settle) the call. */ + hostCallSettled(callId ) { + if (!this.log.hostCall(callId)) return; + this.log.settle(callId); + this.link?.send(JSON.stringify({ op: "settled", callId })); + } + + /** A `host_tool_progress` reached the session and restarted the call's deadline: keep tracking it as long. */ + hostCallProgressed(callId ) { + if (!this.log.hostCall(callId)) return; + this.log.progress(callId); + this.link?.send(JSON.stringify({ op: "progressed", callId })); + } + + pendingHostCalls() { + return this.log.pendingHostCalls(); + } + + broadcast(seq , line ) { + const frame = sseRecord(seq, line); + for (const sub of this.subscribers) { + if (sub.sink.destroyed) { + this.subscribers.delete(sub); + this.deviceLeft(sub.deviceId); + continue; + } + if (sub.filter && !sub.filter(line)) continue; + if (sub.sink.writableLength > this.limits.clientBufferBytes) { + this.drop(sub, "slow_client"); + continue; + } + sub.sink.write(frame); + } + } + + /** Ends a subscriber's stream with a resync marker; it reconnects with its last seq. */ + drop(sub , reason ) { + if (!this.subscribers.delete(sub)) return; + this.deviceLeft(sub.deviceId); + try { + sub.sink.end(sseEvent("resync", { reason, seq: this.log.seq })); + } catch { + sub.sink.destroy(); + return; + } + // A client that never reads would hold the marker (and its buffer) forever. + const timer = setTimeout(() => sub.sink.destroy(), this.limits.dropFlushMs); + timer.unref?.(); + } + + /** Closes every stream opened by `deviceId` (a revoked device); the host tool calls it owed fail now. */ + dropDevice(deviceId ) { + for (const sub of [...this.subscribers]) { + if (sub.deviceId !== deviceId) continue; + this.subscribers.delete(sub); + sub.sink.destroy(); + } + this.deviceLeft(deviceId, true); + } + + heartbeat() { + for (const sub of this.subscribers) { + if (sub.sink.writableLength > this.limits.clientBufferBytes) this.drop(sub, "slow_client"); + else sub.sink.write(": ping\n\n"); + } + } + + /** + * Attaches an SSE subscriber: a `hello`, then either the records after + * `after` or `snapshot-required`, then every dialog still waiting that the + * replay did not carry, then (to the device that provides them) the host + * tool calls still waiting that the replay did not carry, then the live + * stream. An exited session's stream ends after that. With a `filter`, + * only the records (replayed or live) it keeps are sent, and no dialog or + * host tool call is re-sent. + */ + subscribe(sink , deviceId , after , filter ) { + const ring = this.log.ring; + const hello = { session: this.id, state: this.log.state, seq: this.log.seq, oldest: ring.oldest ?? null }; + sink.write(`retry: 3000\n\n${sseEvent("hello", hello)}`); + let replayedFrom = Number.POSITIVE_INFINITY; + if (after !== undefined) { + const replay = ring.since(after, this.log.seq); + if ("snapshotRequired" in replay) { + sink.write(sseEvent("snapshot-required", { after, oldest: replay.oldest, seq: this.log.seq })); + } else { + replayedFrom = after; + for (const r of replay.records) if (!filter || filter(r.line)) sink.write(sseRecord(r.seq, r.line)); + } + } + for (const dialog of filter ? [] : this.pendingDialogs()) { + if (dialog.seq > replayedFrom) continue; + sink.write(`event: dialog\ndata: ${dialog.line}\n\n`); + } + for (const call of filter ? [] : this.log.pendingHostCalls()) { + if (call.provider !== deviceId || call.seq > replayedFrom) continue; + sink.write(`event: host_tool_call\ndata: ${call.line}\n\n`); + } + if (this.log.state === "exited" || this.detached) { + sink.end(); + return; + } + this.subscribers.add({ sink, deviceId, ...(filter ? { filter } : {}) }); + const grace = this.graceTimers.get(deviceId); + if (grace !== undefined) { + clearTimeout(grace); + this.graceTimers.delete(deviceId); + } + this.syncActivity(); + } + + unsubscribe(sink ) { + for (const sub of this.subscribers) { + if (sub.sink !== sink) continue; + this.subscribers.delete(sub); + this.deviceLeft(sub.deviceId); + } + } + + // --- input --- + + write(record ) { + if (this.log.state !== "running") throw new SessionError("session_exited", "The session has exited"); + const link = this.link; + if (!link || link.closed || this.detached) throw new SessionError("session_exited", "The session's input is closed"); + if (link.writableLength > this.limits.stdinBufferBytes) throw new SessionError("session_busy", "The session is not reading its input; try again later"); + link.send(`>${JSON.stringify(record)}`); + } + + /** + * Sends one Pi RPC command under a server-assigned id (clients may share a + * session, so their own ids could collide) and waits for its response. The + * caller's `id` is put back on the response it gets. + */ + async rpc(command , timeoutMs ) { + this.nextRpc += 1; + const id = `serve-rpc-${this.epoch}-${this.nextRpc}`; + const response = this.waitFor(this.rpcWaiters, id, timeoutMs); + try { + this.write({ ...command, id }); + } catch (error) { + this.cancelWait(this.rpcWaiters, id); + throw error; + } + const record = await response; + if (record === undefined) return { timeout: true, id }; + const { id: _server, ...rest } = record; + return { response: command.id === undefined ? rest : { ...rest, id: command.id } }; + } + + /** Forwards an `extension_ui_response`; only the first answer to a dialog reaches Pi (the keeper decides). */ + async answerDialog(answer ) { + const id = answer.id; + if (typeof id !== "string") return "unknown"; + const status = this.log.dialogStatus(id); + if (status !== "pending") return status; + if (this.log.state !== "running" || !this.link || this.detached) throw new SessionError("session_exited", "The session has exited"); + const outcome = await this.link.request({ op: "answer", answer }); + return outcome === "accepted" || outcome === "answered" ? outcome : "unknown"; + } + + /** + * One Desktop RPC request through `/gentle:desktop`, answered by the matching + * `gentle-desktop-rpc` widget. Returns the Desktop RPC response object, or + * undefined on timeout. A refused prompt is reported as its Pi response. + */ + async desktop(method , params , timeoutMs ) { + this.nextDesktop += 1; + const requestId = `serve-desktop-${this.epoch}-${this.nextDesktop}`; + const message = `/gentle:desktop ${JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId, method, params })}`; + const answer = this.waitFor(this.desktopWaiters, requestId, timeoutMs); + // The session can exit while the prompt is in flight: that rejection is rethrown below, never unhandled. + answer.catch(() => {}); + let prompt ; + try { + prompt = await this.rpc({ type: "prompt", message }, timeoutMs); + } catch (error) { + this.cancelWait(this.desktopWaiters, requestId); + throw error; + } + if ("response" in prompt && prompt.response.success !== true) { + this.cancelWait(this.desktopWaiters, requestId); + return { prompt: prompt.response }; + } + const result = await answer; + return result === undefined ? undefined : { answer: result }; + } + + waitFor(waiters , id , timeoutMs ) { + const { promise, resolve, reject } = Promise.withResolvers (); + const timer = setTimeout(() => { + waiters.delete(id); + resolve(undefined); + }, timeoutMs); + timer.unref?.(); + waiters.set(id, { + resolve: (record) => { clearTimeout(timer); resolve(record); }, + reject: (error) => { clearTimeout(timer); reject(error); }, + }); + return promise; + } + + cancelWait(waiters , id ) { + waiters.get(id)?.resolve(undefined); + waiters.delete(id); + } + + // --- lifecycle --- + + failWaiters(error ) { + for (const waiters of [this.rpcWaiters, this.desktopWaiters]) { + for (const waiter of waiters.values()) waiter.reject(error); + waiters.clear(); + } + } + + onExited() { + for (const timer of this.graceTimers.values()) clearTimeout(timer); + this.graceTimers.clear(); + this.failWaiters(new SessionError("session_exited", "The session has exited")); + for (const sub of this.subscribers) sub.sink.end(); + this.subscribers.clear(); + this.onExit?.(this); + this.markExited(); + } + + /** + * Orderly stop: the keeper closes the session's stdin and sends SIGTERM + * together (Pi treats them as one request), then SIGKILL, and ends. + */ + async stop() { + if (this.log.state === "exited") return; + if (!this.link || this.link.closed) return this.exited; + this.link.send(JSON.stringify({ op: "stop" })); + // A keeper that never reports the exit is given up on: the link closes and the session counts as lost. + const timer = setTimeout(() => this.link .close(), this.limits.stopGraceMs + 5000); + timer.unref?.(); + await this.exited; + clearTimeout(timer); + } + + /** + * Lets go of the session without stopping it (the server is stopping and a + * later one reattaches): streams end (clients reconnect to the next server + * with their last seq), waiting requests fail, the keeper keeps running. + */ + detach() { + if (this.detached) return; + this.detached = true; + for (const timer of this.graceTimers.values()) clearTimeout(timer); + this.graceTimers.clear(); + this.failWaiters(new SessionError("shutting_down", "The server is stopping")); + for (const sub of this.subscribers) sub.sink.end(); + this.subscribers.clear(); + this.link?.close(); + } + + whenExited() { + return this.exited; + } +} diff --git a/runtime/serve-share.mjs b/runtime/serve-share.mjs new file mode 100644 index 000000000..1a2761db9 --- /dev/null +++ b/runtime/serve-share.mjs @@ -0,0 +1,323 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `gentle-shell serve share`: the connection code a desktop client pastes when +// LAN discovery cannot find this server, the addresses that +// code advertises, the firewall hint, and the login autostart (a systemd user +// unit or a macOS LaunchAgent) that keeps the network server running. + +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, openSync, closeSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { homedir, hostname, networkInterfaces, } from "node:os"; +import { delimiter, dirname, isAbsolute, join } from "node:path"; + +export const CONNECTION_CODE_PREFIX = "gsc1."; +export const SHARE_DEFAULT_PORT = 8787; +/** Ports tried after the requested one when it is taken. */ +export const SHARE_PORT_ATTEMPTS = 10; +const MAX_ADDRESSES = 8; + +// One DNS name (no port, no trailing dot) a client may put in the Host header. +export const HOST_NAME = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; + +// --- connection code --------------------------------------------------------------- + + + + + + + + + + + + + + + + + +/** `gsc1.` + base64url (no padding) of `{"v":1,"id","n","p","a","c"[,"fp"][,"r"]}`. A secret while its pairing code is valid. */ +export function encodeConnectionCode(code ) { + const json = JSON.stringify({ v: 1, id: code.id, n: code.n, p: code.p, a: code.a, c: code.c, ...(code.fp === undefined ? {} : { fp: code.fp }), ...(code.r === undefined ? {} : { r: code.r }) }); + return `${CONNECTION_CODE_PREFIX}${Buffer.from(json, "utf8").toString("base64url")}`; +} + +// --- addresses --------------------------------------------------------------------- + +// Container, VM and bridge interfaces: reachable from this machine only, so last. +const VIRTUAL_INTERFACE = /^(?:docker|br-|veth|virbr|vmnet|vboxnet|cni|flannel|podman|lxcbr|lxdbr|bridge)/i; + +function privateIPv4(address ) { + const [a, b] = address.split(".").map(Number); + return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168); +} + +/** This machine's own names a client may use: the hostname and `.local` (the names a `0.0.0.0` bind admits). */ +export function ownHostNames(name ) { + const own = name.toLowerCase(); + if (!HOST_NAME.test(own)) return []; + return own.endsWith(".local") ? [own] : [own, `${own}.local`]; +} + +/** + * The addresses a connection code advertises: this machine's IPv4 addresses + * other than loopback and link-local (private LAN ranges first, then others such + * as a tailnet's, then container and VM bridges), then its own names as + * fallbacks. At most 8; the names always keep their places. + */ +export function shareAddresses(interfaces , name ) { + const names = ownHostNames(name); + const ranked = []; + for (const [iface, infos] of Object.entries(interfaces)) { + for (const info of infos ?? []) { + // Node < 18.4 reported the family as a number. + if ((info.family ) !== "IPv4" && (info.family ) !== 4) continue; + const address = info.address; + if (info.internal || address.startsWith("127.") || address.startsWith("169.254.") || address === "0.0.0.0") continue; + if (ranked.some((r) => r.address === address)) continue; + ranked.push({ address, rank: VIRTUAL_INTERFACE.test(iface) ? 2 : privateIPv4(address) ? 0 : 1 }); + } + } + const addresses = ranked.sort((x, y) => x.rank - y.rank).map((r) => r.address); + return [...addresses.slice(0, Math.max(0, MAX_ADDRESSES - names.length)), ...names]; +} + +// --- firewall ---------------------------------------------------------------------- + +/** Whether `command` is on PATH (plus the sbin folders a user PATH may lack). */ +export function commandExists(command , env ) { + const dirs = [...(env.PATH ?? "").split(delimiter), "/usr/sbin", "/sbin", "/usr/local/sbin"]; + return dirs.some((dir) => dir !== "" && isAbsolute(dir) && existsSync(join(dir, command))); +} + +/** Inclusive listen ports for forwarded pages. */ + + + + + +/** The ports `share` gives forwarded pages, so one firewall rule covers them all. */ +export const SHARE_FORWARD_PORTS = { from: 8800, to: 8899 }; + +/** + * The command that opens `port` in the local firewall for TCP (HTTP) and UDP (LAN discovery), plus the + * forwarded pages' TCP range when the server has one, on Linux with ufw or firewalld; never run for the user. + */ +export function firewallHint(platform , port , has , forwardPorts ) { + if (platform !== "linux") return undefined; + if (has("ufw")) return `sudo ufw allow ${port}${forwardPorts ? ` && sudo ufw allow ${forwardPorts.from}:${forwardPorts.to}/tcp` : ""}`; + if (has("firewall-cmd")) return `sudo firewall-cmd --permanent --add-port=${port}/tcp --add-port=${port}/udp${forwardPorts ? ` --add-port=${forwardPorts.from}-${forwardPorts.to}/tcp` : ""} && sudo firewall-cmd --reload`; + return undefined; +} + +// --- autostart --------------------------------------------------------------------- + +export const AUTOSTART_UNIT = "gentle-shell-serve.service"; +export const AUTOSTART_LABEL = "com.gentle-shell.serve"; +/** Environment an autostarted server keeps from the invocation that installed it. */ +const AUTOSTART_ENV = ["PATH", "GENTLE_SHELL_NO_AUTO_SETUP", "GENTLE_SHELL_HOME", "GENTLE_SHELL_CONFIG", "GENTLE_PI_CONFIG_HOME", "GENTLE_SHELL_PI", "PI_CODING_AGENT_DIR"]; + + + + + + + + + +/** The same launcher, home flags and kept environment as this invocation, serving the network in the foreground. */ +export function autostartCommand(input ) { + const env = {}; + for (const key of AUTOSTART_ENV) { + const value = input.env[key]; + if (value !== undefined && value !== "" && !/[\r\n]/.test(value)) env[key] = value; + } + return { + command: input.nodePath, + args: [input.launcher, ...input.homeFlags, "serve", "--foreground", "--listen", `0.0.0.0:${input.port}`, ...input.allowHosts.flatMap((name) => ["--allow-host", name]), + ...(input.forwardPorts ? ["--forward-ports", `${input.forwardPorts.from}-${input.forwardPorts.to}`] : []), + ...(input.noTls ? ["--no-tls"] : []), ...(input.relay === undefined ? [] : ["--relay", input.relay])], + env, + logFile: input.logFile, + }; +} + +// systemd unit quoting: `%` is a specifier and `$` a variable in ExecStart. +function systemdArg(value ) { + if (value !== "" && !/[\s"'\\%$;]/.test(value)) return value; + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`; +} + +export function systemdUnit(spec ) { + const env = Object.entries(spec.env).map(([key, value]) => `Environment="${key}=${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`); + return [ + "# Written by 'gentle-shell serve share --always'; remove with 'gentle-shell serve share --off'.", + "[Unit]", + "Description=Gentle Shell server for the local network", + // Gives up after 5 failed starts in a minute (for example another server already holds this home). + "StartLimitIntervalSec=60", + "StartLimitBurst=5", + "", + "[Service]", + "Type=simple", + ...env, + `ExecStart=${[spec.command, ...spec.args].map(systemdArg).join(" ")}`, + "Restart=on-failure", + "RestartSec=5", + "TimeoutStopSec=30", + // Stopping or restarting the server (an upgrade exits for a restart) ends only the server: + // session keepers and the terminal host it started live on, and the next server reattaches them. + "KillMode=process", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); +} + +function xml(value ) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} + +export function launchAgentPlist(spec ) { + return [ + '', + '', + "", + '', + "", + "\tLabel", + `\t${AUTOSTART_LABEL}`, + "\tProgramArguments", + "\t", + ...[spec.command, ...spec.args].map((arg) => `\t\t${xml(arg)}`), + "\t", + "\tEnvironmentVariables", + "\t", + ...Object.entries(spec.env).flatMap(([key, value]) => [`\t\t${xml(key)}`, `\t\t${xml(value)}`]), + "\t", + "\tRunAtLoad", + "\t", + // Restarted after a crash, not after `serve stop`. + "\tKeepAlive", + "\t", + "\t\tSuccessfulExit", + "\t\t", + "\t", + "\tStandardOutPath", + `\t${xml(spec.logFile)}`, + "\tStandardErrorPath", + `\t${xml(spec.logFile)}`, + "", + "", + "", + ].join("\n"); +} + +/** Runs a command to completion; ENOENT is status 127. */ + + +export function commandRunner(env ) { + return (command, args) => { + const { promise, resolve } = Promise.withResolvers (); + let output = ""; + const child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + child.stdout.on("data", (d) => { output += d; }); + child.stderr.on("data", (d) => { output += d; }); + child.once("error", (error) => resolve({ status: (error ).code === "ENOENT" ? 127 : 1, output: `${output}${error.message}` })); + child.once("close", (code) => resolve({ status: code ?? 1, output })); + return promise; + }; +} + +/** Machine facts and the command runner `serve share` uses; tests replace them. */ + + + + + + + + + + + + + +export function defaultShareSystem(env ) { + const userHome = homedir(); + return { + platform: process.platform, + hostname, + networkInterfaces, + userHome, + ...(env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME) ? { configHome: env.XDG_CONFIG_HOME } : {}), + uid: process.getuid?.() ?? 0, + user: env.USER ?? env.LOGNAME ?? "$USER", + run: commandRunner(env), + has: (command) => commandExists(command, env), + }; +} + +/** Where autostart lives on this platform, or undefined where it is not supported (Windows). */ +export function autostartFile(system ) { + if (system.platform === "linux") return join(system.configHome ?? join(system.userHome, ".config"), "systemd", "user", AUTOSTART_UNIT); + if (system.platform === "darwin") return join(system.userHome, "Library", "LaunchAgents", `${AUTOSTART_LABEL}.plist`); + return undefined; +} + +export function autostartContent(system , spec ) { + return system.platform === "darwin" ? launchAgentPlist(spec) : systemdUnit(spec); +} + +/** Whether the installed autostart is exactly this one. */ +export function autostartInstalled(system , spec ) { + const file = autostartFile(system); + try { + return file !== undefined && readFileSync(file, "utf8") === autostartContent(system, spec); + } catch { + return false; + } +} + +/** Writes the unit or agent and starts it now through the service manager. An error removes what was written. */ +export async function installAutostart(system , spec ) { + const file = autostartFile(system); + if (!file) return { error: `autostart is not supported on ${system.platform} yet` }; + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, autostartContent(system, spec), { mode: 0o644 }); + const steps = system.platform === "darwin" + ? [["launchctl", ["bootstrap", `gui/${system.uid}`, file]]] + : [["systemctl", ["--user", "daemon-reload"]], ["systemctl", ["--user", "enable", "--now", AUTOSTART_UNIT]]]; + if (system.platform === "darwin") { + // launchd opens the log before the server runs: create it owner-only first. + mkdirSync(dirname(spec.logFile), { recursive: true, mode: 0o700 }); + closeSync(openSync(spec.logFile, "a", 0o600)); + // A previous version of the agent may still be loaded. + await system.run("launchctl", ["bootout", `gui/${system.uid}/${AUTOSTART_LABEL}`]); + } + for (const [command, args] of steps) { + const result = await system.run(command, args); + if (result.status !== 0) { + rmSync(file, { force: true }); + if (system.platform !== "darwin") await system.run("systemctl", ["--user", "daemon-reload"]); + return { error: `${command} ${args.join(" ")} failed (${result.status})${result.output.trim() ? `: ${result.output.trim()}` : ""}` }; + } + } + return { file }; +} + +/** Stops the autostarted server and removes the unit or agent. */ +export async function removeAutostart(system ) { + const file = autostartFile(system); + if (!file || !existsSync(file)) return { file: file ?? "", removed: false }; + if (system.platform === "darwin") { + await system.run("launchctl", ["bootout", `gui/${system.uid}/${AUTOSTART_LABEL}`]); + rmSync(file, { force: true }); + } else { + await system.run("systemctl", ["--user", "disable", "--now", AUTOSTART_UNIT]); + rmSync(file, { force: true }); + await system.run("systemctl", ["--user", "daemon-reload"]); + } + return { file, removed: true }; +} diff --git a/runtime/serve-terminals.mjs b/runtime/serve-terminals.mjs new file mode 100644 index 000000000..821395210 --- /dev/null +++ b/runtime/serve-terminals.mjs @@ -0,0 +1,627 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// Persistent terminals for `gentle-shell serve`, over a native terminal host +// (`gentle-term-host`): the host owns the PTYs and keeps them alive while no +// client is connected (and across serve restarts); serve starts it on first +// use, talks to it in JSON Lines over its owner-only Unix socket (on Windows, +// loopback TCP with a token from an owner-only file), and exposes the +// terminals to paired devices over HTTP + SSE. One host connection is the +// control connection; every SSE stream gets its own, so each stream has its +// own attachment and backpressure. + +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { accessSync, closeSync, constants as fsConstants, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { chmod, mkdir, readdir, rename, rm } from "node:fs/promises"; + +import { connect, } from "node:net"; +import { delimiter, join } from "node:path"; +import { StringDecoder } from "node:string_decoder"; +import { hasScope, } from "./serve-auth.mjs"; +import { fsHttpError, HttpError, need, ownsOrAdmin, readJsonBody, realDirectory, receiveBodyToFile, sendJson, sseEvent, startSse } from "./serve-http.mjs"; + +export const TERM_HOST_PROTOCOL = 1; +export const TERM_HOST_BINARY = process.platform === "win32" ? "gentle-term-host.exe" : "gentle-term-host"; +/** Where a host started with `--tcp` writes `{ port, token, pid }`, in its state folder. */ +export const TERM_HOST_TCP_FILE = "term-host.json"; +const OWNERS_SCHEMA = "gentle-shell.serve.terminals/v1"; + +/** How serve reaches the host: its Unix socket, or loopback TCP with the token the host wrote. */ + + + +/** TCP on Windows (no Unix sockets for the host there); `GENTLE_TERM_HOST_TRANSPORT=tcp` picks it anywhere. */ +export function termHostTransport(env , platform = process.platform) { + return platform === "win32" || env.GENTLE_TERM_HOST_TRANSPORT === "tcp" ? "tcp" : "unix"; +} + +const ASSET_OS = { linux: "linux", darwin: "macos", win32: "windows" }; +const ASSET_ARCHS = { linux: ["x64", "arm64"], darwin: ["x64", "arm64"], win32: ["x64"] }; + +/** The Gentle Shell GPUI release asset with the host for this system, `gentle-term-host--[.exe]`; null when none is built for it. */ +export function termHostAsset(platform = process.platform, arch = process.arch) { + const os = ASSET_OS[platform]; + if (!os || !ASSET_ARCHS[platform]?.includes(arch)) return null; + return `gentle-term-host-${os}-${arch}${platform === "win32" ? ".exe" : ""}`; +} + +export const SERVE_TERM_LIMITS = { + /** One request to the host. */ + requestTimeoutMs: 10_000, + /** A freshly started host opening its socket. */ + startTimeoutMs: 5_000, + /** `input` bodies (base64 in JSON). */ + inputBodyBytes: 4 * 1024 * 1024, + /** A host binary sent with `PUT /api/term-host`. */ + installBytes: 64 * 1024 * 1024, + /** Unsent bytes of one stream; past it the stream ends with `overflow`. */ + streamQueueBytes: 8 * 1024 * 1024, + maxCols: 1000, + maxRows: 500, + smallBodyBytes: 64 * 1024, +}; + +/** An error answer from the host: `{ ok: false, error: { code, message } }`. */ +export class TermHostError extends Error { + code ; + constructor(code , message ) { + super(message); + this.code = code; + } +} + +function hostHttpError(error ) { + if (!(error instanceof TermHostError)) return error; + switch (error.code) { + case "not_found": return new HttpError(404, "not_found", "No such terminal"); + case "bad_request": return new HttpError(400, "invalid_request", error.message); + case "exited": + case "alive": return new HttpError(409, `terminal_${error.code}`, error.message); + case "spawn_failed": return new HttpError(502, "term_spawn_failed", error.message); + default: return new HttpError(502, "term_host_error", `${error.code}: ${error.message}`); + } +} + + + +/** One connection to the host: requests with ids and their replies, plus unsolicited events. */ +export class HostConnection { + socket ; + decoder = new StringDecoder("utf8"); + buffered = ""; + nextId = 1; + pending = new Map (); + eventListeners = []; + closeListeners = []; + closed = false; + + constructor(socket ) { + this.socket = socket; + socket.setNoDelay(true); + socket.on("data", (chunk ) => this.receive(this.decoder.write(chunk))); + socket.on("error", () => { /* close follows */ }); + socket.on("close", () => { + this.closed = true; + for (const [id, entry] of this.pending) { + clearTimeout(entry.timer); + entry.reject(new HttpError(502, "term_host_gone", "The terminal host closed the connection")); + this.pending.delete(id); + } + for (const listener of this.closeListeners) listener(); + }); + } + + /** Connects, and over TCP authenticates first (`{ op: "auth", token }`); rejects when the host refuses the token. */ + static open(endpoint , timeoutMs ) { + const { promise, resolve, reject } = Promise.withResolvers (); + const socket = "path" in endpoint ? connect(endpoint.path) : connect({ host: "127.0.0.1", port: endpoint.port }); + const timer = setTimeout(() => { socket.destroy(); reject(Object.assign(new Error("connect timeout"), { code: "ETIMEDOUT" })); }, timeoutMs); + socket.once("error", (error) => { clearTimeout(timer); reject(error); }); + socket.once("connect", () => { + clearTimeout(timer); + const conn = new HostConnection(socket); + if ("path" in endpoint) return resolve(conn); + conn.request("auth", { token: endpoint.token }, timeoutMs).then(() => resolve(conn), (error ) => { + conn.close(); + reject(error); + }); + }); + return promise; + } + + receive(text ) { + this.buffered += text; + let newline = this.buffered.indexOf("\n"); + while (newline !== -1) { + const line = this.buffered.slice(0, newline).replace(/\r$/, ""); + this.buffered = this.buffered.slice(newline + 1); + newline = this.buffered.indexOf("\n"); + if (line.trim() === "") continue; + let message ; + try { message = JSON.parse(line); } catch { continue; } + if (!message || typeof message !== "object" || Array.isArray(message)) continue; + const record = message ; + if (typeof record.ev === "string") { + for (const listener of this.eventListeners) listener(record); + continue; + } + const entry = typeof record.id === "number" ? this.pending.get(record.id) : undefined; + if (!entry) continue; + this.pending.delete(record.id ); + clearTimeout(entry.timer); + if (record.ok === true) entry.resolve(record); + else { + const error = record.error && typeof record.error === "object" ? record.error : {}; + entry.reject(new TermHostError(typeof error.code === "string" ? error.code : "error", typeof error.message === "string" ? error.message : "The terminal host refused the request")); + } + } + } + + request(op , params , timeoutMs ) { + if (this.closed) return Promise.reject(new HttpError(502, "term_host_gone", "The terminal host closed the connection")); + const { promise, resolve, reject } = Promise.withResolvers (); + const id = this.nextId++; + const timer = setTimeout(() => { + this.pending.delete(id); + reject(new HttpError(504, "term_host_timeout", `The terminal host did not answer ${op} in time`)); + }, timeoutMs); + this.pending.set(id, { resolve, reject, timer }); + this.socket.write(`${JSON.stringify({ ...params, id, op })}\n`); + return promise; + } + + onEvent(listener ) { + this.eventListeners.push(listener); + } + + onClose(listener ) { + this.closeListeners.push(listener); + } + + close() { + this.socket.destroy(); + } +} + +/** Whether `path` is a file this process may execute. */ +function executable(path ) { + try { + if (!statSync(path).isFile()) return false; + accessSync(path, process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK); + return true; + } catch { + return false; + } +} + + + + + + + + + + + + + + + + +export class TerminalService { + serveDir ; + env ; + limits ; + log ; + transport ; + socketPath ; + stateDir ; + /** Where a TCP host writes its port and token. */ + tcpFile ; + ownersFile ; + /** Which device opened each terminal; kept on disk because terminals outlive this process. */ + owners ; + control ; + hello ; + connecting ; + streams = new Set (); + closed = false; + + constructor(options ) { + this.serveDir = options.serveDir; + this.env = options.env; + this.limits = { ...SERVE_TERM_LIMITS, ...options.limits }; + this.log = options.log ?? (() => {}); + this.transport = termHostTransport(this.env); + this.socketPath = join(this.serveDir, "term.sock"); + this.stateDir = join(this.serveDir, "term"); + this.tcpFile = join(this.stateDir, TERM_HOST_TCP_FILE); + this.ownersFile = join(this.serveDir, "terminals.json"); + this.owners = this.readOwners(); + } + + /** Where the installed binary goes. */ + installPath() { + return join(this.serveDir, "bin", TERM_HOST_BINARY); + } + + /** The host binary: `$GENTLE_TERM_HOST`, else the installed one, else the first on `PATH`; undefined when there is none. */ + binary() { + const configured = this.env.GENTLE_TERM_HOST; + if (configured) return executable(configured) ? configured : undefined; + if (executable(this.installPath())) return this.installPath(); + for (const dir of (this.env.PATH ?? "").split(delimiter)) { + if (dir && executable(join(dir, TERM_HOST_BINARY))) return join(dir, TERM_HOST_BINARY); + } + return undefined; + } + + /** Where the host is reached: its socket, or the port and token it wrote (undefined before it has). */ + endpoint() { + if (this.transport === "unix") return { path: this.socketPath }; + try { + const parsed = JSON.parse(readFileSync(this.tcpFile, "utf8")) ; + const port = parsed.port; + if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535 || typeof parsed.token !== "string" || parsed.token === "") return undefined; + return { port, token: parsed.token }; + } catch { + return undefined; + } + } + + /** Whether a host may be running: its socket or its port file is there. */ + hostMayRun() { + return existsSync(this.transport === "unix" ? this.socketPath : this.tcpFile); + } + + readOwners() { + try { + const parsed = JSON.parse(readFileSync(this.ownersFile, "utf8")) ; + if (parsed.schema !== OWNERS_SCHEMA || !parsed.owners || typeof parsed.owners !== "object") return {}; + return Object.fromEntries(Object.entries(parsed.owners).filter((e) => typeof e[1] === "string")); + } catch { + return {}; + } + } + + saveOwners() { + mkdirSync(this.serveDir, { recursive: true, mode: 0o700 }); + const temp = `${this.ownersFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + writeFileSync(temp, `${JSON.stringify({ schema: OWNERS_SCHEMA, owners: this.owners }, null, "\t")}\n`, { mode: 0o600 }); + renameSync(temp, this.ownersFile); + } + + /** The control connection, starting the host when nothing answers on the socket (or port). */ + ensureHost() { + if (this.closed) return Promise.reject(new HttpError(503, "shutting_down", "The server is stopping")); + if (this.control && !this.control.closed) return Promise.resolve(this.control); + this.connecting ??= this.connectOrStart().finally(() => { this.connecting = undefined; }); + return this.connecting; + } + + async connectOrStart() { + let stale = false; + const endpoint = this.endpoint(); + let conn = endpoint && await HostConnection.open(endpoint, this.limits.requestTimeoutMs).catch((error ) => { + stale = error.code === "ECONNREFUSED" || error instanceof TermHostError; + return undefined; + }); + if (!conn) { + const bin = this.binary(); + if (!bin) throw new HttpError(501, "term_host_missing", `No terminal host on the server: install ${TERM_HOST_BINARY} (PUT /api/term-host) or set GENTLE_TERM_HOST`); + // A socket nothing listens on, or a port file whose host is gone (or refuses its token), is left from a host that died. + if (stale) rmSync(this.transport === "unix" ? this.socketPath : this.tcpFile, { force: true }); + conn = await this.start(bin); + } + const hello = await conn.request("hello", {}, this.limits.requestTimeoutMs); + if (hello.protocol !== TERM_HOST_PROTOCOL) { + conn.close(); + throw new HttpError(502, "term_host_protocol", `The terminal host speaks protocol ${String(hello.protocol)}, not ${TERM_HOST_PROTOCOL}`); + } + this.hello = hello; + this.control = conn; + conn.onClose(() => { + if (this.control === conn) { + this.control = undefined; + this.hello = undefined; + } + }); + return conn; + } + + /** Starts the host detached (it outlives this server) and waits for its socket (or port file). */ + async start(bin ) { + mkdirSync(this.serveDir, { recursive: true, mode: 0o700 }); + mkdirSync(this.stateDir, { recursive: true, mode: 0o700 }); + // The host keeps its own log in the state folder; this catches what it prints before it opens it. + const logPath = join(this.stateDir, "term-host.log"); + const logFd = openSync(logPath, "a", 0o600); + const listen = this.transport === "unix" ? ["--socket", this.socketPath] : ["--tcp"]; + const child = spawn(bin, [...listen, "--state-dir", this.stateDir], { detached: true, stdio: ["ignore", logFd, logFd], env: this.env, windowsHide: true }); + closeSync(logFd); + let failure ; + child.once("error", (error) => { failure = error; }); + child.unref(); + this.log(`terminal host started: ${bin} (pid ${child.pid ?? "?"})`); + const deadline = Date.now() + this.limits.startTimeoutMs; + while (Date.now() < deadline) { + if (failure || child.exitCode !== null || child.signalCode !== null) break; + const endpoint = this.endpoint(); + const conn = endpoint && await HostConnection.open(endpoint, 1000).catch(() => undefined); + if (conn) return conn; + await new Promise((r) => setTimeout(r, 50)); + } + let tail = ""; + try { tail = readFileSync(logPath, "utf8").slice(-1000).trim(); } catch { /* no log */ } + throw new HttpError(503, "term_host_failed", `The terminal host did not start${failure ? `: ${failure.message}` : ""}${tail ? `\n${tail}` : ""}`); + } + + async call(op , params = {}) { + const conn = await this.ensureHost(); + try { + return await conn.request(op, params, this.limits.requestTimeoutMs); + } catch (error) { + throw hostHttpError(error); + } + } + + /** `/api/term-host` and `/api/terminals/*`; false for any other path. */ + async route(req , res , method , path , url , principal ) { + if (path === "/api/term-host") { + if (method === "PUT") await this.install(req, res, need(principal, "admin")); + else if (method === "GET") await this.status(res, need(principal, "terminal")); + else throw new HttpError(405, "method_not_allowed", "Use GET or PUT"); + return true; + } + if (path === "/api/terminals") { + if (method === "GET") await this.list(res, need(principal, "terminal")); + else if (method === "POST") await this.open(req, res, need(principal, "terminal")); + else throw new HttpError(405, "method_not_allowed", "Use GET or POST"); + return true; + } + const one = /^\/api\/terminals\/(t_[A-Za-z0-9]{1,64})(?:\/(input|resize|stream))?$/.exec(path); + if (!one) return false; + const who = need(principal, "terminal"); + const term = one[1]; + if (!ownsOrAdmin(who, this.owners[term] ?? "")) throw new HttpError(404, "not_found", "No such terminal"); + const expect = (wanted ) => { if (method !== wanted) throw new HttpError(405, "method_not_allowed", `Use ${wanted}`); }; + switch (one[2]) { + case undefined: expect("DELETE"); await this.remove(res, term); break; + case "input": expect("POST"); await this.input(req, res, term); break; + case "resize": expect("POST"); await this.resize(req, res, term); break; + default: expect("GET"); await this.stream(req, res, url, term, who); break; + } + return true; + } + + view(entry ) { + const term = String(entry.term); + return { + id: term, + pid: entry.pid, + cwd: entry.cwd, + argv: entry.argv, + cols: entry.cols, + rows: entry.rows, + title: entry.title ?? "", + alive: entry.alive, + ...(entry.exitCode === undefined || entry.exitCode === null ? {} : { exitCode: entry.exitCode }), + createdAt: entry.createdAt, + offset: entry.offset, + owner: this.owners[term] ?? null, + }; + } + + /** Every terminal the host has, with owners no longer on the host forgotten. */ + async hostTerms() { + const listed = await this.call("list"); + const terms = Array.isArray(listed.terms) ? listed.terms.filter((t) => !!t && typeof t === "object" && typeof (t ).term === "string") : []; + const known = new Set(terms.map((t) => String(t.term))); + const stale = Object.keys(this.owners).filter((term) => !known.has(term)); + if (stale.length > 0) { + for (const term of stale) delete this.owners[term]; + this.saveOwners(); + } + return terms; + } + + async list(res , who ) { + const terms = await this.hostTerms(); + sendJson(res, 200, { terminals: terms.filter((t) => ownsOrAdmin(who, this.owners[String(t.term)] ?? "")).map((t) => this.view(t)) }); + } + + async open(req , res , who ) { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + const cwd = realDirectory(body.cwd); + const cols = size(body.cols, "cols", this.limits.maxCols); + const rows = size(body.rows, "rows", this.limits.maxRows); + const params = { cwd, cols, rows }; + if (body.argv !== undefined) { + if (!Array.isArray(body.argv) || body.argv.length === 0 || body.argv.length > 256 || !body.argv.every((a) => typeof a === "string" && !a.includes("\0") && a.length <= 32_768)) { + throw new HttpError(400, "invalid_argv", "argv must be 1-256 strings without NUL"); + } + params.argv = body.argv; + } + if (body.env !== undefined) { + if (!body.env || typeof body.env !== "object" || Array.isArray(body.env)) throw new HttpError(400, "invalid_env", "env must be an object of strings"); + const entries = Object.entries(body.env); + if (entries.length > 128 || !entries.every(([k, v]) => /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(k) && typeof v === "string" && !v.includes("\0") && v.length <= 32_768)) { + throw new HttpError(400, "invalid_env", "env must map at most 128 variable names to strings"); + } + params.env = body.env; + } + const opened = await this.call("open", params); + const term = String(opened.term); + this.owners[term] = who.deviceId; + this.saveOwners(); + this.log(`terminal ${term} opened for ${who.deviceId} in ${cwd}`); + const entry = (await this.hostTerms()).find((t) => t.term === term) ?? { term, pid: opened.pid, cwd, argv: params.argv ?? null, cols, rows, alive: true, offset: 0 }; + sendJson(res, 201, { terminal: this.view(entry) }); + } + + async input(req , res , term ) { + const body = await readJsonBody(req, this.limits.inputBodyBytes); + if (typeof body.data !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(body.data)) throw new HttpError(400, "invalid_data", "data must be base64"); + await this.call("write", { term, data: body.data }); + sendJson(res, 200, { ok: true }); + } + + async resize(req , res , term ) { + const body = await readJsonBody(req, this.limits.smallBodyBytes); + await this.call("resize", { term, cols: size(body.cols, "cols", this.limits.maxCols), rows: size(body.rows, "rows", this.limits.maxRows) }); + sendJson(res, 200, { ok: true }); + } + + /** Closes a running terminal (SIGHUP, then a kill of its process group after 3 s) or forgets an exited one. */ + async remove(res , term ) { + await this.closeTerm(term); + sendJson(res, 200, { closed: term }); + } + + async closeTerm(term ) { + const entry = (await this.hostTerms()).find((t) => t.term === term); + if (entry) { + await this.call(entry.alive === true ? "close" : "forget", { term }).catch((error ) => { + if (!(error instanceof HttpError && error.status === 404)) throw error; + }); + } + delete this.owners[term]; + this.saveOwners(); + } + + async stream(req , res , url , term , who ) { + const raw = url.searchParams.get("from") ?? (typeof req.headers["last-event-id"] === "string" ? req.headers["last-event-id"] : null); + let from ; + if (raw !== null && raw !== "") { + if (!/^\d{1,15}$/.test(raw)) throw new HttpError(400, "invalid_from", "from must be a byte offset"); + from = Number(raw); + } + await this.ensureHost(); + const endpoint = this.endpoint(); + const conn = endpoint && await HostConnection.open(endpoint, this.limits.requestTimeoutMs).catch(() => undefined); + if (!conn) throw new HttpError(502, "term_host_gone", "The terminal host is not answering"); + const entry = { deviceId: who.deviceId, res, conn }; + // Events that arrive before the attach reply wait for it, so `attached` always comes first. + const early = []; + let attached = false; + const forward = (event ) => { + if (event.term !== term || res.writableEnded) return; + if (!attached) return void early.push(event); + if (res.writableLength > this.limits.streamQueueBytes || event.ev === "overflow") { + return this.stopStream(entry, sseEvent("overflow", { reason: event.ev === "overflow" ? "host" : "slow_client" })); + } + switch (event.ev) { + case "output": res.write(sseEvent("output", { offset: event.offset, data: event.data }, String(event.offset))); break; + case "title": res.write(sseEvent("title", { title: event.title })); break; + case "resized": res.write(sseEvent("resized", { cols: event.cols, rows: event.rows })); break; + case "exit": this.stopStream(entry, sseEvent("exit", { code: event.code ?? null })); break; + default: break; + } + }; + conn.onEvent(forward); + let reply ; + try { + reply = await conn.request("attach", { term, ...(from === undefined ? {} : { from }) }, this.limits.requestTimeoutMs); + } catch (error) { + conn.close(); + throw hostHttpError(error); + } + this.streams.add(entry); + startSse(req, res); + res.write(`retry: 3000\n\n${sseEvent("attached", { offset: reply.offset, ...(typeof reply.snapshot === "string" ? { snapshot: reply.snapshot } : {}) }, String(reply.offset))}`); + attached = true; + for (const event of early.splice(0)) forward(event); + conn.onClose(() => this.stopStream(entry, sseEvent("error", { code: "term_host_gone", message: "The terminal host closed the connection" }))); + res.on("close", () => this.stopStream(entry)); + } + + stopStream(entry , last ) { + if (!this.streams.delete(entry)) return; + entry.conn.close(); + if (!entry.res.writableEnded) entry.res.end(last); + } + + /** `GET /api/term-host`: whether a binary is there and whether the host runs (connecting, never starting it), and which release asset fits this server. */ + async status(res , who ) { + const bin = this.binary(); + if (!(this.control && !this.control.closed) && this.hostMayRun()) await this.ensureHost().catch(() => undefined); + const running = !!(this.control && !this.control.closed); + sendJson(res, 200, { + available: bin !== undefined, + // The binary's location is the server's business: only for an admin. + ...(bin !== undefined && hasScope(who, "admin") ? { path: bin } : {}), + running, + ...(running && this.hello ? { version: this.hello.version ?? null, pid: this.hello.pid ?? null, protocol: this.hello.protocol } : {}), + platform: process.platform, + arch: process.arch, + asset: termHostAsset(), + transport: this.transport, + }); + } + + /** `PUT /api/term-host`: installs a host binary into `/bin`, checked against `x-sha256`. */ + async install(req , res , who ) { + const expected = req.headers["x-sha256"]; + if (typeof expected !== "string" || !/^[0-9a-fA-F]{64}$/.test(expected)) { + req.resume(); + throw new HttpError(400, "invalid_sha256", "The x-sha256 header must carry the binary's sha256 (64 hex digits)"); + } + const target = this.installPath(); + const dir = join(this.serveDir, "bin"); + await mkdir(dir, { recursive: true, mode: 0o700 }); + const temp = join(dir, `.${TERM_HOST_BINARY}.${randomBytes(6).toString("hex")}.tmp`); + try { + const received = await receiveBodyToFile(req, temp, this.limits.installBytes, 0o700).catch((error ) => { throw fsHttpError(error, target); }); + if (received.size === 0) throw new HttpError(400, "empty", "The body is empty"); + if (received.sha256 !== expected.toLowerCase()) throw new HttpError(400, "sha256_mismatch", `The body's sha256 is ${received.sha256}`); + await chmod(temp, 0o755); + // Windows won't replace a running .exe but lets it be renamed: the old one moves aside, and goes on a later install once nothing runs it. + if (process.platform === "win32") { + for (const name of await readdir(dir)) if (name.endsWith(".old")) await rm(join(dir, name), { force: true }).catch(() => undefined); + await rename(target, `${target}.${randomBytes(6).toString("hex")}.old`).catch((error ) => { if (error.code !== "ENOENT") throw error; }); + } + await rename(temp, target); + this.log(`terminal host installed by ${who.deviceId}: ${target} (${received.size} bytes, sha256 ${received.sha256})`); + sendJson(res, 201, { path: target, sha256: received.sha256, size: received.size, active: this.binary() === target }); + } finally { + await rm(temp, { force: true }); + } + } + + heartbeat() { + for (const entry of this.streams) entry.res.write(": ping\n\n"); + } + + /** A revoked device: its streams end and its terminals are closed. */ + closeDevice(deviceId ) { + for (const entry of [...this.streams]) if (entry.deviceId === deviceId) this.stopStream(entry); + // Its terminals live only in a running host: never start one just to close nothing. + const terms = this.hostMayRun() ? Object.entries(this.owners).filter(([, owner]) => owner === deviceId).map(([term]) => term) : []; + for (const term of terms) { + void this.closeTerm(term).catch((error ) => this.log(`terminal ${term}: close on revoke failed: ${error instanceof Error ? error.message : String(error)}`)); + } + } + + /** A device paired again replaces its earlier pairing `from`: the terminals `from` opened are `to`'s now. */ + adopt(from , to ) { + let moved = false; + for (const [term, owner] of Object.entries(this.owners)) { + if (owner !== from) continue; + this.owners[term] = to; + moved = true; + } + if (moved) this.saveOwners(); + } + + /** The server is stopping: streams and connections close; the host and its terminals keep running. */ + closeAll() { + this.closed = true; + for (const entry of [...this.streams]) this.stopStream(entry); + this.control?.close(); + } +} + +function size(value , name , max ) { + if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max) throw new HttpError(400, `invalid_${name}`, `${name} must be a whole number 1-${max}`); + return value; +} diff --git a/runtime/serve-tls.mjs b/runtime/serve-tls.mjs new file mode 100644 index 000000000..1ef0901df --- /dev/null +++ b/runtime/serve-tls.mjs @@ -0,0 +1,451 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// TLS for `gentle-shell serve` on the network: a self-signed ECDSA P-256 +// certificate made on first run (a minimal DER encoder builds the X.509 here, +// no dependencies), kept owner-only in `/serve/tls/`, and pinned by +// clients through its SHA-256 fingerprint. A client that found the server +// through untrusted discovery checks a pairing proof before it sends the +// pairing code: only a server that knows the code can bind it to the +// fingerprint the client saw in the handshake. Listeners here speak TLS to the +// network and keep plain HTTP for connections from this machine. + +import { createHash, createHmac, createPrivateKey, generateKeyPairSync, randomBytes, scrypt, sign, timingSafeEqual, X509Certificate } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { createServer as createHttpServer, } from "node:http"; +import { createServer as createHttpsServer, } from "node:https"; +import { createServer as createNetServer, isIPv4, isIPv6, } from "node:net"; +import { connect as tlsConnect, } from "node:tls"; +import { join } from "node:path"; +import { normalizePairingCode } from "./serve-auth.mjs"; + +// --- DER --------------------------------------------------------------------------- + +function derLength(length ) { + if (length < 0x80) return Buffer.from([length]); + const bytes = []; + for (let n = length; n > 0; n >>= 8) bytes.unshift(n & 0xff); + return Buffer.from([0x80 | bytes.length, ...bytes]); +} + +/** One DER TLV: tag, length, the concatenated content. */ +export function der(tag , ...content ) { + const body = Buffer.concat(content); + return Buffer.concat([Buffer.from([tag]), derLength(body.length), body]); +} + +const sequence = (...content ) => der(0x30, ...content); +const set = (...content ) => der(0x31, ...content); +const octets = (value ) => der(0x04, value); +const bits = (value , unused = 0) => der(0x03, Buffer.from([unused]), value); +const bool = (value ) => der(0x01, Buffer.from([value ? 0xff : 0x00])); +const explicit = (n , content ) => der(0xa0 + n, content); + +function oid(dotted ) { + const arcs = dotted.split(".").map(Number); + const out = [arcs[0] * 40 + arcs[1]]; + for (const arc of arcs.slice(2)) { + const chunk = [arc & 0x7f]; + for (let n = Math.floor(arc / 128); n > 0; n = Math.floor(n / 128)) chunk.unshift(0x80 | (n & 0x7f)); + out.push(...chunk); + } + return der(0x06, Buffer.from(out)); +} + +/** A non-negative INTEGER from big-endian bytes: leading zeros dropped, one added when the high bit is set. */ +function integer(value ) { + let start = 0; + while (start < value.length - 1 && value[start] === 0) start += 1; + const trimmed = value.subarray(start); + return der(0x02, trimmed[0] & 0x80 ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed); +} + +/** UTCTime through 2049, GeneralizedTime after (RFC 5280 §4.1.2.5). */ +function time(date ) { + const two = (n ) => String(n).padStart(2, "0"); + const rest = `${two(date.getUTCMonth() + 1)}${two(date.getUTCDate())}${two(date.getUTCHours())}${two(date.getUTCMinutes())}${two(date.getUTCSeconds())}Z`; + const year = date.getUTCFullYear(); + return year < 2050 ? der(0x17, Buffer.from(`${two(year % 100)}${rest}`, "ascii")) : der(0x18, Buffer.from(`${year}${rest}`, "ascii")); +} + +/** The 4 or 16 bytes of an IP literal (brackets and an IPv6 zone ignored); undefined for anything else. */ +export function ipBytes(address ) { + const ip = address.replace(/^\[|\]$/g, "").replace(/%.*$/, ""); + if (isIPv4(ip)) return Buffer.from(ip.split(".").map(Number)); + if (!isIPv6(ip)) return undefined; + let text = ip; + const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(text); + if (v4) { + const [a, b, c, d] = v4[1].split(".").map(Number); + text = `${text.slice(0, -v4[1].length)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; + } + const [head, tail] = text.split("::"); + const left = head ? head.split(":") : []; + const right = tail === undefined ? [] : tail ? tail.split(":") : []; + const groups = tail === undefined ? left : [...left, ...Array(8 - left.length - right.length).fill("0"), ...right]; + const out = Buffer.alloc(16); + groups.forEach((g, i) => out.writeUInt16BE(Number.parseInt(g, 16), i * 2)); + return out; +} + +// --- certificate ------------------------------------------------------------------- + +export const SERVE_TLS_LIMITS = { + validityYears: 10, + /** A certificate this close to its end is replaced at start. */ + renewBeforeMs: 30 * 24 * 60 * 60_000, +}; + +const OID = { + ecdsaWithSha256: "1.2.840.10045.4.3.2", + commonName: "2.5.4.3", + basicConstraints: "2.5.29.19", + keyUsage: "2.5.29.15", + extKeyUsage: "2.5.29.37", + subjectAltName: "2.5.29.17", + serverAuth: "1.3.6.1.5.5.7.3.1", +}; + + + + + + + + + + +/** Base64url (no padding) SHA-256 of the certificate's DER: what clients pin. */ +export function certificateFingerprint(derBytes ) { + return createHash("sha256").update(derBytes).digest("base64url"); +} + +function pem(label , body ) { + const lines = body.toString("base64").match(/.{1,64}/g) ?? []; + return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`; +} + +/** + * A self-signed X.509 v3 server certificate on a fresh P-256 key: a random + * serial, valid from an hour ago for ten years, CA false, digitalSignature, + * serverAuth, and every name and address given as subjectAltName. + */ +export function createSelfSignedCertificate(request ) { + const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" }); + const serial = randomBytes(16); + serial[0] = (serial[0] & 0x7f) | 0x01; + const algorithm = sequence(oid(OID.ecdsaWithSha256)); + const name = sequence(set(sequence(oid(OID.commonName), der(0x0c, Buffer.from(request.commonName.slice(0, 64), "utf8"))))); + const notBefore = new Date((request.now ?? new Date()).getTime() - 60 * 60_000); + const notAfter = new Date(notBefore); + notAfter.setUTCFullYear(notAfter.getUTCFullYear() + SERVE_TLS_LIMITS.validityYears); + const names = []; + for (const dns of new Set(request.dnsNames.map((n) => n.toLowerCase()))) if (/^[\x21-\x7e]{1,253}$/.test(dns)) names.push(der(0x82, Buffer.from(dns, "ascii"))); + const seen = new Set (); + for (const ip of request.ips) { + const raw = ipBytes(ip); + if (raw && !seen.has(raw.toString("hex"))) { + seen.add(raw.toString("hex")); + names.push(der(0x87, raw)); + } + } + const extensions = sequence( + sequence(oid(OID.basicConstraints), bool(true), octets(sequence())), + sequence(oid(OID.keyUsage), bool(true), octets(bits(Buffer.from([0x80]), 7))), + sequence(oid(OID.extKeyUsage), octets(sequence(oid(OID.serverAuth)))), + ...(names.length > 0 ? [sequence(oid(OID.subjectAltName), octets(sequence(...names)))] : []), + ); + const tbs = sequence( + explicit(0, integer(Buffer.from([2]))), + integer(serial), + algorithm, + name, + sequence(time(notBefore), time(notAfter)), + name, + publicKey.export({ type: "spki", format: "der" }), + explicit(3, extensions), + ); + const certificate = sequence(tbs, algorithm, bits(sign("sha256", tbs, privateKey))); + return { certPem: pem("CERTIFICATE", certificate), keyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(), der: certificate }; +} + +/** The server's TLS identity: PEMs for the listeners, the DER and its fingerprint for clients. */ + + + + + + + + + + + +export function serveTlsFiles(serveDir ) { + const dir = join(serveDir, "tls"); + return { dir, cert: join(dir, "cert.pem"), key: join(dir, "key.pem") }; +} + +function writePrivate(path , text ) { + const temp = `${path}.${process.pid}.tmp`; + writeFileSync(temp, text, { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows: ACLs, not modes */ } +} + +function readIdentity(certPath , keyPath , now ) { + if (!existsSync(certPath) || !existsSync(keyPath)) return undefined; + try { + const certPem = readFileSync(certPath, "utf8"); + const keyPem = readFileSync(keyPath, "utf8"); + const cert = new X509Certificate(certPem); + const notAfter = new Date(cert.validTo); + if (!cert.checkPrivateKey(createPrivateKey(keyPem)) || notAfter.getTime() - now < SERVE_TLS_LIMITS.renewBeforeMs) return undefined; + return { certPem, keyPem, der: cert.raw, fingerprint: certificateFingerprint(cert.raw), notAfter, created: false }; + } catch { + return undefined; + } +} + +/** + * The certificate in `/tls/`, made when missing, unreadable, not + * matching its key, or within 30 days of its end. Names and addresses are a + * snapshot of the first run: clients pin the fingerprint, not the names, so a + * changed address never replaces it (that would break every paired device). + */ +export function loadOrCreateServeTls(serveDir , request , now = Date.now) { + const files = serveTlsFiles(serveDir); + const existing = readIdentity(files.cert, files.key, now()); + if (existing) return existing; + mkdirSync(files.dir, { recursive: true, mode: 0o700 }); + try { chmodSync(files.dir, 0o700); } catch { /* Windows */ } + const made = createSelfSignedCertificate({ ...request, now: new Date(now()) }); + writePrivate(files.key, made.keyPem); + writePrivate(files.cert, made.certPem); + const cert = new X509Certificate(made.der); + return { certPem: made.certPem, keyPem: made.keyPem, der: made.der, fingerprint: certificateFingerprint(made.der), notAfter: new Date(cert.validTo), created: true }; +} + +// --- pairing proof ----------------------------------------------------------------- + +/** + * `POST /api/pair/proof`. The key is stretched with scrypt because a proof is + * a function of a 40-bit code: with plain HMAC anyone could ask for one and + * search every code offline in minutes. Every number here is part of the contract. + */ +export const PAIR_PROOF = { + salt: "gentle-shell/pair-proof/v1", + N: 32768, + r: 8, + p: 1, + keyBytes: 32, + /** Nonce bytes after base64url decoding. */ + nonceMinBytes: 16, + nonceMaxBytes: 64, + /** Proof requests answered per window across all callers (like failed pairings). */ + perWindow: 20, + windowMs: 60_000, +}; + +/** scrypt(P = normalized code as ASCII, S = "gentle-shell/pair-proof/v1" || raw fingerprint, N=32768, r=8, p=1, 32 bytes). */ +export function pairProofKey(code , fingerprint ) { + const { promise, resolve, reject } = Promise.withResolvers (); + scrypt(Buffer.from(normalizePairingCode(code), "ascii"), Buffer.concat([Buffer.from(PAIR_PROOF.salt, "ascii"), fingerprint]), PAIR_PROOF.keyBytes, + { N: PAIR_PROOF.N, r: PAIR_PROOF.r, p: PAIR_PROOF.p, maxmem: 64 * 1024 * 1024 }, (error, key) => (error ? reject(error) : resolve(key))); + return promise; +} + +/** HMAC-SHA256(key, raw fingerprint || nonce). */ +export function pairProof(key , fingerprint , nonce ) { + return createHmac("sha256", key).update(fingerprint).update(nonce).digest(); +} + +/** Decodes a base64url fingerprint; undefined unless it is 32 bytes. */ +export function fingerprintBytes(fingerprint ) { + if (!/^[A-Za-z0-9_-]{43}$/.test(fingerprint)) return undefined; + const raw = Buffer.from(fingerprint, "base64url"); + return raw.length === 32 ? raw : undefined; +} + +/** The client's check: one of `proofs` binds `code` to the fingerprint it saw in the handshake. */ +export async function verifyPairProof(input ) { + const fp = fingerprintBytes(input.fingerprint); + if (!fp) return false; + const expected = pairProof(await pairProofKey(input.code, fp), fp, input.nonce); + let match = false; + for (const proof of input.proofs) { + if (typeof proof !== "string") continue; + const given = Buffer.from(proof, "base64url"); + if (given.length === expected.length && timingSafeEqual(given, expected)) match = true; + } + return match; +} + +/** Proof keys for the live codes (one scrypt per code, cached) and the global request budget. */ +export class PairProofs { + fingerprint ; + now ; + keys = new Map (); + requests = []; + constructor(fingerprint , now = Date.now) { + const fp = fingerprintBytes(fingerprint); + if (!fp) throw new Error("bad certificate fingerprint"); + this.fingerprint = fp; + this.now = now; + } + + /** False once `perWindow` requests came within the window. */ + allow() { + const now = this.now(); + this.requests = this.requests.filter((t) => now - t < PAIR_PROOF.windowMs); + if (this.requests.length >= PAIR_PROOF.perWindow) return false; + this.requests.push(now); + return true; + } + + /** One base64url proof per live code, in random order. */ + async proofs(codes , nonce ) { + const live = new Set(codes.map(normalizePairingCode)); + for (const code of this.keys.keys()) if (!live.has(code)) this.keys.delete(code); + const keys = await Promise.all([...live].map((code) => { + let key = this.keys.get(code); + if (!key) this.keys.set(code, (key = pairProofKey(code, this.fingerprint))); + return key; + })); + const out = keys.map((key) => pairProof(key, this.fingerprint, nonce).toString("base64url")); + for (let i = out.length - 1; i > 0; i -= 1) { + const j = randomBytes(4).readUInt32BE() % (i + 1); + [out[i], out[j]] = [out[j], out[i]]; + } + return out; + } +} + +// --- listeners --------------------------------------------------------------------- + +/** How a connection reached a listener: plain HTTP from this machine, TLS, or TLS through a relay. */ + + + + + + + +/** `https` when the request came over TLS (directly or through a relay), else `http`. */ +export function requestScheme(req ) { + return "encrypted" in req.socket && req.socket.encrypted === true ? "https" : "http"; +} + +/** Whether the peer is this machine: a loopback address, or the address it connected to (a remote host cannot have ours). */ +export function isLocalPeer(socket ) { + const remote = (socket.remoteAddress ?? "").replace(/^::ffff:/i, ""); + const local = (socket.localAddress ?? "").replace(/^::ffff:/i, ""); + if (remote === "") return false; + return remote === "::1" || /^127\./.test(remote) || remote === local; +} + +/** The first byte of a TLS ClientHello record. */ +const TLS_HANDSHAKE = 0x16; +const SNIFF_TIMEOUT_MS = 20_000; +const TLS_REQUIRED = JSON.stringify({ error: { code: "tls_required", message: "This server speaks HTTPS on the network: connect with https:// and pin its certificate fingerprint" } }); + + + + + + + + + + +/** + * One listening socket for an HTTP API: without `tls`, plain HTTP for every + * peer; with it, TLS for every peer, plus plain HTTP from this machine (the + * first byte tells them apart), so local tools keep `http://127.0.0.1`. A + * network peer that speaks plain HTTP gets `400 tls_required`. `setup` gets + * each underlying HTTP server once, with how its connections arrive. + */ +export function createServeListener(options ) { + const sockets = new Set (); + const plain = createHttpServer(); + options.setup(plain, "plain"); + const tlsOptions = options.tls ? { key: options.tls.keyPem, cert: options.tls.certPem, minVersion: "TLSv1.2" , ALPNProtocols: ["http/1.1"] } : undefined; + const secure = tlsOptions ? createHttpsServer(tlsOptions) : undefined; + if (secure) options.setup(secure, "tls"); + let relayed ; + const track = (socket ) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + options.onConnection?.(socket); + }; + const server = createNetServer({ pauseOnConnect: false }, (socket) => { + track(socket); + socket.on("error", () => socket.destroy()); + if (!secure) return void plain.emit("connection", socket); + const local = isLocalPeer(socket); + const timer = setTimeout(() => socket.destroy(), SNIFF_TIMEOUT_MS); + socket.once("data", (chunk ) => { + clearTimeout(timer); + socket.pause(); + socket.unshift(chunk); + if (chunk[0] === TLS_HANDSHAKE) secure.emit("connection", socket); + else if (local) plain.emit("connection", socket); + else return void socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(TLS_REQUIRED)}\r\nConnection: close\r\n\r\n${TLS_REQUIRED}`); + process.nextTick(() => socket.resume()); + }); + }); + return { + server, + acceptRelayed(socket) { + if (!tlsOptions) return void socket.destroy(); + if (!relayed) { + relayed = createHttpsServer(tlsOptions); + options.setup(relayed, "relay"); + } + track(socket); + socket.on("error", () => socket.destroy()); + relayed.emit("connection", socket); + }, + closeAllConnections() { + for (const s of [plain, secure, relayed]) { + if (!s) continue; + s.closeAllConnections(); + s.close(() => {}); + } + for (const socket of sockets) socket.destroy(); + }, + }; +} + +// --- client side ------------------------------------------------------------------- + +/** + * A TLS connection that ends unless the server's certificate has `fingerprint` + * (base64url SHA-256 of its DER): the check is the certificate, not a CA or a + * name. Resolves after the handshake, before a byte of the request is sent. + */ +export function connectPinned(target , fingerprint ) { + const { promise, resolve, reject } = Promise.withResolvers (); + const socket = tlsConnect({ ...target, rejectUnauthorized: false, ALPNProtocols: ["http/1.1"] }); + socket.once("error", reject); + socket.once("secureConnect", () => { + const seen = certificateFingerprint(socket.getPeerCertificate(false).raw); + if (seen !== fingerprint) { + socket.destroy(); + return reject(Object.assign(new Error(`certificate fingerprint ${seen} is not the pinned ${fingerprint}`), { code: "fingerprint_mismatch", seen })); + } + socket.off("error", reject); + resolve(socket); + }); + return promise; +} + +/** The fingerprint a TLS server presents, trusting nothing yet (first contact, before a pairing proof). */ +export function peekFingerprint(target ) { + const { promise, resolve, reject } = Promise.withResolvers (); + const socket = tlsConnect({ ...target, rejectUnauthorized: false, ALPNProtocols: ["http/1.1"] }); + socket.once("error", reject); + socket.once("secureConnect", () => { + socket.off("error", reject); + resolve({ socket, fingerprint: certificateFingerprint(socket.getPeerCertificate(false).raw) }); + }); + return promise; +} diff --git a/runtime/serve-upgrade.mjs b/runtime/serve-upgrade.mjs new file mode 100644 index 000000000..3261e9e14 --- /dev/null +++ b/runtime/serve-upgrade.mjs @@ -0,0 +1,239 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// `gentle-shell serve`'s self-upgrade (`POST /api/upgrade`, admin): runs the +// same `gentle-shell upgrade` a person would on this machine, streams its +// output to admin clients (`GET /api/upgrade/:jobId/stream`, SSE `line` and +// `finished`), and on success asks the server to restart itself on the new +// version. Session keepers and the terminal host are separate processes and +// keep running; the next server reattaches them. +// +// The same runner also runs Gentle Shell's own setup for the server's home +// (`POST /api/setup`, admin; `GET /api/setup/:jobId/stream`): the companion +// packages a `gentle-shell setup` installs there. Setup never replaces the +// launcher, so it never restarts the server. One job at a time, upgrade or setup. + +import { spawn, } from "node:child_process"; +import { randomBytes } from "node:crypto"; + +import { HttpError, sseEvent, startSse } from "./serve-http.mjs"; + + +export const SERVE_UPGRADE_LIMITS = { + /** Output lines kept for a stream that connects late; older ones are dropped. */ + lines: 2000, + line: 2000, + error: 300, + /** An upgrade still running then is stopped. */ + timeoutMs: 30 * 60_000, + /** Time for the `finished` event to reach clients before the server restarts. */ + restartDelayMs: 500, + heartbeatMs: 20_000, +}; + +export const UPGRADE_CHANNELS = ["release", "main"] ; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +export const UPGRADE_JOB_ID = /^upg_[0-9a-f]{16}$/; +export const SETUP_JOB_ID = /^setup_[0-9a-f]{16}$/; +const JOB_ID_PREFIX = { upgrade: "upg_", setup: "setup_" }; + +// eslint-disable-next-line no-control-regex +const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-Z\\-_]/g; + +/** Output text as lines: no color codes, no control characters, no blank lines, each bounded. */ +export function upgradeLines(text , limit = SERVE_UPGRADE_LIMITS.line) { + const lines = []; + for (const raw of text.replace(ANSI, "").split(/\r\n|\r|\n/)) { + // eslint-disable-next-line no-control-regex + const line = raw.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "").trimEnd(); + if (line.trim().length > 0) lines.push(line.length > limit ? `${line.slice(0, limit - 1)}…` : line); + } + return lines; +} + +export class UpgradeService { + job ; + limits ; + heartbeat ; + options ; + closed = false; + + constructor(options ) { + this.options = options; + this.limits = { ...SERVE_UPGRADE_LIMITS, ...options.limits }; + this.heartbeat = setInterval(() => { + for (const res of this.job?.streams ?? []) res.write(": ping\n\n"); + }, this.limits.heartbeatMs); + this.heartbeat.unref(); + } + + running() { + return this.job !== undefined && this.job.finished === undefined; + } + + /** Whether this server can run setup (the `setup` capability). */ + canSetup() { + return this.options.setup !== undefined; + } + + /** Starts the upgrade; `409 upgrade_running` / `setup_running` while a job runs. */ + start(channel ) { + this.claim(); + return this.run("upgrade", this.options.launch(channel), channel === undefined ? "" : ` (channel ${channel})`); + } + + /** Starts Gentle Shell's setup for the server's home; same one-job rule as the upgrade. */ + startSetup() { + const setup = this.options.setup; + if (!setup) throw new HttpError(501, "not_supported", "This server cannot run setup"); + this.claim(); + return this.run("setup", setup(), ""); + } + + claim() { + if (this.closed) throw new HttpError(503, "server_stopping", "The server is stopping"); + const job = this.job; + if (job && job.finished === undefined) { + throw new HttpError(409, `${job.kind}_running`, job.kind === "upgrade" ? "An upgrade is already running" : "Setup is already running"); + } + } + + run(kind , launch , detail ) { + const previous = this.job; + for (const res of previous?.streams ?? []) res.end(); + const job = { kind, jobId: `${JOB_ID_PREFIX[kind]}${randomBytes(8).toString("hex")}`, lines: [], streams: new Set() }; + this.job = job; + this.options.log?.(`${kind} ${job.jobId}: started${detail}`); + let child ; + try { + child = spawn(launch.command, launch.args, { cwd: launch.cwd, env: launch.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + } catch (error) { + queueMicrotask(() => this.finish(job, { ok: false, error: error instanceof Error ? error.message : String(error) })); + return { jobId: job.jobId }; + } + job.child = child; + const errors = []; + const read = (stream , isError ) => { + let rest = ""; + const emit = (text ) => { + for (const line of upgradeLines(text, this.limits.line)) { + if (isError) errors.push(line); + this.line(job, line); + } + }; + stream?.setEncoding("utf8"); + stream?.on("data", (chunk ) => { + const text = rest + chunk; + const cut = Math.max(text.lastIndexOf("\n"), text.lastIndexOf("\r")); + rest = cut === -1 ? text : text.slice(cut + 1); + if (cut !== -1) emit(text.slice(0, cut + 1)); + }); + stream?.on("end", () => { + emit(rest); + rest = ""; + }); + }; + read(child.stdout, false); + read(child.stderr, true); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGTERM"); + setTimeout(() => child.kill("SIGKILL"), 5000).unref(); + }, this.limits.timeoutMs); + timer.unref(); + child.once("error", (error) => { + clearTimeout(timer); + this.finish(job, { ok: false, error: error.message }); + }); + child.once("close", (code, signal) => { + clearTimeout(timer); + if (code === 0) { + let version ; + try { + if (job.kind === "upgrade") version = this.options.installedVersion?.(); + } catch { /* unknown until the new server answers GET /api/server */ } + this.finish(job, { ok: true, ...(version === undefined ? {} : { version }) }); + return; + } + const last = errors.at(-1) ?? job.lines.at(-1); + const error = timedOut ? `The ${job.kind} ran past its time limit` : last ?? (signal ? `Stopped by ${signal}` : `Exited with code ${code}`); + this.finish(job, { ok: false, error: error.length > this.limits.error ? `${error.slice(0, this.limits.error - 1)}…` : error }); + }); + return { jobId: job.jobId }; + } + + line(job , line ) { + job.lines.push(line); + if (job.lines.length > this.limits.lines) job.lines.shift(); + const event = sseEvent("line", { line }); + for (const res of job.streams) res.write(event); + } + + finish(job , finished ) { + if (job.finished) return; + job.finished = finished; + job.child = undefined; + this.options.log?.(`${job.kind} ${job.jobId}: ${finished.ok ? `done${finished.version === undefined ? "" : ` (${finished.version})`}` : `failed: ${finished.error}`}`); + // Before `finished` reaches a client, so what it asks next reflects the job. + this.options.onFinished?.(job.kind); + const event = sseEvent("finished", finished); + for (const res of job.streams) res.end(event); + job.streams.clear(); + if (job.kind === "upgrade" && finished.ok && !this.closed) setTimeout(() => this.options.onUpgraded(), this.limits.restartDelayMs).unref(); + } + + /** SSE: the lines so far, then live ones, then `finished`, then the stream ends. */ + stream(req , res , jobId ) { + const job = this.job; + if (!job || job.jobId !== jobId) throw new HttpError(404, "not_found", "No such job"); + startSse(req, res); + res.write("retry: 3000\n\n"); + for (const line of job.lines) res.write(sseEvent("line", { line })); + if (job.finished) { + res.end(sseEvent("finished", job.finished)); + return; + } + job.streams.add(res); + res.on("close", () => job.streams.delete(res)); + } + + /** The server is stopping: streams end; a running job goes on to its end, as a CLI one would. */ + close() { + this.closed = true; + clearInterval(this.heartbeat); + for (const res of this.job?.streams ?? []) res.end(); + this.job?.streams.clear(); + } +} diff --git a/runtime/serve-uploads.mjs b/runtime/serve-uploads.mjs new file mode 100644 index 000000000..cad576605 --- /dev/null +++ b/runtime/serve-uploads.mjs @@ -0,0 +1,98 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// Uploads for `gentle-shell serve`: a client sends a file it wants the agent +// to see (a chat attachment, a screenshot, a log) and gets back its path on +// the server, under `/serve/uploads///`. +// Uploads are owner-only and removed after 7 days. + +import { randomBytes } from "node:crypto"; +import { mkdir, readdir, rm, rmdir, stat } from "node:fs/promises"; + +import { join } from "node:path"; + +import { fsHttpError, need, receiveBodyToFile, sendJson } from "./serve-http.mjs"; + +export const SERVE_UPLOAD_LIMITS = { + bytes: 64 * 1024 * 1024, + /** An upload older than this is removed. */ + maxAgeMs: 7 * 24 * 60 * 60_000, + sweepMs: 60 * 60_000, + /** UTF-8 bytes of a file name. */ + nameBytes: 200, +}; + +/** + * A file name from a client: its last path component, without control + * characters or characters Windows forbids, at most `maxBytes` UTF-8 bytes; + * `upload` when nothing usable is left. + */ +export function cleanUploadName(raw , maxBytes = SERVE_UPLOAD_LIMITS.nameBytes) { + const last = (raw ?? "").split(/[/\\]/).pop() ?? ""; + let name = last.replace(/[\u0000-\u001f\u007f<>:"|?*]/g, "_").trim(); + while (Buffer.byteLength(name, "utf8") > maxBytes) name = name.slice(0, -1); + return name === "" || name === "." || name === ".." ? "upload" : name; +} + + + + + + + + + +export class UploadStore { + dir ; + limits ; + now ; + log ; + timer ; + + constructor(options ) { + this.dir = options.dir; + this.limits = { ...SERVE_UPLOAD_LIMITS, ...options.limits }; + this.now = options.now ?? Date.now; + this.log = options.log ?? (() => {}); + this.timer = setInterval(() => void this.sweep(), this.limits.sweepMs); + this.timer.unref(); + void this.sweep(); + } + + /** `POST /api/uploads?name=`: the raw body becomes a new file; answers its path. */ + async upload(req , res , url , principal ) { + const who = need(principal, "sessions:operate"); + const name = cleanUploadName(url.searchParams.get("name")); + const folder = join(this.dir, who.deviceId, randomBytes(8).toString("hex")); + await mkdir(folder, { recursive: true, mode: 0o700 }).catch((error ) => { throw fsHttpError(error, folder); }); + const path = join(folder, name); + try { + const { size, sha256 } = await receiveBodyToFile(req, path, this.limits.bytes, 0o600); + sendJson(res, 201, { path, name, size, sha256, expiresAt: new Date(this.now() + this.limits.maxAgeMs).toISOString() }); + } catch (error) { + await rm(folder, { recursive: true, force: true }); + throw fsHttpError(error, path); + } + } + + /** Removes uploads older than `maxAgeMs`, then device folders left empty. */ + async sweep() { + const cutoff = this.now() - this.limits.maxAgeMs; + const devices = await readdir(this.dir).catch(() => [] ); + for (const device of devices) { + const deviceDir = join(this.dir, device); + const uploads = await readdir(deviceDir).catch(() => [] ); + for (const upload of uploads) { + const folder = join(deviceDir, upload); + const stats = await stat(folder).catch(() => undefined); + if (stats && stats.mtimeMs < cutoff) { + await rm(folder, { recursive: true, force: true }); + this.log(`upload ${device}/${upload} expired`); + } + } + await rmdir(deviceDir).catch(() => { /* not empty */ }); + } + } + + close() { + clearInterval(this.timer); + } +} diff --git a/scripts/build-runtime-modules.mjs b/scripts/build-runtime-modules.mjs index 1042b25dc..9992d7701 100644 --- a/scripts/build-runtime-modules.mjs +++ b/scripts/build-runtime-modules.mjs @@ -35,6 +35,29 @@ const sources = [ "tower-open", // The sensitive-path list shared by the tool guard and the verifier preparer. "sensitive-paths", + // `gentle-shell serve` runs its server and sessions without Pi. + "rpc-host", + "serve-session", + // Each session's keeper runs as its own process (`node runtime/serve-session-keeper-main.mjs`). + "serve-session-keeper", + "serve-session-keeper-main", + "serve-auth", + "serve-discovery", + "serve-forward", + "serve-http", + "serve-files", + "serve-git", + "serve-checks", + "serve-print", + "serve-upgrade", + "serve-server", + "serve-uploads", + "serve-terminals", + "serve-share", + "serve-cli", + "serve-tls", + "serve-relay", + "serve-relay-cli", ]; const header = "// Generated by scripts/build-runtime-modules.mjs. Do not edit.\n"; diff --git a/scripts/verify-package-files.mjs b/scripts/verify-package-files.mjs index b2e80439c..a6da5e4ce 100644 --- a/scripts/verify-package-files.mjs +++ b/scripts/verify-package-files.mjs @@ -170,6 +170,30 @@ export const requiredPaths = [ "runtime/tower-actions.mjs", "runtime/tower-snapshot.mjs", "runtime/tower-launch.mjs", + // `gentle-shell serve` imports these generated modules by path. + "runtime/rpc-host.mjs", + "runtime/serve-session.mjs", + "runtime/serve-session-keeper.mjs", + "runtime/serve-session-keeper-main.mjs", + "runtime/serve-auth.mjs", + "runtime/serve-discovery.mjs", + "runtime/serve-forward.mjs", + "runtime/serve-http.mjs", + "runtime/serve-files.mjs", + "runtime/serve-git.mjs", + "runtime/serve-checks.mjs", + "runtime/serve-print.mjs", + "runtime/serve-upgrade.mjs", + "runtime/serve-server.mjs", + "runtime/serve-uploads.mjs", + "runtime/serve-terminals.mjs", + "runtime/serve-share.mjs", + "runtime/serve-cli.mjs", + "runtime/serve-tls.mjs", + "runtime/serve-relay.mjs", + "runtime/serve-relay-cli.mjs", + "docs/serve.md", + "docs/remote.md", "scripts/check-provider-contract.mjs", "scripts/download-progress.mjs", "scripts/gentle-ai-installer.mjs", diff --git a/tests/desktop-feed-actions.test.ts b/tests/desktop-feed-actions.test.ts index 9daae9a97..2125c4ad8 100644 --- a/tests/desktop-feed-actions.test.ts +++ b/tests/desktop-feed-actions.test.ts @@ -467,12 +467,12 @@ test("S2: runDesktopAction calls only the owner its kind names", async () => { // ---- Existing desktop RPC behaviour is unchanged ---- -/** Channel lines other than the feed's session_snapshot events, without the shared event counter. */ +/** Channel lines other than the feed's session_snapshot events, without the shared event counter and the channel's epoch. */ function withoutSessionSnapshots(lines: Array): unknown[] { return lines .map((line) => JSON.parse(line!) as Record) .filter((line) => line.event !== "session_snapshot") - .map(({ seq: _seq, ...line }) => line); + .map(({ seq: _seq, epoch: _epoch, ...line }) => line); } test("S2: desktop RPC set_permission_mode answers are byte-identical with the feed and its inbox loaded", async (t) => { diff --git a/tests/desktop-feed-plan-profiles.test.ts b/tests/desktop-feed-plan-profiles.test.ts index 17857ff95..47a3ead13 100644 --- a/tests/desktop-feed-plan-profiles.test.ts +++ b/tests/desktop-feed-plan-profiles.test.ts @@ -464,12 +464,12 @@ test("S12: the action kinds add refresh_usage and apply_profile and keep every e // ---- The desktop RPC is unchanged ---- -/** Channel lines other than the feed's session_snapshot events, without the shared event counter. */ +/** Channel lines other than the feed's session_snapshot events, without the shared event counter and the channel's epoch. */ function withoutSessionSnapshots(lines: Array): unknown[] { return lines .map((line) => JSON.parse(line!) as Record) .filter((line) => line.event !== "session_snapshot") - .map(({ seq: _seq, ...line }) => line); + .map(({ seq: _seq, epoch: _epoch, ...line }) => line); } test("S12: desktop RPC refresh_subscription_usage and apply_profile answers are byte-identical with the feed loaded", async (t) => { diff --git a/tests/desktop-feed.test.ts b/tests/desktop-feed.test.ts index 6a470cdfe..4929011e9 100644 --- a/tests/desktop-feed.test.ts +++ b/tests/desktop-feed.test.ts @@ -690,12 +690,12 @@ test("S2: children, plain Pi and print sessions publish nothing", async (t) => { // ---- Existing desktop RPC behaviour is unchanged ---- -/** Channel lines other than the feed's session_snapshot events, without the shared event counter. */ +/** Channel lines other than the feed's session_snapshot events, without the shared event counter and the channel's epoch. */ function withoutSessionSnapshots(lines: Array): unknown[] { return lines .map((line) => JSON.parse(line!) as Record) .filter((line) => line.event !== "session_snapshot") - .map(({ seq: _seq, ...line }) => line); + .map(({ seq: _seq, epoch: _epoch, ...line }) => line); } test("S2: desktop RPC jobs answers and events are byte-identical with the feed loaded", async (t) => { diff --git a/tests/desktop-rpc-agent-definitions.test.ts b/tests/desktop-rpc-agent-definitions.test.ts index de1b673ad..84abf54d9 100644 --- a/tests/desktop-rpc-agent-definitions.test.ts +++ b/tests/desktop-rpc-agent-definitions.test.ts @@ -94,7 +94,7 @@ test("the Desktop transport advertises list_agent_definitions once and no new ev const response = app.last(); assert.equal(response.data.methods.filter((method: string) => method === "list_agent_definitions").length, 1); assert.ok(response.data.methods.includes("get_update_status"), "the previous methods stay advertised"); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); // ---- The read ---- diff --git a/tests/desktop-rpc-agents.test.ts b/tests/desktop-rpc-agents.test.ts index c2d60c04b..67eee86e4 100644 --- a/tests/desktop-rpc-agents.test.ts +++ b/tests/desktop-rpc-agents.test.ts @@ -889,8 +889,23 @@ test("the Desktop transport advertises the agents methods and event", (t) => { "clear_profile_binding", "get_auth_status", "reload_credentials", + "list_available_models", + "set_host_tools", + "host_tool_result", + "host_tool_progress", + "host_message", + "set_host_context", + "set_host_activity", + "login_start", + "login_complete", + "login_cancel", + "set_api_key", + "remove_credentials", + "list_packages", + "install_package", + "remove_package", ]); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); test("get_subagent_thread answers agents_unavailable through the transport without an owner extension", async (t) => { diff --git a/tests/desktop-rpc-auth.test.ts b/tests/desktop-rpc-auth.test.ts index 9f2f60758..e820448d5 100644 --- a/tests/desktop-rpc-auth.test.ts +++ b/tests/desktop-rpc-auth.test.ts @@ -9,8 +9,10 @@ import { DESKTOP_AUTH_LIMITS, DESKTOP_AUTH_METHODS, INVALID_GET_AUTH_STATUS, + INVALID_LIST_AVAILABLE_MODELS, INVALID_RELOAD_CREDENTIALS, RELOAD_FAILED, + loginKinds, projectAuthStatus, } from "../lib/desktop-rpc-auth.ts"; import { INTERACTIVE_HOST_ENV } from "../lib/rpc-host.ts"; @@ -38,6 +40,8 @@ function fakeRegistry(options: { configured?: Record ({ "openai-codex": "OpenAI Codex", anthropic: "Anthropic" })[provider] ?? provider, + // Provider definitions: which sign-ins each has (a browser sign-in and a key; Codex adds a device code). + getProvider: (provider: string) => ({ anthropic: { auth: { oauth: {}, apiKey: { login: async () => ({}) } } }, "openai-codex": { auth: { oauth: {} } } })[provider], isUsingOAuth: (model: { provider: string }) => configured[model.provider]?.oauth === true, async refresh(refreshOptions: unknown) { calls.refresh.push(refreshOptions); @@ -52,7 +56,7 @@ function fakeRegistry(options: { configured?: Record { @@ -66,6 +70,7 @@ function harness(t: test.TestContext, registry: unknown) { registerShortcut() {}, on(name: string, handler: any) { handlers.set(name, [...(handlers.get(name) ?? []), handler]); }, events: { on() { return () => {}; }, emit() {} }, + getThinkingLevel: () => session.thinkingLevel ?? "off", } as unknown as ExtensionAPI; desktopRpc(pi); const widgets: string[] = []; @@ -73,6 +78,7 @@ function harness(t: test.TestContext, registry: unknown) { mode: "rpc", cwd: "/x", modelRegistry: registry, + model: session.model, sessionManager: { getCwd: () => "/x", getSessionId: () => "s", getEntries: () => [] }, ui: { setWidget(_key: string, lines: string[]) { widgets.push(...lines); } }, }; @@ -89,14 +95,88 @@ function harness(t: test.TestContext, registry: unknown) { // ---- Capabilities ---- -test("the Desktop transport advertises both methods once and no new event", async (t) => { - assert.deepEqual([...DESKTOP_AUTH_METHODS], ["get_auth_status", "reload_credentials"]); +test("the Desktop transport advertises the three methods once and no new event", async (t) => { + assert.deepEqual([...DESKTOP_AUTH_METHODS], ["get_auth_status", "reload_credentials", "list_available_models"]); assert.deepEqual([...DESKTOP_AUTH_EVENTS], []); const app = harness(t, fakeRegistry().registry); await app.invoke("cap", "capabilities"); const data = app.last().data; for (const method of DESKTOP_AUTH_METHODS) assert.equal(data.methods.filter((name: string) => name === method).length, 1); - assert.deepEqual(data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); +}); + +// ---- list_available_models ---- + +const SOL = { provider: "anthropic", id: "claude-sol", name: "Claude Sol", api: "anthropic-messages", baseUrl: "https://secret.example/v1", headers: { "x-key": SECRET }, contextWindow: 200000, maxTokens: 64000, reasoning: true, thinkingLevelMap: { xhigh: "x", max: null }, input: ["text", "image"], cost: { input: 3 } }; +const LUNA = { provider: "anthropic", id: "claude-luna", contextWindow: 100000, reasoning: false, input: ["text"] }; + +test("list_available_models lists the available snapshot, Pi's thinking levels and the current model, and nothing else of a model", async (t) => { + const fake = fakeRegistry(); + const reads = { available: 0 }; + Object.assign(fake.registry, { getAvailable: () => { reads.available += 1; return [SOL, LUNA, { provider: "C:\\evil", id: "x" }, { provider: "openrouter", id: "openai/gpt-oss:free", name: " " }]; } }); + const app = harness(t, fake.registry, { model: SOL, thinkingLevel: "high" }); + await app.invoke("models-1", "list_available_models"); + assert.deepEqual(app.last(), { + schema: DESKTOP_RPC_SCHEMA, + kind: "response", + requestId: "models-1", + ok: true, + data: { + models: [ + { provider: "anthropic", id: "claude-sol", name: "Claude Sol", contextWindow: 200000, reasoning: true, input: ["text", "image"] }, + { provider: "anthropic", id: "claude-luna", contextWindow: 100000, reasoning: false, input: ["text"] }, + { provider: "openrouter", id: "openai/gpt-oss:free" }, + ], + // Pi's own rule for the current model: `max` is unsupported (null), `xhigh` mapped. + thinkingLevels: ["off", "minimal", "low", "medium", "high", "xhigh"], + current: { provider: "anthropic", id: "claude-sol", thinkingLevel: "high" }, + truncated: false, + }, + }); + const raw = app.widgets.at(-1)!; + for (const leak of [SECRET, "secret.example", "evil", "maxTokens", "cost"]) assert.equal(raw.includes(leak), false, `no ${leak} on the wire`); + assert.equal(reads.available, 1); + assert.equal(fake.calls.secretReads, 0); + assert.deepEqual(fake.calls.refresh, [], "a read never refreshes"); +}); + +test("list_available_models without a current model offers every thinking level and no current", async (t) => { + const fake = fakeRegistry(); + Object.assign(fake.registry, { getAvailable: () => [LUNA] }); + const app = harness(t, fake.registry); + await app.invoke("models-2", "list_available_models"); + const data = app.last().data; + assert.deepEqual(data.thinkingLevels, ["off", "minimal", "low", "medium", "high", "xhigh", "max"]); + assert.equal("current" in data, false); + // A model without reasoning offers `off` only, as Pi's get_available_thinking_levels does. + const plain = harness(t, fake.registry, { model: LUNA, thinkingLevel: "off" }); + await plain.invoke("models-3", "list_available_models"); + assert.deepEqual(plain.last().data.thinkingLevels, ["off"]); + assert.deepEqual(plain.last().data.current, { provider: "anthropic", id: "claude-luna", thinkingLevel: "off" }); + // Pi's placeholder before any model is chosen is no current model. + const fresh = harness(t, fake.registry, { model: { id: "unknown", name: "unknown", api: "unknown", provider: "unknown", reasoning: false, input: [] }, thinkingLevel: "off" }); + await fresh.invoke("models-4", "list_available_models"); + assert.deepEqual(fresh.last().data.thinkingLevels, ["off"]); + assert.equal("current" in fresh.last().data, false); +}); + +test("list_available_models is bounded, takes no params, and is unavailable without the snapshot", async (t) => { + const many = Array.from({ length: DESKTOP_AUTH_LIMITS.models + 5 }, (_, n) => ({ provider: "p", id: `m-${n}` })); + const fake = fakeRegistry(); + Object.assign(fake.registry, { getAvailable: () => many }); + const app = harness(t, fake.registry); + await app.invoke("big", "list_available_models"); + assert.equal(app.last().data.models.length, DESKTOP_AUTH_LIMITS.models); + assert.equal(app.last().data.truncated, true); + await app.invoke("params", "list_available_models", { provider: "anthropic" }); + assert.deepEqual(app.last().error, INVALID_LIST_AVAILABLE_MODELS); + const old = harness(t, fakeRegistry().registry); + await old.invoke("old", "list_available_models"); + assert.deepEqual(old.last().error, AUTH_UNAVAILABLE); + Object.assign(fake.registry, { getAvailable: () => { throw new Error("/home/me/.pi/agent/models.json broke"); } }); + await app.invoke("throws", "list_available_models"); + assert.deepEqual(app.last().error, AUTH_UNAVAILABLE); + assert.equal(app.widgets.at(-1)!.includes("models.json"), false); }); // ---- get_auth_status ---- @@ -112,8 +192,8 @@ test("get_auth_status lists providers with configured, type, and source, and nev ok: true, data: { providers: [ - { provider: "anthropic", displayName: "Anthropic", configured: true, type: "oauth", source: "stored" }, - { provider: "openai-codex", displayName: "OpenAI Codex", configured: true, type: "api_key", source: "models_json" }, + { provider: "anthropic", displayName: "Anthropic", configured: true, type: "oauth", source: "stored", loginKinds: ["oauth", "api_key"] }, + { provider: "openai-codex", displayName: "OpenAI Codex", configured: true, type: "api_key", source: "models_json", loginKinds: ["oauth", "device"] }, ], truncated: false, }, @@ -127,7 +207,7 @@ test("get_auth_status lists providers with configured, type, and source, and nev test("an unconfigured provider has no type and no source", async (t) => { const app = harness(t, fakeRegistry().registry); await app.invoke("auth-2", "get_auth_status"); - assert.deepEqual(app.last().data.providers[0], { provider: "anthropic", displayName: "Anthropic", configured: false, type: null, source: null }); + assert.deepEqual(app.last().data.providers[0], { provider: "anthropic", displayName: "Anthropic", configured: false, type: null, source: null, loginKinds: ["oauth", "api_key"] }); }); test("get_auth_status rejects params and answers auth_unavailable without a registry", async (t) => { @@ -155,7 +235,7 @@ test("reload_credentials refreshes the registry offline and answers the new stat assert.equal(response.data.reloaded, true); assert.equal(response.data.aborted, false); assert.deepEqual(response.data.failedProviders, ["openai-codex"]); - assert.deepEqual(response.data.providers.find((row: { provider: string }) => row.provider === "anthropic"), { provider: "anthropic", displayName: "Anthropic", configured: true, type: "oauth", source: "stored" }); + assert.deepEqual(response.data.providers.find((row: { provider: string }) => row.provider === "anthropic"), { provider: "anthropic", displayName: "Anthropic", configured: true, type: "oauth", source: "stored", loginKinds: ["oauth", "api_key"] }); assert.equal(app.widgets.at(-1)!.includes("example.invalid"), false, "refresh error text never crosses"); assert.equal(fake.calls.secretReads, 0); }); @@ -223,12 +303,25 @@ test("an environment label never crosses and repeated reads never refresh", asyn for (let i = 0; i < 3; i++) await app.invoke(`g${i}`, "get_auth_status"); assert.deepEqual(fake.calls.refresh, []); assert.equal(app.widgets.some((line) => line.includes("ANTHROPIC_API_KEY")), false); - assert.deepEqual(app.last().data.providers[0], { provider: "anthropic", displayName: "Anthropic", configured: true, type: "api_key", source: "environment" }); + assert.deepEqual(app.last().data.providers[0], { provider: "anthropic", displayName: "Anthropic", configured: true, type: "api_key", source: "environment", loginKinds: ["oauth", "api_key"] }); }); test("an unknown source is null and a throwing display name falls back to the id", () => { const result = projectAuthStatus({ getAll: () => [{ provider: "x" }], getProviderAuthStatus: () => ({ configured: true, source: "configured provider" }), getProviderDisplayName: () => { throw new Error("boom"); }, isUsingOAuth: () => false, refresh: async () => ({ aborted: false, errors: new Map() }) }); - assert.deepEqual(result.providers, [{ provider: "x", displayName: "x", configured: true, type: "api_key", source: null }]); + assert.deepEqual(result.providers, [{ provider: "x", displayName: "x", configured: true, type: "api_key", source: null, loginKinds: [] }]); +}); + +test("loginKinds says which sign-ins a provider definition offers, never reading a credential", () => { + const apiKey = { login: async () => ({}) }; + assert.deepEqual(loginKinds("anthropic", { auth: { oauth: {}, apiKey } }), ["oauth", "api_key"]); + assert.deepEqual(loginKinds("github-copilot", { auth: { oauth: {} } }), ["device"]); + assert.deepEqual(loginKinds("openai-codex", { auth: { oauth: {}, apiKey } }), ["oauth", "device", "api_key"]); + // Ambient-only providers (no key setup) and unknown ones offer nothing. + assert.deepEqual(loginKinds("amazon-bedrock", { auth: { apiKey: {} } }), []); + assert.deepEqual(loginKinds("gone", undefined), []); + // A throwing definition read is no sign-in, not a failed answer. + const result = projectAuthStatus({ getAll: () => [{ provider: "x" }], getProviderAuthStatus: () => ({ configured: false }), getProvider: () => { throw new Error("boom"); }, isUsingOAuth: () => false, refresh: async () => ({ aborted: false, errors: new Map() }) }); + assert.deepEqual(result.providers[0]!.loginKinds, []); }); // ---- Native review advisories (review-00bf531659b82903) ---- diff --git a/tests/desktop-rpc-background-subagents.test.ts b/tests/desktop-rpc-background-subagents.test.ts index 0cf68b9b3..f7be113be 100644 --- a/tests/desktop-rpc-background-subagents.test.ts +++ b/tests/desktop-rpc-background-subagents.test.ts @@ -91,7 +91,7 @@ test("the Desktop transport advertises both methods once and no new event", asyn await commands.get("gentle:desktop")!.handler(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "cap", method: "capabilities", params: {} }), host); const data = JSON.parse(widgets.at(-1)!).data; for (const method of DESKTOP_BACKGROUND_SUBAGENTS_METHODS) assert.equal(data.methods.filter((name: string) => name === method).length, 1); - assert.deepEqual(data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); // ---- The real owner ---- diff --git a/tests/desktop-rpc-changes.test.ts b/tests/desktop-rpc-changes.test.ts index a5951a7f5..4351d130a 100644 --- a/tests/desktop-rpc-changes.test.ts +++ b/tests/desktop-rpc-changes.test.ts @@ -257,7 +257,7 @@ test("capabilities advertise get_changes and get_change_diff and no changes even await a.fire("session_start"); const response = await a.call("capabilities"); for (const method of DESKTOP_CHANGES_METHODS) assert.ok(response.data.methods.includes(method), method); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"], "reads advertise no event"); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"], "reads advertise no event"); await a.fire("session_shutdown"); }); diff --git a/tests/desktop-rpc-config-pi-files.test.ts b/tests/desktop-rpc-config-pi-files.test.ts new file mode 100644 index 000000000..f401e1ae2 --- /dev/null +++ b/tests/desktop-rpc-config-pi-files.test.ts @@ -0,0 +1,343 @@ +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { pathToFileURL } from "node:url"; +import { getPackageDir, ModelRegistry, ModelRuntime, type ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { DesktopConfigBridge } from "../lib/desktop-rpc-config.ts"; +import { SECRET_MARKER } from "../lib/pi-user-config.ts"; + +// Pi's own custom models (`/models.json`, `custom_models`) and MCP +// servers (`/mcp.json`, `/.pi/mcp.json`, `mcp`) as config +// stores: clients read and write them through get_config/set_config, never the +// files, and never see a secret. Every home is a temp directory. + +type Watch = { dir: string; onChange: (filename: string | undefined) => void }; + +function env(t: test.TestContext, context: Record = {}) { + const root = mkdtempSync(join(tmpdir(), "desktop-config-pi-files-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const configHome = join(root, "config"); + const agentHome = join(root, "agent"); + const workspace = join(root, "workspace"); + for (const dir of [configHome, agentHome, workspace]) mkdirSync(dir, { recursive: true }); + const watches: Watch[] = []; + const debounced: Array<() => void> = []; + const bridge = new DesktopConfigBridge({ configHome, agentHome }, { + // The debounce window closes when the test says so (`elapse`), never on the wall clock. + timers: { + set: (fn) => { + debounced.push(fn); + return fn; + }, + clear: (handle) => { + const index = debounced.indexOf(handle as () => void); + if (index !== -1) debounced.splice(index, 1); + }, + }, + watch: (dir, onChange) => { + const watch = { dir, onChange }; + watches.push(watch); + return () => watches.splice(watches.indexOf(watch), 1); + }, + }); + const ctx = { cwd: workspace, ...context } as unknown as ExtensionContext; + bridge.attach(ctx); + return { + root, + agentHome, + workspace, + bridge, + ctx, + watches, + /** Closes every open debounce window, then lets the owner re-reads finish. */ + async elapse(): Promise { + for (const fn of debounced.splice(0)) fn(); + await ticks(); + }, + models: join(agentHome, "models.json"), + globalMcp: join(agentHome, "mcp.json"), + projectMcp: join(workspace, ".pi", "mcp.json"), + async read(store: string): Promise { + const outcome = await bridge.handle("get_config", { store }); + assert.ok(outcome?.ok, JSON.stringify(outcome)); + return outcome.data; + }, + async revision(store: string, target = "global"): Promise { + return (await this.read(store)).writeTargets.find((entry: any) => entry.target === target).writeRevision; + }, + async write(store: string, data: unknown, expectedRevision?: string): Promise { + const target = store === "mcp" && (data as any)?.source === "project" ? "project" : "global"; + return bridge.handle("set_config", { store, data, expectedRevision: expectedRevision ?? await this.revision(store, target) }); + }, + }; +} + +function writeJson(path: string, value: unknown): void { + mkdirSync(join(path, ".."), { recursive: true }); + writeFileSync(path, JSON.stringify(value, null, 2)); +} + +/** Lets queued owner work (`setImmediate`, settled promises) run; no wall-clock wait. */ +async function ticks(): Promise { + for (let index = 0; index < 10; index += 1) { + const { promise, resolve } = Promise.withResolvers(); + setImmediate(resolve); + await promise; + } +} + +const PROVIDER = { + baseUrl: "http://127.0.0.1:11434/v1", + api: "openai-completions", + apiKey: "sk-local-secret", + headers: { "X-Team": "team-secret" }, + models: [ + { id: "llama-big", headers: { "X-Model": "model-secret" } }, + { id: "llama-small", contextWindow: 32000 }, + ], + modelOverrides: { "llama-big": { headers: { "X-Override": "override-secret" } } }, +}; + +// ---- custom_models ---- + +test("custom models read Pi's models.json as Pi does, with every secret redacted", async (t) => { + const e = env(t); + const empty = await e.read("custom_models"); + assert.deepEqual([empty.status, empty.scope, empty.readOnly, empty.value], ["missing", "global", false, undefined]); + assert.deepEqual(empty.layers, [{ source: "global", status: "missing" }]); + // Pi accepts `//` comments and trailing commas in models.json. + writeFileSync(e.models, `{\n // local models\n "providers": { "local": ${JSON.stringify(PROVIDER)}, },\n}\n`); + const read = await e.read("custom_models"); + assert.equal(read.status, "ok"); + assert.deepEqual(read.value, { + providers: { + local: { + ...PROVIDER, + apiKey: SECRET_MARKER, + headers: { "X-Team": SECRET_MARKER }, + models: [{ id: "llama-big", headers: { "X-Model": SECRET_MARKER } }, { id: "llama-small", contextWindow: 32000 }], + modelOverrides: { "llama-big": { headers: { "X-Override": SECRET_MARKER } } }, + }, + }, + }); + assert.equal(JSON.stringify(read).includes("secret\""), false, "no secret crosses"); + writeJson(e.models, { providers: { local: { ...PROVIDER, apiKey: "sk-rotated" } } }); + assert.notEqual((await e.read("custom_models")).revision, read.revision, "a secret changed elsewhere moves the revision"); + writeJson(e.models, { providers: { local: { models: [{ id: "" }] } } }); + const invalid = await e.read("custom_models"); + assert.deepEqual([invalid.status, invalid.value], ["invalid", undefined], "Pi's schema refuses an empty model id"); +}); + +test("a custom models write keeps redacted secrets in place and replaces the file atomically", async (t) => { + const e = env(t); + writeJson(e.models, { providers: { local: PROVIDER } }); + const read = await e.read("custom_models"); + const local = read.value.providers.local; + // Reordered models still keep their own headers: models are matched by id. + const data = { providers: { local: { ...local, name: "Local", models: [local.models[1], local.models[0]], headers: { "X-Team": "new-team" } } } }; + const outcome = await e.write("custom_models", data); + assert.equal(outcome.ok, true, JSON.stringify(outcome)); + assert.deepEqual([outcome.data.changed, outcome.data.writeTarget, outcome.event?.name, outcome.event?.data.source], [true, "global", "config_changed", "desktop"]); + assert.deepEqual(outcome.data.value, { providers: { local: { ...data.providers.local, headers: { "X-Team": SECRET_MARKER } } } }, "the answer is the re-read store, a new secret redacted too"); + const written = JSON.parse(readFileSync(e.models, "utf8")); + assert.equal(written.providers.local.apiKey, "sk-local-secret"); + assert.deepEqual(written.providers.local.headers, { "X-Team": "new-team" }); + assert.deepEqual(written.providers.local.models, [PROVIDER.models[1], PROVIDER.models[0]]); + assert.deepEqual(written.providers.local.modelOverrides, PROVIDER.modelOverrides); + if (process.platform !== "win32") assert.equal(statSync(e.models).mode & 0o777, 0o600, "a file holding keys is owner-only"); + const same = await e.write("custom_models", outcome.data.value); + assert.deepEqual([same.ok, same.data.changed, same.event], [true, false, undefined]); +}); + +test("a custom models write is refused when Pi would refuse it, or when a marker has nothing to keep", async (t) => { + const e = env(t); + for (const [data, message] of [ + [{}, /providers/], + [{ providers: { local: { models: [{ id: "" }] } } }, /providers\.local\.models\.0\.id/], + [{ providers: { local: { apiKey: 3 } } }, /providers\.local\.apiKey/], + [{ providers: { local: { apiKey: SECRET_MARKER } } }, /providers\.local\.apiKey: "•••" keeps a stored value/], + [[], /root/], + ] as const) { + const outcome = await e.write("custom_models", data); + assert.equal(outcome.error?.code, "invalid_data", JSON.stringify(data)); + assert.match(outcome.error.message, message); + assert.match(outcome.error.message, /^Invalid custom_models data: /); + } + assert.equal(existsSync(e.models), false); + const stale = await e.revision("custom_models"); + writeJson(e.models, { providers: {} }); + assert.equal((await e.write("custom_models", { providers: { x: { models: [] } } }, stale)).error?.code, "revision_conflict"); + const unproven = await e.bridge.handle("set_config", { store: "custom_models", data: { providers: {} } }); + assert.equal(unproven?.ok === false ? unproven.error.code : undefined, "revision_conflict", "a write without expectedRevision proves nothing"); + // An unreadable file is replaced whole: nothing of it is kept. + writeFileSync(e.models, "{ not json"); + assert.equal((await e.read("custom_models")).status, "invalid"); + assert.equal((await e.write("custom_models", { providers: {} })).ok, true); + assert.deepEqual(JSON.parse(readFileSync(e.models, "utf8")), { providers: {} }); +}); + +test("a custom models write refreshes the session's model registry before answering", async (t) => { + const root = mkdtempSync(join(tmpdir(), "desktop-config-registry-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const agentHome = join(root, "agent"); + mkdirSync(agentHome, { recursive: true }); + const runtime = await ModelRuntime.create({ + authPath: join(agentHome, "auth.json"), + modelsPath: join(agentHome, "models.json"), + modelsStorePath: join(agentHome, "models-store.json"), + allowModelNetwork: false, + refreshOnCreate: false, + }); + const registry = new ModelRegistry(runtime); + const bridge = new DesktopConfigBridge({ configHome: join(root, "config"), agentHome }); + bridge.attach({ cwd: root, modelRegistry: registry } as unknown as ExtensionContext); + assert.equal(registry.find("desk-local", "desk-model"), undefined); + const read: any = await bridge.handle("get_config", { store: "custom_models" }); + const outcome: any = await bridge.handle("set_config", { + store: "custom_models", + data: { providers: { "desk-local": { baseUrl: "http://127.0.0.1:9/v1", api: "openai-completions", apiKey: "local", models: [{ id: "desk-model" }] } } }, + expectedRevision: read.data.writeTargets[0].writeRevision, + }); + assert.equal(outcome.ok, true, JSON.stringify(outcome)); + assert.ok(registry.find("desk-local", "desk-model"), "the new custom model is in the registry at once"); +}); + +test("an outside models.json edit emits config_changed and refreshes the registry; an outside mcp.json edit emits config_changed", async (t) => { + let refreshes = 0; + const e = env(t, { modelRegistry: { refresh: async () => { refreshes += 1; } }, isProjectTrusted: () => true }); + const events: any[] = []; + mkdirSync(join(e.workspace, ".pi"), { recursive: true }); + e.bridge.wire((event, data) => events.push({ event, data })); + writeJson(e.models, { providers: {} }); + for (const watch of e.watches.filter((entry) => entry.dir === e.agentHome)) watch.onChange("models.json"); + await e.elapse(); + assert.deepEqual(events.map((entry) => [entry.event, entry.data.store, entry.data.source, entry.data.status]), [["config_changed", "custom_models", "external", "ok"]]); + assert.equal(refreshes, 1); + assert.equal(JSON.stringify(events).includes(e.root), false, "no path on the wire"); + writeJson(e.projectMcp, { mcpServers: { tool: { command: "node" } } }); + for (const watch of e.watches.filter((entry) => entry.dir === join(e.workspace, ".pi"))) watch.onChange("mcp.json"); + await e.elapse(); + assert.deepEqual(events.slice(1).map((entry) => [entry.data.store, entry.data.scope, entry.data.source]), [["mcp", "global+project", "external"]]); + assert.equal(refreshes, 1, "only a models change refreshes the registry"); +}); + +// ---- mcp ---- + +const GLOBAL_MCP = { + autoEnableCodemode: false, + mcpServers: { + files: { command: "npx", args: ["-y", "server-filesystem", "."], env: { TOKEN: "env-secret", HOME_DIR: "${HOME}" } }, + docs: { url: "https://docs.example/mcp", headers: { Authorization: "Bearer header-secret" }, oauth: { clientId: "id", clientSecret: "oauth-secret" } }, + }, +}; + +test("the mcp store lists the servers Pi loads and each layer Pi reads whole, secrets redacted", async (t) => { + const e = env(t); + const empty = await e.read("mcp"); + assert.deepEqual([empty.status, empty.scope, empty.readOnly, empty.value], ["missing", "global+project", false, undefined]); + assert.deepEqual(empty.writeTargets.map((entry: any) => [entry.target, entry.status]), [["global", "missing"]], "an untrusted project's file is no write target"); + writeJson(e.globalMcp, GLOBAL_MCP); + writeJson(e.projectMcp, { mcpServers: { files: { enabled: false } } }); + const read = await e.read("mcp"); + assert.equal(read.status, "ok"); + assert.deepEqual(read.value, { + servers: [{ name: "files", transport: "stdio", enabled: true }, { name: "docs", transport: "http", enabled: true }], + truncated: false, + omitted: 0, + documents: { + global: { + autoEnableCodemode: false, + mcpServers: { + files: { ...GLOBAL_MCP.mcpServers.files, env: { TOKEN: SECRET_MARKER, HOME_DIR: SECRET_MARKER } }, + docs: { ...GLOBAL_MCP.mcpServers.docs, headers: { Authorization: SECRET_MARKER }, oauth: { clientId: "id", clientSecret: SECRET_MARKER } }, + }, + }, + }, + }, "Pi does not read an untrusted project's mcp.json, so neither does the store"); + assert.deepEqual(read.layers, [{ source: "global", status: "ok" }]); + const trusted = env(t, { isProjectTrusted: () => true }); + writeJson(trusted.projectMcp, { mcpServers: { files: { enabled: false } } }); + const project = await trusted.read("mcp"); + assert.deepEqual(project.value, { servers: [], truncated: false, omitted: 0, documents: { project: { mcpServers: { files: { enabled: false } } } } }); + assert.deepEqual(project.writeTargets.map((entry: any) => [entry.target, entry.status]), [["global", "missing"], ["project", "ok"]]); + writeFileSync(trusted.globalMcp, JSON.stringify({ mcpServers: [] })); + const layers = (await trusted.read("mcp")).layers; + assert.deepEqual(layers, [{ source: "global", status: "invalid" }, { source: "project", status: "ok" }]); + // A secret changed outside moves the revision even though the client never sees it. + writeJson(e.globalMcp, { ...GLOBAL_MCP, mcpServers: { ...GLOBAL_MCP.mcpServers, files: { ...GLOBAL_MCP.mcpServers.files, env: { TOKEN: "rotated", HOME_DIR: "${HOME}" } } } }); + const rotated = await e.read("mcp"); + assert.deepEqual(rotated.value, read.value); + assert.notEqual(rotated.revision, read.revision); +}); + +test("an MCP write replaces one layer, keeps redacted secrets of the same server, and reloads the session once idle", async (t) => { + let reloads = 0; + let idleWaits = 0; + const e = env(t, { waitForIdle: async () => { idleWaits += 1; }, reload: async () => { reloads += 1; } }); + writeJson(e.globalMcp, GLOBAL_MCP); + const read = await e.read("mcp"); + const document = structuredClone(read.value.documents.global); + document.mcpServers.files.env.EXTRA = "extra-value"; + document.mcpServers.docs.headers = { Authorization: SECRET_MARKER, "X-New": "new" }; + document.mcpServers.search = { url: "https://search.example/mcp", exposure: "direct" }; + const outcome = await e.write("mcp", { source: "global", document }); + assert.equal(outcome.ok, true, JSON.stringify(outcome)); + assert.deepEqual([outcome.data.writeTarget, outcome.data.changed, outcome.event?.data.writeTarget], ["global", true, "global"]); + const written = JSON.parse(readFileSync(e.globalMcp, "utf8")); + assert.deepEqual(written.mcpServers.files.env, { TOKEN: "env-secret", HOME_DIR: "${HOME}", EXTRA: "extra-value" }); + assert.deepEqual(written.mcpServers.docs.headers, { Authorization: "Bearer header-secret", "X-New": "new" }); + assert.equal(written.mcpServers.docs.oauth.clientSecret, "oauth-secret"); + assert.equal(written.autoEnableCodemode, false, "other keys are the client's document"); + assert.equal(reloads, 0, "the reload waits until the answer is out"); + await ticks(); + assert.deepEqual([idleWaits, reloads], [1, 1]); + // What the reloaded session loads: Pi's own MCP loader over the same home (not in Pi's exports, so loaded by path). + const { loadMcpConfig } = await import(pathToFileURL(join(getPackageDir(), "dist", "extensions", "mcp", "config.js")).href); + const loaded = loadMcpConfig({ agentDir: e.agentHome, cwd: e.workspace, projectTrusted: false }); + assert.deepEqual(loaded.errors, []); + assert.deepEqual(loaded.servers.map((server: any) => server.name), ["files", "docs", "search"]); + assert.equal(loaded.servers.find((server: any) => server.name === "docs").config.headers.Authorization, "Bearer header-secret"); + const same = await e.write("mcp", { source: "global", document: outcome.data.value.documents.global }); + assert.deepEqual([same.ok, same.data.changed], [true, false]); + await ticks(); + assert.equal(reloads, 1, "no change, no reload"); + // A marker moved to another server has nothing to keep there. + const moved = await e.write("mcp", { source: "global", document: { mcpServers: { other: { command: "x", env: { TOKEN: SECRET_MARKER } } } } }); + assert.equal(moved.error?.code, "invalid_data"); + assert.match(moved.error.message, /mcpServers\.other\.env\.TOKEN/); +}); + +test("an MCP write is checked as Pi loads each layer, and a project layer only for a trusted project", async (t) => { + const untrusted = env(t); + const refused = await untrusted.bridge.handle("set_config", { store: "mcp", data: { source: "project", document: { mcpServers: {} } }, expectedRevision: "sha256:any" }); + assert.deepEqual(refused, { ok: false, error: { code: "project_untrusted", message: "Pi reads this project's files only once the project is trusted" } }); + assert.equal(existsSync(untrusted.projectMcp), false); + const e = env(t, { isProjectTrusted: () => true }); + writeJson(e.globalMcp, GLOBAL_MCP); + for (const [data, message] of [ + [{ source: "global", document: { mcpServers: { broken: { args: ["x"] } } } }, /broken/], + [{ source: "global", document: { mcpServers: { tool: { command: "x", env: { A: 1 } } } } }, /tool/], + [{ source: "global", document: { mcpServers: { "my-tool": { command: "x" }, my_tool: { command: "y" } } } }, /conflicts/], + [{ source: "global", document: { mcpServers: [] } }, /mcpServers/], + [{ source: "global", document: { autoEnableCodemode: "yes" } }, /autoEnableCodemode/], + [{ source: "project", document: { mcpServers: { unknown: { enabled: false } } } }, /global server to override/], + [{ source: "project", document: { mcpServers: { files: { enabled: false, description: "x" } } } }, /an override can only set/], + [{ source: "project", document: { mcpServers: { api: { url: "https://api.example/mcp", auth: { provider: "anthropic" } } } } }, /auth is only allowed in the global/], + ] as const) { + const outcome = await e.write("mcp", data); + assert.equal(outcome.error?.code, "invalid_data", JSON.stringify(data)); + assert.match(outcome.error.message, message); + } + for (const data of [{ document: {} }, { source: "local", document: {} }, { source: "global" }, { source: "global", document: {}, path: "/tmp/x" }]) { + assert.equal((await e.write("mcp", data)).error?.code, "invalid_data", JSON.stringify(data)); + } + assert.equal(existsSync(e.projectMcp), false); + const override = await e.write("mcp", { source: "project", document: { mcpServers: { files: { enabled: false, exposure: "direct" } } } }); + assert.equal(override.ok, true, JSON.stringify(override)); + assert.deepEqual(JSON.parse(readFileSync(e.projectMcp, "utf8")), { mcpServers: { files: { enabled: false, exposure: "direct" } } }); + // Each layer has its own write revision: a global token cannot write the project file. + const globalToken = await e.revision("mcp", "global"); + assert.equal((await e.write("mcp", { source: "project", document: { mcpServers: {} } }, globalToken)).error?.code, "revision_conflict"); +}); diff --git a/tests/desktop-rpc-config-readonly-stores.test.ts b/tests/desktop-rpc-config-readonly-stores.test.ts index ade7998a5..731e9a950 100644 --- a/tests/desktop-rpc-config-readonly-stores.test.ts +++ b/tests/desktop-rpc-config-readonly-stores.test.ts @@ -6,10 +6,12 @@ import { test } from "node:test"; import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; import { DESKTOP_CONFIG_STORES, DesktopConfigBridge, configWatchTargets } from "../lib/desktop-rpc-config.ts"; -// The read-only `mcp`, `pi_settings`, and `claude_bridge` config stores -// (gentle-shell-gpui parity, round 2): display projections of files Pi or a -// third-party package own. Every test runs in an isolated temporary root and -// plants secret-shaped values that must never reach the wire. +// The `mcp`, `pi_settings`, and `claude_bridge` config stores (gentle-shell-gpui +// parity, round 2): projections of files Pi or a third-party package own. +// `claude_bridge` is read-only; the writes of `mcp` and `pi_settings` are tested +// in desktop-rpc-config-pi-files and desktop-rpc-config-settings. Every test +// runs in an isolated temporary root and plants secret-shaped values that must +// never reach the wire. const SECRET_TOKEN = "sk-live-SECRET-TOKEN-0123456789"; const SECRET_HEADER = "Bearer HEADER-SECRET-abcdef"; @@ -52,7 +54,7 @@ function assertNoLeak(answer: unknown, root: string, extra: string[] = []): void // ---- store list ---- -test("the store list keeps every existing store in order and appends the read-only display stores", () => { +test("the store list keeps every existing store in order and appends Pi's stores", () => { assert.deepEqual([...DESKTOP_CONFIG_STORES], [ "profiles", "models", @@ -66,20 +68,19 @@ test("the store list keeps every existing store in order and appends the read-on "mcp", "pi_settings", "claude_bridge", + "custom_models", ]); }); -test("set_config refuses every new store as read_only and writes nothing", async (t) => { +test("set_config refuses claude_bridge as read_only and writes nothing", async (t) => { const e = env(t); - for (const store of ["mcp", "pi_settings", "claude_bridge"]) { - const outcome = await e.bridge.handle("set_config", { store, data: {}, expectedRevision: "sha256:x" }); - assert.equal(outcome?.ok, false, JSON.stringify(outcome)); - assert.equal((outcome as { error: { code: string } }).error.code, "read_only"); - const read = await e.read(store); - assert.equal(read.readOnly, true); - assert.equal(read.writeTargets, undefined, "a read-only store reports no write target"); - assert.equal(read.status, "missing", "a refused write creates nothing"); - } + const outcome = await e.bridge.handle("set_config", { store: "claude_bridge", data: {}, expectedRevision: "sha256:x" }); + assert.equal(outcome?.ok, false, JSON.stringify(outcome)); + assert.equal((outcome as { error: { code: string } }).error.code, "read_only"); + const read = await e.read("claude_bridge"); + assert.equal(read.readOnly, true); + assert.equal(read.writeTargets, undefined, "a read-only store reports no write target"); + assert.equal(read.status, "missing", "a refused write creates nothing"); }); test("the owner files of the new stores are watched for external changes", async (t) => { @@ -95,31 +96,40 @@ test("the owner files of the new stores are watched for external changes", async // ---- mcp ---- -test("mcp lists name, transport, and enabled only, never env, headers, args, command, url, or cwd", async (t) => { +test("mcp lists name, transport, and enabled, and its documents never carry env, header, OAuth or URL credentials", async (t) => { const e = env(t); writeJson(join(e.agentHome, "mcp.json"), { mcpServers: { filesystem: { command: "npx", args: ["-y", ABSOLUTE_PATH], env: { API_TOKEN: SECRET_TOKEN }, cwd: ABSOLUTE_PATH }, docs: { url: "https://user:pass@docs.example.com/mcp", headers: { Authorization: SECRET_HEADER }, enabled: false }, sentry: { type: "http", url: "https://mcp.sentry.example/mcp", oauth: { clientSecret: SECRET_TOKEN } }, + keyed: { url: "https://keyed.example/mcp?api_key=query-secret" }, }, }); const data = await e.read("mcp"); assert.equal(data.store, "mcp"); assert.equal(data.scope, "global+project"); - assert.equal(data.readOnly, true); + assert.equal(data.readOnly, false); assert.equal(data.status, "ok"); assert.deepEqual(data.layers, [{ source: "global", status: "ok" }, { source: "project", status: "missing" }]); - assert.deepEqual(data.value, { + const { documents, ...summary } = data.value; + assert.deepEqual(summary, { servers: [ { name: "filesystem", transport: "stdio", enabled: true }, { name: "docs", transport: "http", enabled: false }, { name: "sentry", transport: "http", enabled: true }, + { name: "keyed", transport: "http", enabled: true }, ], truncated: false, omitted: 0, }); - assertNoLeak(data, e.root, ["npx", "docs.example.com", "user:pass", "mcp.sentry.example", "API_TOKEN", "Authorization"]); + assertNoLeak(summary, e.root, ["npx", "docs.example.com", "user:pass", "mcp.sentry.example", "API_TOKEN", "Authorization"]); + // The documents are what a client edits: command, args, and cwd are the user's own; credentials never cross. + assert.deepEqual(documents.global.mcpServers.filesystem, { command: "npx", args: ["-y", ABSOLUTE_PATH], env: { API_TOKEN: "•••" }, cwd: ABSOLUTE_PATH }); + assert.deepEqual(documents.global.mcpServers.docs, { url: "•••", headers: { Authorization: "•••" }, enabled: false }); + assert.deepEqual(documents.global.mcpServers.keyed, { url: "•••" }); + const wire = JSON.stringify(data); + for (const secret of [SECRET_TOKEN, SECRET_HEADER, "user:pass", "query-secret", e.root]) assert.equal(wire.includes(secret), false, `the answer leaks ${secret}`); }); test("mcp merges a trusted project file like Pi: replacements, enabled-only overrides, and new servers", async (t) => { @@ -146,7 +156,9 @@ test("mcp merges a trusted project file like Pi: replacements, enabled-only over { name: "shared", transport: "http", enabled: true }, { name: "local", transport: "stdio", enabled: true }, ], "an override without a global server and a project `auth` server are skipped, exactly as Pi skips them"); - assertNoLeak(data, e.root, ["internal.example", "project-cmd", "TOKEN"]); + assertNoLeak(data.value.servers, e.root, ["internal.example", "project-cmd", "TOKEN"]); + assert.equal(JSON.stringify(data.value.documents).includes(SECRET_TOKEN), false); + assert.equal(JSON.stringify(data.value.documents).includes(SECRET_HEADER), false); }); test("mcp ignores the project file of an untrusted project, as Pi does", async (t) => { @@ -186,8 +198,9 @@ test("mcp counts over-long server names as omitted, never as a cut at the bound" const long = "n".repeat(129); writeJson(join(e.agentHome, "mcp.json"), { mcpServers: { [long]: { command: "x" }, short: { command: "y" } } }); const data = await e.read("mcp"); - assert.deepEqual(data.value, { servers: [{ name: "short", transport: "stdio", enabled: true }], truncated: false, omitted: 1 }); - assertNoLeak(data, e.root, [long]); + assert.deepEqual(data.value.servers, [{ name: "short", transport: "stdio", enabled: true }]); + assert.deepEqual([data.value.truncated, data.value.omitted], [false, 1]); + assertNoLeak(data.value.servers, e.root, [long]); }); test("mcp reports the transport Pi connects with for an entry with both command and url", async (t) => { @@ -220,7 +233,7 @@ test("pi_settings projects only the default model and thinking, enabled models, const data = await e.read("pi_settings"); assert.equal(data.store, "pi_settings"); assert.equal(data.scope, "global+project"); - assert.equal(data.readOnly, true); + assert.equal(data.readOnly, false); assert.equal(data.status, "ok"); assert.deepEqual(data.layers, [{ source: "global", status: "ok" }, { source: "project", status: "missing" }]); assert.deepEqual(data.value, { diff --git a/tests/desktop-rpc-config-settings.test.ts b/tests/desktop-rpc-config-settings.test.ts index afec2b563..0292613b5 100644 --- a/tests/desktop-rpc-config-settings.test.ts +++ b/tests/desktop-rpc-config-settings.test.ts @@ -12,7 +12,7 @@ import { DEFAULT_NOTIFICATION_SETTINGS, NOTIFICATION_EVENTS, NOTIFICATION_SCHEMA // parity, T3): read and written through the same get_config/set_config // contract as the profile stores, by their own owners. -function env(t: test.TestContext) { +function env(t: test.TestContext, context: Record = {}) { const root = mkdtempSync(join(tmpdir(), "desktop-config-settings-")); t.after(() => rmSync(root, { recursive: true, force: true })); const configHome = join(root, "config"); @@ -20,10 +20,11 @@ function env(t: test.TestContext) { const workspace = join(root, "workspace"); for (const dir of [configHome, agentHome, workspace]) mkdirSync(dir, { recursive: true }); const bridge = new DesktopConfigBridge({ configHome, agentHome }); - bridge.attach({ cwd: workspace } as unknown as ExtensionContext); + bridge.attach({ cwd: workspace, ...context } as unknown as ExtensionContext); return { root, configHome, + agentHome, workspace, bridge, projectPersona: join(workspace, ".pi", "gentle-ai", "persona.json"), @@ -232,3 +233,86 @@ test("an unknown or prototype event key is rejected, never silently dropped", as assert.equal((await e.write("notifications", withProto)).error?.code, "invalid_data"); assert.equal(existsSync(join(e.configHome, "notifications.json")), false); }); + +// ---- pi_settings: Pi's settings.json model keys (Configuration › Models) ---- + +test("pi_settings reads Pi's merged display view and writes the global file's model keys", async (t) => { + const e = env(t); + const empty = await e.read("pi_settings"); + assert.deepEqual([empty.status, empty.scope, empty.readOnly, empty.value], ["missing", "global+project", false, undefined]); + assert.deepEqual(empty.writeTargets.map((entry: any) => [entry.target, entry.status]), [["global", "missing"]]); + writeFileSync(join(e.agentHome, "settings.json"), JSON.stringify({ packages: ["npm:x"], theme: "dark", defaultProvider: "anthropic", defaultModel: "claude-opus", defaultThinkingLevel: "high", enabledModels: ["anthropic/*", "openai/gpt-5"] })); + const read = await e.read("pi_settings"); + assert.equal(read.status, "ok"); + assert.deepEqual(read.value, { defaultProvider: "anthropic", defaultModel: "claude-opus", defaultThinkingLevel: "high", enabledModels: ["anthropic/*", "openai/gpt-5"], extensions: [], truncated: false }); +}); + +test("a pi_settings write patches the model keys and keeps every other settings key", async (t) => { + const e = env(t); + const path = join(e.agentHome, "settings.json"); + writeFileSync(path, JSON.stringify({ packages: ["npm:x"], defaultProvider: "anthropic", defaultModel: "claude-opus", defaultThinkingLevel: "high" })); + const patch = { defaultProvider: "openai", defaultModel: "gpt-5", defaultThinkingLevel: null, enabledModels: ["openai/gpt-5", "anthropic/claude-opus"] }; + const outcome = await e.write("pi_settings", patch); + assert.equal(outcome.ok, true, JSON.stringify(outcome)); + assert.equal(outcome.data.changed, true); + assert.equal(outcome.event?.name, "config_changed"); + assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), { packages: ["npm:x"], defaultProvider: "openai", defaultModel: "gpt-5", enabledModels: ["openai/gpt-5", "anthropic/claude-opus"] }, "null removes a key"); + assert.equal(outcome.data.value.defaultModel, "gpt-5"); + const same = await e.write("pi_settings", patch); + assert.deepEqual([same.ok, same.data.changed, same.event], [true, false, undefined]); + assert.equal((await e.write("pi_settings", { defaultModel: "gpt-5-mini" })).ok, true); + assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), { packages: ["npm:x"], defaultProvider: "openai", defaultModel: "gpt-5-mini", enabledModels: ["openai/gpt-5", "anthropic/claude-opus"] }, "a key the patch leaves out keeps its value"); + assert.deepEqual([(await e.write("pi_settings", {})).data.changed], [false]); + assert.equal((await e.write("pi_settings", { defaultProvider: null, defaultModel: null, enabledModels: null })).ok, true); + assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), { packages: ["npm:x"] }); +}); + +test("a pi_settings write goes to the global file even when a trusted project's file wins the merge", async (t) => { + const e = env(t, { isProjectTrusted: () => true }); + mkdirSync(join(e.workspace, ".pi"), { recursive: true }); + writeFileSync(join(e.workspace, ".pi", "settings.json"), JSON.stringify({ defaultModel: "project-model" })); + const outcome = await e.write("pi_settings", { defaultModel: "global-model" }); + assert.equal(outcome.ok, true, JSON.stringify(outcome)); + assert.deepEqual(JSON.parse(readFileSync(join(e.agentHome, "settings.json"), "utf8")), { defaultModel: "global-model" }); + assert.deepEqual(JSON.parse(readFileSync(join(e.workspace, ".pi", "settings.json"), "utf8")), { defaultModel: "project-model" }); + assert.equal(outcome.data.value.defaultModel, "project-model", "the store shows what Pi runs with"); + assert.deepEqual(outcome.data.layers, [{ source: "global", status: "ok" }, { source: "project", status: "ok" }]); +}); + +test("a pi_settings write validates every key and never replaces an unreadable settings file", async (t) => { + const e = env(t); + for (const data of [ + { theme: "dark" }, + { extensions: [] }, + { truncated: false }, + { defaultProvider: "" }, + { defaultModel: 3 }, + { defaultThinkingLevel: "extreme" }, + { enabledModels: "openai/gpt-5" }, + { enabledModels: ["a", "a"] }, + { enabledModels: ["bad\nline"] }, + [], + ]) { + assert.equal((await e.write("pi_settings", data)).error?.code, "invalid_data", JSON.stringify(data)); + } + assert.equal(existsSync(join(e.agentHome, "settings.json")), false); + const stale = await e.revision("pi_settings"); + writeFileSync(join(e.agentHome, "settings.json"), JSON.stringify({ defaultModel: "x" })); + assert.equal((await e.write("pi_settings", { defaultModel: "y" }, stale)).error?.code, "revision_conflict"); + writeFileSync(join(e.agentHome, "settings.json"), "{ not json"); + const broken = await e.read("pi_settings"); + assert.equal(broken.status, "invalid"); + assert.equal((await e.write("pi_settings", { defaultModel: "y" })).error?.code, "write_failed"); + assert.equal(readFileSync(join(e.agentHome, "settings.json"), "utf8"), "{ not json"); +}); + +test("a pi_settings write waits for a profile apply, which also sets the orchestrator", async (t) => { + const e = env(t); + const revision = await e.revision("pi_settings"); + beginDesktopProfileApply(); + try { + assert.equal((await e.write("pi_settings", { defaultModel: "y" }, revision)).error?.code, "profile_apply_busy"); + } finally { + endDesktopProfileApply(); + } +}); diff --git a/tests/desktop-rpc-config.test.ts b/tests/desktop-rpc-config.test.ts index 3d56fd286..e92929461 100644 --- a/tests/desktop-rpc-config.test.ts +++ b/tests/desktop-rpc-config.test.ts @@ -539,7 +539,7 @@ test("get_config rejects unknown stores, unsupported params, and physical paths" assert.deepEqual(DESKTOP_CONFIG_METHODS, ["get_config", "set_config"]); assert.deepEqual([...DESKTOP_CONFIG_EVENTS], ["config_changed"]); - assert.deepEqual([...DESKTOP_CONFIG_STORES], ["profiles", "models", "profile_fallbacks", "subagents", "pins", "managed_assets", "persona", "banner", "notifications", "mcp", "pi_settings", "claude_bridge"]); + assert.deepEqual([...DESKTOP_CONFIG_STORES], ["profiles", "models", "profile_fallbacks", "subagents", "pins", "managed_assets", "persona", "banner", "notifications", "mcp", "pi_settings", "claude_bridge", "custom_models"]); }); test("reads never mutate any store", async (t) => { @@ -599,9 +599,10 @@ test("stores carry the documented read-only split", async (t) => { persona: false, banner: false, notifications: false, - mcp: true, - pi_settings: true, + mcp: false, + pi_settings: false, claude_bridge: true, + custom_models: false, }); }); @@ -885,7 +886,7 @@ test("read-only and unknown stores reject writes without creating anything", asy const bridge = bridgeFor(env); const before = snapshotTree(env.root); - for (const store of ["models", "subagents", "managed_assets", "mcp", "pi_settings", "claude_bridge"]) { + for (const store of ["models", "subagents", "managed_assets", "claude_bridge"]) { const outcome = await setConfig(bridge, { store, data: {}, expectedRevision: "sha256:x" }); assertError(outcome, "read_only"); } @@ -1354,8 +1355,23 @@ test("capabilities advertise the wired config read and write surface", async (t) "clear_profile_binding", "get_auth_status", "reload_credentials", + "list_available_models", + "set_host_tools", + "host_tool_result", + "host_tool_progress", + "host_message", + "set_host_context", + "set_host_activity", + "login_start", + "login_complete", + "login_cancel", + "set_api_key", + "remove_credentials", + "list_packages", + "install_package", + "remove_package", ]); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); test("get_config answers through the transport with no physical path in the response", async (t) => { diff --git a/tests/desktop-rpc-design.test.ts b/tests/desktop-rpc-design.test.ts index f66f59a3b..f594fa7a8 100644 --- a/tests/desktop-rpc-design.test.ts +++ b/tests/desktop-rpc-design.test.ts @@ -650,8 +650,23 @@ test("the Desktop transport advertises the design method and event", async (t) = "clear_profile_binding", "get_auth_status", "reload_credentials", + "list_available_models", + "set_host_tools", + "host_tool_result", + "host_tool_progress", + "host_message", + "set_host_context", + "set_host_activity", + "login_start", + "login_complete", + "login_cancel", + "set_api_key", + "remove_credentials", + "list_packages", + "install_package", + "remove_package", ]); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); test("get_design_canvas answers design_unavailable through the transport without an owner extension", async (t) => { diff --git a/tests/desktop-rpc-host-tools.test.ts b/tests/desktop-rpc-host-tools.test.ts new file mode 100644 index 000000000..a1ab06fd5 --- /dev/null +++ b/tests/desktop-rpc-host-tools.test.ts @@ -0,0 +1,753 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import type { AssistantMessage, JsonObject, ToolCall } from "@earendil-works/pi-ai"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import desktopRpc from "../extensions/gentle-desktop-rpc.ts"; +import { DESKTOP_RPC_SCHEMA } from "../lib/desktop-rpc.ts"; +import { + ALREADY_ANSWERED, + DESKTOP_HOST_TOOLS_EVENTS, + DESKTOP_HOST_TOOLS_LIMITS, + DESKTOP_HOST_TOOLS_METHODS, + DETAILS_TOO_LARGE, + HOST_TOOL_RESULT_TOO_LARGE, + hostToolOfflineText, + INVALID_HOST_MESSAGE, + INVALID_HOST_TOOL_PROGRESS, + INVALID_SET_HOST_ACTIVITY, + INVALID_SET_HOST_CONTEXT, + MESSAGE_TOO_LARGE, + modelGuidelines, + parseHostMessage, + parseHostToolProgress, + parseHostToolResult, + parseSetHostContext, + parseSetHostTools, + TOO_MANY_CONTEXTS, + UNKNOWN_CALL, +} from "../lib/desktop-rpc-host-tools.ts"; +import { INTERACTIVE_HOST_ENV } from "../lib/rpc-host.ts"; + +// Host tools: a Desktop client offers tools that run on the client. The agent +// calls them like any tool; the call becomes a `host_tool_call` event and the +// client's `host_tool_result` becomes the tool result. Unit tests drive the real +// extension over a fake Pi tool registry; the last tests run a real Pi SDK +// session with an offline scripted provider (no model) to prove registration, +// guidelines, results and aborts reach Pi the way the model would see them. + +const SCHEMA = { type: "object", properties: { region: { type: "string" } }, required: ["region"] }; + +function spec(name: string, extra: Record = {}) { + return { name, label: `Label ${name}`, description: `Does ${name} on the client.\nMore detail.`, parameters: SCHEMA, ...extra }; +} + +interface FakeTimer { callback: () => void; ms: number } + +function setInteractiveHost(t: test.TestContext) { + const previous = process.env[INTERACTIVE_HOST_ENV]; + process.env[INTERACTIVE_HOST_ENV] = "1"; + t.after(() => { + if (previous === undefined) delete process.env[INTERACTIVE_HOST_ENV]; + else process.env[INTERACTIVE_HOST_ENV] = previous; + }); +} + +function harness(t: test.TestContext) { + setInteractiveHost(t); + const commands = new Map Promise }>(); + const handlers = new Map unknown>>(); + /** What Pi holds: the last definition registered under each name. */ + const registry = new Map(); + const registrations: any[] = []; + const timers = new Map(); + let nextTimer = 0; + let nextCall = 0; + let clock = 1_000_000; + const sent: Array<{ message: any; options: any }> = []; + let idle = true; + const pi = { + registerCommand(name: string, command: any) { commands.set(name, command); }, + registerShortcut() {}, + on(name: string, handler: any) { + handlers.set(name, [...(handlers.get(name) ?? []), handler]); + return () => handlers.set(name, (handlers.get(name) ?? []).filter((h) => h !== handler)); + }, + events: { on() { return () => {}; }, emit() {} }, + registerTool(definition: any) { registry.set(definition.name, definition); registrations.push(definition); }, + getAllTools() { + return [{ name: "read" }, { name: "bash" }, { name: "gentle_todo" }, ...[...registry.keys()].map((name) => ({ name }))]; + }, + sendMessage(message: any, options: any) { sent.push({ message, options }); }, + } as unknown as ExtensionAPI; + desktopRpc(pi, { + hostTools: { + timers: { + setTimeout(callback, ms) { nextTimer += 1; timers.set(nextTimer, { callback, ms }); return nextTimer; }, + clearTimeout(handle) { timers.delete(handle as number); }, + }, + newCallId: () => `call-${(nextCall += 1)}`, + now: () => clock, + }, + }); + const widgets: string[] = []; + const ctx = { + mode: "rpc", + cwd: "/x", + sessionManager: { getCwd: () => "/x", getSessionId: () => "s", getEntries: () => [] }, + ui: { setWidget(_key: string, lines: string[]) { widgets.push(...lines); } }, + isIdle: () => idle, + }; + for (const handler of handlers.get("session_start") ?? []) handler({}, ctx); + let request = 0; + const lines = () => widgets.map((line) => JSON.parse(line)); + return { + registry, + registrations, + timers, + advance(ms: number) { clock += ms; }, + widgets, + sent, + setIdle(value: boolean) { idle = value; }, + /** What Pi's `before_agent_start` would collect: one message per handler that returned one. */ + async beforeAgentStart() { + const messages: any[] = []; + for (const handler of handlers.get("before_agent_start") ?? []) { + const result: any = await handler({ type: "before_agent_start", messageType: "user", prompt: "hi" }, ctx); + if (result?.message) messages.push(result.message); + } + return messages; + }, + async start() { for (const handler of handlers.get("session_start") ?? []) await handler({}, ctx); }, + raw(text: string) { return commands.get("gentle:desktop")!.handler(text, ctx); }, + async invoke(method: string, params: Record = {}) { + request += 1; + const requestId = `r-${request}`; + await commands.get("gentle:desktop")!.handler(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId, method, params }), ctx); + const response = lines().find((line) => line.kind === "response" && line.requestId === requestId); + assert.ok(response, `a response to ${method}`); + return response; + }, + events(name: string) { return lines().filter((line) => line.kind === "event" && line.event === name).map((line) => line.data); }, + async shutdown() { for (const handler of handlers.get("session_shutdown") ?? []) await handler({}, ctx); }, + }; +} + +// ---- Contract ---- + +test("the Desktop transport advertises the host tool methods and both events once", async (t) => { + assert.deepEqual([...DESKTOP_HOST_TOOLS_METHODS], ["set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context", "set_host_activity"]); + assert.deepEqual([...DESKTOP_HOST_TOOLS_EVENTS], ["host_tool_call", "host_tool_cancel"]); + const app = harness(t); + const caps = await app.invoke("capabilities"); + for (const name of DESKTOP_HOST_TOOLS_METHODS) assert.equal(caps.data.methods.filter((m: string) => m === name).length, 1); + for (const name of DESKTOP_HOST_TOOLS_EVENTS) assert.equal(caps.data.events.filter((e: string) => e === name).length, 1); + assert.equal(app.registrations.length, 0, "nothing is registered with Pi until a client asks"); +}); + +test("set_host_tools validates the provider, every tool and the limits", () => { + const bad = (params: Record) => { + const parsed = parseSetHostTools(params); + assert.equal(parsed.ok, false, JSON.stringify(params).slice(0, 120)); + if (!parsed.ok) assert.equal(parsed.error.code, "invalid_request"); + }; + assert.equal(parseSetHostTools({ provider: "app", tools: [] }).ok, true, "an empty list unregisters"); + bad({ tools: [] }); + bad({ provider: "", tools: [] }); + bad({ provider: "x".repeat(65), tools: [] }); + bad({ provider: "app\n", tools: [] }); + bad({ provider: "app", tools: [], extra: 1 }); + bad({ provider: "app", tools: "nope" }); + bad({ provider: "app", tools: Array.from({ length: 33 }, (_, i) => spec(`t${i}`)) }); + bad({ provider: "app", tools: [spec("Bad-Name")] }); + bad({ provider: "app", tools: [spec("a".repeat(65))] }); + bad({ provider: "app", tools: [spec("dup"), spec("dup")] }); + bad({ provider: "app", tools: [spec("t", { label: "x".repeat(65) })] }); + bad({ provider: "app", tools: [spec("t", { description: "x".repeat(4097) })] }); + bad({ provider: "app", tools: [spec("t", { parameters: { type: "string" } })] }); + bad({ provider: "app", tools: [spec("t", { parameters: [] })] }); + bad({ provider: "app", tools: [spec("t", { parameters: { type: "object", description: "x".repeat(16 * 1024) } })] }); + bad({ provider: "app", tools: [spec("t", { guidelines: Array.from({ length: 17 }, () => "Use t.") })] }); + bad({ provider: "app", tools: [spec("t", { guidelines: ["x".repeat(513)] })] }); + bad({ provider: "app", tools: [spec("t", { guidelines: ["two\nlines"] })] }); + bad({ provider: "app", tools: [spec("t", { run: "rm -rf /" })] }); + const full = parseSetHostTools({ provider: "app", tools: Array.from({ length: 32 }, (_, i) => spec(`t${i}`, { guidelines: Array.from({ length: 16 }, () => "g".repeat(512)) })) }); + assert.equal(full.ok, true, "the limits themselves are allowed"); +}); + +test("host_tool_result validates content and caps it at 8 MiB of text bytes and base64", () => { + assert.deepEqual(parseHostToolResult({ callId: "c", content: [{ type: "text", text: "hi" }] }), { ok: true, value: { callId: "c", content: [{ type: "text", text: "hi" }], isError: false } }); + for (const params of [ + { content: [{ type: "text", text: "x" }] }, + { callId: "", content: [{ type: "text", text: "x" }] }, + { callId: "c", content: [] }, + { callId: "c", content: [{ type: "video", data: "AAAA" }] }, + { callId: "c", content: [{ type: "image", data: "not base64!", mimeType: "image/png" }] }, + { callId: "c", content: [{ type: "image", data: "AAAA", mimeType: "text/html" }] }, + { callId: "c", content: [{ type: "text", text: "x" }], isError: "yes" }, + { callId: "c", content: [{ type: "text", text: "x" }], extra: true }, + ]) assert.equal(parseHostToolResult(params as Record).ok, false, JSON.stringify(params)); + const limit = DESKTOP_HOST_TOOLS_LIMITS.contentBytes; + const image = "A".repeat(limit - 4); + assert.equal(parseHostToolResult({ callId: "c", content: [{ type: "image", data: image, mimeType: "image/png" }, { type: "text", text: "four" }] }).ok, true); + assert.deepEqual(parseHostToolResult({ callId: "c", content: [{ type: "image", data: image, mimeType: "image/png" }, { type: "text", text: "fives" }] }), { ok: false, error: HOST_TOOL_RESULT_TOO_LARGE }); +}); + +// ---- Registration ---- + +test("set_host_tools registers each tool with Pi as a direct tool with its schema, snippet and guidelines", async (t) => { + const app = harness(t); + const response = await app.invoke("set_host_tools", { provider: "gentle-desktop", tools: [ + spec("desktop_screenshot", { guidelines: ["Use desktop_screenshot to see what the user sees.", "Ask before capturing private windows."] }), + spec("desktop_open_url"), + ] }); + assert.deepEqual(response.data, { registered: ["desktop_screenshot", "desktop_open_url"], rejected: [] }); + const shot = app.registry.get("desktop_screenshot"); + assert.equal(shot.exposure, "direct"); + assert.equal(shot.label, "Label desktop_screenshot"); + assert.equal(shot.description, "Does desktop_screenshot on the client.\nMore detail."); + assert.deepEqual(shot.parameters, SCHEMA); + assert.equal(shot.promptSnippet, "Does desktop_screenshot on the client."); + assert.deepEqual(shot.promptGuidelines, ["Use desktop_screenshot to see what the user sees.", "desktop_screenshot: Ask before capturing private windows."], "a guideline that does not name its tool gets the name"); + assert.equal(app.registry.get("desktop_open_url").promptGuidelines, undefined); + assert.deepEqual(modelGuidelines({ name: "x_y", guidelines: ["Use x_y."] }), ["Use x_y."]); +}); + +test("names held by a built-in or an extension are rejected; another provider's host tool name is shared", async (t) => { + const app = harness(t); + await app.invoke("set_host_tools", { provider: "phone", tools: [spec("device_camera")] }); + const response = await app.invoke("set_host_tools", { provider: "desktop", tools: [spec("read"), spec("gentle_todo"), spec("device_camera"), spec("desktop_clip")] }); + assert.deepEqual(response.data, { + registered: ["device_camera", "desktop_clip"], + rejected: [ + { name: "read", reason: "A built-in or extension tool already has this name" }, + { name: "gentle_todo", reason: "A built-in or extension tool already has this name" }, + ], + }); + assert.equal(app.registry.get("device_camera").exposure, "direct"); + assert.equal(app.registry.has("read"), false, "a built-in is never overridden"); +}); + +test("two providers of one name: the newest definition is the one tool the model sees; unregistering falls back", async (t) => { + const app = harness(t); + await app.invoke("set_host_tools", { provider: "mac", tools: [spec("device_screenshot", { description: "Mac screenshot." })] }); + await app.invoke("set_host_tools", { provider: "phone", tools: [spec("device_screenshot", { description: "Phone screenshot.", parameters: { type: "object", properties: {} } })] }); + assert.equal(app.registry.get("device_screenshot").description, "Phone screenshot.", "the most recent registration's definition"); + assert.deepEqual(app.registry.get("device_screenshot").parameters, { type: "object", properties: {} }); + await app.invoke("set_host_tools", { provider: "mac", tools: [spec("device_screenshot", { description: "Mac screenshot, again." })] }); + assert.equal(app.registry.get("device_screenshot").description, "Mac screenshot, again.", "registering again makes it the newest"); + await app.invoke("set_host_tools", { provider: "mac", tools: [] }); + assert.equal(app.registry.get("device_screenshot").description, "Phone screenshot.", "the next provider's definition takes over"); + assert.equal(app.registry.get("device_screenshot").exposure, "direct"); + const pending = app.registry.get("device_screenshot").execute("m", {}, undefined, undefined, {}); + assert.equal(app.events("host_tool_call").at(-1).provider, "phone", "calls go to the provider that still offers it"); + await app.invoke("host_tool_result", { callId: "call-1", content: [{ type: "text", text: "ok" }] }); + await pending; + await app.invoke("set_host_tools", { provider: "phone", tools: [] }); + assert.equal(app.registry.get("device_screenshot").exposure, "hidden", "the last provider leaving hides it"); +}); + +test("a call goes to the most recently active connected provider, else the next, else the newest registration", async (t) => { + const app = harness(t); + await app.invoke("set_host_tools", { provider: "mac", tools: [spec("device_screenshot")] }); + await app.invoke("set_host_tools", { provider: "phone", tools: [spec("device_screenshot")] }); + await app.invoke("set_host_tools", { provider: "watch", tools: [spec("watch_face")] }); + const tool = app.registry.get("device_screenshot"); + const callTo = async () => { + const pending = tool.execute("m", { region: "x" }, undefined, undefined, {}); + const call = app.events("host_tool_call").at(-1); + await app.invoke("host_tool_result", { callId: call.callId, content: [{ type: "text", text: "ok" }] }); + await pending; + return call.provider; + }; + assert.equal(await callTo(), "phone", "over stdio (no activity list): the newest registration"); + assert.deepEqual((await app.invoke("set_host_activity", { providers: ["mac", "phone"] })).data, { set: true }); + assert.equal(await callTo(), "mac", "the last active device runs it"); + await app.invoke("set_host_activity", { providers: ["watch", "phone", "mac"] }); + assert.equal(await callTo(), "phone", "the most recently active one that offers the tool"); + await app.invoke("set_host_activity", { providers: ["mac"] }); + assert.equal(await callTo(), "mac", "the phone went offline: the next active provider that is connected"); + await app.invoke("set_host_activity", { providers: ["watch"] }); + assert.equal(await callTo(), "phone", "nobody offering it is connected: the newest registration (serve answers it offline at once)"); + for (const params of [{}, { providers: "mac" }, { providers: [""] }, { providers: ["a", "a"] }, { providers: Array.from({ length: 65 }, (_, i) => `p${i}`) }, { providers: [], extra: 1 }]) { + assert.deepEqual((await app.invoke("set_host_activity", params)).error, INVALID_SET_HOST_ACTIVITY, JSON.stringify(params).slice(0, 80)); + } + await app.invoke("set_host_activity", { providers: ["mac"] }); + await app.shutdown(); + await app.start(); + await app.invoke("set_host_tools", { provider: "mac", tools: [spec("device_screenshot")] }); + await app.invoke("set_host_tools", { provider: "phone", tools: [spec("device_screenshot")] }); + const fresh = app.registry.get("device_screenshot"); + const pending = fresh.execute("m", { region: "x" }, undefined, undefined, {}); + assert.equal(app.events("host_tool_call").at(-1).provider, "phone", "a session change forgets the activity list"); + await app.invoke("host_tool_result", { callId: app.events("host_tool_call").at(-1).callId, content: [{ type: "text", text: "ok" }] }); + await pending; +}); + +test("a provider's new set replaces its old one; dropped and unregistered tools become hidden and free", async (t) => { + const app = harness(t); + await app.invoke("set_host_tools", { provider: "desktop", tools: [spec("desktop_a"), spec("desktop_b")] }); + await app.invoke("set_host_tools", { provider: "desktop", tools: [spec("desktop_b", { description: "Newer b." })] }); + assert.equal(app.registry.get("desktop_a").exposure, "hidden", "Pi cannot drop a tool: hidden is unreachable and never declared"); + assert.equal(app.registry.get("desktop_a").promptGuidelines, undefined); + assert.equal(app.registry.get("desktop_b").exposure, "direct"); + assert.equal(app.registry.get("desktop_b").description, "Newer b."); + const empty = await app.invoke("set_host_tools", { provider: "desktop", tools: [] }); + assert.deepEqual(empty.data, { registered: [], rejected: [] }); + assert.equal(app.registry.get("desktop_b").exposure, "hidden"); + const other = await app.invoke("set_host_tools", { provider: "phone", tools: [spec("desktop_a")] }); + assert.deepEqual(other.data, { registered: ["desktop_a"], rejected: [] }, "a hidden host tool name is free"); + assert.equal(app.registry.get("desktop_a").exposure, "direct"); +}); + +test("invalid set_host_tools leaves the registry untouched", async (t) => { + const app = harness(t); + await app.invoke("set_host_tools", { provider: "desktop", tools: [spec("desktop_a")] }); + const response = await app.invoke("set_host_tools", { provider: "desktop", tools: [spec("desktop_a"), spec("BAD")] }); + assert.equal(response.ok, false); + assert.equal(response.error.code, "invalid_request"); + assert.equal(app.registry.get("desktop_a").exposure, "direct"); +}); + +// ---- Calls ---- + +async function registerOne(app: ReturnType, name = "desktop_shot") { + await app.invoke("set_host_tools", { provider: "desktop", tools: [spec(name)] }); + return app.registry.get(name); +} + +test("a call emits host_tool_call; the first result settles it, a second is already_answered, a stranger unknown_call", async (t) => { + const app = harness(t); + const tool = await registerOne(app); + const pending = tool.execute("model-call-1", { region: "main" }, new AbortController().signal, undefined, {}); + assert.deepEqual(app.events("host_tool_call"), [{ callId: "call-1", provider: "desktop", tool: "desktop_shot", args: { region: "main" } }]); + assert.equal(app.timers.size, 1, "the 10-minute cap is armed"); + const accepted = await app.invoke("host_tool_result", { callId: "call-1", content: [{ type: "text", text: "captured" }, { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" }] }); + assert.deepEqual(accepted.data, { accepted: true }); + assert.deepEqual(await pending, { content: [{ type: "text", text: "captured" }, { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" }], details: { provider: "desktop", callId: "call-1" } }); + assert.equal(app.timers.size, 0, "the cap is disarmed"); + assert.deepEqual((await app.invoke("host_tool_result", { callId: "call-1", content: [{ type: "text", text: "again" }] })).error, ALREADY_ANSWERED); + assert.deepEqual((await app.invoke("host_tool_result", { callId: "nope", content: [{ type: "text", text: "x" }] })).error, UNKNOWN_CALL); + assert.deepEqual(app.events("host_tool_cancel"), []); +}); + +test("isError reaches Pi as an error result the model reads", async (t) => { + const app = harness(t); + const tool = await registerOne(app); + const pending = tool.execute("m", { region: "x" }, undefined, undefined, {}); + await app.invoke("host_tool_result", { callId: "call-1", content: [{ type: "text", text: "Screen recording is off" }], isError: true }); + assert.deepEqual(await pending, { content: [{ type: "text", text: "Screen recording is off" }], details: { provider: "desktop", callId: "call-1" }, isError: true }); +}); + +test("aborting the turn cancels the call: host_tool_cancel goes out and a late result is already_answered", async (t) => { + const app = harness(t); + const tool = await registerOne(app); + const abort = new AbortController(); + const pending = tool.execute("m", { region: "x" }, abort.signal, undefined, {}); + abort.abort(); + const result = await pending; + assert.equal(result.isError, true); + assert.match(result.content[0].text, /desktop_shot was cancelled/); + assert.deepEqual(app.events("host_tool_cancel"), [{ callId: "call-1" }]); + assert.equal(app.timers.size, 0); + assert.deepEqual((await app.invoke("host_tool_result", { callId: "call-1", content: [{ type: "text", text: "late" }] })).error, ALREADY_ANSWERED); + const already = new AbortController(); + already.abort(); + assert.equal((await tool.execute("m2", { region: "x" }, already.signal, undefined, {})).isError, true); + assert.equal(app.events("host_tool_call").length, 1, "an already aborted call never goes out"); +}); + +test("a call nobody answers fails after 10 minutes and is cancelled on the client", async (t) => { + const app = harness(t); + const tool = await registerOne(app); + const pending = tool.execute("m", { region: "x" }, undefined, undefined, {}); + const [timer] = [...app.timers.values()]; + assert.equal(timer.ms, 10 * 60 * 1000); + timer.callback(); + const result = await pending; + assert.equal(result.isError, true); + assert.equal(result.content[0].text, "desktop_shot got no answer from desktop within 10 minutes."); + assert.deepEqual(app.events("host_tool_cancel"), [{ callId: "call-1" }]); +}); + +test("host_tool_progress restarts the 10-minute deadline as often as it comes; without it the call still fails", async (t) => { + const app = harness(t); + const tool = await registerOne(app); + const pending = tool.execute("m", { region: "x" }, undefined, undefined, {}); + const [first] = [...app.timers.keys()]; + for (let beat = 1; beat <= 3; beat += 1) { + app.advance(9 * 60 * 1000); + const progress = await app.invoke("host_tool_progress", { callId: "call-1", ...(beat === 2 ? { message: "waiting for review" } : {}) }); + assert.deepEqual(progress.data, { extended: true, deadlineMs: 1_000_000 + beat * 9 * 60 * 1000 + 10 * 60 * 1000 }); + assert.equal(app.timers.size, 1, "one deadline armed at a time"); + assert.equal([...app.timers.values()][0].ms, 10 * 60 * 1000); + } + assert.equal(app.timers.has(first), false, "the original deadline was cleared"); + const [timer] = [...app.timers.values()]; + timer.callback(); + const result = await pending; + assert.equal(result.content[0].text, "desktop_shot got no answer from desktop within 10 minutes."); + assert.deepEqual(app.events("host_tool_cancel"), [{ callId: "call-1" }]); + assert.deepEqual((await app.invoke("host_tool_progress", { callId: "call-1" })).error, ALREADY_ANSWERED); + assert.deepEqual((await app.invoke("host_tool_progress", { callId: "nope" })).error, UNKNOWN_CALL); + assert.equal(app.timers.size, 0, "progress on a settled call arms nothing"); +}); + +test("host_tool_progress validates callId and an optional message up to 512 characters; it keeps 64 KiB", async (t) => { + assert.equal(parseHostToolProgress({ callId: "c" }).ok, true); + assert.equal(parseHostToolProgress({ callId: "c", message: "x".repeat(512) }).ok, true); + for (const params of [{}, { callId: "" }, { callId: 1 }, { callId: "x".repeat(129) }, { callId: "c", message: "x".repeat(513) }, { callId: "c", message: 1 }, { callId: "c", extra: true }]) { + assert.deepEqual(errorOf(parseHostToolProgress(params as Record)), INVALID_HOST_TOOL_PROGRESS); + } + const app = harness(t); + const before = app.widgets.length; + await app.raw(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "big-progress", method: "host_tool_progress", params: { callId: "c", pad: "x".repeat(70 * 1024) } })); + assert.equal(JSON.parse(app.widgets[before]).requestId, null, "over 64 KiB the request is refused before parsing"); +}); + +test("session shutdown fails waiting calls and hides every host tool; a stale definition answers offline", async (t) => { + const app = harness(t); + const tool = await registerOne(app); + const pending = tool.execute("m", { region: "x" }, undefined, undefined, {}); + await app.shutdown(); + const result = await pending; + assert.equal(result.isError, true); + assert.match(result.content[0].text, /session ended/); + assert.equal(app.registry.get("desktop_shot").exposure, "hidden"); + assert.equal((await tool.execute("m", { region: "x" }, undefined, undefined, {})).isError, true); + assert.equal(hostToolOfflineText("desktop_shot", "Ismael's Mac"), "desktop_shot runs in Ismael's Mac, which isn't connected right now."); +}); + +test("host tool requests get larger request caps; every other method keeps 64 KiB", async (t) => { + const app = harness(t); + const tool = await registerOne(app); + const pending = tool.execute("m", { region: "x" }, undefined, undefined, {}); + const big = "A".repeat(2 * 1024 * 1024); + const accepted = await app.invoke("host_tool_result", { callId: "call-1", content: [{ type: "image", data: big, mimeType: "image/png" }] }); + assert.deepEqual(accepted.data, { accepted: true }); + assert.equal(((await pending).content[0] as { data: string }).data.length, big.length); + const before = app.widgets.length; + await app.raw(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "big-snapshot", method: "get_snapshot", params: { pad: "x".repeat(70 * 1024) } })); + assert.deepEqual(JSON.parse(app.widgets[before]).error.code, "invalid_request"); + assert.equal(JSON.parse(app.widgets[before]).requestId, null); + await app.raw(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "huge", method: "host_tool_result", params: { callId: "x", content: [{ type: "text", text: "x".repeat(10 * 1024 * 1024) }] } })); + assert.equal(JSON.parse(app.widgets.at(-1)!).requestId, null, "over 10 MiB the request is refused before parsing"); +}); + +// ---- Result details, host messages and host context ---- + +function errorOf(parsed: { ok: true } | { ok: false; error: unknown }): unknown { + return "error" in parsed ? parsed.error : undefined; +} + +test("host_tool_result details: a JSON object up to 1 MiB becomes the Pi tool result's details", async (t) => { + assert.equal(parseHostToolResult({ callId: "c", content: [{ type: "text", text: "x" }], details: [] }).ok, false); + assert.equal(parseHostToolResult({ callId: "c", content: [{ type: "text", text: "x" }], details: "x" }).ok, false); + assert.deepEqual(parseHostToolResult({ callId: "c", content: [{ type: "text", text: "x" }], details: { pad: "x".repeat(1024 * 1024) } }), { ok: false, error: DETAILS_TOO_LARGE }); + const app = harness(t); + const tool = await registerOne(app); + const pending = tool.execute("m", { region: "x" }, undefined, undefined, {}); + const details = { surface: { id: "s1", version: 3 }, rows: [1, 2] }; + assert.deepEqual((await app.invoke("host_tool_result", { callId: "call-1", content: [{ type: "text", text: "drawn" }], details })).data, { accepted: true }); + assert.deepEqual(await pending, { content: [{ type: "text", text: "drawn" }], details }); +}); + +test("host_message validates its type, content, delivery and details", () => { + const ok = { customType: "host.genui.event", content: "clicked", display: true, deliver: "auto" }; + assert.deepEqual(parseHostMessage(ok), { ok: true, value: ok }); + assert.equal(parseHostMessage({ ...ok, customType: `host.${"a".repeat(64)}` }).ok, true, "64 characters after host. are allowed"); + for (const params of [ + { ...ok, customType: "genui.event" }, + { ...ok, customType: "host." }, + { ...ok, customType: "host.Upper" }, + { ...ok, customType: `host.${"a".repeat(65)}` }, + { ...ok, content: 1 }, + { ...ok, display: "yes" }, + { ...ok, deliver: "now" }, + { ...ok, triggerTurn: 1 }, + { ...ok, details: [] }, + { ...ok, extra: true }, + { customType: "host.x", content: "", deliver: "auto" }, + ]) assert.deepEqual(errorOf(parseHostMessage(params)), INVALID_HOST_MESSAGE, JSON.stringify(params).slice(0, 120)); + assert.equal(parseHostMessage({ ...ok, content: "é".repeat(32 * 1024) }).ok, true, "64 KiB of UTF-8 is allowed"); + assert.deepEqual(parseHostMessage({ ...ok, content: `${"é".repeat(32 * 1024)}x` }), { ok: false, error: MESSAGE_TOO_LARGE }); + assert.deepEqual(parseHostMessage({ ...ok, details: { pad: "x".repeat(1024 * 1024) } }), { ok: false, error: DETAILS_TOO_LARGE }); +}); + +test("host_message calls pi.sendMessage: auto starts a turn when idle and steers while streaming; other modes pass through", async (t) => { + const app = harness(t); + const base = { customType: "host.genui.event", content: "clicked Save", display: true, details: { surface: "s1" } }; + assert.deepEqual((await app.invoke("host_message", { ...base, deliver: "auto" })).data, { delivered: true }); + await app.invoke("host_message", { ...base, deliver: "auto", triggerTurn: false }); + app.setIdle(false); + await app.invoke("host_message", { ...base, deliver: "auto" }); + await app.invoke("host_message", { ...base, deliver: "auto", triggerTurn: false }); + await app.invoke("host_message", { ...base, deliver: "followUp" }); + await app.invoke("host_message", { ...base, deliver: "nextTurn" }); + await app.invoke("host_message", { ...base, deliver: "steer", triggerTurn: true }); + assert.deepEqual(app.sent.map((entry) => entry.options), [ + { triggerTurn: true }, + { triggerTurn: false }, + { deliverAs: "steer" }, + { deliverAs: "steer" }, + { deliverAs: "followUp" }, + { deliverAs: "nextTurn" }, + { deliverAs: "steer", triggerTurn: true }, + ]); + assert.deepEqual(app.sent[0].message, base, "the message reaches Pi as sent"); + const invalid = await app.invoke("host_message", { ...base, deliver: "later" }); + assert.deepEqual(invalid.error, INVALID_HOST_MESSAGE); + assert.equal(app.sent.length, 7, "an invalid message never reaches Pi"); +}); + +test("set_host_context injects one hidden message per provider before each run; empty clears; a session change drops all", async (t) => { + assert.equal(parseSetHostContext({ provider: "app", content: "" }).ok, true, "empty clears"); + for (const params of [{ content: "x" }, { provider: "", content: "x" }, { provider: "app", content: 1 }, { provider: "app", content: "x", details: [] }, { provider: "app", content: "x", extra: 1 }]) { + assert.deepEqual(errorOf(parseSetHostContext(params)), INVALID_SET_HOST_CONTEXT, JSON.stringify(params)); + } + assert.deepEqual(parseSetHostContext({ provider: "app", content: "x".repeat(64 * 1024 + 1) }), { ok: false, error: MESSAGE_TOO_LARGE }); + assert.deepEqual(parseSetHostContext({ provider: "app", content: "x", details: { pad: "x".repeat(1024 * 1024) } }), { ok: false, error: DETAILS_TOO_LARGE }); + + const app = harness(t); + assert.deepEqual(await app.beforeAgentStart(), []); + assert.deepEqual((await app.invoke("set_host_context", { provider: "app", content: "Booted: iPhone 16", details: { devices: 1 } })).data, { set: true }); + await app.invoke("set_host_context", { provider: "phone", content: "Battery low" }); + assert.deepEqual(await app.beforeAgentStart(), [ + { customType: "host.context.app", content: "Booted: iPhone 16", display: false, details: { devices: 1 } }, + { customType: "host.context.phone", content: "Battery low", display: false }, + ]); + await app.invoke("set_host_context", { provider: "app", content: "Booted: Pixel 9" }); + assert.deepEqual(await app.beforeAgentStart(), [ + { customType: "host.context.app", content: "Booted: Pixel 9", display: false }, + { customType: "host.context.phone", content: "Battery low", display: false }, + ], "a new set replaces the provider's context and details"); + await app.invoke("set_host_context", { provider: "phone", content: "" }); + assert.deepEqual((await app.beforeAgentStart()).map((m) => m.customType), ["host.context.app"]); + await app.shutdown(); + await app.start(); + assert.deepEqual(await app.beforeAgentStart(), [], "a session change clears every host context"); + for (let i = 0; i < 16; i += 1) assert.equal((await app.invoke("set_host_context", { provider: `p${i}`, content: "x" })).ok, true); + assert.deepEqual((await app.invoke("set_host_context", { provider: "p16", content: "x" })).error, TOO_MANY_CONTEXTS); + assert.equal((await app.invoke("set_host_context", { provider: "p0", content: "y" })).ok, true, "an existing provider may still update"); +}); + +test("host_message and set_host_context get a 2 MiB request cap", async (t) => { + const app = harness(t); + const response = await app.invoke("set_host_context", { provider: "app", content: "x", details: { pad: "x".repeat(900 * 1024) } }); + assert.deepEqual(response.data, { set: true }); + const message = await app.invoke("host_message", { customType: "host.genui.event", content: "x", display: false, deliver: "nextTurn", details: { pad: "x".repeat(900 * 1024) } }); + assert.deepEqual(message.data, { delivered: true }); +}); + +// ---- A real Pi session ---- + +interface RecordedRequest { systemPrompt: string; tools: string[]; toolResults: Array<{ name: string; isError: boolean; content: unknown[] }>; texts: string[] } + +async function realSession(t: test.TestContext) { + setInteractiveHost(t); + const root = realpathSync(mkdtempSync(join(tmpdir(), "gentle-host-tools-"))); + mkdirSync(join(root, "profile")); + const cwd = join(root, "repo"); + mkdirSync(cwd); + t.after(() => rmSync(root, { recursive: true, force: true })); + const sdk = await import("@earendil-works/pi-coding-agent"); + const ai = await import("@earendil-works/pi-ai"); + const requests: RecordedRequest[] = []; + const queue: Array<{ name: string; arguments: JsonObject } | undefined> = []; + let calls = 0; + const model = { id: "driver", name: "Local driver", provider: "host-fixture", api: "host-fixture", baseUrl: "http://invalid.local", reasoning: false, input: ["text", "image"], contextWindow: 1_000_000, maxTokens: 1024, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } } as const; + const settings = sdk.SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false }, cacheWarming: "off", packages: [] }); + const runtime = await sdk.ModelRuntime.create({ credentials: new ai.InMemoryCredentialStore(), modelsPath: null, modelsStorePath: join(root, "models.json"), refreshOnCreate: false, allowModelNetwork: false }); + const loader = new sdk.DefaultResourceLoader({ + cwd, agentDir: join(root, "profile"), settingsManager: settings, + noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, + extensionFactories: [(pi: ExtensionAPI) => { + desktopRpc(pi); + pi.registerProvider("host-fixture", { + api: "host-fixture", apiKey: "fixture-only", baseUrl: "http://invalid.local", + models: [{ id: model.id, name: model.name, reasoning: false, input: ["text", "image"], cost: model.cost, contextWindow: model.contextWindow, maxTokens: model.maxTokens }], + streamSimple(_model, context) { + requests.push({ + systemPrompt: ai.getCurrentSystemPrompt(context.messages) ?? "", + tools: (ai.getCurrentTools(context.messages) ?? []).map((tool) => tool.name), + toolResults: context.messages.flatMap((message) => message.role === "toolResult" ? [{ name: message.toolName, isError: message.isError, content: message.content }] : []), + // Custom messages reach the model as user messages; their text is what the model reads. + texts: context.messages.flatMap((message) => message.role === "user" ? (typeof message.content === "string" ? [message.content] : message.content.flatMap((part) => part.type === "text" ? [part.text] : [])) : []), + }); + const request = queue.shift(); + calls += 1; + const stream = ai.createAssistantMessageEventStream(); + const message: AssistantMessage = { role: "assistant", api: model.api, provider: model.provider, model: model.id, content: [], stopReason: "pending" as never, timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }; + queueMicrotask(() => { + stream.push({ type: "start", partial: message }); + if (request) { + const toolCall: ToolCall = { type: "toolCall", id: `model-${calls}`, ...request }; + message.content.push(toolCall); + stream.push({ type: "toolcall_start", contentIndex: 0, partial: message }); + stream.push({ type: "toolcall_end", contentIndex: 0, toolCall, partial: message }); + } + message.stopReason = request ? "toolUse" : "stop"; + stream.push({ type: "done", reason: message.stopReason, message }); + stream.end(); + }); + return stream; + }, + }); + }], + }); + await loader.reload(); + assert.deepEqual(loader.getExtensions().errors, []); + const { session } = await sdk.createAgentSession({ + cwd, agentDir: join(root, "profile"), modelRuntime: runtime, model: model as never, thinkingLevel: "off", resourceLoader: loader, + sessionManager: sdk.SessionManager.inMemory(cwd), settingsManager: settings, + }); + const widgets: any[] = []; + const waiters: Array<{ match: (line: any) => boolean; resolve: (line: any) => void }> = []; + // Only the Desktop widget matters here; Pi copies the context's own methods, so this is a plain object. + const ui = { + setWidget(widgetKey: string, lines: unknown) { + if (widgetKey !== "gentle-desktop-rpc" || !Array.isArray(lines)) return; + const line = JSON.parse(lines[0]); + widgets.push(line); + for (const waiter of [...waiters]) if (waiter.match(line)) { waiters.splice(waiters.indexOf(waiter), 1); waiter.resolve(line); } + }, + }; + const errors: string[] = []; + await session.bindExtensions({ mode: "rpc", uiContext: ui as never, onError: (error) => errors.push(error.error) }); + t.after(async () => { + await session.abort(); + session.dispose(); + }); + let request = 0; + const next = (match: (line: any) => boolean) => { + const found = widgets.find(match); + if (found) return Promise.resolve(found); + const { promise, resolve } = Promise.withResolvers(); + waiters.push({ match, resolve }); + return promise; + }; + return { + session, + requests, + queue, + errors, + next, + async desktop(method: string, params: Record) { + request += 1; + const requestId = `real-${request}`; + const answered = next((line) => line.kind === "response" && line.requestId === requestId); + await session.prompt(`/gentle:desktop ${JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId, method, params })}`, { source: "rpc" }); + return answered; + }, + }; +} + +test("real Pi: a registered host tool and its guidelines reach the next request, the call round-trips, unregistering removes both", { timeout: 60_000 }, async (t) => { + const run = await realSession(t); + const guideline = "Use desktop_screenshot when the user mentions what is on their screen."; + const registered = await run.desktop("set_host_tools", { provider: "gentle-desktop", tools: [spec("desktop_screenshot", { guidelines: [guideline] })] }); + assert.deepEqual(registered.data, { registered: ["desktop_screenshot"], rejected: [] }); + const collided = await run.desktop("set_host_tools", { provider: "phone", tools: [spec("bash")] }); + assert.deepEqual(collided.data.rejected, [{ name: "bash", reason: "A built-in or extension tool already has this name" }], "Pi's own tool list decides collisions"); + + run.queue.push({ name: "desktop_screenshot", arguments: { region: "main" } }, undefined); + const turn = run.session.prompt("What is on my screen?", { source: "rpc" }); + const call = await run.next((line) => line.kind === "event" && line.event === "host_tool_call"); + assert.deepEqual({ ...call.data, callId: typeof call.data.callId }, { callId: "string", provider: "gentle-desktop", tool: "desktop_screenshot", args: { region: "main" } }); + const answered = await run.desktop("host_tool_result", { callId: call.data.callId, content: [{ type: "text", text: "A terminal and a browser." }] }); + assert.deepEqual(answered.data, { accepted: true }); + await turn; + + assert.equal(run.requests.length, 2); + assert.ok(run.requests[0].tools.includes("desktop_screenshot"), "declared to the model in the first request after registration"); + assert.ok(run.requests[0].systemPrompt.includes(guideline), "its guideline is in the system prompt"); + assert.ok(run.requests[0].systemPrompt.includes("Does desktop_screenshot on the client."), "its snippet is in the tool list"); + assert.deepEqual(run.requests[1].toolResults.at(-1), { name: "desktop_screenshot", isError: false, content: [{ type: "text", text: "A terminal and a browser." }] }); + + await run.desktop("set_host_tools", { provider: "gentle-desktop", tools: [] }); + run.queue.push(undefined); + await run.session.prompt("And now?", { source: "rpc" }); + const last = run.requests.at(-1)!; + assert.equal(last.tools.includes("desktop_screenshot"), false, "no longer declared"); + assert.equal(last.systemPrompt.includes(guideline), false, "its guideline left the system prompt"); + assert.deepEqual(run.errors, []); +}); + +test("real Pi: aborting the turn sends host_tool_cancel and a late result is already_answered", { timeout: 60_000 }, async (t) => { + const run = await realSession(t); + await run.desktop("set_host_tools", { provider: "gentle-desktop", tools: [spec("desktop_screenshot")] }); + run.queue.push({ name: "desktop_screenshot", arguments: { region: "main" } }, undefined); + const turn = run.session.prompt("Look at my screen.", { source: "rpc" }); + const call = await run.next((line) => line.kind === "event" && line.event === "host_tool_call"); + await run.session.abort(); + await turn; + const cancel = await run.next((line) => line.kind === "event" && line.event === "host_tool_cancel"); + assert.deepEqual(cancel.data, { callId: call.data.callId }); + const late = await run.desktop("host_tool_result", { callId: call.data.callId, content: [{ type: "text", text: "too late" }] }); + assert.deepEqual(late.error, ALREADY_ANSWERED); +}); + +type RealRun = Awaited>; + +/** Resolves when the next run Pi starts on its own (a triggered custom message) has ended. */ +function nextRunEnd(run: RealRun): Promise { + const { promise, resolve } = Promise.withResolvers(); + const off = run.session.subscribe((event) => { + if (event.type !== "agent_end") return; + off(); + resolve(); + }); + return promise; +} + +function customEntries(run: RealRun) { + return run.session.sessionManager.getEntries().flatMap((entry) => entry.type === "custom_message" ? [{ customType: entry.customType, content: entry.content, display: entry.display, details: entry.details }] : []); +} + +test("real Pi: host_message starts a turn when idle and is persisted; host context is injected hidden before each run until cleared", { timeout: 60_000 }, async (t) => { + const run = await realSession(t); + assert.deepEqual((await run.desktop("set_host_context", { provider: "app", content: "Simulators: iPhone 16 booted", details: { booted: ["iPhone 16"] } })).data, { set: true }); + run.queue.push(undefined); + const ended = nextRunEnd(run); + const sent = await run.desktop("host_message", { customType: "host.genui.event", content: "The user clicked Save on surface s1.", display: true, details: { surface: "s1" }, deliver: "auto" }); + assert.deepEqual(sent.data, { delivered: true }); + await ended; + await run.session.waitForIdle(); + assert.deepEqual(run.requests[0].texts, ["The user clicked Save on surface s1.", "Simulators: iPhone 16 booted"], "the message starts the run and the context rides along"); + assert.deepEqual(customEntries(run), [ + { customType: "host.genui.event", content: "The user clicked Save on surface s1.", display: true, details: { surface: "s1" } }, + { customType: "host.context.app", content: "Simulators: iPhone 16 booted", display: false, details: { booted: ["iPhone 16"] } }, + ], "both are session entries, so a client rebuilds its state from get_entries"); + + await run.desktop("host_message", { customType: "host.genui.state", content: "Surface s1 closed.", display: false, deliver: "auto", triggerTurn: false }); + await run.session.waitForIdle(); + assert.equal(run.requests.length, 1, "triggerTurn false only records the message"); + assert.equal(customEntries(run).at(-1)?.customType, "host.genui.state"); + + await run.desktop("set_host_context", { provider: "app", content: "" }); + run.queue.push(undefined); + await run.session.prompt("Anything else?", { source: "rpc" }); + assert.equal(run.requests.length, 2); + assert.equal(run.requests[1].texts.filter((text) => text.startsWith("Simulators:")).length, 1, "a cleared context is not injected again"); + assert.equal(customEntries(run).filter((entry) => entry.customType === "host.context.app").length, 1); + assert.deepEqual(run.errors, []); +}); + +test("real Pi: host_message during a running turn steers it; a result's details become the tool result's details", { timeout: 60_000 }, async (t) => { + const run = await realSession(t); + await run.desktop("set_host_tools", { provider: "gentle-desktop", tools: [spec("desktop_screenshot")] }); + run.queue.push({ name: "desktop_screenshot", arguments: { region: "main" } }, undefined); + const turn = run.session.prompt("Look at my screen.", { source: "rpc" }); + const call = await run.next((line) => line.kind === "event" && line.event === "host_tool_call"); + assert.deepEqual((await run.desktop("host_message", { customType: "host.genui.event", content: "The user also opened Settings.", display: true, deliver: "auto" })).data, { delivered: true }); + const details = { image: { width: 1280, height: 800 }, window: "Terminal" }; + await run.desktop("host_tool_result", { callId: call.data.callId, content: [{ type: "text", text: "A terminal." }], details }); + await turn; + assert.equal(run.requests.length, 2, "the steered message joins the running turn instead of starting another"); + assert.equal(run.requests[1].texts.at(-1), "The user also opened Settings."); + const result = run.session.messages.find((message) => message.role === "toolResult"); + assert.deepEqual(result && "details" in result ? result.details : undefined, details); + assert.deepEqual(run.errors, []); +}); diff --git a/tests/desktop-rpc-jobs.test.ts b/tests/desktop-rpc-jobs.test.ts index ccf7ecfd0..999f53685 100644 --- a/tests/desktop-rpc-jobs.test.ts +++ b/tests/desktop-rpc-jobs.test.ts @@ -624,8 +624,23 @@ test("the Desktop transport advertises the jobs methods and event", (t) => { "clear_profile_binding", "get_auth_status", "reload_credentials", + "list_available_models", + "set_host_tools", + "host_tool_result", + "host_tool_progress", + "host_message", + "set_host_context", + "set_host_activity", + "login_start", + "login_complete", + "login_cancel", + "set_api_key", + "remove_credentials", + "list_packages", + "install_package", + "remove_package", ]); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); test("list_jobs answers jobs_unavailable through the transport without an owner extension", async (t) => { diff --git a/tests/desktop-rpc-login.test.ts b/tests/desktop-rpc-login.test.ts new file mode 100644 index 000000000..73dea4b31 --- /dev/null +++ b/tests/desktop-rpc-login.test.ts @@ -0,0 +1,372 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, test } from "node:test"; +import { ModelRegistry, ModelRuntime, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import desktopRpc, { type DesktopRpcExtensionOptions } from "../extensions/gentle-desktop-rpc.ts"; +import { DESKTOP_RPC_SCHEMA } from "../lib/desktop-rpc.ts"; +import { + DESKTOP_LOGIN_EVENTS, + DESKTOP_LOGIN_METHODS, + INTERACTIVE_SETUP_REQUIRED, + INVALID_CHOICE, + INVALID_SET_API_KEY, + LOGIN_IN_PROGRESS, + LOGIN_UNSUPPORTED, + NO_PENDING_PROMPT, + UNKNOWN_LOGIN, + UNKNOWN_PROVIDER, + promptForEvent, + redirectPrefixOf, +} from "../lib/desktop-rpc-login.ts"; +import { INTERACTIVE_HOST_ENV } from "../lib/rpc-host.ts"; + +// Provider sign-in from a client, end to end through the real Desktop transport +// and Pi's real model runtime and credential store (in a temporary agent home), +// over fake providers registered into that runtime: no real provider is ever +// contacted. The fakes play Pi's flows: a method choice, a browser sign-in whose +// redirect goes to a loopback callback, a device code, and API key setups. + +const roots: string[] = []; +after(() => roots.forEach((root) => rmSync(root, { recursive: true, force: true }))); + +const KEY = "sk-test-NEVER-ON-THE-WIRE-0123456789"; + +type Interaction = { + signal: AbortSignal; + prompt(prompt: Record): Promise; + notify(event: Record): void; +}; + +/** Hooks a test uses to play the provider's side of a flow. */ +interface Remote { + /** The browser reached the server's own loopback callback with this code. */ + callback?: (code: string) => void; + /** The provider approved the device code. */ + approveDevice?: () => void; + signals: AbortSignal[]; +} + +function fakeProvider(id: string, auth: Record) { + const model = { id: `${id}-model`, name: `${id} model`, api: "openai-completions", provider: id, baseUrl: "http://127.0.0.1:9", reasoning: false, input: ["text"], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 1000, maxTokens: 100 }; + return { + id, + name: `Fake ${id}`, + auth, + getModels: () => [model], + stream: () => { throw new Error("no model turns in tests"); }, + streamSimple: () => { throw new Error("no model turns in tests"); }, + }; +} + +const oauthBase = { refresh: async (credential: unknown) => credential, toAuth: async (credential: { access: string }) => ({ apiKey: credential.access }) }; + +/** Like Anthropic's and Codex's: choose a method, then a browser sign-in racing a paste, or a device code. */ +function browserOAuth(remote: Remote) { + return { + ...oauthBase, + name: "Fake browser", + async login(interaction: Interaction) { + remote.signals.push(interaction.signal); + const method = await interaction.prompt({ type: "select", message: "Select login method:", options: [{ id: "browser", label: "Browser login" }, { id: "paste", label: "Copy code login" }] }); + const state = "st4te"; + interaction.notify({ type: "auth_url", url: `https://auth.example.test/authorize?client_id=x&state=${state}&redirect_uri=${encodeURIComponent("http://localhost:1455/auth/callback")}`, instructions: "Complete login in your browser." }); + // Pi's waitForCallbackOrManualInput: the server's own callback races a pasted code or + // redirect URL; a paste cancels the callback, a callback withdraws the paste prompt. + const manual = new AbortController(); + const { promise: callback, resolve: settleCallback } = Promise.withResolvers(); + remote.callback = settleCallback; + let pastedInput: string | undefined; + let pasteError: unknown; + interaction.prompt({ type: "manual_code", message: "Paste the authorization code / redirect URL:", placeholder: "http://localhost:1455/auth/callback", signal: manual.signal }) + .then((value) => { pastedInput = value; }, (error) => { pasteError = error; }) + .finally(() => settleCallback(undefined)); + const fromCallback = await callback; + manual.abort(); + if (fromCallback === undefined && pasteError) throw pasteError; + let code = fromCallback ?? ""; + if (fromCallback === undefined) { + const url = new URL(pastedInput ?? ""); + if (url.searchParams.get("state") !== state) throw new Error("State mismatch"); + code = url.searchParams.get("code") ?? ""; + } + if (!code) throw new Error("Missing authorization code"); + return { type: "oauth", access: `access-${method}-${code}`, refresh: "refresh", expires: Date.now() + 3_600_000 }; + }, + }; +} + +function deviceOAuth(remote: Remote) { + return { + ...oauthBase, + name: "Fake device", + async login(interaction: Interaction) { + remote.signals.push(interaction.signal); + interaction.notify({ type: "device_code", userCode: "WXYZ-1234", verificationUri: "https://device.example.test/activate" }); + interaction.notify({ type: "progress", message: "Waiting for approval..." }); + await new Promise((resolve, reject) => { + remote.approveDevice = resolve; + interaction.signal.addEventListener("abort", () => reject(interaction.signal.reason), { once: true }); + }); + return { type: "oauth", access: "device-access", refresh: "refresh", expires: Date.now() + 3_600_000 }; + }, + }; +} + +function keyAuth(name: string, ask: (interaction: Interaction) => Promise>) { + return { + name, + login: ask, + resolve: async ({ credential }: { credential?: { key?: string } }) => (credential?.key ? { auth: { apiKey: credential.key }, source: "stored credential" } : undefined), + }; +} + +const simpleKey = keyAuth("Fake key", async (interaction) => ({ type: "api_key", key: await interaction.prompt({ type: "secret", message: "Enter Fake key" }) })); +// Like Cloudflare's: an account id first, then the key. +const accountKey = keyAuth("Fake account key", async (interaction) => { + const account = await interaction.prompt({ type: "text", message: "Account id", placeholder: "acc_…" }); + const key = await interaction.prompt({ type: "secret", message: "API token" }); + return { type: "api_key", key, env: { FAKE_ACCOUNT: account } }; +}); + +async function setup(t: test.TestContext, options: DesktopRpcExtensionOptions = {}) { + const previous = process.env[INTERACTIVE_HOST_ENV]; + process.env[INTERACTIVE_HOST_ENV] = "1"; + t.after(() => { + if (previous === undefined) delete process.env[INTERACTIVE_HOST_ENV]; + else process.env[INTERACTIVE_HOST_ENV] = previous; + }); + const agentDir = mkdtempSync(join(tmpdir(), "gs-login-")); + roots.push(agentDir); + const authPath = join(agentDir, "auth.json"); + const runtime = await ModelRuntime.create({ authPath, modelsPath: null, modelsStorePath: join(agentDir, "models-store.json"), refreshOnCreate: false }); + const remote: Remote = { signals: [] }; + for (const provider of [ + fakeProvider("fake-browser", { oauth: browserOAuth(remote), apiKey: simpleKey }), + fakeProvider("fake-device", { oauth: deviceOAuth(remote) }), + fakeProvider("fake-key", { apiKey: simpleKey }), + fakeProvider("fake-account", { apiKey: accountKey }), + fakeProvider("fake-ambient", { apiKey: { name: "Ambient", resolve: async () => undefined } }), + ]) runtime.registerNativeProvider(provider as never); + const registry = new ModelRegistry(runtime); + await registry.refresh({ allowNetwork: false }); + + const commands = new Map Promise }>(); + const handlers = new Map unknown>>(); + const pi = { + registerCommand(name: string, command: { handler: (args: string, ctx: unknown) => Promise }) { commands.set(name, command); }, + registerShortcut() {}, + on(name: string, handler: (event: unknown, ctx: unknown) => unknown) { handlers.set(name, [...(handlers.get(name) ?? []), handler]); }, + events: { on() { return () => {}; }, emit() {} }, + } as unknown as ExtensionAPI; + desktopRpc(pi, options); + const widgets: string[] = []; + const ctx = { + mode: "rpc", + cwd: agentDir, + modelRegistry: registry, + sessionManager: { getCwd: () => agentDir, getSessionId: () => "s", getEntries: () => [] }, + ui: { setWidget(_key: string, lines: string[]) { widgets.push(...lines); } }, + }; + for (const handler of handlers.get("session_start") ?? []) handler({}, ctx); + const parsed = () => widgets.map((line) => JSON.parse(line)); + const app = { + widgets, + authPath, + registry, + remote, + async call(requestId: string, method: string, params: Record = {}) { + await commands.get("gentle:desktop")!.handler(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId, method, params }), ctx); + const response = parsed().findLast((line) => line.kind === "response" && line.requestId === requestId); + assert.ok(response, `a response to ${requestId}`); + return response; + }, + events(name?: string) { + return parsed().filter((line) => line.kind === "event" && (name === undefined || line.event === name)); + }, + /** The next event of a kind after `count` of them were seen. */ + async nextEvent(name: string, count: number) { + const deadline = Date.now() + 5000; + while (app.events(name).length <= count) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${name} #${count + 1}; saw ${JSON.stringify(app.events())}`); + await new Promise((resolve) => setTimeout(resolve, 5)); + } + return app.events(name)[count]!; + }, + stored() { + try { + return JSON.parse(readFileSync(authPath, "utf8")) as Record>; + } catch { + return {}; + } + }, + async shutdown() { for (const handler of handlers.get("session_shutdown") ?? []) await handler({}, ctx); }, + }; + return app; +} + +test("the slice advertises its methods and events", () => { + assert.deepEqual([...DESKTOP_LOGIN_METHODS], ["login_start", "login_complete", "login_cancel", "set_api_key", "remove_credentials"]); + assert.deepEqual([...DESKTOP_LOGIN_EVENTS], ["login_prompt", "login_finished"]); +}); + +test("a browser sign-in: a choice, the URL with its loopback callback, the pasted redirect URL, saved and its models available", async (t) => { + const app = await setup(t); + const status = await app.call("st-0", "get_auth_status"); + assert.deepEqual(status.data.providers.find((row: { provider: string }) => row.provider === "fake-browser"), + { provider: "fake-browser", displayName: "Fake fake-browser", configured: false, type: null, source: null, loginKinds: ["oauth", "api_key"] }); + assert.equal(app.registry.getAvailable().some((model) => model.provider === "fake-browser"), false); + + const started = await app.call("l-1", "login_start", { provider: "fake-browser" }); + assert.equal(started.ok, true); + const { loginId } = started.data; + assert.match(loginId, /^login_[0-9a-f]{16}$/); + const choice = await app.nextEvent("login_prompt", 0); + // The answer precedes the flow's first event. + assert.ok(app.widgets.findIndex((line) => line.includes('"requestId":"l-1"')) < app.widgets.findIndex((line) => line.includes('"event":"login_prompt"'))); + assert.deepEqual(choice.data, { loginId, kind: "input", message: "Select login method:", options: [{ id: "browser", label: "Browser login" }, { id: "paste", label: "Copy code login" }] }); + assert.deepEqual((await app.call("l-2", "login_complete", { loginId, value: "fax" })).error, INVALID_CHOICE); + assert.deepEqual((await app.call("l-3", "login_complete", { loginId, value: "browser" })).data, { accepted: true }); + + const open = await app.nextEvent("login_prompt", 1); + assert.deepEqual(open.data, { + loginId, + kind: "open_url", + url: "https://auth.example.test/authorize?client_id=x&state=st4te&redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback", + message: "Complete login in your browser.", + redirectPrefix: "http://localhost:1455/", + }); + const paste = await app.nextEvent("login_prompt", 2); + assert.deepEqual(paste.data, { loginId, kind: "input", message: "Paste the authorization code / redirect URL:", placeholder: "http://localhost:1455/auth/callback", redirectPrefix: "http://localhost:1455/" }); + // The client intercepted the browser's redirect and hands the full URL over. + assert.deepEqual((await app.call("l-4", "login_complete", { loginId, value: "http://localhost:1455/auth/callback?code=c0de&state=st4te" })).data, { accepted: true }); + const finished = await app.nextEvent("login_finished", 0); + assert.deepEqual(finished.data, { loginId, provider: "fake-browser", ok: true }); + + assert.deepEqual(app.stored()["fake-browser"]?.access, "access-browser-c0de"); + if (process.platform !== "win32") assert.equal(statSync(app.authPath).mode & 0o777, 0o600, "Pi's credential file is owner-only"); + // reload_credentials semantics: the models are there without a restart. + assert.equal(app.registry.getAvailable().some((model) => model.provider === "fake-browser"), true); + const after = await app.call("st-1", "get_auth_status"); + assert.deepEqual(after.data.providers.find((row: { provider: string }) => row.provider === "fake-browser").type, "oauth"); + assert.deepEqual((await app.call("l-5", "login_complete", { loginId, value: "x" })).error, UNKNOWN_LOGIN, "a finished sign-in is gone"); + assert.equal(app.widgets.some((line) => line.includes("access-browser")), false, "no credential crosses"); +}); + +test("a device code sign-in shows the code and the page, then finishes when the provider approves", async (t) => { + const app = await setup(t); + const { data: { loginId } } = await app.call("d-1", "login_start", { provider: "fake-device" }); + assert.deepEqual((await app.nextEvent("login_prompt", 0)).data, { loginId, kind: "device_code", url: "https://device.example.test/activate", userCode: "WXYZ-1234" }); + assert.deepEqual((await app.nextEvent("login_prompt", 1)).data, { loginId, kind: "progress", message: "Waiting for approval..." }); + assert.deepEqual((await app.call("d-2", "login_complete", { loginId, value: "x" })).error, NO_PENDING_PROMPT, "nothing to answer in a device flow"); + app.remote.approveDevice!(); + assert.deepEqual((await app.nextEvent("login_finished", 0)).data, { loginId, provider: "fake-device", ok: true }); + assert.equal(app.stored()["fake-device"]?.type, "oauth"); +}); + +test("the server's own callback wins the race: the paste prompt is withdrawn", async (t) => { + const app = await setup(t); + const { data: { loginId } } = await app.call("c-1", "login_start", { provider: "fake-browser" }); + await app.nextEvent("login_prompt", 0); + await app.call("c-2", "login_complete", { loginId, value: "paste" }); + await app.nextEvent("login_prompt", 2); + app.remote.callback!("cb"); + assert.deepEqual((await app.nextEvent("login_finished", 0)).data, { loginId, provider: "fake-browser", ok: true }); + assert.equal(app.stored()["fake-browser"]?.access, "access-paste-cb"); +}); + +test("one sign-in per provider; cancel ends it with nothing stored; a bad paste fails it with Pi's message", async (t) => { + const app = await setup(t); + const { data: { loginId } } = await app.call("x-1", "login_start", { provider: "fake-browser" }); + assert.deepEqual((await app.call("x-2", "login_start", { provider: "fake-browser" })).error, LOGIN_IN_PROGRESS); + assert.deepEqual((await app.call("x-3", "set_api_key", { provider: "fake-browser", key: KEY })).error, LOGIN_IN_PROGRESS); + await app.nextEvent("login_prompt", 0); + assert.deepEqual((await app.call("x-4", "login_cancel", { loginId })).data, { cancelled: true }); + assert.deepEqual((await app.nextEvent("login_finished", 0)).data, { loginId, provider: "fake-browser", ok: false, error: "Sign-in cancelled" }); + assert.equal(app.remote.signals[0]!.aborted, true, "the provider's flow is aborted"); + assert.deepEqual(app.stored(), {}); + assert.deepEqual((await app.call("x-5", "login_cancel", { loginId })).error, UNKNOWN_LOGIN); + + const again = (await app.call("x-6", "login_start", { provider: "fake-browser" })).data.loginId; + await app.nextEvent("login_prompt", 1); + await app.call("x-7", "login_complete", { loginId: again, value: "browser" }); + await app.nextEvent("login_prompt", 3); + await app.call("x-8", "login_complete", { loginId: again, value: "http://localhost:1455/auth/callback?code=c&state=forged" }); + assert.deepEqual((await app.nextEvent("login_finished", 1)).data, { loginId: again, provider: "fake-browser", ok: false, error: "State mismatch" }); + assert.deepEqual(app.stored(), {}); +}); + +test("a sign-in is cancelled at its time limit, and a session change ends one silently", async (t) => { + const app = await setup(t, { login: { timeoutMs: 40 } }); + const { data: { loginId } } = await app.call("t-1", "login_start", { provider: "fake-device" }); + assert.deepEqual((await app.nextEvent("login_finished", 0)).data, { loginId, provider: "fake-device", ok: false, error: "Sign-in timed out" }); + + const other = await setup(t); + await other.call("t-2", "login_start", { provider: "fake-device" }); + await other.nextEvent("login_prompt", 0); + await other.shutdown(); + // The aborted flow settles within a few turns of the event loop; let it. + for (let turn = 0; turn < 20; turn++) await new Promise((resolve) => setImmediate(resolve)); + assert.equal(other.remote.signals[0]!.aborted, true); + assert.equal(other.events("login_finished").length, 0, "nothing reaches a replaced session"); +}); + +test("login_start refuses bad params, unknown providers and unsupported kinds", async (t) => { + const app = await setup(t); + assert.equal((await app.call("v-1", "login_start", { provider: "../x" })).error.code, "invalid_request"); + assert.equal((await app.call("v-2", "login_start", { provider: "fake-browser", extra: 1 })).error.code, "invalid_request"); + assert.deepEqual((await app.call("v-3", "login_start", { provider: "nope" })).error, UNKNOWN_PROVIDER); + assert.deepEqual((await app.call("v-4", "login_start", { provider: "fake-key", kind: "oauth" })).error, LOGIN_UNSUPPORTED); + assert.deepEqual((await app.call("v-5", "login_start", { provider: "fake-ambient" })).error, LOGIN_UNSUPPORTED); + assert.equal((await app.call("v-6", "login_complete", { loginId: "login_0000000000000000", value: 1 })).error.code, "invalid_request"); +}); + +test("set_api_key saves the key owner-only through Pi, never echoes it, and remove_credentials removes it", async (t) => { + const app = await setup(t); + assert.deepEqual((await app.call("k-1", "set_api_key", { provider: "fake-key", key: ` ${KEY}\n` })).data, { saved: true }); + assert.deepEqual(app.stored()["fake-key"], { type: "api_key", key: KEY }, "trimmed and stored by Pi"); + if (process.platform !== "win32") assert.equal(statSync(app.authPath).mode & 0o777, 0o600); + assert.equal(app.widgets.some((line) => line.includes(KEY)), false, "the key is never on the wire"); + const status = await app.call("k-2", "get_auth_status"); + assert.deepEqual(status.data.providers.find((row: { provider: string }) => row.provider === "fake-key"), + { provider: "fake-key", displayName: "Fake fake-key", configured: true, type: "api_key", source: "stored", loginKinds: ["api_key"] }); + assert.equal(app.registry.getAvailable().some((model) => model.provider === "fake-key"), true); + + assert.deepEqual((await app.call("k-3", "remove_credentials", { provider: "fake-key" })).data, { removed: true }); + assert.equal(app.stored()["fake-key"], undefined); + assert.equal(app.registry.getAvailable().some((model) => model.provider === "fake-key"), false); + assert.deepEqual((await app.call("k-4", "remove_credentials", { provider: "fake-key" })).data, { removed: false }); +}); + +test("set_api_key refuses bad keys and providers, and a setup that needs more than a key", async (t) => { + const app = await setup(t); + for (const key of ["", "a\nb", "x".repeat(4097), 7]) assert.deepEqual((await app.call(`bad-${String(key).length}`, "set_api_key", { provider: "fake-key", key })).error, INVALID_SET_API_KEY); + assert.deepEqual((await app.call("k-5", "set_api_key", { provider: "nope", key: KEY })).error, UNKNOWN_PROVIDER); + assert.deepEqual((await app.call("k-6", "set_api_key", { provider: "fake-device", key: KEY })).error, LOGIN_UNSUPPORTED); + assert.deepEqual((await app.call("k-7", "set_api_key", { provider: "fake-account", key: KEY })).error, INTERACTIVE_SETUP_REQUIRED); + assert.deepEqual(app.stored(), {}); + assert.equal(app.widgets.some((line) => line.includes(KEY)), false); +}); + +test("login_start with kind api_key runs a key setup interactively, masking the secret", async (t) => { + const app = await setup(t); + const { data: { loginId } } = await app.call("a-1", "login_start", { provider: "fake-account", kind: "api_key" }); + assert.deepEqual((await app.nextEvent("login_prompt", 0)).data, { loginId, kind: "input", message: "Account id", placeholder: "acc_…" }); + await app.call("a-2", "login_complete", { loginId, value: "acc_42" }); + assert.deepEqual((await app.nextEvent("login_prompt", 1)).data, { loginId, kind: "input", message: "API token", secret: true }); + await app.call("a-3", "login_complete", { loginId, value: KEY }); + assert.deepEqual((await app.nextEvent("login_finished", 0)).data, { loginId, provider: "fake-account", ok: true }); + assert.deepEqual(app.stored()["fake-account"], { type: "api_key", key: KEY, env: { FAKE_ACCOUNT: "acc_42" } }); +}); + +test("redirect prefixes are loopback origins only, and display text is bounded", () => { + assert.equal(redirectPrefixOf("https://x.test/a?redirect_uri=http%3A%2F%2F127.0.0.1%3A53692%2Fcallback"), "http://127.0.0.1:53692/"); + assert.equal(redirectPrefixOf("https://x.test/a?callback_url=http%3A%2F%2Flocalhost%3A3000%2Fcb"), "http://localhost:3000/"); + assert.equal(redirectPrefixOf("https://x.test/a?redirect_uri=https%3A%2F%2Fconsole.example.test%2Fcode"), undefined, "a provider page is not a loopback callback"); + assert.equal(redirectPrefixOf("https://x.test/a?redirect_uri=http%3A%2F%2Fevil.test%3A1455%2F"), undefined); + assert.equal(promptForEvent("login_0000000000000000", { type: "auth_url", url: "javascript:alert(1)" }), undefined); + const long = promptForEvent("login_0000000000000000", { type: "progress", message: `a\u0007b${"x".repeat(5000)}` }); + assert.equal(long?.message?.length, 1024); + assert.equal(long?.message?.startsWith("a b"), true); +}); diff --git a/tests/desktop-rpc-packages.test.ts b/tests/desktop-rpc-packages.test.ts new file mode 100644 index 000000000..f507537c9 --- /dev/null +++ b/tests/desktop-rpc-packages.test.ts @@ -0,0 +1,245 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, test } from "node:test"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import desktopRpc, { type DesktopRpcExtensionOptions } from "../extensions/gentle-desktop-rpc.ts"; +import { DESKTOP_RPC_SCHEMA } from "../lib/desktop-rpc.ts"; +import { + DESKTOP_PACKAGES_EVENTS, + DESKTOP_PACKAGES_METHODS, + INVALID_INSTALL_PACKAGE, + INVALID_LIST_PACKAGES, + INVALID_REMOVE_PACKAGE, + PACKAGE_JOB_RUNNING, + progressLines, +} from "../lib/desktop-rpc-packages.ts"; +import { cliPackageRunner, GENTLE_SHELL_LAUNCH_ENV, packageCli, settingsPackages, type PackageJobInput } from "../lib/desktop-packages-service.ts"; +import { INTERACTIVE_HOST_ENV } from "../lib/rpc-host.ts"; + +// Package installs and removals from a client: jobs through the real Desktop +// transport over a fake installer (no npm, no git, no network), the production +// runner over a fake CLI script, and the listing over a temporary agent home. + +const roots: string[] = []; +after(() => roots.forEach((root) => rmSync(root, { recursive: true, force: true }))); +function scratch(): string { + const root = realpathSync(mkdtempSync(join(tmpdir(), "gs-pkg-"))); + roots.push(root); + return root; +} + +/** A fake installer a test drives: each call waits until the test finishes it. */ +function fakeInstaller() { + const calls: Array void }> = []; + return { + calls, + runner: (input: PackageJobInput) => { + const { promise, resolve } = Promise.withResolvers<{ ok: true } | { ok: false; error: string }>(); + calls.push({ ...input, finish: resolve }); + input.signal.addEventListener("abort", () => resolve({ ok: false, error: (input.signal.reason as Error).message }), { once: true }); + return promise; + }, + }; +} + +function setup(t: test.TestContext, options: DesktopRpcExtensionOptions = {}) { + const previous = process.env[INTERACTIVE_HOST_ENV]; + process.env[INTERACTIVE_HOST_ENV] = "1"; + t.after(() => { + if (previous === undefined) delete process.env[INTERACTIVE_HOST_ENV]; + else process.env[INTERACTIVE_HOST_ENV] = previous; + }); + const commands = new Map Promise }>(); + const handlers = new Map unknown>>(); + const pi = { + registerCommand(name: string, command: { handler: (args: string, ctx: unknown) => Promise }) { commands.set(name, command); }, + registerShortcut() {}, + on(name: string, handler: (event: unknown, ctx: unknown) => unknown) { handlers.set(name, [...(handlers.get(name) ?? []), handler]); }, + events: { on() { return () => {}; }, emit() {} }, + } as unknown as ExtensionAPI; + desktopRpc(pi, options); + const widgets: string[] = []; + const session = { idle: Promise.withResolvers(), reloads: 0, waited: 0, linesAtReload: -1 }; + session.idle.resolve(); + const ctx = { + mode: "rpc", + cwd: "/work/project", + sessionManager: { getCwd: () => "/work/project", getSessionId: () => "s", getEntries: () => [] }, + ui: { setWidget(_key: string, lines: string[]) { widgets.push(...lines); } }, + // The command context's `/reload`, which a successful job runs once the agent is idle. + waitForIdle: () => { session.waited += 1; return session.idle.promise; }, + reload: async () => { session.reloads += 1; session.linesAtReload = widgets.length; }, + }; + for (const handler of handlers.get("session_start") ?? []) handler({}, ctx); + const parsed = () => widgets.map((line) => JSON.parse(line)); + const app = { + widgets, + session, + async call(requestId: string, method: string, params: Record = {}) { + await commands.get("gentle:desktop")!.handler(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId, method, params }), ctx); + return parsed().findLast((line) => line.kind === "response" && line.requestId === requestId); + }, + events(name: string) { + return parsed().filter((line) => line.kind === "event" && line.event === name).map((line) => line.data); + }, + async until(check: () => boolean, what: string) { + const deadline = Date.now() + 5000; + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((resolve) => setImmediate(resolve)); + } + }, + async shutdown() { for (const handler of handlers.get("session_shutdown") ?? []) await handler({}, ctx); }, + }; + return app; +} + +test("the slice advertises its methods and events", () => { + assert.deepEqual([...DESKTOP_PACKAGES_METHODS], ["list_packages", "install_package", "remove_package"]); + assert.deepEqual([...DESKTOP_PACKAGES_EVENTS], ["package_progress", "package_finished"]); +}); + +test("an install is a job: its id first, then its lines, then one finish, then the session reloads once idle", async (t) => { + const installer = fakeInstaller(); + const app = setup(t, { packages: { runner: installer.runner } }); + const started = await app.call("i-1", "install_package", { source: "npm:@scope/tool@1.2.0" }); + assert.equal(started.ok, true); + const { jobId } = started.data; + assert.match(jobId, /^pkg_[0-9a-f]{16}$/); + await app.until(() => installer.calls.length === 1, "the installer to start"); + const call = installer.calls[0]!; + assert.deepEqual({ action: call.action, source: call.source, scope: call.scope, cwd: call.cwd }, { action: "install", source: "npm:@scope/tool@1.2.0", scope: "user", cwd: "/work/project" }); + assert.deepEqual((await app.call("i-2", "remove_package", { source: "npm:other" })).error, PACKAGE_JOB_RUNNING, "one job at a time"); + + call.onLine("Installing npm:@scope/tool@1.2.0..."); + call.onLine("added 3 packages"); + assert.ok(app.widgets.findIndex((line) => line.includes('"requestId":"i-1"')) < app.widgets.findIndex((line) => line.includes('"event":"package_progress"'))); + call.finish({ ok: true }); + await app.until(() => app.session.reloads === 1, "the reload"); + assert.deepEqual(app.events("package_progress"), [{ jobId, line: "Installing npm:@scope/tool@1.2.0..." }, { jobId, line: "added 3 packages" }]); + assert.deepEqual(app.events("package_finished"), [{ jobId, ok: true }]); + assert.equal(app.session.waited, 1, "the reload waited for the agent to be idle"); + // The finish is published before the reload tears the session's extensions down. + const finishedAt = app.widgets.findIndex((line) => line.includes('"event":"package_finished"')); + assert.ok(finishedAt >= 0 && finishedAt < app.session.linesAtReload); + + // The next job may start once the first finished. + const removal = await app.call("i-3", "remove_package", { source: "npm:@scope/tool", scope: "project" }); + await app.until(() => installer.calls.length === 2, "the removal to start"); + assert.deepEqual({ action: installer.calls[1]!.action, scope: installer.calls[1]!.scope }, { action: "remove", scope: "project" }); + installer.calls[1]!.finish({ ok: false, error: "No matching package found for npm:@scope/tool" }); + await app.until(() => app.events("package_finished").length === 2, "the removal to finish"); + assert.deepEqual(app.events("package_finished")[1], { jobId: removal.data.jobId, ok: false, error: "No matching package found for npm:@scope/tool" }); + assert.equal(app.session.reloads, 1, "a failed job reloads nothing"); +}); + +test("a job is stopped at its time limit, and a session change stops it without events", async (t) => { + const installer = fakeInstaller(); + const app = setup(t, { packages: { runner: installer.runner, timeoutMs: 20 } }); + const { data: { jobId } } = await app.call("t-1", "install_package", { source: "npm:slow" }); + await app.until(() => app.events("package_finished").length === 1, "the time limit"); + assert.deepEqual(app.events("package_finished"), [{ jobId, ok: false, error: "Stopped: it ran past the time limit" }]); + assert.equal(installer.calls[0]!.signal.aborted, true); + + const other = setup(t, { packages: { runner: installer.runner } }); + await other.call("t-2", "install_package", { source: "npm:slow" }); + await other.until(() => installer.calls.length === 2, "the second job"); + await other.shutdown(); + assert.equal(installer.calls[1]!.signal.aborted, true, "the job is stopped with the session"); + for (let turn = 0; turn < 20; turn++) await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(other.events("package_finished"), []); + assert.equal(other.session.reloads, 0); +}); + +test("requests are validated like the CLI's arguments: a source is never read as an option", async (t) => { + const app = setup(t, { packages: { runner: fakeInstaller().runner } }); + for (const params of [{}, { source: "" }, { source: "--approve" }, { source: "-l" }, { source: " npm:x" }, { source: "npm:x\nrm" }, { source: "npm:x", scope: "global" }, { source: "npm:x", extra: true }, { source: "x".repeat(1025) }]) { + assert.deepEqual((await app.call("v", "install_package", params)).error, INVALID_INSTALL_PACKAGE, JSON.stringify(params)); + } + assert.deepEqual((await app.call("v", "remove_package", { source: "-x" })).error, INVALID_REMOVE_PACKAGE); + assert.deepEqual((await app.call("v", "list_packages", { scope: "user" })).error, INVALID_LIST_PACKAGES); +}); + +test("list_packages answers the listing", async (t) => { + const app = setup(t, { packages: { lister: (cwd) => [{ source: "npm:a", version: "1.0.0", scope: "user" }, { source: `git:${cwd}`, scope: "project" }] } }); + assert.deepEqual((await app.call("l-1", "list_packages")).data, { packages: [{ source: "npm:a", version: "1.0.0", scope: "user" }, { source: "git:/work/project", scope: "project" }] }); +}); + +test("the production listing reads Pi's settings in the agent home, with installed versions and local paths made absolute", (t) => { + const root = scratch(); + const agentDir = join(root, "agent"); + mkdirSync(join(agentDir, "git", "github.com", "u", "r"), { recursive: true }); + mkdirSync(join(root, "pkg")); + writeFileSync(join(root, "pkg", "package.json"), JSON.stringify({ name: "pkg", version: "0.0.1" })); + writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ packages: ["npm:not-installed", "git:github.com/u/r", "../pkg", "../gone"] })); + writeFileSync(join(agentDir, "git", "github.com", "u", "r", "package.json"), JSON.stringify({ name: "r", version: "2.3.4" })); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = agentDir; + t.after(() => { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + }); + // A session in another folder lists (and so removes) the local paths by where they are, not as written. + assert.deepEqual(settingsPackages(join(root, "elsewhere")), [ + { source: "npm:not-installed", scope: "user" }, + { source: "git:github.com/u/r", version: "2.3.4", scope: "user" }, + { source: join(root, "pkg"), version: "0.0.1", scope: "user" }, + { source: join(root, "gone"), scope: "user" }, + ]); +}); + +test("the production runner runs the CLI with the source as one argument, streams clean lines, and reports the CLI's last word", async () => { + const root = scratch(); + const script = join(root, "fake-cli.mjs"); + writeFileSync(script, [ + "const args = process.argv.slice(2);", + "process.stdout.write('\\u001b[2mARGS ' + JSON.stringify(args) + '\\u001b[0m\\n');", + "process.stdout.write('ENV ' + JSON.stringify({ host: process.env.GENTLE_SHELL_INTERACTIVE_HOST ?? null, noColor: process.env.NO_COLOR, cwd: process.cwd() }) + '\\n');", + "process.stdout.write('half a ');", + "setTimeout(() => {", + " process.stdout.write('line\\r\\n\\n');", + " if (args.includes('npm:broken')) { process.stderr.write('npm ERR! 404 Not Found\\nError: Could not install npm:broken\\n'); process.exit(1); }", + " if (args.includes('npm:hang')) { setInterval(() => {}, 1000); return; }", + " process.stdout.write('Installed ' + args[3]);", + "}, 5);", + ].join("\n")); + const previous = process.env[INTERACTIVE_HOST_ENV]; + process.env[INTERACTIVE_HOST_ENV] = "1"; + try { + const run = cliPackageRunner({ command: process.execPath, args: [script, "--home", "/h"] }); + const lines: string[] = []; + const ok = await run({ action: "install", source: "npm:good tool", scope: "project", cwd: root, signal: new AbortController().signal, onLine: (line) => lines.push(line) }); + assert.deepEqual(ok, { ok: true }); + assert.deepEqual(lines, [ + `ARGS ${JSON.stringify(["--home", "/h", "install", "npm:good tool", "-l"])}`, + `ENV ${JSON.stringify({ host: null, noColor: "1", cwd: root })}`, + "half a line", + "Installed npm:good tool", + ]); + + const failed = await run({ action: "install", source: "npm:broken", scope: "user", cwd: root, signal: new AbortController().signal, onLine: () => {} }); + assert.deepEqual(failed, { ok: false, error: "Error: Could not install npm:broken" }); + + const stop = new AbortController(); + const hanging = run({ action: "remove", source: "npm:hang", scope: "user", cwd: root, signal: stop.signal, onLine: (line) => { if (line === "half a line") stop.abort(new Error("Stopped: it ran past the time limit")); } }); + assert.deepEqual(await hanging, { ok: false, error: "Stopped: it ran past the time limit" }); + } finally { + if (previous === undefined) delete process.env[INTERACTIVE_HOST_ENV]; + else process.env[INTERACTIVE_HOST_ENV] = previous; + } +}); + +test("the CLI is the launcher and home the session was started with, else this package's launcher on Pi's home", () => { + assert.deepEqual(packageCli({ [GENTLE_SHELL_LAUNCH_ENV]: JSON.stringify({ command: "/node", args: ["/pkg/bin/gentle-shell.mjs", "--link"] }) }), { command: "/node", args: ["/pkg/bin/gentle-shell.mjs", "--link"] }); + const fallback = packageCli({ [GENTLE_SHELL_LAUNCH_ENV]: "{not json" }); + assert.equal(fallback.command, process.execPath); + assert.match(fallback.args[0]!, /bin[\\/]gentle-shell\.mjs$/); + assert.equal(fallback.args[1], "--home"); +}); + +test("progress lines drop color codes, control characters and blank lines", () => { + assert.deepEqual(progressLines("\u001b[32m✔ done\u001b[0m\r\n\n \n\u0007bell\rnext"), ["✔ done", "bell", "next"]); + assert.equal(progressLines("y".repeat(3000))[0]!.length, 2000); +}); diff --git a/tests/desktop-rpc-permissions.test.ts b/tests/desktop-rpc-permissions.test.ts index 0aaefbc9f..43ce61c72 100644 --- a/tests/desktop-rpc-permissions.test.ts +++ b/tests/desktop-rpc-permissions.test.ts @@ -139,8 +139,23 @@ test("capabilities advertise the wired permission domain and no agent tool", asy "clear_profile_binding", "get_auth_status", "reload_credentials", + "list_available_models", + "set_host_tools", + "host_tool_result", + "host_tool_progress", + "host_message", + "set_host_context", + "set_host_activity", + "login_start", + "login_complete", + "login_cancel", + "set_api_key", + "remove_credentials", + "list_packages", + "install_package", + "remove_package", ]); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); assert.deepEqual(app.tools, [], "the control surface is never an agent-callable tool"); }); diff --git a/tests/desktop-rpc-review.test.ts b/tests/desktop-rpc-review.test.ts index 22f76199a..e514c027a 100644 --- a/tests/desktop-rpc-review.test.ts +++ b/tests/desktop-rpc-review.test.ts @@ -380,7 +380,7 @@ test("the Desktop transport advertises the review methods and event", async (t) const at = data.methods.indexOf("get_review_mode"); assert.notEqual(at, -1); assert.deepEqual(data.methods.slice(at, at + 2), ["get_review_mode", "set_review_mode"]); - assert.deepEqual(data.events.slice(-2), ["review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(data.events.slice(-8), ["review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); test("get_review_mode answers review_unavailable through the transport without an owner extension", async (t) => { diff --git a/tests/desktop-rpc-session.test.ts b/tests/desktop-rpc-session.test.ts index 8cf9116d7..e60d56ee5 100644 --- a/tests/desktop-rpc-session.test.ts +++ b/tests/desktop-rpc-session.test.ts @@ -275,15 +275,17 @@ test("S2: get_snapshot without sections is byte-identical with and without the f const legacyWith = await withFeed.invoke("get_snapshot"); assert.equal(legacyWith.length, 1); // `sequence` counts delivered events: with the feed, its start-up flushes may - // already have published session_snapshot events. Everything else is identical. + // already have published session_snapshot events; each channel names its own + // `epoch`. Everything else is identical. const events = withFeed.lines().filter((line) => JSON.parse(line).kind === "event").length; assert.equal(legacyWith[0].data.sequence, events); - assert.deepEqual(legacyWith, [{ ...legacyWithout[0], data: { ...legacyWithout[0].data, sequence: events } }]); + const epoch = legacyWith[0].data.epoch; + assert.deepEqual(legacyWith, [{ ...legacyWithout[0], data: { ...legacyWithout[0].data, sequence: events, epoch } }]); assert.equal("session" in legacyWith[0].data.state, false); // Unrelated params keep today's behavior too. const otherWith = await withFeed.invoke("get_snapshot", { other: true }); const otherWithout = await without.invoke("get_snapshot", { other: true }); - assert.deepEqual(otherWith, [{ ...otherWithout[0], data: { ...otherWithout[0].data, sequence: events } }]); + assert.deepEqual(otherWith, [{ ...otherWithout[0], data: { ...otherWithout[0].data, sequence: events, epoch } }]); }); test("S1/S2/S4/S5: get_snapshot with sections reads the live feed projection; reads emit no event", async (t) => { @@ -327,14 +329,14 @@ test("S5/S6: without the feed, sections answer session_unavailable and capabilit assert.deepEqual(out[0].error, SESSION_UNAVAILABLE); const capabilities = (await app.invoke("capabilities"))[0].data; assert.equal(capabilities.events.includes(DESKTOP_SESSION_EVENT), false); - assert.deepEqual(capabilities.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(capabilities.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); assert.deepEqual((await app.invoke("get_snapshot"))[0].data.state, (await app.invoke("get_snapshot", { other: 1 }))[0].data.state); }); test("S6: with the feed wired, capabilities advertise session_snapshot", async (t) => { const app = await rpcHarness(t, true); const capabilities = (await app.invoke("capabilities"))[0].data; - assert.deepEqual(capabilities.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", DESKTOP_SESSION_EVENT]); + assert.deepEqual(capabilities.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished", DESKTOP_SESSION_EVENT]); assert.equal(capabilities.methods.includes("get_snapshot"), true); }); @@ -418,7 +420,9 @@ test("S2: the router keeps get_snapshot byte-identical when no session reader is const router = new DesktopRpcRouter(undefined, undefined, () => ({ config: { stores: [] } })); router.start((line) => lines.push(line)); router.handle(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "a", method: "get_snapshot", params: { sections: ["todo"] } })); - assert.deepEqual(JSON.parse(lines[0]!).data, { schema: DESKTOP_RPC_SCHEMA, sequence: 0, state: { config: { stores: [] } } }); + const data = JSON.parse(lines[0]!).data; + assert.deepEqual(data, { schema: DESKTOP_RPC_SCHEMA, sequence: 0, epoch: data.epoch, state: { config: { stores: [] } } }); + assert.equal(typeof data.epoch, "string"); }); // ---- Path edge cases (verifier correction batch) ---- diff --git a/tests/desktop-rpc-stats.test.ts b/tests/desktop-rpc-stats.test.ts index f7f017097..74c928f22 100644 --- a/tests/desktop-rpc-stats.test.ts +++ b/tests/desktop-rpc-stats.test.ts @@ -161,7 +161,7 @@ test("the Desktop transport advertises get_usage_stats and no new event", (t) => const response = app.responses()[0]; assert.ok(response.data.methods.includes("get_usage_stats")); assert.equal(response.data.methods.filter((method: string) => method === "get_usage_stats").length, 1); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); // ---- The read ---- diff --git a/tests/desktop-rpc-status.test.ts b/tests/desktop-rpc-status.test.ts index 450bbeddc..d1e3033c8 100644 --- a/tests/desktop-rpc-status.test.ts +++ b/tests/desktop-rpc-status.test.ts @@ -91,7 +91,7 @@ test("the Desktop transport advertises get_status once and no new event", async await commands.get("gentle:desktop")!.handler(JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId: "cap", method: "capabilities", params: {} }), host); const data = JSON.parse(widgets.at(-1)!).data; assert.equal(data.methods.filter((method: string) => method === "get_status").length, 1); - assert.deepEqual(data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); // ---- Contract over a fake owner ---- diff --git a/tests/desktop-rpc-updates.test.ts b/tests/desktop-rpc-updates.test.ts index 5656cc5f2..15508f751 100644 --- a/tests/desktop-rpc-updates.test.ts +++ b/tests/desktop-rpc-updates.test.ts @@ -133,7 +133,7 @@ test("the Desktop transport advertises get_update_status once and no new event", assert.ok(response.data.methods.includes("get_update_status")); assert.equal(response.data.methods.filter((method: string) => method === "get_update_status").length, 1); assert.ok(response.data.methods.includes("get_usage_stats"), "the previous methods stay advertised"); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); // ---- Without refresh: cache only, no network ---- diff --git a/tests/desktop-rpc-usage.test.ts b/tests/desktop-rpc-usage.test.ts index eb56b6a05..26751bb3e 100644 --- a/tests/desktop-rpc-usage.test.ts +++ b/tests/desktop-rpc-usage.test.ts @@ -684,8 +684,23 @@ test("the Desktop transport advertises the usage methods and rate_limit event", "clear_profile_binding", "get_auth_status", "reload_credentials", + "list_available_models", + "set_host_tools", + "host_tool_result", + "host_tool_progress", + "host_message", + "set_host_context", + "set_host_activity", + "login_start", + "login_complete", + "login_cancel", + "set_api_key", + "remove_credentials", + "list_packages", + "install_package", + "remove_package", ]); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); }); test("get_subscription_usage answers usage_unavailable through the transport without an owner extension", async (t) => { diff --git a/tests/desktop-rpc.test.ts b/tests/desktop-rpc.test.ts index ad3a015a8..688116ddc 100644 --- a/tests/desktop-rpc.test.ts +++ b/tests/desktop-rpc.test.ts @@ -66,18 +66,20 @@ test("capabilities and snapshots use correlated structured responses", async (t) schema: DESKTOP_RPC_SCHEMA, command: "gentle:desktop", widget: DESKTOP_RPC_WIDGET, - methods: ["capabilities", "get_snapshot", "get_config", "set_config", "get_permission_mode", "set_permission_mode", "get_subscription_usage", "refresh_subscription_usage", "get_design_canvas", "list_jobs", "cancel_job", "get_job_output", "apply_profile", "list_subagents", "cancel_subagent", "get_subagent_thread", "list_sessions", "switch_session", "get_changes", "get_change_diff", "get_review_mode", "set_review_mode", "get_usage_stats", "get_update_status", "list_agent_definitions", "get_status", "get_background_subagents", "set_background_subagents", "get_profile_binding", "clear_profile_binding", "get_auth_status", "reload_credentials"], - events: ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"], + methods: ["capabilities", "get_snapshot", "get_config", "set_config", "get_permission_mode", "set_permission_mode", "get_subscription_usage", "refresh_subscription_usage", "get_design_canvas", "list_jobs", "cancel_job", "get_job_output", "apply_profile", "list_subagents", "cancel_subagent", "get_subagent_thread", "list_sessions", "switch_session", "get_changes", "get_change_diff", "get_review_mode", "set_review_mode", "get_usage_stats", "get_update_status", "list_agent_definitions", "get_status", "get_background_subagents", "set_background_subagents", "get_profile_binding", "clear_profile_binding", "get_auth_status", "reload_credentials", "list_available_models", "set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context", "set_host_activity", "login_start", "login_complete", "login_cancel", "set_api_key", "remove_credentials", "list_packages", "install_package", "remove_package"], + events: ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"], }, }); await app.invoke(request("get_snapshot")); - assert.deepEqual(widgetPayload(app.widgets[1]!), { + const snapshot = widgetPayload(app.widgets[1]!); + assert.equal(typeof snapshot.data.epoch, "string"); + assert.deepEqual(snapshot, { schema: DESKTOP_RPC_SCHEMA, kind: "response", requestId: "request-get_snapshot", ok: true, - data: { schema: DESKTOP_RPC_SCHEMA, sequence: 0, state: {} }, + data: { schema: DESKTOP_RPC_SCHEMA, sequence: 0, epoch: snapshot.data.epoch, state: {} }, }); }); @@ -120,17 +122,53 @@ test("events advance after delivery, move to a replacement publisher, and reset assert.equal(JSON.parse(first[0]!).seq, 1); assert.equal(JSON.parse(first[1]!).seq, 2); assert.equal(router.snapshot().sequence, 2); + // One numbering, one epoch: every event and the snapshot name it. + const epoch = router.snapshot().epoch; + assert.match(epoch, /^[0-9a-f-]{36}$/); + assert.deepEqual(first.map((line) => JSON.parse(line).epoch), [epoch, epoch]); router.start((line) => second.push(line)); router.emit("jobs_update", { jobs: [] }); assert.equal(first.length, 2); assert.equal(JSON.parse(second[0]!).seq, 1); + // The numbering restarted, so its epoch changed. + const restarted = router.snapshot().epoch; + assert.notEqual(restarted, epoch); + assert.equal(JSON.parse(second[0]!).epoch, restarted); router.stop(); assert.equal(router.snapshot().sequence, 0); router.emit("jobs_update", { jobs: [] }); assert.equal(second.length, 1); }); +test("the epoch stays for a session and changes on a reload or a switch", async (t) => { + const app = harness(t); + const epoch = async (ctx: typeof app.ctx = app.ctx, widgets: WidgetCall[] = app.widgets) => { + await app.invoke(request("get_snapshot"), ctx); + return widgetPayload(widgets.at(-1)!).data.epoch as string; + }; + app.start(); + const first = await epoch(); + assert.equal(await epoch(), first, "reads of one session keep its epoch"); + + // A reload shuts the session down and starts it again: seq restarts, so does the epoch. + app.events.get("session_shutdown")?.({ reason: "reload" }, app.ctx); + app.events.get("session_start")?.({ reason: "reload" }, app.ctx); + const reloaded = await epoch(); + assert.notEqual(reloaded, first); + assert.equal(await epoch(), reloaded); + + // A switch replaces the session the same way. + const switchedWidgets: WidgetCall[] = []; + const switched = { mode: "rpc", ui: { setWidget(key: string, lines: string[]) { switchedWidgets.push({ key, lines }); } } }; + app.events.get("session_shutdown")?.({ reason: "resume" }, app.ctx); + app.events.get("session_start")?.({ reason: "resume" }, switched); + const afterSwitch = await epoch(switched, switchedWidgets); + assert.notEqual(afterSwitch, reloaded); + assert.notEqual(afterSwitch, first); + assert.equal(await epoch(switched, switchedWidgets), afterSwitch); +}); + test("state failures are internal errors and publisher failures are never retried", () => { const internal = new DesktopRpcRouter(undefined, undefined, () => { throw new Error("private path"); }); const lines: string[] = []; diff --git a/tests/fixtures/serve-fake-pi.mjs b/tests/fixtures/serve-fake-pi.mjs new file mode 100755 index 000000000..b80f9440c --- /dev/null +++ b/tests/fixtures/serve-fake-pi.mjs @@ -0,0 +1,105 @@ +#!/usr/bin/env node +// A stand-in for `gentle-shell --mode rpc` in the serve tests: it speaks Pi's +// JSONL RPC on stdin/stdout (responses, a Desktop RPC widget answer, dialogs) +// plus a few `fake_*` commands that let tests drive framing, bursts, exits and +// the Desktop events of a host tool call (as if the agent had called the tool). +// No Pi, no model. + +let buffer = ""; +let dialogs = 0; +let desktopEvents = 0; +const out = (record) => process.stdout.write(`${JSON.stringify(record)}\n`); +const respond = (cmd, data, success = true) => out({ ...(cmd.id === undefined ? {} : { id: cmd.id }), type: "response", command: cmd.type, success, ...(success ? { data } : { error: data }) }); +/** A Desktop RPC event, as the extension's router publishes it. */ +const desktopEvent = (event, data) => { + desktopEvents += 1; + const payload = { schema: "gentle-shell.desktop-rpc/v1", kind: "event", seq: desktopEvents, epoch: "fake-epoch", event, data }; + out({ type: "extension_ui_request", id: `w-event-${desktopEvents}`, method: "setWidget", widgetKey: "gentle-desktop-rpc", widgetLines: [JSON.stringify(payload)] }); +}; + +function handle(cmd) { + switch (cmd.type) { + case "get_state": + return respond(cmd, { sessionId: "fake-session", isStreaming: false, messageCount: 0, cwd: process.cwd(), interactiveHost: process.env.GENTLE_SHELL_INTERACTIVE_HOST ?? null, args: process.argv.slice(2) }); + case "prompt": { + const message = String(cmd.message ?? ""); + if (!message.startsWith("/gentle:desktop ")) return respond(cmd, { disposition: "started" }); + const request = JSON.parse(message.slice("/gentle:desktop ".length)); + if (request.method === "refuse") return respond(cmd, "refused", false); + respond(cmd, { disposition: "handled" }); + if (request.method === "never") return; + const answer = { schema: request.schema, kind: "response", requestId: request.requestId, ok: true, data: { method: request.method, params: request.params } }; + out({ type: "extension_ui_request", id: `w-${request.requestId}`, method: "setWidget", widgetKey: "gentle-desktop-rpc", widgetLines: [JSON.stringify(answer)] }); + // What sign-in and package jobs publish after their answer. + if (request.method === "login_start") desktopEvent("login_prompt", { loginId: "login-1", kind: "open_url", url: "https://login.invalid/authorize" }); + if (request.method === "install_package") { + desktopEvent("package_progress", { jobId: "job-1", line: "added 1 package" }); + desktopEvent("package_finished", { jobId: "job-1", ok: true }); + } + return; + } + case "extension_ui_response": + return out({ type: "fake_dialog_answer", id: cmd.id, value: cmd.value ?? null, cancelled: cmd.cancelled ?? false }); + case "fake_dialog": + dialogs += 1; + respond(cmd, { dialog: `dlg-${dialogs}` }); + return out({ type: "extension_ui_request", id: `dlg-${dialogs}`, method: "select", title: "Pick one", options: ["a", "b"], ...(cmd.timeout ? { timeout: cmd.timeout } : {}) }); + case "fake_burst": { + const pad = "x".repeat(cmd.size ?? 10); + for (let n = 0; n < (cmd.count ?? 1); n += 1) out({ type: "fake_event", n, pad }); + return respond(cmd, { sent: cmd.count ?? 1 }); + } + case "fake_trickle": { + // Records keep coming after the response, as during a turn: `count` of them, one every `everyMs`. + let n = 0; + const timer = setInterval(() => { + out({ type: "fake_event", tick: n }); + n += 1; + if (n >= (cmd.count ?? 1)) clearInterval(timer); + }, cmd.everyMs ?? 10); + return respond(cmd, {}); + } + case "fake_unicode": + // U+2028/U+2029 stay raw inside the JSON string: they must not split the record. + process.stdout.write(`{"type":"fake_event","text":"a\u2028b\u2029c"}\r\n`); + return respond(cmd, {}); + case "fake_split": { + const line = JSON.stringify({ type: "fake_event", split: true }); + process.stdout.write(line.slice(0, 7)); + setTimeout(() => { process.stdout.write(`${line.slice(7)}\nnot json\n`); respond(cmd, {}); }, 30); + return; + } + case "fake_exit": + out({ type: "fake_event", bye: true }); + if (cmd.afterMs) respond(cmd, {}); + return void setTimeout(() => process.exit(cmd.code ?? 0), cmd.afterMs ?? 10); + case "fake_host_call": + case "fake_host_cancel": { + respond(cmd, {}); + const data = cmd.type === "fake_host_call" ? { callId: cmd.callId, provider: cmd.provider, tool: cmd.tool ?? "phone_camera", args: cmd.args ?? {} } : { callId: cmd.callId }; + const event = { schema: "gentle-shell.desktop-rpc/v1", kind: "event", seq: 1, event: cmd.type === "fake_host_call" ? "host_tool_call" : "host_tool_cancel", data }; + return out({ type: "extension_ui_request", id: `w-${cmd.type}-${cmd.callId}`, method: "setWidget", widgetKey: "gentle-desktop-rpc", widgetLines: [JSON.stringify(event)] }); + } + case "fake_silent": + return; // never answers + default: + return respond(cmd, `Unknown command: ${cmd.type}`, false); + } +} + +process.stdin.on("data", (chunk) => { + buffer += chunk.toString("utf8"); + let lf; + while ((lf = buffer.indexOf("\n")) !== -1) { + const line = buffer.slice(0, lf); + buffer = buffer.slice(lf + 1); + if (!line.trim()) continue; + try { + handle(JSON.parse(line)); + } catch (error) { + out({ type: "response", command: "parse", success: false, error: String(error) }); + } + } +}); +process.stdin.on("end", () => process.exit(0)); +process.stderr.write("fake pi ready\n"); diff --git a/tests/fixtures/serve-fake-print.mjs b/tests/fixtures/serve-fake-print.mjs new file mode 100755 index 000000000..b5170de51 --- /dev/null +++ b/tests/fixtures/serve-fake-print.mjs @@ -0,0 +1,24 @@ +#!/usr/bin/env node +// A stand-in for `gentle-shell --print` in the serve tests: it reads the prompt +// from stdin and answers by what the prompt asks for. No Pi, no model. + +let prompt = ""; +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (chunk) => { prompt += chunk; }); +process.stdin.on("end", () => { + if (prompt.startsWith("fail")) { + process.stderr.write("no model configured\n"); + process.exit(3); + } + if (prompt.startsWith("hang")) { + process.stdout.write("thinking…"); + setInterval(() => {}, 1000); + return; + } + if (prompt.startsWith("big")) { + process.stdout.write("x".repeat(64 * 1024)); + setInterval(() => {}, 1000); + return; + } + process.stdout.write(`${JSON.stringify({ prompt, args: process.argv.slice(2), cwd: process.cwd(), interactiveHost: process.env.GENTLE_SHELL_INTERACTIVE_HOST ?? null })}\n`); +}); diff --git a/tests/fixtures/serve-fake-term-host.mjs b/tests/fixtures/serve-fake-term-host.mjs new file mode 100755 index 000000000..6be8fc3e8 --- /dev/null +++ b/tests/fixtures/serve-fake-term-host.mjs @@ -0,0 +1,174 @@ +#!/usr/bin/env node +// A stand-in for gentle-term-host in the serve tests: the same protocol +// (JSON Lines, base64 data) over a Unix socket or, with --tcp, loopback TCP +// with a token in /term-host.json and an `auth` line first; plain +// pipes instead of PTYs and the raw output ring as the "snapshot". It +// records its arguments in /argv.json so a test can check how +// serve started it. + +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { createServer } from "node:net"; +import { join } from "node:path"; + +const args = process.argv.slice(2); +const flag = (name) => { const i = args.indexOf(name); return i === -1 ? undefined : args[i + 1]; }; +const tcp = args.includes("--tcp"); +const socketPath = flag("--socket"); +const stateDir = flag("--state-dir"); +if (!socketPath && !tcp) { console.error("--socket or --tcp is required"); process.exit(2); } +if (tcp && !stateDir) { console.error("--tcp needs --state-dir"); process.exit(2); } +if (stateDir) { + mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + writeFileSync(join(stateDir, "argv.json"), JSON.stringify(args)); +} +const portFile = tcp ? join(stateDir, "term-host.json") : undefined; +const token = randomBytes(32).toString("hex"); +const RING = 2 * 1024 * 1024; +const terms = new Map(); + +function emit(term, event) { + for (const conn of term.attached) conn.send({ ...event, term: term.id }); +} + +function open(msg) { + const argv = Array.isArray(msg.argv) ? msg.argv : [process.env.SHELL || "/bin/sh", "-l"]; + const id = `t_${randomBytes(6).toString("hex")}`; + const child = spawn(argv[0], argv.slice(1), { cwd: msg.cwd, env: { ...process.env, ...msg.env, TERM: "xterm-256color" }, stdio: ["pipe", "pipe", "pipe"] }); + const term = { id, child, cwd: msg.cwd, argv, cols: msg.cols, rows: msg.rows, title: "", alive: true, exitCode: undefined, createdAt: Date.now(), ring: Buffer.alloc(0), offset: 0, attached: new Set() }; + const out = (chunk) => { + term.offset += chunk.length; + term.ring = Buffer.concat([term.ring, chunk]); + if (term.ring.length > RING) term.ring = term.ring.subarray(term.ring.length - RING); + emit(term, { ev: "output", offset: term.offset, data: chunk.toString("base64") }); + }; + child.stdout.on("data", out); + child.stderr.on("data", out); + child.stdin.on("error", () => {}); + child.on("close", (code, signal) => { + term.alive = false; + term.exitCode = code ?? (signal ? 128 : null); + emit(term, { ev: "exit", code: term.exitCode }); + term.attached.clear(); + }); + terms.set(id, term); + return { term: id, pid: child.pid }; +} + +function handle(conn, msg) { + const term = typeof msg.term === "string" ? terms.get(msg.term) : undefined; + const needTerm = () => { if (!term) throw { code: "not_found", message: "no such term" }; return term; }; + switch (msg.op) { + case "hello": return { protocol: 1, version: "fake", pid: process.pid }; + case "open": return open(msg); + case "list": return { terms: [...terms.values()].map((t) => ({ term: t.id, pid: t.child.pid, cwd: t.cwd, argv: t.argv, cols: t.cols, rows: t.rows, title: t.title, alive: t.alive, ...(t.alive ? {} : { exitCode: t.exitCode }), createdAt: t.createdAt, offset: t.offset })) }; + case "write": { + const t = needTerm(); + if (!t.alive) throw { code: "exited", message: "the term exited" }; + t.child.stdin.write(Buffer.from(msg.data, "base64")); + return {}; + } + case "resize": { + const t = needTerm(); + if (!t.alive) throw { code: "exited", message: "the term exited" }; + if (t.cols !== msg.cols || t.rows !== msg.rows) { + t.cols = msg.cols; + t.rows = msg.rows; + conn.after(() => emit(t, { ev: "resized", cols: t.cols, rows: t.rows })); + } + return {}; + } + case "close": { + const t = needTerm(); + terms.delete(t.id); + t.child.kill("SIGHUP"); + setTimeout(() => t.child.kill("SIGKILL"), 3000).unref(); + return {}; + } + case "forget": { + const t = needTerm(); + if (t.alive) throw { code: "alive", message: "the term still runs" }; + terms.delete(t.id); + return {}; + } + case "attach": { + const t = needTerm(); + const start = t.offset - t.ring.length; + const resume = typeof msg.from === "number" && msg.from >= start && msg.from <= t.offset; + if (!t.alive) { + conn.after(() => conn.send({ ev: "exit", term: t.id, code: t.exitCode })); + return { offset: t.offset, snapshot: t.ring.toString("base64") }; + } + t.attached.add(conn); + conn.terms.add(t); + if (resume) { + if (msg.from < t.offset) conn.after(() => conn.send({ ev: "output", term: t.id, offset: t.offset, data: t.ring.subarray(msg.from - start).toString("base64") })); + return { offset: msg.from }; + } + return { offset: t.offset, snapshot: t.ring.toString("base64") }; + } + case "detach": { + const t = needTerm(); + t.attached.delete(conn); + return {}; + } + case "shutdown": + conn.after(() => { + for (const t of terms.values()) t.child.kill("SIGKILL"); + rmSync(portFile ?? socketPath, { force: true }); + process.exit(0); + }); + return {}; + default: throw { code: "bad_request", message: `unknown op ${msg.op}` }; + } +} + +if (socketPath) rmSync(socketPath, { force: true }); +const server = createServer((socket) => { + let buffered = ""; + let authed = !tcp; + const queued = []; + const conn = { + terms: new Set(), + send: (msg) => { if (!socket.destroyed) socket.write(`${JSON.stringify(msg)}\n`); }, + after: (fn) => queued.push(fn), + }; + socket.on("data", (chunk) => { + buffered += chunk.toString("utf8"); + let nl; + while ((nl = buffered.indexOf("\n")) !== -1) { + const line = buffered.slice(0, nl); + buffered = buffered.slice(nl + 1); + let msg; + try { msg = JSON.parse(line); } catch { msg = undefined; } + if (!authed) { + if (msg?.op !== "auth" || msg.token !== token) { + socket.end(`${JSON.stringify({ id: msg?.id ?? null, ok: false, error: { code: "unauthorized", message: "authenticate first" } })}\n`); + return; + } + authed = true; + conn.send({ id: msg.id, ok: true }); + continue; + } + if (msg === undefined) { conn.send({ id: null, ok: false, error: { code: "bad_request", message: "not JSON" } }); continue; } + try { + conn.send({ ...handle(conn, msg), id: msg.id, ok: true }); + } catch (error) { + conn.send({ id: msg.id, ok: false, error: { code: error.code ?? "error", message: error.message ?? String(error) } }); + } + for (const fn of queued.splice(0)) fn(); + } + }); + socket.on("error", () => {}); + socket.on("close", () => { for (const t of conn.terms) t.attached.delete(conn); }); +}); +if (tcp) { + server.listen(0, "127.0.0.1", () => { + const temp = `${portFile}.${process.pid}.tmp`; + writeFileSync(temp, `${JSON.stringify({ port: server.address().port, token, pid: process.pid })}\n`, { mode: 0o600 }); + renameSync(temp, portFile); + }); +} else { + server.listen(socketPath, () => chmodSync(socketPath, 0o600)); +} diff --git a/tests/gentle-shell-bin.test.ts b/tests/gentle-shell-bin.test.ts index 032dd9d50..c73fa1a92 100644 --- a/tests/gentle-shell-bin.test.ts +++ b/tests/gentle-shell-bin.test.ts @@ -201,6 +201,7 @@ function writePiScript(path: string, version: string, removeExitCode = 0) { " GENTLE_SHELL_USER_PI_HOME: process.env.GENTLE_SHELL_USER_PI_HOME,", " GENTLE_SHELL_CHILD_PACKAGE_INJECTION: process.env.GENTLE_SHELL_CHILD_PACKAGE_INJECTION,", " GENTLE_SHELL_HERDR_REPORTER: process.env.GENTLE_SHELL_HERDR_REPORTER,", + " GENTLE_SHELL_LAUNCH: process.env.GENTLE_SHELL_LAUNCH,", "}));", "process.exit(0);", "", @@ -263,6 +264,15 @@ function herdrFixture(t: test.TestContext) { return { ...f, bridge, env, launch, launchWithEnv }; } +test("the launcher tells Pi how to run this same CLI on this same home, for a client's package installs", (t) => { + const f = fixture(t); + for (const [args, flags] of [[[], []], [["--home", f.gentleShellHome], ["--home", f.gentleShellHome]]]) { + const result = run(f.env, args, { cwd: f.root }); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(JSON.parse(result.stdout).GENTLE_SHELL_LAUNCH), { command: process.execPath, args: [binPath, ...flags] }, JSON.stringify(args)); + } +}); + function extensionPaths(args: string[]): string[] { return args.flatMap((arg, i) => arg === "-e" || arg === "--extension" ? [args[i + 1]] : []); } diff --git a/tests/maintainer/desktop-rpc.maintest.ts b/tests/maintainer/desktop-rpc.maintest.ts index e068c0688..441d2e0bc 100644 --- a/tests/maintainer/desktop-rpc.maintest.ts +++ b/tests/maintainer/desktop-rpc.maintest.ts @@ -180,8 +180,8 @@ test("installed Pi dispatches Desktop RPC without adding conversation messages", assert.equal(response.kind, "response"); assert.equal(response.requestId, "real-1"); assert.equal(response.ok, true); - assert.deepEqual(response.data.methods, ["capabilities", "get_snapshot", "get_config", "set_config", "get_permission_mode", "set_permission_mode", "get_subscription_usage", "refresh_subscription_usage", "get_design_canvas", "list_jobs", "cancel_job", "get_job_output", "apply_profile", "list_subagents", "cancel_subagent", "get_subagent_thread", "list_sessions", "switch_session", "get_changes", "get_change_diff", "get_review_mode", "set_review_mode", "get_usage_stats", "get_update_status", "list_agent_definitions", "get_status", "get_background_subagents", "set_background_subagents", "get_profile_binding", "clear_profile_binding", "get_auth_status", "reload_credentials"]); - assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed"]); + assert.deepEqual(response.data.methods, ["capabilities", "get_snapshot", "get_config", "set_config", "get_permission_mode", "set_permission_mode", "get_subscription_usage", "refresh_subscription_usage", "get_design_canvas", "list_jobs", "cancel_job", "get_job_output", "apply_profile", "list_subagents", "cancel_subagent", "get_subagent_thread", "list_sessions", "switch_session", "get_changes", "get_change_diff", "get_review_mode", "set_review_mode", "get_usage_stats", "get_update_status", "list_agent_definitions", "get_status", "get_background_subagents", "set_background_subagents", "get_profile_binding", "clear_profile_binding", "get_auth_status", "reload_credentials", "list_available_models", "set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context", "set_host_activity", "login_start", "login_complete", "login_cancel", "set_api_key", "remove_credentials", "list_packages", "install_package", "remove_package"]); + assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update", "review_mode_changed", "profile_binding_changed", "host_tool_call", "host_tool_cancel", "login_prompt", "login_finished", "package_progress", "package_finished"]); } finally { rmSync(root, { recursive: true, force: true }); } @@ -248,10 +248,10 @@ test("installed Pi serves Desktop config reads from the existing stores", () => assert.deepEqual(models.data.value, { worker: { model: "openai/gpt-probe" } }); const snapshot = byRequest("config-3").data; - assert.equal(snapshot.state.config.stores.length, 12); + assert.equal(snapshot.state.config.stores.length, 13); assert.deepEqual( snapshot.state.config.stores.map((entry: any) => entry.store), - ["profiles", "models", "profile_fallbacks", "subagents", "pins", "managed_assets", "persona", "banner", "notifications", "mcp", "pi_settings", "claude_bridge"], + ["profiles", "models", "profile_fallbacks", "subagents", "pins", "managed_assets", "persona", "banner", "notifications", "mcp", "pi_settings", "claude_bridge", "custom_models"], ); assert.equal(snapshot.state.config.stores[0].status, "ok"); assert.equal(JSON.stringify(snapshot).includes("claude-probe"), false, "snapshots stay bounded"); diff --git a/tests/serve-auth.test.ts b/tests/serve-auth.test.ts new file mode 100644 index 000000000..7d93df1e9 --- /dev/null +++ b/tests/serve-auth.test.ts @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { normalizePairingCode, parseScopes, readDevicesFile, sameSecret, SERVE_SCOPES, ServeAuth } from "../lib/serve-auth.ts"; +import { after, test } from "./serve-test-client.ts"; + +const roots: string[] = []; +after(() => roots.forEach((r) => rmSync(r, { recursive: true, force: true }))); + +function setup(now?: () => number) { + const root = mkdtempSync(join(tmpdir(), "gentle-serve-auth-")); + roots.push(root); + const devicesFile = join(root, "serve", "devices.json"); + return { devicesFile, auth: new ServeAuth({ devicesFile, adminToken: "gsa_local-admin", ...(now ? { now } : {}) }) }; +} + +test("a pairing code is single use and yields a device token stored only as a hash", () => { + const { auth, devicesFile } = setup(); + const { code, scopes } = auth.mintPairingCode(); + assert.match(code, /^[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}$/); + assert.deepEqual(scopes, ["sessions:read", "sessions:operate", "terminal"]); + const paired = auth.redeem(code.toLowerCase(), " phone\u0007 "); + assert.ok("token" in paired); + assert.match(paired.token, /^gss_[A-Za-z0-9_-]{43}$/); + assert.equal(paired.device.name, "phone"); + assert.deepEqual(auth.redeem(code, "again"), { error: "invalid_code" }); + + const text = readFileSync(devicesFile, "utf8"); + assert.ok(!text.includes(paired.token), "the token never reaches the file"); + assert.ok(!text.includes(code), "nor does the code"); + if (process.platform !== "win32") { + assert.equal(statSync(devicesFile).mode & 0o777, 0o600); + assert.equal(statSync(join(devicesFile, "..")).mode & 0o777, 0o700); + } + const principal = auth.authenticate(paired.token); + assert.deepEqual(principal, { deviceId: paired.device.id, name: "phone", scopes: ["sessions:read", "sessions:operate", "terminal"] }); + assert.equal(auth.authenticate(`${paired.token}x`), undefined); + assert.equal(auth.authenticate(undefined), undefined); + + // A new process reads the same devices back. + const reloaded = new ServeAuth({ devicesFile, adminToken: "other" }); + assert.equal(reloaded.authenticate(paired.token)?.deviceId, paired.device.id); + assert.equal(reloaded.authenticate("gsa_local-admin"), undefined, "the admin token belongs to one server run"); +}); + +test("the local admin token carries every scope", () => { + const { auth } = setup(); + assert.deepEqual(auth.authenticate("gsa_local-admin"), { deviceId: "local", name: "local", scopes: SERVE_SCOPES }); +}); + +test("a pairing code expires after five minutes", () => { + let clock = 0; + const { auth } = setup(() => clock); + const fresh = auth.mintPairingCode(["sessions:read"]); + const stale = auth.mintPairingCode(); + clock = 5 * 60_000 - 1; + assert.ok("token" in auth.redeem(fresh.code, "ok")); + clock = 5 * 60_000; + assert.deepEqual(auth.redeem(stale.code, "late"), { error: "invalid_code" }); +}); + +test("failed pairing attempts are rate limited", () => { + let clock = 0; + const { auth } = setup(() => clock); + const { code } = auth.mintPairingCode(); + for (let i = 0; i < 10; i += 1) assert.deepEqual(auth.redeem(`WRONG-${i}`, "x"), { error: "invalid_code" }); + assert.deepEqual(auth.redeem(code, "x"), { error: "rate_limited" }, "even the right code waits"); + clock += 60_000; + assert.ok("token" in auth.redeem(code, "x")); +}); + +test("revoking a device stops its token, kills its tickets and notifies listeners at once", () => { + const { auth, devicesFile } = setup(); + const paired = auth.redeem(auth.mintPairingCode().code, "laptop"); + assert.ok("token" in paired); + const principal = auth.authenticate(paired.token)!; + const ticket = auth.mintTicket(principal, "ses_1"); + const revoked: string[] = []; + auth.onRevoke((id) => revoked.push(id)); + assert.equal(auth.revoke(paired.device.id), true); + assert.deepEqual(revoked, [paired.device.id]); + assert.equal(auth.authenticate(paired.token), undefined); + assert.equal(auth.redeemTicket(ticket.ticket, "ses_1"), undefined); + assert.deepEqual(readDevicesFile(devicesFile), []); + assert.equal(auth.revoke(paired.device.id), false); +}); + +test("stream tickets are single use, bound to one session and short lived", () => { + let clock = 0; + const { auth } = setup(() => clock); + const principal = auth.authenticate("gsa_local-admin")!; + const a = auth.mintTicket(principal, "ses_a"); + assert.equal(auth.redeemTicket(a.ticket, "ses_b"), undefined, "wrong session (and now spent)"); + assert.equal(auth.redeemTicket(a.ticket, "ses_a"), undefined); + const b = auth.mintTicket(principal, "ses_a"); + assert.deepEqual(auth.redeemTicket(b.ticket, "ses_a"), principal); + assert.equal(auth.redeemTicket(b.ticket, "ses_a"), undefined); + const c = auth.mintTicket(principal, "ses_a"); + clock += 60_000; + assert.equal(auth.redeemTicket(c.ticket, "ses_a"), undefined); +}); + +test("helpers: code normalization, constant-time compare, scope parsing", () => { + assert.equal(normalizePairingCode(" abcd-efgh "), "ABCDEFGH"); + assert.equal(normalizePairingCode("o1il"), "0111"); + assert.equal(sameSecret("abc", "abc"), true); + assert.equal(sameSecret("abc", "abcd"), false); + assert.equal(sameSecret("", ""), false); + assert.deepEqual(parseScopes(["sessions:read,admin", "admin"]), { scopes: ["sessions:read", "admin"] }); + assert.deepEqual(parseScopes(["root"]), { error: 'unknown scope "root" (expected sessions:read, sessions:operate, terminal, admin)' }); + assert.deepEqual(parseScopes([","]), { error: "--scope needs at least one scope" }); +}); diff --git a/tests/serve-checks.test.ts b/tests/serve-checks.test.ts new file mode 100644 index 000000000..feab6db5c --- /dev/null +++ b/tests/serve-checks.test.ts @@ -0,0 +1,177 @@ +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { setupLaunch } from "../lib/serve-cli.ts"; +import { parseVersion, ServeChecks, settingsList, type ServeCheck, type ServeChecksOptions } from "../lib/serve-checks.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { after, before, call, pairDevice, stream, test } from "./serve-test-client.ts"; + +const ADMIN = "gsa_test-admin-token"; +const LAUNCHER = fileURLToPath(new URL("../bin/gentle-shell.mjs", import.meta.url)); +// Fake tools are shell scripts the kernel runs by their `#!` line. +const skip = process.platform === "win32" ? "fake tools are POSIX scripts" : false; +let root: string; +let server: ServeServer | undefined; + +before(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), "gentle-serve-checks-"))); +}); +after(async () => { + await server?.close(); + rmSync(root, { recursive: true, force: true }); +}); + +let dirs = 0; +/** A folder of fake tools: `name` → its script body (after `#!/bin/sh`). */ +function tools(scripts: Record): string { + const dir = join(root, `bin${(dirs += 1)}`); + mkdirSync(dir); + for (const [name, body] of Object.entries(scripts)) { + writeFileSync(join(dir, name), `#!/bin/sh\n${body}\n`); + chmodSync(join(dir, name), 0o755); + } + return dir; +} + +/** A fake `gentle-shell setup --check --json`: prints `report`, exits with `code`. */ +function companion(report: unknown, code: number): ServeChecksOptions["companion"] { + const dir = tools({ "setup-check": `printf '%s\\n' '${JSON.stringify(report)}'\nexit ${code}` }); + return () => ({ command: join(dir, "setup-check"), args: [], cwd: root, env: {} }); +} + +const report = (needsSetup: boolean, reasons: string[], mode = "isolated") => ({ schema: "gentle-shell.setup-check/v1", needsSetup, home: { mode }, reasons, foreign: false }); + +function agentHome(name: string, provisioned?: Record): { home: string; config: string } { + const home = join(root, name); + mkdirSync(home); + const config = join(root, `${name}-config.json`); + writeFileSync(config, JSON.stringify(provisioned === undefined ? {} : { provisioned: { [home]: provisioned } })); + return { home, config }; +} + +const byId = (checks: ServeCheck[]) => Object.fromEntries(checks.map((check) => [check.id, check])); + +test("parseVersion reads versions the way the app's checklist does", () => { + assert.deepEqual(parseVersion("v22.19.0\n"), [22, 19, 0]); + assert.deepEqual(parseVersion("3.0.0-beta.1"), [3, 0, 0]); + assert.deepEqual(parseVersion("22.19"), [22, 19, 0]); + assert.equal(parseVersion("nope"), undefined); + assert.equal(settingsList({ packages: ["npm:gentle-engram@1.2.0"] }, "gentle-engram"), true); + assert.equal(settingsList({ packages: [{ source: "npm:@scope/x@1" }, "npm:gentle-engram-extra"] }, "gentle-engram"), false); +}); + +test("everything in place: ok rows with versions, the companion's setup record", { skip }, async () => { + const bin = tools({ node: "echo v22.19.0", npm: "echo 10.9.0", git: "echo 'git version 2.47.1'", engram: "echo 'engram v3.1.0'; echo 'A newer version is available'" }); + const { home, config } = agentHome("ready", { gentleAi: "1.40.2", gentlePi: "5.0.0", at: "2026-11-20T10:00:00.000Z" }); + const checks = new ServeChecks({ env: { PATH: bin, GENTLE_SHELL_CONFIG: config }, agentHome: home, companion: companion(report(false, []), 0) }); + const rows = await checks.checks(); + assert.deepEqual(rows.map((row) => row.id), ["node", "companion", "git", "engram"]); + assert.deepEqual(byId(rows), { + node: { id: "node", state: "ok", version: "22.19.0", detail: "npm 10.9.0" }, + companion: { id: "companion", state: "ok", version: "1.40.2", detail: "Set up 2026-11-20" }, + git: { id: "git", state: "ok", version: "2.47.1", detail: null }, + engram: { id: "engram", state: "ok", version: "3.1.0", detail: "engram v3.1.0" }, + }); +}); + +test("nothing installed: missing rows", { skip }, async () => { + const { home, config } = agentHome("bare"); + const checks = new ServeChecks({ env: { PATH: tools({}), GENTLE_SHELL_CONFIG: config }, agentHome: home, companion: companion(report(true, ["never-provisioned"]), 1) }); + assert.deepEqual(byId(await checks.checks()), { + node: { id: "node", state: "missing", version: null, detail: "Node.js isn't installed" }, + companion: { id: "companion", state: "missing", version: null, detail: "Not set up yet — the first chat would do it silently" }, + git: { id: "git", state: "missing", version: null, detail: "Git isn't installed" }, + engram: { id: "engram", state: "missing", version: null, detail: "Not installed" }, + }); +}); + +test("old versions, a missing npm, a stale setup and a broken ENGRAM_BIN are errors that say why", { skip }, async () => { + const old = tools({ node: "echo v20.11.1", npm: "echo 10.2.4", git: "exit 1", engram: "echo 'engram 2.1.0'" }); + const { home, config } = agentHome("stale", { gentleAi: "1.40.2", gentlePi: "4.9.0", at: "2026-01-02T00:00:00.000Z" }); + const stale = new ServeChecks({ env: { PATH: old, GENTLE_SHELL_CONFIG: config }, agentHome: home, version: "5.0.0", companion: companion(report(true, ["gentle-pi-changed"]), 1) }); + assert.deepEqual(byId(await stale.checks()), { + node: { id: "node", state: "error", version: "20.11.1", detail: "Node 20.11.1 — needs 22.19.0 or newer" }, + companion: { id: "companion", state: "error", version: "1.40.2", detail: "Set up with gentle-pi 4.9.0; 5.0.0 is installed" }, + git: { id: "git", state: "missing", version: null, detail: "Git isn't installed" }, + engram: { id: "engram", state: "error", version: "2.1.0", detail: "Engram 2.1.0 — needs 3.0.0 or newer" }, + }); + + const noNpm = tools({ node: "echo v24.1.0", engram: "echo 'engram 3.0.0'" }); + const other = new ServeChecks({ env: { PATH: noNpm, ENGRAM_BIN: join(root, "no-engram") }, companion: companion({ schema: "gentle-shell.setup-check/v1", error: "could not read the launcher config or home (EACCES)" }, 3) }); + const rows = byId(await other.checks()); + assert.deepEqual(rows.node, { id: "node", state: "missing", version: "24.1.0", detail: "Node 24.1.0 found, but not npm" }); + assert.deepEqual(rows.engram, { id: "engram", state: "error", version: null, detail: `ENGRAM_BIN points to ${join(root, "no-engram")}, which can't be run. Fix or remove it.` }); + assert.deepEqual(rows.companion, { id: "companion", state: "error", version: null, detail: "`gentle-shell setup --check` failed: could not read the launcher config or home (EACCES)" }); + + // ENGRAM_BIN wins over the PATH; a tool that hangs is killed at its timeout and counts as not running. + const hang = tools({ node: "exec /bin/sleep 30", engram: "echo 'engram 3.2.0'" }); + const slow = new ServeChecks({ env: { PATH: noNpm, ENGRAM_BIN: join(hang, "engram") }, limits: { toolTimeoutMs: 200 } }); + const slowRows = byId(await slow.checks()); + assert.equal(slowRows.engram.version, "3.2.0"); + assert.equal(slowRows.companion.state, "error", "no companion check without the launcher"); + const timed = byId(await new ServeChecks({ env: { PATH: hang }, limits: { toolTimeoutMs: 200 } }).checks()); + assert.deepEqual(timed.node, { id: "node", state: "error", version: null, detail: `${join(hang, "node")} doesn't run` }); +}); + +test("a --link home is set up once its settings list gentle-engram", { skip }, async () => { + const { home, config } = agentHome("linked"); + const linked = () => new ServeChecks({ env: { PATH: tools({}), GENTLE_SHELL_CONFIG: config }, agentHome: home, companion: companion(report(true, ["never-provisioned"], "link"), 1) }); + assert.deepEqual(byId(await linked().checks()).companion, { id: "companion", state: "missing", version: null, detail: `${home} isn't set up yet` }); + writeFileSync(join(home, "settings.json"), JSON.stringify({ packages: ["npm:gentle-engram@1.0.0"] })); + assert.deepEqual(byId(await linked().checks()).companion, { id: "companion", state: "ok", version: null, detail: `Linked to ${home}` }); +}); + +test("the real launcher's setup --check answers the companion row", { skip }, async () => { + const fakeHome = join(root, "user"); + const { home, config } = agentHome("real"); + mkdirSync(fakeHome); + const env = { PATH: tools({}), HOME: fakeHome, USERPROFILE: fakeHome, GENTLE_SHELL_CONFIG: config }; + const launch = () => setupLaunch({ launcher: LAUNCHER, nodePath: process.execPath, homeFlags: ["--home", home], env }, ["--check", "--json"]); + assert.deepEqual(launch().args.slice(-3), ["setup", "--check", "--json"]); + const checks = new ServeChecks({ env, agentHome: home, companion: launch }); + assert.deepEqual(byId(await checks.checks()).companion, { id: "companion", state: "missing", version: null, detail: "Not set up yet — the first chat would do it silently" }); +}); + +test("GET /api/checks: sessions:read, the checks capability, one result per cache window, fresh after a setup job", { skip }, async () => { + let now = 1_000_000; + const bin = tools({ node: "read -r v < \"${0%/*}/version\"; echo \"$v\"", npm: "echo 10.9.0", git: "echo 'git version 2.47.1'" }); + writeFileSync(join(bin, "version"), "v22.19.0\n"); + // A setup job that installs a newer Node. + const setup = tools({ setup: `printf 'v24.1.0\\n' > '${join(bin, "version")}'` }); + server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth: new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }), + version: "test", + launchSession: () => { throw new Error("no sessions here"); }, + env: { PATH: bin }, + checks: { companion: companion(report(false, []), 0), now: () => now }, + upgrade: { launch: () => { throw new Error("no upgrades here"); }, onUpgraded: () => {}, setup: () => ({ command: join(setup, "setup"), args: [], cwd: root, env: {} }) }, + }); + const reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader"); + assert.ok((await call(server.url, "GET", "/api/server", { token: reader.token })).body.capabilities.includes("checks")); + assert.equal((await call(server.url, "GET", "/api/checks")).status, 401); + assert.equal((await call(server.url, "POST", "/api/checks", { token: reader.token })).status, 405); + + const first = await call(server.url, "GET", "/api/checks", { token: reader.token }); + assert.equal(first.status, 200); + assert.deepEqual(Object.keys(first.body), ["checks"]); + for (const row of first.body.checks) assert.deepEqual(Object.keys(row), ["id", "state", "version", "detail"]); + assert.deepEqual(first.body.checks.map((row: ServeCheck) => [row.id, row.state]), [["node", "ok"], ["companion", "ok"], ["git", "ok"], ["engram", "missing"]]); + + writeFileSync(join(bin, "version"), "v20.0.0\n"); + now += 5_000; + assert.equal(byId((await call(server.url, "GET", "/api/checks", { token: reader.token })).body.checks).node.version, "22.19.0", "cached"); + now += 5_000; + assert.deepEqual(byId((await call(server.url, "GET", "/api/checks", { token: reader.token })).body.checks).node, { id: "node", state: "error", version: "20.0.0", detail: "Node 20.0.0 — needs 22.19.0 or newer" }); + + const job = await call(server.url, "POST", "/api/setup", { token: ADMIN, body: {} }); + assert.equal(job.status, 202); + const events = await stream(server.url, `/api/setup/${job.body.jobId}/stream`, ADMIN); + await events.waitFor("event: finished"); + await events.closed; + assert.equal(byId((await call(server.url, "GET", "/api/checks", { token: reader.token })).body.checks).node.version, "24.1.0", "the job's end clears the cache"); +}); diff --git a/tests/serve-cli.test.ts b/tests/serve-cli.test.ts new file mode 100644 index 000000000..0037f8978 --- /dev/null +++ b/tests/serve-cli.test.ts @@ -0,0 +1,220 @@ +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { helpText, parseLauncherArgs } from "../lib/gentle-shell-launcher.ts"; +import { acquireServeLock, parseListen, parseServeArgs, readServerFile, serveFiles, sessionLaunch } from "../lib/serve-cli.ts"; +import { isLoopbackHost } from "../lib/serve-server.ts"; +import { after, endServeLeftovers, remainingServeLeftovers, test } from "./serve-test-client.ts"; + +const binPath = fileURLToPath(new URL("../bin/gentle-shell.mjs", import.meta.url)); +const roots: string[] = []; +after(async () => { + // A failed test must not leave a server daemon behind. + await endServeLeftovers([], roots); + roots.forEach((r) => rmSync(r, { recursive: true, force: true })); +}); +function scratch(): string { + const r = mkdtempSync(join(tmpdir(), "gentle-serve-cli-")); + roots.push(r); + return r; +} + +test("serve is a launcher command that takes the home selectors ahead of it", () => { + const plain = parseLauncherArgs(["serve", "--foreground"]); + assert.equal(plain.command, "serve"); + assert.deepEqual(plain.commandArgs, ["--foreground"]); + const home = parseLauncherArgs(["--home", "/tmp/h", "serve", "pair", "--scope", "admin"]); + assert.equal(home.command, "serve"); + assert.equal(home.home, "/tmp/h"); + assert.deepEqual(home.commandArgs, ["pair", "--scope", "admin"]); + assert.equal(parseLauncherArgs(["--", "serve"]).command, undefined); + assert.deepEqual(parseLauncherArgs(["install", "serve"]).passthrough, ["install", "serve"]); + assert.match(helpText(), /\n serve +Run a per-user server/); + assert.match(helpText(), /gentle-shell \[home selectors\] serve \[--listen :\]/); +}); + +test("parseServeArgs reads each subcommand and rejects what it does not know", () => { + assert.deepEqual(parseServeArgs([]), { action: "start", host: "127.0.0.1", port: 0, foreground: false, json: false }); + assert.deepEqual(parseServeArgs(["--foreground", "--listen", "0.0.0.0:8787"]), { action: "start", host: "0.0.0.0", port: 8787, foreground: true, json: false }); + assert.deepEqual(parseServeArgs(["--listen=localhost:9000", "--json"]), { action: "start", host: "127.0.0.1", port: 9000, foreground: false, json: true }); + assert.deepEqual(parseServeArgs(["status", "--json"]), { action: "status", json: true }); + assert.deepEqual(parseServeArgs(["stop"]), { action: "stop", endSessions: false }); + assert.deepEqual(parseServeArgs(["stop", "--sessions"]), { action: "stop", endSessions: true }); + assert.deepEqual(parseServeArgs(["pair"]), { action: "pair", scopes: ["sessions:read", "sessions:operate", "terminal"], json: false }); + assert.deepEqual(parseServeArgs(["pair", "--scope", "sessions:read", "--scope=admin"]), { action: "pair", scopes: ["sessions:read", "admin"], json: false }); + assert.deepEqual(parseServeArgs(["devices", "--revoke", "dev_123"]), { action: "devices", revoke: "dev_123", json: false }); + assert.deepEqual(parseServeArgs(["--help"]), { action: "help" }); + assert.deepEqual(parseServeArgs(["stop", "--json"]), { error: 'unknown serve stop argument "--json"' }); + assert.deepEqual(parseServeArgs(["status", "--listen", "1:2"]), { error: 'unknown serve status argument "--listen"' }); + assert.deepEqual(parseServeArgs(["pair", "--scope", "root"]), { error: 'unknown scope "root" (expected sessions:read, sessions:operate, terminal, admin)' }); + assert.deepEqual(parseServeArgs(["devices", "--revoke", "../x"]), { error: "--revoke needs a device id" }); + assert.deepEqual(parseServeArgs(["--listen"]), { error: "--listen needs :" }); + assert.deepEqual(parseServeArgs(["--listen", "0.0.0.0:8787", "--allow-host", "Box.tail1234.ts.net", "--allow-host=nas.lan", "--allow-host", "box.tail1234.ts.net"]), + { action: "start", host: "0.0.0.0", port: 8787, foreground: false, json: false, allowHosts: ["box.tail1234.ts.net", "nas.lan"] }); + assert.deepEqual(parseServeArgs(["--allow-host"]), { error: '--allow-host needs a DNS name without a port (got "")' }); + assert.deepEqual(parseServeArgs(["--allow-host", "box.lan:8787"]), { error: '--allow-host needs a DNS name without a port (got "box.lan:8787")' }); + assert.deepEqual(parseServeArgs(["--allow-host", "*.ts.net"]), { error: '--allow-host needs a DNS name without a port (got "*.ts.net")' }); + assert.deepEqual(parseServeArgs(["--forward-ports", "8800-8899"]), { action: "start", host: "127.0.0.1", port: 0, foreground: false, json: false, forwardPorts: { from: 8800, to: 8899 } }); + assert.deepEqual(parseServeArgs(["--forward-ports=9000-9000"]), { action: "start", host: "127.0.0.1", port: 0, foreground: false, json: false, forwardPorts: { from: 9000, to: 9000 } }); + for (const bad of ["8899-8800", "0-10", "1-70000", "8800", "1-2000"]) assert.deepEqual(parseServeArgs(["--forward-ports", bad]), { error: `--forward-ports needs a port range like 8800-8899 (got "${bad}")` }); + assert.deepEqual(parseServeArgs(["share", "--forward-ports", "1-2"]), { error: 'unknown serve share argument "--forward-ports"' }); + assert.deepEqual(parseServeArgs(["status", "--allow-host", "box.lan"]), { error: 'unknown serve status argument "--allow-host"' }); +}); + +test("parseListen accepts host:port, [v6]:port, :port and a bare port", () => { + assert.deepEqual(parseListen("127.0.0.1:0"), { host: "127.0.0.1", port: 0 }); + assert.deepEqual(parseListen("[::1]:8787"), { host: "::1", port: 8787 }); + assert.deepEqual(parseListen(":8787"), { host: "127.0.0.1", port: 8787 }); + assert.deepEqual(parseListen("8787"), { host: "127.0.0.1", port: 8787 }); + assert.deepEqual(parseListen("box.local:80"), { host: "box.local", port: 80 }); + assert.deepEqual(parseListen("1.2.3.4:70000"), { error: '--listen port must be 0-65535 (got "70000")' }); + assert.deepEqual(parseListen("nope"), { error: '--listen needs : (got "nope")' }); + assert.ok(isLoopbackHost("127.0.0.1") && isLoopbackHost("::1") && isLoopbackHost("[::1]") && isLoopbackHost("localhost")); + assert.ok(!isLoopbackHost("0.0.0.0") && !isLoopbackHost("192.168.1.2")); +}); + +test("the lock admits one server per home and takes over a stale one", () => { + const lock = join(scratch(), "server.lock"); + assert.deepEqual(acquireServeLock(lock), { acquired: true }); + // Another live process (this test's parent) asking for the same lock is refused. + assert.deepEqual(acquireServeLock(lock, process.ppid), { heldBy: process.pid }); + writeFileSync(lock, "999999999\n"); + assert.deepEqual(acquireServeLock(lock), { acquired: true }, "a dead pid's lock is stale"); +}); + +test("a session child is this launcher with the same home, in Pi RPC mode with the Desktop marker", () => { + const launch = sessionLaunch({ homeFlags: ["--home", "/h"], launcher: "/pkg/bin/gentle-shell.mjs", nodePath: "/node", env: { PATH: "/bin" } }, { cwd: "/w", sessionId: "abc" }); + // By exact id, created when missing: `--session` fails on a conversation Pi never wrote. + assert.deepEqual(launch.args, ["/pkg/bin/gentle-shell.mjs", "--home", "/h", "--mode", "rpc", "--session-id", "abc"]); + assert.equal(launch.command, "/node"); + assert.equal(launch.cwd, "/w"); + assert.equal(launch.env.GENTLE_SHELL_INTERACTIVE_HOST, "1"); + assert.equal(launch.env.GENTLE_DESIGN_OPEN_BROWSER, "0"); + assert.equal(launch.env.PATH, "/bin"); +}); + +function isolatedEnv(root: string): NodeJS.ProcessEnv { + return { HOME: root, USERPROFILE: root, PATH: process.env.PATH, GENTLE_SHELL_NO_AUTO_SETUP: "1" }; +} + +function cli(root: string, args: string[]) { + return spawnSync(process.execPath, [binPath, "--home", join(root, "agent"), "serve", ...args], { env: isolatedEnv(root), encoding: "utf8", timeout: 30_000 }); +} + +// `serve stop` waits for the server pid to go away. When that server is this +// test's own child it stays a zombie until this event loop reaps it, so the +// stop must not block the loop the way spawnSync does. +function cliAsync(root: string, args: string[]): Promise<{ status: number | null; stdout: string; stderr: string }> { + const child = spawn(process.execPath, [binPath, "--home", join(root, "agent"), "serve", ...args], { env: isolatedEnv(root), stdio: ["ignore", "pipe", "pipe"] }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d; }); + child.stderr.on("data", (d) => { stderr += d; }); + const done = Promise.withResolvers<{ status: number | null; stdout: string; stderr: string }>(); + child.once("close", (status) => done.resolve({ status, stdout, stderr })); + return done.promise; +} + +test("gentle-shell serve end to end: foreground, single instance, status, pair, devices, stop", { timeout: 60_000 }, async (t) => { + const root = scratch(); + const home = join(root, "agent"); + const child = spawn(process.execPath, [binPath, "--home", home, "serve", "--foreground"], { env: isolatedEnv(root), stdio: ["ignore", "pipe", "pipe"] }); + t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); }); + let stdout = "", stderr = ""; + child.stderr.on("data", (d) => { stderr += d; }); + const ready = Promise.withResolvers(); + child.stdout.on("data", (d) => { + stdout += d; + const m = /Gentle Shell server: (http:\/\/127\.0\.0\.1:\d+) \(pid/.exec(stdout); + if (m) ready.resolve(m[1]); + }); + child.once("exit", () => ready.reject(new Error(`exited early: ${stderr}`))); + const url = await ready.promise; + + const files = serveFiles(home); + const server = readServerFile(files.server)!; + assert.equal(server.url, url); + assert.equal(server.pid, child.pid); + assert.equal(server.protocol, 1); + assert.match(server.adminToken, /^gsa_/); + if (process.platform !== "win32") { + assert.equal(statSync(files.server).mode & 0o777, 0o600); + assert.equal(statSync(files.dir).mode & 0o777, 0o700); + } + assert.ok(existsSync(join(home, ".gentle-shell-home")), "a new home is bootstrapped like a first launch"); + + const second = cli(root, ["--foreground"]); + assert.equal(second.status, 1); + assert.match(second.stderr, /already running \(pid \d+\) at http/); + + const status = cli(root, ["status", "--json"]); + assert.equal(status.status, 0, status.stderr); + assert.deepEqual({ ...JSON.parse(status.stdout), startedAt: undefined, version: undefined, serverId: undefined }, + { running: true, url, pid: child.pid, protocol: 1, sessions: [], startedAt: undefined, version: undefined, serverId: undefined }); + + const pair = cli(root, ["pair", "--json", "--scope", "sessions:read"]); + assert.equal(pair.status, 0, pair.stderr); + const minted = JSON.parse(pair.stdout); + assert.deepEqual(minted.scopes, ["sessions:read"]); + const human = cli(root, ["pair"]); + assert.match(human.stdout, /^Pairing code: [0-9A-Z]{4}-[0-9A-Z]{4}\nServer: +http/); + + const redeemed = await fetch(`${url}/api/pair`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: minted.code, name: "test phone" }) }); + assert.equal(redeemed.status, 201); + const device = await redeemed.json(); + const list = await fetch(`${url}/api/sessions`, { headers: { Authorization: `Bearer ${device.token}` } }); + assert.equal(list.status, 200); + + const devices = cli(root, ["devices", "--json"]); + assert.deepEqual(JSON.parse(devices.stdout).devices.map((d: { id: string }) => d.id), [device.id]); + const revoke = cli(root, ["devices", "--revoke", device.id]); + assert.equal(revoke.status, 0, revoke.stderr); + assert.equal((await fetch(`${url}/api/sessions`, { headers: { Authorization: `Bearer ${device.token}` } })).status, 401); + + const exited = new Promise((resolve) => child.once("exit", (code) => resolve(code))); + const stop = await cliAsync(root, ["stop"]); + assert.equal(stop.status, 0, stop.stderr); + assert.equal(stop.stdout, "Stopped.\n"); + assert.equal(await exited, 0); + assert.ok(!existsSync(files.server) && !existsSync(files.lock), "the server file and lock are removed"); + const gone = cli(root, ["status"]); + assert.equal(gone.status, 1); + assert.equal(gone.stderr, "gentle-shell serve: not running\n"); + assert.equal(cli(root, ["stop"]).status, 0, "stopping a stopped server is not an error"); + + // Without a server the devices file is still listable. + const offline = cli(root, ["devices"]); + assert.equal(offline.stdout, "No paired devices.\n"); + assert.ok(!readFileSync(files.devices, "utf8").includes(device.token)); +}); + +test("gentle-shell serve starts a background daemon that serve stop ends", { timeout: 60_000 }, async () => { + const root = scratch(); + const started = cli(root, ["--json"]); + assert.equal(started.status, 0, started.stderr); + const info = JSON.parse(started.stdout); + assert.match(info.url, /^http:\/\/127\.0\.0\.1:\d+$/); + try { + const again = cli(root, []); + assert.equal(again.status, 1); + assert.match(again.stderr, /already running/); + assert.equal(cli(root, ["status"]).status, 0); + } finally { + const stop = cli(root, ["stop"]); + assert.equal(stop.status, 0, stop.stderr); + } + assert.equal(cli(root, ["status"]).status, 1); + assert.match(readFileSync(serveFiles(join(root, "agent")).log, "utf8"), /stopping/); +}); + +test("gentle-shell serve with a bad argument exits 2", () => { + const result = cli(scratch(), ["--port", "1"]); + assert.equal(result.status, 2); + assert.equal(result.stderr, `gentle-shell serve: unknown serve argument "--port"\nRun 'gentle-shell serve --help' for usage.\n`); +}); + +test("no server daemon outlives the tests above", async () => { + assert.deepEqual(await remainingServeLeftovers([], roots), []); +}); diff --git a/tests/serve-desktop.test.ts b/tests/serve-desktop.test.ts new file mode 100644 index 000000000..281583dac --- /dev/null +++ b/tests/serve-desktop.test.ts @@ -0,0 +1,267 @@ +// `POST /api/desktop` and `GET /api/desktop/events`: Desktop RPC without a +// session of the client's own, answered by serve's hidden control session (a +// fake Pi here: no model, no turn). + +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { startServeServer, type ServeServer, type ServeServerOptions } from "../lib/serve-server.ts"; +import { keeperAlive, newKeeperToken, spawnKeeper, type KeeperRecord } from "../lib/serve-session-keeper.ts"; +import { after, call, endServeLeftovers, pairDevice, remainingServeLeftovers, stream, test } from "./serve-test-client.ts"; + +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); +const ADMIN = "gsa_test-admin-token"; +const roots: string[] = []; +const sessionDirs = () => roots.map((root) => join(root, "serve", "sessions")); +after(async () => { + // A failed test must not leave a keeper (or its fake Pi) behind. + await endServeLeftovers(sessionDirs(), roots); + roots.forEach((root) => rmSync(root, { recursive: true, force: true })); +}); + +function serveDir(): string { + const root = mkdtempSync(join(tmpdir(), "gs-desk-")); + roots.push(root); + return join(root, "serve"); +} + +function serve(dir: string, launches: Array<{ cwd: string }> = [], extra: Partial = {}): Promise { + return startServeServer({ + host: "127.0.0.1", + port: 0, + auth: new ServeAuth({ devicesFile: join(dir, "devices.json"), adminToken: ADMIN }), + version: "test", + serveDir: dir, + launchSession: (input) => { + launches.push(input); + return { command: process.execPath, args: [FAKE_PI], cwd: input.cwd, env: { ...process.env, GENTLE_SHELL_INTERACTIVE_HOST: "1" } }; + }, + limits: { rpcTimeoutMs: 3000 }, + ...extra, + }); +} + +/** The control session's id and keeper record, as serve keeps them beside the other keepers. */ +function controlOf(dir: string): { id: string; record: KeeperRecord } | undefined { + const file = join(dir, "sessions", "control"); + if (!existsSync(file)) return undefined; + const id = readFileSync(file, "utf8").trim(); + const record = JSON.parse(readFileSync(join(dir, "sessions", `${id}.json`), "utf8")) as KeeperRecord; + return { id, record }; +} + +async function until(check: () => boolean, what: string, timeoutMs = 8000): Promise { + const deadline = Date.now() + timeoutMs; + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((r) => setTimeout(r, 20)); + } +} + +/** The `id:`/`data:` records of an SSE text. */ +function records(text: string): Array<{ seq: number; record: Record }> { + const out: Array<{ seq: number; record: Record }> = []; + for (const block of text.split("\n\n")) { + const id = /^id: (\d+)$/m.exec(block); + const data = /^data: (.*)$/m.exec(block); + if (id && data) out.push({ seq: Number(id[1]), record: JSON.parse(data[1]) }); + } + return out; +} + +const eventName = (record: Record) => JSON.parse(record.widgetLines[0]).event as string; + +test("the control session starts on first use in the server's home, answers Desktop RPC, and is hidden from the session list", { timeout: 30_000 }, async () => { + const dir = serveDir(); + const launches: Array<{ cwd: string }> = []; + const server = await serve(dir, launches); + try { + const info = await call(server.url, "GET", "/api/server", { token: ADMIN }); + assert.ok(info.body.capabilities.includes("desktop")); + assert.equal(launches.length, 0, "nothing starts before a client uses it"); + assert.equal(controlOf(dir), undefined); + + const answer = await call(server.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "get_config", params: { store: "pi_settings" } } }); + assert.equal(answer.status, 200, JSON.stringify(answer.body)); + assert.equal(answer.body.kind, "response"); + assert.equal(answer.body.ok, true); + assert.deepEqual(answer.body.data, { method: "get_config", params: { store: "pi_settings" } }); + assert.deepEqual(launches.map((l) => l.cwd), [homedir()], "one session, in the server user's home folder"); + const control = controlOf(dir)!; + assert.ok(control, "serve names its control session beside the keepers"); + + // A second request reuses it. + assert.equal((await call(server.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "capabilities" } })).status, 200); + assert.equal(launches.length, 1); + + const listed = await call(server.url, "GET", "/api/sessions", { token: ADMIN }); + assert.deepEqual(listed.body.sessions, [], "never in the list"); + const byId = await call(server.url, "GET", `/api/sessions/${control.id}`, { token: ADMIN }); + assert.equal(byId.status, 404, "nor reachable as a session"); + assert.equal((await call(server.url, "POST", `/api/sessions/${control.id}/rpc`, { token: ADMIN, body: { type: "prompt", message: "hi" } })).status, 404, "no model turn through it"); + const admin = await call(server.url, "GET", "/api/sessions?includeControl=1", { token: ADMIN }); + assert.equal(admin.body.sessions.length, 1); + assert.equal(admin.body.sessions[0].id, control.id); + assert.equal(admin.body.sessions[0].control, true); + const device = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"]); + const notAdmin = await call(server.url, "GET", "/api/sessions?includeControl=1", { token: device.token }); + assert.deepEqual(notAdmin.body.sessions, [], "only an admin sees it"); + } finally { + await server.close({ endSessions: true }); + } + assert.equal(controlOf(dir), undefined, "stopping it with the server forgets it"); +}); + +test("scopes per method as /desktop; host tool methods and bad requests are refused before the session starts", { timeout: 30_000 }, async () => { + const dir = serveDir(); + const launches: Array<{ cwd: string }> = []; + const server = await serve(dir, launches); + try { + const reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader"); + const operator = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"], "operator"); + assert.equal((await call(server.url, "POST", "/api/desktop", { body: { method: "capabilities" } })).status, 401); + for (const method of ["set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context", "set_host_activity"]) { + const refused = await call(server.url, "POST", "/api/desktop", { token: operator.token, body: { method, params: {} } }); + assert.equal(refused.status, 400, method); + assert.equal(refused.body.error.code, "use_session_desktop", method); + } + assert.equal((await call(server.url, "POST", "/api/desktop", { token: operator.token, body: { method: "Bad Method" } })).status, 400); + assert.equal((await call(server.url, "POST", "/api/desktop", { token: operator.token, body: { method: "get_config", params: [] } })).status, 400); + for (const method of ["login_start", "set_config", "install_package", "set_api_key"]) { + const refused = await call(server.url, "POST", "/api/desktop", { token: reader.token, body: { method, params: {} } }); + assert.equal(refused.status, 403, method); + } + assert.equal((await call(server.url, "GET", "/api/desktop", { token: operator.token })).status, 405); + assert.equal(launches.length, 0, "no refused request starts the control session"); + + for (const method of ["capabilities", "get_auth_status", "list_available_models", "list_packages", "get_config"]) { + const read = await call(server.url, "POST", "/api/desktop", { token: reader.token, body: { method } }); + assert.equal(read.status, 200, method); + } + const write = await call(server.url, "POST", "/api/desktop", { token: operator.token, body: { method: "set_config", params: { store: "pi_settings", data: {} } } }); + assert.equal(write.status, 200); + assert.equal(launches.length, 1); + } finally { + await server.close({ endSessions: true }); + } +}); + +test("GET /api/desktop/events carries only the control session's Desktop events, resumes by seq and takes a desktop ticket", { timeout: 30_000 }, async () => { + const dir = serveDir(); + const server = await serve(dir); + try { + const device = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"]); + // Opening the stream starts the session too. + const events = await stream(server.url, "/api/desktop/events", device.token); + assert.equal(events.status, 200); + await events.waitFor("event: hello"); + const login = await call(server.url, "POST", "/api/desktop", { token: device.token, body: { method: "login_start", params: { provider: "anthropic" } } }); + assert.equal(login.status, 200); + await events.waitFor('\\"event\\":\\"login_prompt\\"'); + const install = await call(server.url, "POST", "/api/desktop", { token: device.token, body: { method: "install_package", params: { source: "npm:pi-btw" } } }); + assert.equal(install.status, 200); + await events.waitFor('\\"event\\":\\"package_finished\\"'); + const seen = records(events.text); + assert.deepEqual(seen.map((r) => eventName(r.record)), ["login_prompt", "package_progress", "package_finished"], "events only: no Pi response, no Desktop answer"); + assert.ok(seen.every((r, i) => i === 0 || r.seq > seen[i - 1]!.seq), "the session's own seq, increasing"); + events.close(); + + // Resuming after the first event replays exactly the rest. + const resumed = await stream(server.url, `/api/desktop/events?after=${seen[0]!.seq}`, device.token); + await resumed.waitFor('\\"event\\":\\"package_finished\\"'); + assert.deepEqual(records(resumed.text).map((r) => eventName(r.record)), ["package_progress", "package_finished"]); + resumed.close(); + const ahead = await stream(server.url, "/api/desktop/events?after=999999", device.token); + await ahead.waitFor("event: snapshot-required"); + ahead.close(); + assert.equal((await call(server.url, "GET", "/api/desktop/events?after=x", { token: device.token })).status, 400); + + // EventSource-style: a single-use ticket bound to this stream. + const minted = await call(server.url, "POST", "/api/tickets", { token: device.token, body: { stream: "desktop" } }); + assert.equal(minted.status, 201); + const ticketed = await stream(server.url, `/api/desktop/events?ticket=${minted.body.ticket}&after=0`); + assert.equal(ticketed.status, 200); + await ticketed.waitFor('\\"event\\":\\"package_finished\\"'); + ticketed.close(); + assert.equal((await call(server.url, "GET", `/api/desktop/events?ticket=${minted.body.ticket}`)).status, 401, "single use"); + assert.equal((await call(server.url, "POST", "/api/tickets", { token: device.token, body: { stream: "other" } })).status, 400); + assert.equal((await call(server.url, "GET", "/api/desktop/events")).status, 401); + } finally { + await server.close({ endSessions: true }); + } +}); + +test("the control session stops when idle, not while a stream is open, and starts again on the next use", { timeout: 30_000 }, async () => { + const dir = serveDir(); + const launches: Array<{ cwd: string }> = []; + const server = await serve(dir, launches, { limits: { rpcTimeoutMs: 3000, controlIdleMs: 300 } }); + try { + const events = await stream(server.url, "/api/desktop/events", ADMIN); + await events.waitFor("event: hello"); + const first = controlOf(dir)!; + assert.equal((await call(server.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "capabilities" } })).status, 200); + // Twice the idle time on the real clock: the keeper is another process, so its staying alive is all there is to observe. + await new Promise((r) => setTimeout(r, 700)); + assert.ok(keeperAlive(first.record.keeperPid), "an open stream keeps it"); + assert.equal(launches.length, 1); + events.close(); + await until(() => !keeperAlive(first.record.keeperPid), "the idle control session to stop"); + await until(() => controlOf(dir) === undefined, "serve to forget it"); + assert.equal(existsSync(join(dir, "sessions", `${first.id}.json`)), false, "its record goes with it"); + + assert.equal((await call(server.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "capabilities" } })).status, 200); + const second = controlOf(dir)!; + assert.notEqual(second.id, first.id, "a new one on the next use"); + assert.equal(launches.length, 2); + } finally { + await server.close({ endSessions: true }); + } +}); + +test("the control session ends with its server; one an older server left is stopped, never taken back, while agent sessions are", { timeout: 30_000 }, async () => { + const dir = serveDir(); + const sessionsDir = join(dir, "sessions"); + const launches: Array<{ cwd: string }> = []; + const first = await serve(dir, launches); + assert.equal((await call(first.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "capabilities" } })).status, 200); + const control = controlOf(dir)!; + const created = await call(first.url, "POST", "/api/sessions", { token: ADMIN, body: { cwd: realpathSync(homedir()) } }); + assert.equal(created.status, 201, JSON.stringify(created.body)); + const agentId = created.body.session.id as string; + await first.close(); + assert.equal(controlOf(dir), undefined, "the close stops the control session and forgets it"); + await until(() => !keeperAlive(control.record.keeperPid), "its keeper to end with it"); + + // A control session the way a crashed or older server leaves it: its keeper running the old code, named beside the keepers. + const staleId = `ses_${randomBytes(8).toString("hex")}`; + await spawnKeeper({ id: staleId, dir: sessionsDir, token: newKeeperToken(), launch: { command: process.execPath, args: [FAKE_PI], cwd: homedir(), env: { ...process.env, GENTLE_SHELL_INTERACTIVE_HOST: "1" } } }); + writeFileSync(join(sessionsDir, "control"), `${staleId}\n`, { mode: 0o600 }); + const stale = controlOf(dir)!; + assert.ok(keeperAlive(stale.record.keeperPid)); + + const second = await serve(dir, launches); + try { + await until(() => !keeperAlive(stale.record.keeperPid), "the next server to stop the old control session"); + await until(() => controlOf(dir) === undefined, "serve to forget it"); + assert.equal(existsSync(join(sessionsDir, `${staleId}.json`)), false, "its record goes with it"); + const admin = await call(second.url, "GET", "/api/sessions?includeControl=1", { token: ADMIN }); + assert.deepEqual(admin.body.sessions.map((s: { id: string; state: string }) => [s.id, s.state]), [[agentId, "running"]], "the agent session reattached, no control session taken back"); + assert.equal((await call(second.url, "POST", `/api/sessions/${agentId}/rpc`, { token: ADMIN, body: { type: "get_state" } })).status, 200); + + assert.equal((await call(second.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "get_auth_status" } })).status, 200); + const fresh = controlOf(dir)!; + assert.ok(fresh.id !== staleId && fresh.id !== control.id, "a fresh control session, on this server's code"); + assert.equal(launches.length, 3, "started by this server: the first control, the agent session, the fresh control"); + } finally { + await second.close({ endSessions: true }); + } + assert.equal(controlOf(dir), undefined); +}); + +test("no session keeper or fake Pi outlives the tests above", async () => { + assert.deepEqual(await remainingServeLeftovers(sessionDirs(), roots), []); +}); diff --git a/tests/serve-discovery.test.ts b/tests/serve-discovery.test.ts new file mode 100644 index 000000000..e62a892de --- /dev/null +++ b/tests/serve-discovery.test.ts @@ -0,0 +1,158 @@ +import assert from "node:assert/strict"; +import { createSocket, type Socket } from "node:dgram"; +import { mkdtempSync, rmSync } from "node:fs"; +import { hostname, tmpdir } from "node:os"; +import { join } from "node:path"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { DISCOVERY_MAX_DATAGRAM, DiscoveryRateLimiter, isDiscoveryQuery, startDiscoveryResponder } from "../lib/serve-discovery.ts"; +import { startServeServer } from "../lib/serve-server.ts"; +import { test } from "./serve-test-client.ts"; + +const QUERY = Buffer.from(JSON.stringify({ t: "gentle-shell/discover", v: 1 })); + +interface Client { + socket: Socket; + replies: Buffer[]; + /** The next reply (matching `match`, when given). */ + nextReply(match?: (reply: Buffer) => boolean): Promise; +} + +async function client(): Promise { + const socket = createSocket("udp4"); + const replies: Buffer[] = []; + const waiters: Array<{ match: (reply: Buffer) => boolean; resolve: (reply: Buffer) => void }> = []; + socket.on("message", (m) => { + replies.push(m); + for (const w of waiters.splice(0)) { + if (w.match(m)) w.resolve(m); + else waiters.push(w); + } + }); + const bound = Promise.withResolvers(); + socket.bind(0, "127.0.0.1", () => bound.resolve()); + await bound.promise; + return { + socket, + replies, + nextReply: (match = () => true) => { + const { promise, resolve } = Promise.withResolvers(); + waiters.push({ match, resolve }); + return promise; + }, + }; +} + +/** A UDP socket bound exclusively on 0.0.0.0:`port`; rejects when the port is taken. */ +async function udpBind(port: number): Promise { + const socket = createSocket("udp4"); + const bound = Promise.withResolvers(); + socket.once("error", bound.reject); + socket.bind({ port, address: "0.0.0.0", exclusive: true }, () => bound.resolve(socket)); + return bound.promise; +} + +function send(socket: Socket, datagram: Buffer, port: number): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + socket.send(datagram, port, "127.0.0.1", (error) => (error ? reject(error) : resolve())); + return promise; +} + +test("a discovery query is exactly the documented JSON; junk and oversize datagrams are not", () => { + assert.equal(isDiscoveryQuery(QUERY), true); + assert.equal(isDiscoveryQuery(Buffer.from('{"t":"gentle-shell/discover","v":1,"x":2}')), true, "extra keys are ignored"); + for (const junk of ["", "hello", "null", "[]", '{"t":"gentle-shell/discover"}', '{"t":"gentle-shell/discover","v":2}', '{"t":"gentle-shell/discover","v":"1"}', '{"t":"gentle-shell/here","v":1}']) { + assert.equal(isDiscoveryQuery(Buffer.from(junk)), false, junk); + } + const padded = Buffer.from(JSON.stringify({ t: "gentle-shell/discover", v: 1, pad: "x".repeat(DISCOVERY_MAX_DATAGRAM) })); + assert.ok(padded.length > DISCOVERY_MAX_DATAGRAM); + assert.equal(isDiscoveryQuery(padded), false); +}); + +test("the rate limiter caps replies per source and overall in each one-second window", () => { + const limiter = new DiscoveryRateLimiter({ globalPerSecond: 5, perSourcePerSecond: 2 }); + assert.deepEqual([1, 2, 3].map(() => limiter.allow("a", 0)), [true, true, false]); + assert.deepEqual([1, 2, 3].map(() => limiter.allow("b", 10)), [true, true, false]); + assert.equal(limiter.allow("c", 20), true); + assert.equal(limiter.allow("d", 30), false, "the global cap"); + assert.equal(limiter.allow("a", 1000), true, "a new window"); +}); + +test("the responder answers a query by unicast with id, name and HTTP port, and ignores junk", async () => { + // The clock is read once per valid query: the 1st at 0, the 2nd-7th at 5000, then 7000. + let queries = 0; + let now = 0; + const clock = () => { queries += 1; now = queries === 1 ? 0 : queries <= 7 ? 5_000 : 7_000; return now; }; + const responder = await startDiscoveryResponder({ port: 0, serverId: "srv_test", httpPort: 8787, name: () => `box${now}`, now: clock }); + const { socket, replies, nextReply } = await client(); + try { + await send(socket, Buffer.from("hello"), responder.port); + await send(socket, Buffer.from('{"t":"gentle-shell/here","v":1}'), responder.port); + await send(socket, Buffer.concat([QUERY, Buffer.alloc(DISCOVERY_MAX_DATAGRAM)]), responder.port); + const answered = nextReply(); + await send(socket, QUERY, responder.port); + // One socket over loopback is processed in order: the junk before it got nothing. + assert.deepEqual(JSON.parse((await answered).toString("utf8")), { t: "gentle-shell/here", v: 1, id: "srv_test", n: "box0", p: 8787 }); + assert.equal(replies.length, 1); + + // Rate limit: 4 per source per second. Queries 2-7 share one window and query 8 starts the next; the + // name carries the window, so the reply to query 8 marks the end (one socket is processed in order). + replies.length = 0; + for (let i = 0; i < 6; i += 1) await send(socket, QUERY, responder.port); + const marker = nextReply((m) => JSON.parse(m.toString("utf8")).n === "box7000"); + await send(socket, QUERY, responder.port); + await marker; + assert.equal(replies.filter((m) => JSON.parse(m.toString("utf8")).n === "box5000").length, 4); + assert.equal(replies.length, 5, "the 5th and 6th queries of the window got nothing"); + } finally { + socket.close(); + await responder.close(); + } +}); + +test("a network server answers discovery on its HTTP port; a loopback server does not listen for it", async () => { + const root = mkdtempSync(join(tmpdir(), "gentle-serve-discovery-")); + const launchSession = () => { throw new Error("no sessions"); }; + const lan = await startServeServer({ host: "0.0.0.0", port: 0, auth: new ServeAuth({ devicesFile: join(root, "lan.json"), adminToken: "gsa_a" }), version: "test", launchSession }); + const loop = await startServeServer({ host: "127.0.0.1", port: 0, auth: new ServeAuth({ devicesFile: join(root, "loop.json"), adminToken: "gsa_b" }), version: "test", launchSession }); + const { socket, replies, nextReply } = await client(); + try { + assert.equal(lan.discovery, true); + assert.equal(loop.discovery, false); + const answered = nextReply(); + await send(socket, QUERY, lan.port); + const reply = JSON.parse((await answered).toString("utf8")); + assert.deepEqual(reply, { t: "gentle-shell/here", v: 1, id: lan.serverId, n: hostname(), p: lan.port }); + assert.equal(replies.length, 1); + const identity = await (await fetch(`http://127.0.0.1:${reply.p}/.well-known/gentle-shell`)).json(); + assert.equal(identity.serverId, reply.id); + + // Nothing holds UDP on the loopback server's port. + (await udpBind(loop.port)).close(); + } finally { + socket.close(); + await lan.close(); + await loop.close(); + rmSync(root, { recursive: true, force: true }); + } + // Closed with the server: the UDP port is free again. + (await udpBind(lan.port)).close(); +}); + +test("a taken UDP port leaves the network server running without discovery", async () => { + const root = mkdtempSync(join(tmpdir(), "gentle-serve-discovery-")); + const holder = await udpBind(0); + const port = holder.address().port; + const logs: string[] = []; + let server; + try { + server = await startServeServer({ host: "0.0.0.0", port, auth: new ServeAuth({ devicesFile: join(root, "d.json"), adminToken: "gsa_c" }), version: "test", + launchSession: () => { throw new Error("no sessions"); }, log: (l) => logs.push(l) }); + assert.equal(server.discovery, false); + assert.ok(logs.some((l) => l.startsWith(`discovery off: could not bind UDP 0.0.0.0:${port}`)), logs.join("\n")); + assert.equal((await fetch(`${server.url}/.well-known/gentle-shell`)).status, 200); + } finally { + holder.close(); + await server?.close(); + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tests/serve-files.test.ts b/tests/serve-files.test.ts new file mode 100644 index 000000000..0bf839960 --- /dev/null +++ b/tests/serve-files.test.ts @@ -0,0 +1,293 @@ +import assert from "node:assert/strict"; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, sep } from "node:path"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { searchScore } from "../lib/serve-files.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { after, before, call, pairDevice, stream, test } from "./serve-test-client.ts"; + +const ADMIN = "gsa_test-admin-token"; +const savedHome = process.env.HOME; +let root: string; +let home: string; +let work: string; +let server: ServeServer; +let reader: { id: string; token: string }; +let operator: { id: string; token: string }; + +before(async () => { + root = realpathSync(mkdtempSync(join(tmpdir(), "gentle-serve-files-"))); + // The protected-path rules read the server user's home: a throwaway one here. + home = join(root, "home"); + work = join(home, "work"); + mkdirSync(work, { recursive: true }); + process.env.HOME = home; + const auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth, + version: "test", + launchSession: () => { throw new Error("no sessions here"); }, + fsLimits: { listEntries: 50, readBytes: 64, writeBytes: 1024 * 1024, watchersPerDevice: 2, watchDebounceMs: 50 }, + }); + reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader"); + operator = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"], "operator"); +}); +after(async () => { + await server?.close(); + process.env.HOME = savedHome; + rmSync(root, { recursive: true, force: true }); +}); + +const q = (path: string) => encodeURIComponent(path); + +test("GET /api/server names the platform, the architecture and the path separator", async () => { + const info = await call(server.url, "GET", "/api/server", { token: reader.token }); + assert.equal(info.status, 200); + assert.equal(info.body.platform, process.platform); + assert.equal(info.body.pathSeparator, sep); + assert.equal(typeof info.body.arch, "string"); + assert.ok(info.body.capabilities.includes("files")); + assert.equal(info.body.home, undefined, "home only for operate"); +}); + +test("list: entries with kind, size and mtime, hidden ones included, links resolved to their kind", async () => { + const dir = join(work, "list"); + mkdirSync(join(dir, "sub"), { recursive: true }); + writeFileSync(join(dir, "a.txt"), "hello"); + writeFileSync(join(dir, ".hidden"), ""); + symlinkSync(join(dir, "sub"), join(dir, "to-sub")); + symlinkSync(join(dir, "missing"), join(dir, "dangling")); + const listed = await call(server.url, "GET", `/api/fs/list?path=${q(dir)}`, { token: reader.token }); + assert.equal(listed.status, 200, JSON.stringify(listed.body)); + assert.equal(listed.body.truncated, false); + const byName = Object.fromEntries(listed.body.entries.map((e: { name: string }) => [e.name, e])); + assert.deepEqual(Object.keys(byName), [".hidden", "a.txt", "dangling", "sub", "to-sub"]); + assert.equal(byName["a.txt"].kind, "file"); + assert.equal(byName["a.txt"].size, 5); + assert.equal(typeof byName["a.txt"].mtime, "number"); + assert.equal(byName.sub.kind, "dir"); + assert.equal(byName["to-sub"].kind, "symlink"); + assert.equal(byName["to-sub"].linkKind, "dir"); + assert.equal(byName.dangling.linkKind, null); + + const big = join(work, "big"); + mkdirSync(big); + for (let i = 0; i < 60; i += 1) writeFileSync(join(big, `f${i}`), ""); + const capped = await call(server.url, "GET", `/api/fs/list?path=${q(big)}`, { token: reader.token }); + assert.equal(capped.body.entries.length, 50); + assert.equal(capped.body.truncated, true); +}); + +test("paths must be absolute, without NUL; missing ones answer 404; auth applies", async () => { + assert.equal((await call(server.url, "GET", "/api/fs/list?path=relative/dir", { token: reader.token })).body.error.code, "invalid_path"); + assert.equal((await call(server.url, "GET", `/api/fs/list?path=${q(`${work}\0x`)}`, { token: reader.token })).body.error.code, "invalid_path"); + assert.equal((await call(server.url, "GET", "/api/fs/list", { token: reader.token })).body.error.code, "invalid_path"); + const missing = await call(server.url, "GET", `/api/fs/stat?path=${q(join(work, "nope"))}`, { token: reader.token }); + assert.equal(missing.status, 404); + assert.equal(missing.body.error.code, "not_found"); + assert.equal((await call(server.url, "GET", `/api/fs/list?path=${q(work)}`)).status, 401); + assert.equal((await call(server.url, "POST", "/api/fs/list", { token: reader.token })).status, 405); + assert.equal((await call(server.url, "GET", "/api/fs/nothing", { token: reader.token })).status, 404); +}); + +test("stat: a file's etag and mode; a link's target, its kind and the file it points to", async () => { + const file = join(work, "stat.txt"); + writeFileSync(file, "abc"); + chmodSync(file, 0o640); + symlinkSync(file, join(work, "stat-link")); + const plain = await call(server.url, "GET", `/api/fs/stat?path=${q(file)}`, { token: reader.token }); + assert.equal(plain.status, 200); + assert.equal(plain.body.kind, "file"); + assert.equal(plain.body.size, 3); + assert.equal(plain.body.mode, 0o640); + assert.match(plain.body.etag, /^"[0-9a-z]+-[0-9a-z]+"$/); + assert.equal(plain.body.realPath, file); + const link = await call(server.url, "GET", `/api/fs/stat?path=${q(join(work, "stat-link"))}`, { token: reader.token }); + assert.equal(link.body.kind, "symlink"); + assert.equal(link.body.linkTarget, file); + assert.equal(link.body.linkKind, "file"); + assert.equal(link.body.realPath, file); + assert.equal(link.body.size, 3); + assert.equal(link.body.etag, plain.body.etag); +}); + +test("read: raw bytes, offset and length, capped per call, conditional requests", async () => { + const file = join(work, "read.bin"); + const bytes = Buffer.from(Array.from({ length: 100 }, (_, i) => i)); + writeFileSync(file, bytes); + const first = await call(server.url, "GET", `/api/fs/read?path=${q(file)}`, { token: operator.token }); + assert.equal(first.status, 200); + assert.equal(first.headers["content-type"], "application/octet-stream"); + assert.deepEqual(first.bytes, bytes.subarray(0, 64), "capped at the per-call limit"); + assert.equal(first.headers["x-file-size"], "100"); + assert.equal(first.headers["x-truncated"], "1"); + const rest = await call(server.url, "GET", `/api/fs/read?path=${q(file)}&offset=64`, { token: operator.token }); + assert.deepEqual(rest.bytes, bytes.subarray(64)); + assert.equal(rest.headers["x-truncated"], "0"); + const slice = await call(server.url, "GET", `/api/fs/read?path=${q(file)}&offset=10&length=5`, { token: operator.token }); + assert.deepEqual(slice.bytes, bytes.subarray(10, 15)); + const past = await call(server.url, "GET", `/api/fs/read?path=${q(file)}&offset=500`, { token: operator.token }); + assert.equal(past.status, 200); + assert.equal(past.bytes.length, 0); + + const etag = first.headers.etag as string; + assert.equal((await call(server.url, "GET", `/api/fs/read?path=${q(file)}`, { token: operator.token, headers: { "If-None-Match": etag } })).status, 304); + const since = first.headers["last-modified"] as string; + assert.equal((await call(server.url, "GET", `/api/fs/read?path=${q(file)}`, { token: operator.token, headers: { "If-Modified-Since": since } })).status, 304); + assert.equal((await call(server.url, "GET", `/api/fs/read?path=${q(file)}`, { token: operator.token, headers: { "If-None-Match": "\"other\"" } })).status, 200); + + assert.equal((await call(server.url, "GET", `/api/fs/read?path=${q(work)}`, { token: operator.token })).body.error.code, "not_a_file"); + assert.equal((await call(server.url, "GET", `/api/fs/read?path=${q(file)}&offset=-1`, { token: operator.token })).body.error.code, "invalid_offset"); +}); + +test("a device that only watches lists, stats and searches, but never reads a file's contents", async () => { + const dir = join(work, "secrets"); + mkdirSync(dir); + const file = join(dir, "mcp.json"); + writeFileSync(file, "{\"token\":\"secret\"}"); + const denied = await call(server.url, "GET", `/api/fs/read?path=${q(file)}`, { token: reader.token }); + assert.equal(denied.status, 403); + assert.equal(denied.body.error.code, "forbidden"); + assert.match(denied.body.error.message, /sessions:operate/); + assert.equal((await call(server.url, "GET", `/api/fs/read?path=${q(file)}`, { token: reader.token, headers: { "If-None-Match": "\"x\"" } })).status, 403); + const listed = await call(server.url, "GET", `/api/fs/list?path=${q(dir)}`, { token: reader.token }); + assert.equal(listed.status, 200); + assert.deepEqual(listed.body.entries.map((e: { name: string }) => e.name), ["mcp.json"]); + assert.equal((await call(server.url, "GET", `/api/fs/stat?path=${q(file)}`, { token: reader.token })).status, 200); + assert.equal((await call(server.url, "GET", `/api/fs/search?root=${q(dir)}&q=mcp`, { token: reader.token })).status, 200); +}); + +test("write: atomic create and replace, mode kept, create_only, If-Match, through a link, bounded", async () => { + const file = join(work, "write.txt"); + const url = (extra = "") => `/api/fs/write?path=${q(file)}${extra}`; + assert.equal((await call(server.url, "PUT", url(), { token: reader.token, raw: "x" })).status, 403); + const created = await call(server.url, "PUT", url(), { token: operator.token, raw: "one" }); + assert.equal(created.status, 201, JSON.stringify(created.body)); + assert.equal(created.body.created, true); + assert.equal(readFileSync(file, "utf8"), "one"); + chmodSync(file, 0o755); + const replaced = await call(server.url, "PUT", url(), { token: operator.token, raw: "two!" }); + assert.equal(replaced.status, 200); + assert.equal(replaced.body.size, 4); + assert.equal(statSync(file).mode & 0o777, 0o755); + assert.equal((await call(server.url, "PUT", url("&create_only=1"), { token: operator.token, raw: "three" })).body.error.code, "exists"); + assert.equal(readFileSync(file, "utf8"), "two!"); + + const stale = await call(server.url, "PUT", url(), { token: operator.token, raw: "late", headers: { "If-Match": created.body.etag } }); + assert.equal(stale.status, 412); + assert.equal(stale.body.error.code, "changed"); + const fresh = await call(server.url, "PUT", url(), { token: operator.token, raw: "ok", headers: { "If-Match": replaced.body.etag } }); + assert.equal(fresh.status, 200); + + const onlyNew = join(work, "fresh.txt"); + assert.equal((await call(server.url, "PUT", `/api/fs/write?path=${q(onlyNew)}&create_only=1`, { token: operator.token, raw: "n" })).status, 201); + + const link = join(work, "write-link"); + symlinkSync(file, link); + assert.equal((await call(server.url, "PUT", `/api/fs/write?path=${q(link)}`, { token: operator.token, raw: "via link" })).status, 200); + assert.ok(lstatSync(link).isSymbolicLink(), "the link stays a link"); + assert.equal(readFileSync(file, "utf8"), "via link"); + + const tooBig = await call(server.url, "PUT", url(), { token: operator.token, raw: Buffer.alloc(1024 * 1024 + 1) }); + assert.equal(tooBig.status, 413); + assert.equal(readFileSync(file, "utf8"), "via link"); + assert.equal((await call(server.url, "PUT", `/api/fs/write?path=${q(join(work, "no-dir", "x"))}`, { token: operator.token, raw: "x" })).status, 404); + assert.equal((await call(server.url, "PUT", `/api/fs/write?path=${q(work)}`, { token: operator.token, raw: "x" })).body.error.code, "not_a_file"); + const leftovers = (await call(server.url, "GET", `/api/fs/list?path=${q(work)}`, { token: reader.token })).body.entries.filter((e: { name: string }) => e.name.endsWith(".tmp")); + assert.deepEqual(leftovers, [], "no temporary file is left behind"); +}); + +test("mkdir, rename and remove", async () => { + const nested = join(work, "m", "n"); + const made = await call(server.url, "POST", "/api/fs/mkdir", { token: operator.token, body: { path: nested } }); + assert.equal(made.status, 201); + assert.equal(made.body.created, true); + assert.equal((await call(server.url, "POST", "/api/fs/mkdir", { token: operator.token, body: { path: nested } })).body.created, false); + assert.equal((await call(server.url, "POST", "/api/fs/mkdir", { token: reader.token, body: { path: nested } })).status, 403); + + writeFileSync(join(work, "r1"), "1"); + writeFileSync(join(work, "r2"), "2"); + const clash = await call(server.url, "POST", "/api/fs/rename", { token: operator.token, body: { from: join(work, "r1"), to: join(work, "r2") } }); + assert.equal(clash.status, 409); + assert.equal((await call(server.url, "POST", "/api/fs/rename", { token: operator.token, body: { from: join(work, "r1"), to: join(work, "r2"), overwrite: true } })).status, 200); + assert.equal(readFileSync(join(work, "r2"), "utf8"), "1"); + assert.equal(existsSync(join(work, "r1")), false); + assert.equal((await call(server.url, "POST", "/api/fs/rename", { token: operator.token, body: { from: join(work, "r1"), to: join(work, "r3") } })).status, 404); + + const notEmpty = await call(server.url, "POST", "/api/fs/remove", { token: operator.token, body: { path: join(work, "m") } }); + assert.equal(notEmpty.status, 409); + assert.equal(notEmpty.body.error.code, "not_empty"); + assert.equal((await call(server.url, "POST", "/api/fs/remove", { token: operator.token, body: { path: join(work, "m"), recursive: true } })).status, 200); + assert.equal(existsSync(join(work, "m")), false); + assert.equal((await call(server.url, "POST", "/api/fs/remove", { token: operator.token, body: { path: join(work, "r2") } })).status, 200); +}); + +test("remove and rename refuse the root, the home and the folders above it; a link to the home goes, not the home", async () => { + for (const path of ["/", home, root, `${home}/work/..`]) { + const refused = await call(server.url, "POST", "/api/fs/remove", { token: operator.token, body: { path, recursive: true } }); + assert.equal(refused.status, 403, path); + assert.equal(refused.body.error.code, "protected_path"); + } + assert.equal((await call(server.url, "POST", "/api/fs/rename", { token: operator.token, body: { from: home, to: join(root, "moved") } })).body.error.code, "protected_path"); + const link = join(work, "home-link"); + symlinkSync(home, link); + assert.equal((await call(server.url, "POST", "/api/fs/remove", { token: operator.token, body: { path: link, recursive: true } })).status, 200); + assert.equal(existsSync(link), false); + assert.ok(existsSync(work), "the home is untouched"); + // A path through a link to the home's parent is the same folder: refused. + symlinkSync(root, join(work, "root-link")); + assert.equal((await call(server.url, "POST", "/api/fs/remove", { token: operator.token, body: { path: join(work, "root-link", "home"), recursive: true } })).body.error.code, "protected_path"); + assert.equal(readlinkSync(join(work, "root-link")), root); +}); + +test("search: ranked filename matches, .git and node_modules skipped", async () => { + assert.equal(searchScore("main.rs", "src/main.rs", "main.rs"), 100); + assert.equal(searchScore("main.rs", "src/main.rs", "mai"), 80); + assert.equal(searchScore("domain.rs", "src/domain.rs", "main"), 60); + assert.equal(searchScore("lib.rs", "src/app/lib.rs", "app/lib"), 40); + assert.equal(searchScore("serve-files.ts", "lib/serve-files.ts", "sfts"), 10); + assert.equal(searchScore("abc", "abc", "zzz"), 0); + + const tree = join(work, "tree"); + mkdirSync(join(tree, "src", "deep"), { recursive: true }); + mkdirSync(join(tree, ".git"), { recursive: true }); + mkdirSync(join(tree, "node_modules", "pkg"), { recursive: true }); + writeFileSync(join(tree, "src", "deep", "widget.ts"), ""); + writeFileSync(join(tree, "src", "my-widget-list.ts"), ""); + writeFileSync(join(tree, ".git", "widget"), ""); + writeFileSync(join(tree, "node_modules", "pkg", "widget.ts"), ""); + const found = await call(server.url, "GET", `/api/fs/search?root=${q(tree)}&q=Widget.ts`, { token: reader.token }); + assert.equal(found.status, 200, JSON.stringify(found.body)); + // The exact name first; the loose in-order match after it. + assert.deepEqual(found.body.results.map((r: { path: string }) => r.path), [join(tree, "src", "deep", "widget.ts"), join(tree, "src", "my-widget-list.ts")]); + const loose = await call(server.url, "GET", `/api/fs/search?root=${q(tree)}&q=widget&limit=1`, { token: reader.token }); + assert.equal(loose.body.results.length, 1); + assert.equal(loose.body.results[0].name, "widget.ts"); + assert.equal(loose.body.truncated, false); + assert.equal((await call(server.url, "GET", `/api/fs/search?root=${q(tree)}`, { token: reader.token })).body.error.code, "invalid_query"); +}); + +test("watch: debounced change batches over SSE, capped per device, closed on revoke", async () => { + const dir = join(work, "watched"); + mkdirSync(dir); + const watchDevice = await pairDevice(server.url, ADMIN, ["sessions:read"], "watcher"); + const changes = await stream(server.url, `/api/fs/watch?path=${q(dir)}`, watchDevice.token); + assert.equal(changes.status, 200); + await changes.waitFor("event: ready"); + writeFileSync(join(dir, "new.txt"), "x"); + await changes.waitFor("event: changes"); + await changes.waitFor(JSON.stringify(join(dir, "new.txt")).slice(1, -1)); + + const second = await stream(server.url, `/api/fs/watch?path=${q(dir)}`, watchDevice.token); + assert.equal(second.status, 200); + const third = await call(server.url, "GET", `/api/fs/watch?path=${q(dir)}`, { token: watchDevice.token }); + assert.equal(third.status, 429); + assert.equal((await call(server.url, "GET", `/api/fs/watch?path=${q(join(dir, "missing"))}`, { token: reader.token })).status, 404); + + assert.equal((await call(server.url, "DELETE", `/api/devices/${watchDevice.id}`, { token: ADMIN })).status, 200); + await changes.closed; + await second.closed; +}); diff --git a/tests/serve-forward.test.ts b/tests/serve-forward.test.ts new file mode 100644 index 000000000..d8a904fcd --- /dev/null +++ b/tests/serve-forward.test.ts @@ -0,0 +1,476 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { createServer, request as httpRequest, type IncomingMessage, type Server } from "node:http"; +import { connect, type Socket } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServeAuth, type ServeScope } from "../lib/serve-auth.ts"; +import { ForwardManager, splitTicket, stripForwardCookies } from "../lib/serve-forward.ts"; +import { allowedHosts, startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { after, before, endServeLeftovers, remainingServeLeftovers, test } from "./serve-test-client.ts"; + +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); +const ADMIN = "gsa_test-admin-token"; +const TOWER_TOKEN = "tower-token-123"; +let root: string; +let server: ServeServer; +let auth: ServeAuth; +let project: string; +let page: Server; +let pagePort: number; +let towerPage: Server; +let towerStarts = 0; +let towerCloses = 0; +/** What the page saw last: the request as it reached the target. */ +let seen: { method?: string; url?: string; headers?: IncomingMessage["headers"]; body?: string } = {}; +let releaseStream: () => void = () => {}; + +function listen(s: Server): Promise { + const { promise, resolve } = Promise.withResolvers(); + s.listen(0, "127.0.0.1", () => resolve((s.address() as { port: number }).port)); + return promise; +} + +/** The page on the server's loopback: echoes requests, streams SSE, redirects, sets cookies, and echoes WebSocket bytes. */ +function startPage(): Server { + const s = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + seen = { method: req.method, url: req.url, headers: req.headers, body: Buffer.concat(chunks).toString("utf8") }; + if (req.url === "/sse") { + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.write("data: first\n\n"); + releaseStream = () => res.end("data: last\n\n"); + return; + } + if (req.url === "/redirect") { + res.writeHead(302, { Location: `http://127.0.0.1:${pagePort}/landed?x=1` }); + return res.end(); + } + if (req.url === "/cookies") { + res.writeHead(200, { "Set-Cookie": ["app=1; Path=/", "gs_fwd_fwd_spoof=1; Path=/"] }); + return res.end("ok"); + } + res.writeHead(200, { "Content-Type": "text/html", "X-Page": "yes" }); + res.end(`

page ${req.url}

`); + }); + }); + s.on("upgrade", (req: IncomingMessage, socket: Socket, head: Buffer) => { + seen = { method: req.method, url: req.url, headers: req.headers }; + const accept = createHash("sha1").update(`${req.headers["sec-websocket-key"]}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64"); + socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); + if (head.length) socket.write(head); + socket.pipe(socket); + }); + return s; +} + +before(async () => { + root = mkdtempSync(join(tmpdir(), "gentle-serve-forward-")); + project = realpathSync(mkdtempSync(join(root, "project-"))); + page = startPage(); + pagePort = await listen(page); + // A stand-in for Gentle Tower: its token is the first path segment and only its own origin may post. + towerPage = createServer((req, res) => { + const origin = req.headers.origin; + const port = (towerPage.address() as { port: number }).port; + if (origin && origin !== `http://127.0.0.1:${port}`) { res.writeHead(403); return res.end("bad origin"); } + if (!req.url?.startsWith(`/${TOWER_TOKEN}/`)) { res.writeHead(403); return res.end("no token"); } + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(`tower ${req.method} ${req.url}`); + }); + auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth, + version: "test", + launchSession: (input) => ({ command: process.execPath, args: [FAKE_PI], cwd: input.cwd, env: { ...process.env } }), + startTower: async () => { + towerStarts += 1; + const port = await listen(towerPage); + const close = () => { + towerCloses += 1; + const closed = Promise.withResolvers(); + towerPage.close(() => closed.resolve()); + towerPage.closeAllConnections(); + return closed.promise; + }; + return { port, path: `/${TOWER_TOKEN}/`, close }; + }, + }); +}); +// Sessions end with the server: no serve folder, so their keepers live in a private temp folder. +let closing: Promise | undefined; +const closeServer = () => (closing ??= server?.close({ endSessions: true })); +after(async () => { + await closeServer(); + // A failed test must not leave a keeper (or its fake Pi) behind. + await endServeLeftovers([], root ? [root] : []); + page?.close(); + page?.closeAllConnections(); + rmSync(root, { recursive: true, force: true }); +}); + +interface Reply { status: number; body: any; headers: IncomingMessage["headers"]; text: string } + +function http(url: string, options: { method?: string; headers?: Record; body?: string } = {}): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const req = httpRequest(url, { method: options.method ?? "GET", headers: options.headers, agent: false }, (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + let body: unknown = text; + try { body = JSON.parse(text); } catch { /* not JSON */ } + resolve({ status: res.statusCode ?? 0, body, headers: res.headers, text }); + }); + }); + req.on("error", reject); + req.end(options.body); + return promise; +} + +const api = (method: string, path: string, token: string, body?: unknown) => http(`${server.url}${path}`, { + method, + headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), +}); + +async function pairDevice(scopes: ServeScope[], name = "device"): Promise<{ id: string; token: string }> { + const code = await api("POST", "/api/pairing-codes", ADMIN, { scopes }); + const paired = await http(`${server.url}/api/pair`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: code.body.code, name }) }); + assert.equal(paired.status, 201); + return { id: paired.body.id, token: paired.body.token }; +} + +async function startSession(token = ADMIN): Promise { + const started = await api("POST", "/api/sessions", token, { cwd: project }); + assert.equal(started.status, 201, JSON.stringify(started.body)); + return started.body.session.id; +} + +/** Opens a forward link as a browser would: the ticket redirect, then the page with the cookie. */ +async function openLink(url: string): Promise<{ cookie: string; origin: string; first: Reply; page: Reply }> { + const first = await http(url); + assert.equal(first.status, 303, first.text); + const setCookie = first.headers["set-cookie"]?.[0] ?? ""; + assert.match(setCookie, /^gs_fwd_fwd_[0-9a-f]{16}=[A-Za-z0-9_-]{43}; HttpOnly; SameSite=Strict; Path=\/$/); + const cookie = setCookie.split(";")[0]; + const origin = new URL(url).origin; + const landed = await http(`${origin}${first.headers.location}`, { headers: { Cookie: cookie } }); + return { cookie, origin, first, page: landed }; +} + +function closedPort(port: number): Promise { + const { promise, resolve } = Promise.withResolvers(); + const socket = connect({ host: "127.0.0.1", port }); + socket.once("connect", () => { socket.destroy(); resolve(false); }); + socket.once("error", () => resolve(true)); + return promise; +} + +test("helpers: the ticket leaves the request target and forward cookies leave the Cookie header", () => { + assert.deepEqual(splitTicket("/a?gs_ticket=T"), { path: "/a", ticket: "T" }); + assert.deepEqual(splitTicket("/a?x=1&gs_ticket=T&y=2"), { path: "/a?x=1&y=2", ticket: "T" }); + assert.deepEqual(splitTicket("/a?x=1"), { path: "/a?x=1" }); + assert.equal(stripForwardCookies("a=1; gs_fwd_fwd_1=s; b=2"), "a=1; b=2"); + assert.equal(stripForwardCookies("gs_fwd_fwd_1=s"), undefined); + assert.equal(stripForwardCookies(undefined), undefined); +}); + +test("creating a forward: operate scope, a valid port and path, a running session; the same device and port reuse it", async () => { + const id = await startSession(); + const reader = await pairDevice(["sessions:read"], "reader"); + const refused = await api("POST", `/api/sessions/${id}/forwards`, reader.token, { port: pagePort }); + assert.equal(refused.status, 403); + assert.equal((await api("POST", `/api/sessions/${id}/forwards`, "nope", { port: pagePort })).status, 401); + for (const port of [0, 65536, "80", 1.5, null]) { + const bad = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port }); + assert.equal(bad.status, 400, String(port)); + assert.equal(bad.body.error.code, "invalid_port"); + } + assert.equal((await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: server.port })).body.error.code, "invalid_port", "never the server itself"); + for (const path of ["x", "//evil.example/", "/a b", "/\n"]) { + assert.equal((await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort, path })).body.error.code, "invalid_path", path); + } + assert.equal((await api("POST", "/api/sessions/ses_missing/forwards", ADMIN, { port: pagePort })).status, 404); + + const created = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort, path: "/app?x=1#top" }); + assert.equal(created.status, 201, JSON.stringify(created.body)); + assert.deepEqual(Object.keys(created.body), ["id", "port", "listenPort", "sessionId", "kind", "createdAt", "lastUsedAt", "url", "expiresAt"]); + assert.equal(created.body.kind, "session"); + assert.match(created.body.id, /^fwd_[0-9a-f]{16}$/); + assert.equal(created.body.port, pagePort); + assert.equal(created.body.sessionId, id); + assert.notEqual(created.body.listenPort, pagePort); + assert.match(created.body.url, new RegExp(`^http://127\\.0\\.0\\.1:${created.body.listenPort}/app\\?x=1&gs_ticket=[A-Za-z0-9_-]{32}#top$`)); + assert.ok(Date.parse(created.body.expiresAt) - Date.now() <= 60_000); + assert.equal((await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: created.body.listenPort })).body.error.code, "invalid_port", "never a forward"); + + const again = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort }); + assert.equal(again.status, 200, "reused"); + assert.equal(again.body.id, created.body.id); + assert.notEqual(new URL(again.body.url).searchParams.get("gs_ticket"), new URL(created.body.url).searchParams.get("gs_ticket"), "a fresh ticket"); + + const list = await api("GET", `/api/sessions/${id}/forwards`, reader.token); + assert.deepEqual(list.body, { forwards: [] }, "a device lists its own forwards"); + const own = await api("GET", `/api/sessions/${id}/forwards`, ADMIN); + assert.equal(own.body.forwards.length, 1); + assert.equal(own.body.forwards[0].url, undefined, "a listing carries no ticket"); + assert.equal((await api("DELETE", `/api/sessions/${id}/forwards/${created.body.id}`, reader.token)).status, 403); + await api("DELETE", `/api/sessions/${id}`, ADMIN); +}); + +test("the ticket opens the page once and leaves a per-forward cookie; the target never sees ticket or cookie", async () => { + const id = await startSession(); + const created = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort, path: "/app?x=1" }); + const { cookie, origin, first, page: landed } = await openLink(created.body.url); + assert.equal(first.headers.location, "/app?x=1", "the same URL without the ticket"); + assert.equal(first.headers["cache-control"], "no-store"); + assert.equal(landed.status, 200); + assert.equal(landed.text, "

page /app?x=1

"); + assert.equal(landed.headers["x-page"], "yes"); + assert.equal(landed.headers["access-control-allow-origin"], undefined, "no CORS added"); + assert.equal(seen.url, "/app?x=1"); + assert.equal(seen.headers?.cookie, undefined, "the forward's cookie is stripped"); + assert.equal(seen.headers?.host, `127.0.0.1:${pagePort}`, "Host is the page's own"); + + assert.equal((await http(created.body.url)).status, 401, "single use"); + assert.equal((await http(`${origin}/app`)).status, 401, "no cookie, no page"); + assert.equal((await http(`${origin}/app`, { headers: { Cookie: `${cookie.split("=")[0]}=forged` } })).status, 401); + // Other cookies of the host go through; every forward's own is stripped. + await http(`${origin}/other`, { headers: { Cookie: `theme=dark; ${cookie}; gs_fwd_fwd_0000000000000000=x` } }); + assert.equal(seen.headers?.cookie, "theme=dark"); + // A used ticket with a valid cookie (a reload of the link) just drops the ticket. + const reload = await http(created.body.url, { headers: { Cookie: cookie } }); + assert.equal(reload.status, 303); + assert.equal(reload.headers["set-cookie"], undefined); + await api("DELETE", `/api/sessions/${id}`, ADMIN); +}); + +test("cookies are per forward: one forward's cookie does not open another, and tickets are bound to their forward", async () => { + const id = await startSession(); + const phone = await pairDevice(["sessions:read", "sessions:operate"], "phone"); + const mine = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort }); + const theirs = await api("POST", `/api/sessions/${id}/forwards`, phone.token, { port: pagePort }); + assert.equal(theirs.status, 201, "another device gets its own forward"); + assert.notEqual(theirs.body.listenPort, mine.body.listenPort); + const a = await openLink(mine.body.url); + const theirOrigin = `http://127.0.0.1:${theirs.body.listenPort}`; + assert.equal((await http(`${theirOrigin}/`, { headers: { Cookie: a.cookie } })).status, 401, "a cookie names its forward"); + const renamed = a.cookie.replace(mine.body.id, theirs.body.id); + assert.equal((await http(`${theirOrigin}/`, { headers: { Cookie: renamed } })).status, 401, "nor does its secret open another"); + const ticket = new URL(theirs.body.url).searchParams.get("gs_ticket"); + assert.equal((await http(`${a.origin}/?gs_ticket=${ticket}`)).status, 401, "a ticket opens only its forward"); + await api("DELETE", `/api/sessions/${id}`, ADMIN); +}); + +test("Host and Origin are checked like the main server's", async () => { + const id = await startSession(); + const created = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort }); + const { cookie, origin } = await openLink(created.body.url); + const port = created.body.listenPort; + const rebound = await http(`${origin}/`, { headers: { Cookie: cookie, Host: `evil.example:${port}` } }); + assert.equal(rebound.status, 421); + assert.equal((await http(`${origin}/`, { headers: { Cookie: cookie, Host: `127.0.0.1:${port + 1}` } })).status, 421); + assert.equal((await http(`${origin}/`, { headers: { Cookie: cookie, Host: `localhost:${port}` } })).status, 200, "loopback names on a loopback bind"); + assert.equal((await http(`${origin}/`, { headers: { Cookie: cookie, Origin: "http://127.0.0.1:1" } })).status, 403, "another port is another page"); + assert.equal((await http(`${origin}/`, { headers: { Cookie: cookie, Origin: "null" } })).status, 403); + const own = await http(`${origin}/post`, { method: "POST", headers: { Cookie: cookie, Origin: origin, Referer: `${origin}/from`, "Content-Type": "text/plain" }, body: "hello" }); + assert.equal(own.status, 200); + assert.equal(seen.method, "POST"); + assert.equal(seen.body, "hello", "the body streams through"); + assert.equal(seen.headers?.origin, `http://127.0.0.1:${pagePort}`, "its own origin reads as the page's"); + assert.equal(seen.headers?.referer, `http://127.0.0.1:${pagePort}/from`); + await api("DELETE", `/api/sessions/${id}`, ADMIN); +}); + +test("HTTP proxy: loopback redirects point back at the forward, forward cookies cannot be set, SSE streams unbuffered, a dead page is 502", async () => { + const id = await startSession(); + const created = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort }); + const { cookie, origin } = await openLink(created.body.url); + const redirected = await http(`${origin}/redirect`, { headers: { Cookie: cookie } }); + assert.equal(redirected.status, 302); + assert.equal(redirected.headers.location, `${origin}/landed?x=1`); + const cookies = await http(`${origin}/cookies`, { headers: { Cookie: cookie } }); + assert.deepEqual(cookies.headers["set-cookie"], ["app=1; Path=/"]); + + // The first event arrives while the page still holds the stream open. + const first = Promise.withResolvers(); + const done = Promise.withResolvers(); + const req = httpRequest(`${origin}/sse`, { headers: { Cookie: cookie }, agent: false }, (res) => { + assert.equal(res.headers["content-type"], "text/event-stream"); + let text = ""; + res.on("data", (c: Buffer) => { text += c.toString("utf8"); if (text.includes("first")) first.resolve(text); }); + res.on("end", () => done.resolve(text)); + }); + req.end(); + assert.equal(await first.promise, "data: first\n\n"); + releaseStream(); + assert.equal(await done.promise, "data: first\n\ndata: last\n\n"); + + const dead = createServer(); + const deadPort = await listen(dead); + await new Promise((r) => dead.close(() => r())); + const gone = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: deadPort }); + const link = await http(gone.body.url); + const failed = await http(`http://127.0.0.1:${gone.body.listenPort}/`, { headers: { Cookie: link.headers["set-cookie"]![0].split(";")[0] } }); + assert.equal(failed.status, 502); + await api("DELETE", `/api/sessions/${id}`, ADMIN); +}); + +test("WebSocket upgrades are piped both ways and need the cookie", async () => { + const id = await startSession(); + const created = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort }); + const { cookie, origin } = await openLink(created.body.url); + const port = created.body.listenPort; + const upgrade = (headers: string) => { + const { promise, resolve } = Promise.withResolvers<{ socket: Socket; head: string }>(); + const socket = connect({ host: "127.0.0.1", port }); + let text = ""; + const onData = (c: Buffer) => { + text += c.toString("latin1"); + const end = text.indexOf("\r\n\r\n"); + if (end !== -1) { socket.off("data", onData); resolve({ socket, head: text.slice(0, end) }); } + }; + socket.on("data", onData); + socket.write(`GET /ws?x=1 HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n${headers}\r\n`); + return promise; + }; + const refused = await upgrade(""); + assert.match(refused.head, /^HTTP\/1\.1 401 /); + refused.socket.destroy(); + const foreign = await upgrade(`Cookie: ${cookie}\r\nOrigin: http://evil.example\r\n`); + assert.match(foreign.head, /^HTTP\/1\.1 403 /); + foreign.socket.destroy(); + + const { socket, head } = await upgrade(`Cookie: ${cookie}\r\nOrigin: ${origin}\r\n`); + assert.match(head, /^HTTP\/1\.1 101 Switching Protocols/); + assert.match(head, /Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK\+xOo=/); + assert.equal(seen.url, "/ws?x=1"); + assert.equal(seen.headers?.cookie, undefined); + assert.equal(seen.headers?.origin, `http://127.0.0.1:${pagePort}`); + assert.equal(seen.headers?.host, `127.0.0.1:${pagePort}`); + const echoed = Promise.withResolvers(); + let got = ""; + socket.on("data", (c: Buffer) => { got += c.toString("latin1"); if (got.length >= 6) echoed.resolve(got); }); + socket.write(Buffer.from("\x81\x04ping", "latin1")); + assert.equal(await echoed.promise, "\x81\x04ping"); + + // Ending the session closes the forward, open WebSockets included. + const closed = Promise.withResolvers(); + socket.on("close", () => closed.resolve()); + await api("DELETE", `/api/sessions/${id}`, ADMIN); + await closed.promise; + assert.ok(await closedPort(port), "the listener is gone"); + assert.deepEqual((await api("GET", "/api/sessions", ADMIN)).status, 200); +}); + +test("forwards close when their device is revoked or they are deleted", async () => { + const id = await startSession(); + const laptop = await pairDevice(["sessions:read", "sessions:operate"], "laptop"); + const created = await api("POST", `/api/sessions/${id}/forwards`, laptop.token, { port: pagePort }); + assert.equal(created.status, 201); + const { cookie, origin } = await openLink(created.body.url); + assert.equal((await http(`${origin}/`, { headers: { Cookie: cookie } })).status, 200); + assert.equal((await api("DELETE", `/api/devices/${laptop.id}`, ADMIN)).status, 200); + assert.ok(await closedPort(created.body.listenPort), "revoked: closed at once"); + assert.deepEqual((await api("GET", `/api/sessions/${id}/forwards`, ADMIN)).body.forwards.filter((f: { id: string }) => f.id === created.body.id), []); + + const mine = await api("POST", `/api/sessions/${id}/forwards`, ADMIN, { port: pagePort }); + assert.equal((await api("DELETE", `/api/sessions/${id}/forwards/fwd_0000000000000000`, ADMIN)).status, 404); + const deleted = await api("DELETE", `/api/sessions/${id}/forwards/${mine.body.id}`, ADMIN); + assert.deepEqual(deleted.body, { closed: mine.body.id }); + assert.ok(await closedPort(mine.body.listenPort)); + await api("DELETE", `/api/sessions/${id}`, ADMIN); +}); + +test("Gentle Tower: started once on request, forwarded with its token path, stopped by DELETE", async () => { + const reader = await pairDevice(["sessions:read"], "tower-reader"); + assert.equal((await api("POST", "/api/tower", reader.token)).status, 403, "Tower acts on sessions: operate scope"); + assert.deepEqual((await api("GET", "/api/tower", reader.token)).body, { running: false }); + const opened = await api("POST", "/api/tower", ADMIN); + assert.equal(opened.status, 201, JSON.stringify(opened.body)); + assert.equal(opened.body.started, true); + assert.equal(opened.body.sessionId, null); + assert.match(opened.body.url, new RegExp(`^http://127\\.0\\.0\\.1:${opened.body.listenPort}/${TOWER_TOKEN}/\\?gs_ticket=`)); + const { cookie, origin, page: landed } = await openLink(opened.body.url); + assert.equal(landed.text, `tower GET /${TOWER_TOKEN}/`); + // Tower refuses any Origin but its own; the forward's own reads as Tower's. + const posted = await http(`${origin}/${TOWER_TOKEN}/api/action`, { method: "POST", headers: { Cookie: cookie, Origin: origin }, body: "{}" }); + assert.equal(posted.text, `tower POST /${TOWER_TOKEN}/api/action`); + + const again = await api("POST", "/api/tower", ADMIN); + assert.equal(again.status, 200); + assert.equal(again.body.started, false); + assert.equal(again.body.id, opened.body.id); + assert.equal(towerStarts, 1); + assert.equal((await api("GET", "/api/tower", reader.token)).body.running, true); + + assert.equal((await api("DELETE", "/api/tower", reader.token)).status, 403); + assert.deepEqual((await api("DELETE", "/api/tower", ADMIN)).body, { stopped: true }); + assert.equal(towerCloses, 1); + assert.ok(await closedPort(opened.body.listenPort), "its forwards close with it"); + assert.deepEqual((await api("DELETE", "/api/tower", ADMIN)).body, { stopped: false }); +}); + +test("forward manager: tickets expire, idle forwards close, connections are bounded, the port range is used", async () => { + let clock = 1_000_000; + const manager = new ForwardManager({ + bindHost: "127.0.0.1", + hostCheck: (port) => allowedHosts("127.0.0.1", port), + now: () => clock, + limits: { maxConnections: 1, idleMs: 1000, sweepMs: 20 }, + }); + try { + // The idle sweep runs on a real (short) interval: it is the manager's own timer, not one the test can drive. + const { forward } = await manager.open({ deviceId: "dev_a", sessionId: "ses_a", kind: "session", port: pagePort }); + const expired = manager.mintTicket(forward.id); + clock += 60_001; + const late = await http(manager.urlFor(forward.id, "127.0.0.1", "/", expired.ticket)); + assert.equal(late.status, 401, "a ticket lives 60 s"); + const fresh = manager.mintTicket(forward.id); + const link = await http(manager.urlFor(forward.id, "127.0.0.1", "/", fresh.ticket)); + assert.equal(link.status, 303); + + // One connection held open: the next one is refused at accept. + const held = connect({ host: "127.0.0.1", port: forward.listenPort }); + await new Promise((r) => held.once("connect", r)); + await new Promise((r) => setTimeout(r, 50)); + const second = await new Promise((resolve) => { + const s = connect({ host: "127.0.0.1", port: forward.listenPort }); + s.on("error", () => resolve("error")); + s.on("close", () => resolve("closed")); + s.write(`GET / HTTP/1.1\r\nHost: 127.0.0.1:${forward.listenPort}\r\n\r\n`); + }); + assert.ok(second === "closed" || second === "error"); + // Open connections keep it; idle and unconnected, it closes. + clock += 2000; + await new Promise((r) => setTimeout(r, 80)); + assert.ok(manager.get(forward.id), "an open connection is use"); + held.destroy(); + await new Promise((r) => setTimeout(r, 80)); + assert.equal(manager.get(forward.id), undefined, "idle past the limit"); + assert.ok(await closedPort(forward.listenPort)); + + const ranged = new ForwardManager({ bindHost: "127.0.0.1", hostCheck: (port) => allowedHosts("127.0.0.1", port), portRange: { from: forward.listenPort, to: forward.listenPort } }); + const blocker = createServer(); + await new Promise((r) => blocker.listen(forward.listenPort, "127.0.0.1", () => r())); + await assert.rejects(ranged.open({ deviceId: "dev_a", sessionId: null, kind: "tower", port: pagePort }), /in use/); + blocker.close(); + const inRange = await ranged.open({ deviceId: "dev_a", sessionId: null, kind: "tower", port: pagePort }); + assert.equal(inRange.forward.listenPort, forward.listenPort); + ranged.closeAll(); + } finally { + manager.closeAll(); + } +}); + +test("no session keeper or fake Pi outlives the tests above", async () => { + await closeServer(); + assert.deepEqual(await remainingServeLeftovers([], [root]), []); +}); diff --git a/tests/serve-git.test.ts b/tests/serve-git.test.ts new file mode 100644 index 000000000..4c98da097 --- /dev/null +++ b/tests/serve-git.test.ts @@ -0,0 +1,187 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, type Server } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { classifyGitArgs } from "../lib/serve-git.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { after, before, call, pairDevice, test } from "./serve-test-client.ts"; + +const ADMIN = "gsa_test-admin-token"; +const IDENTITY = { GIT_AUTHOR_NAME: "T", GIT_AUTHOR_EMAIL: "t@example.com", GIT_COMMITTER_NAME: "T", GIT_COMMITTER_EMAIL: "t@example.com" }; +let root: string; +let repo: string; +let server: ServeServer; +let reader: { id: string; token: string }; +let operator: { id: string; token: string }; +let silent: Server; + +before(async () => { + root = realpathSync(mkdtempSync(join(tmpdir(), "gentle-serve-git-"))); + repo = join(root, "repo"); + mkdirSync(repo); + const auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + // No user or system git configuration: the fixture's own only. + const emptyConfig = join(root, "empty.gitconfig"); + writeFileSync(emptyConfig, ""); + server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth, + version: "test", + launchSession: () => { throw new Error("no sessions here"); }, + env: { PATH: process.env.PATH, HOME: root, GIT_CONFIG_GLOBAL: emptyConfig, GIT_CONFIG_NOSYSTEM: "1", GIT_DIR: "/somewhere/else" }, + gitLimits: { stdoutBytes: 100 }, + }); + reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader"); + operator = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"], "operator"); + // A remote that accepts and never answers, for the timeout. + silent = createServer(() => { /* hold the connection */ }); + const listening = Promise.withResolvers(); + silent.listen(0, "127.0.0.1", listening.resolve); + await listening.promise; +}); +after(async () => { + await server?.close(); + silent?.close(); + rmSync(root, { recursive: true, force: true }); +}); + +const git = (token: string, args: string[], extra: Record = {}) => call(server.url, "POST", "/api/git", { token, body: { cwd: repo, args, ...extra } }); +const text = (b64: string) => Buffer.from(b64, "base64").toString("utf8"); + +test("classifyGitArgs: reads, operations, network commands and refused options", () => { + assert.deepEqual(classifyGitArgs(["status", "--porcelain=v2"]), { subcommand: "status", scope: "sessions:read", network: false }); + assert.deepEqual(classifyGitArgs(["-C", "sub", "--no-pager", "log", "-n", "5"]), { subcommand: "log", scope: "sessions:read", network: false }); + assert.deepEqual(classifyGitArgs(["--version"]), { scope: "sessions:read", network: false }); + assert.equal(classifyGitArgs(["commit", "-m", "x"]).scope, "sessions:operate"); + assert.deepEqual(classifyGitArgs(["fetch", "origin"]), { subcommand: "fetch", scope: "sessions:operate", network: true }); + assert.equal(classifyGitArgs(["ls-remote", "origin"]).scope, "sessions:read"); + assert.equal(classifyGitArgs(["log", "--output=/tmp/x"]).scope, "sessions:operate", "--output writes a file"); + assert.equal(classifyGitArgs(["diff", "--numstat", "--output-indicator-new=+"]).scope, "sessions:read"); + assert.equal(classifyGitArgs(["grep", "-O", "x"]).scope, "sessions:operate"); + assert.equal(classifyGitArgs(["-c", "color.ui=false", "status"]).scope, "sessions:operate", "any -c operates"); + assert.equal(classifyGitArgs(["status", "--", "-c"]).scope, "sessions:read"); + + for (const args of [["branch"], ["branch", "--list", "feat/*"], ["branch", "-a", "--contains", "HEAD"], ["branch", "--show-current"], ["tag"], ["tag", "-l", "v*"], + ["config", "--get", "user.name"], ["config", "get", "user.name"], ["config", "--list"], ["remote", "-v"], ["remote", "get-url", "origin"], + ["stash", "list"], ["worktree", "list"], ["symbolic-ref", "HEAD"], ["rev-parse", "--show-toplevel"], ["for-each-ref", "refs/heads"]]) { + assert.equal(classifyGitArgs(args).scope, "sessions:read", args.join(" ")); + } + for (const args of [["branch", "new"], ["branch", "-D", "old"], ["tag", "v1"], ["tag", "-a", "v1", "-m", "x"], ["config", "user.name", "x"], + ["config", "--unset", "user.name"], ["remote", "add", "o", "u"], ["stash"], ["stash", "pop"], ["worktree", "add", "x"], ["symbolic-ref", "HEAD", "refs/heads/x"], + ["checkout", "main"], ["add", "."]]) { + assert.equal(classifyGitArgs(args).scope, "sessions:operate", args.join(" ")); + } + + const refused = [["-c", "core.sshCommand=evil", "fetch"], ["-c", "Core.FSMonitor=evil", "status"], ["-c", "core.hooksPath=/x", "commit"], + ["-c", "alias.x=!evil", "x"], ["-c", "uploadpack.packObjectsHook=evil", "fetch"], ["-c", "remote.origin.uploadpack=evil", "fetch"], + ["--config-env=core.sshCommand=VAR", "fetch"], ["--config-env", "core.fsmonitor=VAR", "status"], ["--exec-path=/tmp", "status"], + ["fetch", "--upload-pack=evil", "origin"], ["push", "--receive-pack", "evil"], ["push", "--exec=evil"], ["clone", "-u", "evil", "url"], + ["clone", "--config", "core.fsmonitor=evil", "url"], ["clone", "-c", "core.sshCommand=evil", "url"], ["ls-remote", "-uevil", "url"]]; + for (const args of refused) assert.throws(() => classifyGitArgs(args), (error: { code?: string }) => error.code === "git_refused", args.join(" ")); + // After `--` they are paths, not options. + assert.equal(classifyGitArgs(["log", "--", "--upload-pack=x"]).scope, "sessions:read"); +}); + +test("classifyGitArgs: file contents (patches, blobs, blame, grep) need sessions:operate; paths and counts do not", () => { + for (const args of [["log", "--format=%H%x00%s", "-n", "20"], ["log", "--all", "--no-merges", "--format=%at"], ["log", "--stat"], ["log", "-1", "--format=%B"], + ["diff", "--numstat", "-z"], ["diff", "--numstat", "-z", "HEAD"], ["diff", "--name-status"], ["diff", "--stat", "main"], ["diff", "--quiet"], + ["diff-tree", "-r", "-M", "-z", "--no-commit-id", "--name-status", "HEAD"], ["diff-index", "--cached", "HEAD"], ["diff-files"], + ["stash", "list", "--format=%gd%x00%gs"], ["stash", "show", "stash@{0}"], ["cat-file", "-t", "HEAD"], ["cat-file", "-s", "HEAD:a.txt"], + ["cat-file", "--batch-check"], ["ls-files", "-z"], ["ls-tree", "-r", "HEAD"], ["rev-parse", "HEAD:a.txt"]]) { + assert.equal(classifyGitArgs(args).scope, "sessions:read", args.join(" ")); + } + for (const args of [["show", "HEAD"], ["show", "HEAD:a.txt"], ["show", "-s", "--format=%H"], ["diff"], ["diff", "HEAD"], ["diff", "--no-color", "--no-ext-diff", "a", "b"], + ["diff", "--numstat", "-p"], ["diff", "--stat", "--patch"], ["diff", "--check"], ["diff", "--name-only", "-U3"], ["diff-tree", "-p", "HEAD"], ["diff-tree", "--cc", "HEAD"], + ["diff-index", "-p", "HEAD"], ["diff-files", "--patch"], ["log", "-p"], ["log", "-pM"], ["log", "--patch"], ["log", "-L1,2:a.txt"], ["log", "-Ssecret"], + ["log", "-G", "secret"], ["log", "--word-diff"], ["log", "-c"], ["log", "--diff-merges=on"], ["stash", "show", "-p"], ["stash", "list", "-p"], + ["cat-file", "-p", "HEAD:a.txt"], ["cat-file", "blob", "HEAD:a.txt"], ["cat-file", "--batch"], ["blame", "a.txt"], ["grep", "secret"]]) { + assert.equal(classifyGitArgs(args).scope, "sessions:operate", args.join(" ")); + } +}); + +test("POST /api/git runs git without a shell: exit code, base64 output, stdin and allowed env", async () => { + const init = await git(operator.token, ["init", "-q", "-b", "main"]); + assert.equal(init.status, 200, JSON.stringify(init.body)); + assert.equal(init.body.code, 0, text(init.body.stderr)); + writeFileSync(join(repo, "a.txt"), "hello\n"); + assert.equal((await git(operator.token, ["add", "a.txt"])).body.code, 0); + const commit = await git(operator.token, ["commit", "-q", "-m", "first"], { env: IDENTITY }); + assert.equal(commit.body.code, 0, text(commit.body.stderr)); + + const status = await git(reader.token, ["status", "--porcelain"]); + assert.equal(status.body.code, 0); + assert.equal(text(status.body.stdout), "", "the inherited GIT_DIR does not leak into the request"); + assert.equal(status.body.truncated, false); + assert.equal(status.body.timedOut, false); + + const hashed = await git(operator.token, ["hash-object", "--stdin"], { stdin: Buffer.from("hello\n").toString("base64") }); + assert.equal(text(hashed.body.stdout).trim(), "ce013625030ba8dba906f756967f9e9ca394464a"); + + const failing = await git(reader.token, ["rev-parse", "--verify", "nope"]); + assert.equal(failing.status, 200); + assert.notEqual(failing.body.code, 0); + assert.match(text(failing.body.stderr), /fatal|Needed a single revision/); + + const big = await git(operator.token, ["log", "-p"]); + assert.equal(big.body.truncated, true); + assert.equal(Buffer.from(big.body.stdout, "base64").length, 100); + + // No editor can answer: a commit without a message gives up at once. + writeFileSync(join(repo, "b.txt"), "b\n"); + await git(operator.token, ["add", "b.txt"]); + const noMessage = await git(operator.token, ["commit"], { env: IDENTITY }); + assert.notEqual(noMessage.body.code, 0); +}); + +test("scopes, refusals and validation", async () => { + assert.equal((await git(reader.token, ["commit", "-m", "x"])).status, 403); + assert.equal((await git(reader.token, ["-c", "color.ui=false", "status"])).status, 403); + // Contents need operate; status, branches, the log and changed paths stay readable. + for (const args of [["show", "HEAD:a.txt"], ["diff", "HEAD"], ["cat-file", "-p", "HEAD:a.txt"], ["blame", "a.txt"], ["grep", "hello"], ["log", "-p"]]) { + const denied = await git(reader.token, args); + assert.equal(denied.status, 403, args.join(" ")); + assert.equal(denied.body.error.code, "forbidden"); + } + assert.equal(text((await git(operator.token, ["show", "HEAD:a.txt"])).body.stdout), "hello\n"); + for (const args of [["status", "--porcelain"], ["branch", "--show-current"], ["log", "--format=%s"], ["diff", "--numstat", "HEAD"], ["diff-tree", "-r", "--name-status", "HEAD"]]) { + const allowed = await git(reader.token, args); + assert.equal(allowed.status, 200, args.join(" ")); + assert.equal(allowed.body.code, 0, `${args.join(" ")}: ${text(allowed.body.stderr)}`); + } + const refused = await git(operator.token, ["-c", "core.fsmonitor=touch /tmp/pwned", "status"]); + assert.equal(refused.status, 400); + assert.equal(refused.body.error.code, "git_refused"); + assert.equal((await git(operator.token, ["status"], { env: { GIT_SSH_COMMAND: "evil" } })).body.error.code, "env_not_allowed"); + assert.equal((await git(operator.token, ["status"], { env: { GIT_CONFIG_PARAMETERS: "'core.fsmonitor'='evil'" } })).body.error.code, "env_not_allowed"); + assert.equal((await git(operator.token, [])).body.error.code, "invalid_args"); + assert.equal((await git(operator.token, ["status", "a\0b"])).body.error.code, "invalid_args"); + assert.equal((await git(operator.token, ["status"], { stdin: "not base64!" })).body.error.code, "invalid_stdin"); + assert.equal((await git(operator.token, ["status"], { timeoutMs: 300_000 })).body.error.code, "invalid_timeout", "only network commands may wait that long"); + assert.equal((await call(server.url, "POST", "/api/git", { token: operator.token, body: { cwd: "relative", args: ["status"] } })).body.error.code, "invalid_cwd"); + assert.equal((await call(server.url, "POST", "/api/git", { body: { cwd: repo, args: ["status"] } })).status, 401); + assert.equal((await call(server.url, "GET", "/api/git", { token: operator.token })).status, 405); +}); + +test("a network command that hangs is ended at its timeout", async () => { + const port = (silent.address() as { port: number }).port; + const started = Date.now(); + const hung = await git(reader.token, ["ls-remote", `http://127.0.0.1:${port}/repo.git`], { timeoutMs: 1000 }); + assert.equal(hung.status, 200); + assert.equal(hung.body.timedOut, true); + assert.ok(Date.now() - started < 5000); +}); + +test("git missing on the server answers 501 git_missing", async () => { + const auth = new ServeAuth({ devicesFile: join(root, "serve2", "devices.json"), adminToken: ADMIN }); + const bare = await startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", launchSession: () => { throw new Error("none"); }, env: { PATH: join(root, "no-bin") } }); + try { + const missing = await call(bare.url, "POST", "/api/git", { token: ADMIN, body: { cwd: repo, args: ["status"] } }); + assert.equal(missing.status, 501); + assert.equal(missing.body.error.code, "git_missing"); + } finally { + await bare.close(); + } +}); diff --git a/tests/serve-print.test.ts b/tests/serve-print.test.ts new file mode 100644 index 000000000..acf51574c --- /dev/null +++ b/tests/serve-print.test.ts @@ -0,0 +1,112 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { printLaunch } from "../lib/serve-cli.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { after, before, call, pairDevice, test } from "./serve-test-client.ts"; + +const FAKE_PRINT = fileURLToPath(new URL("./fixtures/serve-fake-print.mjs", import.meta.url)); +const ADMIN = "gsa_test-admin-token"; +let root: string; +let project: string; +let server: ServeServer; +let bare: ServeServer; +const launches: Array<{ cwd: string; model?: string }> = []; + +before(async () => { + root = mkdtempSync(join(tmpdir(), "gentle-serve-print-")); + project = realpathSync(mkdtempSync(join(root, "project-"))); + const auth = new ServeAuth({ devicesFile: join(root, "devices.json"), adminToken: ADMIN }); + const base = { host: "127.0.0.1", port: 0, auth, version: "test", launchSession: () => { throw new Error("no sessions here"); } }; + server = await startServeServer({ + ...base, + launchPrint: (input) => { + launches.push(input); + // The real launch, with the fake standing in for the launcher. + return printLaunch({ nodePath: process.execPath, launcher: FAKE_PRINT, homeFlags: ["--isolated"], env: { ...process.env, GENTLE_SHELL_INTERACTIVE_HOST: "1" } }, input); + }, + printLimits: { timeoutMs: 1500, stdoutBytes: 1000, maxRunning: 1, killGraceMs: 200 }, + }); + bare = await startServeServer(base); +}); +after(async () => { + await server?.close(); + await bare?.close(); + rmSync(root, { recursive: true, force: true }); +}); + +test("the launch mirrors the app's commit-message run: --print, no session, no tools, no interactive host", () => { + const launch = printLaunch({ nodePath: "/node", launcher: "/gs.mjs", homeFlags: ["--home", "/h"], env: { A: "1", GENTLE_SHELL_INTERACTIVE_HOST: "1" } }, { cwd: "/w", model: "anthropic/claude-x" }); + assert.equal(launch.command, "/node"); + assert.deepEqual(launch.args, ["/gs.mjs", "--home", "/h", "--print", "--no-session", "--no-tools", "--model", "anthropic/claude-x"]); + assert.equal(launch.cwd, "/w"); + assert.equal(launch.env.A, "1"); + assert.equal(launch.env.GENTLE_SHELL_INTERACTIVE_HOST, undefined); + assert.deepEqual(printLaunch({ nodePath: "/node", launcher: "/gs.mjs", homeFlags: [], env: {} }, { cwd: "/w" }).args, ["/gs.mjs", "--print", "--no-session", "--no-tools"]); +}); + +test("POST /api/print answers the run's stdout; the prompt goes on stdin", async () => { + const info = await call(server.url, "GET", "/api/server", { token: ADMIN }); + assert.ok(info.body.capabilities.includes("print")); + const prompt = "Write a commit message\n\n\n+ü\n\n"; + const answer = await call(server.url, "POST", "/api/print", { token: ADMIN, body: { cwd: project, prompt, model: "openai/gpt-x:high" } }); + assert.equal(answer.status, 200, JSON.stringify(answer.body)); + assert.deepEqual(Object.keys(answer.body), ["text"]); + const ran = JSON.parse(answer.body.text); + assert.equal(ran.prompt, prompt); + assert.deepEqual(ran.args, ["--isolated", "--print", "--no-session", "--no-tools", "--model", "openai/gpt-x:high"]); + assert.equal(ran.cwd, project); + assert.equal(ran.interactiveHost, null); + assert.deepEqual(launches.at(-1), { cwd: project, model: "openai/gpt-x:high" }); +}); + +test("a failing run, a run past its time and an answer over the cap are errors", async () => { + const failed = await call(server.url, "POST", "/api/print", { token: ADMIN, body: { cwd: project, prompt: "fail please" } }); + assert.equal(failed.status, 502); + assert.equal(failed.body.error.code, "print_failed"); + assert.match(failed.body.error.message, /no model configured/); + assert.equal(failed.body.exitCode, 3); + + const big = await call(server.url, "POST", "/api/print", { token: ADMIN, body: { cwd: project, prompt: "big" } }); + assert.equal(big.status, 502); + assert.equal(big.body.error.code, "output_too_large"); + + const started = Date.now(); + const launched = launches.length; + const slow = call(server.url, "POST", "/api/print", { token: ADMIN, body: { cwd: project, prompt: "hang" } }); + // The run starts in the same tick as its launch is built; there is no event to await for it. + while (launches.length === launched) await new Promise((r) => setImmediate(r)); + // One run at a time here: a second is refused, not queued. + const busy = await call(server.url, "POST", "/api/print", { token: ADMIN, body: { cwd: project, prompt: "hello" } }); + assert.equal(busy.status, 429); + assert.equal(busy.body.error.code, "too_many_prints"); + const timedOut = await slow; + assert.equal(timedOut.status, 504); + assert.equal(timedOut.body.error.code, "print_timeout"); + assert.ok(Date.now() - started < 5000); + const again = await call(server.url, "POST", "/api/print", { token: ADMIN, body: { cwd: project, prompt: "hello" } }); + assert.equal(again.status, 200, "the slot is free once the run ended"); +}); + +test("print checks its input and scope, and a server without a launcher runs none", async () => { + const reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader"); + assert.equal((await call(server.url, "POST", "/api/print", { token: reader.token, body: { cwd: project, prompt: "hi" } })).status, 403); + assert.equal((await call(server.url, "POST", "/api/print", { body: { cwd: project, prompt: "hi" } })).status, 401); + assert.equal((await call(server.url, "GET", "/api/print", { token: ADMIN })).status, 405); + const bad = async (body: unknown) => (await call(server.url, "POST", "/api/print", { token: ADMIN, body })).body.error.code; + assert.equal(await bad({ cwd: "relative", prompt: "hi" }), "invalid_cwd"); + assert.equal(await bad({ cwd: join(project, "missing"), prompt: "hi" }), "invalid_cwd"); + assert.equal(await bad({ cwd: project, prompt: " " }), "invalid_prompt"); + assert.equal(await bad({ cwd: project, prompt: "x".repeat(256 * 1024 + 1) }), "invalid_prompt"); + assert.equal(await bad({ cwd: project, prompt: "hi", model: "--tools" }), "invalid_model"); + assert.equal(await bad({ cwd: project, prompt: "hi", model: "a b" }), "invalid_model"); + + const info = await call(bare.url, "GET", "/api/server", { token: ADMIN }); + assert.ok(!info.body.capabilities.includes("print")); + const none = await call(bare.url, "POST", "/api/print", { token: ADMIN, body: { cwd: project, prompt: "hi" } }); + assert.equal(none.status, 501); + assert.equal(none.body.error.code, "not_supported"); +}); diff --git a/tests/serve-relay.test.ts b/tests/serve-relay.test.ts new file mode 100644 index 000000000..0717662e7 --- /dev/null +++ b/tests/serve-relay.test.ts @@ -0,0 +1,248 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { createServer as createHttpServer } from "node:http"; +import { connect as netConnect, createServer as createNetServer, type Socket } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { relaySecret } from "../lib/serve-cli.ts"; +import { connectThroughRelay, parseRelayUrl, RELAY_SIGNATURE_PREFIX, RelayError, startRelay, startRelayLink, type Relay } from "../lib/serve-relay.ts"; +import { parseRelayArgs, relayServerSecret, runRelayCommand } from "../lib/serve-relay-cli.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { connectPinned, createSelfSignedCertificate, loadOrCreateServeTls, peekFingerprint, verifyPairProof } from "../lib/serve-tls.ts"; +import { after, callOver, test } from "./serve-test-client.ts"; + +const ADMIN = "gsa_relay-test-admin"; +const SECRET = "relay-test-secret"; +const roots: string[] = []; +after(() => roots.forEach((r) => rmSync(r, { recursive: true, force: true }))); +function scratch(): string { + const r = realpathSync(mkdtempSync(join(tmpdir(), "gentle-serve-relay-"))); + roots.push(r); + return r; +} + +/** One handshake line from a raw socket: the relay's protocol as a client written in any language sees it. */ +function line(socket: Socket): Promise> { + const { promise, resolve, reject } = Promise.withResolvers>(); + let text = ""; + const onData = (chunk: Buffer) => { + text += chunk.toString("utf8"); + const end = text.indexOf("\n"); + if (end === -1) return; + socket.off("data", onData); + resolve(JSON.parse(text.slice(0, end))); + }; + socket.on("data", onData); + socket.once("error", reject); + return promise; +} + +async function raw(port: number, hello: Record): Promise<{ socket: Socket; answer: Record }> { + const socket = netConnect({ host: "127.0.0.1", port }); + await new Promise((resolve) => socket.once("connect", () => resolve())); + socket.write(`${JSON.stringify(hello)}\n`); + return { socket, answer: await line(socket) }; +} + +interface Setup { relay: Relay; server: ServeServer; auth: ServeAuth; fingerprint: string; logs: string[]; url: string } + +async function setup(t: { after: (fn: () => unknown) => void }, options: { serverSecret?: string; relayLimits?: Parameters[0]["limits"] } = {}): Promise { + const root = scratch(); + const logs: string[] = []; + const relay = await startRelay({ host: "127.0.0.1", port: 0, secret: SECRET, log: (l) => logs.push(l), ...(options.relayLimits ? { limits: options.relayLimits } : {}) }); + t.after(() => relay.close()); + const url = `gsr://127.0.0.1:${relay.port}`; + const auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + const tls = loadOrCreateServeTls(join(root, "serve"), { commonName: "relay test", dnsNames: ["localhost"], ips: ["127.0.0.1"] }); + // A loopback server: only the relay brings it network clients. + const server = await startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", tls, relay: { url, secret: options.serverSecret ?? SECRET, retryMinMs: 50 }, + launchSession: () => { throw new Error("no sessions in these tests"); }, log: (l) => logs.push(l) }); + t.after(() => server.close()); + return { relay, server, auth, fingerprint: tls.fingerprint, logs, url }; +} + +test("relay URLs are gsr://host:port and nothing else", () => { + assert.deepEqual(parseRelayUrl("gsr://relay.example.com:7700"), { url: "gsr://relay.example.com:7700", host: "relay.example.com", port: 7700 }); + assert.deepEqual(parseRelayUrl("gsr://[2001:db8::1]:7700/"), { url: "gsr://[2001:db8::1]:7700", host: "2001:db8::1", port: 7700 }); + for (const bad of ["relay.example.com:7700", "https://relay.example.com:7700", "gsr://relay.example.com", "gsr://u:p@relay.example.com:7700", "gsr://relay.example.com:7700/x", "gsr://relay.example.com:7700?q"]) { + assert.ok("error" in parseRelayUrl(bad), bad); + } +}); + +test("through the relay: pairing with a proof, then the API, end to end TLS the relay cannot read", async (t) => { + const { relay, server, auth, fingerprint, logs, url } = await setup(t); + await server.relay!.ready(); + assert.deepEqual(relay.servers(), [fingerprint], "the server registered under its certificate's fingerprint"); + + // A tap between the client and the relay records every byte the relay receives from the client and sends back. + const tapped: Buffer[] = []; + const tap = createNetServer((client) => { + const upstream = netConnect({ host: "127.0.0.1", port: relay.port }); + client.on("data", (c: Buffer) => tapped.push(c)); + upstream.on("data", (c: Buffer) => tapped.push(c)); + client.pipe(upstream).pipe(client); + client.on("error", () => upstream.destroy()); + upstream.on("error", () => client.destroy()); + }); + await new Promise((resolve) => tap.listen(0, "127.0.0.1", resolve)); + t.after(() => tap.close()); + const viaTap = `gsr://127.0.0.1:${(tap.address() as { port: number }).port}`; + const pinned = async () => connectPinned({ socket: await connectThroughRelay(viaTap, fingerprint) }, fingerprint); + + // The long code gives fp and r: the client pins fp, so the proof is optional, but works through the relay as well. + const minted = auth.mintPairingCode(); + const nonce = randomBytes(16); + const seen = await peekFingerprint({ socket: await connectThroughRelay(viaTap, fingerprint) }); + assert.equal(seen.fingerprint, fingerprint, "the server's own certificate, through the relay"); + const proof = await callOver(seen.socket, "POST", "/api/pair/proof", { host: "relay.example", body: { nonce: nonce.toString("base64url") } }); + assert.equal(proof.status, 200, "no Host check through the relay"); + assert.equal(await verifyPairProof({ code: minted.code, fingerprint: seen.fingerprint, nonce, proofs: proof.body.proofs }), true); + const paired = await callOver(await pinned(), "POST", "/api/pair", { host: "relay.example", body: { code: minted.code, name: "phone" } }); + assert.equal(paired.status, 201, JSON.stringify(paired.body)); + const token: string = paired.body.token; + const info = await callOver(await pinned(), "GET", "/api/server", { host: "relay.example", token }); + assert.equal(info.status, 200); + assert.equal(info.body.serverId, server.serverId); + assert.deepEqual(info.body.relay, { url, connected: true }); + // A bigger body both ways stays intact. + const big = await callOver(await pinned(), "POST", "/api/pair/proof", { host: "relay.example", body: { nonce: randomBytes(16).toString("base64url"), pad: "x".repeat(10_000) } }); + assert.equal(big.status, 200); + + // What the relay saw: handshake lines, then TLS records only. + const seenByRelay = Buffer.concat(tapped).toString("latin1"); + for (const secret of [token, minted.code, "/api/pair", "/api/server", "Authorization", "phone"]) assert.ok(!seenByRelay.includes(secret), `the relay never saw ${secret}`); + assert.ok(seenByRelay.includes('"t":"gsr/client"'), "the client's hello is the only plaintext"); + // The relay logs connections and byte counts, never content. + await new Promise((resolve) => { const poll = setInterval(() => { if (logs.some((l) => /connection closed after \d+ s, \d+ B up, \d+ B down/.test(l))) { clearInterval(poll); resolve(); } }, 10); }); + assert.ok(!logs.join("\n").includes(token)); +}); + +test("the relay refuses: unknown servers, bad hellos, a wrong secret, a server without the certificate's key", async (t) => { + const { relay, server, fingerprint } = await setup(t); + await server.relay!.ready(); + assert.deepEqual((await raw(relay.port, { t: "gsr/client", v: 1, id: "A".repeat(43) })).answer, { t: "error", code: "offline", message: "That server is not connected to this relay" }); + assert.equal((await raw(relay.port, { t: "gsr/client", v: 1, id: "nope" })).answer.code, "bad_request"); + assert.equal((await raw(relay.port, { t: "gsr/client", v: 2, id: fingerprint })).answer.code, "unsupported_version"); + assert.equal((await raw(relay.port, { t: "gsr/client", v: 1, id: fingerprint, port: 0 })).answer.code, "bad_request"); + assert.equal((await raw(relay.port, { t: "gsr/data", v: 1, cid: "x", key: "y" })).answer.code, "unauthorized"); + await assert.rejects(connectThroughRelay(`gsr://127.0.0.1:${relay.port}`, "B".repeat(43)), (e: RelayError) => e.code === "offline"); + // Nothing listens on that port of the server: refused, not a timeout. + await assert.rejects(connectThroughRelay(`gsr://127.0.0.1:${relay.port}`, fingerprint, { port: 1 }), (e: RelayError) => e.code === "refused"); + + // Registering without the relay secret. + assert.equal((await raw(relay.port, { t: "gsr/server", v: 1, id: fingerprint })).answer.code, "unauthorized"); + assert.equal((await raw(relay.port, { t: "gsr/server", v: 1, id: fingerprint, secret: "wrong" })).answer.code, "unauthorized"); + // An impostor with the secret claims the server's fingerprint but signs with another key: refused, the real one stays. + const impostor = await raw(relay.port, { t: "gsr/server", v: 1, id: fingerprint, secret: SECRET }); + assert.equal(impostor.answer.t, "challenge"); + const other = createSelfSignedCertificate({ commonName: "impostor", dnsNames: [], ips: [] }); + const { sign, createPrivateKey } = await import("node:crypto"); // the signature helpers a raw client would use + const sig = sign("sha256", Buffer.from(`${RELAY_SIGNATURE_PREFIX}${String(impostor.answer.nonce)}`), createPrivateKey(other.keyPem)); + impostor.socket.write(`${JSON.stringify({ t: "auth", cert: other.der.toString("base64url"), sig: sig.toString("base64url") })}\n`); + assert.equal((await line(impostor.socket)).code, "unauthorized"); + assert.deepEqual(relay.servers(), [fingerprint]); + assert.ok(server.relay!.connected()); +}); + +test("a server with the wrong relay secret is not registered and says so", async (t) => { + const { relay, server, logs } = await setup(t, { serverSecret: "not-it" }); + await new Promise((resolve) => { const poll = setInterval(() => { if (logs.some((l) => l.includes("refused the registration: unauthorized"))) { clearInterval(poll); resolve(); } }, 10); }); + assert.equal(server.relay!.connected(), false); + assert.deepEqual(relay.servers(), []); +}); + +test("relay limits: connections per server, the open timeout, idle pairs", async (t) => { + const { relay, server, fingerprint } = await setup(t, { relayLimits: { maxConnectionsPerServer: 2, idleMs: 300 } }); + await server.relay!.ready(); + const url = `gsr://127.0.0.1:${relay.port}`; + const first = await connectThroughRelay(url, fingerprint); + const second = await connectThroughRelay(url, fingerprint); + await assert.rejects(connectThroughRelay(url, fingerprint), (e: RelayError) => e.code === "busy"); + // An idle pair is closed by the relay (no byte either way for idleMs). + await Promise.all([new Promise((r) => first.once("close", r)), new Promise((r) => second.once("close", r))]); + const third = await connectThroughRelay(url, fingerprint); + third.destroy(); + + // A registered server that never opens the data connection: the client hears "timeout". + const quiet = await startRelay({ host: "127.0.0.1", port: 0, limits: { openTimeoutMs: 100 } }); + t.after(() => quiet.close()); + const cert = createSelfSignedCertificate({ commonName: "quiet", dnsNames: [], ips: [] }); + const link = startRelayLink({ url: `gsr://127.0.0.1:${quiet.port}`, certDer: cert.der, keyPem: cert.keyPem, accept: () => () => {} }); + t.after(() => link.close()); + await link.ready(); + const silent = startRelayLink({ url: `gsr://127.0.0.1:${quiet.port}`, certDer: cert.der, keyPem: cert.keyPem, accept: () => undefined }); + t.after(() => silent.close()); + await silent.ready(); // the same certificate registers again: it replaces the first registration + const { id } = silent; + const hello = await raw(quiet.port, { t: "gsr/client", v: 1, id }); + assert.equal(hello.answer.code, "refused", "the replacing registration refuses (accept says no)"); +}); + +test("the server registers again when the relay comes back, and forwards are reachable by their port", async (t) => { + const root = scratch(); + const logs: string[] = []; + let relay = await startRelay({ host: "127.0.0.1", port: 0, secret: SECRET }); + const port = relay.port; + const auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + const tls = loadOrCreateServeTls(join(root, "serve"), { commonName: "relay test", dnsNames: [], ips: ["127.0.0.1"] }); + const server = await startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", tls, relay: { url: `gsr://127.0.0.1:${port}`, secret: SECRET, retryMinMs: 20 }, + launchSession: () => { throw new Error("none"); }, log: (l) => logs.push(l) }); + t.after(() => server.close()); + await server.relay!.ready(); + await relay.close(); + await new Promise((resolve) => { const poll = setInterval(() => { if (!server.relay!.connected()) { clearInterval(poll); resolve(); } }, 10); }); + relay = await startRelay({ host: "127.0.0.1", port, secret: SECRET }); + t.after(() => relay.close()); + await new Promise((resolve) => { const poll = setInterval(() => { if (server.relay!.connected()) { clearInterval(poll); resolve(); } }, 10); }); + assert.deepEqual(relay.servers(), [tls.fingerprint]); + + // A forward: the client asks the relay for the forward's listen port. + const page = createHttpServer((req, res) => res.end(`page ${req.url}`)); + await new Promise((resolve) => page.listen(0, "127.0.0.1", resolve)); + t.after(() => page.close()); + const url = `gsr://127.0.0.1:${port}`; + const opened = await callOver(await connectPinned({ socket: await connectThroughRelay(url, tls.fingerprint) }, tls.fingerprint), "POST", "/api/forwards", + { host: "relay.example", token: ADMIN, body: { port: (page.address() as { port: number }).port, path: "/p" } }); + assert.equal(opened.status, 201, JSON.stringify(opened.body)); + const link = new URL(opened.body.url); + assert.equal(link.protocol, "https:"); + const first = await callOver(await connectPinned({ socket: await connectThroughRelay(url, tls.fingerprint, { port: Number(link.port) }) }, tls.fingerprint), "GET", `${link.pathname}${link.search}`, { host: "relay.example" }); + assert.equal(first.status, 303); + const shown = await callOver(await connectPinned({ socket: await connectThroughRelay(url, tls.fingerprint, { port: Number(link.port) }) }, tls.fingerprint), "GET", "/p", + { host: "relay.example", headers: { Cookie: String(first.headers["set-cookie"]).split(";")[0] } }); + assert.equal(shown.body, "page /p"); +}); + +test("gentle-shell relay: arguments, the secret, and a run", async () => { + assert.deepEqual(parseRelayArgs(["--listen", "0.0.0.0:7700"]), { action: "run", host: "0.0.0.0", port: 7700, json: false }); + assert.deepEqual(parseRelayArgs(["--listen=7700", "--secret-file", "/etc/relay", "--json"]), { action: "run", host: "127.0.0.1", port: 7700, json: true, secretFile: "/etc/relay" }); + assert.deepEqual(parseRelayArgs([]), { error: "relay needs --listen :, for example --listen 0.0.0.0:7700" }); + assert.deepEqual(parseRelayArgs(["--help"]), { action: "help" }); + assert.deepEqual(parseRelayArgs(["--open"]), { error: 'unknown relay argument "--open"' }); + + const root = scratch(); + const made = relayServerSecret({ agentHome: root, env: {} }); + assert.equal(made.source, join(root, "relay", "secret")); + if (process.platform !== "win32") assert.equal(statSync(made.source).mode & 0o777, 0o600); + assert.equal(relayServerSecret({ agentHome: root, env: {} }).secret, made.secret, "made once"); + assert.deepEqual(relayServerSecret({ agentHome: root, env: { GENTLE_SHELL_RELAY_SECRET: " env-secret " } }), { secret: "env-secret", source: "GENTLE_SHELL_RELAY_SECRET" }); + const file = join(root, "given"); + writeFileSync(file, "from-file\nignored\n"); + assert.equal(relayServerSecret({ agentHome: root, env: {} }, file).secret, "from-file"); + // The server side: env first, then /serve/relay-secret. + writeFileSync(join(root, "relay-secret"), "server-file\n"); + assert.equal(relaySecret({}, root), "server-file"); + assert.equal(relaySecret({ GENTLE_SHELL_RELAY_SECRET: "e" }, root), "e"); + assert.equal(relaySecret({}, join(root, "missing")), undefined); + + const out: string[] = []; + const stop = Promise.withResolvers(); + const running = runRelayCommand({ action: "run", host: "127.0.0.1", port: 0, json: true }, { agentHome: root, env: {}, stdout: (s) => { out.push(s); stop.resolve(); }, stderr: () => {}, untilStopped: () => stop.promise }); + assert.equal(await running, 0); + const printed = JSON.parse(out.join("")); + assert.equal(printed.schema, "gentle-shell.relay/v1"); + assert.equal(printed.secretSource, join(root, "relay", "secret")); + assert.ok(!out.join("").includes(readFileSync(made.source, "utf8").trim()), "the secret itself is never printed"); +}); diff --git a/tests/serve-server-id.test.ts b/tests/serve-server-id.test.ts new file mode 100644 index 000000000..be38b2ec1 --- /dev/null +++ b/tests/serve-server-id.test.ts @@ -0,0 +1,53 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { call, test } from "./serve-test-client.ts"; + +const ADMIN = "gsa_test-admin-token"; + +async function run(serveDir: string, check: (server: ServeServer) => Promise): Promise { + const server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth: new ServeAuth({ devicesFile: join(serveDir, "devices.json"), adminToken: ADMIN }), + version: "test", + serveDir, + launchSession: () => { throw new Error("no sessions here"); }, + }); + try { + await check(server); + } finally { + await server.close(); + } +} + +test("the server id is minted once per home and kept across runs", async (t) => { + const root = mkdtempSync(join(tmpdir(), "gentle-serve-id-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const serveDir = join(root, "serve"); + const ids: string[] = []; + for (let i = 0; i < 2; i += 1) { + await run(serveDir, async (server) => { + const identity = await call(server.url, "GET", "/.well-known/gentle-shell"); + const info = await call(server.url, "GET", "/api/server", { token: ADMIN }); + assert.equal(identity.body.serverId, server.serverId); + assert.equal(info.body.serverId, server.serverId); + ids.push(server.serverId); + }); + } + assert.match(ids[0], /^srv_[0-9a-f]{16}$/); + assert.equal(ids[1], ids[0], "a restart keeps the id"); + const file = join(serveDir, "server-id"); + assert.equal(readFileSync(file, "utf8").trim(), ids[0]); + if (process.platform !== "win32") assert.equal(statSync(file).mode & 0o777, 0o600); + + writeFileSync(file, "not an id\n"); + await run(serveDir, async (server) => { + assert.match(server.serverId, /^srv_[0-9a-f]{16}$/); + assert.notEqual(server.serverId, ids[0], "a malformed file is replaced"); + assert.equal(readFileSync(file, "utf8").trim(), server.serverId); + }); +}); diff --git a/tests/serve-server.test.ts b/tests/serve-server.test.ts new file mode 100644 index 000000000..ea90360a5 --- /dev/null +++ b/tests/serve-server.test.ts @@ -0,0 +1,501 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { request as httpRequest, type IncomingMessage } from "node:http"; +import { homedir, hostname, tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServeAuth, type ServeScope } from "../lib/serve-auth.ts"; +import { allowedHosts, carriesHostToolRequest, desktopMethodScope, rpcCommandScope, startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { after, before, endServeLeftovers, remainingServeLeftovers, test } from "./serve-test-client.ts"; + +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); +const ADMIN = "gsa_test-admin-token"; +const roots: string[] = []; +let server: ServeServer; +let auth: ServeAuth; +let project: string; +let stopRequests = 0; +const launches: Array<{ cwd: string; sessionId?: string }> = []; + +before(async () => { + const root = mkdtempSync(join(tmpdir(), "gentle-serve-server-")); + roots.push(root); + project = realpathSync(mkdtempSync(join(root, "project-"))); + auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth, + version: "test", + launchSession: (input) => { + launches.push(input); + return { command: process.execPath, args: [FAKE_PI, ...(input.sessionId ? ["--session", input.sessionId] : [])], cwd: input.cwd, env: { ...process.env, GENTLE_SHELL_INTERACTIVE_HOST: "1" } }; + }, + onStopRequested: () => { stopRequests += 1; }, + limits: { rpcTimeoutMs: 2000, maxSessions: 3 }, + }); +}); +// Sessions end with the server: no serve folder, so their keepers live in a private temp folder. +let closing: Promise | undefined; +const closeServer = () => (closing ??= server?.close({ endSessions: true })); +after(async () => { + await closeServer(); + // A failed test must not leave a keeper (or its fake Pi) behind. + await endServeLeftovers([], roots); + roots.forEach((r) => rmSync(r, { recursive: true, force: true })); +}); + +interface Reply { status: number; body: any; headers: IncomingMessage["headers"] } + +function call(method: string, path: string, options: { token?: string; body?: unknown; raw?: string; headers?: Record } = {}): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const payload = options.raw ?? (options.body === undefined ? undefined : JSON.stringify(options.body)); + const req = httpRequest(`${server.url}${path}`, { + method, + headers: { + ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}), + ...(payload === undefined ? {} : { "Content-Type": "application/json" }), + ...options.headers, + }, + }, (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + let body: unknown = text; + try { body = JSON.parse(text); } catch { /* not JSON */ } + resolve({ status: res.statusCode ?? 0, body, headers: res.headers }); + }); + }); + req.on("error", reject); + req.end(payload); + return promise; +} + +/** An open SSE stream; `text` grows as events arrive. */ +interface Stream { status: number; text: string; closed: Promise; waitFor(what: string): Promise; close(): void } + +function stream(path: string, token?: string): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const req = httpRequest(`${server.url}${path}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }, (res) => { + const closed = Promise.withResolvers(); + const waiters: Array<{ what: string; done: () => void }> = []; + const s: Stream = { + status: res.statusCode ?? 0, + text: "", + closed: closed.promise, + waitFor(what) { + if (s.text.includes(what)) return Promise.resolve(); + const w = Promise.withResolvers(); + waiters.push({ what, done: w.resolve }); + return w.promise; + }, + close: () => req.destroy(), + }; + res.on("data", (c: Buffer) => { + s.text += c.toString("utf8"); + for (const w of [...waiters]) if (s.text.includes(w.what)) { waiters.splice(waiters.indexOf(w), 1); w.done(); } + }); + res.on("close", () => closed.resolve()); + resolve(s); + }); + req.on("error", (error) => { if (!(error as NodeJS.ErrnoException).code?.startsWith("ECONNRESET")) reject(error); }); + req.end(); + return promise; +} + +async function pairDevice(scopes: ServeScope[], name = "device"): Promise<{ id: string; token: string }> { + const code = await call("POST", "/api/pairing-codes", { token: ADMIN, body: { scopes } }); + assert.equal(code.status, 201); + const paired = await call("POST", "/api/pair", { body: { code: code.body.code, name } }); + assert.equal(paired.status, 201, JSON.stringify(paired.body)); + assert.deepEqual(paired.body.scopes, scopes); + return { id: paired.body.id, token: paired.body.token }; +} + +async function startSession(token = ADMIN): Promise { + const started = await call("POST", "/api/sessions", { token, body: { cwd: project } }); + assert.equal(started.status, 201, JSON.stringify(started.body)); + return started.body.session.id; +} + +test("scope tables: reads need sessions:read, everything else operates", () => { + assert.equal(rpcCommandScope("get_state"), "sessions:read"); + assert.equal(rpcCommandScope("get_messages"), "sessions:read"); + assert.equal(rpcCommandScope("prompt"), "sessions:operate"); + assert.equal(rpcCommandScope("bash"), "sessions:operate"); + assert.equal(desktopMethodScope("capabilities"), "sessions:read"); + assert.equal(desktopMethodScope("get_snapshot"), "sessions:read"); + assert.equal(desktopMethodScope("list_jobs"), "sessions:read"); + assert.equal(desktopMethodScope("set_permission_mode"), "sessions:operate"); + assert.equal(desktopMethodScope("apply_profile"), "sessions:operate"); +}); + +test("Host header allowlist follows the listen address", () => { + const loop = allowedHosts("127.0.0.1", 4000); + assert.ok(loop("127.0.0.1:4000") && loop("localhost:4000") && loop("[::1]:4000")); + assert.ok(!loop("evil.example:4000") && !loop("127.0.0.1:4001") && !loop("192.168.1.2:4000")); + const lan = allowedHosts("192.168.1.2", 4000); + assert.ok(lan("192.168.1.2:4000")); + assert.ok(!lan("127.0.0.1:4000") && !lan("rebind.example:4000")); + const any = allowedHosts("0.0.0.0", 4000); + assert.ok(any("10.0.0.7:4000") && any("127.0.0.1:4000") && any("[fe80::1]:4000")); + assert.ok(!any("rebind.example:4000") && !any("10.0.0.7:4001")); + // A tailnet MagicDNS name is another DNS name: refused unless the operator allowed it. + assert.ok(!any("box.tail1234.ts.net:4000")); + const tailnet = allowedHosts("0.0.0.0", 4000, ["box.tail1234.ts.net"]); + assert.ok(tailnet("box.tail1234.ts.net:4000") && tailnet("BOX.tail1234.ts.net:4000") && tailnet("10.0.0.7:4000")); + assert.ok(!tailnet("box.tail1234.ts.net:4001") && !tailnet("other.tail1234.ts.net:4000")); +}); + +test("requests with a foreign Origin or an unexpected Host are refused before auth", async () => { + const origin = await call("GET", "/api/server", { token: ADMIN, headers: { Origin: "http://evil.example" } }); + assert.equal(origin.status, 403); + assert.equal(origin.body.error.code, "forbidden_origin"); + const same = await call("GET", "/api/server", { token: ADMIN, headers: { Origin: server.url } }); + assert.equal(same.status, 200); + const host = await call("GET", "/api/server", { token: ADMIN, headers: { Host: "rebind.example" } }); + assert.equal(host.status, 421); + const pair = await call("POST", "/api/pair", { body: { code: "XXXX-XXXX" }, headers: { Origin: "http://evil.example" } }); + assert.equal(pair.status, 403, "a page elsewhere cannot even try a code"); +}); + +test("GET /.well-known/gentle-shell names the server without a token, and Host/Origin rules still apply", async () => { + const identity = await call("GET", "/.well-known/gentle-shell"); + assert.equal(identity.status, 200); + assert.deepEqual(identity.body, { schema: "gentle-shell.serve.identity/v1", serverId: server.serverId, name: hostname(), protocol: 1, version: "test", tls: false }); + assert.equal(identity.headers["cache-control"], "no-store"); + assert.ok(!JSON.stringify(identity.body).includes("gsa_"), "no admin token, code or device in it"); + // A token changes nothing: the answer is the same public identity. + assert.deepEqual((await call("GET", "/.well-known/gentle-shell", { token: ADMIN })).body, identity.body); + assert.equal((await call("POST", "/.well-known/gentle-shell")).status, 405); + assert.equal((await call("GET", "/.well-known/gentle-shell", { headers: { Host: "rebind.example" } })).status, 421); + assert.equal((await call("GET", "/.well-known/gentle-shell", { headers: { Origin: "http://evil.example" } })).status, 403); +}); + +test("security headers, no token, a bad token and unknown routes", async () => { + const none = await call("GET", "/api/sessions"); + assert.equal(none.status, 401); + assert.equal(none.headers["cache-control"], "no-store"); + assert.match(String(none.headers["content-security-policy"]), /default-src 'none'/); + assert.equal(none.headers["access-control-allow-origin"], undefined); + assert.equal((await call("GET", "/api/sessions", { token: "gss_nope" })).status, 401); + assert.equal((await call("GET", "/nope", { token: ADMIN })).status, 404); + const info = await call("GET", "/api/server", { token: ADMIN }); + assert.equal(info.body.schema, "gentle-shell.serve/v1"); + assert.equal(info.body.protocol, 1); + assert.equal(info.body.serverId, server.serverId); + assert.deepEqual(info.body.device.scopes, ["sessions:read", "sessions:operate", "terminal", "admin"]); + assert.equal(info.body.home, homedir(), "a token that may start sessions learns the default folder"); + const reader = await pairDevice(["sessions:read"], "info-reader"); + assert.equal((await call("GET", "/api/server", { token: reader.token })).body.home, undefined, "a reader does not"); +}); + +test("bodies are bounded and must be one JSON object", async () => { + const big = await call("POST", "/api/pairing-codes", { token: ADMIN, raw: JSON.stringify({ pad: "x".repeat(40_000) }) }); + assert.equal(big.status, 413); + const bad = await call("POST", "/api/pairing-codes", { token: ADMIN, raw: "[1,2]" }); + assert.equal(bad.status, 400); + const scopes = await call("POST", "/api/pairing-codes", { token: ADMIN, body: { scopes: ["root"] } }); + assert.equal(scopes.status, 400); +}); + +test("per-endpoint scopes: a read-only device reads, a session device operates, only admin pairs", async () => { + const reader = await pairDevice(["sessions:read"], "reader"); + const operator = await pairDevice(["sessions:read", "sessions:operate"], "operator"); + const id = await startSession(operator.token); + + assert.equal((await call("POST", "/api/sessions", { token: reader.token, body: { cwd: project } })).status, 403); + const list = await call("GET", "/api/sessions", { token: reader.token }); + assert.equal(list.status, 200); + const seen = list.body.sessions.find((s: any) => s.id === id); + assert.equal(seen.cwd, undefined, "a read-only token sees the folder name, not the path"); + assert.equal(seen.name, project.split(/[\\/]/).at(-1)); + const full = await call("GET", `/api/sessions/${id}`, { token: operator.token }); + assert.equal(full.body.session.cwd, project); + + assert.equal((await call("POST", `/api/sessions/${id}/rpc`, { token: reader.token, body: { type: "get_state" } })).status, 200); + const prompt = await call("POST", `/api/sessions/${id}/rpc`, { token: reader.token, body: { type: "prompt", message: "hi" } }); + assert.equal(prompt.status, 403); + assert.equal((await call("POST", `/api/sessions/${id}/desktop`, { token: reader.token, body: { method: "get_snapshot" } })).status, 200); + assert.equal((await call("POST", `/api/sessions/${id}/desktop`, { token: reader.token, body: { method: "set_permission_mode", params: { mode: "yolo" } } })).status, 403); + assert.equal((await call("POST", `/api/sessions/${id}/desktop`, { token: operator.token, body: { method: "set_permission_mode", params: { mode: "normal" } } })).status, 200); + assert.equal((await call("DELETE", `/api/sessions/${id}`, { token: reader.token })).status, 403); + + for (const token of [reader.token, operator.token]) { + assert.equal((await call("POST", "/api/pairing-codes", { token, body: {} })).status, 403); + assert.equal((await call("GET", "/api/devices", { token })).status, 403); + assert.equal((await call("DELETE", `/api/devices/${reader.id}`, { token })).status, 403); + assert.equal((await call("POST", "/api/server/stop", { token })).status, 403); + } + const devices = await call("GET", "/api/devices", { token: ADMIN }); + assert.ok(devices.body.devices.some((d: any) => d.id === reader.id && d.lastUsedAt)); + assert.ok(devices.body.devices.every((d: any) => !("tokenHash" in d) && !("token" in d))); + assert.equal((await call("DELETE", `/api/sessions/${id}`, { token: operator.token })).status, 200); +}); + +test("session lifecycle: start, Pi RPC, Desktop RPC, SSE replay, stop", async () => { + const started = await call("POST", "/api/sessions", { token: ADMIN, body: { cwd: project, sessionId: "abc-123" } }); + assert.equal(started.status, 201); + const id = started.body.session.id; + assert.equal(started.body.session.state, "running"); + assert.deepEqual(launches.at(-1), { cwd: project, sessionId: "abc-123" }); + + const state = await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "get_state", id: "client-1" } }); + assert.equal(state.status, 200); + assert.equal(state.body.id, "client-1"); + assert.equal(state.body.data.interactiveHost, "1"); + assert.deepEqual(state.body.data.args, ["--session", "abc-123"]); + + const caps = await call("POST", `/api/sessions/${id}/desktop`, { token: ADMIN, body: { method: "capabilities", params: {} } }); + assert.equal(caps.status, 200); + assert.equal(caps.body.kind, "response"); + assert.equal(caps.body.data.method, "capabilities"); + + const refused = await call("POST", `/api/sessions/${id}/desktop`, { token: ADMIN, body: { method: "refuse" } }); + assert.equal(refused.status, 502); + const slow = await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_silent" } }); + assert.equal(slow.status, 202); + assert.equal(slow.body.pending, true); + + const events = await stream(`/api/sessions/${id}/events?after=0`, ADMIN); + assert.equal(events.status, 200); + await events.waitFor('"command":"get_state"'); + assert.match(events.text, /event: hello\n/); + assert.match(events.text, /id: 1\ndata: \{/); + await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_burst", count: 2 } }); + await events.waitFor('"n":1'); + + const resumed = await stream(`/api/sessions/${id}/events`, ADMIN); + resumed.close(); + const lastId = Number([...events.text.matchAll(/^id: (\d+)$/gm)].at(-1)![1]); + const gap = await stream(`/api/sessions/${id}/events?after=${lastId - 1}`, ADMIN); + await gap.waitFor(`id: ${lastId}\n`); + gap.close(); + const invalid = await call("GET", `/api/sessions/${id}/events?after=x`, { token: ADMIN }); + assert.equal(invalid.status, 400); + + const stopped = await call("DELETE", `/api/sessions/${id}`, { token: ADMIN }); + assert.equal(stopped.status, 200); + assert.equal(stopped.body.session.state, "exited"); + await events.closed; + assert.match(events.text, /serve_session_exited/); + assert.equal((await call("GET", `/api/sessions/${id}`, { token: ADMIN })).status, 404); +}); + +test("sessions need an existing absolute folder and a plain Pi session id; the count is bounded", async () => { + for (const cwd of ["relative/path", join(project, "missing"), 42]) { + assert.equal((await call("POST", "/api/sessions", { token: ADMIN, body: { cwd } })).status, 400); + } + assert.equal((await call("POST", "/api/sessions", { token: ADMIN, body: { cwd: project, sessionId: "../../etc" } })).status, 400); + const ids = [await startSession(), await startSession(), await startSession()]; + const fourth = await call("POST", "/api/sessions", { token: ADMIN, body: { cwd: project } }); + assert.equal(fourth.status, 429); + for (const id of ids) await call("DELETE", `/api/sessions/${id}`, { token: ADMIN }); +}); + +test("dialogs: a late subscriber gets the pending dialog, the first answer wins", async () => { + const id = await startSession(); + // The RPC answer may reach the server ahead of the dialog Pi sends after it: an early stream sees when it is pending. + const early = await stream(`/api/sessions/${id}/events`, ADMIN); + await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_dialog" } }); + await early.waitFor('"id":"dlg-1"'); + early.close(); + const late = await stream(`/api/sessions/${id}/events`, ADMIN); + await late.waitFor("event: dialog\n"); + assert.match(late.text, /"id":"dlg-1"/); + const first = await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "extension_ui_response", id: "dlg-1", value: "a" } }); + assert.equal(first.status, 202); + const second = await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "extension_ui_response", id: "dlg-1", value: "b" } }); + assert.equal(second.status, 409); + const unknown = await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "extension_ui_response", id: "zzz", value: "b" } }); + assert.equal(unknown.status, 404); + await late.waitFor('"type":"fake_dialog_answer"'); + await late.waitFor('"type":"serve_dialog_resolved"'); + late.close(); + await call("DELETE", `/api/sessions/${id}`, { token: ADMIN }); +}); + +test("stream tickets: EventSource-style access with ?ticket=, single use, bound to the session", async () => { + const reader = await pairDevice(["sessions:read"], "browser"); + const id = await startSession(); + const other = await startSession(); + const minted = await call("POST", "/api/tickets", { token: reader.token, body: { sessionId: id } }); + assert.equal(minted.status, 201); + assert.match(minted.body.ticket, /^[A-Za-z0-9_-]{32}$/); + assert.equal((await call("GET", `/api/sessions/${other}/events?ticket=${minted.body.ticket}`)).status, 401, "another session spends it"); + const again = await call("POST", "/api/tickets", { token: reader.token, body: { sessionId: id } }); + const opened = await stream(`/api/sessions/${id}/events?ticket=${again.body.ticket}`); + assert.equal(opened.status, 200); + await opened.waitFor("event: hello"); + opened.close(); + assert.equal((await call("GET", `/api/sessions/${id}/events?ticket=${again.body.ticket}`)).status, 401, "single use"); + assert.equal((await call("GET", `/api/sessions/${id}/rpc?ticket=${again.body.ticket}`)).status, 405); + assert.equal((await call("POST", "/api/tickets", { token: reader.token, body: { sessionId: "ses_missing" } })).status, 404); + assert.equal((await call("POST", "/api/tickets", { body: { sessionId: id } })).status, 401); + await call("DELETE", `/api/sessions/${id}`, { token: ADMIN }); + await call("DELETE", `/api/sessions/${other}`, { token: ADMIN }); +}); + +test("revoking a device closes its open streams at once and its token stops working", async () => { + const phone = await pairDevice(["sessions:read", "sessions:operate"], "phone"); + const id = await startSession(); + const open = await stream(`/api/sessions/${id}/events`, phone.token); + await open.waitFor("event: hello"); + const mine = await stream(`/api/sessions/${id}/events`, ADMIN); + await mine.waitFor("event: hello"); + const revoked = await call("DELETE", `/api/devices/${phone.id}`, { token: ADMIN }); + assert.equal(revoked.status, 200); + await open.closed; + assert.equal((await call("GET", "/api/sessions", { token: phone.token })).status, 401); + await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "get_state" } }); + await mine.waitFor('"command":"get_state"'); + mine.close(); + assert.equal((await call("DELETE", `/api/devices/${phone.id}`, { token: ADMIN })).status, 404); + await call("DELETE", `/api/sessions/${id}`, { token: ADMIN }); +}); + +test("a device unpairs itself without admin: its streams close and its token stops working", async () => { + const laptop = await pairDevice(["sessions:read", "sessions:operate"], "laptop"); + const other = await pairDevice(["sessions:read"], "other"); + const server = await call("GET", "/api/server", { token: laptop.token }); + assert.ok(server.body.capabilities.includes("unpair")); + const id = await startSession(); + const open = await stream(`/api/sessions/${id}/events`, laptop.token); + await open.waitFor("event: hello"); + assert.equal((await call("GET", "/api/devices/self", { token: laptop.token })).status, 405); + assert.equal((await call("DELETE", "/api/devices/self")).status, 401); + assert.equal((await call("DELETE", "/api/devices/self", { token: ADMIN })).status, 400); + const revoked = await call("DELETE", "/api/devices/self", { token: laptop.token }); + assert.equal(revoked.status, 200); + assert.equal(revoked.body.revoked, laptop.id); + await open.closed; + assert.equal((await call("GET", "/api/server", { token: laptop.token })).status, 401); + assert.equal((await call("DELETE", "/api/devices/self", { token: laptop.token })).status, 401); + // Only the caller goes; its session keeps running. + assert.equal((await call("GET", "/api/server", { token: other.token })).status, 200); + assert.equal((await call("GET", `/api/sessions/${id}`, { token: ADMIN })).status, 200); + await call("DELETE", `/api/sessions/${id}`, { token: ADMIN }); +}); + +test("pairing over HTTP is single use and admin can stop the server", async () => { + const code = await call("POST", "/api/pairing-codes", { token: ADMIN, body: {} }); + assert.equal((await call("POST", "/api/pair", { body: { code: code.body.code, name: "a" } })).status, 201); + const reused = await call("POST", "/api/pair", { body: { code: code.body.code, name: "b" } }); + assert.equal(reused.status, 403); + assert.equal(reused.body.error.code, "invalid_code"); + assert.equal((await call("GET", "/api/pair")).status, 405); + const stop = await call("POST", "/api/server/stop", { token: ADMIN }); + assert.equal(stop.status, 202); + await new Promise((r) => setImmediate(r)); + assert.equal(stopRequests, 1); +}); + +test("only /desktop carries host tool requests: a /gentle:desktop prompt naming them through /rpc is refused", () => { + const prompt = (method: string) => `/gentle:desktop ${JSON.stringify({ schema: "gentle-shell.desktop-rpc/v1", requestId: "r", method, params: {} })}`; + for (const method of ["set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context"]) { + assert.equal(carriesHostToolRequest(prompt(method)), true, method); + assert.equal(desktopMethodScope(method), "sessions:operate", method); + } + assert.equal(carriesHostToolRequest(prompt("capabilities")), false); + assert.equal(carriesHostToolRequest("/gentle:desktop not json"), false, "the session refuses what it cannot parse anyway"); + assert.equal(carriesHostToolRequest("set_host_tools"), false); +}); + +test("host tools over HTTP: the provider is the calling device, only that device answers its calls, an offline device is answered for", async () => { + const phone = await pairDevice(["sessions:read", "sessions:operate"], "phone"); + const laptop = await pairDevice(["sessions:read", "sessions:operate"], "laptop"); + const reader = await pairDevice(["sessions:read"], "watcher"); + const id = await startSession(phone.token); + const desktop = (token: string, method: string, params: Record) => + call("POST", `/api/sessions/${id}/desktop`, { token, body: { schema: "gentle-shell.desktop-rpc/v1", requestId: "client-own", method, params } }); + + const registered = await desktop(phone.token, "set_host_tools", { provider: laptop.id, tools: [] }); + assert.equal(registered.status, 200); + assert.equal(registered.body.data.params.provider, phone.id, "the server overwrites the provider with the calling device"); + assert.equal((await desktop(reader.token, "set_host_tools", { provider: "x", tools: [] })).status, 403, "registering tools operates"); + const context = await desktop(phone.token, "set_host_context", { provider: laptop.id, content: "Simulators: iPhone 16" }); + assert.equal(context.status, 200); + assert.equal(context.body.data.params.provider, phone.id, "host context is always the calling device's"); + assert.equal((await desktop(reader.token, "set_host_context", { provider: "x", content: "" })).status, 403, "setting host context operates"); + const message = await desktop(phone.token, "host_message", { customType: "host.genui.event", content: "clicked", display: true, deliver: "auto", details: { pad: "d".repeat(200 * 1024) } }); + assert.equal(message.status, 200, "a host message's details may exceed the usual Desktop cap"); + assert.equal(message.body.data.params.customType, "host.genui.event"); + assert.equal((await desktop(reader.token, "host_message", { customType: "host.x", content: "", display: false, deliver: "auto" })).status, 403, "sending host messages operates"); + for (const method of ["set_host_tools", "host_tool_result", "host_tool_progress", "host_message", "set_host_context"]) { + const message = `/gentle:desktop ${JSON.stringify({ schema: "gentle-shell.desktop-rpc/v1", requestId: "r", method, params: { provider: laptop.id, tools: [] } })}`; + const refused = await call("POST", `/api/sessions/${id}/rpc`, { token: phone.token, body: { type: "prompt", message } }); + assert.equal(refused.status, 400, method); + assert.equal(refused.body.error.code, "use_desktop_endpoint"); + } + const other = await call("POST", `/api/sessions/${id}/rpc`, { token: phone.token, body: { type: "prompt", message: `/gentle:desktop ${JSON.stringify({ schema: "gentle-shell.desktop-rpc/v1", requestId: "r", method: "capabilities", params: {} })}` } }); + assert.equal(other.status, 200, "other Desktop requests still go through /rpc"); + + const phoneStream = await stream(`/api/sessions/${id}/events`, phone.token); + await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_host_call", callId: "call-1", provider: phone.id } }); + await phoneStream.waitFor('\\"callId\\":\\"call-1\\"'); + const stolen = await desktop(laptop.token, "host_tool_result", { callId: "call-1", content: [{ type: "text", text: "not mine" }] }); + assert.equal(stolen.status, 403); + assert.equal(stolen.body.error.code, "forbidden"); + const big = "x".repeat(1024 * 1024); + const stolenBeat = await desktop(laptop.token, "host_tool_progress", { callId: "call-1" }); + assert.equal(stolenBeat.status, 403, "only the provider keeps its call alive"); + assert.equal(stolenBeat.body.error.code, "forbidden"); + await desktop(laptop.token, "host_message", { customType: "host.x", content: "hi", display: false, deliver: "auto" }); + assert.equal((await call("GET", `/api/sessions/${id}`, { token: phone.token })).body.session.lastActiveDevice, laptop.id); + const beat = await desktop(phone.token, "host_tool_progress", { callId: "call-1", message: "waiting for review" }); + assert.equal(beat.status, 200); + assert.equal(beat.body.data.method, "host_tool_progress"); + assert.equal((await call("GET", `/api/sessions/${id}`, { token: phone.token })).body.session.lastActiveDevice, laptop.id, "a heartbeat is not activity"); + assert.equal((await desktop(phone.token, "host_tool_progress", { callId: "call-1", pad: "x".repeat(100 * 1024) })).status, 413, "a heartbeat keeps the usual Desktop cap"); + const answered = await desktop(phone.token, "host_tool_result", { callId: "call-1", content: [{ type: "text", text: big }] }); + assert.equal(answered.status, 200, "a host tool result may be far larger than other Desktop requests"); + assert.equal(answered.body.data.params.content[0].text.length, big.length); + assert.equal((await desktop(phone.token, "get_snapshot", { pad: "x".repeat(100 * 1024) })).status, 413, "every other method keeps its cap"); + + // The laptop registered nothing and has no stream: its call is answered for it at once, by name. + await call("POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_host_call", callId: "call-2", provider: laptop.id, tool: "laptop_clip" } }); + await phoneStream.waitFor("laptop_clip runs in laptop, which isn't connected right now."); + phoneStream.close(); + assert.equal((await call("DELETE", `/api/sessions/${id}`, { token: phone.token })).status, 200); +}); + +test("several devices may provide one host tool: the session learns which are connected, most recently active first", async () => { + const phone = await pairDevice(["sessions:read", "sessions:operate"], "phone"); + const laptop = await pairDevice(["sessions:read", "sessions:operate"], "laptop"); + const id = await startSession(phone.token); + const desktop = (token: string, method: string, params: Record) => + call("POST", `/api/sessions/${id}/desktop`, { token, body: { method, params } }); + // What the fake child echoes for a set_host_activity the server sent, as it appears inside the stream's widget record. + const activity = (providers: string[]) => JSON.stringify(JSON.stringify({ method: "set_host_activity", params: { providers } })).slice(1, -1); + const tools = [{ name: "device_screenshot", label: "Screenshot", description: "Takes a screenshot.", parameters: { type: "object" } }]; + + const phoneStream = await stream(`/api/sessions/${id}/events`, phone.token); + const laptopStream = await stream(`/api/sessions/${id}/events`, laptop.token); + assert.equal((await call("GET", `/api/sessions/${id}`, { token: phone.token })).body.session.lastActiveDevice, phone.id, "starting the session drove it"); + await desktop(phone.token, "set_host_tools", { tools }); + await laptopStream.waitFor(activity([phone.id])); + await desktop(laptop.token, "set_host_tools", { tools }); + await laptopStream.waitFor(activity([laptop.id, phone.id])); + assert.equal((await call("POST", `/api/sessions/${id}/rpc`, { token: phone.token, body: { type: "prompt", message: "take a screenshot" } })).status, 200); + await laptopStream.waitFor(activity([phone.id, laptop.id])); + const view = await call("GET", `/api/sessions/${id}`, { token: laptop.token }); + assert.equal(view.body.session.lastActiveDevice, phone.id, "the last device that drove the session"); + assert.equal((await call("POST", `/api/sessions/${id}/rpc`, { token: laptop.token, body: { type: "get_state" } })).status, 200); + assert.equal((await call("GET", `/api/sessions/${id}`, { token: laptop.token })).body.session.lastActiveDevice, phone.id, "a read is not activity"); + + phoneStream.close(); + await laptopStream.waitFor(activity([laptop.id])); + + const forged = await desktop(laptop.token, "set_host_activity", { providers: [laptop.id] }); + assert.equal(forged.status, 403, "only the server reports activity"); + const viaRpc = `/gentle:desktop ${JSON.stringify({ schema: "gentle-shell.desktop-rpc/v1", requestId: "r", method: "set_host_activity", params: { providers: [] } })}`; + assert.equal((await call("POST", `/api/sessions/${id}/rpc`, { token: laptop.token, body: { type: "prompt", message: viaRpc } })).body.error.code, "use_desktop_endpoint"); + laptopStream.close(); + assert.equal((await call("DELETE", `/api/sessions/${id}`, { token: phone.token })).status, 200); +}); + +test("no session keeper or fake Pi outlives the tests above", async () => { + await closeServer(); + assert.deepEqual(await remainingServeLeftovers([], roots), []); +}); diff --git a/tests/serve-services.test.ts b/tests/serve-services.test.ts new file mode 100644 index 000000000..61a58f480 --- /dev/null +++ b/tests/serve-services.test.ts @@ -0,0 +1,111 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { after, before, call, pairDevice, test } from "./serve-test-client.ts"; + +const ADMIN = "gsa_test-admin-token"; +let root: string; +let server: ServeServer; +let engram: Server; +let engramPort: number; + +function listen(s: Server): Promise { + const { promise, resolve } = Promise.withResolvers(); + s.listen(0, "127.0.0.1", () => resolve((s.address() as { port: number }).port)); + return promise; +} + +before(async () => { + root = mkdtempSync(join(tmpdir(), "gentle-serve-services-")); + // A stand-in for Engram: /health answers, every other path echoes. + engram = createServer((req, res) => { + res.writeHead(200, { "Content-Type": "text/plain" }); + res.end(req.url === "/health" ? "ok" : `engram ${req.url}`); + }); + engramPort = await listen(engram); + const auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth, + version: "test", + launchSession: () => { throw new Error("no sessions here"); }, + env: { ENGRAM_URL: `http://user:secret@127.0.0.1:${engramPort}/` }, + }); +}); +after(async () => { + await server?.close(); + engram?.close(); + engram?.closeAllConnections(); + rmSync(root, { recursive: true, force: true }); +}); + +test("GET /api/services lists Engram when it answers /health, without the URL's credentials", async () => { + const reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader"); + const listed = await call(server.url, "GET", "/api/services", { token: reader.token }); + assert.equal(listed.status, 200, JSON.stringify(listed.body)); + assert.deepEqual(listed.body.services, [{ id: "engram", name: "Engram", url: `http://127.0.0.1:${engramPort}`, port: engramPort, available: true, forwardable: true, via: "forwards" }]); + assert.equal((await call(server.url, "GET", "/api/services")).status, 401); + const caps = (await call(server.url, "GET", "/api/server", { token: reader.token })).body.capabilities; + assert.ok(caps.includes("server-forwards") && caps.includes("services")); +}); + +test("an Engram that does not answer is listed as unavailable; a remote one is not forwardable", async () => { + for (const [url, forwardable] of [["http://127.0.0.1:1", true], ["http://192.0.2.1:7437", false]] as const) { + const auth = new ServeAuth({ devicesFile: join(root, `other-${forwardable}`, "devices.json"), adminToken: ADMIN }); + const other = await startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", launchSession: () => { throw new Error("none"); }, env: { ENGRAM_URL: url } }); + try { + const [entry] = (await call(other.url, "GET", "/api/services", { token: ADMIN })).body.services; + assert.equal(entry.available, false); + assert.equal(entry.forwardable, forwardable); + } finally { + await other.close(); + } + } +}); + +test("server-level forwards: open, reuse, list, reach, close; per device; closed on revoke", async () => { + const phone = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"], "phone"); + const laptop = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"], "laptop"); + const reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader2"); + assert.equal((await call(server.url, "POST", "/api/forwards", { token: reader.token, body: { port: engramPort } })).status, 403); + assert.equal((await call(server.url, "POST", "/api/forwards", { token: phone.token, body: { port: server.port } })).body.error.code, "invalid_port"); + assert.equal((await call(server.url, "POST", "/api/forwards", { token: phone.token, body: { port: engramPort, path: "//evil" } })).body.error.code, "invalid_path"); + + const opened = await call(server.url, "POST", "/api/forwards", { token: phone.token, body: { port: engramPort, path: "/ui" } }); + assert.equal(opened.status, 201, JSON.stringify(opened.body)); + assert.equal(opened.body.sessionId, null); + assert.equal(opened.body.kind, "server"); + assert.equal(opened.body.port, engramPort); + assert.match(opened.body.url, new RegExp(`^http://127\\.0\\.0\\.1:${opened.body.listenPort}/ui\\?gs_ticket=`)); + const again = await call(server.url, "POST", "/api/forwards", { token: phone.token, body: { port: engramPort } }); + assert.equal(again.status, 200); + assert.equal(again.body.id, opened.body.id); + + // The link works like a session forward's: ticket, redirect with a cookie, then the page. + const first = await call(opened.body.url, "GET", ""); + assert.equal(first.status, 303); + const cookie = String(first.headers["set-cookie"]).split(";")[0]; + const page = await call(`http://127.0.0.1:${opened.body.listenPort}`, "GET", "/ui", { headers: { Cookie: cookie } }); + assert.equal(page.status, 200); + assert.equal(page.body, "engram /ui"); + + const listed = await call(server.url, "GET", "/api/forwards", { token: phone.token }); + assert.deepEqual(listed.body.forwards.map((f: { id: string }) => f.id), [opened.body.id]); + assert.deepEqual((await call(server.url, "GET", "/api/forwards", { token: laptop.token })).body.forwards, []); + assert.equal((await call(server.url, "GET", "/api/forwards", { token: ADMIN })).body.forwards.length, 1, "an admin sees every device's"); + assert.equal((await call(server.url, "DELETE", `/api/forwards/${opened.body.id}`, { token: laptop.token })).status, 404, "only the owner closes it"); + + const laptopForward = await call(server.url, "POST", "/api/forwards", { token: laptop.token, body: { port: engramPort } }); + assert.notEqual(laptopForward.body.id, opened.body.id, "another device gets its own"); + assert.equal((await call(server.url, "DELETE", `/api/forwards/${opened.body.id}`, { token: phone.token })).body.closed, opened.body.id); + assert.deepEqual((await call(server.url, "GET", "/api/forwards", { token: phone.token })).body.forwards, []); + + assert.equal((await call(server.url, "DELETE", `/api/devices/${laptop.id}`, { token: ADMIN })).status, 200); + assert.deepEqual((await call(server.url, "GET", "/api/forwards", { token: ADMIN })).body.forwards, [], "revoking the device closed its forward"); + assert.equal((await call(server.url, "PUT", "/api/forwards", { token: phone.token })).status, 405); +}); diff --git a/tests/serve-session-keeper.test.ts b/tests/serve-session-keeper.test.ts new file mode 100644 index 000000000..4a0ccd32b --- /dev/null +++ b/tests/serve-session-keeper.test.ts @@ -0,0 +1,266 @@ +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { startServeServer, type ServeServer, type ServeServerOptions } from "../lib/serve-server.ts"; +import { KeeperLink, SERVE_SESSION_LIMITS } from "../lib/serve-session.ts"; +import { keeperAlive, keeperEndpoint, type KeeperRecord } from "../lib/serve-session-keeper.ts"; +import { after, call, endServeLeftovers, pairDevice, remainingServeLeftovers, stream, test, type Stream } from "./serve-test-client.ts"; + +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); +const ADMIN = "gsa_test-admin-token"; +const roots: string[] = []; +const sessionDirs = () => roots.map((root) => join(root, "serve", "sessions")); +after(async () => { + // A failed test must not leave keepers (and their fake Pi) behind. + await endServeLeftovers(sessionDirs(), roots); + roots.forEach((root) => rmSync(root, { recursive: true, force: true })); +}); + +function home(): { serveDir: string; project: string } { + const root = mkdtempSync(join(tmpdir(), "gs-keep-")); + roots.push(root); + return { serveDir: join(root, "serve"), project: realpathSync(mkdtempSync(join(root, "p-"))) }; +} + +function serve(serveDir: string, extra: Partial = {}): Promise { + return startServeServer({ + host: "127.0.0.1", + port: 0, + auth: new ServeAuth({ devicesFile: join(serveDir, "devices.json"), adminToken: ADMIN }), + version: "test", + serveDir, + launchSession: (input) => ({ command: process.execPath, args: [FAKE_PI], cwd: input.cwd, env: { ...process.env, GENTLE_SHELL_INTERACTIVE_HOST: "1" } }), + limits: { rpcTimeoutMs: 3000 }, + ...extra, + }); +} + +function record(serveDir: string, id: string): KeeperRecord { + return JSON.parse(readFileSync(join(serveDir, "sessions", `${id}.json`), "utf8")) as KeeperRecord; +} + +async function startSession(server: ServeServer, serveDir: string, project: string, token = ADMIN): Promise { + const created = await call(server.url, "POST", "/api/sessions", { token, body: { cwd: project } }); + assert.equal(created.status, 201, JSON.stringify(created.body)); + return created.body.session.id; +} + +// Polls a condition another process makes true; there is no event to await for it. +async function until(check: () => boolean, what: string, timeoutMs = 8000): Promise { + const deadline = Date.now() + timeoutMs; + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((r) => setTimeout(r, 20)); + } +} + +/** The `id:`/`data:` records of an SSE text, in order. */ +function records(text: string): Array<{ seq: number; record: Record }> { + const out: Array<{ seq: number; record: Record }> = []; + for (const block of text.split("\n\n")) { + const id = /^id: (\d+)$/m.exec(block); + const data = /^data: (.*)$/m.exec(block); + if (id && data) out.push({ seq: Number(id[1]), record: JSON.parse(data[1]) }); + } + return out; +} + +test("a session survives a server restart mid-stream: same id, seq continues, nothing lost within the ring", { timeout: 30_000 }, async () => { + const { serveDir, project } = home(); + const first = await serve(serveDir); + const id = await startSession(first, serveDir, project); + const before = await stream(first.url, `/api/sessions/${id}/events?after=0`, ADMIN); + assert.equal((await call(first.url, "POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_trickle", count: 40, everyMs: 15 } })).status, 200); + await before.waitFor('"tick":5'); + await first.close(); + await before.closed; + const seen = records(before.text); + const last = seen.at(-1)!.seq; + assert.ok(seen.every((r, i) => r.seq === i + 1), "the first server delivered every record in order"); + + // Pi keeps going while no server runs; its keeper holds the records. + const keeper = record(serveDir, id); + assert.equal(keeper.state, "running"); + assert.ok(keeperAlive(keeper.keeperPid)); + if (process.platform !== "win32") { + assert.equal(statSync(join(serveDir, "sessions")).mode & 0o777, 0o700); + assert.equal(statSync(join(serveDir, "sessions", `${id}.json`)).mode & 0o777, 0o600); + assert.equal(statSync(keeperEndpoint(join(serveDir, "sessions"), id)).mode & 0o777, 0o600); + } + + const second = await serve(serveDir); + try { + const listed = await call(second.url, "GET", "/api/sessions", { token: ADMIN }); + const session = listed.body.sessions.find((s: { id: string }) => s.id === id); + assert.equal(session.state, "running", "the same id, still running"); + assert.ok(session.seq >= last); + const info = await call(second.url, "GET", "/api/server", { token: ADMIN }); + assert.ok(info.body.capabilities.includes("persistent-sessions")); + + const resumed = await stream(second.url, `/api/sessions/${id}/events?after=${last}`, ADMIN); + await resumed.waitFor('"tick":39'); + const rest = records(resumed.text); + assert.ok(!resumed.text.includes("snapshot-required")); + assert.deepEqual(rest.map((r) => r.seq), rest.map((_, i) => last + 1 + i), "seq continues where the client left off, without a gap"); + const ticks = [...seen, ...rest].map((r) => r.record.tick).filter((tick) => tick !== undefined); + assert.deepEqual(ticks, Array.from({ length: 40 }, (_, i) => i), "every record reached the client exactly once"); + + // The session still takes commands, under the seq the keeper keeps. + const state = await call(second.url, "POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "get_state", id: "mine" } }); + assert.equal(state.status, 200); + assert.equal(state.body.id, "mine"); + await resumed.waitFor('"command":"get_state"'); + resumed.close(); + } finally { + await second.close({ endSessions: true }); + } + await until(() => !keeperAlive(keeper.keeperPid), "the keeper to end with its session"); + assert.equal(record(serveDir, id).state, "exited", "the record stays for the listing"); +}); + +test("a pending dialog, an open host tool call and the last active device survive a restart", { timeout: 30_000 }, async () => { + const { serveDir, project } = home(); + const limits = { sessionLimits: { hostToolReattachGraceMs: 400 } }; + const first = await serve(serveDir, limits); + const phone = await pairDevice(first.url, ADMIN, ["sessions:read", "sessions:operate"], "phone"); + const id = await startSession(first, serveDir, project, phone.token); + const phoneStream = await stream(first.url, `/api/sessions/${id}/events`, phone.token); + const tools = await call(first.url, "POST", `/api/sessions/${id}/desktop`, { token: phone.token, body: { method: "set_host_tools", params: { tools: [{ name: "phone_camera" }] } } }); + assert.equal(tools.status, 200, JSON.stringify(tools.body)); + assert.equal((await call(first.url, "POST", `/api/sessions/${id}/rpc`, { token: phone.token, body: { type: "fake_dialog" } })).status, 200); + assert.equal((await call(first.url, "POST", `/api/sessions/${id}/rpc`, { token: phone.token, body: { type: "fake_host_call", callId: "c1", provider: phone.id } })).status, 200); + await phoneStream.waitFor('\\"callId\\":\\"c1\\"'); + await first.close(); + + const second = await serve(serveDir, limits); + let back: Stream | undefined; + try { + const view = (await call(second.url, "GET", `/api/sessions/${id}`, { token: ADMIN })).body.session; + assert.equal(view.pendingDialogs, 1); + assert.equal(view.lastActiveDevice, phone.id, "the last active device is kept with the keeper"); + // The phone comes back within the grace: a fresh stream gets the dialog and its call again. + back = await stream(second.url, `/api/sessions/${id}/events`, phone.token); + await back.waitFor("event: dialog"); + await back.waitFor("event: host_tool_call"); + const answered = await call(second.url, "POST", `/api/sessions/${id}/rpc`, { token: phone.token, body: { type: "extension_ui_response", id: "dlg-1", value: "a" } }); + assert.equal(answered.status, 202, JSON.stringify(answered.body)); + await back.waitFor('"type":"fake_dialog_answer"'); + await back.waitFor('"type":"serve_dialog_resolved"'); + const again = await call(second.url, "POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "extension_ui_response", id: "dlg-1", value: "b" } }); + assert.equal(again.status, 409); + const result = await call(second.url, "POST", `/api/sessions/${id}/desktop`, { token: phone.token, body: { method: "host_tool_result", params: { callId: "c1", content: [{ type: "text", text: "ok" }] } } }); + assert.equal(result.status, 200); + + // A call the phone owes when no phone comes back is answered for it once the grace ends. + assert.equal((await call(second.url, "POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_host_call", callId: "c2", provider: phone.id } })).status, 200); + await back.waitFor('\\"callId\\":\\"c2\\"'); + back.close(); + } finally { + await second.close(); + } + const third = await serve(serveDir, limits); + try { + const watcher = await stream(third.url, `/api/sessions/${id}/events`, ADMIN); + await watcher.waitFor("phone_camera runs in phone, which isn't connected right now."); + watcher.close(); + } finally { + await third.close({ endSessions: true }); + } +}); + +test("keeper cleanup: a deleted session, a session that ended while no server ran, an orphan and a lost keeper", { timeout: 30_000 }, async () => { + const { serveDir, project } = home(); + const sessionsDir = join(serveDir, "sessions"); + const options = { keeperLimits: { lingerMs: 150, orphanMs: 600 } }; + let server = await serve(serveDir, options); + + // DELETE stops Pi and its keeper and forgets the session. + const deleted = await startSession(server, serveDir, project); + const deletedPid = record(serveDir, deleted).keeperPid; + assert.equal((await call(server.url, "DELETE", `/api/sessions/${deleted}`, { token: ADMIN })).status, 200); + await until(() => !keeperAlive(deletedPid), "the deleted session's keeper to end"); + assert.ok(!existsSync(join(sessionsDir, `${deleted}.json`))); + if (process.platform !== "win32") assert.ok(!existsSync(keeperEndpoint(sessionsDir, deleted))); + + // Pi exits while no server runs: the keeper records it and ends; the next server lists it. + const ended = await startSession(server, serveDir, project); + assert.equal((await call(server.url, "POST", `/api/sessions/${ended}/rpc`, { token: ADMIN, body: { type: "fake_exit", code: 4, afterMs: 300 } })).status, 200); + // No server comes back to the other one for longer than the orphan limit: it stops its session. + const orphan = await startSession(server, serveDir, project); + // The keeper of a third one is killed: the server sees the session lost. + const lost = await startSession(server, serveDir, project); + const lostStream = await stream(server.url, `/api/sessions/${lost}/events`, ADMIN); + process.kill(record(serveDir, lost).keeperPid, "SIGKILL"); + await lostStream.closed; + assert.ok(lostStream.text.includes('"error":"keeper_lost"')); + assert.equal((await call(server.url, "GET", `/api/sessions/${lost}`, { token: ADMIN })).body.session.state, "exited"); + await server.close(); + + const endedPid = record(serveDir, ended).keeperPid; + const orphanPid = record(serveDir, orphan).keeperPid; + await until(() => !keeperAlive(endedPid), "the ended session's keeper to finish"); + assert.equal(record(serveDir, ended).state, "exited"); + assert.equal(record(serveDir, ended).exitCode, 4); + await until(() => !keeperAlive(orphanPid), "the orphan keeper to stop its session"); + assert.equal(record(serveDir, orphan).state, "exited"); + + server = await serve(serveDir, options); + try { + const listed = (await call(server.url, "GET", "/api/sessions", { token: ADMIN })).body.sessions as Array<{ id: string; state: string; exitCode: number | null }>; + const byId = new Map(listed.map((s) => [s.id, s])); + assert.equal(byId.get(ended)?.state, "exited"); + assert.equal(byId.get(ended)?.exitCode, 4); + assert.equal(byId.get(orphan)?.state, "exited"); + assert.equal(byId.get(lost)?.state, "exited"); + assert.equal(record(serveDir, lost).error, "keeper_lost", "a keeper that died is recorded as lost"); + assert.equal(byId.has(deleted), false); + // An ended session has no ring left: a client's cursor gets snapshot-required. + const late = await stream(server.url, `/api/sessions/${ended}/events?after=1`, ADMIN); + await late.closed; + assert.ok(late.text.includes("event: snapshot-required")); + } finally { + await server.close(); + } +}); + +test("a server collects the end of a session that exited moments before it started", { timeout: 30_000 }, async () => { + const { serveDir, project } = home(); + const first = await serve(serveDir); + const id = await startSession(first, serveDir, project); + assert.equal((await call(first.url, "POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "fake_exit", code: 2, afterMs: 200 } })).status, 200); + await first.close(); + await until(() => record(serveDir, id).state === "exited", "the session to exit"); + const keeperPid = record(serveDir, id).keeperPid; + assert.ok(keeperAlive(keeperPid), "its keeper waits for a server"); + + const second = await serve(serveDir); + try { + const replay = await stream(second.url, `/api/sessions/${id}/events?after=0`, ADMIN); + await replay.closed; + const last = records(replay.text).at(-1)!.record; + assert.deepEqual(last, { type: "serve_session_exited", code: 2, signal: null }, "the exit record reached the new server"); + await until(() => !keeperAlive(keeperPid), "the keeper to end once collected"); + } finally { + await second.close(); + } +}); + +test("a keeper answers only a server holding its token", { timeout: 30_000 }, async () => { + const { serveDir, project } = home(); + const server = await serve(serveDir); + try { + const id = await startSession(server, serveDir, project); + await assert.rejects(KeeperLink.connect(keeperEndpoint(join(serveDir, "sessions"), id), "not-the-token", { timeoutMs: 3000, maxLineBytes: SERVE_SESSION_LIMITS.maxLineBytes }), /keeper/); + // The real server stays attached. + assert.equal((await call(server.url, "POST", `/api/sessions/${id}/rpc`, { token: ADMIN, body: { type: "get_state" } })).status, 200); + } finally { + await server.close({ endSessions: true }); + } +}); + +test("no session keeper or fake Pi outlives the tests above", async () => { + assert.deepEqual(await remainingServeLeftovers(sessionDirs(), roots), []); +}); diff --git a/tests/serve-session.test.ts b/tests/serve-session.test.ts new file mode 100644 index 000000000..5a4145f17 --- /dev/null +++ b/tests/serve-session.test.ts @@ -0,0 +1,396 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { DESKTOP_RPC_WIDGET, JsonlDecoder, KeeperLink, ReplayRing, SERVE_SESSION_LIMITS, ServeSession, SessionLog, type ServeSessionLimits, type SessionLaunch, type StreamSink } from "../lib/serve-session.ts"; +import { keeperEndpoint, SessionKeeper } from "../lib/serve-session-keeper.ts"; +import { after, endServeLeftovers, remainingServeLeftovers, test } from "./serve-test-client.ts"; + +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); +const roots: string[] = []; +after(async () => { + // A failed test must not leave a fake Pi (started by a keeper running in this process) behind. + await endServeLeftovers([], []); + roots.forEach((root) => rmSync(root, { recursive: true, force: true })); +}); + +/** An SSE sink that records what it was sent; `backlog` simulates unsent bytes. */ +class FakeSink implements StreamSink { + chunks: string[] = []; + ended = false; + destroyed = false; + backlog = 0; + get writableLength(): number { return this.backlog; } + get text(): string { return this.chunks.join(""); } + write(chunk: string): boolean { this.chunks.push(chunk); return true; } + end(chunk?: string): void { if (chunk) this.chunks.push(chunk); this.ended = true; } + destroy(): void { this.destroyed = true; } +} + +interface Frame { event?: string; id?: string; data?: string } + +function frames(text: string): Frame[] { + return text.split("\n\n").filter((block) => block.trim() && !block.startsWith(":") && !block.startsWith("retry:")).map((block) => { + const frame: Frame = {}; + for (const line of block.split("\n")) { + const colon = line.indexOf(": "); + const key = line.slice(0, colon), value = line.slice(colon + 2); + if (key === "event" || key === "id" || key === "data") frame[key] = value; + } + return frame; + }); +} + +interface FakeOptions { + now?: () => number; + launch?: SessionLaunch; + deviceLabel?: (id: string) => string | undefined; +} + +/** A session as the server holds it, over a keeper running in this process (so both share the test's clock). */ +async function startFake(limits: Partial = {}, options: FakeOptions = {}): Promise { + const dir = mkdtempSync(join(tmpdir(), "gs-session-")); + roots.push(dir); + const keeper = new SessionKeeper({ + id: "ses_test", + dir, + token: "test-token", + launch: options.launch ?? { command: process.execPath, args: [FAKE_PI], cwd: process.cwd(), env: process.env }, + limits, + }, options.now ? { now: options.now } : {}); + await keeper.start(); + const { link, snapshot, ring } = await KeeperLink.connect(keeperEndpoint(dir, "ses_test"), "test-token", { timeoutMs: 5000, maxLineBytes: SERVE_SESSION_LIMITS.maxLineBytes }); + return new ServeSession({ snapshot, ring, link, limits, ...(options.now ? { now: options.now } : {}), ...(options.deviceLabel ? { deviceLabel: options.deviceLabel } : {}) }); +} + +// Polls a condition a real child process makes true; there is no event to await for it. +async function until(check: () => boolean, what: string, timeoutMs = 5000): Promise { + const deadline = Date.now() + timeoutMs; + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((r) => setTimeout(r, 10)); + } +} + +test("JsonlDecoder splits only on LF, strips CR, keeps U+2028/U+2029 and joins chunks", () => { + const lines: string[] = []; + let oversize = 0; + const decoder = new JsonlDecoder((line) => lines.push(line), () => { oversize += 1; }, 64); + decoder.push(Buffer.from('{"a":"x\u2028y\u2029z"}\r\n{"b":')); + decoder.push(Buffer.from('1}\n\n{"c":2}')); + assert.deepEqual(lines, ['{"a":"x\u2028y\u2029z"}', '{"b":1}']); + decoder.end(); + assert.deepEqual(lines.at(-1), '{"c":2}'); + // A multi-byte character split across chunks still decodes whole. + const euro = Buffer.from('{"e":"€"}\n'); + decoder.push(euro.subarray(0, 8)); + decoder.push(euro.subarray(8)); + assert.equal(lines.at(-1), '{"e":"€"}'); + assert.equal(oversize, 0); +}); + +test("JsonlDecoder drops an oversize record whole and resumes at the next LF", () => { + const lines: string[] = []; + let oversize = 0; + const decoder = new JsonlDecoder((line) => lines.push(line), () => { oversize += 1; }, 16); + decoder.push(Buffer.from(`${"x".repeat(10)}`)); + decoder.push(Buffer.from(`${"y".repeat(10)}\n{"ok":1}\n`)); + assert.equal(oversize, 1); + assert.deepEqual(lines, ['{"ok":1}']); +}); + +test("ReplayRing evicts by count and bytes and answers snapshot-required outside its window", () => { + const ring = new ReplayRing(3, 1000); + for (let seq = 1; seq <= 5; seq += 1) ring.push({ seq, line: `r${seq}`, bytes: 10 }); + assert.equal(ring.length, 3); + assert.equal(ring.oldest, 3); + assert.deepEqual(ring.since(2, 5), { records: [3, 4, 5].map((seq) => ({ seq, line: `r${seq}`, bytes: 10 })) }); + assert.deepEqual(ring.since(4, 5), { records: [{ seq: 5, line: "r5", bytes: 10 }] }); + assert.deepEqual(ring.since(5, 5), { records: [] }); + assert.deepEqual(ring.since(1, 5), { snapshotRequired: true, oldest: 3 }); + assert.deepEqual(ring.since(9, 5), { snapshotRequired: true, oldest: 3 }, "a cursor from another lifetime"); + assert.deepEqual(ring.since(-1, 5), { snapshotRequired: true, oldest: 3 }); + + const bytes = new ReplayRing(100, 25); + for (let seq = 1; seq <= 4; seq += 1) bytes.push({ seq, line: "x", bytes: 10 }); + assert.equal(bytes.oldest, 3, "byte budget keeps the newest that fit"); + const huge = new ReplayRing(100, 5); + huge.push({ seq: 1, line: "big", bytes: 50 }); + assert.equal(huge.length, 1, "the newest record is always kept"); + const empty = new ReplayRing(10, 100); + assert.deepEqual(empty.since(0, 0), { records: [] }); +}); + +test("SessionLog: host_tool_progress keeps a call tracked past the tracking window; without it the call is forgotten", () => { + let clock = 0; + const log = new SessionLog({ ringRecords: 100, ringBytes: 1024 * 1024, hostToolTrackMs: 11 * 60 * 1000 }, () => clock); + let seq = 0; + const call = (callId: string) => { + const line = JSON.stringify({ kind: "event", event: "host_tool_call", data: { callId, provider: "phone", tool: "gentle_ui", args: {} } }); + const record = { type: "extension_ui_request", id: `w${seq}`, method: "setWidget", widgetKey: DESKTOP_RPC_WIDGET, widgetLines: [line] }; + seq += 1; + log.push(seq, JSON.stringify(record), record); + }; + call("kept"); + call("dropped"); + for (let beat = 0; beat < 3; beat += 1) { + clock += 9 * 60 * 1000; + log.progress("kept"); + } + clock += 60_000; + call("next"); + assert.equal(log.hostCall("kept")?.provider, "phone", "heartbeats keep the call's owner known"); + assert.equal(log.hostCall("dropped"), undefined, "a call without heartbeats is pruned after the window"); + log.progress("dropped"); + assert.equal(log.hostCall("dropped"), undefined, "progress never revives a forgotten call"); +}); + +test("a session numbers every record, restores the caller's id and survives framing edge cases", async (t) => { + const session = await startFake(); + t.after(() => session.stop()); + const outcome = await session.rpc({ type: "get_state", id: "mine" }, 5000); + assert.ok("response" in outcome); + assert.equal(outcome.response.id, "mine"); + assert.equal(outcome.response.command, "get_state"); + assert.equal(session.seq, 1); + + const noId = await session.rpc({ type: "get_state" }, 5000); + assert.ok("response" in noId && !("id" in noId.response), "no id in, no id out"); + + await session.rpc({ type: "fake_unicode" }, 5000); + await session.rpc({ type: "fake_split" }, 5000); + assert.equal(session.invalidRecords, 1, "a non-JSON stdout line is not forwarded"); + + const sink = new FakeSink(); + session.subscribe(sink, "dev", 0); + const replay = frames(sink.text); + assert.equal(replay[0].event, "hello"); + const records = replay.filter((f) => f.id !== undefined); + assert.deepEqual(records.map((f) => Number(f.id)), [1, 2, 3, 4, 5, 6]); + assert.ok(records.some((f) => JSON.parse(f.data!).text === "a\u2028b\u2029c")); + assert.ok(records.some((f) => JSON.parse(f.data!).split === true)); + assert.ok(records.every((f) => !JSON.parse(f.data!).id?.startsWith?.("x"))); +}); + +test("rpc times out without losing the late response, and Desktop RPC is matched by requestId", async (t) => { + const session = await startFake(); + t.after(() => session.stop()); + const silent = await session.rpc({ type: "fake_silent" }, 50); + assert.ok("timeout" in silent); + const answer = await session.desktop("capabilities", { a: 1 }, 5000); + assert.ok(answer && "answer" in answer); + assert.equal(answer.answer.kind, "response"); + assert.deepEqual(answer.answer.data, { method: "capabilities", params: { a: 1 } }); + const refused = await session.desktop("refuse", {}, 5000); + assert.ok(refused && "prompt" in refused && refused.prompt.success === false); + assert.equal(await session.desktop("never", {}, 100), undefined); +}); + +test("pending dialogs replay to a late subscriber and only the first answer reaches the child", async (t) => { + const session = await startFake(); + t.after(() => session.stop()); + await session.rpc({ type: "fake_dialog" }, 5000); + await until(() => session.pendingDialogs().length === 1, "dialog"); + + const late = new FakeSink(); + session.subscribe(late, "dev"); // live only: no replay, but the open dialog + const dialog = frames(late.text).find((f) => f.event === "dialog"); + assert.ok(dialog, late.text); + assert.equal(JSON.parse(dialog.data!).id, "dlg-1"); + + const caughtUp = new FakeSink(); + session.subscribe(caughtUp, "dev", 0); // the replay already carries it: no duplicate + assert.equal(frames(caughtUp.text).filter((f) => f.event === "dialog").length, 0); + + assert.equal(await session.answerDialog({ type: "extension_ui_response", id: "dlg-1", value: "a" }), "accepted"); + assert.equal(await session.answerDialog({ type: "extension_ui_response", id: "dlg-1", value: "b" }), "answered"); + assert.equal(await session.answerDialog({ type: "extension_ui_response", id: "nope", value: "b" }), "unknown"); + await until(() => late.text.includes("fake_dialog_answer"), "answer echo"); + const echoes = frames(late.text).map((f) => f.data && JSON.parse(f.data)).filter((r) => r?.type === "fake_dialog_answer"); + assert.deepEqual(echoes.map((r) => r.value), ["a"], "the second answer never reached the child"); + assert.ok(late.text.includes('"serve_dialog_resolved"')); + assert.equal(session.pendingDialogs().length, 0); +}); + +test("a dialog with a timeout stops being pending once it expires", async (t) => { + let clock = 1_000; + const session = await startFake({}, { now: () => clock }); + t.after(() => session.stop()); + await session.rpc({ type: "fake_dialog", timeout: 500 }, 5000); + await until(() => session.pendingDialogs().length === 1, "dialog"); + clock += 501; + assert.equal(session.pendingDialogs().length, 0); + assert.equal(await session.answerDialog({ type: "extension_ui_response", id: "dlg-1", value: "a" }), "unknown"); +}); + +test("a cursor older than the ring gets snapshot-required, then the live stream", async (t) => { + const session = await startFake({ ringRecords: 5 }); + t.after(() => session.stop()); + await session.rpc({ type: "fake_burst", count: 10 }, 5000); + assert.equal(session.seq, 11); + const sink = new FakeSink(); + session.subscribe(sink, "dev", 2); + const got = frames(sink.text); + assert.equal(got[1].event, "snapshot-required"); + assert.deepEqual(JSON.parse(got[1].data!), { after: 2, oldest: 7, seq: 11 }); + assert.equal(got.filter((f) => f.id).length, 0); + await session.rpc({ type: "get_state" }, 5000); + assert.ok(frames(sink.text).some((f) => f.id === "12"), "live records follow"); + + const inWindow = new FakeSink(); + session.subscribe(inWindow, "dev", 9); + assert.deepEqual(frames(inWindow.text).filter((f) => f.id).map((f) => f.id), ["10", "11", "12"]); +}); + +test("a slow subscriber is dropped with a resync marker and never stalls the others", async (t) => { + const session = await startFake({ clientBufferBytes: 1024, dropFlushMs: 20 }); + t.after(() => session.stop()); + const slow = new FakeSink(); + const fast = new FakeSink(); + session.subscribe(slow, "dev"); + session.subscribe(fast, "dev"); + slow.backlog = 4096; // the client stopped reading + await session.rpc({ type: "fake_burst", count: 50, size: 200 }, 5000); + assert.equal(session.subscriberCount, 1); + assert.ok(slow.ended); + const marker = frames(slow.text).find((f) => f.event === "resync"); + assert.ok(marker); + assert.equal(JSON.parse(marker.data!).reason, "slow_client"); + await until(() => slow.destroyed, "forced close after the flush window"); + assert.equal(frames(fast.text).filter((f) => f.id).length, 51, "the reading client got everything"); +}); + +test("revoking a device closes only its streams; the child's own exit is a record and ends every stream", async () => { + const session = await startFake(); + const a = new FakeSink(), b = new FakeSink(); + session.subscribe(a, "dev_a"); + session.subscribe(b, "dev_b"); + session.dropDevice("dev_a"); + assert.ok(a.destroyed); + assert.equal(session.subscriberCount, 1); + // The child exits without answering: the waiting command fails instead of hanging. + await assert.rejects(session.rpc({ type: "fake_exit", code: 3 }, 5000), /exited/); + await session.whenExited(); + assert.equal(session.state, "exited"); + assert.equal(session.exitCode, 3); + assert.ok(b.ended); + const last = frames(b.text).filter((f) => f.data).map((f) => JSON.parse(f.data!)).at(-1); + assert.deepEqual(last, { type: "serve_session_exited", code: 3, signal: null }); + await assert.rejects(session.rpc({ type: "get_state" }, 1000), /exited/); + const after = new FakeSink(); + session.subscribe(after, "dev_a", 0); + assert.ok(after.ended, "an exited session replays and ends the stream"); + assert.ok(after.text.includes("serve_session_exited")); +}); + +test("stop closes stdin and terminates the child", async () => { + const session = await startFake(); + await session.rpc({ type: "get_state" }, 5000); + await session.stop(); + assert.equal(session.state, "exited"); + await session.stop(); // idempotent +}); + +test("a command that cannot spawn exits the session instead of throwing", async () => { + const session = await startFake({}, { launch: { command: "/nonexistent/serve-test-binary", args: [], cwd: process.cwd(), env: process.env } }); + await session.whenExited(); + assert.equal(session.state, "exited"); + const sink = new FakeSink(); + session.subscribe(sink, "dev", 0); + assert.ok(sink.text.includes('"error":"spawn_failed"')); +}); + +// ---- host tools --------------------------------------------------------------- + +function startHostFake(limits: Partial = {}): Promise { + return startFake(limits, { deviceLabel: (id) => (id === "dev_phone" ? "Ismael's phone" : undefined) }); +} + +/** The host_tool_result the server sent for `callId` on a device's behalf, as the fake child echoed it. */ +function serverAnswer(sink: FakeSink, callId: string): { callId: string; content: Array<{ type: string; text: string }>; isError: boolean } | undefined { + for (const frame of frames(sink.text)) { + if (!frame.data) continue; + const record = JSON.parse(frame.data); + if (record.method !== "setWidget") continue; + const line = JSON.parse(record.widgetLines[0]); + if (line.kind === "response" && line.data?.method === "host_tool_result" && line.data.params.callId === callId) return line.data.params; + } + return undefined; +} + +test("a host tool call for a device with no open stream is answered at once with a not-connected error", async (t) => { + const session = await startHostFake(); + t.after(() => session.stop()); + const watcher = new FakeSink(); + session.subscribe(watcher, "local"); + await session.rpc({ type: "fake_host_call", callId: "c1", provider: "dev_phone", tool: "phone_camera" }, 5000); + await until(() => serverAnswer(watcher, "c1") !== undefined, "the server's answer"); + assert.deepEqual(serverAnswer(watcher, "c1"), { callId: "c1", content: [{ type: "text", text: "phone_camera runs in Ismael's phone, which isn't connected right now." }], isError: true }); + assert.deepEqual(session.pendingHostCalls(), []); + await session.rpc({ type: "fake_host_call", callId: "c2", provider: "dev_unknown", tool: "x_tool" }, 5000); + await until(() => serverAnswer(watcher, "c2") !== undefined, "the answer for an unnamed device"); + assert.equal(serverAnswer(watcher, "c2")!.content[0].text, "x_tool runs in dev_unknown, which isn't connected right now."); +}); + +test("a connected device's call waits; a reconnect within the grace gets it again; the last stream gone past the grace fails it", async (t) => { + const session = await startHostFake({ hostToolGraceMs: 80 }); + t.after(() => session.stop()); + const watcher = new FakeSink(); + session.subscribe(watcher, "local"); + const phone = new FakeSink(); + session.subscribe(phone, "dev_phone"); + await session.rpc({ type: "fake_host_call", callId: "c1", provider: "dev_phone" }, 5000); + await until(() => session.pendingHostCalls().length === 1, "the call is tracked"); + assert.ok(phone.text.includes('\\"callId\\":\\"c1\\"'), "the device sees the call live"); + assert.equal(session.hostCallProvider("c1"), "dev_phone"); + + session.unsubscribe(phone); + const back = new FakeSink(); + session.subscribe(back, "dev_phone"); // a fresh stream without a cursor: the waiting call is re-sent + const resent = frames(back.text).filter((f) => f.event === "host_tool_call"); + assert.equal(resent.length, 1); + assert.equal(JSON.parse(JSON.parse(resent[0].data!).widgetLines[0]).data.callId, "c1"); + const caughtUp = new FakeSink(); + session.subscribe(caughtUp, "dev_phone", 0); // the replay carries it: no duplicate + assert.equal(frames(caughtUp.text).filter((f) => f.event === "host_tool_call").length, 0); + const other = new FakeSink(); + session.subscribe(other, "dev_other"); + assert.equal(frames(other.text).filter((f) => f.event === "host_tool_call").length, 0, "only the provider's device gets the re-send"); + // The reconnect cancelled the grace timer; give it time to have fired if it had not. + await new Promise((r) => setTimeout(r, 160)); + assert.equal(serverAnswer(watcher, "c1"), undefined, "a device back within the grace keeps its call"); + + session.unsubscribe(back); + session.unsubscribe(caughtUp); + assert.equal(serverAnswer(watcher, "c1"), undefined, "nothing fails before the grace ends"); + await until(() => serverAnswer(watcher, "c1") !== undefined, "the call fails after the grace"); + assert.equal(serverAnswer(watcher, "c1")!.content[0].text, "phone_camera runs in Ismael's phone, which isn't connected right now."); + assert.deepEqual(session.pendingHostCalls(), []); +}); + +test("a cancel or a settled result forgets a call; revoking the device fails its calls at once", async (t) => { + const session = await startHostFake(); + t.after(() => session.stop()); + const watcher = new FakeSink(); + session.subscribe(watcher, "local"); + const phone = new FakeSink(); + session.subscribe(phone, "dev_phone"); + await session.rpc({ type: "fake_host_call", callId: "c1", provider: "dev_phone" }, 5000); + await session.rpc({ type: "fake_host_call", callId: "c2", provider: "dev_phone" }, 5000); + await session.rpc({ type: "fake_host_call", callId: "c3", provider: "dev_phone" }, 5000); + await until(() => session.pendingHostCalls().length === 3, "three calls"); + await session.rpc({ type: "fake_host_cancel", callId: "c1" }, 5000); + await until(() => session.pendingHostCalls().length === 2, "the cancel"); + session.hostCallSettled("c2"); + assert.deepEqual(session.pendingHostCalls().map((call) => call.callId), ["c3"]); + session.dropDevice("dev_phone"); + assert.ok(phone.destroyed); + await until(() => serverAnswer(watcher, "c3") !== undefined, "the revoked device's call fails"); + assert.equal(serverAnswer(watcher, "c1"), undefined); + assert.equal(serverAnswer(watcher, "c2"), undefined); +}); + +test("no fake Pi outlives the tests above", async () => { + assert.deepEqual(await remainingServeLeftovers([], []), []); +}); diff --git a/tests/serve-share.test.ts b/tests/serve-share.test.ts new file mode 100644 index 000000000..cf15aedaf --- /dev/null +++ b/tests/serve-share.test.ts @@ -0,0 +1,460 @@ +import assert from "node:assert/strict"; +import { spawn, spawnSync, type ChildProcess } from "node:child_process"; +import { once } from "node:events"; +import { existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { createServer, type Server } from "node:net"; +import { hostname, tmpdir, type NetworkInterfaceInfo } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { liveServer, parseServeArgs, readServerFile, runServeCommand, serveFiles, type ServeCommandContext } from "../lib/serve-cli.ts"; +import { autostartCommand, autostartFile, autostartInstalled, encodeConnectionCode, firewallHint, installAutostart, launchAgentPlist, ownHostNames, + removeAutostart, SHARE_FORWARD_PORTS, shareAddresses, systemdUnit, type ShareSystem } from "../lib/serve-share.ts"; +import { after, endServeLeftovers, remainingServeLeftovers, test } from "./serve-test-client.ts"; + +const binPath = fileURLToPath(new URL("../bin/gentle-shell.mjs", import.meta.url)); +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); +const roots: string[] = []; +const sessionDirs = () => roots.map((root) => join(serveFiles(join(root, "agent")).dir, "sessions")); +after(async () => { + // A failed test must not leave a server, a session keeper, or its fake Pi behind. + await endServeLeftovers(sessionDirs(), roots); + roots.forEach((r) => rmSync(r, { recursive: true, force: true })); +}); +function scratch(): string { + const r = realpathSync(mkdtempSync(join(tmpdir(), "gentle-serve-share-"))); + roots.push(r); + return r; +} + +/** The client side of the contract: `gsc1.` + base64url (no padding) of the JSON. */ +function decode(code: string): { v: number; id: string; n: string; p: number; a: string[]; c: string; fp?: string; r?: string } { + assert.ok(code.startsWith("gsc1."), code); + const payload = code.slice("gsc1.".length); + assert.match(payload, /^[A-Za-z0-9_-]+$/, "base64url without padding"); + return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")); +} + +function nic(address: string, options: { family?: "IPv4" | "IPv6"; internal?: boolean } = {}): NetworkInterfaceInfo { + const family = options.family ?? "IPv4"; + return { address, family, internal: options.internal ?? false, netmask: "", mac: "00:00:00:00:00:00", cidr: null, ...(family === "IPv6" ? { scopeid: 0 } : {}) } as NetworkInterfaceInfo; +} + +test("serve share arguments", () => { + assert.deepEqual(parseServeArgs(["share"]), { action: "share", port: 8787, always: false, json: false }); + assert.deepEqual(parseServeArgs(["share", "--port", "9000", "--always", "--json"]), { action: "share", port: 9000, always: true, json: true }); + assert.deepEqual(parseServeArgs(["share", "--port=9001"]), { action: "share", port: 9001, always: false, json: false }); + assert.deepEqual(parseServeArgs(["share", "--off"]), { action: "share-off" }); + assert.deepEqual(parseServeArgs(["share", "--off", "--always"]), { error: "serve share --off takes no other argument" }); + assert.deepEqual(parseServeArgs(["share", "--port", "0"]), { error: '--port needs a port 1-65535 (got "0")' }); + assert.deepEqual(parseServeArgs(["share", "--port"]), { error: '--port needs a port 1-65535 (got "")' }); + assert.deepEqual(parseServeArgs(["share", "--listen", "0.0.0.0:1"]), { error: 'unknown serve share argument "--listen"' }); + assert.deepEqual(parseServeArgs(["--always"]), { error: 'unknown serve argument "--always"' }); + assert.deepEqual(parseServeArgs(["share", "--no-tls"]), { action: "share", port: 8787, always: false, json: false, noTls: true }); + assert.deepEqual(parseServeArgs(["share", "--relay", "gsr://relay.example.com:7700"]), { action: "share", port: 8787, always: false, json: false, relay: "gsr://relay.example.com:7700" }); + assert.deepEqual(parseServeArgs(["--listen", "0.0.0.0:8787", "--relay=gsr://[2001:db8::1]:7700"]), { action: "start", host: "0.0.0.0", port: 8787, foreground: false, json: false, relay: "gsr://[2001:db8::1]:7700" }); + assert.deepEqual(parseServeArgs(["share", "--relay", "gsr://relay.example.com:7700", "--no-tls"]), { error: "--relay needs TLS (the relay must only see ciphertext): leave out --no-tls" }); + assert.match((parseServeArgs(["share", "--relay", "https://relay.example.com"]) as { error: string }).error, /starts with gsr:\/\//); + assert.match((parseServeArgs(["share", "--relay", "gsr://relay.example.com"]) as { error: string }).error, /needs a port/); + assert.match((parseServeArgs(["share", "--relay", "gsr://secret@relay.example.com:7700"]) as { error: string }).error, /relay secret goes in GENTLE_SHELL_RELAY_SECRET/); + assert.deepEqual(parseServeArgs(["share", "--off", "--no-tls"]), { error: "serve share --off takes no other argument" }); +}); + +test("a connection code is gsc1. + base64url JSON in the contract's key order", () => { + const code = encodeConnectionCode({ id: "srv_0123456789abcdef", n: "Box", p: 8787, a: ["192.168.1.20", "box", "box.local"], c: "ABCD-EFGH" }); + assert.ok(!code.includes("="), "no padding"); + assert.deepEqual(decode(code), { v: 1, id: "srv_0123456789abcdef", n: "Box", p: 8787, a: ["192.168.1.20", "box", "box.local"], c: "ABCD-EFGH" }); + assert.deepEqual(Object.keys(decode(code)), ["v", "id", "n", "p", "a", "c"]); + // HTTPS and a relay add the certificate's fingerprint and the relay, last. + const fp = "q2pTqfGOkIMwLzAqnmz5aHN5LyFnSRmA7Xc3WEZ8k4o"; + const secure = decode(encodeConnectionCode({ id: "srv_0123456789abcdef", n: "Box", p: 8787, a: ["box"], c: "ABCD-EFGH", fp, r: "gsr://relay.example.com:7700" })); + assert.deepEqual(Object.keys(secure), ["v", "id", "n", "p", "a", "c", "fp", "r"]); + assert.equal(secure.fp, fp); + assert.equal(secure.r, "gsr://relay.example.com:7700"); + // Characters base64 would turn into + and / stay URL-safe. + const odd = encodeConnectionCode({ id: "srv_?>?>", n: "ñ~~~", p: 1, a: [], c: "????-????" }); + assert.match(odd, /^gsc1\.[A-Za-z0-9_-]+$/); + assert.equal(decode(odd).n, "ñ~~~"); +}); + +test("advertised addresses: LAN IPv4 first, never loopback or link-local, names last, at most 8", () => { + const interfaces = { + lo0: [nic("127.0.0.1", { internal: true }), nic("::1", { family: "IPv6", internal: true })], + docker0: [nic("172.17.0.1")], + tailscale0: [nic("100.101.102.103"), nic("fd7a:115c:a1e0::1", { family: "IPv6" })], + en0: [nic("fe80::1c2b:3cff:fe4d:5e6f", { family: "IPv6" }), nic("192.168.1.20"), nic("169.254.10.2")], + en1: [nic("10.0.0.5")], + en2: [nic("192.168.1.20")], + }; + assert.deepEqual(shareAddresses(interfaces, "Box"), ["192.168.1.20", "10.0.0.5", "100.101.102.103", "172.17.0.1", "box", "box.local"]); + // A macOS-style name already ending in .local is not doubled. + assert.deepEqual(shareAddresses({ en0: [nic("192.168.1.20")] }, "Ismaels-MacBook-Pro.local"), ["192.168.1.20", "ismaels-macbook-pro.local"]); + assert.deepEqual(shareAddresses({}, "box"), ["box", "box.local"], "no network: the names alone"); + const many = { en0: Array.from({ length: 12 }, (_, i) => nic(`192.168.1.${i + 1}`)) }; + const capped = shareAddresses(many, "box"); + assert.equal(capped.length, 8); + assert.deepEqual(capped.slice(-2), ["box", "box.local"], "the names keep their places"); + // A hostname that is not a DNS name is left out (it could not be a URL host). + assert.deepEqual(ownHostNames("my_box"), []); + assert.equal(shareAddresses(many, "my_box").length, 8); +}); + +test("the firewall hint names the exact command, on Linux with ufw or firewalld only", () => { + assert.equal(firewallHint("linux", 8787, (c) => c === "ufw"), "sudo ufw allow 8787", "TCP and UDP (discovery)"); + assert.equal(firewallHint("linux", 8788, (c) => c === "firewall-cmd"), "sudo firewall-cmd --permanent --add-port=8788/tcp --add-port=8788/udp && sudo firewall-cmd --reload"); + assert.equal(firewallHint("linux", 8787, () => false), undefined); + assert.equal(firewallHint("darwin", 8787, () => true), undefined); + // The forwarded pages' range is TCP only. + assert.equal(firewallHint("linux", 8787, (c) => c === "ufw", { from: 8800, to: 8899 }), "sudo ufw allow 8787 && sudo ufw allow 8800:8899/tcp"); + assert.equal(firewallHint("linux", 8787, (c) => c === "firewall-cmd", { from: 8800, to: 8899 }), + "sudo firewall-cmd --permanent --add-port=8787/tcp --add-port=8787/udp --add-port=8800-8899/tcp && sudo firewall-cmd --reload"); +}); + +function fakeSystem(root: string, platform: NodeJS.Platform, run: ShareSystem["run"]): ShareSystem { + return { platform, hostname: () => "box", networkInterfaces: () => ({ en0: [nic("192.168.1.20")] }), userHome: root, uid: 501, user: "me", run, has: () => false }; +} + +function recorder(fail?: string): { calls: string[]; run: ShareSystem["run"] } { + const calls: string[] = []; + return { calls, run: async (command, args) => { + const line = [command, ...args].join(" "); + calls.push(line); + return line.includes(fail ?? "\0") ? { status: 1, output: "Failed to connect to bus\n" } : { status: 0, output: "" }; + } }; +} + +const sampleSpec = (logFile = "/home/me/.gs/serve/server.log") => autostartCommand({ + nodePath: "/usr/bin/node", + launcher: "/home/me/src/gentle shell/bin/gentle-shell.mjs", + homeFlags: ["--home", "/home/me/.gs"], + port: 8787, + allowHosts: ["box", "box.local"], + env: { PATH: "/usr/local/bin:/usr/bin", GENTLE_SHELL_NO_AUTO_SETUP: "1", HOME: "/home/me", ANTHROPIC_API_KEY: "secret" }, + logFile, +}); + +test("autostart runs this same launcher and home on the network, with only the kept environment", () => { + const spec = sampleSpec(); + assert.equal(spec.command, "/usr/bin/node"); + assert.deepEqual(spec.args, ["/home/me/src/gentle shell/bin/gentle-shell.mjs", "--home", "/home/me/.gs", "serve", "--foreground", "--listen", "0.0.0.0:8787", "--allow-host", "box", "--allow-host", "box.local"]); + assert.deepEqual(spec.env, { PATH: "/usr/local/bin:/usr/bin", GENTLE_SHELL_NO_AUTO_SETUP: "1" }, "no secrets, no HOME (the service manager sets it)"); + assert.deepEqual(autostartCommand({ nodePath: "/n", launcher: "/l", homeFlags: [], port: 8787, allowHosts: [], forwardPorts: SHARE_FORWARD_PORTS, env: {}, logFile: "/log" }).args, + ["/l", "serve", "--foreground", "--listen", "0.0.0.0:8787", "--forward-ports", "8800-8899"]); + + const unit = systemdUnit(spec); + assert.match(unit, /^ExecStart=\/usr\/bin\/node "\/home\/me\/src\/gentle shell\/bin\/gentle-shell\.mjs" --home \/home\/me\/\.gs serve --foreground --listen 0\.0\.0\.0:8787 --allow-host box --allow-host box\.local$/m); + assert.match(unit, /^Environment="PATH=\/usr\/local\/bin:\/usr\/bin"$/m); + assert.match(unit, /^Environment="GENTLE_SHELL_NO_AUTO_SETUP=1"$/m); + assert.match(unit, /^Restart=on-failure$/m); + // A restart (after an upgrade) or a stop ends the server only, never the session keepers it started. + assert.match(unit, /^KillMode=process$/m); + assert.match(unit, /^\[Install\]\nWantedBy=default\.target$/m); + assert.ok(!unit.includes("secret")); + // systemd specifiers and variables are escaped, not expanded. + const odd = systemdUnit({ ...spec, args: ["/opt/50%/$HOME/x"], env: { PATH: "/a%b" } }); + assert.match(odd, /^ExecStart=\/usr\/bin\/node "\/opt\/50%%\/\$\$HOME\/x"$/m); + assert.match(odd, /^Environment="PATH=\/a%%b"$/m); + + const plist = launchAgentPlist({ ...spec, args: [...spec.args, "a&b"] }); + assert.match(plist, /Label<\/key>\n\tcom\.gentle-shell\.serve<\/string>/); + const programArgs = /ProgramArguments<\/key>\n\t\n([\s\S]*?)\n\t<\/array>/.exec(plist)![1].split("\n").map((l) => l.trim().replace(/^|<\/string>$/g, "")); + assert.deepEqual(programArgs, ["/usr/bin/node", ...spec.args, "a&b<c>"]); + assert.match(plist, /EnvironmentVariables<\/key>\n\t\n\t\tPATH<\/key>\n\t\t\/usr\/local\/bin:\/usr\/bin<\/string>\n\t\tGENTLE_SHELL_NO_AUTO_SETUP<\/key>\n\t\t1<\/string>\n\t<\/dict>/); + assert.match(plist, /RunAtLoad<\/key>\n\t/); + assert.match(plist, /StandardErrorPath<\/key>\n\t\/home\/me\/\.gs\/serve\/server\.log<\/string>/); +}); + +test("autostart on Linux: a systemd user unit, enabled and started; --off disables and removes it", async () => { + const root = scratch(); + const { calls, run } = recorder(); + const system = fakeSystem(root, "linux", run); + const spec = sampleSpec(); + const installed = await installAutostart(system, spec); + const file = join(root, ".config", "systemd", "user", "gentle-shell-serve.service"); + assert.deepEqual(installed, { file }); + assert.equal(readFileSync(file, "utf8"), systemdUnit(spec)); + assert.deepEqual(calls, ["systemctl --user daemon-reload", "systemctl --user enable --now gentle-shell-serve.service"]); + assert.ok(autostartInstalled(system, spec)); + assert.ok(!autostartInstalled(system, { ...spec, args: [...spec.args, "--allow-host", "other"] })); + + calls.length = 0; + assert.deepEqual(await removeAutostart(system), { file, removed: true }); + assert.deepEqual(calls, ["systemctl --user disable --now gentle-shell-serve.service", "systemctl --user daemon-reload"]); + assert.ok(!existsSync(file)); + assert.equal((await removeAutostart(system)).removed, false); + + // XDG_CONFIG_HOME moves user units. + assert.equal(autostartFile({ ...system, configHome: "/xdg" }), "/xdg/systemd/user/gentle-shell-serve.service"); + + // Without a user bus (an SSH login without lingering) nothing is left behind. + const failing = recorder("enable"); + const refused = await installAutostart(fakeSystem(root, "linux", failing.run), spec); + assert.deepEqual(refused, { error: "systemctl --user enable --now gentle-shell-serve.service failed (1): Failed to connect to bus" }); + assert.ok(!existsSync(file)); + assert.deepEqual(failing.calls.at(-1), "systemctl --user daemon-reload"); +}); + +test("autostart on macOS: a LaunchAgent bootstrapped in the GUI domain; Windows has none", async () => { + const root = scratch(); + const { calls, run } = recorder(); + const system = fakeSystem(root, "darwin", run); + const spec = sampleSpec(join(root, "home", "serve", "server.log")); + const file = join(root, "Library", "LaunchAgents", "com.gentle-shell.serve.plist"); + assert.deepEqual(await installAutostart(system, spec), { file }); + assert.equal(readFileSync(file, "utf8"), launchAgentPlist(spec)); + assert.deepEqual(calls, ["launchctl bootout gui/501/com.gentle-shell.serve", `launchctl bootstrap gui/501 ${file}`]); + if (process.platform !== "win32") assert.equal(statSync(spec.logFile).mode & 0o777, 0o600, "the log launchd appends to is owner-only"); + calls.length = 0; + assert.deepEqual(await removeAutostart(system), { file, removed: true }); + assert.deepEqual(calls, ["launchctl bootout gui/501/com.gentle-shell.serve"]); + assert.ok(!existsSync(file)); + + const windows = fakeSystem(root, "win32", run); + assert.equal(autostartFile(windows), undefined); + assert.deepEqual(await installAutostart(windows, spec), { error: "autostart is not supported on win32 yet" }); +}); + +// --- share against real servers ------------------------------------------------------ + +function isolatedEnv(root: string): NodeJS.ProcessEnv { + return { HOME: root, USERPROFILE: root, PATH: process.env.PATH, GENTLE_SHELL_NO_AUTO_SETUP: "1" }; +} + +function cli(root: string, args: string[]) { + return spawnSync(process.execPath, [binPath, "--home", join(root, "agent"), "serve", ...args], { env: isolatedEnv(root), encoding: "utf8", timeout: 60_000 }); +} + +function canBind(port: number, host: string): Promise { + const { promise, resolve } = Promise.withResolvers(); + const probe = createServer(); + probe.once("error", () => resolve(false)); + probe.listen(port, host, () => probe.close(() => resolve(true))); + return promise; +} + +/** + * A port P such that P..P+count-1 are free on every interface. Below the + * ephemeral ranges (Linux 32768+, macOS and Windows 49152+): a port the OS just + * handed out is next to the ones it hands to parallel tests' `listen(0)`. + */ +async function freePorts(count: number): Promise { + for (;;) { + const base = 20_000 + Math.floor(Math.random() * 10_000); + let ok = true; + for (let p = base; p < base + count && ok; p += 1) ok = (await canBind(p, "0.0.0.0")) && (await canBind(p, "127.0.0.1")); + if (ok) return base; + } +} + +function listen(port: number): Promise { + const { promise, resolve } = Promise.withResolvers(); + const server = createServer(); + server.listen(port, "0.0.0.0", () => resolve(server)); + return promise; +} + +test("serve share from stopped: starts on the network (next port when taken), the code finds and pairs it; share again reuses it", { timeout: 90_000 }, async () => { + const root = scratch(); + const home = join(root, "agent"); + const port = await freePorts(2); + const blocker = await listen(port); + let started; + try { + started = cli(root, ["share", "--port", String(port), "--json"]); + } finally { + blocker.close(); + } + assert.equal(started.status, 0, started.stderr); + try { + const info = JSON.parse(started.stdout); + assert.deepEqual(Object.keys(info), ["code", "pairingCode", "port", "addresses", "expiresAt", "serverId", "discovery", "tls", "fingerprint"]); + assert.equal(info.tls, true, "the network gets HTTPS"); + assert.match(info.fingerprint, /^[A-Za-z0-9_-]{43}$/); + assert.equal(info.discovery, true, "the network server answers LAN discovery"); + assert.equal(info.port, port + 1, "the taken port is skipped"); + const code = decode(info.code); + assert.equal(info.pairingCode, code.c, "the short code is the one the long code carries"); + assert.equal(code.v, 1); + assert.equal(code.id, info.serverId); + assert.equal(code.n, hostname()); + assert.equal(code.p, port + 1); + assert.deepEqual(code.a, info.addresses); + assert.equal(code.fp, info.fingerprint, "the long code pins the certificate"); + assert.equal(code.r, undefined, "no relay asked"); + assert.ok(code.a.length >= 1 && code.a.length <= 8); + const names = ownHostNames(hostname()); + assert.deepEqual(code.a.slice(code.a.length - names.length), names, "this machine's names come last"); + for (const a of code.a) assert.ok(!a.startsWith("127.") && !a.startsWith("169.254.") && !a.includes(":"), a); + assert.match(code.c, /^[0-9A-Z]{4}-[0-9A-Z]{4}$/); + assert.ok(Date.parse(info.expiresAt) > Date.now()); + + const server = readServerFile(serveFiles(home).server)!; + assert.deepEqual(server.listen, { host: "0.0.0.0", port: port + 1 }); + assert.deepEqual(server.forwardPorts, { from: 8800, to: 8899 }, "forwarded pages take one range a firewall can open"); + assert.equal(server.serverId, info.serverId); + assert.equal(server.fingerprint, info.fingerprint); + assert.ok(existsSync(join(home, "serve", "tls", "cert.pem")) && (process.platform === "win32" || (statSync(join(home, "serve", "tls", "key.pem")).mode & 0o777) === 0o600), "the key is owner-only"); + + // What the client does: identity first, then the pairing code, at the same address (this machine may use plain HTTP). + const base = `http://127.0.0.1:${port + 1}`; + const identity = await (await fetch(`${base}/.well-known/gentle-shell`)).json(); + assert.equal(identity.fp, info.fingerprint); + assert.equal(identity.tls, true); + assert.equal(identity.serverId, code.id); + assert.equal(identity.schema, "gentle-shell.serve.identity/v1"); + const paired = await fetch(`${base}/api/pair`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: code.c, name: "gpui" }) }); + assert.equal(paired.status, 201); + const again = await fetch(`${base}/api/pair`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: code.c, name: "gpui" }) }); + assert.equal(again.status, 403, "single use"); + + const human = cli(root, ["share", "--port", String(port)]); + assert.equal(human.status, 0, human.stderr); + const lines = human.stdout.split("\n"); + assert.equal(lines[0], `The Gentle Shell server is already open to your network on port ${port + 1}.`); + assert.equal(lines[1], ""); + const short = /^ {2}Code: ([0-9A-Z]{4}-[0-9A-Z]{4})$/.exec(lines[2]); + assert.ok(short, lines[2]); + assert.equal(lines[3], ""); + assert.equal(lines[4], "In Gentle Shell GPUI → Configuration → Where agents run → Gentle Shell server, enter this code. Valid for 5 minutes, once."); + assert.equal(lines[5], "If the app can't find this computer, paste this instead:"); + assert.match(lines[6], /^gsc1\.[A-Za-z0-9_-]+$/, "the long code alone on its line"); + assert.equal(decode(lines[6]).id, info.serverId, "the same server"); + assert.equal(decode(lines[6]).c, short[1], "the long code carries the short one"); + assert.notEqual(short[1], code.c, "a fresh pairing code"); + assert.equal(lines[7], ""); + assert.equal(lines[8], `It uses HTTPS; the app checks this computer's certificate, fingerprint ${info.fingerprint}.`, "discovery is on: no note before it"); + assert.equal(readServerFile(serveFiles(home).server)!.pid, server.pid); + } finally { + assert.equal(cli(root, ["stop"]).status, 0); + } +}); + +test("serve share reopens a loopback server with no sessions on the network", { timeout: 90_000 }, async () => { + const root = scratch(); + const home = join(root, "agent"); + const loop = cli(root, ["--listen", "127.0.0.1:0", "--json"]); + assert.equal(loop.status, 0, loop.stderr); + const before = readServerFile(serveFiles(home).server)!; + const port = await freePorts(1); + const shared = cli(root, ["share", "--port", String(port)]); + try { + assert.equal(shared.status, 0, shared.stderr); + assert.match(shared.stdout, new RegExp(`^Opened the Gentle Shell server to your network on port ${port} \\(it was reachable from this computer only\\)\\.\n`)); + const after = readServerFile(serveFiles(home).server)!; + assert.deepEqual(after.listen, { host: "0.0.0.0", port }); + assert.notEqual(after.pid, before.pid); + assert.ok(!liveServer(home) || liveServer(home)!.pid === after.pid); + } finally { + assert.equal(cli(root, ["stop"]).status, 0); + } +}); + +function context(root: string, overrides: Partial = {}): ServeCommandContext & { out: string[]; err: string[] } { + const out: string[] = []; + const err: string[] = []; + const home = join(root, "agent"); + return { agentHome: home, homeFlags: ["--home", home], launcher: binPath, nodePath: process.execPath, version: "test", env: isolatedEnv(root), + stdout: (t) => out.push(t), stderr: (t) => err.push(t), out, err, ...overrides }; +} + +test("serve share leaves a loopback server with running sessions alone and says why", { timeout: 60_000 }, async () => { + const root = scratch(); + const project = join(root, "project"); + mkdirSync(project); + const release = Promise.withResolvers(); + const ready = Promise.withResolvers(); + // An in-process server whose sessions are the fake Pi; it prints once it serves. + const owner = context(root, { launcher: FAKE_PI, untilStopped: (stop) => Promise.race([stop, release.promise]), stdout: () => ready.resolve() }); + const running = runServeCommand({ action: "start", host: "127.0.0.1", port: 0, foreground: true, json: true }, owner); + try { + await Promise.race([ready.promise, running.then(() => { throw new Error(owner.err.join("")); })]); + const server = liveServer(owner.agentHome)!; + const session = await fetch(`${server.url}/api/sessions`, { method: "POST", headers: { Authorization: `Bearer ${server.adminToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ cwd: project }) }); + assert.equal(session.status, 201); + + const ctx = context(root, { system: fakeSystem(root, "linux", recorder().run) }); + assert.equal(await runServeCommand({ action: "share", port: 8787, always: false, json: false }, ctx), 1); + assert.equal(ctx.err.join(""), `gentle-shell serve share: the server here is reachable from this computer only and has 1 running session(s); stop them or run 'gentle-shell serve stop', then run share again to open it to your network.\n`); + assert.equal(ctx.out.join(""), ""); + assert.equal(liveServer(owner.agentHome)?.pid, process.pid, "still the same server"); + const list = await (await fetch(`${server.url}/api/sessions`, { headers: { Authorization: `Bearer ${server.adminToken}` } })).json(); + assert.deepEqual(list.sessions.map((s: { state: string }) => s.state), ["running"]); + } finally { + // The session ends with its server: what `gentle-shell serve stop --sessions` asks (this server runs in the test's own process, so no pid to wait on). + const server = liveServer(owner.agentHome); + if (server) { + const stopped = await fetch(`${server.url}/api/server/stop`, { method: "POST", headers: { Authorization: `Bearer ${server.adminToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ endSessions: true }) }); + assert.equal(stopped.status, 202); + } + release.resolve(); + assert.equal(await running, 0); + } +}); + +/** A stand-in for launchd: bootstrap runs the agent's ProgramArguments, bootout stops it. */ +function fakeLaunchd(root: string): { run: ShareSystem["run"]; calls: string[]; child(): ChildProcess | undefined } { + const calls: string[] = []; + let child: ChildProcess | undefined; + const run: ShareSystem["run"] = async (command, args) => { + calls.push([command, ...args].join(" ")); + if (args[0] === "bootstrap") { + const plist = readFileSync(args[2], "utf8"); + const strings = (block: string) => [...block.matchAll(/(.*?)<\/string>/g)].map((m) => m[1].replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/&/g, "&")); + const argv = strings(/ProgramArguments<\/key>\s*([\s\S]*?)<\/array>/.exec(plist)![1]); + const envPairs = strings(/EnvironmentVariables<\/key>\s*([\s\S]*?)<\/dict>/.exec(plist)![1].replace(/(.*?)<\/key>/g, "$1")); + const env: NodeJS.ProcessEnv = { HOME: root, USERPROFILE: root }; + for (let i = 0; i < envPairs.length; i += 2) env[envPairs[i]] = envPairs[i + 1]; + const log = openSync(strings(/StandardErrorPath<\/key>\s*(.*?<\/string>)/.exec(plist)![1])[0], "a"); + child = spawn(argv[0], argv.slice(1), { env, stdio: ["ignore", log, log], detached: true }); + } + if (args[0] === "bootout" && child && child.exitCode === null) child.kill("SIGTERM"); + return { status: 0, output: "" }; + }; + return { run, calls, child: () => child }; +} + +test("serve share --always hands the server to the login service manager, reuses it, and --off stops it", { timeout: 90_000 }, async (t) => { + const root = scratch(); + const launchd = fakeLaunchd(root); + t.after(() => { const c = launchd.child(); if (c && c.exitCode === null) c.kill("SIGKILL"); }); + const system = fakeSystem(root, "darwin", launchd.run); + const port = await freePorts(1); + const ctx = context(root, { system }); + assert.equal(await runServeCommand({ action: "share", port, always: true, json: false }, ctx), 0, ctx.err.join("")); + const plistFile = join(root, "Library", "LaunchAgents", "com.gentle-shell.serve.plist"); + const plist = readFileSync(plistFile, "utf8"); + for (const arg of [process.execPath, binPath, "--home", ctx.agentHome, "serve", "--foreground", "--listen", `0.0.0.0:${port}`, "--allow-host", "box", "box.local"]) assert.ok(plist.includes(`${arg}`), arg); + assert.ok(plist.includes("GENTLE_SHELL_NO_AUTO_SETUP"), "kept from the installing invocation"); + const server = liveServer(ctx.agentHome)!; + assert.equal(server.pid, launchd.child()!.pid, "the service manager's process serves"); + const out = ctx.out.join(""); + assert.match(out, new RegExp(`^Started the Gentle Shell server for your network on port ${port}\\.\n\n Code: [0-9A-Z]{4}-[0-9A-Z]{4}\n\n`)); + assert.match(out, /\nIt starts at every login; turn that off with 'gentle-shell serve share --off'\.\n$/); + assert.deepEqual(decode(out.split("\n")[6]).a, ["192.168.1.20", "box", "box.local"]); + + // Already installed and running: reused as is, the service manager untouched. + launchd.calls.length = 0; + const again = context(root, { system }); + assert.equal(await runServeCommand({ action: "share", port, always: true, json: true }, again), 0, again.err.join("")); + assert.equal(JSON.parse(again.out.join("")).serverId, server.serverId); + assert.deepEqual(launchd.calls, []); + + const exited = once(launchd.child()!, "exit"); + const off = context(root, { system }); + assert.equal(await runServeCommand({ action: "share-off" }, off), 0); + assert.equal(off.out.join(""), `Start at login is off (removed ${plistFile}); the server it started has stopped.\n`); + await exited; + assert.ok(!existsSync(plistFile)); + assert.equal(liveServer(ctx.agentHome), undefined); +}); + +test("serve share --always is refused on Windows before anything starts", async () => { + const root = scratch(); + const ctx = context(root, { system: fakeSystem(root, "win32", recorder().run) }); + assert.equal(await runServeCommand({ action: "share", port: 8787, always: true, json: false }, ctx), 1); + assert.equal(ctx.err.join(""), "gentle-shell serve share: --always (start at login) is not supported on Windows yet; run 'gentle-shell serve share' without it.\n"); + assert.equal(liveServer(ctx.agentHome), undefined); +}); + +test("no server, session keeper, or fake Pi outlives the tests above", async () => { + assert.deepEqual(await remainingServeLeftovers(sessionDirs(), roots), []); +}); diff --git a/tests/serve-terminals.test.ts b/tests/serve-terminals.test.ts new file mode 100644 index 000000000..d8ac525f5 --- /dev/null +++ b/tests/serve-terminals.test.ts @@ -0,0 +1,333 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { setTimeout as sleep } from "node:timers/promises"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { startServeServer, type ServeServer, type ServeServerOptions } from "../lib/serve-server.ts"; +import { HostConnection, termHostAsset, termHostTransport, type TermHostEndpoint } from "../lib/serve-terminals.ts"; +import { after, before, call, pairDevice, stream, test } from "./serve-test-client.ts"; + +const FAKE_HOST = fileURLToPath(new URL("./fixtures/serve-fake-term-host.mjs", import.meta.url)); +const ADMIN = "gsa_test-admin-token"; +// Unix socket paths are short (104 bytes on macOS): a short root. +const root = realpathSync(mkdtempSync(process.platform === "win32" ? join(process.env.TEMP ?? ".", "gst-") : "/tmp/gst-")); +const serveDir = join(root, "serve"); +const project = join(root, "project"); +// Echoes its input back, so a test sees a round trip through the terminal. +const ECHO = [process.execPath, "-e", "process.stdout.write('ready\\n'); process.stdin.on('data', (d) => process.stdout.write('echo:' + d))"]; +// Input sent before `ready` is out may come back in one chunk with it: tests wait for it (live or in the snapshot) first. +const READY = Buffer.from("ready\n").toString("base64"); +let server: ServeServer; +let auth: ServeAuth; +let phone: { id: string; token: string }; + +const options = (env: NodeJS.ProcessEnv): ServeServerOptions => ({ + host: "127.0.0.1", + port: 0, + auth, + version: "test", + serveDir, + env, + launchSession: () => { throw new Error("no sessions here"); }, +}); + +async function shutdownHost(endpoint: TermHostEndpoint): Promise { + const conn = await HostConnection.open(endpoint, 1000).catch(() => undefined); + if (!conn) return; + await conn.request("shutdown", {}, 2000).catch(() => undefined); + conn.close(); +} + +before(async () => { + mkdirSync(project); + auth = new ServeAuth({ devicesFile: join(serveDir, "devices.json"), adminToken: ADMIN }); + server = await startServeServer(options({ PATH: process.env.PATH, GENTLE_TERM_HOST: FAKE_HOST })); + phone = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate", "terminal"], "phone"); +}); +after(async () => { + await server?.close(); + await shutdownHost({ path: join(serveDir, "term.sock") }); + rmSync(root, { recursive: true, force: true }); +}); + +const decode = (b64: string) => Buffer.from(b64, "base64").toString("utf8"); + +/** The `data` of every SSE event of one type, parsed. */ +function events(text: string, type: string): any[] { + return text.split("\n\n").filter((block) => block.split("\n").includes(`event: ${type}`)) + .map((block) => JSON.parse(block.split("\n").find((line) => line.startsWith("data: "))!.slice(6))); +} + +async function openTerm(token = phone.token): Promise { + const opened = await call(server.url, "POST", "/api/terminals", { token, body: { cwd: project, cols: 80, rows: 24, argv: ECHO } }); + assert.equal(opened.status, 201, JSON.stringify(opened.body)); + return opened.body.terminal.id; +} + +test("the terminal scope is in the default pairing scopes and gates the endpoints", async () => { + const code = await call(server.url, "POST", "/api/pairing-codes", { token: ADMIN, body: {} }); + assert.deepEqual(code.body.scopes, ["sessions:read", "sessions:operate", "terminal"]); + const noTerminal = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"], "no-terminal"); + assert.equal((await call(server.url, "GET", "/api/terminals", { token: noTerminal.token })).status, 403); + assert.equal((await call(server.url, "POST", "/api/terminals", { token: noTerminal.token, body: { cwd: project, cols: 80, rows: 24 } })).status, 403); + assert.equal((await call(server.url, "GET", "/api/terminals")).status, 401); + const info = await call(server.url, "GET", "/api/server", { token: phone.token }); + assert.ok(info.body.capabilities.includes("terminals")); +}); + +test("open starts the host on first use, detached, with its socket and state folder under serve/", async () => { + const id = await openTerm(); + assert.match(id, /^t_[0-9a-f]+$/); + const recorded = JSON.parse(readFileSync(join(serveDir, "term", "argv.json"), "utf8")); + assert.deepEqual(recorded, ["--socket", join(serveDir, "term.sock"), "--state-dir", join(serveDir, "term")]); + assert.equal(statSync(join(serveDir, "term")).mode & 0o777, 0o700); + const listed = await call(server.url, "GET", "/api/terminals", { token: phone.token }); + const entry = listed.body.terminals.find((t: { id: string }) => t.id === id); + assert.equal(entry.owner, phone.id); + assert.equal(entry.cwd, project); + assert.deepEqual(entry.argv, ECHO); + assert.equal(entry.alive, true); + assert.equal(entry.cols, 80); + const host = await call(server.url, "GET", "/api/term-host", { token: phone.token }); + assert.equal(host.body.running, true); + assert.equal(host.body.version, "fake"); + assert.equal(host.body.transport, "unix"); + assert.equal(host.body.asset, termHostAsset()); + assert.equal(host.body.path, undefined, "the binary's path only for an admin"); + assert.equal((await call(server.url, "GET", "/api/term-host", { token: ADMIN })).body.path, FAKE_HOST); +}); + +test("stream: attached first, then output; input round-trips; resize is announced; resume and snapshot", async () => { + const id = await openTerm(); + const live = await stream(server.url, `/api/terminals/${id}/stream`, phone.token); + assert.equal(live.status, 200); + await live.waitFor("event: attached"); + assert.ok(live.text.indexOf("event: attached") < Math.max(0, live.text.indexOf("event: output")) || !live.text.includes("event: output")); + await live.waitFor(READY); + const input = await call(server.url, "POST", `/api/terminals/${id}/input`, { token: phone.token, body: { data: Buffer.from("hi\n").toString("base64") } }); + assert.equal(input.status, 200, JSON.stringify(input.body)); + await live.waitFor(/event: output\ndata: [^\n]*"data":"ZWNobzpoaQo="/); + const outputs = events(live.text, "output"); + const last = outputs.at(-1); + assert.equal(decode(last.data), "echo:hi\n"); + assert.equal(last.offset, "ready\necho:hi\n".length); + assert.match(live.text, new RegExp(`id: ${last.offset}\nevent: output`)); + + assert.equal((await call(server.url, "POST", `/api/terminals/${id}/resize`, { token: phone.token, body: { cols: 100, rows: 30 } })).status, 200); + await live.waitFor("event: resized"); + assert.deepEqual(events(live.text, "resized")[0], { cols: 100, rows: 30 }); + live.close(); + + // From an offset inside the ring: no snapshot, the missed bytes as output. + const resumed = await stream(server.url, `/api/terminals/${id}/stream?from=6`, phone.token); + await resumed.waitFor("event: output"); + assert.deepEqual(events(resumed.text, "attached")[0], { offset: 6 }); + assert.equal(decode(events(resumed.text, "output")[0].data), "echo:hi\n"); + resumed.close(); + // Last-Event-ID works as `from`, as EventSource sends it. + const viaHeader = await stream(server.url, `/api/terminals/${id}/stream`, phone.token, { "Last-Event-ID": "6" }); + await viaHeader.waitFor("event: attached"); + assert.deepEqual(events(viaHeader.text, "attached")[0], { offset: 6 }); + viaHeader.close(); + // Without `from`: a snapshot and the current end. + const fresh = await stream(server.url, `/api/terminals/${id}/stream`, phone.token); + await fresh.waitFor("event: attached"); + const attached = events(fresh.text, "attached")[0]; + assert.equal(attached.offset, 14); + assert.equal(decode(attached.snapshot), "ready\necho:hi\n"); + fresh.close(); + + assert.equal((await call(server.url, "GET", `/api/terminals/${id}/stream?from=x`, { token: phone.token })).body.error.code, "invalid_from"); + assert.equal((await call(server.url, "POST", `/api/terminals/${id}/input`, { token: phone.token, body: { data: "!!" } })).body.error.code, "invalid_data"); + assert.equal((await call(server.url, "POST", `/api/terminals/${id}/resize`, { token: phone.token, body: { cols: 0, rows: 30 } })).body.error.code, "invalid_cols"); + assert.equal((await call(server.url, "POST", "/api/terminals", { token: phone.token, body: { cwd: "relative", cols: 80, rows: 24 } })).body.error.code, "invalid_cwd"); + assert.equal((await call(server.url, "POST", "/api/terminals", { token: phone.token, body: { cwd: project, cols: 80, rows: 501 } })).body.error.code, "invalid_rows"); +}); + +test("the stream ends with exit when the program ends; DELETE closes and forgets", async () => { + const opened = await call(server.url, "POST", "/api/terminals", { token: phone.token, body: { cwd: project, cols: 80, rows: 24, argv: [process.execPath, "-e", "setTimeout(() => process.exit(3), 300)"] } }); + const id = opened.body.terminal.id; + const live = await stream(server.url, `/api/terminals/${id}/stream`, phone.token); + await live.closed; + assert.deepEqual(events(live.text, "exit")[0], { code: 3 }); + const exited = (await call(server.url, "GET", "/api/terminals", { token: phone.token })).body.terminals.find((t: { id: string }) => t.id === id); + assert.equal(exited.alive, false); + assert.equal(exited.exitCode, 3); + assert.equal((await call(server.url, "POST", `/api/terminals/${id}/input`, { token: phone.token, body: { data: "eA==" } })).status, 409); + assert.equal((await call(server.url, "DELETE", `/api/terminals/${id}`, { token: phone.token })).body.closed, id); + + const running = await openTerm(); + assert.equal((await call(server.url, "DELETE", `/api/terminals/${running}`, { token: phone.token })).status, 200); + const ids = (await call(server.url, "GET", "/api/terminals", { token: phone.token })).body.terminals.map((t: { id: string }) => t.id); + assert.equal(ids.includes(id) || ids.includes(running), false); + assert.equal((await call(server.url, "DELETE", `/api/terminals/${running}`, { token: phone.token })).status, 404); +}); + +test("terminals belong to the device that opened them; an admin sees all; revoking closes them", async () => { + const laptop = await pairDevice(server.url, ADMIN, ["terminal"], "laptop"); + const id = await openTerm(laptop.token); + assert.equal((await call(server.url, "POST", `/api/terminals/${id}/input`, { token: phone.token, body: { data: "eA==" } })).status, 404); + assert.equal((await call(server.url, "GET", `/api/terminals/${id}/stream`, { token: phone.token })).status, 404); + const phoneSees = (await call(server.url, "GET", "/api/terminals", { token: phone.token })).body.terminals.map((t: { id: string }) => t.id); + assert.equal(phoneSees.includes(id), false); + const adminSees = (await call(server.url, "GET", "/api/terminals", { token: ADMIN })).body.terminals.find((t: { id: string }) => t.id === id); + assert.equal(adminSees.owner, laptop.id); + + const live = await stream(server.url, `/api/terminals/${id}/stream`, laptop.token); + await live.waitFor("event: attached"); + assert.equal((await call(server.url, "DELETE", `/api/devices/${laptop.id}`, { token: ADMIN })).status, 200); + await live.closed; + for (let i = 0; i < 50; i += 1) { + // Closing runs in the background after the revoke answers: poll for its effect. + const left = (await call(server.url, "GET", "/api/terminals", { token: ADMIN })).body.terminals.some((t: { id: string }) => t.id === id); + if (!left) break; + await new Promise((r) => setTimeout(r, 20)); + } + assert.equal((await call(server.url, "GET", "/api/terminals", { token: ADMIN })).body.terminals.some((t: { id: string }) => t.id === id), false); +}); + +test("a device paired again takes its earlier pairing's place: its terminals, then that device is revoked", async () => { + const before = await pairDevice(server.url, ADMIN, ["terminal"], "tablet"); + const id = await openTerm(before.token); + const live = await stream(server.url, `/api/terminals/${id}/stream`, before.token); + await live.waitFor("event: attached"); + const again = await pairDevice(server.url, ADMIN, ["terminal"], "tablet"); + assert.equal((await call(server.url, "POST", "/api/devices/self/replace", { token: again.token, body: { token: "gss_nobody" } })).status, 404); + assert.equal((await call(server.url, "POST", "/api/devices/self/replace", { token: again.token, body: { token: again.token } })).status, 400); + const replaced = await call(server.url, "POST", "/api/devices/self/replace", { token: again.token, body: { token: before.token } }); + assert.equal(replaced.status, 200, JSON.stringify(replaced.body)); + assert.equal(replaced.body.replaced, before.id); + await live.closed; + assert.equal((await call(server.url, "GET", "/api/terminals", { token: before.token })).status, 401); + // Still running, now the new pairing's. + const mine = (await call(server.url, "GET", "/api/terminals", { token: again.token })).body.terminals.find((t: { id: string }) => t.id === id); + assert.ok(mine, "the terminal is the new pairing's"); + assert.equal(mine.owner, again.id); + assert.equal(JSON.parse(readFileSync(join(serveDir, "terminals.json"), "utf8")).owners[id], again.id); + const reattached = await stream(server.url, `/api/terminals/${id}/stream`, again.token); + await reattached.waitFor("event: attached"); + reattached.close(); + assert.equal((await call(server.url, "DELETE", `/api/terminals/${id}`, { token: again.token })).status, 200); +}); + +test("terminals and their owners survive a serve restart; the host keeps running", async () => { + const id = await openTerm(); + const pid = (await call(server.url, "GET", "/api/term-host", { token: phone.token })).body.pid; + await server.close(); + server = await startServeServer(options({ PATH: process.env.PATH, GENTLE_TERM_HOST: FAKE_HOST })); + const after = await call(server.url, "GET", "/api/terminals", { token: phone.token }); + const entry = after.body.terminals.find((t: { id: string }) => t.id === id); + assert.ok(entry, "still listed for its owner"); + assert.equal(entry.owner, phone.id); + assert.equal((await call(server.url, "GET", "/api/term-host", { token: phone.token })).body.pid, pid, "the same host"); + const owners = JSON.parse(readFileSync(join(serveDir, "terminals.json"), "utf8")); + assert.equal(owners.owners[id], phone.id); + assert.equal(statSync(join(serveDir, "terminals.json")).mode & 0o777, 0o600); +}); + +test("without a host binary: no terminals capability and 501; PUT /api/term-host installs one", async () => { + const otherRoot = realpathSync(mkdtempSync(join(dirname(root), "gst-"))); + const otherServe = join(otherRoot, "serve"); + const otherAuth = new ServeAuth({ devicesFile: join(otherServe, "devices.json"), adminToken: ADMIN }); + // Only node on PATH: the fake host's `#!/usr/bin/env node` still runs, and nothing named gentle-term-host is found. + const bare = await startServeServer({ ...options({ PATH: dirname(process.execPath) }), auth: otherAuth, serveDir: otherServe }); + try { + const operator = await pairDevice(bare.url, ADMIN, ["sessions:read", "sessions:operate", "terminal"], "op"); + assert.equal((await call(bare.url, "GET", "/api/server", { token: operator.token })).body.capabilities.includes("terminals"), false); + const missing = await call(bare.url, "POST", "/api/terminals", { token: operator.token, body: { cwd: project, cols: 80, rows: 24 } }); + assert.equal(missing.status, 501); + assert.equal(missing.body.error.code, "term_host_missing"); + assert.equal((await call(bare.url, "GET", "/api/term-host", { token: operator.token })).body.available, false); + + const bytes = readFileSync(FAKE_HOST); + const sha = createHash("sha256").update(bytes).digest("hex"); + assert.equal((await call(bare.url, "PUT", "/api/term-host", { token: operator.token, raw: bytes, headers: { "x-sha256": sha } })).status, 403, "admin only"); + assert.equal((await call(bare.url, "PUT", "/api/term-host", { token: ADMIN, raw: bytes })).body.error.code, "invalid_sha256"); + assert.equal((await call(bare.url, "PUT", "/api/term-host", { token: ADMIN, raw: bytes, headers: { "x-sha256": "0".repeat(64) } })).body.error.code, "sha256_mismatch"); + assert.equal(existsSync(join(otherServe, "bin", "gentle-term-host")), false); + const installed = await call(bare.url, "PUT", "/api/term-host", { token: ADMIN, raw: bytes, headers: { "x-sha256": sha } }); + assert.equal(installed.status, 201, JSON.stringify(installed.body)); + assert.equal(installed.body.path, join(otherServe, "bin", "gentle-term-host")); + assert.equal(installed.body.active, true); + assert.equal(statSync(installed.body.path).mode & 0o777, 0o755); + + assert.ok((await call(bare.url, "GET", "/api/server", { token: operator.token })).body.capabilities.includes("terminals")); + const opened = await call(bare.url, "POST", "/api/terminals", { token: operator.token, body: { cwd: project, cols: 80, rows: 24, argv: ECHO } }); + assert.equal(opened.status, 201, JSON.stringify(opened.body)); + } finally { + await bare.close(); + await shutdownHost({ path: join(otherServe, "term.sock") }); + rmSync(otherRoot, { recursive: true, force: true }); + } +}); + +test("the transport and the release asset follow the server's system", () => { + assert.equal(termHostTransport({}, "linux"), "unix"); + assert.equal(termHostTransport({ GENTLE_TERM_HOST_TRANSPORT: "tcp" }, "darwin"), "tcp"); + assert.equal(termHostTransport({}, "win32"), "tcp"); + assert.equal(termHostAsset("linux", "x64"), "gentle-term-host-linux-x64"); + assert.equal(termHostAsset("linux", "arm64"), "gentle-term-host-linux-arm64"); + assert.equal(termHostAsset("darwin", "arm64"), "gentle-term-host-macos-arm64"); + assert.equal(termHostAsset("darwin", "x64"), "gentle-term-host-macos-x64"); + assert.equal(termHostAsset("win32", "x64"), "gentle-term-host-windows-x64.exe"); + assert.equal(termHostAsset("win32", "arm64"), null); + assert.equal(termHostAsset("freebsd", "x64"), null); +}); + +test("over TCP (Windows' transport): a port file with a token, the host reused across restarts and replaced once it died", async (t) => { + const tcpRoot = realpathSync(mkdtempSync(join(dirname(root), "gst-"))); + const tcpServe = join(tcpRoot, "serve"); + const tcpAuth = new ServeAuth({ devicesFile: join(tcpServe, "devices.json"), adminToken: ADMIN }); + const start = () => startServeServer({ ...options({ PATH: process.env.PATH, GENTLE_TERM_HOST: FAKE_HOST, GENTLE_TERM_HOST_TRANSPORT: "tcp" }), auth: tcpAuth, serveDir: tcpServe }); + const portFile = join(tcpServe, "term", "term-host.json"); + const written = () => JSON.parse(readFileSync(portFile, "utf8")) as { port: number; token: string; pid: number }; + let tcpServer = await start(); + // An after hook, not a finally: it also runs when the test times out, so its server cannot keep the run alive. + t.after(async () => { + await tcpServer.close(); + const left = existsSync(portFile) ? written() : undefined; + if (left) await shutdownHost({ port: left.port, token: left.token }); + rmSync(tcpRoot, { recursive: true, force: true }); + }); + const device = await pairDevice(tcpServer.url, ADMIN, ["terminal"], "tcp"); + const opened = await call(tcpServer.url, "POST", "/api/terminals", { token: device.token, body: { cwd: project, cols: 80, rows: 24, argv: ECHO } }); + assert.equal(opened.status, 201, JSON.stringify(opened.body)); + const id = opened.body.terminal.id; + assert.deepEqual(JSON.parse(readFileSync(join(tcpServe, "term", "argv.json"), "utf8")), ["--tcp", "--state-dir", join(tcpServe, "term")]); + assert.equal(existsSync(join(tcpServe, "term.sock")), false); + const first = written(); + assert.equal(statSync(portFile).mode & 0o777, 0o600); + const refused = await HostConnection.open({ port: first.port, token: "not-the-token" }, 2000).then(() => undefined, (error: unknown) => error); + assert.equal((refused as { code?: string } | undefined)?.code, "unauthorized"); + + const live = await stream(tcpServer.url, `/api/terminals/${id}/stream`, device.token); + await live.waitFor("event: attached"); + await live.waitFor(READY); + assert.equal((await call(tcpServer.url, "POST", `/api/terminals/${id}/input`, { token: device.token, body: { data: Buffer.from("hi\n").toString("base64") } })).status, 200); + await live.waitFor(/"data":"ZWNobzpoaQo="/); + live.close(); + const status = (await call(tcpServer.url, "GET", "/api/term-host", { token: device.token })).body; + assert.equal(status.transport, "tcp"); + assert.equal(status.running, true); + assert.equal(status.pid, first.pid); + + // A restarted serve finds the same host through the port file. + await tcpServer.close(); + tcpServer = await start(); + assert.equal((await call(tcpServer.url, "GET", "/api/term-host", { token: device.token })).body.pid, first.pid); + + // A host that died leaves its port file: nothing answers there, so serve starts another. + process.kill(first.pid, "SIGKILL"); + // Another process's exit has no event to await here: poll until it's gone. + for (let i = 0; i < 100; i += 1) { + try { process.kill(first.pid, 0); } catch { break; } + await sleep(20); + } + assert.equal((await call(tcpServer.url, "GET", "/api/terminals", { token: device.token })).status, 200); + const second = written(); + assert.notEqual(second.pid, first.pid); + assert.notEqual(second.token, first.token); + assert.equal((await call(tcpServer.url, "GET", "/api/term-host", { token: device.token })).body.pid, second.pid); +}); diff --git a/tests/serve-test-client.ts b/tests/serve-test-client.ts new file mode 100644 index 000000000..e1fb8c9ef --- /dev/null +++ b/tests/serve-test-client.ts @@ -0,0 +1,200 @@ +// A tiny HTTP client for the `gentle-shell serve` tests: JSON or raw calls, +// SSE streams that collect their text, device pairing, and HTTPS over a pinned +// socket. Plus what keeps those tests from hanging a run: `test`, `before` and +// `after` with a default timeout, and the teardown of tests that start +// sessions: the session keepers (and their Pi) a test leaves running, and +// ending them. + +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { request as httpRequest, type IncomingMessage } from "node:http"; +import { request as httpsRequest } from "node:https"; +import type { Socket } from "node:net"; +import nodeTest, { after as nodeAfter, before as nodeBefore } from "node:test"; +import { setTimeout as sleep } from "node:timers/promises"; +import { fileURLToPath } from "node:url"; +import type { ServeScope } from "../lib/serve-auth.ts"; +import { keeperAlive, readKeeperRecords } from "../lib/serve-session-keeper.ts"; + +/** + * Serve tests run servers, keepers and child processes and wait on their + * streams: a wait that never ends fails the test after this long instead of + * hanging the whole run (a test without a timeout waits forever). A test or + * hook may still pass its own `timeout`. + */ +export const SERVE_TEST_TIMEOUT_MS = 60_000; + +export function test(name: string, fn: nodeTest.TestFn): Promise; +export function test(name: string, options: nodeTest.TestOptions, fn: nodeTest.TestFn): Promise; +export function test(name: string, optionsOrFn: nodeTest.TestOptions | nodeTest.TestFn, fn?: nodeTest.TestFn): Promise { + const [options, body] = typeof optionsOrFn === "function" ? [{}, optionsOrFn] : [optionsOrFn, fn]; + return nodeTest(name, { timeout: SERVE_TEST_TIMEOUT_MS, ...options }, body); +} + +export function before(fn: nodeTest.HookFn, options: nodeTest.HookOptions = {}): void { + nodeBefore(fn, { timeout: SERVE_TEST_TIMEOUT_MS, ...options }); +} + +export function after(fn: nodeTest.HookFn, options: nodeTest.HookOptions = {}): void { + nodeAfter(fn, { timeout: SERVE_TEST_TIMEOUT_MS, ...options }); +} + +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); + +/** A process a test left running. */ +export interface Leftover { pid: number; command: string } + +interface ProcessRow extends Leftover { ppid: number } + +function processTable(): ProcessRow[] { + return execFileSync("ps", ["-axo", "pid=,ppid=,command="], { encoding: "utf8" }).split("\n").flatMap((line) => { + const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line); + return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), command: m[3]! }] : []; + }); +} + +/** + * What a test's serve folders left running: the live keepers their session + * records (`/sessions`) name, the keepers and fake Pis this process + * started itself (a server without a serve folder keeps its records in a + * private temp folder; a keeper run in-process starts its fake Pi here), and + * the Pi each keeper runs, plus every process whose command line names one of + * `roots` (a server daemon, or a fake Pi started with `--home /agent`). + * A keeper is matched by its recorded pid or its parent, and its entry point, + * so a reused pid is never taken for one. Windows has no `ps`: there only + * recorded keepers of running sessions that are alive count. + */ +function serveLeftovers(sessionDirs: readonly string[], roots: readonly string[] = []): Leftover[] { + const records = sessionDirs.flatMap((dir) => readKeeperRecords(dir)); + if (process.platform === "win32") { + return records.filter((record) => record.state === "running" && keeperAlive(record.keeperPid)).map((record) => ({ pid: record.keeperPid, command: `session keeper ${record.id}` })); + } + const recorded = new Set(records.map((record) => record.keeperPid)); + const table = processTable(); + const keepers = new Set(table.filter((row) => (recorded.has(row.pid) || row.ppid === process.pid) && row.command.includes("serve-session-keeper-main")).map((row) => row.pid)); + return table + .filter((row) => row.pid !== process.pid && (keepers.has(row.pid) || keepers.has(row.ppid) || (row.ppid === process.pid && row.command.includes(FAKE_PI)) || roots.some((root) => row.command.includes(root)))) + .map(({ pid, command }) => ({ pid, command })); +} + +/** + * The guard that ends a suite: what `serveLeftovers` still finds once the + * processes on their way out had `graceMs` to go (a keeper exits just after + * its server has seen its session end). + */ +export async function remainingServeLeftovers(sessionDirs: readonly string[], roots: readonly string[] = [], graceMs = 5000): Promise { + const deadline = Date.now() + graceMs; + let leftovers = serveLeftovers(sessionDirs, roots); + while (leftovers.length > 0 && Date.now() < deadline) { + await sleep(50); + leftovers = serveLeftovers(sessionDirs, roots); + } + return leftovers; +} + +/** + * The teardown of tests that start sessions: kills what `serveLeftovers` finds + * and waits until it is gone, so no keeper outlives the run (a keeper with no + * server stops its session only after a day). Returns what it ended. + */ +export async function endServeLeftovers(sessionDirs: readonly string[], roots: readonly string[] = []): Promise { + const leftovers = serveLeftovers(sessionDirs, roots); + for (const { pid } of leftovers) try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } + const deadline = Date.now() + 5000; + while (leftovers.some(({ pid }) => keeperAlive(pid)) && Date.now() < deadline) await sleep(20); + return leftovers; +} + +export interface Reply { status: number; body: any; headers: IncomingMessage["headers"]; bytes: Buffer } + +export function call(base: string, method: string, path: string, options: { token?: string; body?: unknown; raw?: Buffer | string; headers?: Record } = {}): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const payload = options.raw ?? (options.body === undefined ? undefined : JSON.stringify(options.body)); + const req = httpRequest(`${base}${path}`, { + method, + agent: false, + headers: { + ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}), + ...(options.body === undefined ? {} : { "Content-Type": "application/json" }), + ...options.headers, + }, + }, (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => { + const bytes = Buffer.concat(chunks); + let body: unknown = bytes.toString("utf8"); + try { body = JSON.parse(body as string); } catch { /* not JSON */ } + resolve({ status: res.statusCode ?? 0, body, headers: res.headers, bytes }); + }); + }); + req.on("error", reject); + req.end(payload); + return promise; +} + +/** An open SSE stream; `text` grows as events arrive. */ +export interface Stream { status: number; text: string; closed: Promise; waitFor(what: string | RegExp): Promise; close(): void } + +export function stream(base: string, path: string, token?: string, headers: Record = {}): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const req = httpRequest(`${base}${path}`, { agent: false, headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers } }, (res) => { + const closed = Promise.withResolvers(); + const waiters: Array<{ what: string | RegExp; done: () => void }> = []; + const has = (what: string | RegExp) => (typeof what === "string" ? s.text.includes(what) : what.test(s.text)); + const s: Stream = { + status: res.statusCode ?? 0, + text: "", + closed: closed.promise, + waitFor(what) { + if (has(what)) return Promise.resolve(); + const w = Promise.withResolvers(); + waiters.push({ what, done: w.resolve }); + return w.promise; + }, + close: () => req.destroy(), + }; + res.on("data", (c: Buffer) => { + s.text += c.toString("utf8"); + for (const w of [...waiters]) if (has(w.what)) { waiters.splice(waiters.indexOf(w), 1); w.done(); } + }); + res.on("close", () => closed.resolve()); + resolve(s); + }); + req.on("error", (error) => { if (!(error as NodeJS.ErrnoException).code?.startsWith("ECONNRESET")) reject(error); }); + req.end(); + return promise; +} + +export async function pairDevice(base: string, admin: string, scopes: ServeScope[], name = "device"): Promise<{ id: string; token: string }> { + const code = await call(base, "POST", "/api/pairing-codes", { token: admin, body: { scopes } }); + assert.equal(code.status, 201); + const paired = await call(base, "POST", "/api/pair", { body: { code: code.body.code, name } }); + assert.equal(paired.status, 201, JSON.stringify(paired.body)); + return { id: paired.body.id, token: paired.body.token }; +} + +/** One HTTPS request over a connection that is already open and pinned (directly, or through a relay). */ +export function callOver(socket: Socket, method: string, path: string, options: { token?: string; body?: unknown; host?: string; headers?: Record } = {}): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const payload = options.body === undefined ? undefined : JSON.stringify(options.body); + // The Host header as given (host:port included): the request options would bracket a host holding a colon. + const req = httpsRequest({ createConnection: () => socket, method, path, headers: { + Host: options.host ?? "127.0.0.1", + ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}), + ...(payload === undefined ? {} : { "Content-Type": "application/json" }), + ...options.headers, + } }, (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => { + const bytes = Buffer.concat(chunks); + let body: unknown = bytes.toString("utf8"); + try { body = JSON.parse(body as string); } catch { /* not JSON */ } + resolve({ status: res.statusCode ?? 0, body, headers: res.headers, bytes }); + }); + }); + req.on("error", reject); + req.end(payload); + return promise; +} diff --git a/tests/serve-tls.test.ts b/tests/serve-tls.test.ts new file mode 100644 index 000000000..1c6cf34aa --- /dev/null +++ b/tests/serve-tls.test.ts @@ -0,0 +1,299 @@ +import assert from "node:assert/strict"; +import { randomBytes, X509Certificate } from "node:crypto"; +import { mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { createServer as createHttpServer } from "node:http"; +import { connect as netConnect, type Socket } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer as createTlsServer } from "node:tls"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { after, callOver as overSocket, test } from "./serve-test-client.ts"; +import { discoveryReply } from "../lib/serve-discovery.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { certificateFingerprint, connectPinned, createSelfSignedCertificate, createServeListener, ipBytes, isLocalPeer, loadOrCreateServeTls, PAIR_PROOF, pairProof, pairProofKey, + peekFingerprint, serveTlsFiles, verifyPairProof } from "../lib/serve-tls.ts"; + +const ADMIN = "gsa_tls-test-admin"; +const roots: string[] = []; +after(() => roots.forEach((r) => rmSync(r, { recursive: true, force: true }))); +function scratch(): string { + const r = realpathSync(mkdtempSync(join(tmpdir(), "gentle-serve-tls-"))); + roots.push(r); + return r; +} + +function tlsIdentity(root: string) { + return loadOrCreateServeTls(join(root, "serve"), { commonName: "gentle-shell serve test", dnsNames: ["localhost"], ips: ["127.0.0.1", "::1"] }); +} + +async function tlsServer(root: string, extra: Partial[0]> = {}): Promise<{ server: ServeServer; auth: ServeAuth; fingerprint: string }> { + const auth = new ServeAuth({ devicesFile: join(root, "serve", "devices.json"), adminToken: ADMIN }); + const tls = tlsIdentity(root); + const server = await startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", tls, + launchSession: () => { throw new Error("no sessions in these tests"); }, ...extra }); + return { server, auth, fingerprint: tls.fingerprint }; +} + +test("the certificate: self-signed P-256, ten years, CA false, serverAuth, every name and address", () => { + const made = createSelfSignedCertificate({ commonName: "gentle-shell serve box", dnsNames: ["localhost", "Box.local", "box"], ips: ["127.0.0.1", "::1", "192.168.1.20", "[fe80::1%en0]", "::ffff:10.0.0.5", "not-an-ip"] }); + const cert = new X509Certificate(made.der); + assert.equal(cert.subject, "CN=gentle-shell serve box"); + assert.equal(cert.issuer, cert.subject, "self-issued"); + assert.ok(cert.verify(cert.publicKey), "self-signed with its own key"); + assert.equal(cert.publicKey.asymmetricKeyType, "ec"); + assert.equal(cert.publicKey.asymmetricKeyDetails?.namedCurve, "prime256v1"); + assert.equal(cert.ca, false); + assert.deepEqual(cert.keyUsage, ["1.3.6.1.5.5.7.3.1"]); + assert.equal(cert.subjectAltName, "DNS:localhost, DNS:box.local, DNS:box, IP Address:127.0.0.1, IP Address:0:0:0:0:0:0:0:1, IP Address:192.168.1.20, IP Address:FE80:0:0:0:0:0:0:1, IP Address:0:0:0:0:0:FFFF:A00:5"); + assert.equal(cert.checkHost("box.local"), "box.local"); + assert.equal(cert.checkIP("192.168.1.20"), "192.168.1.20"); + const years = (Date.parse(cert.validTo) - Date.parse(cert.validFrom)) / (365.25 * 24 * 3600_000); + assert.ok(years > 9.99 && years < 10.01, String(years)); + assert.ok(Date.parse(cert.validFrom) < Date.now(), "valid from before now (clock skew)"); + assert.ok(!cert.serialNumber.startsWith("0") || cert.serialNumber.length > 1); + assert.match(made.keyPem, /^-----BEGIN PRIVATE KEY-----\n/); + assert.equal(new X509Certificate(made.certPem).fingerprint256, cert.fingerprint256, "the PEM is the same certificate"); + // The fingerprint is base64url SHA-256 of the DER: the colon-hex form Node prints, re-encoded. + assert.equal(certificateFingerprint(made.der), Buffer.from(cert.fingerprint256.replace(/:/g, ""), "hex").toString("base64url")); + // Validity past 2049 switches to GeneralizedTime. + const late = new X509Certificate(createSelfSignedCertificate({ commonName: "late", dnsNames: [], ips: [], now: new Date("2045-06-01T00:00:00Z") }).der); + assert.equal(new Date(late.validTo).getUTCFullYear(), 2055); +}); + +test("IP literals to SAN bytes", () => { + assert.deepEqual(ipBytes("10.1.2.3"), Buffer.from([10, 1, 2, 3])); + assert.equal(ipBytes("::1")?.toString("hex"), "00000000000000000000000000000001"); + assert.equal(ipBytes("2001:db8::8a2e:370:7334")?.toString("hex"), "20010db80000000000008a2e03707334"); + assert.equal(ipBytes("[fe80::1%en0]")?.toString("hex"), "fe800000000000000000000000000001"); + assert.equal(ipBytes("::ffff:192.168.1.1")?.toString("hex"), "00000000000000000000ffffc0a80101"); + assert.equal(ipBytes("box.local"), undefined); +}); + +test("made once in /serve/tls, owner-only, and kept across runs; an unusable one is replaced", () => { + const root = scratch(); + const first = tlsIdentity(root); + assert.equal(first.created, true); + const files = serveTlsFiles(join(root, "serve")); + if (process.platform !== "win32") { + assert.equal(statSync(files.dir).mode & 0o777, 0o700); + assert.equal(statSync(files.key).mode & 0o777, 0o600); + assert.equal(statSync(files.cert).mode & 0o777, 0o600); + } + const second = tlsIdentity(root); + assert.equal(second.created, false); + assert.equal(second.fingerprint, first.fingerprint, "the same certificate: paired devices keep their pin"); + // A key that does not match the certificate is not used. + writeFileSync(files.key, createSelfSignedCertificate({ commonName: "other", dnsNames: [], ips: [] }).keyPem); + const third = tlsIdentity(root); + assert.equal(third.created, true); + assert.notEqual(third.fingerprint, first.fingerprint); + assert.equal(readFileSync(files.key, "utf8"), third.keyPem); + // One near its end is replaced at start. + assert.equal(loadOrCreateServeTls(join(root, "serve"), { commonName: "x", dnsNames: [], ips: [] }, () => Date.now() + 10 * 365.25 * 24 * 3600_000).created, true); +}); + +test("which peers may use plain HTTP: this machine only", () => { + assert.equal(isLocalPeer({ remoteAddress: "127.0.0.1", localAddress: "127.0.0.1" }), true); + assert.equal(isLocalPeer({ remoteAddress: "::ffff:127.0.0.1", localAddress: "::ffff:127.0.0.1" }), true); + assert.equal(isLocalPeer({ remoteAddress: "::1", localAddress: "::1" }), true); + assert.equal(isLocalPeer({ remoteAddress: "192.168.1.20", localAddress: "192.168.1.20" }), true, "this machine through its own LAN address"); + assert.equal(isLocalPeer({ remoteAddress: "::ffff:192.168.1.30", localAddress: "::ffff:192.168.1.20" }), false); + assert.equal(isLocalPeer({ remoteAddress: undefined, localAddress: "192.168.1.20" }), false); +}); + +test("discovery replies carry tls and the fingerprint only when the server has one", () => { + assert.deepEqual(JSON.parse(discoveryReply({ id: "srv_1", name: "box", port: 8787 }).toString()), { t: "gentle-shell/here", v: 1, id: "srv_1", n: "box", p: 8787 }); + assert.deepEqual(JSON.parse(discoveryReply({ id: "srv_1", name: "box", port: 8787, fingerprint: "F".repeat(43) }).toString()), + { t: "gentle-shell/here", v: 1, id: "srv_1", n: "box", p: 8787, tls: true, fp: "F".repeat(43) }); +}); + +test("the pairing proof: scrypt key, HMAC over fingerprint and nonce, exact numbers", async () => { + const fp = randomBytes(32); + const nonce = randomBytes(16); + // Normalization: case, separators and O/I/L are the same code. + const key = await pairProofKey("abcd-efgh", fp); + assert.deepEqual(key, await pairProofKey("ABCDEFGH", fp)); + assert.deepEqual(await pairProofKey("0111-2222", fp), await pairProofKey("oIl1-2222", fp)); + const proof = pairProof(key, fp, nonce).toString("base64url"); + assert.equal(await verifyPairProof({ code: "ABCD-EFGH", fingerprint: fp.toString("base64url"), nonce, proofs: ["junk", proof] }), true); + assert.equal(await verifyPairProof({ code: "ABCD-EFGX", fingerprint: fp.toString("base64url"), nonce, proofs: [proof] }), false, "another code"); + assert.equal(await verifyPairProof({ code: "ABCD-EFGH", fingerprint: randomBytes(32).toString("base64url"), nonce, proofs: [proof] }), false, "another certificate"); + assert.equal(await verifyPairProof({ code: "ABCD-EFGH", fingerprint: fp.toString("base64url"), nonce: randomBytes(16), proofs: [proof] }), false, "another nonce"); + // A known-answer vector a client in another language can check itself against. + const vectorFp = Buffer.alloc(32, 0x11); + const vectorKey = await pairProofKey("7PH3-DM9V", vectorFp); + assert.equal(vectorKey.length, PAIR_PROOF.keyBytes); + assert.deepEqual(PAIR_PROOF, { salt: "gentle-shell/pair-proof/v1", N: 32768, r: 8, p: 1, keyBytes: 32, nonceMinBytes: 16, nonceMaxBytes: 64, perWindow: 20, windowMs: 60_000 }); + const vector = pairProof(vectorKey, vectorFp, Buffer.alloc(16, 0x22)).toString("base64url"); + assert.equal(vector, VECTOR_PROOF, `key ${vectorKey.toString("hex")}`); +}); + +/** key = scrypt("7PH3DM9V", "gentle-shell/pair-proof/v1" || 32×0x11) = 59ff303c…1c5255; proof = HMAC(key, 32×0x11 || 16×0x22); also in docs/serve.md. */ +const VECTOR_PROOF = "fVUUvh7KIXU0NWi6IYymHsCbVNxnxvrPSpB9O0h_XKs"; + +test("HTTPS with a pinned fingerprint; plain HTTP stays for this machine; a different certificate fails the pin", async (t) => { + const root = scratch(); + const { server, fingerprint } = await tlsServer(root); + t.after(() => server.close()); + assert.equal(server.fingerprint, fingerprint); + assert.match(server.url, /^http:\/\/127\.0\.0\.1:\d+$/, "the local URL stays plain"); + const target = { host: "127.0.0.1", port: server.port }; + + const identity = await overSocket(await connectPinned(target, fingerprint), "GET", "/.well-known/gentle-shell", { host: `127.0.0.1:${server.port}` }); + assert.equal(identity.status, 200); + assert.equal(identity.body.tls, true); + assert.equal(identity.body.fp, fingerprint); + // The same port answers plain HTTP from this machine (the CLI, a local app). + const plain = await fetch(`${server.url}/.well-known/gentle-shell`); + assert.equal((await plain.json()).fp, fingerprint); + // An admin token over TLS: /api/server names the certificate too. + const info = await overSocket(await connectPinned(target, fingerprint), "GET", "/api/server", { host: `127.0.0.1:${server.port}`, token: ADMIN }); + assert.deepEqual(info.body.tls, { fingerprint }); + // Origin: this server's own, over either scheme. + assert.equal((await overSocket(await connectPinned(target, fingerprint), "GET", "/.well-known/gentle-shell", { host: `127.0.0.1:${server.port}`, headers: { Origin: `https://127.0.0.1:${server.port}` } })).status, 200); + assert.equal((await overSocket(await connectPinned(target, fingerprint), "GET", "/.well-known/gentle-shell", { host: `127.0.0.1:${server.port}`, headers: { Origin: "https://evil.example" } })).status, 403); + // The Host check still applies over TLS. + assert.equal((await overSocket(await connectPinned(target, fingerprint), "GET", "/.well-known/gentle-shell", { host: "evil.example" })).status, 421); + + // A man in the middle with its own certificate: the pinned client stops before sending a byte. + const mitm = createSelfSignedCertificate({ commonName: "gentle-shell serve test", dnsNames: ["localhost"], ips: ["127.0.0.1"] }); + const seenByMitm: Buffer[] = []; + const accepted: Socket[] = []; + const proxy = createTlsServer({ key: mitm.keyPem, cert: mitm.certPem }, (inner) => { + accepted.push(inner); + inner.on("data", (chunk: Buffer) => seenByMitm.push(chunk)); + inner.on("error", () => inner.destroy()); + }); + await new Promise((resolve) => proxy.listen(0, "127.0.0.1", resolve)); + t.after(() => { + for (const socket of accepted) socket.destroy(); + proxy.close(); + }); + const proxyPort = (proxy.address() as { port: number }).port; + await assert.rejects(connectPinned({ host: "127.0.0.1", port: proxyPort }, fingerprint), (error: Error & { code?: string; seen?: string }) => { + assert.equal(error.code, "fingerprint_mismatch"); + assert.equal(error.seen, certificateFingerprint(mitm.der)); + return true; + }); + // The client rejected the certificate before writing anything, so the + // impostor has seen no bytes; waiting for its socket to notice adds nothing. + assert.equal(Buffer.concat(seenByMitm).length, 0, "nothing was sent to the impostor"); +}); + +test("a network peer that speaks plain HTTP is told to use HTTPS", async (t) => { + const root = scratch(); + const tls = tlsIdentity(root); + const listener = createServeListener({ tls, setup: (http) => http.on("request", (_req, res) => res.end("ok")) }); + await new Promise((resolve) => listener.server.listen(0, "127.0.0.1", resolve)); + t.after(() => { listener.server.close(); listener.closeAllConnections(); }); + // Forge the peer address a remote client would have. + const socketFromElsewhere = netConnect({ host: "127.0.0.1", port: (listener.server.address() as { port: number }).port }); + listener.server.prependOnceListener("connection", (socket: Socket) => { + Object.defineProperty(socket, "remoteAddress", { value: "192.168.1.30" }); + }); + const answer = await new Promise((resolve) => { + let text = ""; + socketFromElsewhere.on("data", (c) => { text += c.toString(); }); + socketFromElsewhere.on("close", () => resolve(text)); + socketFromElsewhere.write("GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + }); + assert.match(answer, /^HTTP\/1\.1 400 Bad Request\r\n/); + assert.match(answer, /"code":"tls_required"/); +}); + +test("pairing after discovery: the proof binds the code to the certificate seen; a man in the middle cannot pass it", async (t) => { + const root = scratch(); + const { server, auth, fingerprint } = await tlsServer(root); + t.after(() => server.close()); + const target = { host: "127.0.0.1", port: server.port }; + const host = `127.0.0.1:${server.port}`; + const proofOf = async (via: { host: string; port: number }, nonce: Buffer) => { + const seen = await peekFingerprint(via); + const reply = await overSocket(seen.socket, "POST", "/api/pair/proof", { host, body: { nonce: nonce.toString("base64url") } }); + return { seen: seen.fingerprint, reply }; + }; + + const none = await proofOf(target, randomBytes(16)); + assert.equal(none.reply.status, 200); + assert.deepEqual(none.reply.body, { proofs: [] }, "no live code, no proof"); + + const minted = auth.mintPairingCode(); + auth.mintPairingCode(); + const nonce = randomBytes(24); + const direct = await proofOf(target, nonce); + assert.equal(direct.seen, fingerprint); + assert.equal(direct.reply.body.proofs.length, 2, "one proof per live code"); + assert.equal(await verifyPairProof({ code: minted.code, fingerprint: direct.seen, nonce, proofs: direct.reply.body.proofs }), true); + assert.equal(await verifyPairProof({ code: "ZZZZ-ZZZZ", fingerprint: direct.seen, nonce, proofs: direct.reply.body.proofs }), false); + + // A man in the middle: terminates TLS with its own certificate and relays the HTTP to the real server. + const mitm = createSelfSignedCertificate({ commonName: "evil", dnsNames: [], ips: ["127.0.0.1"] }); + const proxy = createTlsServer({ key: mitm.keyPem, cert: mitm.certPem }, async (inner) => { + inner.on("error", () => inner.destroy()); + const outer = await connectPinned(target, fingerprint); + inner.pipe(outer).pipe(inner); + }); + await new Promise((resolve) => proxy.listen(0, "127.0.0.1", resolve)); + t.after(() => proxy.close()); + const relayed = await proofOf({ host: "127.0.0.1", port: (proxy.address() as { port: number }).port }, nonce); + assert.equal(relayed.reply.status, 200, "the real server answered through the proxy"); + assert.notEqual(relayed.seen, fingerprint); + assert.equal(await verifyPairProof({ code: minted.code, fingerprint: relayed.seen, nonce, proofs: relayed.reply.body.proofs }), false, + "the proofs name the real certificate, not the one the client saw: the client keeps its code"); + + // Then the code goes to the pinned server, which pairs as before. + const paired = await overSocket(await connectPinned(target, fingerprint), "POST", "/api/pair", { host, body: { code: minted.code, name: "phone" } }); + assert.equal(paired.status, 201); + assert.match(paired.body.token, /^gss_/); + const live = await proofOf(target, nonce); + assert.equal(live.reply.body.proofs.length, 1, "the used code has no proof any more"); + + // Nonces: 16-64 bytes of base64url. + for (const bad of ["", "short", randomBytes(8).toString("base64url"), randomBytes(65).toString("base64url"), "not base64url!"]) { + const reply = await overSocket(await connectPinned(target, fingerprint), "POST", "/api/pair/proof", { host, body: { nonce: bad } }); + assert.equal(reply.status, 400, bad); + assert.equal(reply.body.error.code, "invalid_nonce"); + } + assert.equal((await overSocket(await connectPinned(target, fingerprint), "GET", "/api/pair/proof", { host })).status, 405); + // 20 proofs a minute across callers (this test used 4 of them so far). + const codes: number[] = []; + for (let i = 0; i < 17; i += 1) codes.push((await overSocket(await connectPinned(target, fingerprint), "POST", "/api/pair/proof", { host, body: { nonce: randomBytes(16).toString("base64url") } })).status); + assert.deepEqual(codes.slice(0, 16), Array(16).fill(200)); + assert.equal(codes[16], 429); +}); + +test("a plain server has no proof to give", async (t) => { + const root = scratch(); + const auth = new ServeAuth({ devicesFile: join(root, "devices.json"), adminToken: ADMIN }); + const server = await startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", launchSession: () => { throw new Error("none"); } }); + t.after(() => server.close()); + const reply = await fetch(`${server.url}/api/pair/proof`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ nonce: randomBytes(16).toString("base64url") }) }); + assert.equal(reply.status, 501); + assert.equal(server.fingerprint, undefined); + await assert.rejects(startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", relay: { url: "gsr://127.0.0.1:1" }, launchSession: () => { throw new Error("none"); } }), /a relay needs TLS/); +}); + +test("forwards speak TLS with the same certificate and link over https", async (t) => { + const root = scratch(); + const page = createHttpServer((req, res) => res.end(`page ${req.url}`)); + await new Promise((resolve) => page.listen(0, "127.0.0.1", resolve)); + t.after(() => page.close()); + const pagePort = (page.address() as { port: number }).port; + const { server, fingerprint } = await tlsServer(root); + t.after(() => server.close()); + const host = `127.0.0.1:${server.port}`; + const opened = await overSocket(await connectPinned({ host: "127.0.0.1", port: server.port }, fingerprint), "POST", "/api/forwards", { host, token: ADMIN, body: { port: pagePort, path: "/hello" } }); + assert.equal(opened.status, 201, JSON.stringify(opened.body)); + const link = new URL(opened.body.url); + assert.equal(link.protocol, "https:", "a link reached over TLS is https"); + const forwardTarget = { host: "127.0.0.1", port: Number(link.port) }; + const first = await overSocket(await connectPinned(forwardTarget, fingerprint), "GET", `${link.pathname}${link.search}`, { host: `127.0.0.1:${link.port}` }); + assert.equal(first.status, 303); + const cookie = String(first.headers["set-cookie"]).split(";")[0]; + const shown = await overSocket(await connectPinned(forwardTarget, fingerprint), "GET", "/hello", { host: `127.0.0.1:${link.port}`, headers: { Cookie: cookie } }); + assert.equal(shown.status, 200); + assert.equal(shown.body, "page /hello"); + // Over plain HTTP from this machine, the link is http. + const local = await fetch(`${server.url}/api/forwards`, { method: "POST", headers: { Authorization: `Bearer ${ADMIN}`, "Content-Type": "application/json" }, body: JSON.stringify({ port: pagePort }) }); + assert.match((await local.json()).url, /^http:\/\//); +}); diff --git a/tests/serve-upgrade.test.ts b/tests/serve-upgrade.test.ts new file mode 100644 index 000000000..9f2bd0d28 --- /dev/null +++ b/tests/serve-upgrade.test.ts @@ -0,0 +1,368 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { parseServeArgs, readServerFile, runServeCommand, SERVE_RESTART_EXIT, serveFiles, setupLaunch, supervisedServe, upgradeLaunch } from "../lib/serve-cli.ts"; +import { desktopMethodScope, startServeServer, type ServeServer, type ServeServerOptions } from "../lib/serve-server.ts"; +import { keeperAlive, type KeeperRecord } from "../lib/serve-session-keeper.ts"; +import { upgradeLines } from "../lib/serve-upgrade.ts"; +import { after, call, endServeLeftovers, pairDevice, remainingServeLeftovers, stream, test } from "./serve-test-client.ts"; + +// `POST /api/upgrade`: the server runs the upgrade command (a fake one here: +// no npm, no network), streams its output to admin clients, and on success +// restarts on the new version while its sessions keep running. + +const FAKE_PI = fileURLToPath(new URL("./fixtures/serve-fake-pi.mjs", import.meta.url)); +const BIN = fileURLToPath(new URL("../bin/gentle-shell.mjs", import.meta.url)); +const ADMIN = "gsa_test-admin-token"; +const roots: string[] = []; +// Sessions of in-process servers keep their records in `/serve`, the CLI's in `/agent/serve`. +const sessionDirs = () => roots.flatMap((root) => [join(root, "serve", "sessions"), join(serveFiles(join(root, "agent")).dir, "sessions")]); +after(async () => { + // A failed test must not leave a keeper, its fake Pi, or a restarted server behind. + await endServeLeftovers(sessionDirs(), roots); + roots.forEach((root) => rmSync(root, { recursive: true, force: true })); +}); + +function scratch(): string { + const root = realpathSync(mkdtempSync(join(tmpdir(), "gs-upg-"))); + roots.push(root); + return root; +} + +/** A stand-in for `gentle-shell upgrade`: colored progress, then success, or a failure on stderr, or a wait. */ +function fakeUpgrade(root: string): string { + const script = join(root, "fake-upgrade.mjs"); + writeFileSync(script, [ + "const args = process.argv.slice(2);", + "process.stdout.write('\\u001b[1mChecking the release channel\\u001b[0m\\n');", + "process.stdout.write('args ' + JSON.stringify(args) + '\\n');", + "if (args.includes('fail')) { process.stderr.write('npm ERR! network\\ngentle-shell upgrade: could not reach the registry\\n'); process.exit(1); }", + "if (args.includes('wait')) { process.stdin.resume(); setTimeout(() => { process.stdout.write('Upgraded Gentle Shell to 9.9.9\\n'); }, 300); }", + "else process.stdout.write('Upgraded Gentle Shell to 9.9.9\\n');", + ].join("\n")); + return script; +} + +function serve(root: string, upgrade: ServeServerOptions["upgrade"], version = "1.0.0"): Promise { + const serveDir = join(root, "serve"); + return startServeServer({ + host: "127.0.0.1", + port: 0, + auth: new ServeAuth({ devicesFile: join(serveDir, "devices.json"), adminToken: ADMIN }), + version, + serveDir, + launchSession: (input) => ({ command: process.execPath, args: [FAKE_PI], cwd: input.cwd, env: { ...process.env, GENTLE_SHELL_INTERACTIVE_HOST: "1" } }), + limits: { rpcTimeoutMs: 3000 }, + ...(upgrade === undefined ? {} : { upgrade }), + }); +} + +function events(text: string): Array<{ event: string; data: Record }> { + return text.split("\n\n").flatMap((block) => { + const event = /^event: (.+)$/m.exec(block); + const data = /^data: (.*)$/m.exec(block); + return event && data ? [{ event: event[1]!, data: JSON.parse(data[1]!) }] : []; + }); +} + +test("an admin upgrades the server: lines, finished, then a restart that keeps the sessions running", { timeout: 30_000 }, async () => { + const root = scratch(); + const script = fakeUpgrade(root); + const restarted = Promise.withResolvers(); + const channels: Array = []; + const upgrade: ServeServerOptions["upgrade"] = { + launch: (channel) => { + channels.push(channel); + return { command: process.execPath, args: [script, ...(channel === "main" ? ["wait"] : [])], cwd: root, env: process.env }; + }, + installedVersion: () => "9.9.9", + onUpgraded: () => restarted.resolve(), + }; + const first = await serve(root, upgrade); + let second: ServeServer | undefined; + try { + const info = await call(first.url, "GET", "/api/server", { token: ADMIN }); + assert.ok(info.body.capabilities.includes("upgrade")); + const created = await call(first.url, "POST", "/api/sessions", { token: ADMIN, body: { cwd: realpathSync(root) } }); + assert.equal(created.status, 201, JSON.stringify(created.body)); + const sessionId = created.body.session.id; + const record = JSON.parse(readFileSync(join(root, "serve", "sessions", `${sessionId}.json`), "utf8")) as KeeperRecord; + // The control session behind `/api/desktop` runs the old version's code. + assert.equal((await call(first.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "capabilities" } })).status, 200); + const oldControl = (await call(first.url, "GET", "/api/sessions?includeControl=1", { token: ADMIN })).body.sessions.find((s: { control?: boolean }) => s.control)?.id as string; + assert.ok(oldControl); + + // Only an admin token; a known channel only. + const device = await pairDevice(first.url, ADMIN, ["sessions:read", "sessions:operate", "terminal"]); + assert.equal((await call(first.url, "POST", "/api/upgrade", { token: device.token, body: {} })).status, 403); + const bad = await call(first.url, "POST", "/api/upgrade", { token: ADMIN, body: { channel: "nightly" } }); + assert.deepEqual([bad.status, bad.body.error.code], [400, "invalid_request"]); + + const started = await call(first.url, "POST", "/api/upgrade", { token: ADMIN, body: { channel: "main" } }); + assert.equal(started.status, 202); + assert.match(started.body.jobId, /^upg_[0-9a-f]{16}$/); + const busy = await call(first.url, "POST", "/api/upgrade", { token: ADMIN, body: {} }); + assert.deepEqual([busy.status, busy.body.error.code], [409, "upgrade_running"]); + assert.equal((await call(first.url, "GET", `/api/upgrade/${started.body.jobId}/stream`, { token: device.token })).status, 403); + + const live = await stream(first.url, `/api/upgrade/${started.body.jobId}/stream`, ADMIN); + assert.equal(live.status, 200); + await live.closed; + assert.deepEqual(events(live.text), [ + { event: "line", data: { line: "Checking the release channel" } }, + { event: "line", data: { line: 'args ["wait"]' } }, + { event: "line", data: { line: "Upgraded Gentle Shell to 9.9.9" } }, + { event: "finished", data: { ok: true, version: "9.9.9" } }, + ]); + assert.deepEqual(channels, ["main"]); + // A late stream replays the job and its end. + const late = await stream(first.url, `/api/upgrade/${started.body.jobId}/stream`, ADMIN); + await late.closed; + assert.deepEqual(events(late.text).at(-1), { event: "finished", data: { ok: true, version: "9.9.9" } }); + assert.equal((await call(first.url, "GET", "/api/upgrade/upg_0000000000000000/stream", { token: ADMIN })).status, 404); + + // The owner restarts: this server closes, keeping its sessions, and the upgraded one reattaches them. + await restarted.promise; + await first.close(); + assert.ok(keeperAlive(record.keeperPid), "the session's keeper outlives the server"); + second = await serve(root, upgrade, "9.9.9"); + const after = await call(second.url, "GET", "/api/server", { token: ADMIN }); + assert.equal(after.body.version, "9.9.9"); + assert.equal(after.body.serverId, info.body.serverId, "the same server identity"); + const listed = await call(second.url, "GET", "/api/sessions", { token: ADMIN }); + assert.equal(listed.body.sessions.find((s: { id: string }) => s.id === sessionId)?.state, "running", "the same session, still running"); + const state = await call(second.url, "POST", `/api/sessions/${sessionId}/rpc`, { token: ADMIN, body: { type: "get_state" } }); + assert.equal(state.status, 200); + // The control session is not: the upgraded server answers `/api/desktop` from a fresh one, on its own code. + assert.equal((await call(second.url, "POST", "/api/desktop", { token: ADMIN, body: { method: "capabilities" } })).status, 200); + const newControl = (await call(second.url, "GET", "/api/sessions?includeControl=1", { token: ADMIN })).body.sessions.find((s: { control?: boolean }) => s.control)?.id as string; + assert.ok(newControl && newControl !== oldControl, "a fresh control session after the upgrade"); + } finally { + await first.close().catch(() => undefined); + await second?.close({ endSessions: true }); + } +}); + +test("a failed upgrade reports the command's last word and does not restart; another may start", { timeout: 30_000 }, async () => { + const root = scratch(); + const script = fakeUpgrade(root); + let upgraded = 0; + const server = await serve(root, { + launch: () => ({ command: process.execPath, args: [script, "fail"], cwd: root, env: process.env }), + onUpgraded: () => { upgraded += 1; }, + limits: { restartDelayMs: 0 }, + }); + try { + const { body: { jobId } } = await call(server.url, "POST", "/api/upgrade", { token: ADMIN }); + const live = await stream(server.url, `/api/upgrade/${jobId}/stream`, ADMIN); + await live.closed; + assert.deepEqual(events(live.text).at(-1), { event: "finished", data: { ok: false, error: "gentle-shell upgrade: could not reach the registry" } }); + assert.equal(upgraded, 0); + assert.equal((await call(server.url, "POST", "/api/upgrade", { token: ADMIN })).status, 202, "a finished upgrade does not block the next"); + } finally { + await server.close({ endSessions: true }); + } +}); + +test("a server without an upgrade command has no upgrade capability and answers 501", { timeout: 30_000 }, async () => { + const root = scratch(); + const server = await serve(root, undefined); + try { + assert.equal((await call(server.url, "GET", "/api/server", { token: ADMIN })).body.capabilities.includes("upgrade"), false); + assert.equal((await call(server.url, "POST", "/api/upgrade", { token: ADMIN })).status, 501); + } finally { + await server.close({ endSessions: true }); + } +}); + +/** A stand-in for `gentle-shell setup`: progress, then success, or a failure on stderr; `wait` holds it open. */ +function fakeSetup(root: string): string { + const script = join(root, "fake-setup.mjs"); + writeFileSync(script, [ + "const args = process.argv.slice(2);", + "process.stdout.write('\\u001b[1mInstalling companion packages\\u001b[0m\\n');", + "if (args.includes('fail')) { process.stderr.write('gentle-shell setup: npm install failed\\n'); process.exit(1); }", + "if (args.includes('wait')) { process.stdin.resume(); setTimeout(() => { process.stdout.write('Setup complete\\n'); process.exit(0); }, 400); }", + "else process.stdout.write('Setup complete\\n');", + ].join("\n")); + return script; +} + +test("an admin runs setup on the server: lines, finished, no restart; one job at a time with the upgrade", { timeout: 30_000 }, async () => { + const root = scratch(); + const setup = fakeSetup(root); + const upgradeScript = fakeUpgrade(root); + let upgraded = 0; + let mode = "wait"; + const server = await serve(root, { + launch: () => ({ command: process.execPath, args: [upgradeScript, "wait"], cwd: root, env: process.env }), + onUpgraded: () => { upgraded += 1; }, + setup: () => ({ command: process.execPath, args: [setup, mode], cwd: root, env: process.env }), + limits: { restartDelayMs: 0 }, + }); + try { + const info = (await call(server.url, "GET", "/api/server", { token: ADMIN })).body; + assert.ok(info.capabilities.includes("setup")); + // Config files are reached through Desktop RPC config stores, never by path: only the user's home is named. + assert.deepEqual(["agentHome" in info, "paths" in info, typeof info.home], [false, false, "string"]); + const device = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"]); + assert.equal((await call(server.url, "POST", "/api/setup", { token: device.token, body: {} })).status, 403); + assert.equal((await call(server.url, "POST", "/api/setup", { token: ADMIN, body: { force: true } })).status, 400); + const started = await call(server.url, "POST", "/api/setup", { token: ADMIN, body: {} }); + assert.equal(started.status, 202); + assert.match(started.body.jobId, /^setup_[0-9a-f]{16}$/); + const busy = await call(server.url, "POST", "/api/upgrade", { token: ADMIN, body: {} }); + assert.deepEqual([busy.status, busy.body.error.code], [409, "setup_running"]); + assert.deepEqual((await call(server.url, "POST", "/api/setup", { token: ADMIN })).body.error.code, "setup_running"); + assert.equal((await call(server.url, "GET", `/api/setup/${started.body.jobId}/stream`, { token: device.token })).status, 403); + const live = await stream(server.url, `/api/setup/${started.body.jobId}/stream`, ADMIN); + await live.closed; + assert.deepEqual(events(live.text), [ + { event: "line", data: { line: "Installing companion packages" } }, + { event: "line", data: { line: "Setup complete" } }, + { event: "finished", data: { ok: true } }, + ]); + assert.equal((await call(server.url, "GET", "/api/setup/setup_0000000000000000/stream", { token: ADMIN })).status, 404); + assert.equal(upgraded, 0, "setup never restarts the server"); + mode = "fail"; + const failed = await call(server.url, "POST", "/api/setup", { token: ADMIN }); + assert.equal(failed.status, 202, "a finished setup does not block the next"); + const failure = await stream(server.url, `/api/setup/${failed.body.jobId}/stream`, ADMIN); + await failure.closed; + assert.deepEqual(events(failure.text).at(-1), { event: "finished", data: { ok: false, error: "gentle-shell setup: npm install failed" } }); + const upgrading = await call(server.url, "POST", "/api/upgrade", { token: ADMIN }); + assert.equal(upgrading.status, 202); + assert.deepEqual((await call(server.url, "POST", "/api/setup", { token: ADMIN })).body.error.code, "upgrade_running"); + assert.equal((await call(server.url, "GET", `/api/setup/${upgrading.body.jobId}/stream`, { token: ADMIN })).status, 404, "an upgrade's id is not a setup stream"); + } finally { + await server.close({ endSessions: true }); + } +}); + +test("a server without a setup command has no setup capability and answers 501", { timeout: 30_000 }, async () => { + const root = scratch(); + const server = await serve(root, { launch: () => ({ command: process.execPath, args: ["-e", ""], cwd: root, env: process.env }), onUpgraded: () => {} }); + try { + assert.equal((await call(server.url, "GET", "/api/server", { token: ADMIN })).body.capabilities.includes("setup"), false); + assert.equal((await call(server.url, "POST", "/api/setup", { token: ADMIN })).status, 501); + } finally { + await server.close({ endSessions: true }); + } +}); + +test("the CLI's upgrade is this launcher's `upgrade`, and a service manager restarts a supervised server", () => { + const launch = upgradeLaunch({ launcher: "/pkg/bin/gentle-shell.mjs", nodePath: "/node", env: { PATH: "/bin", GENTLE_SHELL_INTERACTIVE_HOST: "1" } }, "main"); + assert.equal(launch.command, "/node"); + assert.deepEqual(launch.args, ["/pkg/bin/gentle-shell.mjs", "upgrade", "--channel", "main"]); + assert.equal(launch.env.GENTLE_SHELL_INTERACTIVE_HOST, undefined); + assert.equal(launch.env.NO_COLOR, "1"); + assert.deepEqual(upgradeLaunch({ launcher: "/l", nodePath: "/n", env: {} }, undefined).args, ["/l", "upgrade"]); + const setup = setupLaunch({ launcher: "/l", nodePath: "/n", homeFlags: ["--home", "/srv/agent"], env: { GENTLE_SHELL_INTERACTIVE_HOST: "1" } }); + assert.deepEqual(setup.args, ["/l", "--home", "/srv/agent", "setup"], "the server's own home"); + assert.equal(setup.env.GENTLE_SHELL_INTERACTIVE_HOST, undefined); + assert.equal(supervisedServe({ SYSTEMD_EXEC_PID: "4242" }, 4242), true); + assert.equal(supervisedServe({ SYSTEMD_EXEC_PID: "1" }, 4242), false, "an inherited variable from another unit's process"); + assert.equal(supervisedServe({ XPC_SERVICE_NAME: "com.gentle-shell.serve" }), true); + assert.equal(supervisedServe({ XPC_SERVICE_NAME: "com.apple.Terminal" }), false); + assert.deepEqual(upgradeLines("\u001b[32mok\u001b[0m\r\n\n\u0007x"), ["ok", "x"]); + // Desktop RPC through `/desktop`: sign-in, keys and package jobs operate; the package list reads. + for (const method of ["login_start", "login_complete", "login_cancel", "set_api_key", "remove_credentials", "install_package", "remove_package"]) assert.equal(desktopMethodScope(method), "sessions:operate"); + assert.equal(desktopMethodScope("list_packages"), "sessions:read"); +}); + +function isolatedEnv(root: string): NodeJS.ProcessEnv { + return { HOME: root, USERPROFILE: root, PATH: process.env.PATH, GENTLE_SHELL_NO_AUTO_SETUP: "1" }; +} + +test("gentle-shell serve restarts itself after an upgrade: the next server takes the same address and identity", { timeout: 60_000 }, async () => { + const root = scratch(); + const home = join(root, "agent"); + const script = fakeUpgrade(root); + const files = serveFiles(home); + const args = parseServeArgs(["--foreground"]); + assert.ok(!("error" in args)); + let output = ""; + const ctx = { + agentHome: home, + homeFlags: ["--home", home], + launcher: BIN, + nodePath: process.execPath, + version: "1.0.0", + env: isolatedEnv(root), + stdout: (text: string) => { output += text; }, + stderr: (text: string) => { output += text; }, + untilStopped: (stopRequested: Promise) => stopRequested, + upgradeCommand: () => ({ command: process.execPath, args: [script], cwd: root, env: process.env }), + }; + const running = runServeCommand(args, ctx); + const deadline = Date.now() + 15_000; + while (readServerFile(files.server)?.pid !== process.pid) { + if (Date.now() > deadline) throw new Error(`the server did not start: ${output}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + const before = readServerFile(files.server)!; + const started = await call(before.url, "POST", "/api/upgrade", { token: before.adminToken }); + assert.equal(started.status, 202); + assert.equal(await running, 0, output); + assert.match(output, /restarted on the upgraded version as pid (\d+)/); + const pid = Number(/as pid (\d+)/.exec(output)![1]); + + let next = readServerFile(files.server); + while (next?.pid !== pid) { + if (Date.now() > deadline + 15_000) throw new Error(`the restarted server did not come up: ${readFileSync(files.log, "utf8")}`); + await new Promise((resolve) => setTimeout(resolve, 50)); + next = readServerFile(files.server); + } + assert.equal(next.url, before.url, "the same address"); + assert.equal(next.serverId, before.serverId, "the same identity"); + const info = await call(next.url, "GET", "/api/server", { token: next.adminToken }); + assert.equal(info.status, 200); + assert.equal(info.body.version, JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version, "the installed version answers"); + // The restarted server is this test's child: stopping it must not block the loop that reaps it. + const stopper = spawn(process.execPath, [BIN, "--home", home, "serve", "stop"], { env: isolatedEnv(root), stdio: ["ignore", "ignore", "pipe"] }); + let stopErr = ""; + stopper.stderr.on("data", (chunk) => { stopErr += chunk; }); + const { promise: stopped, resolve: stopDone } = Promise.withResolvers(); + stopper.once("close", stopDone); + assert.equal(await stopped, 0, stopErr); +}); + +test("under a service manager the upgraded server exits for the manager to restart it", { timeout: 60_000 }, async () => { + const root = scratch(); + const home = join(root, "agent"); + const script = fakeUpgrade(root); + const files = serveFiles(home); + const args = parseServeArgs(["--foreground"]); + assert.ok(!("error" in args)); + let output = ""; + const running = runServeCommand(args, { + agentHome: home, + homeFlags: ["--home", home], + launcher: BIN, + nodePath: process.execPath, + version: "1.0.0", + env: { ...isolatedEnv(root), XPC_SERVICE_NAME: "com.gentle-shell.serve" }, + stdout: (text) => { output += text; }, + stderr: (text) => { output += text; }, + untilStopped: (stopRequested) => stopRequested, + upgradeCommand: () => ({ command: process.execPath, args: [script], cwd: root, env: process.env }), + }); + const deadline = Date.now() + 15_000; + while (readServerFile(files.server)?.pid !== process.pid) { + if (Date.now() > deadline) throw new Error(`the server did not start: ${output}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + const server = readServerFile(files.server)!; + assert.equal((await call(server.url, "POST", "/api/upgrade", { token: server.adminToken })).status, 202); + assert.equal(await running, SERVE_RESTART_EXIT); + assert.match(output, /the service manager starts the upgraded server/); + assert.equal(readServerFile(files.server), undefined, "no server left behind for the manager's one to find"); +}); + +test("no server, session keeper, or fake Pi outlives the tests above", async () => { + assert.deepEqual(await remainingServeLeftovers(sessionDirs(), roots), []); +}); diff --git a/tests/serve-uploads.test.ts b/tests/serve-uploads.test.ts new file mode 100644 index 000000000..70841dc10 --- /dev/null +++ b/tests/serve-uploads.test.ts @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { ServeAuth } from "../lib/serve-auth.ts"; +import { startServeServer, type ServeServer } from "../lib/serve-server.ts"; +import { cleanUploadName } from "../lib/serve-uploads.ts"; +import { after, before, call, pairDevice, test } from "./serve-test-client.ts"; + +const ADMIN = "gsa_test-admin-token"; +let root: string; +let serveDir: string; +let server: ServeServer; +let operator: { id: string; token: string }; +let reader: { id: string; token: string }; +let expired: string; +let fresh: string; + +before(async () => { + root = realpathSync(mkdtempSync(join(tmpdir(), "gentle-serve-uploads-"))); + serveDir = join(root, "serve"); + // One upload from 8 days ago and one from yesterday, for the sweep at start. + expired = join(serveDir, "uploads", "dev_old", "aaaa"); + fresh = join(serveDir, "uploads", "dev_old", "bbbb"); + for (const [dir, days] of [[expired, 8], [fresh, 1]] as const) { + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "f.txt"), "x"); + const at = new Date(Date.now() - days * 24 * 60 * 60_000); + utimesSync(dir, at, at); + } + const auth = new ServeAuth({ devicesFile: join(serveDir, "devices.json"), adminToken: ADMIN }); + server = await startServeServer({ + host: "127.0.0.1", + port: 0, + auth, + version: "test", + serveDir, + launchSession: () => { throw new Error("no sessions here"); }, + uploadLimits: { bytes: 1024 }, + }); + operator = await pairDevice(server.url, ADMIN, ["sessions:read", "sessions:operate"], "operator"); + reader = await pairDevice(server.url, ADMIN, ["sessions:read"], "reader"); +}); +after(async () => { + await server?.close(); + rmSync(root, { recursive: true, force: true }); +}); + +test("cleanUploadName keeps the last component, drops control and reserved characters", () => { + assert.equal(cleanUploadName("photo.png"), "photo.png"); + assert.equal(cleanUploadName("../../etc/passwd"), "passwd"); + assert.equal(cleanUploadName("C:\\Users\\me\\shot 1.png"), "shot 1.png"); + assert.equal(cleanUploadName("a\u0000b\nc?.txt"), "a_b_c_.txt"); + assert.equal(cleanUploadName(".."), "upload"); + assert.equal(cleanUploadName(""), "upload"); + assert.equal(cleanUploadName(null), "upload"); + assert.equal(cleanUploadName("dir/"), "upload"); + assert.ok(Buffer.byteLength(cleanUploadName("é".repeat(300)), "utf8") <= 200); +}); + +test("POST /api/uploads stores the body under the device's folder and answers its path", async () => { + const sent = await call(server.url, "POST", `/api/uploads?name=${encodeURIComponent("../notes.md")}`, { token: operator.token, raw: "# hi\n" }); + assert.equal(sent.status, 201, JSON.stringify(sent.body)); + assert.equal(sent.body.name, "notes.md"); + assert.equal(sent.body.size, 5); + assert.match(sent.body.sha256, /^[0-9a-f]{64}$/); + assert.ok(Date.parse(sent.body.expiresAt) > Date.now() + 6 * 24 * 60 * 60_000); + const path: string = sent.body.path; + assert.equal(dirname(dirname(path)), join(serveDir, "uploads", operator.id)); + assert.match(path, /\/[0-9a-f]{16}\/notes\.md$/); + assert.equal(readFileSync(path, "utf8"), "# hi\n"); + assert.equal(statSync(path).mode & 0o777, 0o600); + assert.equal(statSync(dirname(path)).mode & 0o777, 0o700); + + const again = await call(server.url, "POST", "/api/uploads?name=notes.md", { token: operator.token, raw: "two" }); + assert.notEqual(again.body.path, path, "every upload gets its own folder"); + + const capabilities = (await call(server.url, "GET", "/api/server", { token: reader.token })).body.capabilities; + assert.ok(capabilities.includes("uploads")); +}); + +test("uploads need sessions:operate, are bounded, and leave nothing behind when refused", async () => { + assert.equal((await call(server.url, "POST", "/api/uploads?name=x", { token: reader.token, raw: "x" })).status, 403); + assert.equal((await call(server.url, "POST", "/api/uploads?name=x", { raw: "x" })).status, 401); + assert.equal((await call(server.url, "GET", "/api/uploads", { token: operator.token })).status, 405); + const before = readdirSync(join(serveDir, "uploads", operator.id)).length; + const big = await call(server.url, "POST", "/api/uploads?name=big.bin", { token: operator.token, raw: Buffer.alloc(2048) }); + assert.equal(big.status, 413); + assert.equal(readdirSync(join(serveDir, "uploads", operator.id)).length, before); +}); + +test("uploads older than 7 days are removed", async () => { + // The sweep at start runs in the background with nothing to await: poll for its effect. + for (let i = 0; i < 50 && existsSync(expired); i += 1) await new Promise((r) => setTimeout(r, 20)); + assert.equal(existsSync(expired), false); + assert.equal(existsSync(fresh), true); +}); + +test("a server without a serve folder takes no uploads", async () => { + const auth = new ServeAuth({ devicesFile: join(root, "other", "devices.json"), adminToken: ADMIN }); + const bare = await startServeServer({ host: "127.0.0.1", port: 0, auth, version: "test", launchSession: () => { throw new Error("none"); } }); + try { + assert.equal((await call(bare.url, "POST", "/api/uploads?name=x", { token: ADMIN, raw: "x" })).status, 501); + assert.equal((await call(bare.url, "GET", "/api/server", { token: ADMIN })).body.capabilities.includes("uploads"), false); + } finally { + await bare.close(); + } +});