From 43510a5e65874261b6ffa74bfc31dffdaa4d8c83 Mon Sep 17 00:00:00 2001
From: gbarnai
Date: Sun, 29 Nov 2026 14:45:16 -0500
Subject: [PATCH 1/8] feat: serve other devices over TLS only and pair each
device with its own revocable token
The devices listener now runs on https with a self-signed certificate made
once per install (key kept 0600 in the data folder). The pairing link carries
the certificate's SHA-256 fingerprint and pairing refuses a link for any other
certificate. Each pairing spends a one-time code and issues a token for that
device alone, stored as a hash; devices.list and devices.revoke list and unpair
devices, and unpairing closes the device's open connections. A plain http
request to the listener gets no answer.
---
.../skills/format-driving/references/tools.md | 20 +-
.../format-harness/references/command-map.md | 2 +
.../format-harness/references/tool-map.md | 2 +
.../skills/format-driving/references/tools.md | 20 +-
.../format-harness/references/command-map.md | 2 +
.../format-harness/references/tool-map.md | 2 +
.docs/wiki/Architecture.md | 6 +-
.docs/wiki/Engine.md | 4 +-
CLAUDE.md | 2 +-
NOTICE.md | 1 +
SECURITY.md | 8 +-
agents/manifest.json | 5 +
backend/HASHOUT_LOG.md | 21 ++
backend/app/agent_guide.py | 2 +
backend/app/core/local_guard.py | 7 +-
backend/app/engine/device_tokens.py | 90 ++++++++
backend/app/engine/devices.py | 203 ++++++++++++-----
backend/app/engine/lan_cert.py | 111 +++++++++
backend/app/engine/store.py | 11 +-
backend/requirements.txt | 1 +
backend/requirements_macos.txt | 1 +
backend/tests/test_artifacts_and_devices.py | 211 ++++++++++++++++--
backend/tests/test_device_pairing_link.py | 2 +-
backend/tests/test_migrations.py | 8 +-
docs/artifacts-and-documents.md | 2 +-
docs/other-devices.md | 21 +-
docs/settings.md | 2 +-
docs/troubleshooting.md | 5 +-
28 files changed, 665 insertions(+), 107 deletions(-)
create mode 100644 backend/app/engine/device_tokens.py
create mode 100644 backend/app/engine/lan_cert.py
diff --git a/.agents/skills/format-driving/references/tools.md b/.agents/skills/format-driving/references/tools.md
index 5322fed..a48c22c 100644
--- a/.agents/skills/format-driving/references/tools.md
+++ b/.agents/skills/format-driving/references/tools.md
@@ -579,25 +579,37 @@ Returns the conversation of one demo, and puts the demo back first when it was d
### forget_devices
-Changes the pairing code, so every paired device has to pair again. Use when the person wants every paired device to pair again.
+Unpairs every device at once and changes the pairing code, so each one has to pair again. Use when the person wants every paired device to pair again.
- changes state · command `devices.forget` · params: none
+### list_paired_devices
+
+The devices paired with Format: id, a name read from the device's browser, when it paired and when it was last seen. Use to see which phones and computers are paired and when each was last seen.
+
+- read-only · command `devices.list` · params: none
+
+### unpair_device
+
+Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code. Use when the person wants one paired device, such as a lost phone, to stop reaching Format.
+
+- changes state · command `devices.revoke` · params: `id` string
+
### open_to_devices
-Starts Format's network listener (port 8492) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code. Use when the person wants to continue on their phone or another computer, or to share links beyond this computer.
+Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code. Use when the person wants to continue on their phone or another computer, or to share links beyond this computer.
- changes state · command `devices.start` · params: none
### get_devices_status
-Whether Format is reachable from other devices on this network (a phone or another computer), its addresses, and, when on, the pairing link and its QR code as SVG. Use to see whether Format is open to the person's other devices and to get the pairing link.
+Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint, the paired devices, and, when on, the one-time pairing link and its QR code as SVG. Use to see whether Format is open to the person's other devices and to get the pairing link.
- read-only · command `devices.status` · params: none
### close_to_devices
-Stops the network listener; paired devices and shared links stop working until it starts again. Use when the person wants Format reachable from this computer only.
+Stops the network listener; paired devices and shared links stop working until it starts again. Paired devices stay paired. Use when the person wants Format reachable from this computer only.
- changes state · command `devices.stop` · params: none
diff --git a/.agents/skills/format-harness/references/command-map.md b/.agents/skills/format-harness/references/command-map.md
index 721e39b..7bd9ae8 100644
--- a/.agents/skills/format-harness/references/command-map.md
+++ b/.agents/skills/format-harness/references/command-map.md
@@ -100,6 +100,8 @@ Generated by ./format agents sync from the engine's command registry; do not edi
| `demo.list` | `./format cli demo.list` | `list_demos` | Demos |
| `demo.restore` | `./format cli demo.restore id=...` | `restore_demo` | Restore a demo chat |
| `devices.forget` | `./format cli devices.forget` | `forget_devices` | Forget paired devices |
+| `devices.list` | `./format cli devices.list` | `list_paired_devices` | Paired devices |
+| `devices.revoke` | `./format cli devices.revoke id=...` | `unpair_device` | Unpair a device |
| `devices.start` | `./format cli devices.start` | `open_to_devices` | Open to other devices |
| `devices.status` | `./format cli devices.status` | `get_devices_status` | Other devices |
| `devices.stop` | `./format cli devices.stop` | `close_to_devices` | Close to other devices |
diff --git a/.agents/skills/format-harness/references/tool-map.md b/.agents/skills/format-harness/references/tool-map.md
index a287136..d0bfed3 100644
--- a/.agents/skills/format-harness/references/tool-map.md
+++ b/.agents/skills/format-harness/references/tool-map.md
@@ -100,6 +100,8 @@ Generated by ./format agents sync from the engine's command registry; do not edi
| `list_demos` | `demo.list` | `backend/app/engine/cmd_demo.py` | read |
| `restore_demo` | `demo.restore` | `backend/app/engine/cmd_demo.py` | write |
| `forget_devices` | `devices.forget` | `backend/app/engine/devices.py` | write |
+| `list_paired_devices` | `devices.list` | `backend/app/engine/devices.py` | read |
+| `unpair_device` | `devices.revoke` | `backend/app/engine/devices.py` | write |
| `open_to_devices` | `devices.start` | `backend/app/engine/devices.py` | write |
| `get_devices_status` | `devices.status` | `backend/app/engine/devices.py` | read |
| `close_to_devices` | `devices.stop` | `backend/app/engine/devices.py` | write |
diff --git a/.claude/skills/format-driving/references/tools.md b/.claude/skills/format-driving/references/tools.md
index 5322fed..a48c22c 100644
--- a/.claude/skills/format-driving/references/tools.md
+++ b/.claude/skills/format-driving/references/tools.md
@@ -579,25 +579,37 @@ Returns the conversation of one demo, and puts the demo back first when it was d
### forget_devices
-Changes the pairing code, so every paired device has to pair again. Use when the person wants every paired device to pair again.
+Unpairs every device at once and changes the pairing code, so each one has to pair again. Use when the person wants every paired device to pair again.
- changes state · command `devices.forget` · params: none
+### list_paired_devices
+
+The devices paired with Format: id, a name read from the device's browser, when it paired and when it was last seen. Use to see which phones and computers are paired and when each was last seen.
+
+- read-only · command `devices.list` · params: none
+
+### unpair_device
+
+Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code. Use when the person wants one paired device, such as a lost phone, to stop reaching Format.
+
+- changes state · command `devices.revoke` · params: `id` string
+
### open_to_devices
-Starts Format's network listener (port 8492) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code. Use when the person wants to continue on their phone or another computer, or to share links beyond this computer.
+Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code. Use when the person wants to continue on their phone or another computer, or to share links beyond this computer.
- changes state · command `devices.start` · params: none
### get_devices_status
-Whether Format is reachable from other devices on this network (a phone or another computer), its addresses, and, when on, the pairing link and its QR code as SVG. Use to see whether Format is open to the person's other devices and to get the pairing link.
+Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint, the paired devices, and, when on, the one-time pairing link and its QR code as SVG. Use to see whether Format is open to the person's other devices and to get the pairing link.
- read-only · command `devices.status` · params: none
### close_to_devices
-Stops the network listener; paired devices and shared links stop working until it starts again. Use when the person wants Format reachable from this computer only.
+Stops the network listener; paired devices and shared links stop working until it starts again. Paired devices stay paired. Use when the person wants Format reachable from this computer only.
- changes state · command `devices.stop` · params: none
diff --git a/.claude/skills/format-harness/references/command-map.md b/.claude/skills/format-harness/references/command-map.md
index 721e39b..7bd9ae8 100644
--- a/.claude/skills/format-harness/references/command-map.md
+++ b/.claude/skills/format-harness/references/command-map.md
@@ -100,6 +100,8 @@ Generated by ./format agents sync from the engine's command registry; do not edi
| `demo.list` | `./format cli demo.list` | `list_demos` | Demos |
| `demo.restore` | `./format cli demo.restore id=...` | `restore_demo` | Restore a demo chat |
| `devices.forget` | `./format cli devices.forget` | `forget_devices` | Forget paired devices |
+| `devices.list` | `./format cli devices.list` | `list_paired_devices` | Paired devices |
+| `devices.revoke` | `./format cli devices.revoke id=...` | `unpair_device` | Unpair a device |
| `devices.start` | `./format cli devices.start` | `open_to_devices` | Open to other devices |
| `devices.status` | `./format cli devices.status` | `get_devices_status` | Other devices |
| `devices.stop` | `./format cli devices.stop` | `close_to_devices` | Close to other devices |
diff --git a/.claude/skills/format-harness/references/tool-map.md b/.claude/skills/format-harness/references/tool-map.md
index a287136..d0bfed3 100644
--- a/.claude/skills/format-harness/references/tool-map.md
+++ b/.claude/skills/format-harness/references/tool-map.md
@@ -100,6 +100,8 @@ Generated by ./format agents sync from the engine's command registry; do not edi
| `list_demos` | `demo.list` | `backend/app/engine/cmd_demo.py` | read |
| `restore_demo` | `demo.restore` | `backend/app/engine/cmd_demo.py` | write |
| `forget_devices` | `devices.forget` | `backend/app/engine/devices.py` | write |
+| `list_paired_devices` | `devices.list` | `backend/app/engine/devices.py` | read |
+| `unpair_device` | `devices.revoke` | `backend/app/engine/devices.py` | write |
| `open_to_devices` | `devices.start` | `backend/app/engine/devices.py` | write |
| `get_devices_status` | `devices.status` | `backend/app/engine/devices.py` | read |
| `close_to_devices` | `devices.stop` | `backend/app/engine/devices.py` | write |
diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md
index e7d395a..d09be1e 100644
--- a/.docs/wiki/Architecture.md
+++ b/.docs/wiki/Architecture.md
@@ -32,8 +32,8 @@ The engine owns all state:
| Where | Holds |
| --- | --- |
-| `data/format.db` (SQLite, WAL, schema 8) | conversations, messages (a tree by `parent_id`), artifacts and versions, projects, connectors, schedules and runs, shares, `meta` key-values (settings, tasks, outputs) |
-| `data/` folders | uploads, memory, skills, plugins, exports, snapshots, the browser profile, the pairing secret, saved keys |
+| `data/format.db` (SQLite, WAL, schema 9) | conversations, messages (a tree by `parent_id`), artifacts and versions, projects, connectors, schedules and runs, shares, paired devices (a SHA-256 of each device token, never the token), `meta` key-values (settings, tasks, outputs) |
+| `data/` folders | uploads, memory, skills, plugins, exports, snapshots, the browser profile, the one-time pairing code (`pairing.json`), the devices listener's certificate and private key (`devices/`, 0600), saved keys |
| `workspace/chats/` | each chat's own folder for Claude's tools |
Demo chats are ordinary rows: at start `engine/demos.py` reads each folder under `app/demos` and, once per data folder, writes its conversation, messages, artifact and output files (`conversations.demo` names the demo; `meta` key `demos.seeded` remembers which were added, so a deleted demo stays deleted until `demo.restore`). `meta` key `demos.shipped` records, per demo, a digest of the shipped `chat.json`, page and `files/` plus the title and file list it was made with. When the digest of the app's copy differs (or is missing, as in a data folder made before this existed) and the chat is still as made (title as shipped, only the recorded messages in one unbranched line ending in the recorded reply, only its own one-version artifact, no other files in its folder), `demos.update_if_stale` rebuilds it in place at the next start: same conversation id, pin, project and place in the list, share links moved to the new artifact. A chat the person renamed, continued, edited or branched is left alone. A demo is added by its folder alone: `chat.json` and the page, plus an optional `about.json` (`blurb`, one line for the Help menu, and `order`, an integer, 1000 when missing); `demo.list` returns them sorted by `order` and the window takes its list, menu entries and sidebar order from it.
@@ -51,4 +51,4 @@ The window keeps only view state, and layout state (sidebar, panel, terminal, si
| Local dictation | `./format install-voice` | `engine/voice.py` |
| Built-in browser | `./format install-browser` | `engine/browser.py` |
| Native renderer | `./format native build`, `FORMAT_NATIVE=1` | `engine/native.py`, `native/format-render` |
-| Other devices | Settings, Other devices | `engine/devices.py` (second server on 8492) |
+| Other devices | Settings, Other devices | `engine/devices.py` (second server on 8492, https only), `engine/lan_cert.py`, `engine/device_tokens.py` |
diff --git a/.docs/wiki/Engine.md b/.docs/wiki/Engine.md
index ebea204..a632ad4 100644
--- a/.docs/wiki/Engine.md
+++ b/.docs/wiki/Engine.md
@@ -25,7 +25,9 @@ Python 3.12, FastAPI, in `backend/app`.
| `engine/projects.py`, `memory.py`, `skills.py`, `connectors.py`, `plugins.py` | projects, memory, skills, MCP connectors, plugins |
| `engine/schedules.py` | scheduled tasks on a scheduler thread |
| `engine/terminal.py` | PTY terminals and the Claude tab |
-| `engine/devices.py` | the LAN server, pairing, share links |
+| `engine/devices.py` | the LAN server (TLS only), the gate, one-time pairing codes, share links |
+| `engine/lan_cert.py` | the listener's self-signed certificate and key, made once per install, and its SHA-256 fingerprint |
+| `engine/device_tokens.py` | per-device tokens (stored as hashes), unpairing, closing a revoked device's open connections |
| `engine/browser.py` | the built-in browser on its worker thread |
| `engine/voice.py` | transcription |
| `mcp_server.py`, `mcp_stdio.py`, `agent_guide.py` | Format as an MCP server |
diff --git a/CLAUDE.md b/CLAUDE.md
index bf4bdce..dc75d6b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8,7 +8,7 @@ A.T, the Agentic Terminal: a chat and agent workspace on the Claude API, in the
- `frontend/src/styles/` holds the family's vendored Studio Dark sheets unchanged (`tokens.css`, `scrollbars.css`, `fonts.css`, `shell.css`, `dialogs.css`, `light-mode.css`) beside Format's own `ft-*.css` (`ft-` classes). Colours and z-index come from tokens only.
- `native/format-render` is the family-standard wgpu crate (`Gpu`, `budget`, opt-in `native_start` on FORMAT_NATIVE): a terminal glyph grid (vt100 screen, fontdue atlas, one full-screen shader) with a CLI binary (`info`, `snapshot`) and a winit demo window behind the `window` feature. The engine calls the binary from `backend/app/engine/native.py` (`native.status`, `terminal.snapshot`); nothing runs while FORMAT_NATIVE is unset, and the window's terminal stays xterm.
- `backend/app/harness/` is the only place a Claude API request is built (system prompt, content blocks, effort, thinking, caching); `backend/app/providers/` holds one adapter per provider. Chat runs through `chat.send`, `chat.stop`, `chat.retry`, `chat.edit`, `chat.branch`, `chat.compact` and `chat.wait`; a stored compaction block (beta `compact-2026-09-04`) starts every later request, and attachments of 1 MB or more go through the Files API; keys through `keys.set`, `keys.clear`, `keys.status`. A chat is a tree of messages (`parent_id`) with `conversations.leaf_id` marking the path on screen; `messages_of` returns that path.
-- Tools live in `backend/app/engine/tools.py` (definitions, the per-chat folder `workspace/chats/`, approvals, executors); the loop is `chat._run`, which keeps a whole multi-round reply in one message with `tool_result` blocks inline and lets `harness.api_messages` split it for the API. Approvals: `tool.approve`, `tool.pending`; questions: `tool.answer`; the plan and the files Claude sends: `tasks.get`, `outputs.list`, downloads under `/api/chats/{id}/`. Sub-agents (`spawn_agent`) run inside the parent's tool call (`chat._run_agent`) and keep their transcript in `meta.agents`. Artifacts (`publish_artifact`, `backend/app/engine/artifacts.py`) are versioned rows served at `/api/artifacts/{id}/v/{n}` under a sandboxing CSP; the window shows them in `frontend/src/ui/artifact-panel.ts`, never with `allow-same-origin`. The chat folder's files come through `files.list` and `files.read` and preview in `frontend/src/ui/files-pane.ts`, which shares the side track with the artifact panel (`data-ft-side`); comments on them travel in `chat.send` `comments`. Projects (`backend/app/engine/projects.py`, `cmd_project.py`) hold instructions and knowledge files (uploads); `projects.context` is read at the start of each reply, and `harness.build` puts the instructions in the system prompt and the files at the start of the first user turn. Memory (`memory.py`) runs Anthropic's client-side memory tool on `data/memory` (general or per project); skills (`skills.py`) are SKILL.md folders in `data/skills`, listed in the system prompt and loaded through the `skill` tool. Connectors (`connectors.py`) send public https MCP servers through the API's MCP connector (`mcp_servers`, `mcp_toolset`, beta `mcp-client-2025-11-20`) and run every other server in the engine with the `mcp` SDK, as client tools named `mcp____` that go through approvals. Format is itself an MCP server (`backend/app/mcp_server.py`, generated from the command registry: a tool per command with `.` as `_`, plus `run_command`, chat and artifact resources, three prompts), served at `/mcp` (`routers/mcp_http.py`, Streamable HTTP) and over stdio by `./format mcp` (`mcp_stdio.py`, a proxy to the running engine's REST API with header `x-format-agent`). Outside agents pass `agents.require` (setting `outsideAgents`: ask, allowed, blocked; ask publishes `agents.consent` and waits for the window). Scheduled tasks (`backend/app/engine/schedules.py`, tables `schedules` and `schedule_runs`, schema 7) run on a scheduler thread started with the engine; each run is `chat.send` into a new chat, and `background.list` reports every chat working or waiting. Documents, spreadsheets and decks are artifact kinds written by `write_document` and exported by `documents.py`. Other devices (`backend/app/engine/devices.py`) run a second, cookie-gated server on port 8492 only while the person turns it on; share links (`artifact.share`, table `shares`, schema 8) are served at `/s/{token}`. Plugins (`plugins.py`) install a Claude plugin folder's skills, commands and MCP servers as Format skills and connectors and track them in `data/plugins//.format-plugin.json`. The built-in browser (`browser.py`, optional Playwright) runs on one worker thread; Claude's `browser` tool and the window's Browser pane (`frontend/src/ui/browser-pane.ts`) drive the same page.
+- Tools live in `backend/app/engine/tools.py` (definitions, the per-chat folder `workspace/chats/`, approvals, executors); the loop is `chat._run`, which keeps a whole multi-round reply in one message with `tool_result` blocks inline and lets `harness.api_messages` split it for the API. Approvals: `tool.approve`, `tool.pending`; questions: `tool.answer`; the plan and the files Claude sends: `tasks.get`, `outputs.list`, downloads under `/api/chats/{id}/`. Sub-agents (`spawn_agent`) run inside the parent's tool call (`chat._run_agent`) and keep their transcript in `meta.agents`. Artifacts (`publish_artifact`, `backend/app/engine/artifacts.py`) are versioned rows served at `/api/artifacts/{id}/v/{n}` under a sandboxing CSP; the window shows them in `frontend/src/ui/artifact-panel.ts`, never with `allow-same-origin`. The chat folder's files come through `files.list` and `files.read` and preview in `frontend/src/ui/files-pane.ts`, which shares the side track with the artifact panel (`data-ft-side`); comments on them travel in `chat.send` `comments`. Projects (`backend/app/engine/projects.py`, `cmd_project.py`) hold instructions and knowledge files (uploads); `projects.context` is read at the start of each reply, and `harness.build` puts the instructions in the system prompt and the files at the start of the first user turn. Memory (`memory.py`) runs Anthropic's client-side memory tool on `data/memory` (general or per project); skills (`skills.py`) are SKILL.md folders in `data/skills`, listed in the system prompt and loaded through the `skill` tool. Connectors (`connectors.py`) send public https MCP servers through the API's MCP connector (`mcp_servers`, `mcp_toolset`, beta `mcp-client-2025-11-20`) and run every other server in the engine with the `mcp` SDK, as client tools named `mcp____` that go through approvals. Format is itself an MCP server (`backend/app/mcp_server.py`, generated from the command registry: a tool per command with `.` as `_`, plus `run_command`, chat and artifact resources, three prompts), served at `/mcp` (`routers/mcp_http.py`, Streamable HTTP) and over stdio by `./format mcp` (`mcp_stdio.py`, a proxy to the running engine's REST API with header `x-format-agent`). Outside agents pass `agents.require` (setting `outsideAgents`: ask, allowed, blocked; ask publishes `agents.consent` and waits for the window). Scheduled tasks (`backend/app/engine/schedules.py`, tables `schedules` and `schedule_runs`, schema 7) run on a scheduler thread started with the engine; each run is `chat.send` into a new chat, and `background.list` reports every chat working or waiting. Documents, spreadsheets and decks are artifact kinds written by `write_document` and exported by `documents.py`. Other devices (`backend/app/engine/devices.py`) run a second, https-only server on port 8492 only while the person turns it on, with a per-install certificate (`lan_cert.py`, fingerprint in the pairing code) and a revocable token per paired device (`device_tokens.py`, table `paired_devices`, schema 9); share links (`artifact.share`, table `shares`, schema 8) are served at `/s/{token}`. Plugins (`plugins.py`) install a Claude plugin folder's skills, commands and MCP servers as Format skills and connectors and track them in `data/plugins//.format-plugin.json`. The built-in browser (`browser.py`, optional Playwright) runs on one worker thread; Claude's `browser` tool and the window's Browser pane (`frontend/src/ui/browser-pane.ts`) drive the same page.
- Terminals are engine PTYs (`backend/app/engine/terminal.py`): the window's dock attaches over `WS /api/terminal/{id}`, and `terminal.write` and `terminal.read` let the CLI and agents use the same shells. Claude's own bash commands are mirrored into one read-only session of kind `agent` (no PTY), shown as the Claude tab. Layout state (sidebar, panel, terminal) lives on `documentElement` data attributes set before first paint.
- The manual for people using Format is `docs/`; the developer wiki is `.docs/wiki` (architecture, engine, window, agents, checks, releasing); `BRANCHING.md` covers branches and tags. Update the manual page a change shows on.
- Planning documents (DEV_PLAN, BUILD_NOTES, UI_STUDY, PARITY_BASELINE, the root HASHOUT_LOG) ship in the planning sidecar zip, not in this tree. The living logs `frontend/HASHOUT_LOG.md` and `backend/HASHOUT_LOG.md` are in the tree: read them before editing.
diff --git a/NOTICE.md b/NOTICE.md
index 3fa9ec9..3889eeb 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -102,6 +102,7 @@ Two page quirks: the Miranda page lists its download under the name `Uranus - Ar
| Libraries inside the Pillow wheel | libjpeg, libpng, libtiff, libwebp, libavif, OpenJPEG, Little CMS, HarfBuzz, Brotli, zstd, xz, libxcb: permissive (see the wheel's LICENSE); FreeType 2.14.3 used under the FreeType License | Portions of this software are copyright (c) 2026 The FreeType Project (www.freetype.org). All rights reserved. |
| certifi | MPL-2.0 | engine: its `cacert.pem`, frozen unedited |
| segno | BSD-3-Clause | the pairing QR code |
+| cryptography 50.0.2 | Apache-2.0 OR BSD-3-Clause (its wheel bundles OpenSSL 3, Apache-2.0) | makes the other-devices listener's own certificate and key |
| keyring | MIT | keeps the key that seals the outside-agent choice in the system keychain |
| FastAPI, Starlette, Pydantic | MIT | engine |
| Uvicorn, httpx | BSD-3-Clause | engine |
diff --git a/SECURITY.md b/SECURITY.md
index 962ae77..012e005 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -30,9 +30,11 @@ something outside it could get in:
reachable from another machine, or lets a web page on another origin drive it.
- **Other devices** (off by default): the second listener on port 8492 that opens
only while the person turns it on. Reaching chats from a device that is not paired,
- guessing or reusing the pairing link, keeping access after Forget paired devices or
- Close to other devices, or a share link opening more than the one artifact it was
- made for, or still answering after Stop sharing.
+ guessing or reusing the pairing link, keeping access after Unpair, Forget paired
+ devices or Close to other devices, the listener answering without TLS or with a
+ certificate other than the one whose fingerprint the pairing code carries, or a
+ share link opening more than the one artifact it was made for, or still answering
+ after Stop sharing.
- **Agents and the MCP server** (`/mcp`, and `./format mcp` over stdio): an agent
acting before the person has allowed outside agents in Settings.
- **Approvals and Claude's tools**: a command, file change, browser action or local
diff --git a/agents/manifest.json b/agents/manifest.json
index 3148185..61e8a6b 100644
--- a/agents/manifest.json
+++ b/agents/manifest.json
@@ -50,6 +50,8 @@
"list_demos",
"restore_demo",
"forget_devices",
+ "list_paired_devices",
+ "unpair_device",
"open_to_devices",
"get_devices_status",
"close_to_devices",
@@ -136,6 +138,7 @@
"get_conversation",
"list_conversations",
"list_demos",
+ "list_paired_devices",
"get_devices_status",
"list_chat_files",
"read_chat_file",
@@ -211,6 +214,8 @@
"list_demos",
"restore_demo",
"forget_devices",
+ "list_paired_devices",
+ "unpair_device",
"open_to_devices",
"get_devices_status",
"close_to_devices",
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index f8120cd..94803bb 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -1355,3 +1355,24 @@ Git transports. Every git call runs with `protocol.ext.allow=never`, so a source
Tool processes, second pass. `_kill` waits up to 3 seconds for the whole process group, not only its leader, and then sends SIGKILL to the group if anything in it still runs, so a child that ignores SIGTERM ends too (tests/test_tool_processes.py).
The shared finder, version 1.0.2 (app/engine/agent_lookup.py, hash in setup/agents.py `LOOKUP_HASHES`). On Windows `start_argv` no longer puts cmd.exe in front of an npm, pnpm or bun shim: `shim_target` reads the .cmd and runs the .exe it names, or node.exe (beside the shim, then on PATH) and the script it names. A shim of another kind still goes through cmd.exe, now with /d, and only when every word, the program's path included, passes `cmd_safe`: none of & | < > ^ ( ) ! % " and no control character (\x00-\x1f, \x7f), with or without spaces, because the shim reads its arguments again through %* and quoting does not hold there; otherwise the start is refused with an OSError that says to pass long text through stdin or a file. A name ending in .cmd or .bat followed by dots or spaces counts as a shim too. The Claude Code chat run passes its child environment to `start_argv`, so node is looked for on the same PATH the program gets (tests/test_windows_start.py; not run on Windows). The other Form engines still carry 1.0.1.
+
+### Other devices over TLS with a token per device (unreleased)
+- refers-to: app/engine/lan_cert.py :: ensure, fingerprint, write_private; app/engine/device_tokens.py :: issue, check, revoke, revoke_all, watch; app/engine/devices.py :: Gate, _pair, _held, _code, _spend, listener_config, status, devices_list, devices_revoke, devices_forget; app/engine/store.py :: paired_devices (schema 9); app/core/local_guard.py :: LocalGuard._permitted; requirements.txt, requirements_macos.txt :: cryptography
+- kind: decision
+- logged: unreleased
+
+The owner's decision: the devices listener speaks TLS only, with a certificate made per install, its fingerprint in the pairing code, and a revocable token per device in place of the one shared pairing secret.
+
+Certificate. `lan_cert.ensure` makes an EC P-256 self-signed certificate on the first devices.start (CN "FormAT paired devices", SAN localhost, 127.0.0.1 and the LAN addresses of that moment, EKU serverAuth, not a CA) and keeps it in `data/devices/listener.crt` with its key in `listener.key`, written through a 0600 temporary file and os.replace, so the key is never readable by others even for a moment. It is reused while it matches its key and has more than 30 days left; the life is 825 days because iOS refuses server certificates that last longer. A new address does not make a new certificate (the browser warns about the name, as it already does about the issuer), because a new certificate means a new warning and a new fingerprint on every device. cryptography was already frozen into the engine through pyjwt's extra; it is now pinned directly in both lists and has its own NOTICE row.
+
+TLS only. `listener_config` gives uvicorn the certificate and key, so a plain http request to 8492 fails the handshake and gets no HTTP answer (seen in tests/test_artifacts_and_devices.py with a real uvicorn on a free port, which also pins the served certificate by its fingerprint). The Gate also answers 426 to any scope that is not https or wss, as a second line in case the listener is ever built without TLS.
+
+Pinning. A browser cannot be told to pin a certificate from a link, so the pairing link carries `fp=` and the window shows the same fingerprint for the person to compare with the browser's certificate warning; the browser then keeps its exception for that one certificate. `/pair` refuses a link whose fingerprint is not this install's, so a code shown for another certificate never pairs. A client that can pin (a future companion app) reads `fp` from the code.
+
+Tokens. `pairing.json` holds a one-time code (key `code`; the old `secret` key is not read, so the old shared secret is retired on upgrade and old cookies stop working). `/pair` checks fingerprint and code, spends the code under a lock (two scans of one code pair one device), issues a 32-byte token in cookie `format_device` (HttpOnly, Secure, SameSite=Lax; Strict would drop the cookie on the redirect that follows a scan) and stores only its SHA-256 in `paired_devices` with a name read from the User-Agent. `last seen` is written at most once a minute per device. devices.list and devices.status never return a token or its hash.
+
+Revocation. devices.revoke deletes one row and devices.forget all of them (and changes the code). Every paired request runs under `_held`, which watches an asyncio.Event per device; revoking sets it through call_soon_threadsafe from the command thread, the request task is cancelled, and a WebSocket gets close 4401 (an HTTP request that has not started its answer gets the not-paired page). New requests fail at once because each one looks its token up again.
+
+LocalGuard. Its same-origin fallback compared the Origin only as http, so a paired page served over https would have been refused; it now compares with the request's own scheme.
+
+Not done here: the window's new Paired devices list and fingerprint line were type-checked and built but not driven in a throttled browser; a renewal of the certificate is not announced in the window beyond the new fingerprint it shows.
diff --git a/backend/app/agent_guide.py b/backend/app/agent_guide.py
index 79c7edb..9fdb483 100644
--- a/backend/app/agent_guide.py
+++ b/backend/app/agent_guide.py
@@ -15,6 +15,8 @@
"devices.start": ("open_to_devices", "Use when the person wants to continue on their phone or another computer, or to share links beyond this computer."),
"devices.stop": ("close_to_devices", "Use when the person wants Format reachable from this computer only."),
"devices.forget": ("forget_devices", "Use when the person wants every paired device to pair again."),
+ "devices.list": ("list_paired_devices", "Use to see which phones and computers are paired and when each was last seen."),
+ "devices.revoke": ("unpair_device", "Use when the person wants one paired device, such as a lost phone, to stop reaching Format."),
"claudecode.status": ("get_claude_code_status", "Use when chats run without an API key, to see whether Claude Code is installed and whether it or the API key answers."),
"browser.status": ("get_browser_status", "Use to see whether Format's built-in browser is installed and open, and which page it shows."),
"browser.open": ("open_in_browser", "Use to open a page in Format's built-in browser, which the person watches in its Browser pane; returns the page as text with numbered elements."),
diff --git a/backend/app/core/local_guard.py b/backend/app/core/local_guard.py
index 5ad228e..fc66a70 100644
--- a/backend/app/core/local_guard.py
+++ b/backend/app/core/local_guard.py
@@ -29,7 +29,7 @@ def __init__(self, app, origins: list[str]) -> None:
self.app = app
self.allowed = {key for key in (_origin_key(o) for o in origins) if key is not None}
- def _permitted(self, headers: dict[str, str], paired: bool = False) -> bool:
+ def _permitted(self, headers: dict[str, str], paired: bool = False, scheme: str = "http") -> bool:
host = headers.get("host", "")
if BROWSER_MARK in headers:
return False
@@ -44,14 +44,15 @@ def _permitted(self, headers: dict[str, str], paired: bool = False) -> bool:
if key in self.allowed:
return True
own = _origin_key(f"{key[0]}://{host}")
- return key[0] == "http" and own is not None and own == key
+ return key[0] == scheme and own is not None and own == key
async def __call__(self, scope, receive, send) -> None:
if scope["type"] not in ("http", "websocket"):
await self.app(scope, receive, send)
return
headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])}
- if self._permitted(headers, scope.get("format.paired") is True):
+ scheme = "https" if scope.get("scheme") in ("https", "wss") else "http"
+ if self._permitted(headers, scope.get("format.paired") is True, scheme):
await self.app(scope, receive, send)
return
if scope["type"] == "websocket":
diff --git a/backend/app/engine/device_tokens.py b/backend/app/engine/device_tokens.py
new file mode 100644
index 0000000..3fb7da6
--- /dev/null
+++ b/backend/app/engine/device_tokens.py
@@ -0,0 +1,90 @@
+import asyncio
+import hashlib
+import re
+import secrets
+import threading
+
+from app.engine import store
+
+COOKIE = "format_device"
+SEEN_EVERY = 60.0
+_live_lock = threading.Lock()
+_live: dict[str, set[tuple[asyncio.AbstractEventLoop, asyncio.Event]]] = {}
+_PLATFORMS = (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"), ("CrOS", "ChromeOS"), ("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux"))
+_BROWSERS = (("Edg/", "Edge"), ("Firefox/", "Firefox"), ("FxiOS", "Firefox"), ("CriOS", "Chrome"), ("Chrome/", "Chrome"), ("Safari/", "Safari"))
+
+
+def _hash(token: str) -> str:
+ return hashlib.sha256(token.encode("utf-8")).hexdigest()
+
+
+def label(user_agent: str) -> str:
+ ua = user_agent or ""
+ platform = next((name for mark, name in _PLATFORMS if mark in ua), "")
+ browser = next((name for mark, name in _BROWSERS if mark in ua), "")
+ text = ", ".join(p for p in (platform, browser) if p) or "A browser"
+ return re.sub(r"[^\w ,.-]", "", text)[:60]
+
+
+def issue(name: str) -> tuple[str, str]:
+ token = secrets.token_urlsafe(32)
+ did = store.new_id()
+ now = store.now()
+ store.run("INSERT INTO paired_devices(id, name, token_hash, created, seen) VALUES (?, ?, ?, ?, ?)", (did, name, _hash(token), now, now))
+ return did, token
+
+
+def check(token: str | None) -> str | None:
+ if not token:
+ return None
+ found = store.row("SELECT id, seen FROM paired_devices WHERE token_hash = ?", (_hash(token),))
+ if found is None:
+ return None
+ now = store.now()
+ if now - found["seen"] > SEEN_EVERY:
+ store.run("UPDATE paired_devices SET seen = ? WHERE id = ?", (now, found["id"]))
+ return found["id"]
+
+
+def listing() -> list[dict]:
+ return store.rows("SELECT id, name, created, seen FROM paired_devices ORDER BY created")
+
+
+def revoke(did: str) -> int:
+ n = store.run("DELETE FROM paired_devices WHERE id = ?", (did,))
+ _cut([did])
+ return n
+
+
+def revoke_all() -> int:
+ ids = [r["id"] for r in listing()]
+ n = store.run("DELETE FROM paired_devices")
+ _cut(ids + list(_live))
+ return n
+
+
+def watch(did: str) -> asyncio.Event:
+ gone = asyncio.Event()
+ with _live_lock:
+ _live.setdefault(did, set()).add((asyncio.get_running_loop(), gone))
+ return gone
+
+
+def unwatch(did: str, gone: asyncio.Event) -> None:
+ with _live_lock:
+ held = _live.get(did)
+ if held is None:
+ return
+ held.difference_update({pair for pair in held if pair[1] is gone})
+ if not held:
+ _live.pop(did, None)
+
+
+def _cut(ids: list[str]) -> None:
+ with _live_lock:
+ targets = [pair for did in ids for pair in _live.get(did, ())]
+ for loop, gone in targets:
+ try:
+ loop.call_soon_threadsafe(gone.set)
+ except RuntimeError:
+ pass
diff --git a/backend/app/engine/devices.py b/backend/app/engine/devices.py
index bf23724..6c83ec4 100644
--- a/backend/app/engine/devices.py
+++ b/backend/app/engine/devices.py
@@ -1,4 +1,5 @@
import asyncio
+import contextlib
import hmac
import json
import logging
@@ -6,18 +7,22 @@
import re
import secrets
import socket
+import threading
from http.cookies import SimpleCookie
from pathlib import Path
+from urllib.parse import parse_qs
from fastapi import APIRouter
from fastapi.responses import Response
from app.core import config
-from app.engine import artifacts, events, store
+from app.engine import artifacts, device_tokens, events, lan_cert, store
from app.engine.commands import CommandError, command
LAN_PORT = int(os.environ.get("FORMAT_LAN_PORT") or 8492)
-COOKIE = "format_pair"
+COOKIE = device_tokens.COOKIE
+SECURE = ("https", "wss")
+_code_lock = threading.Lock()
_server = None
_task = None
_loop: asyncio.AbstractEventLoop | None = None
@@ -53,24 +58,33 @@ def bind(loop: asyncio.AbstractEventLoop) -> None:
_loop = loop
-def _secret_path() -> Path:
+def _code_path() -> Path:
return config.data_dir() / "pairing.json"
-def _secret(rotate: bool = False) -> str:
- p = _secret_path()
- if not rotate and p.is_file():
+def _code(rotate: bool = False) -> str:
+ with _code_lock:
+ p = _code_path()
+ if not rotate and p.is_file():
+ try:
+ return json.loads(p.read_text())["code"]
+ except (OSError, ValueError, KeyError, TypeError):
+ pass
+ s = secrets.token_urlsafe(24)
+ lan_cert.write_private(p, json.dumps({"code": s}).encode("utf-8"))
+ return s
+
+
+def _spend(code: str) -> bool:
+ with _code_lock:
try:
- return json.loads(p.read_text())["secret"]
- except (ValueError, KeyError):
- pass
- s = secrets.token_urlsafe(24)
- p.write_text(json.dumps({"secret": s}))
- try:
- os.chmod(p, 0o600)
- except OSError:
- pass
- return s
+ held = json.loads(_code_path().read_text())["code"]
+ except (OSError, ValueError, KeyError, TypeError):
+ return False
+ if not (code and hmac.compare_digest(code.encode("utf-8"), str(held).encode("utf-8"))):
+ return False
+ lan_cert.write_private(_code_path(), json.dumps({"code": secrets.token_urlsafe(24)}).encode("utf-8"))
+ return True
def lan_addresses() -> list[str]:
@@ -97,20 +111,36 @@ def running() -> bool:
def base_url() -> str:
- return f"http://{lan_addresses()[0]}:{LAN_PORT}" if running() else f"http://127.0.0.1:{config.PORT}"
+ return f"https://{lan_addresses()[0]}:{LAN_PORT}" if running() else f"http://127.0.0.1:{config.PORT}"
+
+
+def _header(scope: dict, name: bytes) -> str:
+ return next((v.decode("latin-1") for k, v in scope.get("headers") or [] if k.lower() == name), "")
-def _paired(scope: dict, secret: str) -> bool:
+def _device_of(scope: dict) -> str | None:
for k, v in scope.get("headers") or []:
- if k == b"cookie":
+ if k.lower() == b"cookie":
c = SimpleCookie()
try:
c.load(v.decode("latin-1"))
except Exception:
continue
- if COOKIE in c and hmac.compare_digest(c[COOKIE].value, secret):
- return True
- return False
+ if COOKIE in c:
+ found = device_tokens.check(c[COOKIE].value)
+ if found:
+ return found
+ return None
+
+
+_PAGE = "
FormAT
{}
"
+NOT_PAIRED = "This device is not paired. On the computer running FormAT, open Settings, Other devices, and scan the code or open its link here."
+STALE_LINK = "This pairing link has been used or is out of date. On the computer running FormAT, open Settings, Other devices, and scan the code shown there now."
+
+
+async def _page(send, status: int, text: str) -> None:
+ await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"text/html; charset=utf-8"), (b"cache-control", b"no-store")]})
+ await send({"type": "http.response.body", "body": _PAGE.format(text).encode("utf-8")})
class Gate:
@@ -118,49 +148,92 @@ def __init__(self, api, static):
self.api = api
self.static = static
- async def inner(self, scope, receive, send):
+ async def inner(self, scope, receive, send, device: str | None = None):
path = scope.get("path") or "/"
target = self.api if path.startswith(("/api", "/mcp", "/s/")) or self.static is None else self.static
- return await target(dict(scope) | {"format.paired": True}, receive, send)
+ return await target(dict(scope) | {"format.paired": True, "format.device": device}, receive, send)
+
+ async def _held(self, scope, receive, send, device: str):
+ gone = device_tokens.watch(device)
+ started = {"yes": False}
+
+ async def tracked(message):
+ if message["type"] in ("http.response.start", "websocket.accept"):
+ started["yes"] = True
+ await send(message)
+
+ work = asyncio.ensure_future(self.inner(scope, receive, tracked, device))
+ cut = asyncio.ensure_future(gone.wait())
+ try:
+ done, _ = await asyncio.wait({work, cut}, return_when=asyncio.FIRST_COMPLETED)
+ if work in done:
+ return work.result()
+ work.cancel()
+ with contextlib.suppress(BaseException):
+ await work
+ with contextlib.suppress(Exception):
+ if scope["type"] == "websocket":
+ await send({"type": "websocket.close", "code": 4401})
+ elif not started["yes"]:
+ await _page(send, 401, NOT_PAIRED)
+ finally:
+ cut.cancel()
+ device_tokens.unwatch(device, gone)
+
+ async def _pair(self, scope, send):
+ q = parse_qs((scope.get("query_string") or b"").decode("latin-1"))
+ fp = (q.get("fp") or [""])[0].lower().replace(":", "")
+ own = lan_cert.fingerprint()
+ if own is None or not hmac.compare_digest(fp.encode("utf-8"), own.encode("utf-8")) or not _spend((q.get("code") or [""])[0]):
+ return await _page(send, 401, STALE_LINK)
+ _, token = device_tokens.issue(device_tokens.label(_header(scope, b"user-agent")))
+ _changed()
+ await send({"type": "http.response.start", "status": 303, "headers": [
+ (b"location", b"/"), (b"cache-control", b"no-store"),
+ (b"set-cookie", f"{COOKIE}={token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=31536000".encode())]})
+ await send({"type": "http.response.body", "body": b""})
async def __call__(self, scope, receive, send):
if scope["type"] not in ("http", "websocket"):
return await self.api(scope, receive, send)
+ if scope.get("scheme") not in SECURE:
+ if scope["type"] == "websocket":
+ await send({"type": "websocket.close", "code": 4426})
+ return
+ return await _page(send, 426, "FormAT answers other devices over https only.")
path = scope.get("path") or "/"
- secret = _secret()
if (path.startswith("/s/") and "/" not in path[3:]) or path in ("/favicon.svg", "/favicon.png"):
return await self.inner(scope, receive, send)
if scope["type"] == "http" and path == "/pair":
- q = dict(p.split("=", 1) for p in (scope.get("query_string") or b"").decode().split("&") if "=" in p)
- if hmac.compare_digest(q.get("code", ""), secret):
- await send({"type": "http.response.start", "status": 303, "headers": [
- (b"location", b"/"), (b"set-cookie", f"{COOKIE}={secret}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000".encode())]})
- await send({"type": "http.response.body", "body": b""})
- return
- if _paired(scope, secret):
- return await self.inner(scope, receive, send)
+ return await self._pair(scope, send)
+ device = _device_of(scope)
+ if device:
+ return await self._held(scope, receive, send, device)
if scope["type"] == "websocket":
await send({"type": "websocket.close", "code": 4401})
return
- body = b"
FormAT
This device is not paired. On the computer running FormAT, open Settings, Other devices, and scan the code or open its link here.
"
- await send({"type": "http.response.start", "status": 401, "headers": [(b"content-type", b"text/html; charset=utf-8")]})
- await send({"type": "http.response.body", "body": body})
+ await _page(send, 401, NOT_PAIRED)
def _dist() -> Path:
return config.frontend_dist()
+def listener_config(asgi, port: int, host: str = "0.0.0.0"):
+ import uvicorn
+ cert, key = lan_cert.ensure(lan_addresses())
+ return uvicorn.Config(asgi, host=host, port=port, lifespan="off", log_config=None, log_level=None,
+ ssl_certfile=str(cert), ssl_keyfile=str(key))
+
+
async def _serve() -> None:
global _server
- import contextlib
-
import uvicorn
from starlette.staticfiles import StaticFiles
from app.main import app
redact_logs()
- cfg = uvicorn.Config(Gate(app, StaticFiles(directory=str(_dist()), html=True)), host="0.0.0.0", port=LAN_PORT, lifespan="off", log_config=None, log_level=None)
+ cfg = listener_config(Gate(app, StaticFiles(directory=str(_dist()), html=True)), LAN_PORT)
_server = uvicorn.Server(cfg)
_server.capture_signals = contextlib.nullcontext
await _server.serve()
@@ -174,6 +247,10 @@ def _start() -> None:
raise CommandError("The engine is still starting; try again", 503)
if not (_dist() / "index.html").is_file():
raise CommandError("Build the window first with ./format build, so other devices can load it", 409)
+ try:
+ lan_cert.ensure(lan_addresses())
+ except (OSError, ValueError) as exc:
+ raise CommandError(f"Could not make the certificate for other devices: {exc}", 500) from exc
fut = asyncio.run_coroutine_threadsafe(_launch(), _loop)
fut.result(10)
@@ -205,39 +282,61 @@ def _qr(url: str) -> str:
def status() -> dict:
on = running()
- urls = [f"http://{ip}:{LAN_PORT}" for ip in lan_addresses()] if on else []
- out = {"on": on, "port": LAN_PORT, "urls": urls, "pairUrl": None, "qr": None}
- if on and urls:
- out["pairUrl"] = f"{urls[0]}/pair?code={_secret()}"
+ urls = [f"https://{ip}:{LAN_PORT}" for ip in lan_addresses()] if on else []
+ fp = lan_cert.fingerprint()
+ out = {"on": on, "port": LAN_PORT, "urls": urls, "pairUrl": None, "qr": None,
+ "fingerprint": lan_cert.spaced(fp), "devices": device_tokens.listing()}
+ if on and urls and fp:
+ out["pairUrl"] = f"{urls[0]}/pair?code={_code()}&fp={fp}"
out["qr"] = _qr(out["pairUrl"])
return out
+def _changed() -> None:
+ events.publish("devices.changed", devices={"on": running(), "paired": len(device_tokens.listing())})
+
+
@command("devices.status", "Other devices", mutates=False,
- description="Whether Format is reachable from other devices on this network (a phone or another computer), its addresses, and, when on, the pairing link and its QR code as SVG.")
+ description="Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint, the paired devices, and, when on, the one-time pairing link and its QR code as SVG.")
def devices_status() -> dict:
return status()
@command("devices.start", "Open to other devices",
- description="Starts Format's network listener (port 8492) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code.")
+ description="Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code.")
def devices_start() -> dict:
_start()
- out = status()
- events.publish("devices.changed", devices={k: v for k, v in out.items() if k != "qr"})
- return out
+ _changed()
+ return status()
-@command("devices.stop", "Close to other devices", description="Stops the network listener; paired devices and shared links stop working until it starts again.")
+@command("devices.stop", "Close to other devices", description="Stops the network listener; paired devices and shared links stop working until it starts again. Paired devices stay paired.")
def devices_stop() -> dict:
stop_server()
- events.publish("devices.changed", devices={"on": False})
+ _changed()
return {"on": False}
-@command("devices.forget", "Forget paired devices", description="Changes the pairing code, so every paired device has to pair again.")
+@command("devices.list", "Paired devices", mutates=False,
+ description="The devices paired with Format: id, a name read from the device's browser, when it paired and when it was last seen.")
+def devices_list() -> dict:
+ return {"devices": device_tokens.listing()}
+
+
+@command("devices.revoke", "Unpair a device", {"id": {"type": "string", "required": True, "description": "device id from devices.list"}},
+ description="Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code.")
+def devices_revoke(id: str) -> dict:
+ if not device_tokens.revoke(id):
+ raise CommandError(f"No paired device {id}; devices.list gives the ids", 404)
+ _changed()
+ return status()
+
+
+@command("devices.forget", "Forget paired devices", description="Unpairs every device at once and changes the pairing code, so each one has to pair again.")
def devices_forget() -> dict:
- _secret(rotate=True)
+ device_tokens.revoke_all()
+ _code(rotate=True)
+ _changed()
return status()
diff --git a/backend/app/engine/lan_cert.py b/backend/app/engine/lan_cert.py
new file mode 100644
index 0000000..2a3a69c
--- /dev/null
+++ b/backend/app/engine/lan_cert.py
@@ -0,0 +1,111 @@
+import datetime
+import hashlib
+import ipaddress
+import os
+import threading
+from pathlib import Path
+
+from app.core import config
+
+LIFE_DAYS = 825
+RENEW_DAYS = 30
+_lock = threading.Lock()
+
+
+def folder() -> Path:
+ return config.data_dir() / "devices"
+
+
+def cert_path() -> Path:
+ return folder() / "listener.crt"
+
+
+def key_path() -> Path:
+ return folder() / "listener.key"
+
+
+def write_private(path: Path, data: bytes) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}")
+ fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ try:
+ with os.fdopen(fd, "wb") as out:
+ out.write(data)
+ os.replace(temp, path)
+ except BaseException:
+ temp.unlink(missing_ok=True)
+ raise
+ try:
+ os.chmod(path, 0o600)
+ except OSError:
+ pass
+
+
+def _load():
+ from cryptography import x509
+ from cryptography.hazmat.primitives import serialization
+ try:
+ cert = x509.load_pem_x509_certificate(cert_path().read_bytes())
+ key = serialization.load_pem_private_key(key_path().read_bytes(), password=None)
+ except (OSError, ValueError, TypeError):
+ return None
+ if cert.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) != key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo):
+ return None
+ left = cert.not_valid_after_utc - datetime.datetime.now(datetime.timezone.utc)
+ return cert if left > datetime.timedelta(days=RENEW_DAYS) else None
+
+
+def _names(addresses: list[str]) -> list:
+ from cryptography import x509
+ found: list = [x509.DNSName("localhost")]
+ for text in [*addresses, "127.0.0.1"]:
+ try:
+ ip = ipaddress.ip_address(text)
+ except ValueError:
+ continue
+ if x509.IPAddress(ip) not in found:
+ found.append(x509.IPAddress(ip))
+ return found
+
+
+def _make(addresses: list[str]) -> None:
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec
+ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
+ key = ec.generate_private_key(ec.SECP256R1())
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "FormAT paired devices")])
+ now = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(minutes=5)
+ cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
+ .serial_number(x509.random_serial_number()).not_valid_before(now).not_valid_after(now + datetime.timedelta(days=LIFE_DAYS))
+ .add_extension(x509.SubjectAlternativeName(_names(addresses)), critical=False)
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
+ .sign(key, hashes.SHA256()))
+ write_private(key_path(), key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
+ write_private(cert_path(), cert.public_bytes(serialization.Encoding.PEM))
+
+
+def ensure(addresses: list[str]) -> tuple[Path, Path]:
+ with _lock:
+ if _load() is None:
+ _make(addresses)
+ try:
+ os.chmod(key_path(), 0o600)
+ except OSError:
+ pass
+ return cert_path(), key_path()
+
+
+def fingerprint() -> str | None:
+ from cryptography import x509
+ from cryptography.hazmat.primitives import serialization
+ try:
+ cert = x509.load_pem_x509_certificate(cert_path().read_bytes())
+ except (OSError, ValueError):
+ return None
+ return hashlib.sha256(cert.public_bytes(serialization.Encoding.DER)).hexdigest()
+
+
+def spaced(fp: str | None) -> str | None:
+ return ":".join(fp[i:i + 2] for i in range(0, len(fp), 2)).upper() if fp else None
diff --git a/backend/app/engine/store.py b/backend/app/engine/store.py
index d5af765..1098e4e 100644
--- a/backend/app/engine/store.py
+++ b/backend/app/engine/store.py
@@ -106,6 +106,13 @@
created REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS shares_by_artifact ON shares(artifact_id);
+CREATE TABLE IF NOT EXISTS paired_devices (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ token_hash TEXT NOT NULL UNIQUE,
+ created REAL NOT NULL,
+ seen REAL NOT NULL
+);
"""
_lock = threading.RLock()
@@ -153,8 +160,8 @@ def conn() -> sqlite3.Connection:
if "demo" not in conv_cols:
c.execute("ALTER TABLE conversations ADD COLUMN demo TEXT")
c.execute("CREATE INDEX IF NOT EXISTS messages_by_parent ON messages(conversation_id, parent_id)")
- c.execute("INSERT OR IGNORE INTO meta(key, value) VALUES ('schema', '8')")
- c.execute("UPDATE meta SET value = '8' WHERE key = 'schema'")
+ c.execute("INSERT OR IGNORE INTO meta(key, value) VALUES ('schema', '9')")
+ c.execute("UPDATE meta SET value = '9' WHERE key = 'schema'")
_conn = c
return _conn
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 2782bfd..c8a5793 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -9,6 +9,7 @@ python-docx==1.2.0
openpyxl==3.1.5
reportlab==5.0.1
segno==1.6.6
+cryptography==50.0.2
keyring==25.7.0
ptyprocess==0.7.0; sys_platform != "win32"
pywinpty==3.0.5; sys_platform == "win32"
diff --git a/backend/requirements_macos.txt b/backend/requirements_macos.txt
index c172efa..42d4582 100644
--- a/backend/requirements_macos.txt
+++ b/backend/requirements_macos.txt
@@ -9,5 +9,6 @@ python-docx==1.2.0
openpyxl==3.1.5
reportlab==5.0.1
segno==1.6.6
+cryptography==50.0.2
keyring==25.7.0
ptyprocess==0.7.0
diff --git a/backend/tests/test_artifacts_and_devices.py b/backend/tests/test_artifacts_and_devices.py
index eb7793b..37d79f0 100644
--- a/backend/tests/test_artifacts_and_devices.py
+++ b/backend/tests/test_artifacts_and_devices.py
@@ -1,10 +1,19 @@
import asyncio
+import hashlib
+import http.client
+import os
+import socket
+import ssl
+import stat
+import threading
+import time
+from urllib.parse import parse_qs, urlsplit
import pytest
from _format import run
-from app.engine import devices
+from app.engine import device_tokens, devices, lan_cert
from app.engine.commands import dispatch
PAGE = "t
artifact body
"
@@ -68,11 +77,15 @@ async def __call__(self, scope, receive, send):
await send({"type": "http.response.body", "body": b"inside"})
-def _through_gate(path, cookie=None, query=b"", kind="http"):
+PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1"
+
+
+def _through_gate(path, cookie=None, query=b"", kind="http", scheme=None, agent=PHONE):
api = _Recorder()
gate = devices.Gate(api, None)
sent = []
headers = [(b"cookie", cookie.encode())] if cookie else []
+ headers.append((b"user-agent", agent.encode()))
async def receive():
return {"type": "http.request" if kind == "http" else "websocket.connect"}
@@ -80,13 +93,30 @@ async def receive():
async def send(message):
sent.append(message)
- asyncio.run(gate({"type": kind, "path": path, "query_string": query, "headers": headers}, receive, send))
+ scheme = scheme or ("https" if kind == "http" else "wss")
+ asyncio.run(gate({"type": kind, "scheme": scheme, "path": path, "query_string": query, "headers": headers}, receive, send))
return api.called, sent
-def test_the_devices_server_refuses_a_request_without_its_cookie(client):
- secret = devices._secret()
- for cookie in (None, "format_pair=wrong", f"other={secret}", "format_pair="):
+def _pair(agent=PHONE):
+ lan_cert.ensure(["192.0.2.10"])
+ query = f"code={devices._code()}&fp={lan_cert.fingerprint()}".encode()
+ called, sent = _through_gate("/pair", query=query, agent=agent)
+ assert not called and sent[0]["status"] == 303, sent
+ cookie = dict(sent[0]["headers"])[b"set-cookie"].decode()
+ return cookie, cookie.split(";", 1)[0]
+
+
+@pytest.fixture
+def no_devices(client):
+ run(client, "devices.forget")
+ yield
+ run(client, "devices.forget")
+
+
+def test_the_devices_server_refuses_a_request_without_a_device_token(client, no_devices):
+ code = devices._code()
+ for cookie in (None, f"{devices.COOKIE}=wrong", f"other={code}", f"{devices.COOKIE}=", f"{devices.COOKIE}={code}", f"format_pair={code}"):
called, sent = _through_gate("/api/commands", cookie)
assert not called, cookie
assert sent[0]["status"] == 401
@@ -94,19 +124,40 @@ def test_the_devices_server_refuses_a_request_without_its_cookie(client):
assert not called and sent[0] == {"type": "websocket.close", "code": 4401}
-def test_the_devices_server_lets_a_paired_device_in(client):
- called, _ = _through_gate("/api/commands", f"{devices.COOKIE}={devices._secret()}")
+def test_pairing_issues_a_token_for_this_device_only_and_spends_the_code(client, no_devices):
+ code = devices._code()
+ cookie, pair = _pair()
+ token = pair.split("=", 1)[1]
+ assert token != code and len(token) >= 40
+ assert "HttpOnly" in cookie and "Secure" in cookie and "SameSite=Lax" in cookie
+ assert devices._code() != code
+ called, sent = _through_gate("/pair", query=f"code={code}&fp={lan_cert.fingerprint()}".encode())
+ assert not called and sent[0]["status"] == 401
+ called, _ = _through_gate("/api/commands", pair)
assert called
+ listed = run(client, "devices.list")["devices"]
+ assert [d["name"] for d in listed] == ["iPhone, Safari"]
+ assert token not in str(listed) and "token_hash" not in listed[0]
-def test_pairing_needs_the_code_and_sets_the_cookie(client):
- secret = devices._secret()
- called, sent = _through_gate("/pair", query=f"code={secret}".encode())
- assert not called and sent[0]["status"] == 303
- cookie = dict(sent[0]["headers"])[b"set-cookie"].decode()
- assert cookie.startswith(f"{devices.COOKIE}={secret};") and "HttpOnly" in cookie
- called, sent = _through_gate("/pair", query=b"code=guess")
- assert not called and sent[0]["status"] == 401
+def test_pairing_needs_this_install_s_certificate_fingerprint(client, no_devices):
+ lan_cert.ensure(["192.0.2.10"])
+ code = devices._code()
+ for query in (f"code={code}", f"code={code}&fp={'0' * 64}", f"code=guess&fp={lan_cert.fingerprint()}"):
+ called, sent = _through_gate("/pair", query=query.encode())
+ assert not called and sent[0]["status"] == 401, query
+ assert devices._code() == code
+ assert run(client, "devices.list")["devices"] == []
+
+
+def test_the_devices_server_refuses_plain_http_even_with_a_token(client, no_devices):
+ _, pair = _pair()
+ called, sent = _through_gate("/api/commands", pair, scheme="http")
+ assert not called and sent[0]["status"] == 426
+ called, sent = _through_gate("/s/anything", scheme="http")
+ assert not called and sent[0]["status"] == 426
+ called, sent = _through_gate("/api/events", pair, kind="websocket", scheme="ws")
+ assert not called and sent[0]["type"] == "websocket.close"
def test_share_links_pass_the_gate_without_pairing(client):
@@ -114,10 +165,126 @@ def test_share_links_pass_the_gate_without_pairing(client):
assert called
-def test_forgetting_devices_changes_the_code(client):
- before = devices._secret()
+def test_unpairing_one_device_leaves_the_others_paired(client, no_devices):
+ _, phone = _pair()
+ _, laptop = _pair("Mozilla/5.0 (Macintosh; Intel Mac OS X 15_0) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15")
+ listed = run(client, "devices.list")["devices"]
+ assert [d["name"] for d in listed] == ["iPhone, Safari", "Mac, Safari"]
+ after = run(client, "devices.revoke", {"id": listed[0]["id"]})
+ assert [d["name"] for d in after["devices"]] == ["Mac, Safari"]
+ assert not _through_gate("/api/commands", phone)[0]
+ assert _through_gate("/api/commands", laptop)[0]
+
+
+def test_forgetting_devices_unpairs_every_device_and_changes_the_code(client, no_devices):
+ _, pair = _pair()
+ before = devices._code()
run(client, "devices.forget")
- after = devices._secret()
- assert after != before
- called, _ = _through_gate("/api/commands", f"{devices.COOKIE}={before}")
- assert not called
+ assert devices._code() != before
+ assert run(client, "devices.list")["devices"] == []
+ assert not _through_gate("/api/commands", pair)[0]
+
+
+def test_unpairing_closes_a_connection_the_device_holds_open(client, no_devices):
+ _, pair = _pair()
+ did = run(client, "devices.list")["devices"][0]["id"]
+ sent = []
+
+ async def held(scope, receive, send):
+ await send({"type": "websocket.accept"})
+ await asyncio.Event().wait()
+
+ async def go():
+ never = asyncio.Event()
+
+ async def receive():
+ await never.wait()
+
+ async def send(message):
+ sent.append(message)
+
+ gate = devices.Gate(held, None)
+ task = asyncio.create_task(gate({"type": "websocket", "scheme": "wss", "path": "/api/events", "query_string": b"",
+ "headers": [(b"cookie", pair.encode())]}, receive, send))
+ await asyncio.sleep(0.05)
+ assert sent == [{"type": "websocket.accept"}]
+ await asyncio.to_thread(device_tokens.revoke, did)
+ await asyncio.wait_for(task, 2)
+
+ asyncio.run(go())
+ assert sent[-1] == {"type": "websocket.close", "code": 4401}
+
+
+def test_the_certificate_is_made_once_with_a_private_key_only_the_owner_reads(client):
+ cert, key = lan_cert.ensure(["192.0.2.10"])
+ first = lan_cert.fingerprint()
+ assert lan_cert.ensure(["192.0.2.99"]) == (cert, key) and lan_cert.fingerprint() == first
+ assert len(first) == 64
+ if os.name != "nt":
+ assert stat.S_IMODE(key.stat().st_mode) == 0o600
+ assert stat.S_IMODE(devices._code_path().stat().st_mode) == 0o600
+ assert b"PRIVATE KEY" not in cert.read_bytes()
+
+
+def test_the_pairing_link_carries_the_certificate_fingerprint(client, monkeypatch):
+ monkeypatch.setattr(devices, "running", lambda: True)
+ monkeypatch.setattr(devices, "lan_addresses", lambda: ["192.0.2.10"])
+ lan_cert.ensure(["192.0.2.10"])
+ got = run(client, "devices.status")
+ link = urlsplit(got["pairUrl"])
+ assert link.scheme == "https" and link.netloc == f"192.0.2.10:{devices.LAN_PORT}"
+ assert parse_qs(link.query)["fp"] == [lan_cert.fingerprint()]
+ assert got["fingerprint"].replace(":", "").lower() == lan_cert.fingerprint()
+ assert got["urls"] == [f"https://192.0.2.10:{devices.LAN_PORT}"]
+
+
+def test_a_paired_device_page_on_https_passes_the_engine_s_origin_check(app, client, no_devices):
+ from fastapi.testclient import TestClient
+
+ _, pair = _pair()
+ origin = f"https://192.0.2.10:{devices.LAN_PORT}"
+ phone = TestClient(devices.Gate(app, None), base_url=origin)
+ r = phone.post("/api/commands/devices.list", json={}, headers={"cookie": pair, "origin": origin})
+ assert r.status_code == 200, r.text
+ assert r.json()["result"]["devices"][0]["name"] == "iPhone, Safari"
+
+
+def _free_port():
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+def test_the_listener_speaks_only_tls_with_the_pinned_certificate(client):
+ import uvicorn
+
+ async def hello(scope, receive, send):
+ await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]})
+ await send({"type": "http.response.body", "body": b"hello"})
+
+ port = _free_port()
+ server = uvicorn.Server(devices.listener_config(hello, port, host="127.0.0.1"))
+ thread = threading.Thread(target=server.run, daemon=True)
+ thread.start()
+ try:
+ deadline = time.time() + 10
+ while not server.started and time.time() < deadline:
+ time.sleep(0.05)
+ assert server.started
+ with socket.create_connection(("127.0.0.1", port), timeout=5) as plain:
+ plain.sendall(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
+ try:
+ answer = plain.recv(64)
+ except (ConnectionResetError, socket.timeout):
+ answer = b""
+ assert not answer.startswith(b"HTTP/")
+ pinned = ssl.create_default_context(cafile=str(lan_cert.cert_path()))
+ conn = http.client.HTTPSConnection("127.0.0.1", port, context=pinned, timeout=5)
+ conn.request("GET", "/")
+ r = conn.getresponse()
+ assert r.status == 200 and r.read() == b"hello"
+ assert hashlib.sha256(conn.sock.getpeercert(binary_form=True)).hexdigest() == lan_cert.fingerprint()
+ conn.close()
+ finally:
+ server.should_exit = True
+ thread.join(10)
diff --git a/backend/tests/test_device_pairing_link.py b/backend/tests/test_device_pairing_link.py
index c9b8e57..8bd6e0a 100644
--- a/backend/tests/test_device_pairing_link.py
+++ b/backend/tests/test_device_pairing_link.py
@@ -11,7 +11,7 @@ def listening(monkeypatch):
monkeypatch.setattr(devices, "running", lambda: True)
monkeypatch.setattr(devices, "lan_addresses", lambda: ["192.0.2.10"])
set_policy("allowed")
- yield devices._secret()
+ yield devices._code()
def test_the_window_gets_the_pairing_link(client, listening):
diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py
index b847899..ac568ee 100644
--- a/backend/tests/test_migrations.py
+++ b/backend/tests/test_migrations.py
@@ -86,7 +86,7 @@ def _open(data):
return json.loads(proc.stdout.strip().splitlines()[-1])
-CURRENT_TABLES = ["artifact_versions", "artifacts", "connectors", "conversations", "messages", "meta", "project_files", "projects", "schedule_runs", "schedules", "shares"]
+CURRENT_TABLES = ["artifact_versions", "artifacts", "connectors", "conversations", "messages", "meta", "paired_devices", "project_files", "projects", "schedule_runs", "schedules", "shares"]
def _message(mid, cid, text, created, parent=None, with_meta=False):
@@ -98,13 +98,13 @@ def _message(mid, cid, text, created, parent=None, with_meta=False):
@pytest.mark.parametrize("populated", [False, True])
-def test_schema_1_opens_as_schema_8(tmp_path, populated):
+def test_schema_1_opens_as_schema_9(tmp_path, populated):
rows = []
if populated:
rows.append(("INSERT INTO conversations(id, title, created, updated) VALUES (?, ?, ?, ?)", ("c1", "Old chat", 1.0, 4.0)))
rows += [_message(f"m{i}", "c1", f"line {i}", float(i)) for i in range(1, 5)]
got = _open(_db(tmp_path, SCHEMA_1, rows))
- assert got["schema"] == "8"
+ assert got["schema"] == "9"
assert got["tables"] == CURRENT_TABLES
assert {"meta", "parent_id"} <= set(got["cols"]["messages"])
assert {"leaf_id", "allow_all", "connectors_off"} <= set(got["cols"]["conversations"])
@@ -123,7 +123,7 @@ def test_schema_7_with_data_keeps_every_row(tmp_path):
("b2", "c7", "a1", "assistant", json.dumps([{"type": "text", "text": "other reply"}]), 3.0, "{}")),
("INSERT INTO connectors(id, name, kind, url, created, updated) VALUES (?, ?, ?, ?, ?, ?)", ("k1", "docs", "remote", "https://example.com/mcp", 1.0, 1.0))]
got = _open(_db(tmp_path, SCHEMA_1 + SCHEMA_7_EXTRA, rows))
- assert got["schema"] == "8"
+ assert got["schema"] == "9"
assert got["tables"] == CURRENT_TABLES
assert got["leafs"] == {"c7": "b2"}
assert got["paths"] == {"c7": ["first", "other reply"]}
diff --git a/docs/artifacts-and-documents.md b/docs/artifacts-and-documents.md
index 0b83527..56c5b01 100644
--- a/docs/artifacts-and-documents.md
+++ b/docs/artifacts-and-documents.md
@@ -24,7 +24,7 @@ Ask for one, or use Create in the + menu. They open beside the chat in their own
## Share links
-Share in the panel's header makes a read-only link to the latest version of the artifact, with Copy link, Open link and Stop sharing. While Other devices is off the link opens only on this computer; with it on, anyone on your network who has the link can open it. Stopped links answer "no longer shared". See [Other devices](other-devices.md).
+Share in the panel's header makes a read-only link to the latest version of the artifact, with Copy link, Open link and Stop sharing. While Other devices is off the link opens only on this computer; with it on, anyone on your network who has the link can open it, over https with FormAT's own certificate, so their browser warns once. Stopped links answer "no longer shared". See [Other devices](other-devices.md).
## The chat's files
diff --git a/docs/other-devices.md b/docs/other-devices.md
index 8497d98..ad143ba 100644
--- a/docs/other-devices.md
+++ b/docs/other-devices.md
@@ -6,15 +6,28 @@ FormAT runs on one computer, but you can carry on from your phone or another com
1. On the computer running FormAT, open Settings, Other devices, and choose Open to other devices.
2. Scan the code with your phone's camera, or open the link shown under it on the other device.
-3. The other device opens FormAT, paired. It sees the same chats, live, both ways: start a chat on the computer and continue it on the phone.
+3. The other device's browser warns that it does not know the certificate. That is expected: FormAT makes its own certificate for this computer the first time you open it to other devices. Open the certificate details in the warning and check that its SHA-256 fingerprint matches the one Settings shows under the code, then continue. The browser remembers the certificate after that.
+4. The other device opens FormAT, paired. It sees the same chats, live, both ways: start a chat on the computer and continue it on the phone.
-A device that is not paired gets a page saying so. Forget paired devices unpairs every device at once (they pair again with the new code). Close to other devices stops FormAT listening on the network.
+Each code pairs one device. Once a device has used it, Settings shows a new code, so pair each phone or computer with its own scan. A link that was already used, or that names a different certificate, shows a page saying so; scan the code shown now.
-FormAT listens on your network (port 8492) only while this is on. The pairing link is a secret: anyone on your network who has it can use FormAT as you, with your API key. Share it only with your own devices.
+A device that is not paired gets a page saying so.
+
+## Paired devices
+
+Settings, Other devices lists every paired device with the browser it paired from, when it paired and when it was last seen. Unpair beside a device stops that device at once, including a page it has open, and leaves the others paired. Forget paired devices unpairs every device at once and changes the code. Close to other devices stops FormAT listening on the network; paired devices stay paired and work again when you open it again.
+
+## How the connection is kept private
+
+FormAT listens on your network (port 8492) only while this is on, and only over https: a plain http request to that port gets no answer. The certificate and its private key stay in FormAT's data folder, readable by your user account only. The certificate lasts about two years; FormAT makes a new one shortly before it expires, and each browser warns once more.
+
+The code is a secret until it is used: anyone on your network who has an unused code can pair a device and use FormAT as you, with your API key. Share it only with your own devices, and unpair a device you no longer use or have lost.
+
+Devices paired with a version of FormAT before this change have to pair again once.
## Share links
-An artifact's Share button makes a read-only link to its latest version. While other devices are open the link uses your network address, so anyone on your network with the link can open that one artifact, without being paired. Stop sharing makes the link answer "no longer shared".
+An artifact's Share button makes a read-only link to its latest version. While other devices are open the link uses your network address over https, so anyone on your network with the link can open that one artifact, without being paired; their browser shows the same certificate warning. Stop sharing makes the link answer "no longer shared".
## On a phone
diff --git a/docs/settings.md b/docs/settings.md
index 0b7e1eb..9ee972b 100644
--- a/docs/settings.md
+++ b/docs/settings.md
@@ -36,7 +36,7 @@ The sections, in order: Account, API keys, Tools, Long chats, Memory, Voice, Oth
## Other devices
-Open or close FormAT to your network, the pairing code and link, and Forget paired devices. See [Other devices](other-devices.md).
+Open or close FormAT to your network, the pairing code and link, the certificate fingerprint to compare on the other device, the list of paired devices with Unpair beside each, and Forget paired devices. See [Other devices](other-devices.md).
## Outside agents
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 55fcac2..c7c5845 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -14,7 +14,10 @@ Start with `./format doctor`: it checks Node, Python, the installs, your key and
| Dictation says ElevenLabs transcription failed (401) | the ElevenLabs key is wrong or lacks speech to text; save a new one in Settings, API keys |
| The Browser pane says the browser is not installed | run `./format install-browser`, then restart FormAT |
| Claude's commands fail to install packages | the sandbox has no network by default; allow it in Settings, Tools, or turn the sandbox off |
-| A phone cannot open the pairing link | both devices must be on the same network, and a firewall must allow port 8492 on the computer |
+| A phone cannot open the pairing link | both devices must be on the same network, and a firewall must allow port 8492 on the computer; the link starts with https, and typing http instead gets no answer |
+| The phone's browser warns about the certificate | expected the first time: FormAT uses its own certificate; check that the fingerprint in the certificate details matches the one in Settings, Other devices, then continue |
+| The pairing page says the link was used or is out of date | each code pairs one device; scan the code Settings shows now |
+| A device that used to be paired asks to pair again | it was unpaired, or it paired with a version of FormAT before per-device pairing; scan the code again |
| A share link says "no longer shared" | sharing was stopped; Share again makes a new link |
| A plugin will not add | the .zip needs `.claude-plugin/plugin.json` with a name (lowercase, hyphens) and a description |
| A connector shows an error | open it in Customize and Reconnect; the message says what failed |
From 94cc032c797b6585bc42797aca24f04759276824 Mon Sep 17 00:00:00 2001
From: gbarnai
Date: Sun, 29 Nov 2026 14:45:24 -0500
Subject: [PATCH 2/8] feat: list paired devices with Unpair and show the
certificate fingerprint in Settings
Settings, Other devices shows the listener certificate's SHA-256 fingerprint
under the pairing code and a keyed list of paired devices, each with Unpair.
The window repaints the section on devices.changed, so a spent code is
replaced on screen after a device pairs.
---
frontend/HASHOUT_LOG.md | 7 ++++++
frontend/src/app.ts | 2 ++
frontend/src/styles/ft-shell.css | 8 ++++++-
frontend/src/ui/views.ts | 37 +++++++++++++++++++++++++++++---
4 files changed, 50 insertions(+), 4 deletions(-)
diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md
index 4f58c4c..8481494 100644
--- a/frontend/HASHOUT_LOG.md
+++ b/frontend/HASHOUT_LOG.md
@@ -1215,3 +1215,10 @@ The note under Settings, Outside agents listed "Claude Code, Codex, Cursor and o
- logged: v0.32.0 · 2026-11-20
The engine now answers `GET /api/browser/frame` only to the window (see the engine log's entry for 0.32.0), so `loadFrame` sends `keyHeaders()` with it. The pane fetches frames only after the events socket has delivered a browser status, and that socket opens only with a ticket taken after `loadWindowKey` has settled, so the key is always there by then. Seen in Chromium with the built window and the real engine: the pane's own frame requests answered 200 image/jpeg; the same read from a local program without the key, 403.
+
+### src/ui/views.ts, src/app.ts, src/styles/ft-shell.css · Settings, Other devices lists paired devices and shows the certificate fingerprint
+- refers-to: src/ui/views.ts :: the Other devices section, `paintDevices`, `paintPaired`; src/app.ts :: the `devices.changed` branch; src/styles/ft-shell.css `.ft-dev-fp`, `.ft-dev-list`, `.ft-dev-row`, `.ft-dev-unpair`
+- kind: feature
+- logged: unreleased
+
+The engine now pairs each device with its own token and serves other devices over https with a per-install certificate (backend HASHOUT, same entry name). The pairing box gains one line with the certificate's SHA-256 fingerprint, filled with `setText` while the box is shown, so the person can compare it with the warning on the other device. A Paired devices group lists each device keyed by id: rows that are gone are removed, new ones appended, and the name and times written through `setText`, so a repaint of the same list touches nothing; Unpair is one delegated click handler that calls devices.revoke. The list is empty (hidden by `:empty`) with the "No devices are paired" note toggled only when its state changes. `devices.changed` no longer carries the pairing link; the window answers it with devices.status, which also repaints the code after a scan spends it.
diff --git a/frontend/src/app.ts b/frontend/src/app.ts
index c769344..3a63388 100644
--- a/frontend/src/app.ts
+++ b/frontend/src/app.ts
@@ -540,6 +540,8 @@ export class App {
} else if (e.type === 'terminal.opened') {
const t = e.terminal as { id: string; title: string; kind?: string };
if (t.kind === 'agent') this.dock.adopt(t);
+ } else if (e.type === 'devices.changed') {
+ void this.settingsView.refreshDevices();
} else if (e.type === 'agents.consent') {
this.consent(String(e.client ?? 'An agent'), String(e.channel ?? ''));
} else if (e.type === 'settings.changed') {
diff --git a/frontend/src/styles/ft-shell.css b/frontend/src/styles/ft-shell.css
index 2c9748e..23eae1a 100644
--- a/frontend/src/styles/ft-shell.css
+++ b/frontend/src/styles/ft-shell.css
@@ -594,7 +594,13 @@ textarea.ft-input { resize: vertical; line-height: 1.5; overflow-y: auto; }
.ft-dev-qr { flex: none; width: 205px; height: 205px; line-height: 0; }
.ft-dev-qr svg { width: 100%; height: 100%; border-radius: var(--radius-md); }
.ft-dev-text { display: grid; gap: var(--space-1); min-width: 0; font-size: var(--fs-12); color: var(--text-secondary); }
-.ft-dev-url { font: var(--fs-12) var(--font-mono); color: var(--text-primary); overflow-wrap: anywhere; user-select: all; }
+.ft-dev-url, .ft-dev-fp { font: var(--fs-12) var(--font-mono); color: var(--text-primary); overflow-wrap: anywhere; user-select: all; }
+.ft-dev-list { display: grid; gap: var(--space-2); margin: 0; padding: 0; list-style: none; }
+.ft-dev-list:empty, .ft-dev-none[hidden] { display: none; }
+.ft-dev-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: auto auto; column-gap: var(--space-3); align-items: center; padding: var(--space-2) var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius-lg); background: var(--surface-1); }
+.ft-dev-name { min-width: 0; font-size: var(--fs-13); color: var(--text-primary); overflow-wrap: anywhere; }
+.ft-dev-seen { grid-column: 1; font-size: var(--fs-12); color: var(--text-muted); }
+.ft-dev-unpair { grid-column: 2; grid-row: 1 / span 2; }
.ft-br-head { padding-left: var(--space-2); }
.ft-br-url { flex: 1; min-width: 0; margin: 0 var(--space-1); }
diff --git a/frontend/src/ui/views.ts b/frontend/src/ui/views.ts
index 95eea85..48dd723 100644
--- a/frontend/src/ui/views.ts
+++ b/frontend/src/ui/views.ts
@@ -94,7 +94,8 @@ function sourceText(k: KeyStatus | undefined): string {
return `Set ${k.hint ?? ''} · ${where}`;
}
-interface DevicesStatus { on: boolean; port: number; urls: string[]; pairUrl: string | null; qr: string | null }
+interface PairedDevice { id: string; name: string; created: number; seen: number }
+interface DevicesStatus { on: boolean; port: number; urls: string[]; pairUrl: string | null; qr: string | null; fingerprint?: string | null; devices?: PairedDevice[] }
export type SettingsSection = 'Account' | 'API keys' | 'Tools' | 'Long chats' | 'Memory' | 'Voice' | 'Other devices' | 'Outside agents' | 'About';
@@ -154,11 +155,16 @@ export class SettingsView {
`);
prefs.add('Other devices', 'devices', `
-
Continue on your phone or another computer on the same network: turn this on, then scan the code or open the link there. Paired devices see the same chats live; shared artifact links open for anyone who can reach this computer, read-only. Turn it off to keep FormAT on this computer only.
+
Continue on your phone or another computer on the same network: turn this on, then scan the code or open the link there. The connection is encrypted with this computer's own certificate, so the other browser warns once; check its fingerprint against the one shown here. Each code pairs one device. Paired devices see the same chats live; shared artifact links open for anyone who can reach this computer, read-only. Turn it off to keep FormAT on this computer only.
Pairing
-
Open on the other device:
+
Open on the other device:Certificate fingerprint (SHA-256), to compare with the one the other device's browser shows:
+
+
+
Paired devices
+
+ No devices are paired.
`);
prefs.add('Outside agents', 'plug', `
While FormAT runs it is an MCP server at http://127.0.0.1:8490/mcp, and ./format mcp serves the same over stdio, so Claude Code, Codex, Cursor, Antigravity and other agents on this computer can chat, publish artifacts and run any FormAT command. Ask shows a prompt here the first time an agent calls.
Certificate fingerprint (SHA-256), the same one this browser shows for this site's certificate and FormAT's window shows:"
+ " {fp}")
+_CLEAR_WAIT = f"{WAIT_COOKIE}=; Path=/pair; HttpOnly; Secure; SameSite=Lax; Max-Age=0".encode()
+
+
+async def _page(send, status: int, text: str, headers: list | None = None, head: str = "") -> None:
+ await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"text/html; charset=utf-8"), (b"cache-control", b"no-store"), *(headers or [])]})
+ await send({"type": "http.response.body", "body": _PAGE.format(head, text).encode("utf-8")})
-async def _page(send, status: int, text: str) -> None:
- await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"text/html; charset=utf-8"), (b"cache-control", b"no-store")]})
- await send({"type": "http.response.body", "body": _PAGE.format(text).encode("utf-8")})
+async def _redirect(send, where: bytes, cookies: list[bytes]) -> None:
+ await send({"type": "http.response.start", "status": 303, "headers": [
+ (b"location", where), (b"cache-control", b"no-store"), *((b"set-cookie", c) for c in cookies)]})
+ await send({"type": "http.response.body", "body": b""})
async def _refuse(scope, send) -> None:
@@ -160,9 +253,9 @@ async def inner(self, scope, receive, send, device: str | None = None):
target = self.api if path.startswith(("/api", "/mcp", "/s/")) or self.static is None else self.static
return await target(dict(scope) | {"format.paired": True, "format.device": device}, receive, send)
- async def _held(self, scope, receive, send, device: str):
+ async def _held(self, scope, receive, send, device: str, token: str):
gone = device_tokens.watch(device)
- if not device_tokens.alive(device):
+ if device_tokens.check(token) != device:
device_tokens.unwatch(device, gone)
return await _refuse(scope, send)
started = {"yes": False}
@@ -196,12 +289,27 @@ async def _pair(self, scope, send):
own = lan_cert.fingerprint()
if own is None or not hmac.compare_digest(fp.encode("utf-8"), own.encode("utf-8")) or not _spend((q.get("code") or [""])[0]):
return await _page(send, 401, STALE_LINK)
- _, token = device_tokens.issue(device_tokens.label(_header(scope, b"user-agent")))
+ secret = _ask(device_tokens.label(_header(scope, b"user-agent")))
_changed()
- await send({"type": "http.response.start", "status": 303, "headers": [
- (b"location", b"/"), (b"cache-control", b"no-store"),
- (b"set-cookie", f"{COOKIE}={token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=31536000".encode())]})
- await send({"type": "http.response.body", "body": b""})
+ await _redirect(send, b"/pair/wait", [f"{WAIT_COOKIE}={secret}; Path=/pair; HttpOnly; Secure; SameSite=Lax; Max-Age={int(REQUEST_LIFE)}".encode()])
+
+ async def _wait(self, scope, send):
+ secret = next(iter(_cookies(scope, WAIT_COOKIE)), "")
+ found = _request_of(secret)
+ if found is None:
+ return await _page(send, 401, STALE_LINK, [(b"set-cookie", _CLEAR_WAIT)])
+ if found["state"] == "denied":
+ _settle(found["id"])
+ return await _page(send, 403, TURNED_DOWN, [(b"set-cookie", _CLEAR_WAIT)])
+ if found["state"] == "waiting":
+ text = WAITING.format(name=html.escape(found["name"]), check=f"{found['check'][:3]} {found['check'][3:]}",
+ fp=html.escape(lan_cert.spaced(lan_cert.fingerprint()) or ""))
+ return await _page(send, 200, text, head=f"")
+ if not _settle(found["id"]):
+ return await _page(send, 401, STALE_LINK, [(b"set-cookie", _CLEAR_WAIT)])
+ _, token = device_tokens.issue(found["name"])
+ _changed()
+ await _redirect(send, b"/", [_CLEAR_WAIT, f"{COOKIE}={token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=31536000".encode()])
async def __call__(self, scope, receive, send):
if scope["type"] not in ("http", "websocket"):
@@ -216,9 +324,11 @@ async def __call__(self, scope, receive, send):
return await self.inner(scope, receive, send)
if scope["type"] == "http" and path == "/pair":
return await self._pair(scope, send)
+ if scope["type"] == "http" and path == "/pair/wait":
+ return await self._wait(scope, send)
device = _device_of(scope)
if device:
- return await self._held(scope, receive, send, device)
+ return await self._held(scope, receive, send, *device)
await _refuse(scope, send)
@@ -276,6 +386,7 @@ async def _launch() -> None:
def stop_server() -> None:
global _server
+ _forget_requests()
if _server is not None:
_server.should_exit = True
_server = None
@@ -291,26 +402,39 @@ def status() -> dict:
on = running()
urls = [f"https://{ip}:{LAN_PORT}" for ip in lan_addresses()] if on else []
fp = lan_cert.fingerprint()
- out = {"on": on, "port": LAN_PORT, "urls": urls, "pairUrl": None, "qr": None,
- "fingerprint": lan_cert.spaced(fp), "devices": device_tokens.listing()}
+ out = {"on": on, "port": LAN_PORT, "urls": urls, "pairUrl": None, "qr": None, "pairExpiresIn": None,
+ "fingerprint": lan_cert.spaced(fp), "devices": device_tokens.listing(), "pending": pending() if on else []}
if on and urls and fp:
- out["pairUrl"] = f"{urls[0]}/pair?code={_code()}&fp={fp}"
+ held = _current_code()
+ out["pairUrl"] = f"{urls[0]}/pair?code={held['code']}&fp={fp}"
out["qr"] = _qr(out["pairUrl"])
+ out["pairExpiresIn"] = max(0, round(held["made"] + CODE_LIFE - time.time()))
return out
def _changed() -> None:
- events.publish("devices.changed", devices={"on": running(), "paired": len(device_tokens.listing())})
+ events.publish("devices.changed", devices={"on": running(), "paired": len(device_tokens.listing()), "waiting": len(pending())})
@command("devices.status", "Other devices", mutates=False,
- description="Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint, the paired devices, and, when on, the one-time pairing link and its QR code as SVG.")
+ description="Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint and the paired devices. Only FormAT's window also gets the pairing link, its QR code as SVG, how many seconds the code has left, and the devices waiting to be allowed.")
def devices_status() -> dict:
return status()
-@command("devices.start", "Open to other devices",
- description="Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code.")
+@command("devices.answer", "Allow or turn down a device",
+ {"id": {"type": "string", "required": True, "description": "request id from devices.status pending"},
+ "allow": {"type": "boolean", "required": True, "description": "true pairs the device, false turns it down"}},
+ description="Answers a device that opened the pairing link and is waiting: allow pairs it, otherwise it is turned down. Only FormAT's window can run this.", window_only=True)
+def devices_answer(id: str, allow: bool) -> dict:
+ if not answer(id, allow):
+ raise CommandError("That device is no longer waiting; it may have given up or its request ran out of time", 404)
+ _changed()
+ return status()
+
+
+@command("devices.start", "Open to other devices", window_only=True,
+ description="Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Only FormAT's window can run this; it gets the pairing link and QR code back.")
def devices_start() -> dict:
_start()
_changed()
@@ -330,8 +454,8 @@ def devices_list() -> dict:
return {"devices": device_tokens.listing()}
-@command("devices.revoke", "Unpair a device", {"id": {"type": "string", "required": True, "description": "device id from devices.list"}},
- description="Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code.")
+@command("devices.revoke", "Unpair a device", {"id": {"type": "string", "required": True, "description": "device id from devices.list"}}, window_only=True,
+ description="Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code. Only FormAT's window can run this.")
def devices_revoke(id: str) -> dict:
if not device_tokens.revoke(id):
raise CommandError(f"No paired device {id}; devices.list gives the ids", 404)
@@ -339,9 +463,11 @@ def devices_revoke(id: str) -> dict:
return status()
-@command("devices.forget", "Forget paired devices", description="Unpairs every device at once and changes the pairing code, so each one has to pair again.")
+@command("devices.forget", "Forget paired devices", window_only=True,
+ description="Unpairs every device at once, turns down any device still waiting and changes the pairing code, so each one has to pair again. Only FormAT's window can run this.")
def devices_forget() -> dict:
device_tokens.revoke_all()
+ _forget_requests()
_code(rotate=True)
_changed()
return status()
diff --git a/backend/app/routers/commands.py b/backend/app/routers/commands.py
index bf0e70c..73178c3 100644
--- a/backend/app/routers/commands.py
+++ b/backend/app/routers/commands.py
@@ -42,12 +42,15 @@ def describe(cid: str) -> Any:
@router.post("/commands/{cid}")
def run(request: Request, cid: str, params: dict | None = Body(default=None), x_format_agent: str | None = Header(default=None)) -> Any:
outside = bool(x_format_agent) or not window_key.is_window(request.scope)
- if outside:
- try:
+ own = not x_format_agent and window_key.own_window(request.scope)
+ try:
+ if outside:
agents.require_outside(x_format_agent or "", "stdio" if x_format_agent else "rest", cid, params)
- except CommandError as exc:
- return JSONResponse({"ok": False, "command": cid, "error": str(exc)}, status_code=exc.status)
+ if not own:
+ agents.refuse_window_only(cid)
+ except CommandError as exc:
+ return JSONResponse({"ok": False, "command": cid, "error": str(exc)}, status_code=exc.status)
status, body = _run(cid, params)
- if outside and status == 200:
+ if not own and status == 200:
body = body | {"result": agents.outside_result(cid, body["result"])}
return body if status == 200 else JSONResponse(body, status_code=status)
diff --git a/backend/app/routers/mcp_http.py b/backend/app/routers/mcp_http.py
index b0305e7..e66b8e5 100644
--- a/backend/app/routers/mcp_http.py
+++ b/backend/app/routers/mcp_http.py
@@ -13,6 +13,7 @@
async def _call(cid: str, params: dict, client: str):
def run():
agents.require_outside(client, "http", cid, params)
+ agents.refuse_window_only(cid)
return agents.outside_result(cid, dispatch(cid, params))
return await anyio.to_thread.run_sync(run)
diff --git a/backend/tests/test_artifacts_and_devices.py b/backend/tests/test_artifacts_and_devices.py
index 8d1f0f3..d976934 100644
--- a/backend/tests/test_artifacts_and_devices.py
+++ b/backend/tests/test_artifacts_and_devices.py
@@ -98,12 +98,34 @@ async def send(message):
return api.called, sent
-def _pair(agent=PHONE):
+def _cookies_set(message):
+ return [v.decode() for k, v in message["headers"] if k == b"set-cookie"]
+
+
+def _ask(agent=PHONE):
lan_cert.ensure(["192.0.2.10"])
query = f"code={devices._code()}&fp={lan_cert.fingerprint()}".encode()
called, sent = _through_gate("/pair", query=query, agent=agent)
assert not called and sent[0]["status"] == 303, sent
- cookie = dict(sent[0]["headers"])[b"set-cookie"].decode()
+ assert dict(sent[0]["headers"])[b"location"] == b"/pair/wait"
+ (cookie,) = _cookies_set(sent[0])
+ assert not cookie.startswith(f"{devices.COOKIE}=")
+ return cookie.split(";", 1)[0]
+
+
+def _poll(wait):
+ called, sent = _through_gate("/pair/wait", wait)
+ assert not called
+ return sent
+
+
+def _pair(agent=PHONE):
+ wait = _ask(agent)
+ rid = devices.pending()[-1]["id"]
+ dispatch("devices.answer", {"id": rid, "allow": True})
+ sent = _poll(wait)
+ assert sent[0]["status"] == 303, sent
+ cookie = next(c for c in _cookies_set(sent[0]) if c.startswith(f"{devices.COOKIE}="))
return cookie, cookie.split(";", 1)[0]
diff --git a/backend/tests/test_device_pairing_consent.py b/backend/tests/test_device_pairing_consent.py
new file mode 100644
index 0000000..f8aea9b
--- /dev/null
+++ b/backend/tests/test_device_pairing_consent.py
@@ -0,0 +1,168 @@
+import json
+from types import SimpleNamespace
+
+import pytest
+from conftest import set_policy
+from fastapi.testclient import TestClient
+from test_artifacts_and_devices import PHONE, _ask, _cookies_set, _pair, _poll, _through_gate
+
+from _format import run
+from app.engine import device_tokens, devices, lan_cert, store
+from app.engine.commands import dispatch
+
+WINDOW_ONLY = ("devices.start", "devices.revoke", "devices.forget", "devices.answer")
+ORIGIN = f"https://192.0.2.10:{devices.LAN_PORT}"
+
+
+@pytest.fixture
+def clean(client, monkeypatch):
+ monkeypatch.setattr(devices, "running", lambda: True)
+ monkeypatch.setattr(devices, "lan_addresses", lambda: ["192.0.2.10"])
+ monkeypatch.setattr(devices, "_start", lambda: None)
+ lan_cert.ensure(["192.0.2.10"])
+ run(client, "devices.forget")
+ yield
+ run(client, "devices.forget")
+ set_policy("ask")
+
+
+def _phone(app, cookie):
+ return TestClient(devices.Gate(app, None), base_url=ORIGIN, headers={"cookie": cookie, "origin": ORIGIN})
+
+
+def _params(cid):
+ return {"devices.revoke": {"id": "x"}, "devices.answer": {"id": "x", "allow": True}}.get(cid, {})
+
+
+def test_a_paired_device_gets_no_pairing_link_code_or_waiting_devices(app, client, clean):
+ _, pair = _pair()
+ _ask("Mozilla/5.0 (Linux; Android 15) Chrome/140.0 Mobile Safari/537.36")
+ code = devices._code()
+ r = _phone(app, pair).post("/api/commands/devices.status", json={})
+ assert r.status_code == 200, r.text
+ got = r.json()["result"]
+ assert got["on"] is True and got["fingerprint"] and got["devices"]
+ assert got["pairUrl"] is None and got["qr"] is None and got["pending"] == []
+ assert "pairExpiresIn" not in got
+ assert code not in r.text
+ own = run(client, "devices.status")
+ assert code in own["pairUrl"] and own["qr"] and len(own["pending"]) == 1
+
+
+@pytest.mark.parametrize("cid", WINDOW_ONLY)
+def test_a_paired_device_cannot_pair_unpair_forget_or_start(app, client, clean, cid):
+ _, pair = _pair()
+ before = run(client, "devices.list")["devices"]
+ r = _phone(app, pair).post(f"/api/commands/{cid}", json=_params(cid))
+ assert r.status_code == 403, r.text
+ assert "Only the FormAT window" in r.json()["error"]
+ assert run(client, "devices.list")["devices"] == before
+
+
+@pytest.mark.parametrize("cid", WINDOW_ONLY)
+def test_an_outside_agent_cannot_pair_unpair_forget_or_start(client, bare, clean, cid):
+ from test_f3_mcp import call, session
+
+ set_policy("allowed")
+ r = client.post(f"/api/commands/{cid}", json=_params(cid), headers={"x-format-agent": "some agent"})
+ assert r.status_code == 403 and "Only the FormAT window" in r.json()["error"]
+ r = bare.post(f"/api/commands/{cid}", json=_params(cid))
+ assert r.status_code == 403
+ got = call(client, "run_command", {"id": cid, "params": _params(cid)}, session(client))
+ assert got.get("isError") and "Only the FormAT window" in json.dumps(got)
+
+
+def test_the_window_still_runs_the_window_only_commands(client, clean):
+ _, pair = _pair()
+ did = run(client, "devices.list")["devices"][0]["id"]
+ assert run(client, "devices.revoke", {"id": did})["devices"] == []
+ assert run(client, "devices.start")["pairUrl"]
+
+
+def test_a_pairing_code_runs_out_after_a_few_minutes(client, clean, monkeypatch):
+ clock = {"now": 1_000_000.0}
+ monkeypatch.setattr(devices, "time", SimpleNamespace(time=lambda: clock["now"]))
+ code = devices._code(rotate=True)
+ left = run(client, "devices.status")["pairExpiresIn"]
+ assert 0 < left <= devices.CODE_LIFE <= 600
+ clock["now"] += devices.CODE_LIFE + 1
+ called, sent = _through_gate("/pair", query=f"code={code}&fp={lan_cert.fingerprint()}".encode())
+ assert not called and sent[0]["status"] == 401
+ assert devices.pending() == []
+ fresh = run(client, "devices.status")
+ assert code not in fresh["pairUrl"] and fresh["pairExpiresIn"] == devices.CODE_LIFE
+
+
+def test_a_scan_waits_for_the_window_and_issues_no_token_before_it_allows(client, clean):
+ wait = _ask()
+ assert run(client, "devices.list")["devices"] == []
+ (asked,) = run(client, "devices.status")["pending"]
+ assert asked["name"] == "iPhone, Safari" and len(asked["check"]) == 6
+ assert "secret" not in asked and "state" not in asked
+ sent = _poll(wait)
+ assert sent[0]["status"] == 200
+ assert not any(c.startswith(f"{devices.COOKIE}=") for c in _cookies_set(sent[0]))
+ page = sent[1]["body"].decode()
+ assert "http-equiv=refresh" in page and "iPhone, Safari" in page
+ assert f"{asked['check'][:3]} {asked['check'][3:]}" in page
+ assert lan_cert.spaced(lan_cert.fingerprint()) in page
+ called, sent = _through_gate("/api/commands", wait)
+ assert not called and sent[0]["status"] == 401
+ run(client, "devices.answer", {"id": asked["id"], "allow": True})
+ sent = _poll(wait)
+ assert sent[0]["status"] == 303 and dict(sent[0]["headers"])[b"location"] == b"/"
+ token = next(c for c in _cookies_set(sent[0]) if c.startswith(f"{devices.COOKIE}=")).split(";", 1)[0]
+ assert _through_gate("/api/commands", token)[0]
+ assert [d["name"] for d in run(client, "devices.list")["devices"]] == ["iPhone, Safari"]
+ assert run(client, "devices.status")["pending"] == []
+ assert _poll(wait)[0]["status"] == 401
+
+
+def test_a_device_turned_down_in_the_window_is_not_paired(client, clean):
+ wait = _ask()
+ rid = run(client, "devices.status")["pending"][0]["id"]
+ run(client, "devices.answer", {"id": rid, "allow": False})
+ sent = _poll(wait)
+ assert sent[0]["status"] == 403
+ assert not any(c.startswith(f"{devices.COOKIE}=") for c in _cookies_set(sent[0]))
+ assert run(client, "devices.list")["devices"] == []
+ assert _poll(wait)[0]["status"] == 401
+ r = client.post("/api/commands/devices.answer", json={"id": rid, "allow": True})
+ assert r.status_code == 404
+
+
+def test_a_waiting_device_runs_out_of_time_and_a_made_up_wait_cookie_is_refused(client, clean, monkeypatch):
+ clock = {"now": 2_000_000.0}
+ monkeypatch.setattr(devices, "time", SimpleNamespace(time=lambda: clock["now"]))
+ wait = _ask()
+ rid = devices.pending()[0]["id"]
+ assert _poll(f"{devices.WAIT_COOKIE}=made-up")[0]["status"] == 401
+ clock["now"] += devices.REQUEST_LIFE + 1
+ assert devices.pending() == []
+ assert client.post("/api/commands/devices.answer", json={"id": rid, "allow": True}).status_code == 404
+ assert _poll(wait)[0]["status"] == 401
+ assert run(client, "devices.list")["devices"] == []
+
+
+def test_closing_or_forgetting_drops_waiting_devices(client, clean):
+ wait = _ask()
+ run(client, "devices.forget")
+ assert devices.pending() == [] and _poll(wait)[0]["status"] == 401
+ wait = _ask()
+ devices.stop_server()
+ assert devices.pending() == [] and _poll(wait)[0]["status"] == 401
+
+
+def test_a_device_whose_token_changes_while_it_is_being_admitted_is_refused(client, clean, monkeypatch):
+ _, pair = _pair()
+ did = run(client, "devices.list")["devices"][0]["id"]
+ real_watch = device_tokens.watch
+
+ def swap_then_watch(device):
+ store.run("UPDATE paired_devices SET token_hash = ? WHERE id = ?", ("0" * 64, did))
+ return real_watch(device)
+
+ monkeypatch.setattr(device_tokens, "watch", swap_then_watch)
+ called, sent = _through_gate("/api/commands", pair, agent=PHONE)
+ assert not called and sent[0]["status"] == 401
+ assert device_tokens._live == {}
diff --git a/docs/other-devices.md b/docs/other-devices.md
index ad143ba..5f1a489 100644
--- a/docs/other-devices.md
+++ b/docs/other-devices.md
@@ -7,9 +7,14 @@ FormAT runs on one computer, but you can carry on from your phone or another com
1. On the computer running FormAT, open Settings, Other devices, and choose Open to other devices.
2. Scan the code with your phone's camera, or open the link shown under it on the other device.
3. The other device's browser warns that it does not know the certificate. That is expected: FormAT makes its own certificate for this computer the first time you open it to other devices. Open the certificate details in the warning and check that its SHA-256 fingerprint matches the one Settings shows under the code, then continue. The browser remembers the certificate after that.
-4. The other device opens FormAT, paired. It sees the same chats, live, both ways: start a chat on the computer and continue it on the phone.
+4. The other device shows a waiting page with its name (for example "iPhone, Safari"), a six-digit check number and the certificate fingerprint. On the computer, Settings, Other devices shows the same request with the same name, check number and fingerprint. If they match the device in your hand, choose Allow; otherwise choose Turn down.
+5. The other device opens FormAT, paired, within a few seconds. It sees the same chats, live, both ways: start a chat on the computer and continue it on the phone.
-Each code pairs one device. Once a device has used it, Settings shows a new code, so pair each phone or computer with its own scan. A link that was already used, or that names a different certificate, shows a page saying so; scan the code shown now.
+Nothing is paired until you choose Allow in FormAT's window on the computer. A device that is turned down, or that waits more than five minutes, has to scan a new code.
+
+Each code pairs one device and lasts five minutes; Settings shows a new code when it runs out and once a device has used it, so pair each phone or computer with its own scan. A link that was already used, that ran out, or that names a different certificate, shows a page saying so; scan the code shown now.
+
+Only FormAT's window on the computer shows the pairing code and link, and only it can open FormAT to other devices, allow a device, unpair one or forget them all. A paired phone sees the paired devices and the fingerprint, but not the code, and cannot pair, unpair or forget devices. Agents connected over MCP or the command line cannot either.
A device that is not paired gets a page saying so.
@@ -21,7 +26,7 @@ Settings, Other devices lists every paired device with the browser it paired fro
FormAT listens on your network (port 8492) only while this is on, and only over https: a plain http request to that port gets no answer. The certificate and its private key stay in FormAT's data folder, readable by your user account only. The certificate lasts about two years; FormAT makes a new one shortly before it expires, and each browser warns once more.
-The code is a secret until it is used: anyone on your network who has an unused code can pair a device and use FormAT as you, with your API key. Share it only with your own devices, and unpair a device you no longer use or have lost.
+The code is a secret until it is used, and it runs out after five minutes. A device that uses it still needs you to choose Allow on the computer, so check the name and check number before you do: a request you did not expect, or one whose check number differs from your device's page, is not your device. Paired devices use FormAT as you, with your API key; unpair a device you no longer use or have lost.
Devices paired with a version of FormAT before this change have to pair again once.
diff --git a/docs/settings.md b/docs/settings.md
index 9ee972b..eaa44b2 100644
--- a/docs/settings.md
+++ b/docs/settings.md
@@ -36,7 +36,7 @@ The sections, in order: Account, API keys, Tools, Long chats, Memory, Voice, Oth
## Other devices
-Open or close FormAT to your network, the pairing code and link, the certificate fingerprint to compare on the other device, the list of paired devices with Unpair beside each, and Forget paired devices. See [Other devices](other-devices.md).
+Open or close FormAT to your network, the pairing code and link (each code lasts five minutes), the certificate fingerprint to compare on the other device, devices waiting to pair with Allow and Turn down, the list of paired devices with Unpair beside each, and Forget paired devices. See [Other devices](other-devices.md).
## Outside agents
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index c7c5845..8854e3d 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -16,7 +16,9 @@ Start with `./format doctor`: it checks Node, Python, the installs, your key and
| Claude's commands fail to install packages | the sandbox has no network by default; allow it in Settings, Tools, or turn the sandbox off |
| A phone cannot open the pairing link | both devices must be on the same network, and a firewall must allow port 8492 on the computer; the link starts with https, and typing http instead gets no answer |
| The phone's browser warns about the certificate | expected the first time: FormAT uses its own certificate; check that the fingerprint in the certificate details matches the one in Settings, Other devices, then continue |
-| The pairing page says the link was used or is out of date | each code pairs one device; scan the code Settings shows now |
+| The pairing page says the link was used or is out of date | each code pairs one device and lasts five minutes; scan the code Settings shows now |
+| The phone stays on the waiting page | choose Allow beside its request in Settings, Other devices, on the computer; a request runs out after five minutes |
+| The phone says FormAT's window turned it down | Turn down was chosen on the computer; scan the code Settings shows now and choose Allow |
| A device that used to be paired asks to pair again | it was unpaired, or it paired with a version of FormAT before per-device pairing; scan the code again |
| A share link says "no longer shared" | sharing was stopped; Share again makes a new link |
| A plugin will not add | the .zip needs `.claude-plugin/plugin.json` with a name (lowercase, hyphens) and a description |
diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md
index 8481494..799d325 100644
--- a/frontend/HASHOUT_LOG.md
+++ b/frontend/HASHOUT_LOG.md
@@ -1222,3 +1222,10 @@ The engine now answers `GET /api/browser/frame` only to the window (see the engi
- logged: unreleased
The engine now pairs each device with its own token and serves other devices over https with a per-install certificate (backend HASHOUT, same entry name). The pairing box gains one line with the certificate's SHA-256 fingerprint, filled with `setText` while the box is shown, so the person can compare it with the warning on the other device. A Paired devices group lists each device keyed by id: rows that are gone are removed, new ones appended, and the name and times written through `setText`, so a repaint of the same list touches nothing; Unpair is one delegated click handler that calls devices.revoke. The list is empty (hidden by `:empty`) with the "No devices are paired" note toggled only when its state changes. `devices.changed` no longer carries the pairing link; the window answers it with devices.status, which also repaints the code after a scan spends it.
+
+### src/ui/views.ts, src/styles/ft-shell.css · Settings, Other devices asks before it pairs a device
+- refers-to: src/ui/views.ts :: `PairRequest`, `codeTimer`, the `.ft-dev-asks` click handler, `paintDevices`, `paintAsks`; src/styles/ft-shell.css `.ft-dev-asks`, `.ft-dev-ask`, `.ft-dev-answer`
+- kind: feature
+- logged: unreleased
+
+The engine no longer pairs a device on the scan; it waits for the window (backend HASHOUT, "Pairing asks the window, codes run out, and pairing is window-only"). Under the pairing box, `.ft-dev-asks` lists each waiting device keyed by id, with its name, its check number and the certificate fingerprint, and Allow and Turn down, which call devices.answer through one delegated handler. A row is built once and only removed when the request is gone, so a repaint touches nothing; the list is hidden by `:empty`, and a row appears only when a device asks. A refused answer (the request ran out) shows the engine's sentence and repaints from devices.status. The code now lasts five minutes: `paintDevices` sets one timer from `pairExpiresIn` and asks for status again when it runs out, so the QR changes in place; the timer is cleared on every paint.
diff --git a/frontend/src/styles/ft-shell.css b/frontend/src/styles/ft-shell.css
index 23eae1a..611cc7e 100644
--- a/frontend/src/styles/ft-shell.css
+++ b/frontend/src/styles/ft-shell.css
@@ -595,8 +595,11 @@ textarea.ft-input { resize: vertical; line-height: 1.5; overflow-y: auto; }
.ft-dev-qr svg { width: 100%; height: 100%; border-radius: var(--radius-md); }
.ft-dev-text { display: grid; gap: var(--space-1); min-width: 0; font-size: var(--fs-12); color: var(--text-secondary); }
.ft-dev-url, .ft-dev-fp { font: var(--fs-12) var(--font-mono); color: var(--text-primary); overflow-wrap: anywhere; user-select: all; }
-.ft-dev-list { display: grid; gap: var(--space-2); margin: 0; padding: 0; list-style: none; }
-.ft-dev-list:empty, .ft-dev-none[hidden] { display: none; }
+.ft-dev-list, .ft-dev-asks { display: grid; gap: var(--space-2); margin: 0; padding: 0; list-style: none; }
+.ft-dev-list:empty, .ft-dev-asks:empty, .ft-dev-none[hidden] { display: none; }
+.ft-dev-asks { margin-top: var(--space-3); }
+.ft-dev-ask { grid-template-rows: auto auto auto; border-color: var(--accent-color); }
+.ft-dev-answer { grid-column: 2; grid-row: 1 / span 3; display: flex; flex-wrap: wrap; gap: var(--space-2); }
.ft-dev-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: auto auto; column-gap: var(--space-3); align-items: center; padding: var(--space-2) var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius-lg); background: var(--surface-1); }
.ft-dev-name { min-width: 0; font-size: var(--fs-13); color: var(--text-primary); overflow-wrap: anywhere; }
.ft-dev-seen { grid-column: 1; font-size: var(--fs-12); color: var(--text-muted); }
diff --git a/frontend/src/ui/views.ts b/frontend/src/ui/views.ts
index 48dd723..daf45b1 100644
--- a/frontend/src/ui/views.ts
+++ b/frontend/src/ui/views.ts
@@ -95,7 +95,8 @@ function sourceText(k: KeyStatus | undefined): string {
}
interface PairedDevice { id: string; name: string; created: number; seen: number }
-interface DevicesStatus { on: boolean; port: number; urls: string[]; pairUrl: string | null; qr: string | null; fingerprint?: string | null; devices?: PairedDevice[] }
+interface PairRequest { id: string; name: string; check: string; created: number }
+interface DevicesStatus { on: boolean; port: number; urls: string[]; pairUrl: string | null; qr: string | null; pairExpiresIn?: number | null; fingerprint?: string | null; devices?: PairedDevice[]; pending?: PairRequest[] }
export type SettingsSection = 'Account' | 'API keys' | 'Tools' | 'Long chats' | 'Memory' | 'Voice' | 'Other devices' | 'Outside agents' | 'About';
@@ -103,6 +104,7 @@ const SECTION_ORDER: SettingsSection[] = ['Account', 'API keys', 'Tools', 'Long
export class SettingsView {
private root: HTMLElement;
+ private codeTimer = 0;
constructor(private state: AppState, prefs: PrefsWindow, memory: HTMLElement) {
this.root = prefs.pages;
@@ -155,11 +157,12 @@ export class SettingsView {
`);
prefs.add('Other devices', 'devices', `
-
Continue on your phone or another computer on the same network: turn this on, then scan the code or open the link there. The connection is encrypted with this computer's own certificate, so the other browser warns once; check its fingerprint against the one shown here. Each code pairs one device. Paired devices see the same chats live; shared artifact links open for anyone who can reach this computer, read-only. Turn it off to keep FormAT on this computer only.
+
Continue on your phone or another computer on the same network: turn this on, then scan the code or open the link there. The connection is encrypted with this computer's own certificate, so the other browser warns once; check its fingerprint against the one shown here. Each code pairs one device and lasts five minutes, and FormAT asks here before it pairs a device that used it. Paired devices see the same chats live; shared artifact links open for anyone who can reach this computer, read-only. Turn it off to keep FormAT on this computer only.
Pairing
Open on the other device:Certificate fingerprint (SHA-256), to compare with the one the other device's browser shows:
@@ -242,6 +244,13 @@ export class SettingsView {
this.root.querySelectorAll('[data-t]').forEach((box) => {
box.addEventListener('change', () => void run('settings.set', { key: box.dataset.t, value: box.checked }).catch(() => undefined));
});
+ const hosts = q(this.root, '.ft-cc-domains');
+ hosts.addEventListener('change', () => {
+ const value = hosts.value.split(/[\s,]+/).filter(Boolean);
+ void run('settings.set', { key: 'claudeCodeDomains', value })
+ .then(() => setText(q(this.root, '.ft-cc-domains-msg'), 'Saved; it applies from the next Claude Code reply.'))
+ .catch((err) => setText(q(this.root, '.ft-cc-domains-msg'), err instanceof Error ? err.message : String(err)));
+ });
q(this.root, '.ft-allowed-list').addEventListener('click', (e) => {
const name = (e.target as HTMLElement).closest('[data-tool]')?.dataset.tool;
if (!name) return;
@@ -381,8 +390,12 @@ export class SettingsView {
const on = box.dataset.off ? v === true : v !== false;
if (box.checked !== on) box.checked = on;
});
- void run<{ note: string; available: boolean }>('sandbox.status').then((sb) => {
+ const hosts = q(this.root, '.ft-cc-domains');
+ const hostText = (s.claudeCodeDomains ?? []).join(', ');
+ if (document.activeElement !== hosts && hosts.value !== hostText) hosts.value = hostText;
+ void run<{ note: string; available: boolean; claudeCode?: { note: string } }>('sandbox.status').then((sb) => {
setText(q(this.root, '.ft-sandbox-note'), sb.note);
+ if (sb.claudeCode) setText(q(this.root, '.ft-cc-sandbox-note'), sb.claudeCode.note);
const box = q(this.root, '[data-t="sandbox"]');
if (box.disabled === sb.available) box.disabled = !sb.available;
}).catch(() => undefined);
From bfa8910edf676cd7f106d2c439034082ed450176 Mon Sep 17 00:00:00 2001
From: gbarnai
Date: Sun, 29 Nov 2026 17:43:21 -0500
Subject: [PATCH 7/8] fix: keep Claude Code's file tools off uploads and skills
and its sandboxed commands off FormAT's data folder
The launch settings deny Claude Code's Edit rules on the uploads and skills
folders on every platform (Windows paths in the //c/ form), hide FormAT's
data folder from sandboxed commands apart from the chat folder, uploads and
skills, and refuse bypass flags also when spelled --flag=value.
---
backend/HASHOUT_LOG.md | 2 ++
backend/app/engine/claude_code.py | 3 ++-
backend/app/engine/claude_code_sandbox.py | 26 +++++++++++++++++------
backend/tests/test_claude_code_sandbox.py | 19 ++++++++++++++---
docs/getting-started.md | 2 +-
5 files changed, 40 insertions(+), 12 deletions(-)
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index 8b747e1..5c85e2c 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -1407,6 +1407,8 @@ Platforms. `support` takes the platform, a `which` and the kernel release so tes
Window. `sandbox.status` gains `claudeCode` (sandboxed, kind, domains, note) and `claudecode.status` gains `sandbox`; each reply's `meta.claudeCode.sandboxed` records what that reply ran with. `claudeCodeDomains` is checked on save: host names or `*.` wildcards, lowercased, duplicates dropped, at most 200 (tests/test_claude_code_sandbox.py, which needs no Claude Code).
+Reads and file tools. The sandbox's `filesystem.denyRead` holds FormAT's data folder (its database, tokens and certificate key) with `allowRead` re-opening the chat folder, uploads and skills, as FormAT's own sandbox hides the data folder. `--add-dir` also made uploads and skills writable for Claude Code's own Write and Edit tools, which the sandbox does not cover and which Allow all accepts without asking inside added folders; `permissions.deny` now carries an `Edit(///**)` rule for each (on Windows `//c/...`, the POSIX form Claude Code matches rules against), on every platform, so a Claude Code chat reads installed skills but cannot replace one outside the overwrite check (that route has no `save_skill`). `check_args` also refuses the `--flag=value` spellings. The home folder stays readable to Claude Code's sandboxed commands: hiding it, as FormAT's own sandbox does, was not tried without a live session, since Claude Code keeps its own files there.
+
Not done here: whether `excludedCommands` and `allowedDomains` from the person's own user settings merge with the launch file's lists was not confirmed in the binary; a person's own entries there may still apply. No real Claude Code session was started (the rules for this change forbid signing in), so the sandbox was not seen refusing a write or a host in a live reply.
### A skill name already in use is never replaced without asking (unreleased)
diff --git a/backend/app/engine/claude_code.py b/backend/app/engine/claude_code.py
index 480dda5..620742e 100644
--- a/backend/app/engine/claude_code.py
+++ b/backend/app/engine/claude_code.py
@@ -6,6 +6,7 @@
from pathlib import Path
from app import providers
+from app.core import config
from app.engine import agent_lookup, claude_code_sandbox, events, projects, skills, tools, uploads
from app.engine.cmd_account import account
from app.engine.cmd_message import messages_of, update
@@ -400,7 +401,7 @@ def drain() -> None:
try:
if not found["installed"]:
raise providers.ProviderError(found.get("said") or "Claude Code is not installed: install it from https://claude.com/claude-code and sign in once with `claude`")
- launch = claude_code_sandbox.write_launch(claude_code_sandbox.settings_for(Path(folder), list(settings.get("claudeCodeDomains") or []), [uploads.root(), skills.root()], boxed))
+ launch = claude_code_sandbox.write_launch(claude_code_sandbox.settings_for(Path(folder), list(settings.get("claudeCodeDomains") or []), [uploads.root(), skills.root()], boxed, [config.data_dir()]))
args = launch_args(found["path"] or "claude", model["id"], settings, _system(conversation_id), launch, servers, blocked, session)
run_env = child_env(found["path"])
proc = subprocess.Popen(agent_lookup.start_argv(args, run_env), cwd=folder, env=run_env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
diff --git a/backend/app/engine/claude_code_sandbox.py b/backend/app/engine/claude_code_sandbox.py
index 19c1032..f620910 100644
--- a/backend/app/engine/claude_code_sandbox.py
+++ b/backend/app/engine/claude_code_sandbox.py
@@ -5,7 +5,7 @@
import shutil
import sys
from collections.abc import Callable
-from pathlib import Path
+from pathlib import Path, PurePosixPath, PureWindowsPath
from app import providers
from app.core import config
@@ -52,8 +52,18 @@ def clean_domains(value: object) -> list[str]:
return out
-def settings_for(workspace: Path, domains: list[str], read_only: list[Path], found: dict) -> dict:
- out: dict = {"permissions": {"disableBypassPermissionsMode": "disable"}}
+def edit_rule(path: Path | str, windows: bool) -> str:
+ if windows:
+ p = PureWindowsPath(str(path))
+ drive = p.drive.rstrip(":").lower()
+ rest = "/".join(p.parts[1:])
+ return f"Edit(//{drive}/{rest}/**)" if len(drive) == 1 else f"Edit({p.as_posix()}/**)"
+ return f"Edit(/{PurePosixPath(str(path)).as_posix()}/**)"
+
+
+def settings_for(workspace: Path, domains: list[str], read_only: list[Path], found: dict, hidden: list[Path] | None = None, windows: bool | None = None) -> dict:
+ win = sys.platform in ("win32", "cygwin") if windows is None else windows
+ out: dict = {"permissions": {"disableBypassPermissionsMode": "disable", "deny": [edit_rule(p, win) for p in read_only]}}
if not found["available"]:
return out
out["sandbox"] = {
@@ -63,16 +73,18 @@ def settings_for(workspace: Path, domains: list[str], read_only: list[Path], fou
"allowUnsandboxedCommands": False,
"excludedCommands": [],
"network": {"allowedDomains": list(domains), "strictAllowlist": True},
- "filesystem": {"allowWrite": [str(workspace)], "denyWrite": [str(p) for p in read_only]},
+ "filesystem": {"allowWrite": [str(workspace)], "denyWrite": [str(p) for p in read_only],
+ "denyRead": [str(p) for p in hidden or []], "allowRead": [str(workspace), *(str(p) for p in read_only)]},
}
return out
def check_args(args: list[str]) -> None:
for i, word in enumerate(args):
- if word in FORBIDDEN_FLAGS:
- raise LaunchRefused(f"FormAT never starts Claude Code with {word}")
- if word == "--permission-mode" and i + 1 < len(args) and args[i + 1] in FORBIDDEN_MODES:
+ flag, eq, value = word.partition("=")
+ if flag in FORBIDDEN_FLAGS:
+ raise LaunchRefused(f"FormAT never starts Claude Code with {flag}")
+ if flag == "--permission-mode" and (value if eq else (args[i + 1] if i + 1 < len(args) else "")) in FORBIDDEN_MODES:
raise LaunchRefused("FormAT never starts Claude Code in bypass permissions mode")
diff --git a/backend/tests/test_claude_code_sandbox.py b/backend/tests/test_claude_code_sandbox.py
index cae96b8..6a3f5d9 100644
--- a/backend/tests/test_claude_code_sandbox.py
+++ b/backend/tests/test_claude_code_sandbox.py
@@ -32,8 +32,9 @@ def test_the_sandbox_is_offered_only_where_claude_code_can_run_one(plat, present
def test_launch_settings_turn_the_sandbox_on_for_the_workspace_only(tmp_path, plat, present, release, expected):
found = box.support(plat, which_of(*present), release)
work, uploads = tmp_path / "chat", tmp_path / "uploads"
- out = box.settings_for(work, ["example.com"], [uploads], found)
+ out = box.settings_for(work, ["example.com"], [uploads], found, [tmp_path], windows=False)
assert out["permissions"]["disableBypassPermissionsMode"] == "disable"
+ assert len(out["permissions"]["deny"]) == 1 and out["permissions"]["deny"][0].startswith("Edit(//")
if not expected:
assert "sandbox" not in out
return
@@ -41,7 +42,18 @@ def test_launch_settings_turn_the_sandbox_on_for_the_workspace_only(tmp_path, pl
assert sb["enabled"] is True and sb["failIfUnavailable"] is True
assert sb["allowUnsandboxedCommands"] is False and sb["autoAllowBashIfSandboxed"] is False and sb["excludedCommands"] == []
assert sb["network"] == {"allowedDomains": ["example.com"], "strictAllowlist": True}
- assert sb["filesystem"] == {"allowWrite": [str(work)], "denyWrite": [str(uploads)]}
+ assert sb["filesystem"] == {"allowWrite": [str(work)], "denyWrite": [str(uploads)], "denyRead": [str(tmp_path)], "allowRead": [str(work), str(uploads)]}
+
+
+@pytest.mark.parametrize("path,windows,rule", [
+ ("/data/skills", False, "Edit(//data/skills/**)"),
+ ("/Users/a b/data/uploads", False, "Edit(//Users/a b/data/uploads/**)"),
+ ("C:\\Users\\a\\FormAT\\skills", True, "Edit(//c/Users/a/FormAT/skills/**)"),
+ ("d:\\data\\uploads", True, "Edit(//d/data/uploads/**)"),
+])
+def test_claude_code_file_tools_cannot_change_the_read_only_folders(path, windows, rule):
+ assert box.edit_rule(path, windows) == rule
+ assert box.settings_for(Path("/w"), [], [Path(path)], {"available": False}, windows=windows)["permissions"]["deny"] == [rule]
@pytest.mark.parametrize("plat,present,release,expected", PLATFORMS)
@@ -68,7 +80,8 @@ def test_launch_arguments_carry_the_settings_file_and_never_bypass(tmp_path, mod
assert not set(args) & set(box.FORBIDDEN_FLAGS)
-@pytest.mark.parametrize("bad", [["--dangerously-skip-permissions"], ["--allow-dangerously-skip-permissions"], ["--permission-mode", "bypassPermissions"]])
+@pytest.mark.parametrize("bad", [["--dangerously-skip-permissions"], ["--allow-dangerously-skip-permissions"], ["--permission-mode", "bypassPermissions"],
+ ["--permission-mode=bypassPermissions"], ["--dangerously-skip-permissions=true"]])
def test_a_bypass_launch_is_refused(bad):
with pytest.raises(box.LaunchRefused):
box.check_args(["claude", "-p", *bad])
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 74ed3f9..17b548c 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -33,7 +33,7 @@ Two optional parts install separately:
If Claude Code is installed (the `claude` command) and you have signed in to it once, FormAT needs no key: each reply runs through Claude Code on your Claude plan, in the chat's own folder, and streams into the chat like any other reply. The line under the composer says "through Claude Code", and so does the account line at the bottom of the sidebar.
- Claude Code's tools show as FormAT's cards (Ran a command, Edited a file, Read a file), and Ask, Allow all and Plan work the same way: in Ask, a command or file change waits for Allow once, Always allow, Allow all or Deny; Allow all allows them; Plan blocks them. FormAT's skills are offered to Claude Code too. Claude Code's questions arrive as FormAT's question card, and its sub-agents show nested.
-- FormAT always starts Claude Code with Claude Code's own sandbox turned on and never in its bypass permissions mode. In the sandbox, Claude Code's commands can change files only in the chat's folder and reach only the addresses you list in Settings, Tools, Sandbox, under "Addresses Claude Code's commands can reach" (none until you add some, such as `pypi.org` or `*.github.com`). Claude Code's sandbox runs on macOS, and on Linux and WSL 2 with bubblewrap and socat installed. Elsewhere, Windows included, the reply still runs, and the same Sandbox section says in plain words that Claude Code's commands are not sandboxed. Settings in the chat's folder cannot turn the sandbox off: FormAT reads only your own Claude Code settings beside the ones it passes.
+- FormAT always starts Claude Code with Claude Code's own sandbox turned on and never in its bypass permissions mode. In the sandbox, Claude Code's commands can change files only in the chat's folder and reach only the addresses you list in Settings, Tools, Sandbox, under "Addresses Claude Code's commands can reach" (none until you add some, such as `pypi.org` or `*.github.com`). Claude Code's sandbox runs on macOS, and on Linux and WSL 2 with bubblewrap and socat installed. Elsewhere, Windows included, the reply still runs, and the same Sandbox section says in plain words that Claude Code's commands are not sandboxed. Settings in the chat's folder cannot turn the sandbox off: FormAT reads only your own Claude Code settings beside the ones it passes. In the sandbox, Claude Code's commands cannot read FormAT's own data folder, apart from the chat's folder, uploads and skills. On every platform, Claude Code's file tools cannot change your uploads or installed skills, so a Claude Code chat never replaces a skill behind your back; add or replace skills in Customize, which asks before replacing one of the same name.
- Each reply continues the chat's Claude Code session, so Claude remembers the chat. Editing an earlier message branches from the session at that point.
- To choose, open the model menu, Answer through: Automatic (your API key when one is set, otherwise Claude Code), Anthropic API key, or Claude Code. The menu item appears once FormAT finds Claude Code.
- If a reply says Claude Code is not signed in, run `claude` in a terminal (FormAT's terminal dock works), sign in with `/login`, then retry.
From 9f38b54c106a4a63a103759d8d04ff2ae508a44f Mon Sep 17 00:00:00 2001
From: gbarnai
Date: Sun, 29 Nov 2026 18:20:46 -0500
Subject: [PATCH 8/8] fix: keep Claude Code's file tools off the home folder,
data folder and key file
The paths hidden from Claude Code now match FormAT's own sandbox: the home
folder, the resolved data folder and the backend .env (or the backend folder
when there is none). Besides the sandbox's denyRead, each becomes Read and Edit
deny rules for Claude Code's file tools on every platform, also when the
sandbox is unavailable. Since deny rules win over allow rules, each hidden
folder is denied entry by entry beside the path to the chat folder, uploads
and skills, which are then allowed for reading.
---
backend/HASHOUT_LOG.md | 4 +-
backend/app/engine/claude_code.py | 3 +-
backend/app/engine/claude_code_sandbox.py | 50 +++++++++++++++++++++--
backend/tests/test_claude_code_sandbox.py | 50 +++++++++++++++++++++++
docs/getting-started.md | 2 +-
5 files changed, 101 insertions(+), 8 deletions(-)
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index 5c85e2c..805eb03 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -1407,7 +1407,9 @@ Platforms. `support` takes the platform, a `which` and the kernel release so tes
Window. `sandbox.status` gains `claudeCode` (sandboxed, kind, domains, note) and `claudecode.status` gains `sandbox`; each reply's `meta.claudeCode.sandboxed` records what that reply ran with. `claudeCodeDomains` is checked on save: host names or `*.` wildcards, lowercased, duplicates dropped, at most 200 (tests/test_claude_code_sandbox.py, which needs no Claude Code).
-Reads and file tools. The sandbox's `filesystem.denyRead` holds FormAT's data folder (its database, tokens and certificate key) with `allowRead` re-opening the chat folder, uploads and skills, as FormAT's own sandbox hides the data folder. `--add-dir` also made uploads and skills writable for Claude Code's own Write and Edit tools, which the sandbox does not cover and which Allow all accepts without asking inside added folders; `permissions.deny` now carries an `Edit(///**)` rule for each (on Windows `//c/...`, the POSIX form Claude Code matches rules against), on every platform, so a Claude Code chat reads installed skills but cannot replace one outside the overwrite check (that route has no `save_skill`). `check_args` also refuses the `--flag=value` spellings. The home folder stays readable to Claude Code's sandboxed commands: hiding it, as FormAT's own sandbox does, was not tried without a live session, since Claude Code keeps its own files there.
+Reads and file tools. The sandbox's `filesystem.denyRead` holds FormAT's data folder (its database, tokens and certificate key) with `allowRead` re-opening the chat folder, uploads and skills, as FormAT's own sandbox hides the data folder. `--add-dir` also made uploads and skills writable for Claude Code's own Write and Edit tools, which the sandbox does not cover and which Allow all accepts without asking inside added folders; `permissions.deny` now carries an `Edit(///**)` rule for each (on Windows `//c/...`, the POSIX form Claude Code matches rules against), on every platform, so a Claude Code chat reads installed skills but cannot replace one outside the overwrite check (that route has no `save_skill`). `check_args` also refuses the `--flag=value` spellings.
+
+Hidden paths. `hidden_paths` hides what FormAT's own sandbox hides (the home folder and the resolved data folder) plus `BACKEND_DIR/.env`, or the whole backend folder when there is no `.env`; the sandbox's `denyRead` takes that list and `allowRead` re-opens the chat folder, uploads and skills. The same list now also becomes `permissions.deny` rules, built before the early return, so Claude Code's own Read and Edit tools are kept off it whether or not the sandbox runs. Claude Code checks deny before allow, so a deny on a folder that holds the chat folder would also refuse the chat folder: `hidden_rules` walks each hidden folder down towards the kept folders and denies every entry beside that path (`Read(//p/**)` and `Edit(//p/**)` for a folder, `Read(//p)` and `Edit(//p)` for a file), and denies a hidden folder whole when nothing kept is inside it. `permissions.allow` then names `Read(///**)` for each kept folder inside a hidden one. The walk runs at each launch, so an entry created beside the path afterwards (a new file in the home folder) is not covered until the next reply; the OS sandbox still hides it from commands. Claude Code reads its own files in the home folder as a program, not through its Read tool, so the rules are not expected to stop it starting (not seen in a live session); its Read tool can no longer open `~/.claude`.
Not done here: whether `excludedCommands` and `allowedDomains` from the person's own user settings merge with the launch file's lists was not confirmed in the binary; a person's own entries there may still apply. No real Claude Code session was started (the rules for this change forbid signing in), so the sandbox was not seen refusing a write or a host in a live reply.
diff --git a/backend/app/engine/claude_code.py b/backend/app/engine/claude_code.py
index 620742e..e19d3ec 100644
--- a/backend/app/engine/claude_code.py
+++ b/backend/app/engine/claude_code.py
@@ -6,7 +6,6 @@
from pathlib import Path
from app import providers
-from app.core import config
from app.engine import agent_lookup, claude_code_sandbox, events, projects, skills, tools, uploads
from app.engine.cmd_account import account
from app.engine.cmd_message import messages_of, update
@@ -401,7 +400,7 @@ def drain() -> None:
try:
if not found["installed"]:
raise providers.ProviderError(found.get("said") or "Claude Code is not installed: install it from https://claude.com/claude-code and sign in once with `claude`")
- launch = claude_code_sandbox.write_launch(claude_code_sandbox.settings_for(Path(folder), list(settings.get("claudeCodeDomains") or []), [uploads.root(), skills.root()], boxed, [config.data_dir()]))
+ launch = claude_code_sandbox.write_launch(claude_code_sandbox.settings_for(Path(folder), list(settings.get("claudeCodeDomains") or []), [uploads.root(), skills.root()], boxed, claude_code_sandbox.hidden_paths()))
args = launch_args(found["path"] or "claude", model["id"], settings, _system(conversation_id), launch, servers, blocked, session)
run_env = child_env(found["path"])
proc = subprocess.Popen(agent_lookup.start_argv(args, run_env), cwd=folder, env=run_env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
diff --git a/backend/app/engine/claude_code_sandbox.py b/backend/app/engine/claude_code_sandbox.py
index f620910..5f3af00 100644
--- a/backend/app/engine/claude_code_sandbox.py
+++ b/backend/app/engine/claude_code_sandbox.py
@@ -1,4 +1,5 @@
import json
+import logging
import platform as _platform
import re
import secrets
@@ -14,6 +15,7 @@
FORBIDDEN_MODES = ("bypassPermissions",)
DOMAIN = re.compile(r"^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$")
MAX_DOMAINS = 200
+log = logging.getLogger(__name__)
class LaunchRefused(providers.ProviderError):
@@ -52,18 +54,58 @@ def clean_domains(value: object) -> list[str]:
return out
-def edit_rule(path: Path | str, windows: bool) -> str:
+def path_rule(tool: str, path: Path | str, windows: bool, tree: bool = True) -> str:
+ tail = "/**" if tree else ""
if windows:
p = PureWindowsPath(str(path))
drive = p.drive.rstrip(":").lower()
rest = "/".join(p.parts[1:])
- return f"Edit(//{drive}/{rest}/**)" if len(drive) == 1 else f"Edit({p.as_posix()}/**)"
- return f"Edit(/{PurePosixPath(str(path)).as_posix()}/**)"
+ return f"{tool}(//{drive}/{rest}{tail})" if len(drive) == 1 else f"{tool}({p.as_posix()}{tail})"
+ return f"{tool}(/{PurePosixPath(str(path)).as_posix()}{tail})"
+
+
+def edit_rule(path: Path | str, windows: bool) -> str:
+ return path_rule("Edit", path, windows)
+
+
+def hidden_paths() -> list[Path]:
+ home = Path.home()
+ key = config.BACKEND_DIR / ".env"
+ found = [home] if home.is_dir() else []
+ found += [config.data_dir().resolve(), (key if key.is_file() else config.BACKEND_DIR).resolve()]
+ return list(dict.fromkeys(found))
+
+
+def _covers(parent: Path, child: Path) -> bool:
+ return child == parent or child.is_relative_to(parent)
+
+
+def _denied_within(root: Path, kept: list[Path]) -> list[tuple[Path, bool]]:
+ if any(_covers(k, root) for k in kept):
+ return []
+ if not any(_covers(root, k) for k in kept):
+ return [(root, root.is_dir() or not root.exists())]
+ try:
+ entries = sorted(root.iterdir())
+ except OSError:
+ log.warning("Claude Code launch: cannot list %s to hide its contents", root)
+ return []
+ return [d for e in entries for d in _denied_within(e, kept)]
+
+
+def hidden_rules(hidden: list[Path], kept: list[Path], windows: bool) -> list[str]:
+ keep = [k.resolve() for k in kept]
+ found = dict.fromkeys(d for h in hidden for d in _denied_within(h.resolve(), keep))
+ return [path_rule(tool, p, windows, tree) for p, tree in found for tool in ("Read", "Edit")]
def settings_for(workspace: Path, domains: list[str], read_only: list[Path], found: dict, hidden: list[Path] | None = None, windows: bool | None = None) -> dict:
win = sys.platform in ("win32", "cygwin") if windows is None else windows
- out: dict = {"permissions": {"disableBypassPermissionsMode": "disable", "deny": [edit_rule(p, win) for p in read_only]}}
+ kept = [workspace, *read_only]
+ inside = [p for p in kept if any(_covers(h.resolve(), p.resolve()) for h in hidden or [])]
+ out: dict = {"permissions": {"disableBypassPermissionsMode": "disable",
+ "deny": [edit_rule(p, win) for p in read_only] + hidden_rules(hidden or [], kept, win),
+ "allow": [path_rule("Read", p.resolve(), win) for p in inside]}}
if not found["available"]:
return out
out["sandbox"] = {
diff --git a/backend/tests/test_claude_code_sandbox.py b/backend/tests/test_claude_code_sandbox.py
index 6a3f5d9..e95aa7a 100644
--- a/backend/tests/test_claude_code_sandbox.py
+++ b/backend/tests/test_claude_code_sandbox.py
@@ -56,6 +56,56 @@ def test_claude_code_file_tools_cannot_change_the_read_only_folders(path, window
assert box.settings_for(Path("/w"), [], [Path(path)], {"available": False}, windows=windows)["permissions"]["deny"] == [rule]
+def _hidden_tree(tmp_path):
+ data = tmp_path / "data"
+ work, uploads, skills = data / "workspace" / "chats" / "c1", data / "uploads", data / "skills"
+ for p in (work, uploads, skills, data / "workspace" / "chats" / "c2", tmp_path / "secrets"):
+ p.mkdir(parents=True)
+ for f in (data / "format.db", tmp_path / ".env", data / "workspace" / "notes.txt"):
+ f.write_text("x")
+ return data, work, uploads, skills
+
+
+@pytest.mark.parametrize("plat,present,release,expected", PLATFORMS)
+def test_claude_code_file_tools_cannot_read_hidden_paths_with_or_without_the_sandbox(tmp_path, plat, present, release, expected):
+ data, work, uploads, skills = _hidden_tree(tmp_path)
+ found = box.support(plat, which_of(*present), release)
+ perms = box.settings_for(work, [], [uploads, skills], found, [tmp_path], windows=False)["permissions"]
+ root = tmp_path.resolve()
+ for d in (root / "secrets", root / "data" / "workspace" / "chats" / "c2"):
+ assert f"Read(/{d.as_posix()}/**)" in perms["deny"] and f"Edit(/{d.as_posix()}/**)" in perms["deny"]
+ for f in (root / ".env", root / "data" / "format.db", root / "data" / "workspace" / "notes.txt"):
+ assert f"Read(/{f.as_posix()})" in perms["deny"] and f"Edit(/{f.as_posix()})" in perms["deny"]
+ for kept in (work, uploads, skills):
+ k = kept.resolve().as_posix()
+ covering = [r for r in perms["deny"] if r.startswith("Read(") and (k + "/").startswith(r[len("Read(/"):].removesuffix(")").removesuffix("/**") + "/")]
+ assert covering == []
+ assert f"Read(/{k}/**)" in perms["allow"]
+
+
+def test_a_hidden_path_with_nothing_allowed_inside_is_denied_whole(tmp_path):
+ work, other = tmp_path / "chat", tmp_path / "home"
+ work.mkdir()
+ other.mkdir()
+ deny = box.settings_for(work, [], [], {"available": False}, [other], windows=False)["permissions"]["deny"]
+ h = other.resolve().as_posix()
+ assert deny == [f"Read(/{h}/**)", f"Edit(/{h}/**)"]
+
+
+def test_claude_code_hides_the_same_paths_as_the_engine_sandbox_plus_the_key_file(tmp_path, monkeypatch):
+ from app.core import config
+ home, data, backend = tmp_path / "home", tmp_path / "elsewhere" / "data", tmp_path / "app" / "backend"
+ for p in (home, data, backend):
+ p.mkdir(parents=True)
+ (backend / ".env").write_text("ANTHROPIC_API_KEY=x")
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ monkeypatch.setattr(config, "data_dir", lambda: data)
+ monkeypatch.setattr(config, "BACKEND_DIR", backend)
+ assert box.hidden_paths() == [home, data.resolve(), (backend / ".env").resolve()]
+ (backend / ".env").unlink()
+ assert box.hidden_paths() == [home, data.resolve(), backend.resolve()]
+
+
@pytest.mark.parametrize("plat,present,release,expected", PLATFORMS)
def test_the_panel_says_plainly_whether_claude_code_is_sandboxed(plat, present, release, expected):
said = box.status({"claudeCodeDomains": []}, box.support(plat, which_of(*present), release))
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 17b548c..b39a6d7 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -33,7 +33,7 @@ Two optional parts install separately:
If Claude Code is installed (the `claude` command) and you have signed in to it once, FormAT needs no key: each reply runs through Claude Code on your Claude plan, in the chat's own folder, and streams into the chat like any other reply. The line under the composer says "through Claude Code", and so does the account line at the bottom of the sidebar.
- Claude Code's tools show as FormAT's cards (Ran a command, Edited a file, Read a file), and Ask, Allow all and Plan work the same way: in Ask, a command or file change waits for Allow once, Always allow, Allow all or Deny; Allow all allows them; Plan blocks them. FormAT's skills are offered to Claude Code too. Claude Code's questions arrive as FormAT's question card, and its sub-agents show nested.
-- FormAT always starts Claude Code with Claude Code's own sandbox turned on and never in its bypass permissions mode. In the sandbox, Claude Code's commands can change files only in the chat's folder and reach only the addresses you list in Settings, Tools, Sandbox, under "Addresses Claude Code's commands can reach" (none until you add some, such as `pypi.org` or `*.github.com`). Claude Code's sandbox runs on macOS, and on Linux and WSL 2 with bubblewrap and socat installed. Elsewhere, Windows included, the reply still runs, and the same Sandbox section says in plain words that Claude Code's commands are not sandboxed. Settings in the chat's folder cannot turn the sandbox off: FormAT reads only your own Claude Code settings beside the ones it passes. In the sandbox, Claude Code's commands cannot read FormAT's own data folder, apart from the chat's folder, uploads and skills. On every platform, Claude Code's file tools cannot change your uploads or installed skills, so a Claude Code chat never replaces a skill behind your back; add or replace skills in Customize, which asks before replacing one of the same name.
+- FormAT always starts Claude Code with Claude Code's own sandbox turned on and never in its bypass permissions mode. In the sandbox, Claude Code's commands can change files only in the chat's folder and reach only the addresses you list in Settings, Tools, Sandbox, under "Addresses Claude Code's commands can reach" (none until you add some, such as `pypi.org` or `*.github.com`). Claude Code's sandbox runs on macOS, and on Linux and WSL 2 with bubblewrap and socat installed. Elsewhere, Windows included, the reply still runs, and the same Sandbox section says in plain words that Claude Code's commands are not sandboxed. Settings in the chat's folder cannot turn the sandbox off: FormAT reads only your own Claude Code settings beside the ones it passes. On every platform, Claude Code cannot read your home folder, FormAT's own data folder or FormAT's key file, apart from the chat's folder, uploads and skills: its file tools are refused there, and in the sandbox its commands are too. On every platform, Claude Code's file tools cannot change your uploads or installed skills, so a Claude Code chat never replaces a skill behind your back; add or replace skills in Customize, which asks before replacing one of the same name.
- Each reply continues the chat's Claude Code session, so Claude remembers the chat. Editing an earlier message branches from the session at that point.
- To choose, open the model menu, Answer through: Automatic (your API key when one is set, otherwise Claude Code), Anthropic API key, or Claude Code. The menu item appears once FormAT finds Claude Code.
- If a reply says Claude Code is not signed in, run `claude` in a terminal (FormAT's terminal dock works), sign in with `/login`, then retry.