Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(relay): keep person power on the paired phone [H15,B26,H13]
Corey Olson5d086acf727e
diff --git a/docs/api.md b/docs/api.mdindex de23675a..db354ee5 100644--- a/docs/api.md+++ b/docs/api.md@@ -151,11 +151,15 @@ Only the coordinator sets or edits an item's `--check`. `pullboard check [id]` p`relay on`, `relay`, and `relay off` share the relay result shape. `status` adds a `relay` object with the current sequence and pending upload count. Successful results may include `diagnostics` for a relay refusal or inactivity notice; a local move still succeeds when its upload must wait. Device sign-in instructions are written immediately to stderr, including with `--json`, so the person can sign in before the command returns.-`relay on --all [--url <address>]` returns `{version, linked: [{project, root, board}], failed: [{project, root, reason}], paired, autoLink: true}`. Its status is nonzero when a project failed; successful links remain available. With no paired phone, the command prints one tappable pairing link and QR, then waits in the foreground up to ten minutes. Interruption or expiration leaves completed links intact and exits zero when no link failed. Later project registrations use the owner-only saved session; `doctor` and `resume` name any unlinked projects with `sign in again: pullboard relay on --all`. `relay off` excludes that project from automatic linking; explicit `relay on` clears the exclusion.+`relay on --all [--url <address>]` returns `{version, linked: [{project, root, board}], failed: [{project, root, reason}], paired, autoLink: true}`. Its status is nonzero when a project failed; successful links remain available. With no paired phone, the command prints one tappable pairing link and QR, then waits in the foreground up to ten minutes. Interruption or expiration leaves completed links intact and exits zero when no link failed. Every explicit invocation signs in afresh; no person session is retained on the Mac. Later project registrations publish one sealed phone-link proposal and keep working locally until its single approval tap. `doctor` and `resume` name the waiting project and its expiry; expiration requires an explicit fresh sign-in rather than silently asking again. `relay off` excludes that project from automatic linking; explicit `relay on` clears the exclusion.-`relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. A remote outage leaves a durable deletion intent for the next `relay on --all`. Revocation stops future wrapping; it cannot erase board keys already received.+`relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation waits for one tap on the paired phone and uses a short-lived, single-use, RAM-only grant for that exact device. A failed or interrupted approval needs an explicit retry. Revocation stops future wrapping; it cannot erase board keys already received.-Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Every endpoint requires a person session, cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.+Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Enrollment, device listing and direct revocation require a person session. A board-scoped machine credential can PUT only its own board wrap to an already enrolled device. Cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.++`POST /auth/machines {board,machine}` requires a foreground person session and returns a `pm_` credential bound to that board and machine. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.++A machine publishes an opaque approval with `POST /api/v1/devices/approvals {context,sealed}`. The publishing machine may GET only its own requests. The paired phone reads `/api/v1/devices/:deviceId/approvals`, explicitly POSTs `/:requestId/authorize {}` and completes the encrypted reply through `/:requestId/complete {response}`. The publishing machine executes a native revocation through `/:requestId/execute {grant}`; the two-minute grant binds the entire context and is atomically consumed once. Native reply keys and grants never persist. New-board linking uses a durable non-person reply key and returns only a board-scoped machine credential. `relay off` immediately unlinks locally even offline or in an agent shell, reports that the relay copy remains, and queues a separate one-tap phone deletion request when possible.The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js` by `docs/api.test.js`.diff --git a/docs/formats.md b/docs/formats.mdindex a1a680c5..4382c896 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -76,20 +76,20 @@ The board file is in the repository's Git common directory at `.git/pullboard/bo| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. || `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. || `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |-| `move engine` | `5` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |+| `move engine` | `6` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |<!-- format-versions:end -->-Pullboard 0.6.1 released engine 1. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Pullboard 0.8.1 released engine 3, including lane-sensitive graft refusals and authenticated relay senders. Engine 4 adds captured background-baseline completions through `completeCheckBaseline`; released engine-3 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Engine 5 requires a one-line reason when releasing a review and gives that reviewer a one-hour cooldown for the current submission. Each sealed move replays under its recorded engine version: engines 1 through 4 retain the original release event and review-reservation behavior. Engine 5 retains support for older moves, including engine-4 baseline completions. Upgrade every linked device before using the new moves.+Pullboard 0.6.1 released engine 1. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Pullboard 0.8.1 released engine 3, including lane-sensitive graft refusals and authenticated relay senders. Engine 4 adds captured background-baseline completions through `completeCheckBaseline`; released engine-3 clients stop with `ENGINE_VERSION` before interpreting this new operation or advancing their replay cursor. Engine 5 requires a one-line reason when releasing a review and gives that reviewer a one-hour cooldown for the current submission. Each sealed move replays under its recorded engine version: engines 1 through 4 retain the original release event and review-reservation behavior. Engine 5 retains support for older moves, including engine-4 baseline completions. Engine 6 adds board-scoped machine credentials and permits machine execution only for one exact, earlier authenticated phone request, including its payload digest. Older request receipts retain their recorded engine semantics. Upgrade every linked device before using the new moves.The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.A linked board requires at least engine 3 after issuing any agent token, including-revoked or expired tokens. The minimum survives reopening the auth database;+revoked or expired tokens. Issuing any machine credential raises that board’s minimum to engine 6, including after revocation or expiry. The minimum survives reopening the auth database;unlink removes the board and ends its lifetime. A missing declaration is legacyengine 1. Board-content requests below their minimum, and malformed declarations,receive `ENGINE_VERSION` with upgrade guidance before records are returned orchanged. The service checks again under its board lock and on live-stream polls.-Engine 3 checks each move or request against the relay's authenticated sender before replay. An agent token acts only as its named agent and cannot act as the person. Refused attribution attempts advance the sequence with a `relay_refusal_<sequence>` receipt and a `relay_refused` event naming the sender, attempted actor and refusal code. They change no item, shout or verdict and do not reserve the forged operation id. Snapshot restoration requires a person sender. The event log remains version 1.+Engine 3 checks each move or request against the relay's authenticated sender before replay. An agent token acts only as its named agent and cannot act as the person. Refused attribution attempts advance the sequence with a `relay_refusal_<sequence>` receipt and a `relay_refused` event naming the sender, attempted actor and refusal code. They change no item, shout or verdict and do not reserve the forged operation id. Snapshot restoration requires an authenticated person or board machine sender. A machine can register ordinary agents and ensure the coordinator; other person effects require an earlier authenticated phone intent with exact operation, arguments, target and digest. Every replica consumes its execution once, including row decisions waiting for repository application. Receipt shouts have fixed text; refusal details remain in the structured request result. The event log remains version 1.A board without `event_log_version` is a legacy version-0 event log. Opening an older board writes the current marker without replacing its events. Opening a newer event log refuses with `EVENT_LOG_VERSION`, naming the stored and supported versions and asking you to upgrade Pullboard. `doctor` reports that version conflict read-only.@@ -99,12 +99,16 @@ Linked clients seal an executable operation and its deterministic inputs. The reA sealed checkpoint keeps the native export tables importable and may carry the local API presentation beside them. Its public sequence equals `relay_applied_sequence`, so clients can restore a compacted prefix and continue after it. The older local-first mirror drains only its already-durable outbox, then publishes a checkpoint covering the acknowledged prefix without executing those events again. A divergent old outbox is refused with the relay and local sequences; re-link from that machine or join by pairing.-Machine relay setup lives outside repositories in `$PULLBOARD_HOME/relay-machine/state.json` (default `~/.pullboard/relay-machine/state.json`), format `v: 1`. The directory is mode 700; state and the SQLite serialization lock are mode 600. State retains the auto-link setting, saved account session, excluded project roots, device roster, one pending ten-minute enrollment, and pending remote revocations. Each roster entry contains `deviceId`, public P-256 JWK, SHA-256 fingerprint, label, creation timestamp, account and relay origin. No device private key is stored on the Mac. The phone retains its non-extractable ECDH P-256 private CryptoKey in IndexedDB database `pullboard-relay-device-v1`, store `keys`, key `device`.+Machine relay setup lives outside repositories in `$PULLBOARD_HOME/relay-machine/state.json` (default `~/.pullboard/relay-machine/state.json`), format `v: 2`. The directory is mode 700; state and the SQLite serialization lock are mode 600. State retains the auto-link setting, account and relay origin, stable machine id, excluded project roots, device roster, one pending ten-minute enrollment, pending remote revocations and non-person board-link proposals. Person sessions never persist on the Mac: old machine sessions, Git-directory sessions and retired per-board session files are scrubbed before use. Each linked board keeps a `pm_` credential bound to that board and machine; it can mint `pa_` agent credentials only for that board. `pa_` credentials cannot mint credentials. Explicit `relay on --all` always signs in afresh and preserves the paired phone key. Each roster entry contains `deviceId`, public P-256 JWK, SHA-256 fingerprint, label, creation timestamp, account and relay origin. No device private key is stored on the Mac. The phone retains its non-extractable ECDH P-256 private CryptoKey in IndexedDB database `pullboard-relay-device-v1`, store `keys`, key `device`.Enrollment HMAC-SHA256 uses an HKDF-SHA256 key derived from the QR-only 32-byte secret, locator-byte salt and UTF-8 JSON info `["pullboard-device-auth",1,account,locator]`. The authenticated enrollment is UTF-8 JSON `["pullboard-device-enroll",1,account,locator,deviceId,{kty,crv,x,y},label,createdAt]`. The Mac consumes its local secret atomically after checking the MAC; relay-supplied public keys are never used as wrapping recipients.Device wraps are `{v:1,board,device,engine,ephemeral,nonce,ciphertext}`. `ephemeral` is a fresh public P-256 JWK; `nonce` is 12 bytes and `ciphertext` is the 32-byte board key plus its 16-byte AES-GCM tag, both canonical base64url. ECDH yields HKDF-SHA256 input, the raw 65-byte ephemeral public point is salt, and UTF-8 JSON `["pullboard-wrap-v1",board,device]` is info. AES-256-GCM AAD is UTF-8 JSON `["pullboard-device-wrap",1,board,device,engine]`. The relay's private `devices.sqlite` stores only account/device identifiers, opaque wraps, expiring public enrollment transports and durable revocation tombstones. Unlink removes board grants; a device revocation atomically deletes all its grants and blocks stale uploads.+Phone approval contexts contain exactly `id,account,publisher,board,device,action,target,machine,command,expires`. New-board link requests have one visible ten-minute proposal and may retain a private reply JWK because their reply grants only board-scoped machine power. Native revocation reply keys are non-extractable and RAM-only. One phone tap returns a `pg_` grant, limited to two minutes and bound to the entire immutable context; the relay retains only its hash and consumes it atomically before executing the exact action. Agent shells refuse native person actions before network access. `relay off` always removes the local link without a tap, including offline and in agent shells; the remote copy remains until a separate explicit phone deletion approval.++Approval intents and replies use separate ECDH/HKDF-SHA256/AES-256-GCM domains. HKDF salt is UTF-8 JSON of the ephemeral public P-256 JWK; info is UTF-8 JSON `["pullboard-phone-approval-v1",direction,context]`. AES-GCM AAD is UTF-8 JSON `["pullboard-phone-approval",1,direction,context]`. The publishing board key authenticates the sealed intent with HMAC-SHA256 over UTF-8 JSON `["pullboard-phone-intent-v1",envelope]` before the phone displays an approval. Opaque encrypted replies never expose a native grant to durable storage. Journal format 3 permits machine sender attribution, upgrading format-2 CHECK constraints atomically while preserving history, snapshots and sequence heads.+The in-place upgrade behavior is exercised by `exerciseUpgrade` in `docs/formats.test.js`:<!-- upgrade-rules:start -->diff --git a/relay/README.md b/relay/README.mdindex 3a8bdabe..19f84a5b 100644--- a/relay/README.md+++ b/relay/README.md@@ -38,8 +38,10 @@ For #113, the person completes these account steps:The smoke command is `node relay/smoke.mjs <address>`. It uses the currentrepository as a disposable smoke board: it links, creates one uniquely nameditem, reads and unseals its mirrored move, then unlinks. Use a throwaway-repository and relay when running it against a live deployment; unlink deletes-the remote board. Tests run the same script against a private loopback relay.+repository and relay when running it against a live deployment. Unlink removes+the local link and key; the sealed relay copy remains until you approve deleting+it on the paired phone. The smoke prints this cleanup notice. Tests run the same+script against a private loopback relay.Railway's current Infrastructure as Code uses the `railway/iac` package. Thisdependency-free project keeps the deployment settings in the service checklistdiff --git a/relay/auth-http.js b/relay/auth-http.jsindex 0010d27e..b6986514 100644--- a/relay/auth-http.js+++ b/relay/auth-http.js@@ -36,18 +36,19 @@ export function createAuthHandler({ auth, publicOrigin }) {try { origin = new URL(publicOrigin); } catch { throw new Refused('RELAY_CONFIG', 'configure the relay public origin'); }if (origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash || (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname)))) throw new Refused('RELAY_CONFIG', 'use an HTTPS public origin, or a loopback HTTP origin for local tests');const secure = origin.protocol === 'https:' ? '; Secure' : '';- const routes = new Set(['GET /auth/github/start', 'GET /auth/github/callback', 'POST /auth/device/start', 'POST /auth/device/poll', 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);+ const routes = new Set(['GET /auth/github/start', 'GET /auth/github/callback', 'POST /auth/device/start', 'POST /auth/device/poll', 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'POST /auth/machines', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);/** Resolve a bearer or cookie credential; cookie writes require an exact trusted Origin. */function token(req, write = false) {const authorization = req.headers.authorization;if (authorization) {- const match = /^Bearer ((?:ps_|pa_)[A-Za-z0-9_-]{43})$/.exec(authorization);+ const match = /^Bearer ((?:ps_|pa_|pm_)[A-Za-z0-9_-]{43})$/.exec(authorization);if (!match) throw new Refused('AUTH_REQUIRED', 'send a current relay bearer credential');return match[1];}const session = cookie(req, 'pb_session');if (write && req.headers.origin !== origin.origin) throw new Refused('BAD_ORIGIN', 'send cookie-authorized writes from the relay origin');+ if (session !== undefined && !/^ps_[A-Za-z0-9_-]{43}$/.test(session)) throw new Refused('AUTH_REQUIRED', 'sign in to the relay in this browser');return session;}@@ -80,6 +81,9 @@ export function createAuthHandler({ auth, publicOrigin }) {const bearer = token(req, true);const input = await body(req);json(res, 200, { board: await auth.linkBoard(bearer, input.board, input.repository) });+ } else if (route === 'POST /auth/machines') {+ const bearer = token(req, true);+ json(res, 201, await auth.issueMachine(bearer, await body(req)));} else if (route === 'GET /auth/tokens') {json(res, 200, { tokens: await auth.listTokens(token(req), url.searchParams.get('board')) });} else if (route === 'POST /auth/tokens') {diff --git a/relay/auth.js b/relay/auth.jsindex e14905c8..529b6f54 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -5,6 +5,7 @@ import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { Refused } from '../src/refused.js';import { repositoryName } from './github.js';+import { approvalContext } from '../src/relay-approval.js';export const ACCESS_WINDOW_MS = 10 * 60_000;const MAX_TTL = 30 * 24 * 3600_000;@@ -43,6 +44,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =CREATE TABLE IF NOT EXISTS relay_boards (id TEXT PRIMARY KEY, repository TEXT NOT NULL, repository_id TEXT NOT NULL);CREATE TABLE IF NOT EXISTS relay_cleanup (board TEXT PRIMARY KEY);CREATE TABLE IF NOT EXISTS relay_credentials (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, kind TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES relay_users(id), board TEXT REFERENCES relay_boards(id), agent TEXT, expires INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);+ CREATE TABLE IF NOT EXISTS relay_action_grants (hash TEXT PRIMARY KEY, request TEXT UNIQUE NOT NULL,+ user_id TEXT NOT NULL, context TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);`);if (!db.prepare('PRAGMA table_info(relay_credentials)').all().some((column) => column.name === 'created')) {db.exec('ALTER TABLE relay_credentials ADD COLUMN created INTEGER');@@ -79,7 +82,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =/** Resolve a current credential and latest account login without storing its plaintext. */function credential(token) {open();- if (typeof token !== 'string' || !/^(ps_|pa_)[A-Za-z0-9_-]{43}$/.test(token)) throw new Refused('AUTH_REQUIRED', 'sign in to the relay or supply a current board token');+ if (typeof token !== 'string' || !/^(ps_|pa_|pm_)[A-Za-z0-9_-]{43}$/.test(token)) throw new Refused('AUTH_REQUIRED', 'sign in to the relay or supply a current board token');const row = db.prepare('SELECT c.*, u.login FROM relay_credentials c JOIN relay_users u ON u.id=c.user_id WHERE c.hash=?').get(hash(token));if (!row || row.revoked || row.expires <= now()) throw new Refused('AUTH_REQUIRED', 'this credential is expired or revoked; sign in or obtain a new board token');return row;@@ -88,7 +91,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =/** Mint one independently expiring/revocable credential and persist only its hash. */function issue(user, kind, board, agent, ttl) {open();- const token = random(kind === 'session' ? 'ps_' : 'pa_');+ const token = random(kind === 'session' ? 'ps_' : kind === 'machine' ? 'pm_' : 'pa_');const id = randomUUID();const created = now();const expires = created + ttl;@@ -205,6 +208,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =async authenticate(token, { board, write = false } = {}) {const row = credential(token);if (row.kind === 'board' && board !== row.board) throw new Refused('TOKEN_BOARD', 'use this token only on its named board; obtain another token for another board');+ if (row.kind === 'machine' && board !== undefined && board !== row.board) throw new Refused('TOKEN_BOARD', 'use this machine credential only on its linked board; ask the paired phone to link another board');let repository;if (board !== undefined) {identifier(board, 'BAD_BOARD');@@ -212,7 +216,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =if (board !== null && board !== undefined && !db.prepare('SELECT 1 FROM relay_boards WHERE id=?').get(board)) throw new Refused('BOARD_NOT_LINKED', 'link this board again before using it');credential(token); // A revocation or expiry during the awaited provider call must take effect.}- return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, agent: row.agent } : {}), ...(repository ? { permission: repository.permission, public: repository.public } : {}), expires: row.expires };+ return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, ...(row.kind === 'machine' ? { machine: row.agent } : { agent: row.agent }) } : {}), ...(repository ? { permission: repository.permission, public: repository.public } : {}), expires: row.expires };},/** Accept a link only from a signed-in human with current repository write access. */async linkBoard(token, board, repository) {@@ -269,7 +273,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =/** List only linked boards the current credential and GitHub account may read. */async boardsFor(token) {const row = credential(token);- const boards = row.kind === 'board' ? db.prepare('SELECT * FROM relay_boards WHERE id=?').all(row.board) : db.prepare('SELECT * FROM relay_boards ORDER BY id').all();+ const boards = row.kind !== 'session' ? db.prepare('SELECT * FROM relay_boards WHERE id=?').all(row.board) : db.prepare('SELECT * FROM relay_boards ORDER BY id').all();const visible = [];for (const board of boards) {try { await auth.authenticate(token, { board: board.id }); visible.push({ id: board.id, repository: board.repository, linkedAt: board.linked_at }); }@@ -277,31 +281,78 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =}return visible;},- /** Keep the minimum replay engine at three after any agent token, including revoked or expired tokens. */+ /** Retain the minimum replay engine after any agent or machine credential, including expired and revoked ones. */minimumEngineVersion(board) {open();identifier(board, 'BAD_BOARD');+ if (db.prepare("SELECT 1 FROM relay_credentials WHERE board=? AND kind='machine' LIMIT 1").get(board)) return 6;return db.prepare("SELECT 1 FROM relay_credentials WHERE board=? AND kind='board' LIMIT 1").get(board) ? 3 : 1;},+ /** Give a foreground person one board-bound machine delegate, never another person credential. */+ async issueMachine(token, { board, machine, expiresIn = MAX_TTL }) {+ identifier(board, 'BAD_BOARD');+ identifier(machine, 'BAD_MACHINE');+ if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0 || expiresIn > MAX_TTL) throw new Refused('BAD_EXPIRY', 'choose a machine expiry of at most thirty days');+ const principal = await auth.authenticate(token, { board, write: true });+ if (principal.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'approve this machine from the signed-in phone');+ credential(token);+ return { ...issue(principal.user, 'machine', board, machine, expiresIn), board, machine };+ },/** Mint an agent credential scoped to a single readable board and immutable human identity. */async issueToken(token, { board, agent, expiresIn = tokenTTL }) {identifier(board, 'BAD_BOARD');identifier(agent, 'BAD_AGENT');if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0 || expiresIn > MAX_TTL) throw new Refused('BAD_EXPIRY', 'choose a token expiry between one millisecond and thirty days');const principal = await auth.authenticate(token, { board, write: true });- if (principal.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to issue a board token');+ if (!['session', 'machine'].includes(principal.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential to issue an agent token');credential(token);return { ...issue(principal.user, 'board', board, agent, expiresIn), board, agent };},- /** List only owned board-token metadata after a fresh person permission check, never bearer values or hashes. */+ /** List only owned board-token metadata after a fresh repository write check, never bearer values or hashes. */async listTokens(token, board) {identifier(board, 'BAD_BOARD');const principal = await auth.authenticate(token, { board, write: true });- if (principal.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to list agent tokens');+ if (!['session', 'machine'].includes(principal.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential to list agent token ids');credential(token);return db.prepare('SELECT id,board,agent,created,expires,revoked FROM relay_credentials WHERE user_id=? AND kind=? AND board=? ORDER BY agent,id').all(principal.user.id, 'board', board).map((row) => ({ ...row, revoked: Boolean(row.revoked) }));},+ /** Mint a short-lived grant only after an authenticated phone approves an immutable action context. */+ async issueActionGrant(token, value) {+ const context = approvalContext(value);+ const principal = await auth.authenticate(token, { board: context.publisher, write: true });+ if (principal.kind !== 'session' || principal.user.id !== context.account || context.action === 'link') throw new Refused('HUMAN_REQUIRED', 'approve this native action from the signed-in paired phone');+ credential(token);+ const grant = random('pg_');+ const expires = Math.min(context.expires, now() + 120_000);+ if (expires <= now()) throw new Refused('PHONE_APPROVAL_EXPIRED', 'request a fresh phone approval explicitly');+ lifecycle(() => {+ if (db.prepare('SELECT 1 FROM relay_action_grants WHERE request=?').get(context.id)) throw new Refused('PHONE_APPROVAL_USED', 'this action was already approved; use its encrypted reply');+ db.prepare('INSERT INTO relay_action_grants(hash,request,user_id,context,expires) VALUES(?,?,?,?,?)').run(hash(grant), context.id, principal.user.id, JSON.stringify(context), expires);+ });+ return { grant, expires };+ },+ /** Atomically consume once before dispatch; an interrupted action needs another explicit phone approval. */+ async consumeActionGrant(token, grant, value) {+ const context = approvalContext(value);+ const principal = await auth.authenticate(token, { board: context.publisher, write: true });+ if (principal.kind !== 'machine' || principal.user.id !== context.account || principal.machine !== context.machine ||+ typeof grant !== 'string' || !/^pg_[A-Za-z0-9_-]{43}$/u.test(grant)) throw new Refused('HUMAN_REQUIRED', 'use the one-time grant approved for this exact native command');+ credential(token);+ lifecycle(() => {+ const row = db.prepare('SELECT * FROM relay_action_grants WHERE hash=?').get(hash(grant));+ if (!row || row.used || row.expires <= now() || row.user_id !== principal.user.id || row.context !== JSON.stringify(context)) throw new Refused('PHONE_APPROVAL_USED', 'this grant was used, expired or names another action; request a fresh approval explicitly');+ db.prepare('UPDATE relay_action_grants SET used=1 WHERE hash=? AND used=0').run(hash(grant));+ });+ return principal;+ },+ /** Revoke only a current account's own board token after the native grant boundary consumed approval. */+ async revokeApprovedToken(principal, id, board) {+ const target = db.prepare("SELECT * FROM relay_credentials WHERE id=? AND kind='board' AND board=? AND user_id=?").get(id, board, principal.user.id);+ if (!target) throw new Refused('TOKEN_NOT_OWNED', 'choose an agent token id listed on this board');+ db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=?').run(id);+ return { id, revoked: true };+ },/** Revoke one owned credential; this never revokes an unrelated session or board token. */async revoke(token, id) {const row = credential(token);diff --git a/relay/browser-client.js b/relay/browser-client.jsindex 857114bd..cf663cc5 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -1,5 +1,5 @@/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15,H16,H17]. */-import { rememberDevicePairing, enrollPhone, deviceBoardKeys } from './browser-devices.js';+import { rememberDevicePairing, enrollPhone, deviceBoardKeys, installPhoneApprovals } from './browser-devices.js';import { decodeBoardKey, encodeBoardKey, seal, unseal } from './seal.js';import { preparePersonRequest, validatePersonRequest } from './person-request.js';import { snapshotState, presentationState } from './model.js';@@ -463,6 +463,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });await enrollPhone((path, options) => documentAt(path, denied, options));await listing();+ await installPhoneApprovals((path, options) => documentAt(path, denied, options), keys, async () => { await listing(); onUpdate(); });return {/** Return decoded API state or seal narrow person intent; no board key or plaintext leaves the device. */async request(path, body) {diff --git a/relay/browser-devices.js b/relay/browser-devices.jsindex 105127d2..c30e5225 100644--- a/relay/browser-devices.js+++ b/relay/browser-devices.js@@ -3,6 +3,8 @@ import { createDeviceKeys, signDeviceEnrollment, unwrapDeviceBoardKey } from './import { encodeBoardKey } from './seal.js';import { ENGINE_VERSION } from './engine.js';import { Refused } from './refused.js';+import { approvalContext, openApproval, sealApproval, verifyApprovalIntent } from './relay-approval.js';+import { devicePublicKey } from './device-keys.js';const PENDING = 'pullboard.relay.device-pair.v1';@@ -97,3 +99,74 @@ export async function deviceBoardKeys(documentAt) {}return keys;}++/** Decode only bounded approval transport; keys and plaintext grants never enter device storage. */+function approvalDocument(value) {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{1,32000}$/u.test(value)) throw new Refused('PHONE_APPROVAL_AUTH', 'Request a fresh native approval.');+ try {+ const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), char => char.charCodeAt(0));+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));+ } catch { throw new Refused('PHONE_APPROVAL_AUTH', 'The native approval could not be read. Request it again.'); }+}++/** Show exact paired native intent and approve only on one explicit phone tap. */+export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {+ if (document.getElementById('phone-approvals')) return;+ const device = await deviceStorage();+ if (!device) return;+ const panel = document.createElement('section');+ panel.className = 'card-panel'; panel.id = 'phone-approvals';+ panel.setAttribute('aria-label', 'Requests from your Mac');+ document.querySelector('main').prepend(panel);+ const active = new Set();+ let stopped = false;+ let timer;+ /** Refresh pending metadata without approving it or replacing a button whose request is in flight. */+ async function refresh() {+ if (stopped) return;+ try {+ const response = await documentAt('/api/v1/devices/' + device.deviceId + '/approvals');+ const ids = new Set(response.approvals.map(value => value.context.id));+ for (const child of [...panel.children]) if (!ids.has(child.dataset.request) && !active.has(child.dataset.request)) child.remove();+ for (const row of response.approvals) {+ const context = approvalContext(row.context);+ if (context.device !== device.deviceId || context.account !== device.account || Date.now() >= context.expires ||+ [...panel.children].some(child => child.dataset.request === context.id)) continue;+ const raw = boardKeys[context.publisher];+ if (!raw) continue;+ const key = Uint8Array.from(atob(raw.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - raw.length % 4) % 4)), char => char.charCodeAt(0));+ const envelope = await verifyApprovalIntent(key, approvalDocument(row.sealed));+ const intent = await openApproval(device.privateKey, envelope, context, 'intent');+ if (JSON.stringify(approvalContext(intent.context)) !== JSON.stringify(context)) throw new Refused('PHONE_APPROVAL_AUTH', 'The displayed request differs from its sealed action.');+ const replyKey = devicePublicKey(intent.replyKey);+ const card = document.createElement('div'); card.className = 'phone-approval'; card.dataset.request = context.id;+ const text = document.createElement('p');+ text.textContent = context.command + ' · board ' + context.board + ' · target ' + context.target + ' · machine ' + context.machine + ' · expires ' + new Date(context.expires).toISOString();+ const button = document.createElement('button'); button.type = 'button'; button.id = 'phone-approve-' + context.id;+ button.textContent = context.action === 'link' ? 'Link project' : context.action === 'delete-board' ? 'Delete relay copy' : 'Approve revocation';+ /** Issue once on this tap, then encrypt the result to the native command's private RAM reply key. */+ button.onclick = async () => {+ if (active.has(context.id)) return;+ active.add(context.id); button.disabled = true;+ try {+ const authorized = await documentAt('/api/v1/devices/approvals/' + context.id + '/authorize', {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}',+ });+ const encrypted = await sealApproval(authorized.result, replyKey, context, 'reply');+ const response = btoa(JSON.stringify(encrypted)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');+ await documentAt('/api/v1/devices/approvals/' + context.id + '/complete', {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ response }),+ });+ card.remove(); await onApproved();+ } catch (error) { text.textContent = 'Approval failed: ' + (error instanceof Refused ? error.message : 'Request the action again from the Mac.'); }+ finally { active.delete(context.id); }+ };+ card.append(text, button); panel.append(card);+ }+ } catch (error) {+ if (error?.code !== 'DEVICE_NOT_ENROLLED') panel.setAttribute('data-error', 'Approval requests are unavailable. Retry from the Mac.');+ } finally { if (!stopped) timer = setTimeout(refresh, 1000); }+ }+ addEventListener('pagehide', () => { stopped = true; clearTimeout(timer); }, { once: true });+ await refresh();+}diff --git a/relay/browser-page.js b/relay/browser-page.jsindex 9061a143..02b4bb9e 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -24,6 +24,7 @@ export function createRelayBrowserHandler({ authenticate }) {const assets = new Map([['/view.css', ['text/css', STYLES]],['/relay/device-keys.js', ['text/javascript', readFileSync(new URL('../src/relay-device-keys.js', import.meta.url), 'utf8')]],+ ['/relay/relay-approval.js', ['text/javascript', readFileSync(new URL('../src/relay-approval.js', import.meta.url), 'utf8').replace("'./relay-device-keys.js'", "'./device-keys.js'")]],['/relay/browser-devices.js', ['text/javascript', readFileSync(new URL('./browser-devices.js', import.meta.url), 'utf8')]],['/relay/client.js', ['text/javascript', readFileSync(new URL('./browser-client.js', import.meta.url), 'utf8')]],['/relay/browser-notice.js', ['text/javascript', readFileSync(new URL('./browser-notice.js', import.meta.url), 'utf8')]],diff --git a/relay/device-http.js b/relay/device-http.jsindex 27c613c3..f0b5d876 100644--- a/relay/device-http.js+++ b/relay/device-http.js@@ -2,6 +2,7 @@import { apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js';import { Refused } from '../src/refused.js';import { devicePublicKey } from '../src/relay-device-keys.js';+import { approvalContext } from '../src/relay-approval.js';/** Require exact bounded action fields, excluding secrets and unrecognized relay metadata. */function exact(value, fields) {@@ -12,15 +13,78 @@ function exact(value, fields) {}/** Route only fixed device endpoints; ownership always comes from the authenticated session. */-export function createDeviceHandler({ authenticate, authorizeBoard, boardsFor, devices }) {+export function createDeviceHandler({ authenticate, authorizeBoard, boardsFor, devices, linkBoard, issueMachine,+ issueActionGrant, consumeActionGrant, revokeToken, deleteBoard }) {return async function handleDevice(req, res) {const url = new URL(req.url ?? '/', 'http://localhost');if (!url.pathname.startsWith('/api/v1/devices')) return false;try {if (url.search) throw new Refused('BAD_REQUEST', 'Keep device action fields out of URL queries.');const who = await authenticate(req, !['GET', 'HEAD'].includes(req.method));- if (who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'Sign in as a person to pair or revoke a device.');const account = who.user.id;+ if (url.pathname === '/api/v1/devices/approvals' && req.method === 'POST') {+ if (who.kind !== 'machine') throw new Refused('HUMAN_REQUIRED', 'request this approval with the linked board’s machine credential');+ await authorizeBoard(req, who.board);+ const body = exact(await readApiBody(req, { maxBytes: 40000 }), ['context', 'sealed']);+ const context = approvalContext(body.context);+ if (context.account !== account || context.publisher !== who.board || context.machine !== who.machine) throw new Refused('TOKEN_BOARD', 'publish approval only for this authenticated machine and board');+ apiJson(res, 200, { approval: devices.requestApproval(account, context, body.sealed) }); return true;+ }+ const approvalRoute = /^\/api\/v1\/devices\/approvals\/([A-Za-z0-9_-]{1,80})(?:\/(authorize|complete|execute))?$/.exec(url.pathname);+ if (approvalRoute) {+ if (!['session', 'machine'].includes(who.kind)) throw new Refused('HUMAN_REQUIRED', 'use the phone session or the publishing machine for this approval');+ if (who.kind === 'machine') await authorizeBoard(req, who.board);+ const [, id, action] = approvalRoute;+ const request = devices.approval(account, id, who.kind === 'machine' ? { board: who.board, machine: who.machine } : undefined);+ if (!action && req.method === 'GET') { apiJson(res, 200, { approval: request }); return true; }+ if (req.method !== 'POST') throw new Refused('NO_ENDPOINT', 'use the documented phone approval action');+ if (action === 'execute') {+ if (who.kind !== 'machine') throw new Refused('HUMAN_REQUIRED', 'execute the native command with its approved machine grant');+ const body = exact(await readApiBody(req), ['grant']);+ const context = request.context;+ const principal = await consumeActionGrant(req, body.grant, context);+ let result;+ if (context.action === 'revoke-device') { devices.revoke(account, context.target); result = { deviceId: context.target, revoked: true }; }+ else if (context.action === 'revoke-token') result = await revokeToken(principal, context.target, context.board);+ else throw new Refused('PHONE_APPROVAL_CONTEXT', 'use the exact approved native revocation');+ apiJson(res, 200, { result }); return true;+ }+ if (who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'only the signed-in paired phone can approve or complete this request');+ if (request.state !== 'waiting') throw new Refused('PHONE_APPROVAL_USED', 'this approval was used or expired; use its existing reply');+ if (action === 'authorize') {+ exact(await readApiBody(req), []);+ const context = request.context;+ let result;+ if (context.action === 'link') {+ await linkBoard(req, context.board, context.target);+ result = { credential: await issueMachine(req, { board: context.board, machine: context.machine }) };+ } else if (context.action === 'delete-board') {+ await deleteBoard(req, context.board);+ result = { deleted: context.board };+ } else result = await issueActionGrant(req, context);+ apiJson(res, 200, { result }); return true;+ }+ if (action === 'complete') {+ const body = exact(await readApiBody(req, { maxBytes: 40000 }), ['response']);+ apiJson(res, 200, devices.completeApproval(account, id, body.response)); return true;+ }+ throw new Refused('NO_ENDPOINT', 'use the documented phone approval action');+ }+ if (who.kind === 'session' && req.method === 'GET') {+ const inbox = /^\/api\/v1\/devices\/(device-[0-9a-f]{32})\/approvals$/.exec(url.pathname);+ if (inbox) { apiJson(res, 200, { approvals: devices.approvals(account, inbox[1]) }); return true; }+ }+ // A machine may wrap only its own board to an already enrolled device, never enroll or revoke.+ if (who.kind === 'machine') {+ const wrap = /^\/api\/v1\/devices\/(device-[0-9a-f]{32})\/boards\/([0-9a-f]{32})$/.exec(url.pathname);+ if (!wrap || req.method !== 'PUT' || wrap[2] !== who.board) throw new Refused('HUMAN_REQUIRED', 'approve device management from the paired phone');+ await authorizeBoard(req, who.board);+ const body = exact(await readApiBody(req, { maxBytes: 8192 }), ['engine', 'wrapped']);+ if (!Number.isSafeInteger(body.engine) || body.engine < 6 || typeof body.wrapped !== 'string' || !/^[A-Za-z0-9_-]{1,6000}$/u.test(body.wrapped) || Buffer.from(body.wrapped, 'base64url').toString('base64url') !== body.wrapped) throw new Refused('DEVICE_WRAP', 'send a versioned opaque wrap for this board');+ devices.put(account, wrap[1], who.board, body.engine, body.wrapped);+ apiJson(res, 200, { recorded: true }); return true;+ }+ if (who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'Sign in as a person to pair or revoke a device.');if (url.pathname === '/api/v1/devices/session' && req.method === 'GET') {apiJson(res, 200, { account }); return true;}diff --git a/relay/device-store.js b/relay/device-store.jsindex 2d0d53a6..24c6deec 100644--- a/relay/device-store.js+++ b/relay/device-store.js@@ -3,6 +3,7 @@ import { chmodSync, existsSync } from 'node:fs';import { join } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { Refused } from '../src/refused.js';+import { approvalContext } from '../src/relay-approval.js';/** Keep device revocations durable so an in-flight native wrap cannot recreate deleted grants. */export function createDeviceStore({ directory, now = Date.now }) {@@ -17,7 +18,11 @@ export function createDeviceStore({ directory, now = Date.now }) {opened.exec(`PRAGMA busy_timeout=30000;CREATE TABLE IF NOT EXISTS device (account TEXT NOT NULL, id TEXT NOT NULL, revoked INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(account,id));CREATE TABLE IF NOT EXISTS wrapped_key (account TEXT NOT NULL, device TEXT NOT NULL, board TEXT NOT NULL, engine INTEGER NOT NULL, wrapped TEXT NOT NULL, PRIMARY KEY(account,device,board));- CREATE TABLE IF NOT EXISTS enrollment (account TEXT NOT NULL, locator TEXT NOT NULL, expires INTEGER NOT NULL, payload TEXT, PRIMARY KEY(account,locator));`);+ CREATE TABLE IF NOT EXISTS enrollment (account TEXT NOT NULL, locator TEXT NOT NULL, expires INTEGER NOT NULL, payload TEXT, PRIMARY KEY(account,locator));+ CREATE TABLE IF NOT EXISTS phone_approval (id TEXT PRIMARY KEY, account TEXT NOT NULL, publisher TEXT NOT NULL,+ board TEXT NOT NULL, device TEXT NOT NULL, action TEXT NOT NULL, machine TEXT NOT NULL, expires INTEGER NOT NULL,+ context TEXT NOT NULL, sealed TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'waiting', response TEXT);+ CREATE UNIQUE INDEX IF NOT EXISTS phone_approval_pending ON phone_approval(account,board,action) WHERE state='waiting';`);db = opened;return db;} catch (error) { opened.close(); throw error; }@@ -35,7 +40,55 @@ export function createDeviceStore({ directory, now = Date.now }) {if (!row) throw new Refused('DEVICE_PAIR_EXPIRED', 'Run pullboard relay on --all for a fresh one-time pairing link.');return row;}+ /** Keep expired approval metadata visible without renewing it or silently asking the phone again. */+ function expireApprovals() {+ database().prepare("UPDATE phone_approval SET state='expired', response=NULL WHERE expires<=? AND state IN ('waiting','approved')").run(now());+ }+ /** Return public immutable context and opaque envelopes, never a plaintext credential. */+ function approval(row) {+ return row ? { context: JSON.parse(row.context), sealed: row.sealed, state: row.state, response: row.response } : null;+ }return {+ /** Enqueue one immutable action for this account's already enrolled phone; PM cannot approve it. */+ requestApproval(account, value, sealed) {+ const context = approvalContext(value);+ if (context.account !== account || context.expires <= now() || context.expires > now() + 630_000 ||+ typeof sealed !== 'string' || !/^[A-Za-z0-9_-]{1,32000}$/u.test(sealed)) throw new Refused('PHONE_APPROVAL_CONTEXT', 'send a bounded ten-minute sealed approval for this account');+ active(account, context.device);+ database().exec('BEGIN IMMEDIATE');+ try {+ expireApprovals();+ const existing = database().prepare('SELECT * FROM phone_approval WHERE id=?').get(context.id);+ if (existing && (existing.context !== JSON.stringify(context) || existing.sealed !== sealed)) throw new Refused('PHONE_APPROVAL_CONTEXT', 'this request id already names another action');+ const other = database().prepare("SELECT id FROM phone_approval WHERE account=? AND board=? AND action=? AND state='waiting'").get(account, context.board, context.action);+ if (other && other.id !== context.id) throw new Refused('PHONE_APPROVAL_PENDING', 'one approval for this board and action is already waiting; use it or wait for its visible expiry');+ if (!existing) database().prepare('INSERT INTO phone_approval(id,account,publisher,board,device,action,machine,expires,context,sealed) VALUES(?,?,?,?,?,?,?,?,?,?)')+ .run(context.id, account, context.publisher, context.board, context.device, context.action, context.machine, context.expires, JSON.stringify(context), sealed);+ database().exec('COMMIT');+ return approval(existing ?? database().prepare('SELECT * FROM phone_approval WHERE id=?').get(context.id));+ } catch (error) { database().exec('ROLLBACK'); throw error; }+ },+ /** Read one request only within its account and, for PM callers, its exact publisher and machine. */+ approval(account, id, scope) {+ expireApprovals();+ const row = database().prepare('SELECT * FROM phone_approval WHERE account=? AND id=?').get(account, id);+ if (!row || scope && (scope.board !== row.publisher || scope.machine !== row.machine)) throw new Refused('PHONE_APPROVAL_MISSING', 'use the approval published by this machine and board');+ return approval(row);+ },+ /** List only this paired phone's account inbox; a machine never gets the account inventory. */+ approvals(account, device) {+ active(account, device);+ expireApprovals();+ return database().prepare("SELECT * FROM phone_approval WHERE account=? AND device=? AND state='waiting' ORDER BY expires,id").all(account, device).map(approval);+ },+ /** Persist only the phone-encrypted reply, rejecting expired or twice-completed approval. */+ completeApproval(account, id, response) {+ if (typeof response !== 'string' || !/^[A-Za-z0-9_-]{1,32000}$/u.test(response)) throw new Refused('PHONE_APPROVAL_CONTEXT', 'send the encrypted phone reply');+ expireApprovals();+ const result = database().prepare("UPDATE phone_approval SET response=?,state='approved' WHERE account=? AND id=? AND state='waiting' AND expires>?").run(response, account, id, now());+ if (!result.changes) throw new Refused('PHONE_APPROVAL_USED', 'this request was approved or expired; use its existing reply');+ return { recorded: true };+ },/** Initialize an account-owned ten-minute locator without storing its secret. */begin(account, locator) {database().prepare('DELETE FROM enrollment WHERE expires<=?').run(now());diff --git a/relay/journal.js b/relay/journal.jsindex f3f0065c..57e1dd51 100644--- a/relay/journal.js+++ b/relay/journal.js@@ -4,7 +4,7 @@ import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs';import { join, resolve } from 'node:path';import { Refused } from '../src/refused.js';-const FORMAT = 2;+const FORMAT = 3;const DEFAULT_BYTES = 100_000;/** Validate a persistent identity before it can name an internal file. */@@ -37,20 +37,40 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEdb.exec(`CREATE TABLE IF NOT EXISTS journal_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);CREATE TABLE IF NOT EXISTS journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL,kind TEXT NOT NULL CHECK(kind IN ('move','request')), payload BLOB NOT NULL,- sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','agent')), sender_user TEXT NOT NULL,+ sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','agent','machine')), sender_user TEXT NOT NULL,sender_agent TEXT, CHECK((sender_kind='person' AND sender_agent IS NULL) OR- (sender_kind='agent' AND sender_agent IS NOT NULL)))`);+ (sender_kind IN ('agent','machine') AND sender_agent IS NOT NULL)))`);const saved = db.prepare('SELECT key, value FROM journal_meta ORDER BY key').all();if (saved.length === 0) {if (db.prepare('SELECT 1 FROM journal_record LIMIT 1').get()) throw new Refused('RELAY_STORAGE', 'restore the journal with its original identity and format metadata');db.prepare('INSERT INTO journal_meta (key,value) VALUES (?,?), (?,?)').run('board', id, 'format', String(FORMAT));- } else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== id || saved[1].key !== 'format' || saved[1].value !== String(FORMAT)) {+ } else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== id || saved[1].key !== 'format' || !['2', String(FORMAT)].includes(saved[1].value)) {throw new Refused('RELAY_STORAGE', 'open this journal with its original board identity and supported transport format');}db.exec(`CREATE TABLE IF NOT EXISTS journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS journal_snapshot (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL,- received_at TEXT NOT NULL, payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind='person'),- sender_user TEXT NOT NULL, sender_agent TEXT CHECK(sender_agent IS NULL))`);+ received_at TEXT NOT NULL, payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','machine')),+ sender_user TEXT NOT NULL, sender_agent TEXT, CHECK((sender_kind='person' AND sender_agent IS NULL) OR+ (sender_kind='machine' AND sender_agent IS NOT NULL)))`);+ // The authenticated machine principal needs new CHECK constraints; preserve every opaque byte.+ if (saved[1]?.value === '2') {+ db.exec(`ALTER TABLE journal_record RENAME TO journal_record_v2;+ CREATE TABLE journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL,+ kind TEXT NOT NULL CHECK(kind IN ('move','request')), payload BLOB NOT NULL,+ sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','agent','machine')), sender_user TEXT NOT NULL,+ sender_agent TEXT, CHECK((sender_kind='person' AND sender_agent IS NULL) OR+ (sender_kind IN ('agent','machine') AND sender_agent IS NOT NULL)));+ INSERT INTO journal_record SELECT * FROM journal_record_v2;+ DROP TABLE journal_record_v2;+ ALTER TABLE journal_snapshot RENAME TO journal_snapshot_v2;+ CREATE TABLE journal_snapshot (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL,+ received_at TEXT NOT NULL, payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','machine')),+ sender_user TEXT NOT NULL, sender_agent TEXT, CHECK((sender_kind='person' AND sender_agent IS NULL) OR+ (sender_kind='machine' AND sender_agent IS NOT NULL)));+ INSERT INTO journal_snapshot SELECT * FROM journal_snapshot_v2;+ DROP TABLE journal_snapshot_v2;+ UPDATE journal_meta SET value='3' WHERE key='format';`);+ }db.exec('INSERT OR IGNORE INTO journal_head (slot,sequence) SELECT 1, COALESCE(MAX(sequence),0) FROM journal_record');if (!db.prepare('PRAGMA table_info(journal_head)').all().some((column) => column.name === 'last_activity_at')) {db.exec('ALTER TABLE journal_head ADD COLUMN last_activity_at TEXT');@@ -70,18 +90,19 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEfunction record(row) {return { sequence: row.sequence, receivedAt: row.received_at, kind: row.kind ?? 'snapshot',sender: { kind: row.sender_kind, userId: row.sender_user,- ...(row.sender_kind === 'agent' ? { agent: row.sender_agent } : {}) }, bytes: Buffer.from(row.payload) };+ ...(row.sender_kind === 'agent' ? { agent: row.sender_agent } : row.sender_kind === 'machine' ? { machine: row.sender_agent } : {}) }, bytes: Buffer.from(row.payload) };}/** Require server-derived attribution, copying only its public identity and never a credential. */function sender(value, personOnly = false) {- if (!value || !['person', 'agent'].includes(value.kind) || typeof value.userId !== 'string' ||+ if (!value || !['person', 'agent', 'machine'].includes(value.kind) || typeof value.userId !== 'string' ||!value.userId.length || value.userId.length > 256 ||- (value.kind === 'agent' && (typeof value.agent !== 'string' || !value.agent.length || value.agent.length > 256))) {+ (value.kind === 'agent' && (typeof value.agent !== 'string' || !value.agent.length || value.agent.length > 256)) ||+ (value.kind === 'machine' && (typeof value.machine !== 'string' || !value.machine.length || value.machine.length > 256))) {throw new Refused('RELAY_PRINCIPAL', 'supply the authenticated sender before storing a sealed record');}- if (personOnly && value.kind !== 'person') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to replace a board snapshot');- return { kind: value.kind, userId: value.userId, agent: value.kind === 'agent' ? value.agent : null };+ if (personOnly && !['person', 'machine'].includes(value.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential to replace its snapshot');+ return { kind: value.kind, userId: value.userId, agent: value.kind === 'agent' ? value.agent : value.kind === 'machine' ? value.machine : null };}/** Read the latest committed sequence, including an empty journal's initial cursor. */diff --git a/relay/service.js b/relay/service.jsindex 18691b17..450ef05a 100644--- a/relay/service.js+++ b/relay/service.js@@ -29,14 +29,16 @@ function identity(id) {function credential(req, publicOrigin, write = false) {const authorization = req.headers.authorization;if (authorization) {- const match = /^Bearer ((?:ps_|pa_)[A-Za-z0-9_-]{43})$/.exec(String(authorization));+ const match = /^Bearer ((?:ps_|pa_|pm_)[A-Za-z0-9_-]{43})$/.exec(String(authorization));if (!match) throw new Refused('AUTH_REQUIRED', 'supply a current relay bearer credential');return match[1];}const cookies = String(req.headers.cookie ?? '').split(';').map((part) => part.trim()).filter((part) => part.startsWith('pb_session='));if (cookies.length !== 1 || !publicOrigin) throw new Refused('AUTH_REQUIRED', 'sign in to the configured relay origin');if (write && req.headers.origin !== publicOrigin) throw new Refused('BAD_ORIGIN', 'send cookie-authorized writes from the configured relay origin');- return cookies[0].slice('pb_session='.length);+ const session = cookies[0].slice('pb_session='.length);+ if (!/^ps_[A-Za-z0-9_-]{43}$/.test(session)) throw new Refused('AUTH_REQUIRED', 'sign in to the relay in this browser');+ return session;}/** Validate an optional trusted browser origin, never inferring one from a request header. */@@ -69,9 +71,9 @@ function state(row) { return { sequence: row.sequence, receivedAt: row.receivedA/** Project a freshly authenticated credential to public sender metadata, never taking body fields. */function sender(who, personOnly = false) {- if (personOnly && who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to replace a snapshot or unlink a board');- return { kind: who.kind === 'session' ? 'person' : 'agent', userId: who.user.id,- ...(who.kind === 'board' ? { agent: who.agent } : {}) };+ if (personOnly && who.kind !== 'session' && !(personOnly === 'snapshot' && who.kind === 'machine')) throw new Refused('HUMAN_REQUIRED', 'approve this person action from the paired phone');+ return { kind: who.kind === 'session' ? 'person' : who.kind === 'machine' ? 'machine' : 'agent', userId: who.user.id,+ ...(who.kind === 'board' ? { agent: who.agent } : who.kind === 'machine' ? { machine: who.machine } : {}) };}/** Create a private relay handler; the caller owns sign-in lifecycle and service shutdown. */@@ -110,6 +112,16 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginauthorizeBoard: (req, id) => authorizedRequest(req, id, true),boardsFor: req => auth.boardsFor(credential(req, origin)),devices: deviceStore,+ linkBoard: (req, id, repository) => auth.linkBoard(credential(req, origin, true), id, repository),+ issueMachine: (req, value) => auth.issueMachine(credential(req, origin, true), value),+ issueActionGrant: (req, context) => auth.issueActionGrant(credential(req, origin, true), context),+ consumeActionGrant: (req, grant, context) => auth.consumeActionGrant(credential(req, origin, true), grant, context),+ revokeToken: (principal, id, board) => auth.revokeApprovedToken(principal, id, board),+ deleteBoard: async (req, id) => {+ const who = await authorizedRequest(req, id, true);+ sender(who, true);+ auth.withBoard(id, () => { requireClientVersion(id, who.engineVersion); retention.unlink(id); deviceStore.unlink(id); });+ },});const pairingStore = createPairingStore({ now });const pairing = createPairingHandler({@@ -226,12 +238,12 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin}if (req.method === 'PUT' && snapshot) {const id = identity(snapshot[1]);- sender(await authorizedRequest(req, id, true), true);+ sender(await authorizedRequest(req, id, true), 'snapshot');const body = await readApiBody(req, { maxBytes: SNAPSHOT_BODY });const bytes = sealed(body);if (!Number.isSafeInteger(body.sequence) || body.sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence covered by the sealed snapshot');const who = await authorizedRequest(req, id, true);- const principal = sender(who, true);+ const principal = sender(who, 'snapshot');const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes, principal, { initialOnly: req.headers['if-none-match'] === '*' }), true, who.engineVersion);return apiJson(res, 200, { state: annotated(saved, id) });}diff --git a/relay/smoke.mjs b/relay/smoke.mjsindex b64acb92..066d6ba4 100644--- a/relay/smoke.mjs+++ b/relay/smoke.mjs@@ -155,7 +155,10 @@ async function smoke(address) {failure = error;}if (linked) {- try { await cli(root, ['relay', 'off']); }+ try {+ const off = await cli(root, ['relay', 'off']);+ if (result) { result.remoteCopyRetained = true; result.notice = off.notice; }+ }catch (error) { failure ??= error; }}if (failure) throw failure;diff --git a/src/api.js b/src/api.jsindex cd2e788a..8148a4da 100644--- a/src/api.js+++ b/src/api.js@@ -182,7 +182,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =move: (board, body) => executeMove(board.root, body, runCommand),request: (board, body) => createRequest(board.root, body),tokens: async (board) => (await relayTokens(board.root, { err() {} })).tokens,- revokeToken: (board, id) => relayRevoke(board.root, id, { err() {} }),+ revokeToken: (board, id) => relayRevoke(board.root, id, { personChannel: 'view', say() {}, err() {} }),});}diff --git a/src/cli.js b/src/cli.jsindex b7c9f6cf..ffd68026 100644--- a/src/cli.js+++ b/src/cli.js@@ -68,7 +68,7 @@ import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';-import { relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';+import { autoLinkProject, relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';import { readRelayMachine } from './relay-machine.js';import { relayJoin, relayPair } from './relay-pairing-client.js';import { executePersonRequests } from './relay-request-execution.js';@@ -2805,6 +2805,8 @@ async function runMain(argv, streams) {} catch { sync = false; needsRepo = false; }if (parsed) {try {+ const [command, verb] = parsed.positionals;+ if (parsed.values.as === 'person' || command === 'relay' && ['on', 'join', 'revoke'].includes(verb)) requirePersonChannel(io.personChannel);checkoutSession = await bindCheckoutSession(io, parsed.positionals, parsed.values);if (checkoutSession?.lease) CHECKOUT_LEASES.set(io, checkoutSession.lease);} catch (error) {@@ -2829,6 +2831,7 @@ async function runMain(argv, streams) {};if (needsRepo) rememberTrunk(io);if (sync) {+ try { await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }await retry();try { await executePersonRequests(io.cwd, io, main); }catch (error) {diff --git a/src/engine.js b/src/engine.jsindex ff1aa8cc..de2df0e1 100644--- a/src/engine.js+++ b/src/engine.js@@ -133,7 +133,8 @@ export function engineReceipt(board, id) {/** Authorize each public relay position before replay, retaining refusals atomically with its cursor. */export function applyRelayMove(board, move, { sequence, at, sender, kind }) {requireSupportedEngine(move);- const problem = relaySenderProblem(move, sender, kind);+ const phoneReceipt = sender?.kind === 'machine' && move?.engine >= 6 && Boolean(move.personRequest) && !requestMoveProblem(board, move, { checkExecutorLease: false });+ const problem = relaySenderProblem(move, sender, kind, { phoneReceipt });if (!problem) return applyEngineMove(board, move, { sequence, at });if (!Number.isSafeInteger(sequence) || sequence < 1 || !Number.isFinite(Date.parse(at))) throw new Refused('RELAY_MOVE', 'supply a valid relay sequence and receipt timestamp');return store.atomic(board, () => {diff --git a/src/machine.js b/src/machine.jsindex 4e0c1d23..af8f5040 100644--- a/src/machine.js+++ b/src/machine.js@@ -10,7 +10,7 @@*//** Executable move semantics, carried by every sealed move and retained during replay [H16]. */-export const ENGINE_VERSION = 5;+export const ENGINE_VERSION = 6;/** @typedef {'agent' | 'coordinator' | 'clock'} Role */diff --git a/src/relay-approval.js b/src/relay-approval.jsnew file mode 100644index 00000000..831ca7e5--- /dev/null+++ b/src/relay-approval.js@@ -0,0 +1,107 @@+/** Client-only encrypted phone approval and RAM-only native replies [H5,H16,H17,B26]. */+import { devicePublicKey } from './relay-device-keys.js';+import { Refused } from './refused.js';++const encoder = new TextEncoder();+const FIELDS = ['id', 'account', 'publisher', 'board', 'device', 'action', 'target', 'machine', 'command', 'expires'];++/** Canonically bind an opaque approval to the exact command the paired phone will display. */+export function approvalContext(value) {+ if (!value || Object.keys(value).some(key => !FIELDS.includes(key)) ||+ !/^[A-Za-z0-9_-]{1,80}$/u.test(value.id ?? '') || !/^[0-9a-f]{32}$/u.test(value.publisher ?? '') ||+ !/^[0-9a-f]{32}$/u.test(value.board ?? '') || !/^device-[0-9a-f]{32}$/u.test(value.device ?? '') ||+ !['link', 'revoke-device', 'revoke-token', 'delete-board'].includes(value.action) || !Number.isSafeInteger(value.expires) || value.expires < 1 ||+ ['account', 'target', 'machine', 'command'].some(key => typeof value[key] !== 'string' || !value[key] || value[key].length > 256 || /[\u0000-\u001f\u007f]/u.test(value[key])) ||+ value.action === 'link' && !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(value.target) ||+ value.action === 'revoke-device' && !/^device-[0-9a-f]{32}$/u.test(value.target) ||+ value.action === 'revoke-token' && !/^[A-Za-z0-9_-]{1,128}$/u.test(value.target) ||+ value.action === 'delete-board' && value.target !== value.board ||+ value.action !== 'link' && value.board !== value.publisher) {+ throw new Refused('PHONE_APPROVAL_CONTEXT', 'Request approval for the exact board, action, machine and command.');+ }+ return Object.fromEntries(FIELDS.map(key => [key, value[key]]));+}++/** Encode bounded ciphertext without a Node dependency so the same protocol runs on the phone. */+function encode(value) {+ return btoa(String.fromCharCode(...value)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');+}++/** Decode canonical transport bytes without accepting an oversized approval envelope. */+function decode(value) {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{1,24000}$/u.test(value)) throw new Refused('PHONE_APPROVAL_AUTH', 'Request a fresh phone approval.');+ let result;+ try { result = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), char => char.charCodeAt(0)); }+ catch { throw new Refused('PHONE_APPROVAL_AUTH', 'Request a fresh phone approval.'); }+ if (encode(result) !== value) throw new Refused('PHONE_APPROVAL_AUTH', 'Request a fresh phone approval.');+ return result;+}++/** Authenticate a proposal with the already paired board key, preventing relay-created native intent. */+export async function signApprovalIntent(boardKey, envelope) {+ if (!(boardKey instanceof Uint8Array) || boardKey.length !== 32) throw new Refused('PHONE_APPROVAL_AUTH', 'Pair this publishing board on the phone first.');+ const key = await crypto.subtle.importKey('raw', boardKey, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);+ return encode(new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(JSON.stringify(['pullboard-phone-intent-v1', envelope])))));+}++/** Check a native proposal before showing its approval button; unknown boards never receive a grant. */+export async function verifyApprovalIntent(boardKey, packet) {+ try {+ if (!(boardKey instanceof Uint8Array) || boardKey.length !== 32) throw new Error('key');+ const key = await crypto.subtle.importKey('raw', boardKey, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);+ if (!await crypto.subtle.verify('HMAC', key, decode(packet.mac), encoder.encode(JSON.stringify(['pullboard-phone-intent-v1', packet.envelope])))) throw new Error('mac');+ return packet.envelope;+ } catch { throw new Refused('PHONE_APPROVAL_AUTH', 'The native request could not be authenticated by its paired board.'); }+}++/** Create a nonextractable reply key unless this is an explicitly durable, non-person link request. */+export async function createApprovalReply({ link = false } = {}) {+ const pair = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, link, ['deriveBits']);+ return { privateKey: pair.privateKey, publicKey: devicePublicKey(await crypto.subtle.exportKey('jwk', pair.publicKey)),+ ...(link ? { storedKey: await crypto.subtle.exportKey('jwk', pair.privateKey) } : {}) };+}++/** Restore only a non-person link request's reply key; native person actions never call this path. */+export async function restoreLinkReply(value) {+ try { return await crypto.subtle.importKey('jwk', value, { name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits']); }+ catch { throw new Refused('PHONE_APPROVAL_AUTH', 'Cancel the expired link request and ask the phone to link this board again.'); }+}++/** Derive a separate key for each intent/reply and immutable context, outside the board-key domain. */+async function approvalKey(privateKey, publicKey, ephemeral, context, direction, usage) {+ const peer = await crypto.subtle.importKey('jwk', devicePublicKey(publicKey), { name: 'ECDH', namedCurve: 'P-256' }, false, []);+ const shared = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, privateKey, 256);+ const material = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey']);+ return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: encoder.encode(JSON.stringify(devicePublicKey(ephemeral))),+ info: encoder.encode(JSON.stringify(['pullboard-phone-approval-v1', direction, context])) }, material,+ { name: 'AES-GCM', length: 256 }, false, [usage]);+}++/** Encrypt a bounded intent or reply to a locally trusted key, authenticated with its exact context. */+export async function sealApproval(value, publicKey, binding, direction) {+ const context = approvalContext(binding);+ if (!['intent', 'reply'].includes(direction)) throw new Refused('PHONE_APPROVAL_CONTEXT', 'Use the intent or reply approval domain.');+ const plain = encoder.encode(JSON.stringify(value));+ if (plain.length > 16000) throw new Refused('PHONE_APPROVAL_CONTEXT', 'Keep the phone approval smaller than 16 KiB.');+ const pair = await createApprovalReply();+ const derived = await approvalKey(pair.privateKey, publicKey, pair.publicKey, context, direction, 'encrypt');+ const nonce = crypto.getRandomValues(new Uint8Array(12));+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce,+ additionalData: encoder.encode(JSON.stringify(['pullboard-phone-approval', 1, direction, context])), tagLength: 128 }, derived, plain));+ return { v: 1, direction, context, ephemeral: pair.publicKey, nonce: encode(nonce), ciphertext: encode(ciphertext) };+}++/** Authenticate before decoding, refusing changed action metadata or another request's encrypted grant. */+export async function openApproval(privateKey, envelope, binding, direction) {+ const context = approvalContext(binding);+ try {+ if (!envelope || envelope.v !== 1 || envelope.direction !== direction || !['intent', 'reply'].includes(direction) ||+ JSON.stringify(approvalContext(envelope.context)) !== JSON.stringify(context)) throw new Error('context');+ const nonce = decode(envelope.nonce);+ if (nonce.length !== 12) throw new Error('nonce');+ const derived = await approvalKey(privateKey, envelope.ephemeral, envelope.ephemeral, context, direction, 'decrypt');+ const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce,+ additionalData: encoder.encode(JSON.stringify(['pullboard-phone-approval', 1, direction, context])), tagLength: 128 }, derived, decode(envelope.ciphertext));+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plain));+ } catch { throw new Refused('PHONE_APPROVAL_AUTH', 'The phone approval could not be authenticated for this exact action. Request approval again.'); }+}diff --git a/src/relay-key.js b/src/relay-key.jsindex 3789a0b1..f45b657f 100644--- a/src/relay-key.js+++ b/src/relay-key.js@@ -1,7 +1,7 @@/** Device-only board keys, kept outside repositories and relay requests [H1,H15,H17]. */import { spawnSync } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';import { decodeBoardKey, encodeBoardKey } from './seal.js';@@ -116,3 +116,16 @@ export function forgetBoardKey(boardId, storage) {}rmSync(file, { force: true });}++/** Delete the retired same-user person-session files without ever reading or hydrating a credential. */+export function scrubLegacyPersonSessions() {+ const directory = join(keyFile('0'.repeat(32)), '..');+ if (!existsSync(directory)) return;+ const parent = lstatSync(directory);+ if (!parent.isDirectory() || parent.isSymbolicLink() || (parent.mode & 0o077)) {+ throw new Refused('RELAY_KEY_STORAGE', 'Restore the owner-only relay-keys directory before removing retired person sessions.');+ }+ for (const name of readdirSync(directory)) {+ if (/^[0-9a-f]{32}\.session\.json(?:\.[0-9a-f-]+\.tmp)?$/u.test(name)) rmSync(join(directory, name), { force: true });+ }+}diff --git a/src/relay-machine.js b/src/relay-machine.jsindex c0b1a4c0..a98f3a31 100644--- a/src/relay-machine.js+++ b/src/relay-machine.js@@ -1,10 +1,12 @@-/** Owner-only machine sessions, authenticated device roster and one-use enrollment [H5,H15,H17]. */+/** Owner-only machine metadata, authenticated device roster and one-use enrollment [H5,H15,H17]. */import { randomUUID } from 'node:crypto';-import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { authenticateDeviceEnrollment, devicePublicKey, wrapDeviceBoardKey } from './relay-device-keys.js';+import { scrubLegacyPersonSessions } from './relay-key.js';+import { approvalContext } from './relay-approval.js';import { createPairingCode } from './pairing.js';import { Refused } from './refused.js';@@ -26,28 +28,44 @@ function privateEntry(path, folder = false) {/** Return the empty durable format without sharing mutable arrays between callers. */function emptyState() {- return { v: 1, autoLink: false, session: null, devices: [], excluded: [], pending: null, revocations: [] };+ return { v: 2, autoLink: false, owner: null, machine: 'machine-' + randomUUID(), devices: [], excluded: [], pending: null, revocations: [], approvals: [] };}/** Validate machine metadata before any mutation can overwrite the trusted device roster. */function validate(state) {- if (!state || state.v !== 1 || typeof state.autoLink !== 'boolean' || !Array.isArray(state.devices) ||+ if (!state || ![1, 2].includes(state.v) || typeof state.autoLink !== 'boolean' || !Array.isArray(state.devices) ||!Array.isArray(state.excluded) || !Array.isArray(state.revocations) || state.excluded.some(root => typeof root !== 'string') ||state.devices.some(device => !DEVICE.test(device?.deviceId ?? '') || typeof device.account !== 'string' || typeof device.url !== 'string' ||!/^[0-9a-f]{64}$/u.test(device.fingerprint ?? '') || typeof device.label !== 'string' || typeof device.createdAt !== 'string') ||- (state.session !== null && (!state.session || !/^ps_[A-Za-z0-9_-]{43}$/u.test(state.session.token ?? '') ||+ (state.session != null && (!state.session || !/^ps_[A-Za-z0-9_-]{43}$/u.test(state.session.token ?? '') ||typeof state.session.account !== 'string' || typeof state.session.url !== 'string')) ||(state.pending !== null && (!state.pending || !/^[A-Za-z0-9_-]{43}$/u.test(state.pending.secret ?? '') ||!/^[A-Za-z0-9_-]{22}$/u.test(state.pending.locator ?? '') || typeof state.pending.account !== 'string' ||typeof state.pending.url !== 'string' || !Number.isSafeInteger(state.pending.expires)))) {throw new Refused('RELAY_MACHINE_STORAGE', 'Restore supported machine relay settings without replacing the trusted device list.');}+ if (state.v === 2 && (!/^[A-Za-z0-9_-]{1,128}$/u.test(state.machine ?? '') || !Array.isArray(state.approvals) ||+ (state.owner !== null && (!state.owner || typeof state.owner.account !== 'string' || !state.owner.account ||+ typeof state.owner.url !== 'string' || !state.owner.url || Object.keys(state.owner).some(key => !['account', 'url'].includes(key)))))) {+ throw new Refused('RELAY_MACHINE_STORAGE', 'Restore the supported machine identity and phone-link metadata, or sign in again explicitly.');+ }+ for (const entry of state.approvals ?? []) {+ try {+ const context = approvalContext(entry.context);+ if (context.action !== 'link' || typeof entry.root !== 'string' || typeof entry.publisherRoot !== 'string' ||+ typeof entry.published !== 'boolean' || typeof entry.sealed !== 'string' || !/^[A-Za-z0-9_-]{1,40000}$/u.test(entry.sealed) ||+ !/^[A-Za-z0-9_-]{43}$/u.test(entry.replyKey?.d ?? '') ||+ Object.keys(entry).some(key => !['root', 'publisherRoot', 'context', 'sealed', 'replyKey', 'published'].includes(key))) throw new Error('metadata');+ const { d, key_ops, ...publicKey } = entry.replyKey;+ devicePublicKey(publicKey);+ } catch { throw new Refused('RELAY_MACHINE_STORAGE', 'Restore the pending phone-link proposal; person-action replies must stay in memory.'); }+ }for (const device of state.devices) devicePublicKey(device.publicKey);return state;}/** Read the durable machine state without creating a directory or touching the network. */-export function readRelayMachine() {+function readState() {const folder = directory();if (!existsSync(folder)) return emptyState();privateEntry(folder, true);@@ -60,6 +78,19 @@ export function readRelayMachine() {return validate(state);}+/** Scrub legacy person sessions before returning settings to any native or agent command. */+export function readRelayMachine() {+ scrubLegacyPersonSessions();+ const state = readState();+ const folder = directory();+ const fragments = existsSync(folder) && readdirSync(folder).some(name => /^state\.[0-9]+\.[0-9a-f-]+\.tmp$/u.test(name));+ if (state.v === 1 || state.session != null || fragments) {+ updateRelayMachine(() => {});+ return readState();+ }+ return state;+}+/** Serialize cross-process read-modify-write and atomically replace the private machine file. */export function updateRelayMachine(mutate) {const folder = directory();@@ -74,8 +105,18 @@ export function updateRelayMachine(mutate) {db.exec('PRAGMA busy_timeout = 30000');db.exec('CREATE TABLE IF NOT EXISTS machine_lock (id INTEGER PRIMARY KEY)');db.exec('BEGIN IMMEDIATE');- const state = readRelayMachine();+ // A crashed legacy writer may have left a complete person session beside state.json.+ for (const name of readdirSync(folder)) {+ if (/^state\.[0-9]+\.[0-9a-f-]+\.tmp$/u.test(name)) rmSync(join(folder, name), { force: true });+ }+ const state = readState();+ state.owner ??= state.session ? { account: state.session.account, url: state.session.url } : null;+ state.machine ??= 'machine-' + randomUUID();+ state.approvals ??= [];+ state.v = 2;+ delete state.session;const result = mutate(state);+ delete state.session;validate(state);temporary = join(folder, `state.${process.pid}.${randomUUID()}.tmp`);const fd = openSync(temporary, 'wx', 0o600);diff --git a/src/relay-pairing-client.js b/src/relay-pairing-client.jsindex 35ae77ac..9caf9908 100644--- a/src/relay-pairing-client.js+++ b/src/relay-pairing-client.js@@ -12,8 +12,10 @@ import { terminalQr } from './qr.js';import { DEFAULT_RELAY, originRepository, relayStatus, syncRelay } from './relay.js';import { ENGINE_VERSION } from './machine.js';import { Refused } from './refused.js';+import { requirePersonChannel } from './person.js';+import { updateRelayMachine } from './relay-machine.js';-const TOKEN = /^ps_[A-Za-z0-9_-]{43}$/;+const TOKEN = /^pm_[A-Za-z0-9_-]{43}$/;const BOARD = /^[0-9a-f]{32}$/;const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;@@ -87,7 +89,7 @@ async function signIn(url, io) {if (Date.now() >= deadline) throw new Refused('OAUTH_EXPIRED', 'GitHub device sign-in expired; run pullboard relay join again with a fresh code');const result = await relayRequest(url, '', '/auth/device/poll', { ticket: start.ticket });if (!result.pending) {- if (!TOKEN.test(result.token)) throw new Refused('RELAY_RESPONSE', 'the relay did not issue a person session; sign in again');+ if (!/^ps_[A-Za-z0-9_-]{43}$/.test(result.token)) throw new Refused('RELAY_RESPONSE', 'the relay did not issue a person session; sign in again');return result;}wait = result.retryAfter ?? start.interval;@@ -181,6 +183,7 @@ function requireMissingKey(board) {/** Consume a printed one-time code, restore the board and save this device's own link. */export async function relayJoin(root, code, address, io) {+ requirePersonChannel(io.personChannel);const parsed = parsePairingCode(code);const url = relayOrigin(address || DEFAULT_RELAY);requireFreshTarget(root);@@ -194,6 +197,9 @@ export async function relayJoin(root, code, address, io) {if (new URL(bundle.url).origin !== new URL(url).origin) throw new Refused('PAIR_RELAY', 'this code belongs to another relay; rerun join with that relay address');const file = linkFile(root);if (existsSync(file)) throw new Refused('RELAY_LINKED', 'this clone already has relay link metadata; use a fresh clone to join another device');+ const machine = updateRelayMachine(state => state.machine);+ const issued = await relayRequest(url, signed.token, '/auth/machines', { board: bundle.board, machine });+ if (!TOKEN.test(issued.token) || issued.board !== bundle.board || issued.machine !== machine) throw new Refused('RELAY_RESPONSE', 'the relay did not issue this joined board’s machine credential; pair again');let keyStorage;try {keyStorage = storeBoardKey(bundle.board, Buffer.from(bundle.key, 'base64url'));@@ -204,7 +210,7 @@ export async function relayJoin(root, code, address, io) {saveState(file, {version: 1, board: bundle.board, url: bundle.url, repository: bundle.repository,mode: bundle.mode,- token: signed.token, tokenId: signed.id, keyStorage,+ token: issued.token, tokenId: issued.id, machine, account: signed.user.id, keyStorage,sequence: bundle.sequence, cursor: bundle.cursor,});} catch (error) {diff --git a/src/relay-phone.js b/src/relay-phone.jsnew file mode 100644index 00000000..d1d136a8--- /dev/null+++ b/src/relay-phone.js@@ -0,0 +1,58 @@+/** Native approval requests never retain a person grant or its reply key [H5,H16,H17,B26]. */+import { randomUUID } from 'node:crypto';+import { approvalContext, createApprovalReply, openApproval, sealApproval, signApprovalIntent } from './relay-approval.js';+import { readBoardKey } from './relay-key.js';+import { readRelayMachine } from './relay-machine.js';+import { requirePersonChannel } from './person.js';+import { Refused } from './refused.js';++/** Select only a phone whose public key was MAC-authenticated into this native machine's roster. */+export function approvalPhone(state) {+ const device = readRelayMachine().devices.find(entry => entry.account === state.account && entry.url === state.url);+ if (!device) throw new Refused('PHONE_NOT_PAIRED', 'Pair the phone with pullboard relay on --all before requesting this action.');+ return device;+}++/** Build a sealed immutable proposal; only new-board link replies can have a durable private key. */+export async function phoneProposal(state, action, target, { board = state.board, command, link = false } = {}) {+ if (!/^pm_[A-Za-z0-9_-]{43}$/u.test(state.token ?? '')) throw new Refused('RELAY_SESSION', 'Run pullboard relay on --all to replace the old person session with board machine credentials.');+ const phone = approvalPhone(state);+ const reply = await createApprovalReply({ link });+ const context = approvalContext({ id: randomUUID(), account: state.account, publisher: state.board, board,+ device: phone.deviceId, action, target, machine: state.machine,+ command: command ?? 'pullboard relay ' + (action === 'revoke-device' || action === 'revoke-token' ? 'revoke ' + target : 'off'), expires: Date.now() + 600_000 });+ const envelope = await sealApproval({ context, replyKey: reply.publicKey }, phone.publicKey, context, 'intent');+ const mac = await signApprovalIntent(readBoardKey(state.board), envelope);+ return { context, sealed: Buffer.from(JSON.stringify({ envelope, mac })).toString('base64url'), reply };+}++/** Keep a person action foreground and RAM-only from its request through one-use execution. */+export async function nativePhoneAction(state, action, target, io, send) {+ requirePersonChannel(io.personChannel);+ const proposal = await phoneProposal(state, action, target);+ const { context, sealed, reply } = proposal;+ await send(state, '/api/v1/devices/approvals', { method: 'POST', body: { context, sealed } }, io);+ io.say('Approve ' + context.command + ' on your paired phone; expires ' + new Date(context.expires).toISOString() + '.');+ let interrupted = false;+ /** Drop the RAM-only reply key when the foreground command is interrupted. */+ const stop = () => { interrupted = true; };+ process.once('SIGINT', stop); process.once('SIGTERM', stop);+ try {+ while (!interrupted && Date.now() < context.expires) {+ const document = await send(state, '/api/v1/devices/approvals/' + context.id, {}, io);+ const approved = document.approval;+ if (JSON.stringify(approvalContext(approved?.context)) !== JSON.stringify(context)) throw new Refused('PHONE_APPROVAL_AUTH', 'The approval context changed; request this action again.');+ if (approved.state === 'expired') break;+ if (approved.state === 'approved') {+ let envelope;+ try { envelope = JSON.parse(Buffer.from(approved.response, 'base64url').toString('utf8')); }+ catch { throw new Refused('PHONE_APPROVAL_AUTH', 'The phone reply was invalid; request this action again.'); }+ const result = await openApproval(reply.privateKey, envelope, context, 'reply');+ if (!/^pg_[A-Za-z0-9_-]{43}$/u.test(result.grant ?? '') || !Number.isSafeInteger(result.expires) || result.expires <= Date.now()) throw new Refused('PHONE_APPROVAL_EXPIRED', 'Request a fresh phone approval for this exact action.');+ return (await send(state, '/api/v1/devices/approvals/' + context.id + '/execute', { method: 'POST', body: { grant: result.grant } }, io)).result;+ }+ await new Promise(resolve => { setTimeout(resolve, 500); });+ }+ throw new Refused('PHONE_APPROVAL_EXPIRED', 'The action was not approved; run it again explicitly when the phone is ready.');+ } finally { process.off('SIGINT', stop); process.off('SIGTERM', stop); }+}diff --git a/src/relay-request-execution.js b/src/relay-request-execution.jsindex 7d23019e..79e7eaf3 100644--- a/src/relay-request-execution.js+++ b/src/relay-request-execution.js@@ -9,7 +9,7 @@ import { laneNames } from './lanes.js';import { refusalDocument } from './json.js';import { Refused } from './refused.js';import { relayLinked, relayOperation, relayRequestDevice } from './relay.js';-import { personRequestRecords } from './relay-requests.js';+import { personRequestRecords, requestIntentDigest, requestStageText } from './relay-requests.js';/** Read durable intake without retaining a SQLite connection while the CLI runs. */function requests(root) {@@ -25,13 +25,9 @@ function stageId(id, phase, executor) {/** Publish an ordinary person shout as a durable intake, coordinator request or refusal receipt. */async function receipt(root, record, executor, phase, io, error) {- const text = phase === 'claim' ? 'Received a request from the paired view.'- : phase === 'refuse' ? '[' + error.code + '] ' + error.message- : 'Apply the person’s recorded row decision with pullboard spec apply, or decline this request with a reason. '- + record.move.verb + ': ' + record.move.args.ids;- const message = { from: 'person', to: 'coordinator', text: 'View request ' + record.id + ': ' + text, lanes: laneNames(loadConfig(root)), ...(phase === 'repo-request' ? { request: true } : {}) };+ const message = { from: 'person', to: 'coordinator', text: requestStageText(record, phase, error), lanes: laneNames(loadConfig(root)), ...(phase === 'repo-request' ? { request: true } : {}) };return relayOperation(root, 'shout', [message], {- ...io, personRequest: { id: record.id, executor, phase, ...(error ? { error } : {}) },+ ...io, personRequest: { id: record.id, executor, phase, digest: requestIntentDigest(record), ...(error ? { error } : {}) },personRequestMoveId: phase === 'claim' && record.executor && record.executor !== executor ? randomUUID() : stageId(record.id, phase, executor),});}@@ -58,7 +54,7 @@ export async function executePersonRequests(root, io, runCommand) {if (!Object.hasOwn(record, 'result')) {const response = await executeMove(coordinatorRoot, record.move, (argv, streams) => runCommand(argv, {...streams, skipPersonRequests: true,- personRequest: { id: record.id, executor, phase: 'execute' },+ personRequest: { id: record.id, executor, phase: 'execute', digest: requestIntentDigest(record) },personRequestMoveId: stageId(record.id, 'execute', executor),}));if (response.status !== 200) {diff --git a/src/relay-requests.js b/src/relay-requests.jsindex b48f3acc..848b7100 100644--- a/src/relay-requests.js+++ b/src/relay-requests.js@@ -1,5 +1,6 @@/** Durable sealed request intake and ordinary-move receipts; no replica executes CLI intent [H12,H16]. */import * as store from './board.js';+import { createHash } from 'node:crypto';import { refusalDocument } from './json.js';import { Refused } from './refused.js';import { validatePersonRequest } from './person-request.js';@@ -7,6 +8,11 @@ import { relayMoveActor } from './relay-sender.js';const INDEX = 'relay_person_requests';+/** Bind each machine receipt to the exact earlier authenticated phone document. */+export function requestIntentDigest(record) {+ return createHash('sha256').update(record.encoded).digest('hex');+}+/** Read all durable request receipts so an offline browser can still resolve an old request. */export function personRequestRecords(board) {const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(INDEX);@@ -71,10 +77,17 @@ function fulfilsIntent(record, move) {const options = move.args[1];if (intent.verb === 'add') return value?.by === 'person' && value.lane === args.lane && value.title === args.title&& value.criterion === (args.criterion ?? '') && value.brief === (args.brief ?? '')- && value.route === (args.route ?? 'strong')+ && value.route === (args.route ?? 'strong') && (value.check ?? '') === (args.check ?? '')+ && (value.parentId ?? null) === (args.parent ? Number(args.parent.replace(/^#/, '')) : null)+ && JSON.stringify(value.after ?? []) === JSON.stringify((args.after ?? '').split(',').map(id => id.trim()).filter(Boolean).map(id => Number(id.replace(/^#/, ''))))+ && (!args.wait || !value.checkBaseline || value.checkBaseline.result !== 'pending')&& JSON.stringify(value.specIds) === JSON.stringify((args.specs ?? '').split(',').map(id => id.trim()).filter(Boolean));if (intent.verb === 'shout') return value?.from === 'person' && value.text === args.text- && (args.to === undefined || value.to === args.to) && Boolean(value.decision) === Boolean(args.decision);+ && value.to === (args.to ?? (args.decision ? 'person' : args.text)) && Boolean(value.decision) === Boolean(args.decision)+ && !value.request && value.answers == null+ && (args.evidence === undefined ? value.evidence == null : value.evidence?.kind === args.evidence+ && value.evidence.outcome === (args.outcome ?? '') && value.evidence.item === Number(args.item)+ && /^[0-9a-f]{40,64}$/u.test(args.commit ?? '') && value.evidence.commit === args.commit);if (intent.verb === 'answer') return value === intent.item && options?.asPerson === true && options.channel === 'view' && options.text === args.text;if (intent.verb === 'hold') return value === args.lane && options?.asPerson === true && options.channel === 'view'&& (args.off || options.reason === (args.reason ?? ''));@@ -87,30 +100,61 @@ function fulfilsIntent(record, move) {&& (args.text === undefined || row.text === args.text.trim()));}-/** Require an existing person intent and its first elected native executor before an ordinary move. */-export function requestMoveProblem(board, move) {+/** Keep receipt shouts fixed so a valid request cannot authorize unrelated person text or flags. */+export function requestStageText(record, phase) {+ const text = phase === 'claim' ? 'Received a request from the paired view.'+ : phase === 'refuse' ? 'Could not fulfil this request. Read its recorded refusal and next step.'+ : 'Apply the person’s recorded row decision with pullboard spec apply, or decline this request with a reason. '+ + record.move.verb + ': ' + record.move.args.ids;+ return 'View request ' + record.id + ': ' + text;+}++/** Match the receipt's entire effect, including the absence of decision, answer and evidence flags. */+function fulfilsStage(record, move, tag) {+ const value = move.args[0];+ return move.operation === 'shout' && move.args.length === 1 && value?.from === 'person' && value.to === 'coordinator'+ && value.text === requestStageText(record, tag.phase, tag.error) && !value.decision && value.answers == null && value.evidence == null+ && Boolean(value.request) === (tag.phase === 'repo-request')+ && (tag.phase !== 'repo-request' || ['spec-approve', 'spec-decline'].includes(record.move.verb))+ && Object.keys(value).every(key => ['from', 'to', 'text', 'lanes', 'request', 'decision', 'answers', 'evidence'].includes(key));+}++/** Bind a receipt to phone intent; executor takeover uses ordered relay time, not a local preflight clock. */+export function requestMoveProblem(board, move, { checkExecutorLease = true } = {}) {const tag = move.personRequest;if (!tag) return null;if (!tag || typeof tag !== 'object' || typeof tag.id !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(tag.id)- || Object.keys(tag).some(key => !['id', 'executor', 'phase', 'error'].includes(key)) || typeof tag.executor !== 'string'+ || Object.keys(tag).some(key => !['id', 'executor', 'phase', 'error', 'digest'].includes(key)) || typeof tag.executor !== 'string'|| !/^[A-Za-z0-9_-]{1,80}$/u.test(tag.executor) || !['claim', 'execute', 'repo-request', 'refuse'].includes(tag.phase)) {return new Refused('PERSON_REQUEST_RECEIPT', 'the request receipt is malformed; upgrade the linked machine before fulfilling requests');}const record = personRequestRecords(board).find(entry => entry.id === tag.id && !entry.duplicateOf);if (!record || record.status !== 'waiting') return new Refused('PERSON_REQUEST_CLOSED', 'this request is missing or already resolved; read its original receipt');+ if (move.engine >= 6) {+ let source;+ try { source = JSON.parse(record.received); } catch { /* Missing authenticated provenance refuses below. */ }+ const cursor = Number(board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('relay_applied_sequence')?.meta_value ?? 0);+ if (source?.sender?.kind !== 'person' || typeof source.sender.userId !== 'string' || !source.sender.userId ||+ JSON.stringify(source.document) !== record.encoded || JSON.stringify(source.document?.move) !== JSON.stringify(record.move) ||+ !Number.isSafeInteger(record.sequence) || record.sequence < 1 || record.sequence > cursor ||+ tag.digest !== requestIntentDigest(record)) return new Refused('PERSON_REQUEST_RECEIPT', 'match the exact earlier authenticated phone request and its payload digest');+ if ((tag.phase === 'execute' && Object.hasOwn(record, 'resultSequence')) ||+ (tag.phase === 'repo-request' && Object.hasOwn(record, 'coordinatorRequest'))) return new Refused('PERSON_REQUEST_CLOSED', 'this phone request already has its execution receipt; read the original result');+ }const actor = relayMoveActor(move);if (!['coordinator', 'person'].includes(actor)) return new Refused('PERSON_REQUEST_RECEIPT', 'only the coordinator fulfils an authenticated person request');if (tag.phase === 'execute') {const expected = { add: 'addItem', shout: 'shout', answer: 'answerDecision', hold: record.move.args.off ? 'releaseLane' : 'holdLane', 'spec-approve': 'recordRowDecisions', 'spec-decline': 'recordRowDecisions' }[record.move.verb];if (move.operation !== expected || !fulfilsIntent(record, move)) return new Refused('PERSON_REQUEST_RECEIPT', 'the ordinary move does not fulfil this request; execute its original CLI intent');}+ if (move.engine >= 6 && ['claim', 'repo-request', 'refuse'].includes(tag.phase) && !fulfilsStage(record, move, tag)) return new Refused('PERSON_REQUEST_RECEIPT', 'publish only the exact stage for this authenticated phone request');if (['claim', 'repo-request', 'refuse'].includes(tag.phase) && !(move.operation === 'shout' && move.args[0]?.from === 'person' && move.args[0]?.to === 'coordinator'&& move.args[0]?.text?.startsWith('View request ' + tag.id + ': '))) return new Refused('PERSON_REQUEST_RECEIPT', 'publish the original person request stage with its matching id');if (tag.phase === 'refuse' && !['code', 'message', 'next'].every(key => typeof tag.error?.[key] === 'string' && tag.error[key])) return new Refused('PERSON_REQUEST_RECEIPT', 'publish the original CLI refusal code, reason and next step');if (tag.phase === 'repo-request' && !(move.args[0]?.from === 'person' && move.args[0]?.to === 'coordinator' && move.args[0]?.request)) return new Refused('PERSON_REQUEST_RECEIPT', 'repo changes must reach the coordinator as a person request');if (tag.phase === 'claim') {if (move.operation !== 'shout') return new Refused('PERSON_REQUEST_RECEIPT', 'claim a request with its ordinary coordinator receipt');- if (record.executor && record.executor !== tag.executor && Date.parse(record.executorUntil ?? record.at) > board.clock.now().getTime()) return new Refused('PERSON_REQUEST_TAKEN', 'another linked machine is fulfilling this request; wait for its receipt');+ if (checkExecutorLease && record.executor && record.executor !== tag.executor && Date.parse(record.executorUntil ?? record.at) > board.clock.now().getTime()) return new Refused('PERSON_REQUEST_TAKEN', 'another linked machine is fulfilling this request; wait for its receipt');} else if (record.executor !== tag.executor) {return new Refused('PERSON_REQUEST_TAKEN', 'this linked machine did not win the request; wait for its original receipt');}diff --git a/src/relay-sender.js b/src/relay-sender.jsindex b06d6814..bf4bd2ea 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -16,15 +16,23 @@ export function relayMoveActor(move) {}/** Make the same authorization decision on every device, without inspecting its shell or checkout. */-export function relaySenderProblem(move, sender, kind) {- if (!sender || !['person', 'agent'].includes(sender.kind) || typeof sender.userId !== 'string' || !sender.userId.length || sender.userId.length > 256 ||- (sender.kind === 'agent' && (typeof sender.agent !== 'string' || !sender.agent.length || sender.agent.length > 256))) {+export function relaySenderProblem(move, sender, kind, { phoneReceipt = false } = {}) {+ if (!sender || !['person', 'agent', 'machine'].includes(sender.kind) || typeof sender.userId !== 'string' || !sender.userId.length || sender.userId.length > 256 ||+ (sender.kind === 'agent' && (typeof sender.agent !== 'string' || !sender.agent.length || sender.agent.length > 256)) ||+ (sender.kind === 'machine' && (typeof sender.machine !== 'string' || !sender.machine.length || sender.machine.length > 256))) {return new Refused('RELAY_SENDER', 'this relay record has no authenticated sender; restore attribution before replaying it');}if (move?.operation === 'shout' && move.args?.[0]?.answers != null) {return new Refused('RELAY_ANSWER', 'a sealed shout cannot answer or pass a decision; use pullboard answer <id> "<answer>" or pullboard pass <id> --note "<reason>" so the decision rules are checked');}if (sender.kind === 'person') return null;+ if (sender.kind === 'machine') {+ if (kind === 'snapshot') return null;+ if (kind === 'move' && move?.engine >= 6 && (phoneReceipt ||+ move.operation === 'register' && typeof move.args?.[0]?.lane === 'string' && move.args[0].lane !== 'person' ||+ move.operation === 'ensureCoordinator' && typeof move.args?.[0] === 'string')) return null;+ return new Refused('RELAY_PERSON_ONLY', 'a machine cannot act as the person; approve this action on the paired phone');+ }if (kind === 'snapshot' || move?.operation === 'recordRowDecisions' || move?.operation === 'answerDecision' && move.args?.[1]?.asPerson ||move?.operation === 'shout' && move.args?.[0]?.request || relayMoveActor(move) === 'person') {return new Refused('RELAY_PERSON_ONLY', `agent ${sender.agent} cannot make a person-only relay ${kind}; use the person's authenticated session`);diff --git a/src/relay-setup.js b/src/relay-setup.jsindex b522380b..dd2c3b38 100644--- a/src/relay-setup.js+++ b/src/relay-setup.js@@ -1,8 +1,13 @@/** Set up a machine once, enroll its phone in the foreground and link later registrations [H5,H17]. */+import { join } from 'node:path';+import * as store from './board.js';+import { phoneProposal } from './relay-phone.js';+import { openApproval, restoreLinkReply } from './relay-approval.js';+import { requirePersonChannel } from './person.js';import { repoInfo } from './git.js';import { listApiProjects } from './projects.js';-import { acceptDeviceEnrollment, beginDeviceEnrollment, readRelayMachine, removeRecordedDevice, updateRelayMachine } from './relay-machine.js';-import { deliverDeviceWraps, relayDeviceRequest, relayMachineSignIn, relayOn, relayOrigin, relayStatus } from './relay.js';+import { acceptDeviceEnrollment, beginDeviceEnrollment, readRelayMachine, updateRelayMachine } from './relay-machine.js';+import { deliverDeviceWraps, relayDeviceRequest, relayMachineSignIn, relayMachineContext, relayRevokeDevice, relayOn, relayStatus, originRepository } from './relay.js';import { terminalQr } from './qr.js';import { Refused } from './refused.js';@@ -12,42 +17,84 @@ export function unlinkedRelayProjects() {if (!machine.autoLink) return [];return listApiProjects().filter(project => !machine.excluded.includes(project.root)).flatMap(project => {try { if (relayStatus(project.root).linked) return []; } catch { /* Preserve the registered project as a named finding. */ }- return [{ code: 'RELAY_NOT_LINKED', message: `not linked: ${project.name} (sign in again: pullboard relay on --all)`, next: 'pullboard relay on --all' }];+ const pending = machine.approvals.find(entry => entry.root === project.root);+ return [{ code: pending ? 'PHONE_APPROVAL_PENDING' : 'RELAY_NOT_LINKED', message: pending ? 'waiting for phone approval: ' + project.name + '; expires ' + new Date(pending.context.expires).toISOString() : 'not linked: ' + project.name + '; run pullboard relay on --all', next: pending && Date.now() < pending.context.expires ? 'Approve the named link on your paired phone.' : 'pullboard relay on --all' }];});}-/** Link one registered project through the previously authorized machine session, with no prompt. */+/** Read the registered local board identity without executing any person action. */+function projectBoard(root) {+ const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'));+ try { return store.boardId(board); } finally { store.closeBoard(board); }+}++/** Link a new project only after the paired phone explicitly approves its one durable proposal. */export async function autoLinkProject(root, io) {const machine = readRelayMachine();if (!machine.autoLink) return;const project = repoInfo(root).root;- if (machine.excluded.includes(project)) return;+ if (machine.excluded.includes(project) || relayStatus(project).linked) return;const name = listApiProjects().find(entry => entry.root === project)?.name ?? project;try {- if (!machine.session) throw new Refused('RELAY_SESSION', 'sign in again: pullboard relay on --all');- await relayOn(project, machine.session.url, io, { session: machine.session, quiet: true, strict: true });+ let pending = machine.approvals.find(entry => entry.root === project);+ if (pending && Date.now() >= pending.context.expires) throw new Refused('PHONE_APPROVAL_EXPIRED', 'Link approval expired; run pullboard relay on --all explicitly to link this project.');+ let source;+ if (pending) source = relayMachineContext(pending.publisherRoot);+ else {+ const candidate = listApiProjects().map(entry => ({ ...entry, state: relayMachineContext(entry.root) }))+ .find(entry => entry.state?.token?.startsWith('pm_') && entry.state.account === machine.owner?.account && entry.state.url === machine.owner?.url);+ if (!candidate) throw new Refused('RELAY_SESSION', 'Run pullboard relay on --all to link this project and pair the phone.');+ source = candidate.state;+ const proposal = await phoneProposal(source, 'link', originRepository(project),+ { board: projectBoard(project), command: 'Link ' + name + '? (pullboard init)', link: true });+ const value = { root: project, publisherRoot: candidate.root, context: proposal.context, sealed: proposal.sealed, replyKey: proposal.reply.storedKey, published: false };+ pending = updateRelayMachine(state => {+ const existing = state.approvals.find(entry => entry.root === project);+ if (existing) return existing;+ state.approvals.push(value); return value;+ });+ source = relayMachineContext(pending.publisherRoot);+ }+ if (!source?.token?.startsWith('pm_')) throw new Refused('RELAY_SESSION', 'Restore the publishing board link or run pullboard relay on --all.');+ if (!pending.published) {+ await relayDeviceRequest(source, '/api/v1/devices/approvals', { method: 'POST', body: { context: pending.context, sealed: pending.sealed } }, io);+ updateRelayMachine(state => { const entry = state.approvals.find(value => value.context.id === pending.context.id); if (entry) entry.published = true; });+ }+ const document = await relayDeviceRequest(source, '/api/v1/devices/approvals/' + pending.context.id, {}, io);+ if (document.approval.state !== 'approved') {+ io.err('waiting for phone approval: ' + name + '; expires ' + new Date(pending.context.expires).toISOString() + '; local work continues.'); return;+ }+ const privateKey = await restoreLinkReply(pending.replyKey);+ const result = await openApproval(privateKey, JSON.parse(Buffer.from(document.approval.response, 'base64url').toString('utf8')), pending.context, 'reply');+ const credential = { ...result.credential, account: pending.context.account, url: source.url };+ await relayOn(project, source.url, io, { credential, quiet: true, strict: true });+ updateRelayMachine(state => { state.approvals = state.approvals.filter(entry => entry.context.id !== pending.context.id); });} catch (error) {- io.err(`not linked: ${name} (sign in again: pullboard relay on --all); ${error instanceof Refused ? error.message : 'restore the registered project and retry'}`);+ io.err('not linked: ' + name + '; ' + (error instanceof Refused ? error.message : 'Restore the pending phone approval or run pullboard relay on --all.'));}}-/** Retry durable revocation intents using only the corresponding saved account session. */-async function flushRevocations(io) {- const machine = readRelayMachine();- for (const intent of machine.revocations) {- if (!machine.session || machine.session.account !== intent.account || machine.session.url !== intent.url) {- throw new Refused('RELAY_SESSION', 'Sign in to the paired account with pullboard relay on --all to finish device revocation.');- }- await relayDeviceRequest(machine.session, '/api/v1/devices/' + intent.deviceId, { method: 'DELETE' }, io);+/** Retry only old deletion intents during an explicit foreground sign-in; never retain that session. */+async function flushRevocations(session, io) {+ for (const intent of readRelayMachine().revocations) {+ if (session.account !== intent.account || session.url !== intent.url) continue;+ await relayDeviceRequest(session, '/api/v1/devices/' + intent.deviceId, { method: 'DELETE' }, io);updateRelayMachine(state => { state.revocations = state.revocations.filter(entry => entry.deviceId !== intent.deviceId); });}}-/** Revoke locally first; a remote outage leaves a durable deletion intent instead of future wraps. */+/** The native device revocation uses the same one-tap grant path as token revocation. */export async function revokeRelayDevice(deviceId, io) {- removeRecordedDevice(deviceId);- await flushRevocations(io);- return { deviceId, revoked: true, notice: 'Revoked device; keys it already received remain known. Board key rotation is separate.' };+ requirePersonChannel(io.personChannel);+ const device = readRelayMachine().devices.find(entry => entry.deviceId === deviceId);+ if (!device) throw new Refused('DEVICE_NOT_ENROLLED', 'Name a paired device from pullboard relay devices.');+ const roots = [io.cwd, ...listApiProjects().map(entry => entry.root)];+ for (const root of roots) {+ let state;+ try { state = relayMachineContext(root); } catch { continue; }+ if (state?.token?.startsWith('pm_') && state.account === device.account && state.url === device.url) return relayRevokeDevice(root, deviceId, io);+ }+ throw new Refused('RELAY_NOT_LINKED', 'Link a board and pair the phone with pullboard relay on --all.');}/** Link every non-excluded registry entry, collecting project-specific partial failures. */@@ -108,21 +155,15 @@ async function pairFirstDevice(session, board, linked, io) {}}-/** Save the account session once, link all projects and only wait when this Mac has no paired phone. */+/** Explicit foreground sign-in repairs links; only board machine credentials survive this command. */export async function relayOnAll(address, io) {+ requirePersonChannel(io.personChannel);const prior = readRelayMachine();- let session = prior.session;- const requestedOrigin = address ? relayOrigin(address) : undefined;- if (requestedOrigin && session?.url !== requestedOrigin) session = null;- if (session) {- try {- const identity = await relayDeviceRequest(session, '/api/v1/devices/session', {}, io);- if (identity.account !== session.account) throw new Refused('RELAY_SESSION', 'Sign in again to this account.');- } catch (error) { if (error.code !== 'AUTH_REQUIRED') throw error; session = null; }- }- session ??= await relayMachineSignIn(address || prior.session?.url, io);- updateRelayMachine(state => { state.autoLink = true; state.session = session; });- await flushRevocations(io);+ // Scrub every registered legacy link before asking for or using fresh person authority.+ for (const project of listApiProjects()) { try { relayMachineContext(project.root); } catch { /* linkProjects reports invalid projects. */ } }+ const session = await relayMachineSignIn(address || prior.owner?.url, io);+ updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = []; });+ await flushRevocations(session, io);const result = await linkProjects(session, io);const devices = readRelayMachine().devices.filter(device => device.account === session.account && device.url === session.url);const pairing = devices.length || !result.linked.length ? { paired: devices.length > 0 }diff --git a/src/relay.js b/src/relay.jsindex 06abfcfd..a99df418 100644--- a/src/relay.js+++ b/src/relay.js@@ -1,6 +1,6 @@/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H5,H16,H17,P5]. */import { randomUUID } from 'node:crypto';-import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { gunzipSync, gzipSync } from 'node:zlib';import * as store from './board.js';@@ -15,8 +15,11 @@ import { encodeBoardKey, generateBoardKey, seal, unseal } from './seal.js';import { terminalQr } from './qr.js';import { Refused } from './refused.js';import { relaySenderProblem } from './relay-sender.js';-import { readRelayMachine, updateRelayMachine, wrapForRecordedDevice } from './relay-machine.js';-import { receivePersonRequest } from './relay-requests.js';+import { readRelayMachine, removeRecordedDevice, updateRelayMachine, wrapForRecordedDevice } from './relay-machine.js';+import { receivePersonRequest, requestMoveProblem } from './relay-requests.js';+import { nativePhoneAction, phoneProposal } from './relay-phone.js';+import { requirePersonChannel } from './person.js';+import { listApiProjects } from './projects.js';export const DEFAULT_RELAY = 'https://app.pullboard.dev';const SEALED_SNAPSHOT_LIMIT = 10_000_000;@@ -72,11 +75,17 @@ function loadLink(file) {if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_STORAGE', 'restore relay.json as an owner-only regular file with mode 600');let state;try { state = JSON.parse(readFileSync(file, 'utf8')); } catch { throw new Refused('RELAY_STORAGE', 'restore valid relay link metadata before syncing this board'); }- if (!state || typeof state !== 'object' || state.version !== 1 || !/^[0-9a-f]{32}$/.test(state.board) || !/^(ps_|pa_)[A-Za-z0-9_-]{43}$/.test(state.token) ||+ if (!state || typeof state !== 'object' || state.version !== 1 || !/^[0-9a-f]{32}$/.test(state.board) || !(state.token === undefined || state.personReauth && state.token === null || /^(ps_|pa_|pm_)[A-Za-z0-9_-]{43}$/.test(state.token)) ||!Number.isSafeInteger(state.sequence) || state.sequence < 0 || !Number.isSafeInteger(state.cursor) || state.cursor < 0) {throw new Refused('RELAY_STORAGE', 'restore supported relay link metadata before syncing this board');}relayOrigin(state.url);+ if (state.token === undefined || state.token?.startsWith('ps_')) {+ state.token = null;+ delete state.tokenId;+ state.personReauth = true;+ saveLink(file, state);+ }return state;}@@ -112,7 +121,13 @@ async function locked(file, work) {await new Promise((resolve) => setTimeout(resolve, 100));}}- try { return await work(); } finally { rmSync(lock, { recursive: true, force: true }); }+ try {+ // Only the current lock holder can have a live link write; remove crashed legacy bearer fragments.+ for (const name of readdirSync(dirname(file))) {+ if (/^relay\.json\.[0-9a-f-]+\.tmp$/u.test(name)) rmSync(join(dirname(file), name), { force: true });+ }+ return await work();+ } finally { rmSync(lock, { recursive: true, force: true }); }}/** Surface retention notices on the very command that receives them, without exposing credentials. */@@ -212,7 +227,7 @@ export function formatSnapshotLimit(problem, { paused = false } = {}) {function safePauseMessage(error) {const message = String(error.relayMessage ?? error.message ?? 'the relay refused the baseline upload').replace(/https?:\/\/[^\s]+/gu, '[relay]')- .replace(/\b(?:Bearer\s+)?(?:ps|pa)_[A-Za-z0-9_-]{20,}\b/gu, '[credential]')+ .replace(/\b(?:Bearer\s+)?(?:ps|pa|pm|pg)_[A-Za-z0-9_-]{20,}\b/gu, '[credential]').replace(/[\r\n\t\x00-\x1f\x7f]+/gu, ' ').replace(/\s+/gu, ' ').trim();return message.slice(0, 240) || 'the relay refused the baseline upload';@@ -513,7 +528,7 @@ async function decoded(key, record, state, kind, sequence) {/** Persist the exact checkpoint before uploading, so a lost reply retries identical ciphertext. */async function publishCheckpoint(root, file, state, io) {- if (!state.token.startsWith('ps_') || process.env.PULLBOARD_RELAY_TOKEN) return;+ if (!state.token?.startsWith('pm_') || process.env.PULLBOARD_RELAY_TOKEN) return;const document = relaySnapshot(root);const sequence = Number(document.tables.board_meta.find((row) => row.meta_key === 'relay_applied_sequence')?.meta_value ?? 0);const digest = presentationDigest(document.presentation);@@ -620,17 +635,26 @@ async function catchUp(root, file, state, io) {if (localRecords(root, appliedSequence) <= after) throw new Refused('RELAY_RESPONSE', 'the relay checkpoint did not advance the missing prefix; fetch a consistent newer snapshot');return catchUp(root, file, state, io);}- if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string' || !record.sender || !['person', 'agent'].includes(record.sender.kind) || typeof record.sender.userId !== 'string' || (record.sender.kind === 'agent' && typeof record.sender.agent !== 'string'))) {+ if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string' || !record.sender || !['person', 'agent', 'machine'].includes(record.sender.kind) || typeof record.sender.userId !== 'string' || (record.sender.kind === 'agent' && typeof record.sender.agent !== 'string') || (record.sender.kind === 'machine' && typeof record.sender.machine !== 'string'))) {throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid ordered prefix; fetch a consistent relay snapshot');}+ let pendingRefusal;for (const record of remote.events) {const move = await decoded(key, record, state, record.kind, record.event_id);// Legacy executable documents in the request channel still fail closed before attribution.if (record.kind === 'request' && move?.engine !== undefined) requireSupportedEngine(move);- localRecords(root, (board) => {- if (record.kind === 'request') receivePersonRequest(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender });- else applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind });+ const outcome = localRecords(root, (board) => {+ if (record.kind === 'request') return receivePersonRequest(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender });+ else return applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind });});+ // Sender refusals have a sequence receipt, not an executable-ID receipt: never resend them.+ if (record.kind === 'move' && state.pending?.move && record.event_id === state.pending.sequence+ && record.sealed === state.pending.sealed && JSON.stringify(move) === JSON.stringify(state.pending.move)+ && outcome?.error && !localRecords(root, board => engineReceipt(board, move.id))) {+ pendingRefusal = outcome.error;+ delete state.pending;+ delete state.recovered;+ }}state.sequence = localRecords(root, appliedSequence);if (state.pending?.move && localRecords(root, (board) => engineReceipt(board, state.pending.move.id))) {@@ -638,6 +662,7 @@ async function catchUp(root, file, state, io) {delete state.pending;}saveLink(file, state);+ if (pendingRefusal) throw new Refused(pendingRefusal.code, pendingRefusal.message);}/** Finish a durable executable send; a collision reseals its unchanged id after applying the winner. */@@ -666,7 +691,8 @@ async function sendPending(root, file, state, io) {/** Choose credentials only; main's relay sender policy remains the sole replay authorization. */function credentialActor(move) {const args = move.args;- if (move.personRequest || ['register', 'ensureCoordinator', 'recordRowDecisions'].includes(move.operation)+ if (move.personRequest || ['register', 'ensureCoordinator'].includes(move.operation)) return 'machine';+ if (move.operation === 'recordRowDecisions'|| move.operation === 'answerDecision' && args[1]?.asPerson|| move.operation === 'shout' && args[0]?.request) return 'person';return relayMoveActor(move);@@ -678,7 +704,10 @@ async function actorTransport(root, file, state, actor, io) {throw new Refused('RELAY_ACTOR', 'name the registered agent performing this move before sending it');}if (actor === 'person') {- if (!state.token.startsWith('ps_')) throw new Refused('HUMAN_REQUIRED', 'sign in as a person to enroll an agent or answer as the person');+ throw new Refused('HUMAN_REQUIRED', 'send this person action from the paired phone');+ }+ if (actor === 'machine') {+ if (!state.token?.startsWith('pm_')) throw new Refused('HUMAN_REQUIRED', 'run pullboard relay on --all to authorize this board’s machine credential');return state;}const supplied = process.env.PULLBOARD_RELAY_TOKEN;@@ -689,7 +718,7 @@ async function actorTransport(root, file, state, actor, io) {if (identity.session?.kind !== 'board' || identity.session.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');return transport;}- if (state.token.startsWith('pa_')) {+ if (state.token?.startsWith('pa_')) {const identity = await request(state, '/auth/session?board=' + state.board, {}, io);if (identity.session?.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');return { ...state, agent: actor };@@ -782,6 +811,8 @@ export async function relayOperation(root, operation, args, io, command, applyLoif (!move) {move = localRecords(root, (board) => prepareEngineMove(board, operation, args, io.personRequestMoveId ? { id: io.personRequestMoveId } : {}));if (io.personRequest) move.personRequest = structuredClone(io.personRequest);+ const problem = move.personRequest && localRecords(root, board => requestMoveProblem(board, move, { checkExecutorLease: false }));+ if (problem) throw problem;move.actor = relayMoveActor(move) ?? credentialActor(move);await actorTransport(root, file, state, credentialActor(move), io);const sequence = state.sequence + 1;@@ -855,14 +886,14 @@ function tokenContext(state) {return { linked: true, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0 };}-/** Require the signed-in person's existing link before listing or revoking scoped agent credentials. */+/** Require the existing board delegate before listing metadata or requesting an approved revocation. */function managementLink(file) {const state = loadLink(file);if (!state || state.unlinking) throw new Refused('RELAY_OFF', 'link this board with pullboard relay on before managing its agent tokens');return state;}-/** List only this person's current board-token metadata, never bearer values or the board key. */+/** List only this board’s agent-token metadata, never bearer values or the board key. */export async function relayTokens(root, io) {const file = linkFile(root);return locked(file, async () => {@@ -880,6 +911,7 @@ export async function relayTokens(root, io) {/** Revoke one credential listed on this board while retaining its cache so it cannot be silently reminted. */export async function relayRevoke(root, id, io) {+ requirePersonChannel(io.personChannel);if (typeof id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) {throw new Refused('TOKEN_NOT_OWNED', 'name an opaque token id from pullboard relay tokens, never a credential value');}@@ -890,7 +922,7 @@ export async function relayRevoke(root, id, io) {if (!Array.isArray(listed.tokens) || !listed.tokens.some((row) => row.id === id)) {throw new Refused('TOKEN_NOT_OWNED', 'choose a token listed on this board by pullboard relay tokens');}- const result = await request(state, '/auth/tokens/revoke', { method: 'POST', body: { id } }, io);+ const result = await nativePhoneAction(state, 'revoke-token', id, io, request);if (result.id !== id || result.revoked !== true) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge this token revocation; retry its opaque id');for (const credential of Object.values(state.agentTokens ?? {})) if (credential.id === id) credential.revoked = true;saveLink(file, state);@@ -962,7 +994,10 @@ async function deviceSignIn(url, io) {}/** Explicitly sign in through the relay and persist a sealed initial snapshot before uploading it. */-export async function relayOn(root, address, io, { session, quiet = false, strict = false } = {}) {+export async function relayOn(root, address, io, { session, credential, quiet = false, strict = false } = {}) {+ if (!credential) requirePersonChannel(io.personChannel);+ readRelayMachine();+ for (const project of listApiProjects()) { try { loadLink(linkFile(project.root)); } catch { /* Report this command's own link below. */ } }const repository = originRepository(root);const file = linkFile(root);return locked(file, async () => {@@ -972,7 +1007,7 @@ export async function relayOn(root, address, io, { session, quiet = false, stricconst url = relayOrigin(address || state?.url || DEFAULT_RELAY);if (state && (state.url !== url || state.repository !== repository)) throw new Refused('RELAY_LINKED', 'this board is linked to another relay or repository; run relay off before changing its link');const key = state ? readBoardKey(state.board) : await generateBoardKey();- const signed = session ?? await deviceSignIn(url, io);+ const signed = credential ?? session ?? await deviceSignIn(url, io);if (session && session.url !== url) throw new Refused('RELAY_SESSION', 'Sign in again to this relay with pullboard relay on --all.');if (!state) {const snapshot = localRecords(root, (board) => {@@ -982,20 +1017,28 @@ export async function relayOn(root, address, io, { session, quiet = false, stricsnapshot.document = relaySnapshot(root);// Save the device key before creating any remote link; a locked keychain cannot strand it.const keyStorage = storeBoardKey(snapshot.board, key);- state = { version: 1, mode: 'ordered', board: snapshot.board, url, repository, token: signed.token,- tokenId: signed.id, keyStorage, presentationDigest: presentationDigest(snapshot.document.presentation), sequence: 0,+ state = { version: 1, mode: 'ordered', board: snapshot.board, url, repository, token: null, personReauth: true,+ keyStorage, presentationDigest: presentationDigest(snapshot.document.presentation), sequence: 0,cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, baselineCursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0,baselineAccepted: false, linkPending: true };state.snapshot = { sequence: 0, sealed: await sealedRecord(key, snapshot.document, state, 'snapshot', 0) };- } else { state.token = signed.token; state.tokenId = signed.id; }+ }state.account = signed.account ?? signed.user?.id;// Persist the exact sealed snapshot and a recoverable link intent before making the remote link.saveLink(file, state);if (state.linkPending) {- await request(state, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository } }, io);+ if (!credential) await request({ ...state, token: signed.token }, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository } }, io);delete state.linkPending;saveLink(file, state);}+ const machine = updateRelayMachine(settings => settings.machine);+ const issued = credential ?? await request({ ...state, token: signed.token }, '/auth/machines', { method: 'POST', body: { board: state.board, machine } }, io);+ if (!/^pm_[A-Za-z0-9_-]{43}$/u.test(issued.token ?? '') || issued.board !== state.board || issued.machine !== machine) throw new Refused('RELAY_RESPONSE', 'the relay did not issue this board’s machine credential; sign in again');+ state.token = issued.token;+ state.tokenId = issued.id;+ state.machine = machine;+ delete state.personReauth;+ saveLink(file, state);let result;try {let ready = true;@@ -1022,23 +1065,29 @@ export async function relayOn(root, address, io, { session, quiet = false, stric});}-/** Remove the remote board and its link before forgetting this device's private key and metadata. */+/** Unlink locally without approval, then request a separate phone-approved remote deletion if possible. */export async function relayOff(root, io) {updateRelayMachine(machine => { const project = repoInfo(root).root; if (!machine.excluded.includes(project)) machine.excluded.push(project); });const file = linkFile(root);return locked(file, async () => {const state = loadLink(file);if (!state) return summary(root, null);- if (!state.unlinking) {- const deleted = await request(state, '/api/v1/boards/' + state.board, { method: 'DELETE', allowMissing: true }, io);- if (deleted.alreadyDeleted) state.alreadyDeleted = true;- state.unlinking = true;- saveLink(file, state);- }- forgetBoardKey(state.board, state.keyStorage);+ // Local unlink always completes, including agent shells, outages and a fenced remote baseline.+ let proposal;+ try { proposal = await phoneProposal(state, 'delete-board', state.board); }+ catch { /* Missing key or pairing cannot stop local unlinking. */ }rmSync(file, { force: true });+ try { forgetBoardKey(state.board, state.keyStorage); }+ catch { /* The local opt-out is complete even when secure key storage is temporarily locked. */ }+ let requested = false;+ try {+ if (!proposal) throw new Refused('PHONE_NOT_PAIRED', 'Manage the relay copy from your phone.');+ const { context, sealed } = proposal;+ await request(state, '/api/v1/devices/approvals', { method: 'POST', body: { context, sealed } }, io);+ requested = true;+ } catch { /* The local link is already gone; no outage may undo local unlinking. */ }return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0,- ...(state.alreadyDeleted ? { alreadyDeleted: true, notice: 'the relay had already deleted this board; this device is unlinked and the local board is complete' } : {}) };+ notice: 'Local link removed. The relay copy stays until you approve deleting it on your phone.' + (requested ? '' : ' Open the phone to manage the relay copy.') };});}@@ -1057,6 +1106,7 @@ export async function relayRequestDevice(root) {/** Sign in once for machine setup; the saved account is the provider-authenticated identity. */export async function relayMachineSignIn(address, io) {+ requirePersonChannel(io.personChannel);const url = relayOrigin(address || DEFAULT_RELAY);const signed = await deviceSignIn(url, io);if (typeof signed.user?.id !== 'string') throw new Refused('RELAY_RESPONSE', 'Sign in again to receive an authenticated account identity.');@@ -1079,8 +1129,20 @@ export async function deliverDeviceWraps(root, io) {for (const device of devices) {const context = { board: state.board, device: device.deviceId, engine: ENGINE_VERSION };const wrapped = await wrapForRecordedDevice(key, context, state);- await relayDeviceRequest(state, '/api/v1/devices/' + device.deviceId, { method: 'POST', body: {} }, io);await relayDeviceRequest(state, '/api/v1/devices/' + device.deviceId + '/boards/' + state.board,{ method: 'PUT', body: { engine: ENGINE_VERSION, wrapped: Buffer.from(JSON.stringify(wrapped)).toString('base64url') } }, io);}}++/** Expose board-scoped machine context only to the native setup/approval adapter. */+export function relayMachineContext(root) { return loadLink(linkFile(root)); }++/** Require one exact phone approval before revoking and removing a device from the trusted roster. */+export async function relayRevokeDevice(root, deviceId, io) {+ requirePersonChannel(io.personChannel);+ const state = managementLink(linkFile(root));+ const result = await nativePhoneAction(state, 'revoke-device', deviceId, io, request);+ removeRecordedDevice(deviceId);+ updateRelayMachine(machine => { machine.revocations = machine.revocations.filter(entry => entry.deviceId !== deviceId); });+ return { ...result, notice: 'Revoked device; keys it already received remain known. Board key rotation is separate.' };+}diff --git a/test/person-request-receipts.test.js b/test/person-request-receipts.test.jsindex 06f60a04..e1d7c71e 100644--- a/test/person-request-receipts.test.js+++ b/test/person-request-receipts.test.js@@ -11,7 +11,7 @@ import { refusalDocument } from '../src/json.js';import { ENGINE_VERSION } from '../src/machine.js';import { preparePersonRequest } from '../src/person-request.js';import { Refused } from '../src/refused.js';-import { personRequestRecords, personRequestStatuses, receivePersonRequest } from '../src/relay-requests.js';+import { personRequestRecords, personRequestStatuses, receivePersonRequest, requestIntentDigest, requestStageText } from '../src/relay-requests.js';const at = '2026-10-08T12:34:56.000Z';const person = { kind: 'person', userId: 'github-person-1' };@@ -42,7 +42,8 @@ function claimMove(board, id, executor, moveId = 'claim-stage') {const move = prepareEngineMove(board, 'shout', [{from: 'person', to: 'coordinator', text: 'View request ' + id + ': Received a request from the paired view.', lanes: [],}], { id: moveId });- move.personRequest = { id, executor, phase: 'claim' };+ const record = personRequestRecords(board).find(entry => entry.id === id && !entry.duplicateOf);+ move.personRequest = { id, executor, phase: 'claim', digest: requestIntentDigest(record) };return move;}@@ -93,6 +94,7 @@ test('[H12,H16] elected executor commits one ordinary engine move and replay retconst board = box.board;const document = preparePersonRequest({ verb: 'shout', args: { to: 'coordinator', text: 'Please review this' } }, 'shout-1');receivePersonRequest(board, document, { sequence: 1, at, sender: person });+ const digest = requestIntentDigest(personRequestRecords(board).find(record => record.id === document.id));const claim = claimMove(board, document.id, 'device-a');assert.equal(claim.engine, ENGINE_VERSION);@@ -101,14 +103,14 @@ test('[H12,H16] elected executor commits one ordinary engine move and replay retassert.equal(personRequestRecords(board)[0].executor, 'device-a');const badId = prepareEngineMove(board, 'shout', [{ from: 'person', to: 'coordinator', text: 'wrong request', lanes: [] }], { id: 'bad-request-id' });- badId.personRequest = { id: 'missing-request', executor: 'device-a', phase: 'execute' };+ badId.personRequest = { id: 'missing-request', executor: 'device-a', phase: 'execute', digest };assert.equal(applyEngineMove(board, badId, { sequence: 3, at }).error?.code, 'PERSON_REQUEST_CLOSED');const wrongOperation = prepareEngineMove(board, 'addItem', [{ by: 'person', lane: 'web', title: 'Wrong action' }], { id: 'wrong-operation' });- wrongOperation.personRequest = { id: document.id, executor: 'device-a', phase: 'execute' };+ wrongOperation.personRequest = { id: document.id, executor: 'device-a', phase: 'execute', digest };assert.equal(applyEngineMove(board, wrongOperation, { sequence: 4, at }).error?.code, 'PERSON_REQUEST_RECEIPT');const wrongArguments = prepareEngineMove(board, 'shout', [{ from: 'person', to: 'coordinator', text: 'A different question', lanes: [] }], { id: 'wrong-arguments' });- wrongArguments.personRequest = { id: document.id, executor: 'device-a', phase: 'execute' };+ wrongArguments.personRequest = { id: document.id, executor: 'device-a', phase: 'execute', digest };assert.equal(applyEngineMove(board, wrongArguments, { sequence: 5, at }).error?.code, 'PERSON_REQUEST_RECEIPT', 'an ordinary move must fulfil the exact queued intent');const losingClaim = claimMove(board, document.id, 'device-b', 'claim-stage-other');@@ -119,7 +121,7 @@ test('[H12,H16] elected executor commits one ordinary engine move and replay retconst execution = prepareEngineMove(board, 'shout', [{from: 'person', to: 'coordinator', text: 'Please review this', lanes: [],}], { id: 'execute-shout-1' });- execution.personRequest = { id: document.id, executor: 'device-a', phase: 'execute' };+ execution.personRequest = { id: document.id, executor: 'device-a', phase: 'execute', digest };assert.equal(execution.engine, ENGINE_VERSION);const result = applyEngineMove(board, execution, { sequence: 7, at });assert.ok(result.result);@@ -147,9 +149,9 @@ test('[H12,H16] native CLI refusal fields remain attached to the durable requestconst cliError = refusalDocument(new Refused('UNKNOWN_SPEC', 'G999 is not in SPEC.md')).error;const refusal = prepareEngineMove(board, 'shout', [{- from: 'person', to: 'coordinator', text: `View request ${document.id}: [${cliError.code}] ${cliError.message}`, lanes: [],+ from: 'person', to: 'coordinator', text: requestStageText(personRequestRecords(board).find(record => record.id === document.id), 'refuse'), lanes: [],}], { id: 'refusal-stage' });- refusal.personRequest = { id: document.id, executor: 'device-a', phase: 'refuse', error: cliError };+ refusal.personRequest = { id: document.id, executor: 'device-a', phase: 'refuse', digest: requestIntentDigest(personRequestRecords(board).find(record => record.id === document.id)), error: cliError };assert.equal(refusal.engine, ENGINE_VERSION);const outcome = applyEngineMove(board, refusal, { sequence: 3, at });assert.ok(outcome.result);diff --git a/test/relay-agent.test.js b/test/relay-agent.test.jsindex c8fd55f3..fc60f916 100644--- a/test/relay-agent.test.js+++ b/test/relay-agent.test.js@@ -15,6 +15,8 @@ import { decodeBoardKey, unseal } from '../src/seal.js';import { frozenCriterion, parseSpec } from '../src/spec.js';import { relayClientFixture } from './relay-client-fixture.js';import { fetchFresh } from './http-fixture.js';+import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';/** Invoke one real CLI command without retaining stderr or exposing private command output. */function runCli(root, env, cli, args) {@@ -34,6 +36,62 @@ function runCli(root, env, cli, args) {});}+/** Run a foreground private CLI command while another actor completes its phone approval. */+function startCli(root, env, cli, args) {+ const child = spawn(process.execPath, [cli, ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ const timer = setTimeout(() => child.kill('SIGKILL'), 90000);+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });+ child.stderr.resume();+ const done = new Promise((resolveResult, reject) => {+ child.once('error', error => { clearTimeout(timer); reject(error); });+ child.once('close', (code, signal) => {+ clearTimeout(timer);+ if (signal) return reject(new Error('private phone-approved command ended with a signal'));+ try { resolveResult({ code, document: JSON.parse(stdout) }); }+ catch { reject(new Error(`private phone-approved command ${args[0]} did not return JSON (exit ${code ?? 'signal'})`)); }+ });+ });+ return { child, done };+}++/** Poll a real fixture condition without retrying the operation under test. */+async function waitFor(read, message, timeout = 30000) {+ const deadline = Date.now() + timeout;+ do {+ const value = await read();+ if (value) return value;+ await new Promise(resolve => setTimeout(resolve, 25));+ } while (Date.now() < deadline);+ assert.fail(message);+}++/** Read a phone approval proposal from the real relay traffic without exposing its sealed payload. */+async function waitForPhoneProposal(box, start, target) {+ return waitFor(() => {+ const record = box.transit.slice(start).findLast(row => row.method === 'POST' && row.path === '/api/v1/devices/approvals');+ if (!record) return null;+ try {+ const context = JSON.parse(record.request.toString('utf8')).context;+ return context?.action === 'revoke-token' && context.target === target ? context : null;+ } catch { return null; }+ }, 'the revocation publishes one exact phone approval request');+}++/** Read and click only the paired-phone card for this opaque target id. */+async function approvePhoneProposal(chrome, proposal) {+ const selector = `.phone-approval[data-request="${proposal.id}"]`;+ await chrome.waitFor(`Boolean(document.querySelector(${JSON.stringify(selector)})?.querySelector('button'))`);+ const card = await chrome.evaluate(`(() => {+ const node = document.querySelector(${JSON.stringify(selector)});+ return { text: node.querySelector('p')?.textContent, action: node.querySelector('button')?.textContent };+ })()`);+ assert.match(card.text, /revoke/u);+ assert.match(card.text, new RegExp(proposal.target));+ assert.equal(card.action, 'Approve revocation', 'the paired phone presents an explicit revocation action');+ await chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).querySelector('button').click(); true`);+}+/** Run Git in a private fixture and keep all diagnostics credential-free. */function git(root, env, args) {const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });@@ -80,7 +138,10 @@ function assertMetadataOnly(value, credentials, message) {for (const row of value.tokens ?? []) assert.equal(Object.hasOwn(row, 'token'), false, message);}-test('ordered agent joins mint scoped tokens and retain authenticated native actors [H2,H9]', async (t) => {+test('ordered agent joins mint scoped tokens and retain authenticated native actors [H2,H9]', {+ skip: !findChromeExecutable() && 'Chrome is required for real person approval',+ timeout: 180000,+}, async (t) => {const box = await relayClientFixture(t);const cli = join(dirname(fileURLToPath(import.meta.url)), '../bin/pullboard.js');const shim = join(box.env.PATH, 'pullboard');@@ -119,7 +180,29 @@ test('ordered agent joins mint scoped tokens and retain authenticated native actgit(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-one', firstRoot, 'HEAD']);git(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-two', secondRoot, 'HEAD']);- await box.link();+ const personEnv = { ...box.env };+ for (const key of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete personEnv[key];+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');+ const setup = startCli(box.root, personEnv, cli, ['relay', 'on', '--all', '--url', box.origin]);+ t.after(async () => {+ if (setup.child.exitCode === null) setup.child.kill('SIGTERM');+ await setup.done.catch(() => {});+ });+ const pending = await waitFor(() => existsSync(machineFile) && JSON.parse(readFileSync(machineFile, 'utf8')).pending,+ 'foreground setup publishes a one-use phone enrollment');+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const phone = await box.phoneSession();+ assert.equal((await chrome.send('Network.setCookie', {+ name: 'pb_session', value: phone.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ })).success, true);+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);+ assert.equal((await setup.done).code, 0, 'foreground sign-in links and pairs the relay');+ await chrome.waitFor("document.querySelector('#phone-approvals') !== null");+ assert.match(JSON.parse(readFileSync(box.linkFile, 'utf8')).token, /^pm_[A-Za-z0-9_-]{43}$/u,+ 'the native link holds only a machine credential');+ assert.equal(Object.hasOwn(JSON.parse(readFileSync(machineFile, 'utf8')), 'session'), false,+ 'the phone session is not persisted in the machine state');const firstStart = box.calls.length;const firstJoin = await runCli(firstRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);assert.equal(firstJoin.code, 0, 'the first worktree joins through the real linked CLI');@@ -151,6 +234,9 @@ test('ordered agent joins mint scoped tokens and retain authenticated native actconst secondTokenRow = list.document.tokens.find((row) => row.agent === secondAgent);assert.ok(firstTokenRow?.id && secondTokenRow?.id);+ const previousApiHome = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = box.env.PULLBOARD_HOME;+ t.after(() => { if (previousApiHome === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = previousApiHome; });const localApi = await serveApi({runCommand: main,projects: () => [{ root: box.root, name: 'private relay fixture', project: 'fixture/repository', added: '2026-10-07T00:00:00.000Z' }],@@ -181,12 +267,32 @@ test('ordered agent joins mint scoped tokens and retain authenticated native act['verify', String(twoItem.document.item.item_id), 'accept', '--note', 'checked the other private submitted proof']);assert.equal(secondVerify.code, 0, `the second agent gives an ACCEPT verdict using only its scoped token (${secondVerify.document.error?.code ?? 'no refusal'})`);- const revoke = await box.cli('relay', 'revoke', firstTokenRow.id);+ const firstApprovalCount = box.calls.filter((call) => call.path.endsWith('/authorize')).length;+ const nativeRevokeStart = box.transit.length;+ const nativeRevoke = startCli(box.root, personEnv, cli, ['relay', 'revoke', firstTokenRow.id]);+ t.after(async () => { if (nativeRevoke.child.exitCode === null) nativeRevoke.child.kill('SIGTERM'); await nativeRevoke.done.catch(() => {}); });+ const nativeProposal = await waitForPhoneProposal(box, nativeRevokeStart, firstTokenRow.id);+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, firstApprovalCount,+ 'native revocation waits for a phone tap');+ await approvePhoneProposal(chrome, nativeProposal);+ const revoke = await nativeRevoke.done;assert.equal(revoke.code, 0, 'CLI revokes one listed opaque token id');- const apiRevokeResponse = await fetchFresh(tokenUrl, {+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, firstApprovalCount + 1,+ 'one explicit phone approval authorizes native revocation');++ const apiApprovalCount = box.calls.filter((call) => call.path.endsWith('/authorize')).length;+ const apiRevokeStart = box.transit.length;+ const apiRevokePending = fetchFresh(tokenUrl, {method: 'POST', headers: apiHeaders, body: JSON.stringify({ id: firstTokenRow.id }),});+ const apiProposal = await waitForPhoneProposal(box, apiRevokeStart, firstTokenRow.id);+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, apiApprovalCount,+ 'local API revocation waits for a phone tap');+ await approvePhoneProposal(chrome, apiProposal);+ const apiRevokeResponse = await apiRevokePending;assert.equal(apiRevokeResponse.status, 200, 'local API accepts the opaque id-only revocation body');+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, apiApprovalCount + 1,+ 'one explicit phone approval authorizes local API revocation');const apiRevoke = await apiRevokeResponse.json();assert.equal(apiRevoke.id, firstTokenRow.id);assert.equal(apiRevoke.revoked, true);@@ -207,20 +313,20 @@ test('ordered agent joins mint scoped tokens and retain authenticated native actconst cachedMintCount = box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length;const beforeCachedRefusal = nativeEvents(boardFile);const cachedRefusal = await runCli(firstRoot, box.env, cli, ['shout', 'all', 'revoked cache must stay revoked']);- assert.equal(cachedRefusal.code, 1, 'a cached revoked credential refuses even while the person session remains valid');+ assert.equal(cachedRefusal.code, 1, 'a cached revoked credential refuses while the paired phone remains available');assert.equal(cachedRefusal.document.error.code, 'AUTH_REQUIRED');assert.deepEqual(nativeEvents(boardFile), beforeCachedRefusal, 'revoked cached credentials cannot write native board events');assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, cachedMintCount,- 'a valid person session never silently re-mints its revoked agent cache');+ 'a valid machine credential never silently re-mints its revoked agent cache');const linkAfterRevoke = JSON.parse(readFileSync(box.linkFile, 'utf8'));- const personRevoked = await fetch(box.origin + '/auth/tokens/revoke', {+ const machineRevoked = await fetch(box.origin + '/auth/tokens/revoke', {method: 'POST', headers: { authorization: `Bearer ${linkAfterRevoke.token}`, 'content-type': 'application/json' },body: JSON.stringify({ id: linkAfterRevoke.tokenId }),});- assert.equal(personRevoked.status, 200, 'the private person session is revoked before token-only access');+ assert.equal(machineRevoked.status, 200, 'the paired machine credential can revoke its own PM');const deadSession = await fetch(box.origin + '/auth/session', { headers: { authorization: `Bearer ${linkAfterRevoke.token}` } });- assert.equal(deadSession.status, 401);+ assert.equal(deadSession.status, 401, 'the revoked PM no longer authenticates');assert.equal((await deadSession.json()).error.code, 'AUTH_REQUIRED');const mintCount = box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length;@@ -233,9 +339,9 @@ test('ordered agent joins mint scoped tokens and retain authenticated native actconst secondEnv = { ...box.env, PULLBOARD_RELAY_TOKEN: secondToken };const tokenOnlyRead = await runCli(secondRoot, secondEnv, cli, ['list', '--all']);- assert.equal(tokenOnlyRead.code, 0, 'the other agent reads through its scoped token after person revocation');+ assert.equal(tokenOnlyRead.code, 0, 'the other agent reads through its scoped token after PM revocation');const tokenOnlyWrite = await runCli(secondRoot, secondEnv, cli, ['claim', String(workItem.document.item.item_id)]);- assert.equal(tokenOnlyWrite.code, 0, 'the other agent writes through its scoped token after person revocation');+ assert.equal(tokenOnlyWrite.code, 0, 'the other agent writes through its scoped token after PM revocation');const native = nativeEvents(boardFile);assert.ok(native.some((row) => row.event_by === secondAgent && row.event_kind === 'claim' && row.item_id === workItem.document.item.item_id),diff --git a/test/relay-browser-fixture.test.js b/test/relay-browser-fixture.test.jsindex 0f42b3e0..a1fd8afc 100644--- a/test/relay-browser-fixture.test.js+++ b/test/relay-browser-fixture.test.js@@ -44,7 +44,7 @@ test('paired Chrome excludes idle event streams and reports only held state requconst chrome = await startChrome();t.after(() => chrome.close());const cookie = await chrome.send('Network.setCookie', {- name: 'pb_session', value: link.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',});assert.equal(cookie.success, true);await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);diff --git a/test/relay-browser.test.js b/test/relay-browser.test.jsindex 5f371d91..72cbc172 100644--- a/test/relay-browser.test.js+++ b/test/relay-browser.test.js@@ -86,7 +86,7 @@ test('relay fixture does not retry after Chrome publishes an unavailable DevToolasync function signIn(chrome, box) {const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));const result = await chrome.send('Network.setCookie', {- name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',});assert.equal(result.success, true, 'the real authorized person session is installed in this private browser');return state;diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 28847ac2..6b8760e3 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -1,3 +1,4 @@+import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';/** Private real CLI, auth and relay fixture; credentials never enter assertion messages [H1,H7,H18]. */import assert from 'node:assert/strict';import { spawn, spawnSync } from 'node:child_process';@@ -71,7 +72,7 @@ export async function relayClientFixture(t, { cliChildren } = {}) {GIT_AUTHOR_NAME: 'Relay Fixture', GIT_AUTHOR_EMAIL: '[email protected]',GIT_COMMITTER_NAME: 'Relay Fixture', GIT_COMMITTER_EMAIL: '[email protected]',};- for (const name of ['PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']) delete env[name];+ for (const name of ['PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN', ...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete env[name];const provider = await githubFixture(t);provider.state.deviceAuthorized = true;const authDatabase = join(scratch, 'auth.sqlite');@@ -97,6 +98,8 @@ export async function relayClientFixture(t, { cliChildren } = {}) {let refuseRequestWrites = false;let signIn;let api;+ let phone;+ let beforeMove;const calls = [];const transit = [];const moveAcks = [];@@ -133,11 +136,12 @@ export async function relayClientFixture(t, { cliChildren } = {}) {};res.once('finish', () => transit.push({ method: req.method, path: req.url,request: Buffer.concat(requestChunks), response: Buffer.concat(responseChunks) }));- calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '', engine: req.headers['x-pullboard-engine'] });+ calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '', engine: req.headers['x-pullboard-engine'],+ browser: String(req.headers.cookie ?? '').includes('pb_session=') });if (revokeOnNextListing && req.method === 'GET' && req.url === '/api/v1/boards') {revokeOnNextListing = false;- const state = JSON.parse(readFileSync(linkFile, 'utf8'));- await auth.revoke(state.token, state.tokenId);+ const session = await phoneSession();+ await auth.revoke(session.token, session.id);}if ([...privateKeys].some(key => JSON.stringify({ url: req.url, headers: req.headers }).includes(key))) keyLeaked = true;const missingSnapshot = /^\/api\/v1\/boards\/([0-9a-f]{32})\/(state|events)(?:\?|$)/u.exec(req.url ?? '');@@ -201,6 +205,9 @@ export async function relayClientFixture(t, { cliChildren } = {}) {stateReadStarted += 1;await new Promise(resolveDelay => setTimeout(resolveDelay, stateReadDelayMs));}+ if (beforeMove && req.method === 'POST' && /\/api\/v1\/boards\/[0-9a-f]{32}\/moves$/.test(req.url ?? '')) {+ const action = beforeMove; beforeMove = null; await action();+ }if (await signIn(request, res)) return;await api(request, res);});@@ -211,6 +218,20 @@ export async function relayClientFixture(t, { cliChildren } = {}) {auth = createRelayAuth({ database: authDatabase, github: createGitHubClient({ ...provider.config, callbackURL: origin + '/auth/github/callback' }) });signIn = createAuthHandler({ auth, publicOrigin: origin });api = createRelayHandler({ directory: join(scratch, 'relay'), auth, publicOrigin: origin, pollMs: 10, maintenanceMs: 0, now: () => time });+ /** Sign a separate phone in over actual OAuth HTTP; its person session stays only in fixture RAM. */+ async function phoneSession() {+ if (phone) return phone;+ const start = await fetch(origin + '/auth/github/start', { redirect: 'manual' });+ const binding = start.headers.getSetCookie().find(value => value.startsWith('pb_oauth_binding=')).split(';')[0];+ const approved = await fetch(start.headers.get('location'), { redirect: 'manual' });+ const callback = await fetch(approved.headers.get('location'), { redirect: 'manual', headers: { cookie: binding } });+ assert.equal(callback.status, 303, 'independent phone OAuth completes');+ const cookie = callback.headers.getSetCookie().find(value => value.startsWith('pb_session=')).split(';')[0];+ const token = cookie.slice('pb_session='.length);+ const principal = await auth.authenticate(token);+ phone = { token, id: principal.id };+ return phone;+ }t.after(async () => {api.close();server.closeAllConnections();@@ -369,11 +390,13 @@ export async function relayClientFixture(t, { cliChildren } = {}) {}return {transit, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,- root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, link, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,+ root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,/** Assert the test consumed every declared child budget, with no hidden CLI calls. */assertCliChildrenComplete() {if (cliChildren) assert.equal(cliChildIndex, cliChildren.length, 'every planned private CLI child ran exactly once');},+ /** Interleave one real authenticated relay write immediately before the next native move. */+ beforeNextMove(action) { beforeMove = action; },advance(days) { time = Date.now() + days * 86400000; },overrideDelete(value) { override = value; },failTokenMints(count) { mintFailures = count; },@@ -402,7 +425,7 @@ export async function relayClientFixture(t, { cliChildren } = {}) {mainURL: new URL('../src/cli.js', import.meta.url).href,keyInRequest() { return keyLeaked; },/** Revoke the actual synthetic person session, including its current live streams. */- revokeSession() { const state = JSON.parse(readFileSync(linkFile, 'utf8')); return auth.revoke(state.token, state.tokenId); },+ async revokeSession() { const session = await phoneSession(); return auth.revoke(session.token, session.id); },/** Revoke the real session when the next listing arrives so its HTTP authorization refusal is exercised. */revokeSessionOnNextListing() { revokeOnNextListing = true; },refuseReads(value) { refuseEventReads = value; },diff --git a/test/relay-client.test.js b/test/relay-client.test.jsindex 9dd7891b..f612c361 100644--- a/test/relay-client.test.js+++ b/test/relay-client.test.js@@ -24,6 +24,7 @@ import { storeBoardKey } from '../src/relay-key.js';import { ENGINE_VERSION } from '../src/machine.js';import { presentationShout } from '../src/relay-presentation.js';import { fetchFresh } from './http-fixture.js';+import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';const SIGN_INS = new Map();@@ -152,6 +153,8 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offliGIT_COMMITTER_NAME: 'Relay Test',GIT_COMMITTER_EMAIL: '[email protected]',};+ for (const name of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete env[name];+ for (const name of ['PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']) delete env[name];const provider = await githubFixture(t);let signIns = 0;SIGN_INS.set(root, async () => {@@ -201,6 +204,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offliawait assert.rejects(cli(root, relayEnv, 'relay', 'on', '--url', relay.origin), /RELAY_KEY_STORAGE/);assert.deepEqual(await auth.boardsFor(person.token), [], 'a failed device key save creates no remote link');assert.ok(!relay.calls.some((call) => call.path === '/auth/boards/link'));+ assert.equal(signIns, 0, 'a failed key save does not start a foreground person sign-in');chmodSync(keysDirectory, 0o700);const on = await cli(root, relayEnv, 'relay', 'on', '--url', relay.origin);const linkedAt = auth.linkedBoards().find(link => link.id === boardId).linkedAt;@@ -219,9 +223,15 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offliassert.equal(new URLSearchParams(fragment).get('board'), boardId);assert.equal(new URLSearchParams(fragment).get('key'), keyText, 'the phone link carries this board key only after #');- /** Fetch a public sealed document and authenticate it locally with the device-only key. */- async function get(path) {- const response = await fetch(relay.origin + path, { headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}` } });+ const linkFile = join(root, '.git', 'pullboard', 'relay.json');+ const machineLink = JSON.parse(readFileSync(linkFile, 'utf8'));+ assert.match(machineLink.token, /^pm_[A-Za-z0-9_-]{43}$/u, 'the board stores its scoped machine credential');+ assert.notEqual(machineLink.token, person.token, 'the short-lived person session is not stored in the board link');+ assert.equal(machineLink.account, person.user.id);+ assert.equal(typeof machineLink.machine, 'string');+ /** Fetch a public sealed document with the current board-scoped machine credential. */+ async function get(path, token = JSON.parse(readFileSync(linkFile, 'utf8')).token) {+ const response = await fetch(relay.origin + path, { headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${token}` } });return { status: response.status, body: await response.json() };}const remoteState = await get(`/api/v1/boards/${boardId}/state`);@@ -260,7 +270,6 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offliassert.ok(Array.isArray(opened.args));}- const linkFile = join(root, '.git', 'pullboard', 'relay.json');const oldLink = JSON.parse(readFileSync(linkFile, 'utf8'));await auth.revoke(person.token, oldLink.tokenId);const expired = await cli(root, relayEnv, 'status');@@ -270,7 +279,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offliassert.equal(renewed.sequence, 2, 'renewing sign-in preserves the relay cursor');assert.equal((await get(`/api/v1/boards/${boardId}/state`)).body.state.sealed, nativeAfterMoves.body.state.sealed,'renewing sign-in does not replace the acknowledged checkpoint');- assert.ok(signIns >= 3, 'JSON mode exposes each device code before waiting for sign-in');+ assert.equal(signIns, 2, 'JSON mode exposes each device code for the initial successful link and explicit renewal');relay.failMoves(true);const beforeOffline = localEvents(boardFile);@@ -321,7 +330,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli}assert.equal(uniqueMoves.size, 3, 'a lost reply recovers the exact send without inventing a second operation');await legacyMirrorQueueFragment({ relay, root, relayEnv, boardFile, linkFile, lane, lanes: Object.keys(config.lanes), boardId, key,- currentPersonToken: JSON.parse(readFileSync(linkFile, 'utf8')).token, localEvents, cli, store, unseal });+ currentMachineToken: JSON.parse(readFileSync(linkFile, 'utf8')).token, localEvents, cli, store, unseal });relay.advance(80);const warned = await cli(root, relayEnv, 'status');assert.match((warned.diagnostics ?? []).join('\n'), /BOARD_INACTIVE.*10 days left.*Make a board move/i, 'the next linked command shows the real relay retention notice and repair');@@ -335,21 +344,37 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offliassert.equal(stored.includes(Buffer.from(encodeBoardKey(key))), false, 'relay journal does not contain the encoded key');await legacyForeignPrefixFragment({ relay, root, relayEnv, boardFile, linkFile, lane, boardId,- currentPersonToken: JSON.parse(readFileSync(linkFile, 'utf8')).token, localEvents, cliResult });+ currentMachineToken: JSON.parse(readFileSync(linkFile, 'utf8')).token, localEvents, cliResult });const localBeforeOff = await cli(root, relayEnv, 'export');const off = await cli(root, relayEnv, 'relay', 'off');assert.equal(off.linked, false);+ assert.match(off.notice, /Local link removed\. The relay copy stays until you approve deleting it on your phone\./u);assert.deepEqual((await cli(root, env, 'export')).tables, localBeforeOff.tables, 'unlink leaves local rows and counters unchanged');- assert.deepEqual(await auth.boardsFor(person.token), [], 'unlink removes the repository link');- const session = await fetch(relay.origin + '/auth/session', { headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}` } });+ assert.deepEqual(await auth.boardsFor(person.token), [{ id: boardId, repository: 'fixture/repository', linkedAt }],+ 'zero-tap local unlink leaves the remote board linked');+ const session = await fetch(relay.origin + '/auth/session', { headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${person.token}` } });assert.equal(session.status, 200, 'unlink preserves the person session');- assert.equal((await get(`/api/v1/boards/${boardId}/state`)).status, 404);- assert.equal(readdirSync(relayDirectory).some((name) => name.startsWith(boardId + '.journal.sqlite')), false,- 'off removes the relay journal and SQLite sidecars');+ const remoteAfterOff = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, {+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${person.token}` },+ });+ assert.equal(remoteAfterOff.status, 200, 'the relay copy remains until explicit person authorization');+ assert.equal(readdirSync(relayDirectory).some((name) => name.startsWith(boardId + '.journal.sqlite')), true,+ 'local off leaves the remote journal and SQLite sidecars in place');const afterOffCalls = relay.calls.length;await cli(root, env, 'status');assert.equal(relay.calls.length, afterOffCalls, 'unlinked commands stop connecting immediately');assert.equal(existsSync(keyFile), false, 'successful off removes this device copy of the board key');+ const deleted = await fetch(`${relay.origin}/api/v1/boards/${boardId}`, {+ method: 'DELETE', headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${person.token}` },+ });+ assert.equal(deleted.status, 200, 'a separate person HTTP DELETE removes the retained relay copy');+ assert.deepEqual(await auth.boardsFor(person.token), [], 'the real person deletion unlinks the remote board');+ const afterDelete = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, {+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${person.token}` },+ });+ assert.equal(afterDelete.status, 404);+ assert.equal(readdirSync(relayDirectory).some((name) => name.startsWith(boardId + '.journal.sqlite')), false,+ 'person deletion removes the relay journal and SQLite sidecars');});test('[H3,H16] three cloned linked replicas order competing claims and recover lost replies once', { timeout: 240_000 }, async (t) => {@@ -371,6 +396,8 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lconst envs = homes.map((home) => {const env = { ...process.env, HOME: home, USERPROFILE: home, PULLBOARD_HOME: join(home, '.pullboard'), PATH: privateBin };for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];+ for (const key of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete env[key];+ for (const key of ['PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']) delete env[key];Object.assign(env, {GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',GIT_AUTHOR_NAME: 'Relay Clone Test', GIT_AUTHOR_EMAIL: '[email protected]',@@ -445,6 +472,7 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lawait auth.linkBoard(person.token, boardId, 'fixture/repository');const key = await generateBoardKey();+ const cloneCredentials = [];const savedPath = process.env.PATH;const savedHome = process.env.PULLBOARD_HOME;try {@@ -454,9 +482,14 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lassert.equal(storeBoardKey(boardId, key), 'file', 'the isolated PATH forces the private file fallback');const keyFile = join(envs[index].PULLBOARD_HOME, 'relay-keys', `${boardId}.key`);assert.equal(statSync(keyFile).mode & 0o777, 0o600);+ const machine = 'machine-clone-' + (index + 1);+ const machineCredential = await auth.issueMachine(person.token, { board: boardId, machine });+ cloneCredentials.push(machineCredential);+ assert.match(machineCredential.token, /^pm_[A-Za-z0-9_-]{43}$/u);const state = {version: 1, mode: 'ordered', board: boardId, url: relay.origin, repository: 'fixture/repository',- token: person.token, tokenId: person.id, keyStorage: 'file', sequence: 0,+ token: machineCredential.token, tokenId: machineCredential.id, account: person.user.id, machine,+ keyStorage: 'file', sequence: 0,cursor: snapshot.tables.event.at(-1)?.event_id ?? 0,};const linkFile = join(commonDir(clones[index], envs[index]), 'pullboard', 'relay.json');@@ -467,12 +500,14 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lif (savedPath === undefined) delete process.env.PATH; else process.env.PATH = savedPath;if (savedHome === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = savedHome;}+ assert.equal(new Set(cloneCredentials.map(value => value.token)).size, clones.length,+ 'each clone receives a distinct real board-scoped machine credential');const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(snapshot)), {boardId, kind: 'snapshot', sequence: 0,})).toString('base64url');const uploaded = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, {- method: 'PUT', headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },+ method: 'PUT', headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${cloneCredentials[0].token}`, 'content-type': 'application/json' },body: JSON.stringify({ sequence: 0, sealed }),});assert.equal(uploaded.status, 200, await uploaded.text());@@ -560,7 +595,7 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lboardId, kind: 'move', sequence: next,})).toString('base64url');const coordinatorCredential = await auth.issueToken(person.token, { board: boardId, agent: 'coordinator' });- const headers = { 'x-pullboard-engine': '3', authorization: 'Bearer ' + coordinatorCredential.token, 'content-type': 'application/json' };+ const headers = { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: 'Bearer ' + coordinatorCredential.token, 'content-type': 'application/json' };assert.equal((await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {method: 'POST', headers, body: JSON.stringify({ sequence: next, sealed: earlierSealed }),})).status, 200);@@ -743,7 +778,7 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover l/** Exercise migration of an old local-first mirror queue into the ordered native checkpoint. */async function legacyMirrorQueueFragment({- relay, root, relayEnv, boardFile, linkFile, lane, lanes, boardId, key, currentPersonToken,+ relay, root, relayEnv, boardFile, linkFile, lane, lanes, boardId, key, currentMachineToken,localEvents, cli, store, unseal,}) {const priorRows = localEvents(boardFile);@@ -792,7 +827,7 @@ async function legacyMirrorQueueFragment({assert.equal(openedLegacy[0].presentation, undefined, 'the historical first move cannot attest the later row');assert.equal(openedLegacy[1].presentation.state.events[0].event_id, queuedEvents.at(-1).event_id, 'the final legacy move carries only its matching projection');- const authorization = { 'x-pullboard-engine': '3', authorization: `Bearer ${currentPersonToken}` };+ const authorization = { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${currentMachineToken}` };const stateResponse = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, { headers: authorization });assert.equal(stateResponse.status, 200);const stateDocument = await stateResponse.json();@@ -815,7 +850,7 @@ async function legacyMirrorQueueFragment({/** Confirm migration refuses an unrecognized remote prefix before executing another local move. */async function legacyForeignPrefixFragment({- relay, root, relayEnv, boardFile, linkFile, lane, boardId, currentPersonToken, localEvents, cliResult,+ relay, root, relayEnv, boardFile, linkFile, lane, boardId, currentMachineToken, localEvents, cliResult,}) {const originalLink = readFileSync(linkFile, 'utf8');const link = JSON.parse(originalLink);@@ -827,7 +862,7 @@ async function legacyForeignPrefixFragment({const foreign = await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {method: 'POST',- headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${currentPersonToken}`, 'content-type': 'application/json' },+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: `Bearer ${currentMachineToken}`, 'content-type': 'application/json' },body: JSON.stringify({ sequence: link.sequence + 1, sealed: 'AQ' }),});assert.equal(foreign.status, 200, await foreign.text());diff --git a/test/relay-credential.test.js b/test/relay-credential.test.jsindex f5463980..4cd0911a 100644--- a/test/relay-credential.test.js+++ b/test/relay-credential.test.js@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import { readFileSync } from 'node:fs';import { test } from 'node:test';import { ENGINE_OPERATIONS } from '../src/engine.js';+import { ENGINE_VERSION } from '../src/machine.js';import { decodeBoardKey, unseal } from '../src/seal.js';import { relayClientFixture } from './relay-client-fixture.js';@@ -14,8 +15,8 @@ test('every current operation selects its native actor credential without a secoconst cases = ENGINE_OPERATIONS.map(operation => {let args = [999999, options];let kind = 'agent';- if (operation === 'register') { args = [{ lane: box.lane, path: '/private/credential-enrollment' }]; kind = 'person'; }- if (operation === 'ensureCoordinator') { args = [box.root]; kind = 'person'; }+ if (operation === 'register') { args = [{ lane: box.lane, path: '/private/credential-enrollment' }]; kind = 'machine'; }+ if (operation === 'ensureCoordinator') { args = [box.root]; kind = 'machine'; }if (operation === 'addItem') args = [{ by: actor, lane: box.lane, title: 'credential actor fixture' }];if (operation === 'shout') args = [{ from: actor, to: 'all', text: 'credential actor fixture', lanes: [box.lane] }];if (operation === 'release') args = [999999, actor];@@ -29,14 +30,14 @@ test('every current operation selects its native actor credential without a secoif (['holdLane', 'releaseLane'].includes(operation)) args = [box.lane, options];if (operation === 'applyRowDecisions') args = [{ agentId: actor, events: [] }];if (operation === 'recordRowDecisions') { args = [{ agentId: 'person', channel: 'terminal', decisions: [] }]; kind = 'person'; }- return { operation, args, kind };+ return { operation, args, kind, ...(kind === 'person' ? { sent: false } : {}) };});cases.push(- { operation: 'answerDecision', args: [999999, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person' },- { operation: 'holdLane', args: [box.lane, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person' },- { operation: 'releaseLane', args: [box.lane, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person' },- { operation: 'shout', args: [{ from: actor, to: 'all', text: 'person request fixture', lanes: [box.lane], request: true }], kind: 'person' },- { operation: 'applyRowDecisions', args: [{ agentId: actor, events: [] }], kind: 'person', personRequest: { id: 'credential-request', stage: 'apply' } },+ { operation: 'answerDecision', args: [999999, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person', sent: false },+ { operation: 'holdLane', args: [box.lane, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person', sent: false },+ { operation: 'releaseLane', args: [box.lane, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person', sent: false },+ { operation: 'shout', args: [{ from: actor, to: 'all', text: 'person request fixture', lanes: [box.lane], request: true }], kind: 'person', sent: false },+ { operation: 'applyRowDecisions', args: [{ agentId: actor, events: [] }], kind: 'machine', sent: false, expected: 'PERSON_REQUEST_CLOSED', personRequest: { id: 'credential-request', executor: actor, phase: 'execute', digest: '0'.repeat(64) } },);const start = box.moveAcks.length;const results = [];@@ -61,16 +62,28 @@ test('every current operation selects its native actor credential without a secoresults.push(...result.document.results);}const records = box.moveAcks.slice(start);- assert.equal(records.length, cases.length, 'each operation is acknowledged once even when native preconditions refuse it');+ const sentCases = cases.filter(entry => entry.sent !== false);+ assert.equal(records.length, sentCases.length, 'agent and machine moves are acknowledged; person-only moves stop before transport');const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ let recordIndex = 0;for (const [index, entry] of cases.entries()) {- const record = records[index];+ if (entry.sent === false) {+ assert.equal(results[index], entry.expected ?? 'HUMAN_REQUIRED', `${entry.operation} cannot use the saved machine credential for a person action`);+ continue;+ }+ const record = records[recordIndex++];const move = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(record.sealed, 'base64url'), { boardId: state.board, kind: record.kind, sequence: record.event_id })));assert.equal(move.operation, entry.operation);+ assert.equal(move.engine, ENGINE_VERSION, 'the current engine version is recorded on every sealed operation');assert.equal(record.sender.kind, entry.kind, `${entry.operation} selects the correct authenticated credential`);if (entry.kind === 'agent') assert.equal(record.sender.agent, actor, 'the scoped credential belongs to the native actor');- assert.ok(!['RELAY_ACTOR', 'RELAY_SENDER', 'RELAY_SENDER_MISMATCH', 'RELAY_PERSON_ONLY'].includes(results[index]),- `${entry.operation} passes main's shared sender policy`);+ if (entry.kind === 'machine') assert.equal(record.sender.machine, state.machine, 'the machine credential is attributed to this native machine');+ if (entry.personRequest) {+ assert.equal(results[index], 'RELAY_PERSON_ONLY', 'a machine cannot execute an unauthenticated synthetic person request');+ } else {+ assert.ok(!['RELAY_ACTOR', 'RELAY_SENDER', 'RELAY_SENDER_MISMATCH', 'RELAY_PERSON_ONLY'].includes(results[index]),+ `${entry.operation} passes main's shared sender policy`);+ }}});diff --git a/test/relay-deploy.test.js b/test/relay-deploy.test.jsindex 34e7f668..72e7a0fd 100644--- a/test/relay-deploy.test.js+++ b/test/relay-deploy.test.js@@ -210,7 +210,7 @@ test('[H5,H18] the Railway checklist matches the container and relay runtime settest('[H5,H18] the Railway smoke links, reads one unsealed move and unlinks locally', async (t) => {const box = await relayClientFixture(t);await box.link();- assert.equal(await box.requireEngineThree(), 3, 'minting an agent token raises the durable relay minimum to engine 3');+ assert.equal(await box.requireEngineThree(), 6, 'a machine-linked board requires the machine-aware replay engine');const previous = JSON.parse(readFileSync(box.linkFile, 'utf8'));const legacy = await fetch(`${previous.url}/api/v1/boards/${previous.board}/state`, {headers: { authorization: `Bearer ${previous.token}`, 'x-pullboard-engine': '2' },@@ -218,6 +218,11 @@ test('[H5,H18] the Railway smoke links, reads one unsealed move and unlinks locaassert.equal(legacy.status, 400, 'the durable agent-token minimum refuses an engine-2 reader');assert.equal((await legacy.json()).error.code, 'ENGINE_VERSION');assert.equal((await box.cli('relay', 'off')).code, 0);+ const phone = await box.phoneSession();+ const removed = await fetch(`${previous.url}/api/v1/boards/${previous.board}`, {+ method: 'DELETE', headers: { authorization: `Bearer ${phone.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },+ });+ assert.equal(removed.status, 200, 'the signed-in phone explicitly deletes the earlier disposable board before relinking');const beforeSmoke = box.calls.length;const smoke = await runSmoke(box, previous.url);@@ -228,8 +233,14 @@ test('[H5,H18] the Railway smoke links, reads one unsealed move and unlinks locaassert.equal(result.sequence, 1);assert.equal(existsSync(box.linkFile), false, 'relay off forgets the private link metadata');assert.equal(existsSync(box.keyFile), false, 'relay off forgets the device-only board key');- assert.ok(box.calls.slice(beforeSmoke).some((call) => call.method === 'DELETE' && call.path === `/api/v1/boards/${previous.board}`),- 'the smoke sends relay off to the supplied local relay');+ assert.equal(box.calls.slice(beforeSmoke).some(call => call.method === 'DELETE'), false,+ 'the smoke only unlinks locally and cannot delete the relay copy without phone approval');+ assert.equal(result.remoteCopyRetained, true);+ assert.match(result.notice, /relay copy stays until you approve deleting it on your phone/u);+ const retained = await fetch(`${previous.url}/api/v1/boards/${previous.board}/state`, {+ headers: { authorization: `Bearer ${phone.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },+ });+ assert.equal(retained.status, 200, 'local smoke cleanup retains the sealed relay copy for explicit phone deletion');const smokeReads = box.calls.slice(beforeSmoke).filter((call) => call.method === 'GET'&& new RegExp(`^/api/v1/boards/${previous.board}/(?:events|state)(?:\\?|$)`, 'u').test(call.path));assert.ok(smokeReads.length >= 2, 'the smoke reads the mirrored event and its native checkpoint over the real HTTP API');@@ -251,7 +262,7 @@ test('[H5,H18] a linked repository is refused before the smoke can unlink its boassert.equal(existsSync(box.linkFile), true, 'the existing private link remains intact');assert.equal(existsSync(box.keyFile), true, 'the existing device key remains intact');const state = await fetch(`${previous.url}/api/v1/boards/${previous.board}/state`, {- headers: { authorization: `Bearer ${previous.token}` },+ headers: { authorization: `Bearer ${previous.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },});assert.equal(state.status, 200, 'the linked remote board was not deleted');});diff --git a/test/relay-machine-auth.test.js b/test/relay-machine-auth.test.jsnew file mode 100644index 00000000..96b6aaa0--- /dev/null+++ b/test/relay-machine-auth.test.js@@ -0,0 +1,67 @@+/** Board-bound machine credentials remain narrower than person sessions [H16,B26]. */+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { createRelayAuth } from '../relay/auth.js';+import { createGitHubClient } from '../relay/github.js';+import { githubFixture } from './relay-fixture.js';++/** Create an actual signed-in account against the loopback GitHub protocol fixture. */+async function signedPerson(box, auth) {+ const flow = await auth.beginDevice();+ await fetch(flow.verificationURL);+ box.advance(flow.interval * 1000);+ return auth.pollDevice(flow.ticket);+}++test('machine credentials mint and list same-board agents but cannot link, revoke, or mint machines [H16,B26]', async (t) => {+ const provider = await githubFixture(t);+ const root = mkdtempSync(join(tmpdir(), 'pullboard-machine-auth-'));+ let now = Date.now();+ const auth = createRelayAuth({ database: join(root, 'auth.sqlite'), github: createGitHubClient(provider.config), now: () => now });+ t.after(() => { auth.close(); rmSync(root, { recursive: true, force: true }); });+ const box = { ...provider, advance(ms) { now += ms; } };+ const person = await signedPerson(box, auth);+ const alpha = 'a'.repeat(32);+ const beta = 'b'.repeat(32);+ await auth.linkBoard(person.token, alpha, 'fixture/repository');+ await auth.linkBoard(person.token, beta, 'fixture/repository');++ const machine = await auth.issueMachine(person.token, { board: alpha, machine: 'mac-alpha' });+ assert.match(machine.token, /^pm_[A-Za-z0-9_-]{43}$/u);+ assert.notEqual(machine.token, person.token);+ assert.equal(machine.board, alpha);+ assert.equal(machine.machine, 'mac-alpha');+ assert.equal(readFileSync(join(root, 'auth.sqlite')).includes(machine.token), false, 'SQLite stores only the machine credential hash');+ const identity = await auth.authenticate(machine.token, { board: alpha });+ assert.equal(identity.kind, 'machine');+ assert.equal(identity.board, alpha);+ assert.equal(identity.machine, 'mac-alpha');+ assert.deepEqual((await auth.boardsFor(machine.token)).map(row => row.id), [alpha], 'machine inventory stays on its own board');++ const agent = await auth.issueToken(machine.token, { board: alpha, agent: 'worker-alpha' });+ assert.match(agent.token, /^pa_[A-Za-z0-9_-]{43}$/u);+ assert.equal(agent.board, alpha);+ assert.equal(agent.agent, 'worker-alpha');+ assert.deepEqual((await auth.boardsFor(agent.token)).map(row => row.id), [alpha], 'agent inventory stays on its own board');++ await assert.rejects(auth.authenticate(machine.token, { board: beta }), { code: 'TOKEN_BOARD' });+ await assert.rejects(auth.issueMachine(machine.token, { board: beta, machine: 'mac-beta' }), { code: 'TOKEN_BOARD' });+ await assert.rejects(auth.issueMachine(agent.token, { board: alpha, machine: 'agent-machine' }), { code: 'HUMAN_REQUIRED' });+ await assert.rejects(auth.issueMachine(machine.token, { board: alpha, machine: 'nested-machine' }), { code: 'HUMAN_REQUIRED' });+ await assert.rejects(auth.linkBoard(machine.token, 'c'.repeat(32), 'fixture/repository'), { code: 'HUMAN_REQUIRED' });+ const tokens = await auth.listTokens(machine.token, alpha);+ assert.deepEqual(tokens.map(value => value.id), [agent.id]);+ assert.equal(tokens.some(value => Object.hasOwn(value, 'token') || Object.hasOwn(value, 'hash')), false);+ await assert.rejects(auth.listTokens(machine.token, beta), { code: 'TOKEN_BOARD' });+ await assert.rejects(auth.issueToken(machine.token, { board: beta, agent: 'cross-board' }), { code: 'TOKEN_BOARD' });+ assert.equal(auth.minimumEngineVersion(alpha), 6);+ await assert.rejects(auth.listTokens(agent.token, alpha), { code: 'HUMAN_REQUIRED' });+ await assert.rejects(auth.revoke(machine.token, agent.id), { code: 'TOKEN_NOT_OWNED' });++ const personIssued = await auth.issueToken(person.token, { board: alpha, agent: 'worker-person' });+ assert.equal((await auth.authenticate(personIssued.token, { board: alpha })).kind, 'board');+ assert.deepEqual((await auth.boardsFor(person.token)).map(row => row.id), [alpha, beta], 'only the person session can inventory multiple linked boards');+});diff --git a/test/relay-machine-journal.test.js b/test/relay-machine-journal.test.jsnew file mode 100644index 00000000..1a67866f--- /dev/null+++ b/test/relay-machine-journal.test.js@@ -0,0 +1,127 @@+/** Migrate the opaque journal without changing legacy attribution or bytes [H7,H15]. */+import assert from 'node:assert/strict';+import { DatabaseSync } from 'node:sqlite';+import { chmodSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { createRelayJournal } from '../relay/journal.js';++const ID = 'd'.repeat(32);+const PERSON = { kind: 'person', userId: '101' };+const MACHINE = { kind: 'machine', userId: '101', machine: 'machine-phone' };++/** Create the original format-2 SQLite tables and seed opaque records without using production writers. */+function createLegacyJournal(directory, format = '2') {+ const path = join(directory, ID + '.journal.sqlite');+ const db = new DatabaseSync(path);+ chmodSync(path, 0o600);+ try {+ db.exec(`CREATE TABLE journal_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);+ CREATE TABLE journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL,+ kind TEXT NOT NULL CHECK(kind IN ('move','request')), payload BLOB NOT NULL,+ sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','agent')), sender_user TEXT NOT NULL,+ sender_agent TEXT, CHECK((sender_kind='person' AND sender_agent IS NULL) OR+ (sender_kind='agent' AND sender_agent IS NOT NULL)));+ CREATE TABLE journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL, last_activity_at TEXT);+ CREATE TABLE journal_snapshot (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL,+ received_at TEXT NOT NULL, payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind='person'),+ sender_user TEXT NOT NULL, sender_agent TEXT, CHECK(sender_agent IS NULL));`);+ db.prepare('INSERT INTO journal_meta(key,value) VALUES(?,?),(?,?)').run('board', ID, 'format', format);+ db.prepare(`INSERT INTO journal_record(sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent)+ VALUES(1,?,'move',?,'person','101',NULL),(2,?,'request',?,'agent','202','agent-opaque')`)+ .run('2026-10-08T10:00:00.000Z', Buffer.from([0, 255, 2, 128]),+ '2026-10-08T10:01:00.000Z', Buffer.from([9, 0, 250, 1]));+ db.prepare('INSERT INTO journal_head(slot,sequence,last_activity_at) VALUES(1,2,?)').run('2026-10-08T10:02:00.000Z');+ db.prepare(`INSERT INTO journal_snapshot(slot,sequence,received_at,payload,sender_kind,sender_user,sender_agent)+ VALUES(1,1,? ,?,'person','101',NULL)`).run('2026-10-08T10:00:30.000Z', Buffer.from([7, 0, 255, 3]));+ } finally { db.close(); }+ return path;+}++/** Return a deterministic logical snapshot of the original schema and rows. */+function databaseContents(path) {+ const db = new DatabaseSync(path, { readOnly: true });+ try {+ const schema = db.prepare("SELECT type,name,sql FROM sqlite_master WHERE type='table' ORDER BY name").all();+ const tables = {};+ for (const name of ['journal_meta', 'journal_head', 'journal_record', 'journal_snapshot']) {+ tables[name] = db.prepare(`SELECT * FROM ${name} ORDER BY 1`).all().map(row => Object.fromEntries(+ Object.entries(row).map(([key, value]) => [key, Buffer.isBuffer(value) ? value.toString('base64') : value]),+ ));+ }+ return { schema, tables };+ } finally { db.close(); }+}++/** Allocate a private directory and remove SQLite sidecars after every journal handle closes. */+function privateDirectory(t) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-machine-journal-'));+ const opened = [];+ t.after(() => { for (const journal of opened) journal.close(); rmSync(directory, { recursive: true, force: true }); });+ return {+ directory,+ /** Reopen the real private journal through the production migration. */+ open(now = () => new Date('2026-10-09T12:00:00.000Z')) {+ const journal = createRelayJournal({ directory, boardId: ID, now });+ opened.push(journal);+ return journal;+ },+ };+}++test('[H7,H15] format-2 opaque history migrates to machine attribution without changing its records', (t) => {+ const box = privateDirectory(t);+ const path = createLegacyJournal(box.directory);+ const legacy = databaseContents(path);+ const journal = box.open();+ assert.equal(journal.board, ID);+ assert.equal(journal.latest(), 2, 'the existing sequence head survives migration');+ assert.equal(journal.activity(), '2026-10-08T10:02:00.000Z', 'the existing head activity timestamp survives migration');+ assert.deepEqual(journal.after().map(row => ({ sequence: row.sequence, receivedAt: row.receivedAt,+ kind: row.kind, bytes: row.bytes, sender: row.sender })), [+ { sequence: 1, receivedAt: '2026-10-08T10:00:00.000Z', kind: 'move', bytes: Buffer.from([0, 255, 2, 128]), sender: PERSON },+ { sequence: 2, receivedAt: '2026-10-08T10:01:00.000Z', kind: 'request', bytes: Buffer.from([9, 0, 250, 1]),+ sender: { kind: 'agent', userId: '202', agent: 'agent-opaque' } },+ ], 'legacy person and agent provenance and opaque bytes remain exact');+ assert.deepEqual(journal.snapshot(), {+ sequence: 1, receivedAt: '2026-10-08T10:00:30.000Z', kind: 'snapshot',+ sender: PERSON, bytes: Buffer.from([7, 0, 255, 3]),+ }, 'the historical person snapshot remains unchanged');+ const migrated = databaseContents(path);+ assert.equal(migrated.tables.journal_meta.find(row => row.key === 'format').value, '3');+ assert.equal(migrated.tables.journal_meta.find(row => row.key === 'board').value, ID);+ assert.equal(migrated.tables.journal_record.length, legacy.tables.journal_record.length);+ assert.equal(migrated.tables.journal_snapshot.length, legacy.tables.journal_snapshot.length);+ assert.equal(migrated.schema.some(row => row.name.endsWith('_v2')), false, 'migration leaves no renamed legacy table behind');++ const machineMove = journal.appendNext(Buffer.from([4, 240, 1]), 'move', MACHINE);+ assert.equal(machineMove.sequence, 3);+ assert.deepEqual(machineMove.sender, MACHINE);+ assert.deepEqual(journal.after(2)[0].bytes, Buffer.from([4, 240, 1]));+ assert.equal(journal.activity(), '2026-10-09T12:00:00.000Z');+ const checkpoint = journal.saveSnapshot(3, Buffer.from([0, 11, 0, 255]), MACHINE);+ assert.equal(checkpoint.sequence, 3);+ assert.deepEqual(checkpoint.sender, MACHINE);+ assert.deepEqual(checkpoint.bytes, Buffer.from([0, 11, 0, 255]));+ assert.deepEqual(journal.after(), [], 'machine snapshot compaction retains the existing head without old rows');++ journal.close();+ const restarted = box.open();+ assert.equal(restarted.latest(), 3);+ assert.equal(restarted.activity(), '2026-10-09T12:00:00.000Z');+ assert.deepEqual(restarted.snapshot().sender, MACHINE, 'machine attribution survives a real SQLite restart');+ assert.deepEqual(restarted.snapshot().bytes, Buffer.from([0, 11, 0, 255]));+ const afterRestart = restarted.appendNext(Buffer.from([5, 3, 1]), 'request', MACHINE);+ assert.equal(afterRestart.sequence, 4);+ assert.deepEqual(afterRestart.sender, MACHINE);+ assert.equal(restarted.latest(), 4);+});++test('[H7] unsupported journal formats refuse without rewriting legacy tables or bytes', (t) => {+ const box = privateDirectory(t);+ const path = createLegacyJournal(box.directory, '99');+ const before = databaseContents(path);+ assert.throws(() => box.open(), { code: 'RELAY_STORAGE' });+ assert.deepEqual(databaseContents(path), before, 'unsupported format metadata, table checks and opaque rows stay unchanged');+});diff --git a/test/relay-machine-race.test.js b/test/relay-machine-race.test.jsnew file mode 100644index 00000000..9ca2f488--- /dev/null+++ b/test/relay-machine-race.test.js@@ -0,0 +1,175 @@+/** A competing phone execution consumes a request before its elected native receipt arrives [H12,H16,B26]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { appliedSequence, prepareEngineMove } from '../src/engine.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { preparePersonRequest } from '../src/person-request.js';+import { personRequestRecords, requestIntentDigest } from '../src/relay-requests.js';+import { decodeBoardKey, seal } from '../src/seal.js';+import { relayClientFixture } from './relay-client-fixture.js';++const RELAY_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/relay.js')).href;+const BOARD_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/board.js')).href;+const REQUESTS_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/relay-requests.js')).href;+const CONFIG_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/config.js')).href;+const LANES_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/lanes.js')).href;++/** Read one real SQLite person-request receipt without opening a transport or changing the board. */+function requestRecord(root, id) {+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));+ try { return personRequestRecords(board).find(record => record.id === id && !record.duplicateOf); }+ finally { store.closeBoard(board); }+}++/** Seal a browser-format intent and submit it with the real short-lived phone session. */+async function postPhoneRequest(box, boardId, phoneToken, boardKey, document) {+ const sealed = Buffer.from(await seal(boardKey, new TextEncoder().encode(JSON.stringify(document)), {+ boardId, kind: 'request', sequence: 1,+ })).toString('base64url');+ return fetch(box.origin + '/api/v1/boards/' + boardId + '/requests', {+ method: 'POST',+ headers: { authorization: 'Bearer ' + phoneToken, 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) },+ body: JSON.stringify({ sequence: 1, sealed }),+ });+}++test('a raced native request receipt returns its sender refusal and clears pending state [H12,H16,B26]', async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const boardKey = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const phone = await box.phoneSession();+ const requestId = 'native-race-phone-shout';+ const intent = preparePersonRequest({ verb: 'shout', args: { to: 'coordinator', text: 'PHONE_RACE_SHOUT_ONCE' } }, requestId);+ const acceptedIntent = await postPhoneRequest(box, link.board, phone.token, boardKey, intent);+ assert.equal(acceptedIntent.status, 200, 'the real phone session appends the sealed request at sequence one');+ const acceptedIntentDocument = await acceptedIntent.json();+ assert.equal(acceptedIntentDocument.event?.event_id, 1);+ assert.equal(acceptedIntentDocument.event?.kind, 'request');++ const claim = await box.script(`+ import { join } from 'node:path';+ import { relayRequestDevice, relayOperation, syncRelay } from ${JSON.stringify(RELAY_MODULE)};+ import { openBoard, closeBoard } from ${JSON.stringify(BOARD_MODULE)};+ import { personRequestRecords, requestIntentDigest, requestStageText } from ${JSON.stringify(REQUESTS_MODULE)};+ import { loadConfig } from ${JSON.stringify(CONFIG_MODULE)};+ import { laneNames } from ${JSON.stringify(LANES_MODULE)};+ const root = process.cwd();+ const sink = { write() {} };+ const io = { cwd: root, stdout: sink, stderr: sink, say() {}, err() {}, onEvent() {} };+ await syncRelay(root, io);+ const executor = await relayRequestDevice(root);+ const board = openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));+ let record;+ try { record = personRequestRecords(board).find(entry => entry.id === ${JSON.stringify(requestId)} && !entry.duplicateOf); }+ finally { closeBoard(board); }+ const message = { from: 'person', to: 'coordinator', text: requestStageText(record, 'claim'), lanes: laneNames(loadConfig(root)) };+ const result = await relayOperation(root, 'shout', [message], {+ ...io,+ personRequest: { id: record.id, executor, phase: 'claim', digest: requestIntentDigest(record) },+ personRequestMoveId: 'native-race-claim-' + record.id,+ });+ process.stdout.write(JSON.stringify({ claimRecorded: Number.isSafeInteger(result), executor }));+ `);+ assert.equal(claim.code, 0, 'the native replica synchronizes the request and records one elected executor');+ assert.equal(claim.document.claimRecorded, true);+ const record = requestRecord(box.root, requestId);+ assert.ok(record?.executor, 'the sequence-two claim receipt elected a native request executor');+ assert.equal(record.sequence, 1, 'the authenticated request is the first ordered position');+ const claimedBoard = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ try { assert.equal(appliedSequence(claimedBoard), 2, 'the elected executor claim is acknowledged at sequence two'); }+ finally { store.closeBoard(claimedBoard); }++ const otherMachine = await fetch(box.origin + '/auth/machines', {+ method: 'POST',+ headers: { authorization: 'Bearer ' + phone.token, 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) },+ body: JSON.stringify({ board: link.board, machine: 'race-winning-machine' }),+ });+ assert.equal(otherMachine.status, 201, 'the real phone session authorizes an independent board-scoped PM');+ const otherMachineDocument = await otherMachine.json();+ assert.equal(otherMachineDocument.board, link.board);+ assert.equal(otherMachineDocument.machine, 'race-winning-machine');+ assert.equal(/^pm_[A-Za-z0-9_-]{43}$/u.test(otherMachineDocument.token ?? ''), true,+ 'the independent credential is a real board-scoped machine token');++ const competingBoard = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ let competingMove;+ try {+ competingMove = prepareEngineMove(competingBoard, 'shout', [{+ from: 'person', to: record.move.args.to, text: record.move.args.text, lanes: [],+ }], { id: 'phone-race-winning-execution' });+ competingMove.personRequest = {+ id: record.id, executor: record.executor, phase: 'execute', digest: requestIntentDigest(record),+ };+ } finally { store.closeBoard(competingBoard); }+ const competingCiphertext = Buffer.from(await seal(boardKey, new TextEncoder().encode(JSON.stringify(competingMove)), {+ boardId: link.board, kind: 'move', sequence: 3,+ })).toString('base64url');+ let competingStatus;+ let competingSequence;+ box.beforeNextMove(async () => {+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/moves', {+ method: 'POST',+ headers: { authorization: 'Bearer ' + otherMachineDocument.token, 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) },+ body: JSON.stringify({ sequence: 3, sealed: competingCiphertext }),+ });+ competingStatus = response.status;+ const document = await response.json();+ competingSequence = document.event?.event_id;+ });++ const movePostPath = `/api/v1/boards/${link.board}/moves`;+ const postsBefore = box.calls.filter(call => call.method === 'POST' && call.path === movePostPath).length;+ const execution = await box.script(`+ import { readFileSync } from 'node:fs';+ import { join } from 'node:path';+ import { relayOperation, syncRelay } from ${JSON.stringify(RELAY_MODULE)};+ import { Refused } from ${JSON.stringify(pathToFileURL(resolve(import.meta.dirname, '../src/refused.js')).href)};+ const root = process.cwd();+ const sink = { write() {} };+ const io = { cwd: root, stdout: sink, stderr: sink, say() {}, err() {}, onEvent() {} };+ await syncRelay(root, io);+ let refusal = null;+ try {+ await relayOperation(root, 'shout', [{ from: 'person', to: 'coordinator', text: 'PHONE_RACE_SHOUT_ONCE', lanes: [] }], {+ ...io,+ personRequest: { id: ${JSON.stringify(requestId)}, executor: ${JSON.stringify(record.executor)}, phase: 'execute', digest: ${JSON.stringify(requestIntentDigest(record))} },+ personRequestMoveId: 'native-race-execution-${requestId}',+ });+ } catch (error) {+ if (!(error instanceof Refused)) throw error;+ refusal = error.code;+ }+ const state = JSON.parse(readFileSync(${JSON.stringify(box.linkFile)}, 'utf8'));+ process.stdout.write(JSON.stringify({ refusal, pendingCleared: state.pending === undefined }));+ `);+ assert.equal(execution.code, 0, 'the native process completes the real relay race without an unhandled failure');+ assert.equal(competingStatus, 200, 'the competing authenticated machine wins the request at sequence three');+ assert.equal(competingSequence, 3);+ assert.equal(execution.document.refusal, 'RELAY_PERSON_ONLY', 'the elected native receipt reports its original sender refusal');+ assert.equal(execution.document.pendingCleared, true, 'the matching durable sender-refusal receipt clears pending state');+ const postsAfter = box.calls.filter(call => call.method === 'POST' && call.path === movePostPath).length;+ assert.equal(postsAfter - postsBefore, 3, 'the race uses winner, collision and one refused retry posts, not an unbounded resend loop');++ const ordinary = await box.script(`+ import { relayOperation } from ${JSON.stringify(RELAY_MODULE)};+ const root = process.cwd();+ const sink = { write() {} };+ const io = { cwd: root, stdout: sink, stderr: sink, say() {}, err() {}, onEvent() {} };+ const result = await relayOperation(root, 'shout', [{ from: 'coordinator', to: 'all', text: 'ordinary agent shout after phone race', lanes: [] }], io);+ process.stdout.write(JSON.stringify({ acknowledged: Number.isSafeInteger(result) }));+ `);+ assert.equal(ordinary.code, 0, 'the native machine remains able to issue ordinary agent work');+ assert.equal(ordinary.document.acknowledged, true);++ const verified = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ try {+ assert.equal(appliedSequence(verified), 5, 'the winner, refusal and later agent move each consume one relay position');+ assert.equal(verified.db.prepare('SELECT COUNT(*) AS count FROM shout WHERE shout_from=? AND shout_text=?').get('person', 'PHONE_RACE_SHOUT_ONCE').count,+ 1, 'only the winning phone-authorized execution creates the requested person shout');+ } finally { store.closeBoard(verified); }+});diff --git a/test/relay-machine-receipts.test.js b/test/relay-machine-receipts.test.jsnew file mode 100644index 00000000..c23f64bb--- /dev/null+++ b/test/relay-machine-receipts.test.js@@ -0,0 +1,115 @@+/** Machine execution can fulfil only an earlier phone's literal intent on every replica [H12,H16,B26]. */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { appliedSequence, applyRelayMove, prepareEngineMove } from '../src/engine.js';+import { preparePersonRequest } from '../src/person-request.js';+import { personRequestRecords, receivePersonRequest, requestIntentDigest, requestStageText } from '../src/relay-requests.js';++const at = '2026-10-09T21:00:00.000Z';+const phone = { kind: 'person', userId: 'private-person' };+const machine = { kind: 'machine', userId: 'private-person', machine: 'private-machine' };++/** Keep two real SQLite replicas at the same ordered prefix and compare all replay outcomes. */+function replicas(t) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-machine-receipts-'));+ const boards = ['first', 'second'].map(name => {+ const board = store.openBoard(join(directory, name + '.sqlite'), { now: () => new Date(at) });+ store.ensureCoordinator(board, '/private/coordinator');+ return board;+ });+ t.after(() => { for (const board of boards) store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); });+ return {+ boards,+ /** Deliver the same authenticated phone document to both durable replicas. */+ intake(document, sender = phone) {+ return boards.map(board => receivePersonRequest(board, document, { sequence: appliedSequence(board) + 1, at, sender }));+ },+ /** Apply one machine move in order and require equal authorization outcomes. */+ apply(move) {+ const outcomes = boards.map(board => applyRelayMove(board, move, { sequence: appliedSequence(board) + 1, at, sender: machine, kind: 'move' }));+ assert.deepEqual(outcomes[0], outcomes[1], 'independent replicas reach the same authorization result');+ return outcomes[0];+ },+ };+}++/** Build the exact fixed stage receipt using the authenticated request's digest. */+function stage(board, document, phase = 'claim') {+ const record = personRequestRecords(board).find(row => row.id === document.id);+ const move = prepareEngineMove(board, 'shout', [{ from: 'person', to: 'coordinator', text: requestStageText(record, phase), lanes: [], ...(phase === 'repo-request' ? { request: true } : {}) }]);+ move.personRequest = { id: document.id, executor: 'private-executor', phase, digest: requestIntentDigest(record) };+ return move;+}++/** Attach the earlier request binding to a new ordinary executable move. */+function execution(board, document, operation, args) {+ const move = prepareEngineMove(board, operation, args);+ move.personRequest = { ...stage(board, document).personRequest, phase: 'execute' };+ return move;+}++test('machine receipts cannot invent, alter, redirect or repeat a phone action on two replicas [H12,H16,B26]', t => {+ const box = replicas(t);+ const board = box.boards[0];+ const document = preparePersonRequest({ verb: 'shout', args: { to: 'coordinator', text: 'Phone approved this literal text' } }, 'phone-intent');+ const absent = prepareEngineMove(board, 'shout', [{ from: 'person', to: 'coordinator', text: 'invented person text', lanes: [] }]);+ assert.equal(box.apply(absent).error?.code, 'RELAY_PERSON_ONLY');+ absent.id = 'missing-request'; absent.personRequest = { id: document.id, executor: 'private-executor', phase: 'execute', digest: '0'.repeat(64) };+ assert.equal(box.apply(absent).error?.code, 'RELAY_PERSON_ONLY');+ box.intake(document);+ const badDigest = stage(board, document); badDigest.personRequest.digest = '0'.repeat(64);+ assert.equal(box.apply(badDigest).error?.code, 'RELAY_PERSON_ONLY');+ const extraText = stage(board, document); extraText.args[0].text += ' unrelated person instruction';+ assert.equal(box.apply(extraText).error?.code, 'RELAY_PERSON_ONLY');+ const decisionFlag = stage(board, document); decisionFlag.args[0].decision = true;+ assert.equal(box.apply(decisionFlag).error?.code, 'RELAY_PERSON_ONLY');+ const requestFlag = stage(board, document); requestFlag.args[0].request = true;+ assert.equal(box.apply(requestFlag).error?.code, 'RELAY_PERSON_ONLY');+ assert.ok(box.apply(stage(board, document)).result);+ for (const change of [{ text: 'different literal text' }, { to: 'all' }, { decision: true }, { request: true }]) {+ const move = execution(board, document, 'shout', [{ from: 'person', to: 'coordinator', text: document.move.args.text, lanes: [], ...change }]);+ assert.equal(box.apply(move).error?.code, 'RELAY_PERSON_ONLY', 'a valid digest never authorizes changed intent');+ }+ assert.ok(box.apply(execution(board, document, 'shout', [{ from: 'person', to: 'coordinator', text: document.move.args.text, lanes: [] }])).result);+ assert.equal(box.apply(execution(board, document, 'shout', [{ from: 'person', to: 'coordinator', text: document.move.args.text, lanes: [] }])).error?.code, 'RELAY_PERSON_ONLY');+ for (const replica of box.boards) assert.equal(replica.db.prepare('SELECT count(*) AS n FROM shout WHERE shout_text=?').get(document.move.args.text).n, 1);+ const refusal = preparePersonRequest({ verb: 'shout', args: { to: 'coordinator', text: 'Phone intent that may be refused' } }, 'refusal-intent');+ box.intake(refusal);+ assert.ok(box.apply(stage(board, refusal)).result);+ const forgedRefusal = stage(board, refusal, 'refuse');+ forgedRefusal.personRequest.error = { code: 'CHECK_FAILED', message: 'unrelated person instruction', next: 'retry the original intent' };+ forgedRefusal.args[0].text = 'View request ' + refusal.id + ': [CHECK_FAILED] unrelated person instruction';+ assert.equal(box.apply(forgedRefusal).error?.code, 'RELAY_PERSON_ONLY', 'dynamic refusal details cannot authorize unrelated person shout text');+ const fixedRefusal = stage(board, refusal, 'refuse');+ fixedRefusal.personRequest.error = forgedRefusal.personRequest.error;+ assert.ok(box.apply(fixedRefusal).result, 'the fixed refusal receipt preserves structured CLI error details');+ for (const replica of box.boards) {+ assert.deepEqual(personRequestRecords(replica).find(record => record.id === refusal.id).error, fixedRefusal.personRequest.error);+ assert.equal(replica.db.prepare('SELECT count(*) AS n FROM shout WHERE shout_text=?').get(forgedRefusal.args[0].text).n, 0);+ }++});++test('a waiting row decision has one machine execution and one fixed coordinator request [H12,H16,B26]', t => {+ const box = replicas(t);+ const board = box.boards[0];+ const document = preparePersonRequest({ verb: 'spec-approve', args: { ids: 'G1', text: 'A precise phone choice' } }, 'row-intent');+ box.intake(document);+ assert.ok(box.apply(stage(board, document)).result);+ const row = { kind: 'spec', id: 'G1', file: 'SPEC.md', source: '- G1 [draft, must] A precise phone choice | gate: review',+ replacement: '- G1 [approved, must] A precise phone choice | gate: review', text: 'A precise phone choice', decision: 'approve', by: 'person' };+ const wrong = execution(board, document, 'recordRowDecisions', [{ agentId: 'person', channel: 'view', decisions: [{ ...row, id: 'G2' }] }]);+ assert.equal(box.apply(wrong).error?.code, 'RELAY_PERSON_ONLY');+ const approved = execution(board, document, 'recordRowDecisions', [{ agentId: 'person', channel: 'view', decisions: [row] }]);+ const result = box.apply(approved);+ assert.ok(result.result, 'the genuine phone row choice is recorded');+ assert.equal(personRequestRecords(board).find(record => record.id === document.id).status, 'waiting');+ assert.equal(box.apply(execution(board, document, 'recordRowDecisions', [{ agentId: 'person', channel: 'view', decisions: [row] }])).error?.code, 'RELAY_PERSON_ONLY', 'waiting for repository application cannot authorize a second approval');+ assert.ok(box.apply(stage(board, document, 'repo-request')).result);+ assert.equal(box.apply(stage(board, document, 'repo-request')).error?.code, 'RELAY_PERSON_ONLY');+ for (const replica of box.boards) assert.equal(store.rowDecisions(replica).length, 1);+});diff --git a/test/relay-machine-storage.test.js b/test/relay-machine-storage.test.jsnew file mode 100644index 00000000..4724098b--- /dev/null+++ b/test/relay-machine-storage.test.js@@ -0,0 +1,86 @@+/** Legacy person credentials are removed rather than loaded by native or agent work [H15,H16,B26]. */+import assert from 'node:assert/strict';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { test } from 'node:test';+import { relayClientFixture } from './relay-client-fixture.js';++const APPROVAL_MODULE = new URL('../src/relay-approval.js', import.meta.url).href;+const MACHINE_MODULE = new URL('../src/relay-machine.js', import.meta.url).href;++test('legacy machine and board sessions are scrubbed before an agent read or fresh sign-in [H15,H16,B26]', async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const original = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const phone = await box.phoneSession();+ const machineDirectory = join(box.env.PULLBOARD_HOME, 'relay-machine');+ const machineFile = join(machineDirectory, 'state.json');+ const legacy = { v: 1, autoLink: true, session: { token: phone.token, account: original.account, url: box.origin },+ devices: [], excluded: [join(box.root, 'excluded')], pending: null, revocations: [] };+ mkdirSync(machineDirectory, { recursive: true, mode: 0o700 });+ writeFileSync(machineFile, JSON.stringify(legacy), { mode: 0o600 });+ const machineFragment = join(machineDirectory, 'state.1234.abcd-1234.tmp');+ writeFileSync(machineFragment, JSON.stringify(legacy), { mode: 0o600 });+ const linkFragment = box.linkFile + '.abcd-1234.tmp';+ writeFileSync(linkFragment, JSON.stringify({ ...original, token: phone.token }), { mode: 0o600 });+ writeFileSync(box.linkFile, JSON.stringify({ ...original, token: phone.token, tokenId: phone.id }), { mode: 0o600 });+ const legacyFile = join(box.env.PULLBOARD_HOME, 'relay-keys', original.board + '.session.json');+ const otherLegacyFile = join(box.env.PULLBOARD_HOME, 'relay-keys', 'f'.repeat(32) + '.session.json.1234-abcd.tmp');+ writeFileSync(legacyFile, JSON.stringify({ v: 1, token: phone.token, id: phone.id, url: box.origin }), { mode: 0o600 });+ writeFileSync(otherLegacyFile, phone.token, { mode: 0o600 });+ const keyBefore = readFileSync(box.keyFile);+ const agentRead = await box.script(`+ import { readRelayMachine } from ${JSON.stringify(MACHINE_MODULE)};+ process.env.AI_AGENT = '1'; process.env.CODEX_SHELL = '1'; process.env.SSH_CONNECTION = '127.0.0.1 1 127.0.0.1 2';+ const state = readRelayMachine();+ process.stdout.write(JSON.stringify({ version: state.v, noSession: !Object.hasOwn(state, 'session'),+ owner: state.owner, machine: state.machine, excluded: state.excluded }));+ `);+ assert.equal(agentRead.code, 0);+ assert.equal(agentRead.document.version, 2);+ assert.equal(agentRead.document.noSession, true, 'an agent never receives the retired machine person session');+ assert.deepEqual(agentRead.document.owner, { account: original.account, url: box.origin });+ assert.match(agentRead.document.machine, /^machine-[0-9a-f-]+$/u);+ assert.deepEqual(agentRead.document.excluded, legacy.excluded, 'migration retains the explicit local opt-out');+ assert.equal(readFileSync(machineFile).includes(phone.token), false, 'machine metadata no longer contains a person bearer');+ assert.equal(existsSync(legacyFile), false, 'the rejected per-board session store is deleted without hydration');+ assert.equal(existsSync(otherLegacyFile), false, 'a retired atomic-write session fragment is deleted too');+ assert.equal(existsSync(machineFragment), false, 'a crashed legacy machine write cannot retain person authority');+ assert.deepEqual(readFileSync(box.keyFile), keyBefore, 'scrubbing person sessions preserves the paired board key');+ const status = await box.cli('status');+ assert.equal(status.code, 0, 'the board remains readable while foreground reauthentication is required');+ assert.equal(existsSync(linkFragment), false, 'the link lock removes a crashed legacy person-bearing write');+ const scrubbed = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ assert.equal(scrubbed.token, null);+ assert.equal(scrubbed.tokenId, undefined);+ assert.equal(scrubbed.personReauth, true);+ assert.equal(readFileSync(box.linkFile).includes(phone.token), false, 'the old Git-directory person bearer is atomically removed');+ assert.equal((await box.cli('relay', 'on', '--url', box.origin)).code, 0, 'fresh foreground sign-in restores only machine authority');+ const replacement = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ assert.equal(replacement.machine, agentRead.document.machine, 'the migrated machine identity remains stable');+ assert.equal(/^pm_[A-Za-z0-9_-]{43}$/u.test(replacement.token), true);++ // The rejected session-file design had no token field in relay.json: migrate that format too.+ const noToken = { ...replacement };+ delete noToken.token; delete noToken.tokenId;+ writeFileSync(box.linkFile, JSON.stringify(noToken), { mode: 0o600 });+ writeFileSync(legacyFile, JSON.stringify({ v: 1, token: phone.token, id: phone.id, url: box.origin }), { mode: 0o600 });+ assert.equal((await box.cli('status')).code, 0, 'the session-file-era link migrates without loading its credential');+ assert.equal(existsSync(legacyFile), false);+ assert.equal(JSON.parse(readFileSync(box.linkFile, 'utf8')).personReauth, true);+ assert.equal((await box.cli('relay', 'on', '--url', box.origin)).code, 0);+ const safeMachine = readFileSync(machineFile);+ const refusedDurableGrant = await box.script(`+ import { updateRelayMachine } from ${JSON.stringify(MACHINE_MODULE)};+ const { createApprovalReply } = await import(${JSON.stringify(APPROVAL_MODULE)});+ const reply = await createApprovalReply({ link: true });+ let code;+ try { updateRelayMachine(state => { state.approvals.push({ root: process.cwd(), publisherRoot: process.cwd(), published: false, sealed: 'AQ', replyKey: reply.storedKey,+ context: { id: 'native-action-cannot-persist', account: ${JSON.stringify(original.account)}, publisher: ${JSON.stringify(original.board)}, board: ${JSON.stringify(original.board)},+ device: 'device-' + 'd'.repeat(32), action: 'revoke-token', target: 'some-agent-token', machine: state.machine, command: 'pullboard relay revoke some-agent-token', expires: Date.now() + 600000 } }); }); }+ catch (error) { code = error.code; }+ process.stdout.write(JSON.stringify({ code }));+ `);+ assert.equal(refusedDurableGrant.document.code, 'RELAY_MACHINE_STORAGE', 'durable proposals accept only non-person board-link replies');+ assert.deepEqual(readFileSync(machineFile), safeMachine, 'invalid person-action metadata cannot replace the trusted machine state');+});diff --git a/test/relay-person-actions.test.js b/test/relay-person-actions.test.jsindex b9446e14..3e706c2d 100644--- a/test/relay-person-actions.test.js+++ b/test/relay-person-actions.test.js@@ -16,7 +16,7 @@ import { relayClientFixture } from './relay-client-fixture.js';async function signIn(chrome, box) {const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));const result = await chrome.send('Network.setCookie', {- name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',});assert.equal(result.success, true);}diff --git a/test/relay-person-credential.test.js b/test/relay-person-credential.test.jsnew file mode 100644index 00000000..6148ac89--- /dev/null+++ b/test/relay-person-credential.test.js@@ -0,0 +1,204 @@+/** Same-user agents keep working while only the paired phone holds person authority [H5,H16,H17,B26]. */+import assert from 'node:assert/strict';+import { spawn, spawnSync } from 'node:child_process';+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { test } from 'node:test';+import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { relayClientFixture } from './relay-client-fixture.js';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';++const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');++/** Run a real native command while allowing a phone tap before the foreground process finishes. */+function command(root, environment, args) {+ const child = spawn(process.execPath, [CLI, ...args, '--json'], { cwd: root, env: environment, stdio: ['ignore', 'pipe', 'pipe'] });+ let output = '';+ child.stdout.setEncoding('utf8').on('data', part => { output += part; });+ child.stderr.resume();+ const done = new Promise((resolveResult, reject) => {+ child.once('error', reject);+ child.once('close', (code, signal) => {+ if (signal) return reject(new Error('private native command ended with ' + signal));+ try { resolveResult({ code, document: JSON.parse(output) }); }+ catch { reject(new Error('private native command returned invalid JSON for ' + args[0])); }+ });+ });+ return { child, done };+}++/** Poll an actual persisted or HTTP-observed condition without retrying a move. */+async function waitFor(read, message, milliseconds = 30000) {+ const deadline = Date.now() + milliseconds;+ do {+ const value = await read();+ if (value) return value;+ await new Promise(resolve => { setTimeout(resolve, 25); });+ } while (Date.now() < deadline);+ assert.fail(message);+}++/** Inspect every regular client file without following symlinks outside the private fixture. */+function assertNoPersonPower(directory) {+ for (const name of readdirSync(directory)) {+ const path = join(directory, name);+ const stat = lstatSync(path);+ if (stat.isDirectory()) assertNoPersonPower(path);+ else if (stat.isFile()) assert.equal(/(?:ps_|pg_)[A-Za-z0-9_-]{43}/u.test(readFileSync(path).toString('latin1')), false,+ 'no client file stores a person session or native grant');+ }+}++/** Run actual private Git with fixed identity and no credential-bearing diagnostics. */+function git(root, env, ...args) {+ const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });+ assert.equal(result.status, 0, 'private Git ' + args[0] + ' succeeds: ' + result.stderr.replace(/(?:ps_|pm_|pa_|pg_)[A-Za-z0-9_-]{43}/gu, '[private credential]'));+ return result.stdout.trim();+}++test('same-user agents never act as their person while the phone approves native actions [H5,H16,H17,B26]', {+ timeout: 180000,+}, async t => {+ assert.ok(findChromeExecutable(), 'the security proof requires actual Chrome');+ const box = await relayClientFixture(t);+ symlinkSync('/bin/sh', join(box.env.PATH, 'sh'));+ writeFileSync(join(box.env.PATH, 'pullboard'), '#!/bin/sh\nexec node ' + "'" + CLI.replaceAll("'", "'\\''") + "'" + ' "$@"\n', { mode: 0o700 });+ const personEnv = { ...box.env };+ for (const key of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete personEnv[key];+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');+ const fixtureSource = join(box.root, 'src/security-fixture.js');+ mkdirSync(join(box.root, 'src'), { recursive: true });+ writeFileSync(fixtureSource, 'export const ready = true;\n');+ const configFile = join(box.root, 'pullboard.json');+ const config = JSON.parse(readFileSync(configFile, 'utf8'));+ const buildLane = 'core';+ config.lanes[buildLane] = { owns: ['src/'], specs: ['G'] };+ config.gate = 'node --check src/security-fixture.js';+ writeFileSync(configFile, JSON.stringify(config, null, 2) + '\n');+ writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8') + '\n- G1 [approved, must] A private security fixture parses. | gate: node --check src/security-fixture.js\n');+ git(box.root, personEnv, 'add', '-A');+ git(box.root, personEnv, 'commit', '-q', '-m', 'test(fixture): prepare native security proof [G1]');+ const item = await box.cli('add', buildLane, 'native scoped work', '--specs', 'G1', '--criterion', 'the private source parses');+ assert.equal(item.code, 0);+ const itemId = item.document.item.item_id;++ const setup = command(box.root, personEnv, ['relay', 'on', '--all', '--url', box.origin]);+ t.after(async () => { if (setup.child.exitCode === null) setup.child.kill('SIGTERM'); await setup.done.catch(() => {}); });+ const pending = await waitFor(() => existsSync(machineFile) && JSON.parse(readFileSync(machineFile)).pending,+ 'foreground setup publishes the one-use phone enrollment');+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const phone = await box.phoneSession();+ await chrome.send('Network.setCookie', { name: 'pb_session', value: phone.token, url: box.origin, httpOnly: true, sameSite: 'Lax' });+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);+ assert.equal((await setup.done).code, 0, 'one foreground sign-in links and pairs without saving the session');+ await chrome.waitFor("document.querySelector('#phone-approvals') !== null");+ const machine = JSON.parse(readFileSync(machineFile));+ const link = JSON.parse(readFileSync(box.linkFile));+ assert.match(link.token, /^pm_[A-Za-z0-9_-]{43}$/u);+ assert.equal(Object.hasOwn(machine, 'session'), false);+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);++ const joined = await command(box.root, personEnv, ['worktree', buildLane]).done;+ assert.equal(joined.code, 0, 'machine credential enrolls the real agent without a tap: ' + joined.document.error?.code + ' ' + joined.document.error?.message);+ const agentRoot = joined.document.path;+ const agentId = joined.document.agent;+ const agentEnv = { ...personEnv, AI_AGENT: '1', CODEX_SHELL: '1', CODEX_THREAD_ID: 'private-security-agent', SSH_CONNECTION: '127.0.0.1 1 127.0.0.1 2' };+ const approvedBefore = box.calls.filter(call => call.path.endsWith('/authorize')).length;+ const claim = await command(agentRoot, agentEnv, ['claim', String(itemId)]).done;+ assert.equal(claim.code, 0, 'the SSH agent claims with its own PA while the phone remains active');+ writeFileSync(join(agentRoot, 'src/security-fixture.js'), 'export const ready = true;\nexport const built = true;\n');+ git(agentRoot, agentEnv, 'add', 'src/security-fixture.js');+ git(agentRoot, agentEnv, 'commit', '-q', '-m', 'feat(fixture): prove scoped agent submit [G1]');+ const submitted = await command(agentRoot, agentEnv, ['submit', String(itemId)]).done;+ assert.equal(submitted.code, 0, 'the SSH agent submits a clean native commit with its gate green');+ assert.equal((await command(agentRoot, agentEnv, ['shout', 'coordinator', 'scoped agent completed its work']).done).code, 0);+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, approvedBefore, 'agent enroll/claim/submit/shout asks for no phone approval');+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);+ const state = JSON.parse(readFileSync(box.linkFile));+ const pa = state.agentTokens[agentId];+ assert.match(pa.token, /^pa_[A-Za-z0-9_-]{43}$/u);+ const listed = await command(agentRoot, agentEnv, ['relay', 'tokens']).done;+ assert.equal(listed.code, 0, 'board-scoped token ids need no tap');+ assert.equal(listed.document.tokens.some(row => Object.hasOwn(row, 'token') || Object.hasOwn(row, 'hash')), false);+ const nativeCalls = box.calls.filter(call => !call.browser).length;+ const denied = await command(agentRoot, agentEnv, ['relay', 'revoke', machine.devices[0].deviceId]).done;+ assert.equal(denied.code, 1);+ assert.equal(denied.document.error.code, 'B26_PERSON_CHANNEL');+ assert.equal(box.calls.filter(call => !call.browser).length, nativeCalls, 'an agent shell refuses before every approval/network request');++ await t.test('saved PM and PA never acquire HTTP person authority [H16,B26]', async () => {+ const other = await box.additionalBoard('independent board remains private');+ for (const token of [state.token, pa.token]) {+ const headers = { authorization: 'Bearer ' + token, 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) };+ const inventory = await fetch(box.origin + '/auth/boards', { headers });+ assert.equal(inventory.status, 200);+ assert.deepEqual((await inventory.json()).boards.map(value => value.id), [state.board]);+ for (const [path, body, method = 'POST'] of [+ ['/auth/boards/link', { board: 'c'.repeat(32), repository: 'fixture/repository' }],+ ['/auth/machines', { board: state.board, machine: 'forged-machine' }],+ ['/auth/tokens/revoke', { id: phone.id }],+ ['/auth/tokens', { board: other.id, agent: 'cross-board' }],+ ['/api/v1/boards/' + state.board + '/requests', { sequence: 1, sealed: 'AA' }],+ ['/api/v1/devices/' + machine.devices[0].deviceId, undefined, 'DELETE'],+ ['/api/v1/boards/' + other.id + '/state', undefined, 'GET'],+ ]) {+ const response = await fetch(box.origin + path, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}) });+ assert.ok(response.status >= 400 && response.status < 500, 'a stored credential cannot exercise ' + method + ' ' + path);+ }+ const cookie = await fetch(box.origin + '/auth/boards', { headers: { cookie: 'pb_session=' + token } });+ assert.equal(cookie.status, 401, 'a saved delegate cannot become the phone cookie');+ }+ });++ await t.test('the paired phone still sends person intent through the actual page [H12,H16,B26]', async () => {+ await chrome.navigate(box.origin + '/#board=' + state.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());+ await chrome.waitFor('typeof data !== "undefined" && !!data?.project && !!transport');+ await chrome.evaluate(`document.querySelector('[data-tab=shouts]').click(); document.querySelector('#shout-to').value='coordinator'; document.querySelector('#shout-text').value='PRIVATE_PHONE_PERSON_ACTION'; document.querySelector('#shout-form').requestSubmit(); true`);+ await chrome.waitFor('data.project.personRequests?.some(row => row.move?.args?.text === "PRIVATE_PHONE_PERSON_ACTION")');+ assert.equal((await command(agentRoot, agentEnv, ['status']).done).code, 0, 'the native machine fulfils the ordered phone request while the agent keeps working');+ const exported = await command(box.root, personEnv, ['export']).done;+ assert.equal(exported.code, 0);+ assert.equal(exported.document.tables.shout.filter(row => row.shout_from === 'person' && row.shout_text === 'PRIVATE_PHONE_PERSON_ACTION').length, 1);+ assertNoPersonPower(box.root); assertNoPersonPower(agentRoot); assertNoPersonPower(box.env.HOME);+ });++ await t.test('native token revocation needs exactly one phone tap and the grant cannot replay [H16,B26]', async () => {+ const revoke = command(box.root, personEnv, ['relay', 'revoke', pa.id]);+ t.after(async () => { if (revoke.child.exitCode === null) revoke.child.kill('SIGTERM'); await revoke.done.catch(() => {}); });+ await chrome.waitFor("[...document.querySelectorAll('.phone-approval')].some(node => node.textContent.includes(" + JSON.stringify(pa.id) + '))');+ const before = box.calls.filter(call => call.path.endsWith('/authorize')).length;+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);+ await chrome.evaluate("[...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(" + JSON.stringify(pa.id) + ')).querySelector("button").click()');+ assert.equal((await revoke.done).code, 0);+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, before + 1, 'one tap issues one grant');+ const execution = box.transit.findLast(record => record.path.endsWith('/execute'));+ const replay = await fetch(box.origin + execution.path, { method: 'POST', headers: { authorization: 'Bearer ' + state.token,+ 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) }, body: execution.request });+ assert.notEqual(replay.status, 200, 'the exact already consumed grant refuses replay');+ assert.equal((await replay.json()).error.code, 'PHONE_APPROVAL_USED');+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);+ });+ await t.test('native device revocation needs one phone tap and offline agent unlink always works [H5,H16,H17,B26]', async () => {+ const target = machine.devices[0].deviceId;+ const revoke = command(box.root, personEnv, ['relay', 'revoke', target]);+ t.after(async () => { if (revoke.child.exitCode === null) revoke.child.kill('SIGTERM'); await revoke.done.catch(() => {}); });+ await chrome.waitFor("[...document.querySelectorAll('.phone-approval')].some(node => node.textContent.includes(" + JSON.stringify(target) + '))');+ const before = box.calls.filter(call => call.path.endsWith('/authorize')).length;+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);+ await chrome.evaluate("[...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(" + JSON.stringify(target) + ')).querySelector("button").click()');+ assert.equal((await revoke.done).code, 0);+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, before + 1);+ assert.equal(JSON.parse(readFileSync(machineFile)).devices.length, 0);+ await box.stopRelay();+ const calls = box.calls.length;+ const off = await command(agentRoot, agentEnv, ['relay', 'off']).done;+ assert.equal(off.code, 0, 'an offline SSH agent can always stop local syncing');+ assert.equal(existsSync(box.linkFile), false);+ assert.match(off.document.notice, /relay copy stays until you approve/u);+ assert.equal(box.calls.length, calls, 'local unlink needs no reachable relay and no phone tap');+ assertNoPersonPower(box.root); assertNoPersonPower(agentRoot); assertNoPersonPower(box.env.HOME);+ });++});diff --git a/test/relay-person-outbox.test.js b/test/relay-person-outbox.test.jsindex fc771495..8223b275 100644--- a/test/relay-person-outbox.test.js+++ b/test/relay-person-outbox.test.js@@ -9,7 +9,7 @@ import { relayClientFixture } from './relay-client-fixture.js';async function signIn(chrome, box) {const session = JSON.parse(readFileSync(box.linkFile, 'utf8'));const result = await chrome.send('Network.setCookie', {- name: 'pb_session', value: session.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',});assert.equal(result.success, true);}diff --git a/test/relay-person-page.test.js b/test/relay-person-page.test.jsindex 962fc535..90af54c5 100644--- a/test/relay-person-page.test.js+++ b/test/relay-person-page.test.js@@ -17,7 +17,7 @@ test('the actual relay page seals its shout and refuses generic direct moves [H1const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));const chrome = await startChrome();t.after(() => chrome.close());- const cookie = await chrome.send('Network.setCookie', { name: 'pb_session', value: link.token, url: box.origin, httpOnly: true, sameSite: 'Lax' });+ const cookie = await chrome.send('Network.setCookie', { name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax' });assert.equal(cookie.success, true);await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());await chrome.waitFor('typeof data !== "undefined" && !!data?.project && !!transport');diff --git a/test/relay-person-recovery.test.js b/test/relay-person-recovery.test.jsindex b8937491..03a627cc 100644--- a/test/relay-person-recovery.test.js+++ b/test/relay-person-recovery.test.js@@ -7,7 +7,8 @@ import { pathToFileURL } from 'node:url';import { test } from 'node:test';import * as store from '../src/board.js';import { preparePersonRequest } from '../src/person-request.js';-import { personRequestRecords, personRequestStatuses } from '../src/relay-requests.js';+import { personRequestRecords, personRequestStatuses, requestIntentDigest } from '../src/relay-requests.js';+import { ENGINE_VERSION } from '../src/machine.js';import { decodeBoardKey, seal } from '../src/seal.js';import { relayClientFixture } from './relay-client-fixture.js';@@ -16,6 +17,7 @@ const BOARD_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/board.jsconst EXCHANGE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/exchange.js')).href;const RELAY_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/relay.js')).href;const CONFIG_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/config.js')).href;+const REQUESTS_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/relay-requests.js')).href;const LANES_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/lanes.js')).href;/** Run an isolated fixture child without copying its private output into assertion diagnostics. */@@ -44,16 +46,22 @@ function claimOnly(root, env, requestId) {const source = `const root = process.cwd();const { syncRelay, relayRequestDevice, relayOperation } = await import(${JSON.stringify(RELAY_MODULE)});+ const { personRequestRecords, requestIntentDigest, requestStageText } = await import(${JSON.stringify(REQUESTS_MODULE)});+ const { openBoard, closeBoard } = await import(${JSON.stringify(BOARD_MODULE)});const { loadConfig } = await import(${JSON.stringify(CONFIG_MODULE)});const { laneNames } = await import(${JSON.stringify(LANES_MODULE)});const sink = { isTTY: false, write() {} };const io = { cwd: root, stdout: sink, stderr: sink, say() {}, err() {}, onEvent() {} };await syncRelay(root, io);const executor = await relayRequestDevice(root);- const message = { from: 'person', to: 'coordinator', text: ${JSON.stringify(`View request ${requestId}: Received a request from the paired view.`)}, lanes: laneNames(loadConfig(root)) };+ const board = openBoard(${JSON.stringify(join(root, '.git', 'pullboard', 'board.sqlite'))});+ let record;+ try { record = personRequestRecords(board).find(entry => entry.id === ${JSON.stringify(requestId)} && !entry.duplicateOf); }+ finally { closeBoard(board); }+ const message = { from: 'person', to: 'coordinator', text: requestStageText(record, 'claim'), lanes: laneNames(loadConfig(root)) };const result = await relayOperation(root, 'shout', [message], {...io,- personRequest: { id: ${JSON.stringify(requestId)}, executor, phase: 'claim' },+ personRequest: { id: ${JSON.stringify(requestId)}, executor, phase: 'claim', digest: requestIntentDigest(record) },personRequestMoveId: 'recovery-' + ${JSON.stringify(requestId)} + '-' + executor,});process.stdout.write(JSON.stringify({ executor, result: Number.isSafeInteger(result) }));@@ -76,6 +84,7 @@ test('[H12,H16] an expired native executor lease transfers once and the old deviconst box = await relayClientFixture(t);await box.link();const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const phone = await box.phoneSession();const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());const requestId = 'takeover-request-1';const intent = preparePersonRequest({ verb: 'shout', args: { to: 'coordinator', text: 'RECOVERY_SHOUT_ONCE' } }, requestId);@@ -85,7 +94,7 @@ test('[H12,H16] an expired native executor lease transfers once and the old deviconst envelope = Buffer.from(envelopeBytes).toString('base64url');const posted = await fetch(box.origin + '/api/v1/boards/' + link.board + '/requests', {method: 'POST',- headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },+ headers: { authorization: 'Bearer ' + phone.token, 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) },body: JSON.stringify({ sequence: 1, sealed: envelope }),});assert.equal(posted.status, 200, 'the relay accepts the browser-format sealed request through the fixture person session');@@ -117,6 +126,17 @@ test('[H12,H16] an expired native executor lease transfers once and the old deviconst secondState = JSON.parse(readFileSync(box.linkFile, 'utf8'));delete secondState.requestDevice;+ const secondMachine = await fetch(box.origin + '/auth/machines', {+ method: 'POST', headers: { authorization: 'Bearer ' + phone.token, 'content-type': 'application/json' },+ body: JSON.stringify({ board: link.board, machine: 'request-recovery-second-machine' }),+ });+ assert.equal(secondMachine.status, 201, 'the phone provisions an independently bound machine delegate');+ const delegate = await secondMachine.json();+ secondState.token = delegate.token;+ secondState.tokenId = delegate.id;+ secondState.machine = delegate.machine;+ assert.notEqual(secondState.machine, link.machine);+ assert.notEqual(secondState.token, link.token, 'the second device never copies the first machine credential');const secondLinkFile = join(secondRoot, '.git', 'pullboard', 'relay.json');mkdirSync(join(secondRoot, '.git', 'pullboard'), { recursive: true, mode: 0o700 });writeFileSync(secondLinkFile, JSON.stringify(secondState) + '\n', { mode: 0o600 });@@ -149,11 +169,15 @@ test('[H12,H16] an expired native executor lease transfers once and the old devi// The original device catches up to the committed execution, sees a terminal request, and cannot// emit a second person shout even though its native identity is still present in its link file.+ board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ let originalDigest;+ try { originalDigest = requestIntentDigest(personRequestRecords(board).find(record => record.id === requestId)); }+ finally { store.closeBoard(board); }const late = await box.script(`const { main } = await import(${JSON.stringify(pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href)});const code = await main(['shout', 'coordinator', 'RECOVERY_SHOUT_ONCE', '--json'], {cwd: process.cwd(), stdout: process.stdout, stderr: process.stderr, personChannel: 'view', skipPersonRequests: true,- personRequest: { id: ${JSON.stringify(requestId)}, executor: ${JSON.stringify(originalExecutor)}, phase: 'execute' },+ personRequest: { id: ${JSON.stringify(requestId)}, executor: ${JSON.stringify(originalExecutor)}, phase: 'execute', digest: ${JSON.stringify(originalDigest)} },personRequestMoveId: 'late-original-${originalExecutor}',});process.exitCode = code;diff --git a/test/relay-person-requests.test.js b/test/relay-person-requests.test.jsindex 5b792522..48a645da 100644--- a/test/relay-person-requests.test.js+++ b/test/relay-person-requests.test.js@@ -50,7 +50,7 @@ function approvalFlowTimeoutMs(cliChildren) {async function signIn(chrome, box) {const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));const result = await chrome.send('Network.setCookie', {- name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',});assert.equal(result.success, true, 'the real person session is installed in the isolated browser');}diff --git a/test/relay-phone-crypto.test.js b/test/relay-phone-crypto.test.jsnew file mode 100644index 00000000..1baeac88--- /dev/null+++ b/test/relay-phone-crypto.test.js@@ -0,0 +1,84 @@+/** Phone approvals bind opaque replies and proposals to their exact action [H16,B26,H17]. */+import assert from 'node:assert/strict';+import { randomBytes } from 'node:crypto';+import { test } from 'node:test';+import { createApprovalReply, openApproval, restoreLinkReply, sealApproval, signApprovalIntent, verifyApprovalIntent } from '../src/relay-approval.js';++/** Return a valid device-bound revoke context, with overrides for exact-binding controls. */+function revokeContext(overrides = {}) {+ const device = 'device-' + '1'.repeat(32);+ return { id: 'request-01', account: '7', publisher: 'a'.repeat(32), board: 'a'.repeat(32), device,+ action: 'revoke-device', target: device, machine: 'mac-alpha', command: 'pullboard relay revoke ' + device,+ expires: 1_900_000_000_000, ...overrides };+}++/** Change one valid context field so decryption must fail on authenticated binding, not parsing. */+function changedContext(context, changes) { return { ...context, ...changes }; }++test('phone approval envelopes hide grants, bind every action field, and authenticate native intent [H16,B26,H17]', async () => {+ const phone = await createApprovalReply();+ const native = await createApprovalReply();+ assert.equal(phone.privateKey.extractable, false);+ assert.equal(native.privateKey.extractable, false);+ assert.equal(Object.hasOwn(phone, 'storedKey'), false);+ assert.equal(Object.hasOwn(native, 'storedKey'), false);+ await assert.rejects(crypto.subtle.exportKey('jwk', native.privateKey));++ const context = revokeContext();+ const intentValue = { context, replyKey: native.publicKey };+ const intent = await sealApproval(intentValue, phone.publicKey, context, 'intent');+ const packet = { envelope: intent, mac: await signApprovalIntent(new Uint8Array(randomBytes(32)), intent) };+ const boardKey = new Uint8Array(randomBytes(32));+ packet.mac = await signApprovalIntent(boardKey, intent);+ assert.deepEqual(await verifyApprovalIntent(boardKey, packet), intent);+ assert.notEqual(intent.ciphertext, JSON.stringify(intentValue));++ const secretGrant = 'pg_' + 'G'.repeat(43);+ const replyValue = { grant: secretGrant, expires: context.expires };+ const reply = await sealApproval(replyValue, native.publicKey, context, 'reply');+ const serialized = JSON.stringify({ intent, reply, packet });+ assert.equal(serialized.includes(secretGrant), false, 'grant stays opaque in relay transport');+ assert.deepEqual(await openApproval(phone.privateKey, intent, context, 'intent'), intentValue);+ assert.deepEqual(await openApproval(native.privateKey, reply, context, 'reply'), replyValue);++ const mismatchCases = [+ changedContext(context, { id: 'request-02' }),+ changedContext(context, { account: '8' }),+ changedContext(context, { publisher: 'b'.repeat(32), board: 'b'.repeat(32) }),+ changedContext(context, { board: 'c'.repeat(32), publisher: 'c'.repeat(32) }),+ changedContext(context, { device: 'device-' + '2'.repeat(32), target: 'device-' + '2'.repeat(32) }),+ changedContext(context, { action: 'revoke-token', target: 'token-1' }),+ changedContext(context, { target: 'device-' + '3'.repeat(32) }),+ changedContext(context, { machine: 'mac-beta' }),+ changedContext(context, { command: 'pullboard relay revoke another-device' }),+ changedContext(context, { expires: context.expires + 1000 }),+ ];+ for (const other of mismatchCases) {+ await assert.rejects(openApproval(native.privateKey, reply, other, 'reply'), { code: 'PHONE_APPROVAL_AUTH' });+ }+ await assert.rejects(openApproval(native.privateKey, { ...reply, direction: 'intent' }, context, 'reply'), { code: 'PHONE_APPROVAL_AUTH' });+ await assert.rejects(openApproval(native.privateKey, { ...reply, ciphertext: (reply.ciphertext[0] === 'A' ? 'B' : 'A') + reply.ciphertext.slice(1) }, context, 'reply'), { code: 'PHONE_APPROVAL_AUTH' });+ await assert.rejects(openApproval(await createApprovalReply().then(value => value.privateKey), reply, context, 'reply'), { code: 'PHONE_APPROVAL_AUTH' });++ const tampered = { envelope: { ...intent, context: changedContext(context, { command: 'pullboard relay off' }) }, mac: packet.mac };+ await assert.rejects(verifyApprovalIntent(boardKey, tampered), { code: 'PHONE_APPROVAL_AUTH' });+ await assert.rejects(verifyApprovalIntent(new Uint8Array(randomBytes(32)), packet), { code: 'PHONE_APPROVAL_AUTH' });+});++test('only explicit new-board link replies can restore a durable reply key [H16,B26,H17]', async () => {+ const phone = await createApprovalReply();+ const link = await createApprovalReply({ link: true });+ assert.equal(link.privateKey.extractable, true);+ assert.ok(link.storedKey, 'only the non-person link request exports a durable reply key');+ const context = revokeContext({ action: 'link', target: 'fixture/new-repository', board: 'b'.repeat(32) });+ const response = { board: context.board, machineToken: 'pm_' + 'M'.repeat(43) };+ const envelope = await sealApproval(response, link.publicKey, context, 'reply');+ const restored = await restoreLinkReply(link.storedKey);+ assert.deepEqual(await openApproval(restored, envelope, context, 'reply'), response);+ assert.deepEqual(await openApproval(link.privateKey, envelope, context, 'reply'), response);++ const personReply = await createApprovalReply();+ assert.equal(personReply.privateKey.extractable, false);+ assert.equal(Object.hasOwn(personReply, 'storedKey'), false, 'native revoke replies have no persistable private key');+ await assert.rejects(openApproval(restored, envelope, revokeContext({ action: 'link', target: 'fixture/new-repository', board: 'c'.repeat(32) }), 'reply'), { code: 'PHONE_APPROVAL_AUTH' });+});diff --git a/test/relay-phone-grants.test.js b/test/relay-phone-grants.test.jsnew file mode 100644index 00000000..1f97ef79--- /dev/null+++ b/test/relay-phone-grants.test.js@@ -0,0 +1,79 @@+/** Native phone grants are bounded to one authenticated action and consumed atomically [H13,H16,B26]. */+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { createRelayAuth } from '../relay/auth.js';+import { createGitHubClient } from '../relay/github.js';+import { githubFixture } from './relay-fixture.js';++/** Exercise real OAuth and SQLite without persisting a plaintext phone session. */+async function fixture(t) {+ const provider = await githubFixture(t);+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-phone-grants-'));+ let now = Date.now();+ const database = join(directory, 'auth.sqlite');+ const options = { database, github: createGitHubClient(provider.config), now: () => now };+ const auth = createRelayAuth(options);+ const second = createRelayAuth(options);+ t.after(() => { second.close(); auth.close(); rmSync(directory, { recursive: true, force: true }); });+ const flow = auth.beginWeb();+ const authorization = await fetch(flow.authorizationURL, { redirect: 'manual' });+ const callback = new URL(authorization.headers.get('location'));+ const phone = await auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), flow.binding);+ const board = 'a'.repeat(32);+ await auth.linkBoard(phone.token, board, 'fixture/repository');+ const machine = await auth.issueMachine(phone.token, { board, machine: 'native-grant-machine' });+ const other = await auth.issueMachine(phone.token, { board, machine: 'other-native-machine' });+ const agent = await auth.issueToken(machine.token, { board, agent: 'grant-worker' });+ /** Produce a unique action with the same immutable display and execution fields. */+ function context(id, overrides = {}) {+ return { id, account: phone.user.id, publisher: board, board, device: 'device-' + 'd'.repeat(32),+ action: 'revoke-token', target: agent.id, machine: machine.machine, command: 'pullboard relay revoke ' + agent.id,+ expires: now + 600_000, ...overrides };+ }+ return { auth, second, phone, machine, other, agent, context, provider, directory, advance(ms) { now += ms; }, now: () => now };+}++test('phone grants expire, bind every action field and permit one execution across processes [H13,H16,B26]', async t => {+ const box = await fixture(t);+ const context = box.context('grant-boundary-one');+ await assert.rejects(box.auth.issueActionGrant(box.machine.token, context), { code: 'HUMAN_REQUIRED' });+ await assert.rejects(box.auth.issueActionGrant(box.agent.token, context), { code: 'HUMAN_REQUIRED' });+ const approved = await box.auth.issueActionGrant(box.phone.token, context);+ assert.equal(/^pg_[A-Za-z0-9_-]{43}$/u.test(approved.grant), true);+ assert.equal(approved.expires, box.now() + 120_000, 'a ten-minute proposal yields at most two minutes of action authority');+ const bytes = Buffer.concat(readdirSync(box.directory).map(name => readFileSync(join(box.directory, name))));+ assert.equal(bytes.includes(approved.grant), false, 'SQLite and WAL retain only a hash of the single-use grant');+ await assert.rejects(box.auth.authenticate(approved.grant), { code: 'AUTH_REQUIRED' });+ await assert.rejects(box.auth.consumeActionGrant(box.phone.token, approved.grant, context), { code: 'HUMAN_REQUIRED' });+ await assert.rejects(box.auth.consumeActionGrant(box.agent.token, approved.grant, context), { code: 'HUMAN_REQUIRED' });+ await assert.rejects(box.auth.consumeActionGrant(box.other.token, approved.grant, context), { code: 'HUMAN_REQUIRED' });+ for (const changed of [+ { id: 'other-request' }, { target: 'another-token' }, { device: 'device-' + 'e'.repeat(32) },+ { command: 'pullboard relay revoke another-token' }, { expires: context.expires - 1 },+ { action: 'revoke-device', target: 'device-' + 'e'.repeat(32) },+ ]) {+ await assert.rejects(box.auth.consumeActionGrant(box.machine.token, approved.grant, { ...context, ...changed }), { code: 'PHONE_APPROVAL_USED' });+ }+ await assert.rejects(box.auth.issueActionGrant(box.phone.token, context), { code: 'PHONE_APPROVAL_USED' });+ const attempts = await Promise.allSettled([+ box.auth.consumeActionGrant(box.machine.token, approved.grant, context),+ box.second.consumeActionGrant(box.machine.token, approved.grant, context),+ ]);+ assert.equal(attempts.filter(result => result.status === 'fulfilled').length, 1, 'two SQLite connections cannot both consume a grant');+ assert.equal(attempts.find(result => result.status === 'rejected').reason.code, 'PHONE_APPROVAL_USED');+ const principal = attempts.find(result => result.status === 'fulfilled').value;+ assert.deepEqual(await box.auth.revokeApprovedToken(principal, box.agent.id, context.board), { id: box.agent.id, revoked: true });+ await assert.rejects(box.auth.authenticate(box.agent.token), { code: 'AUTH_REQUIRED' });++ const expires = box.context('grant-expiry');+ const short = await box.auth.issueActionGrant(box.phone.token, expires);+ box.advance(120_000);+ await assert.rejects(box.auth.consumeActionGrant(box.machine.token, short.grant, expires), { code: 'PHONE_APPROVAL_USED' });+ const unavailable = box.context('permission-lost');+ const beforeLoss = await box.auth.issueActionGrant(box.phone.token, unavailable);+ box.provider.state.access = false;+ await assert.rejects(box.auth.consumeActionGrant(box.machine.token, beforeLoss.grant, unavailable), { code: 'NO_REPO_ACCESS' });+});diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.jsindex 27bc40e2..6afea73d 100644--- a/test/relay-sealed.test.js+++ b/test/relay-sealed.test.js@@ -38,7 +38,7 @@ function unseal(key, value, binding) {}/** Create a real private CLI board, actual stand-in GitHub sign-in, and an ephemeral relay server. */-async function fixture(t) {+async function fixture(t, { machineCredentials = true } = {}) {const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-sealed-http-')));const root = join(directory, 'repo');const home = join(directory, 'home');@@ -74,8 +74,13 @@ async function fixture(t) {const callback = new URL(redirect.headers.get('location'));const person = await auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), flow.binding);await auth.linkBoard(person.token, id, 'fixture/repository');- const one = await auth.issueToken(person.token, { board: id, agent: 'client-one' });- const two = await auth.issueToken(person.token, { board: id, agent: 'client-two' });+ const machines = machineCredentials ? await Promise.all([+ auth.issueMachine(person.token, { board: id, machine: 'client-one' }),+ auth.issueMachine(person.token, { board: id, machine: 'client-two' }),+ ]) : [];+ const tokenIssuer = machines[0]?.token ?? person.token;+ const one = await auth.issueToken(tokenIssuer, { board: id, agent: 'client-one' });+ const two = await auth.issueToken(machines[1]?.token ?? tokenIssuer, { board: id, agent: 'client-two' });const relay = await serveRelay({ directory: data, auth, port: 0, pollMs: 20, publicOrigin: 'http://127.0.0.1:44444' });t.after(async () => { await relay.close(); auth.close(); rmSync(directory, { recursive: true, force: true }); });const origin = 'http://127.0.0.1:' + relay.port;@@ -85,7 +90,7 @@ async function fixture(t) {async function call(path, { method = 'GET', body, token = one.token, headers = {} } = {}) {const response = await fetch(origin + path, {method,- headers: { 'x-pullboard-engine': '3', ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...headers },+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...headers },...(body === undefined ? {} : { body: JSON.stringify(body) }),});return { status: response.status, body: await response.json() };@@ -94,7 +99,7 @@ async function fixture(t) {function clientSeal(value, kind, sequence, board = id) { return seal(key, value, { board, kind, sequence }); }/** Unseal received records at their actual committed position, never the client's old proposal. */function clientOpen(value, kind, sequence, board = id) { return unseal(key, value, { board, kind, sequence }); }- return { directory, root, home, env, data, cli, document, id, marker, auth, person, one, two, relay, origin, key, call, clientSeal, clientOpen, path: '/api/v1/boards/' + id };+ return { directory, root, home, env, data, cli, document, id, marker, auth, person, machines, tokenIssuer, one, two, relay, origin, key, call, clientSeal, clientOpen, path: '/api/v1/boards/' + id };}/** Run a linked CLI asynchronously so the real relay can serve it, keeping credentials out of diagnostics. */@@ -218,7 +223,7 @@ test('sealed agent shout cannot answer a person decision on either independent cdocument = JSON.parse(JSON.stringify(exportBoard(source)));} finally { store.closeBoard(source); }- const remote = await box.auth.issueToken(box.person.token, { board: box.id, agent: 'remote-1' });+ const remote = await box.auth.issueToken(box.machines[0].token, { board: box.id, agent: 'remote-1' });const roots = [box.root, join(box.directory, 'second-client')];const homes = [box.home, join(box.directory, 'second-home')];const envs = homes.map(home => ({ ...box.env, HOME: home, PULLBOARD_HOME: home }));@@ -235,7 +240,7 @@ test('sealed agent shout cannot answer a person decision on either independent cconst url = await independentReplayOrigin(t, box.origin);writeFileSync(join(roots[i], '.git/pullboard/relay.json'), JSON.stringify({version: 1, mode: 'ordered', board: box.id, url, repository: 'fixture/repository',- token: box.person.token, sequence: 0, cursor: document.tables.event.at(-1).event_id,+ token: box.machines[i].token, sequence: 0, cursor: document.tables.event.at(-1).event_id,}) + '\n', { mode: 0o600 });}@@ -316,7 +321,7 @@ test('two real clients stop before sender checks for newer operations and actorcheckpointSequence(source, 0);document = JSON.parse(JSON.stringify(exportBoard(source)));} finally { store.closeBoard(source); }- const remote = await box.auth.issueToken(box.person.token, { board: box.id, agent: 'remote-1' });+ const remote = await box.auth.issueToken(box.machines[0].token, { board: box.id, agent: 'remote-1' });const roots = [box.root, join(box.directory, 'second-client')];const homes = [box.home, join(box.directory, 'second-home')];const envs = homes.map(home => ({ ...box.env, HOME: home, PULLBOARD_HOME: home }));@@ -332,7 +337,7 @@ test('two real clients stop before sender checks for newer operations and actormkdirSync(keyDirectory, { mode: 0o700 });writeFileSync(join(keyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });const replayOrigin = await independentReplayOrigin(sub, box.origin);- writeFileSync(links[index], JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: replayOrigin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });+ writeFileSync(links[index], JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: replayOrigin, repository: 'fixture/repository', token: box.machines[index].token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });}const originalLinks = links.map(file => readFileSync(file, 'utf8'));const initialSnapshot = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(document)), { boardId: box.id, kind: 'snapshot', sequence: 0 })).toString('base64url');@@ -405,7 +410,7 @@ test('two real clients refuse forged relay actors and person-only requests while];document = JSON.parse(JSON.stringify(exportBoard(source)));} finally { store.closeBoard(source); }- const remote = await box.auth.issueToken(box.person.token, { board: box.id, agent: 'remote-1' });+ const remote = await box.auth.issueToken(box.machines[0].token, { board: box.id, agent: 'remote-1' });const roots = [box.root, join(box.directory, 'second-client')];const homes = [box.home, join(box.directory, 'second-home')];const envs = homes.map(home => ({ ...box.env, HOME: home, PULLBOARD_HOME: home }));@@ -419,7 +424,7 @@ test('two real clients refuse forged relay actors and person-only requests whileconst keyDirectory = join(homes[index], 'relay-keys');mkdirSync(keyDirectory, { mode: 0o700 });writeFileSync(join(keyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });- writeFileSync(join(roots[index], '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: box.origin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });+ writeFileSync(join(roots[index], '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: box.origin, repository: 'fixture/repository', token: box.machines[index].token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });}/** Seal production-format records on this client; the relay stores only their opaque envelopes. */async function upload(value, kind, sequence, token = remote.token) {@@ -562,13 +567,13 @@ test('two real clients enforce the verify policy captured in the item freeze [H1const keyDirectory = join(homes[index], 'relay-keys');mkdirSync(keyDirectory, { mode: 0o700 });writeFileSync(join(keyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });- writeFileSync(join(roots[index], '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: box.origin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });+ writeFileSync(join(roots[index], '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: box.origin, repository: 'fixture/repository', token: box.machines[index].token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });}const snapshotSealed = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(document)), { boardId: box.id, kind: 'snapshot', sequence: 0 })).toString('base64url');const savedSnapshot = await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: snapshotSealed } });assert.equal(savedSnapshot.status, 200, 'person session installs the initial encrypted snapshot');const verifierTokens = new Map();- for (const agent of new Set([verifierSame, verifierOther])) verifierTokens.set(agent, await box.auth.issueToken(box.person.token, { board: box.id, agent }));+ for (const agent of new Set([verifierSame, verifierOther])) verifierTokens.set(agent, await box.auth.issueToken(box.machines[0].token, { board: box.id, agent }));for (let index = 0; index < moves.length; index += 1) {const agent = moves[index].args[1].agentId;const sequence = index + 1;@@ -609,7 +614,7 @@ test('two real clients enforce the verify policy captured in the item freeze [H1});test('relay accepts engine 4 clients carrying sealed background completions [V2,H16]', async t => {- const box = await fixture(t);+ const box = await fixture(t, { machineCredentials: false });const headers = { 'x-pullboard-engine': '4' };assert.ok(ENGINE_VERSION >= 4, 'engine-4 background completions remain supported');const snapshot = await box.call(box.path + '/state', {@@ -800,7 +805,7 @@ test('[A4,H7] live streams follow the same order, resume by cursor and stop afteconst controller = new AbortController();controllers.push(controller);const reply = await fetch(box.origin + box.path + '/events?after=0', {- headers: { 'x-pullboard-engine': '3', authorization: 'Bearer ' + box.two.token, accept: 'text/event-stream', ...(last === null ? {} : { 'last-event-id': String(last) }) },+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), authorization: 'Bearer ' + box.two.token, accept: 'text/event-stream', ...(last === null ? {} : { 'last-event-id': String(last) }) },signal: controller.signal,});assert.equal(reply.status, 200);diff --git a/test/relay-setup-once.test.js b/test/relay-setup-once.test.jsindex f6934f0b..2400ddbb 100644--- a/test/relay-setup-once.test.js+++ b/test/relay-setup-once.test.js@@ -89,7 +89,7 @@ test('set up once links three registered boards, later registration and a persisconst profileDirectory = join(dirname(box.root), 'phone-profile');chrome = await startChrome({ profileDirectory });- assert.equal((await chrome.send('Network.setCookie', { name: 'pb_session', value: link(box.root).token, url: box.origin, httpOnly: true, sameSite: 'Lax' })).success, true);+ assert.equal((await chrome.send('Network.setCookie', { name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax' })).success, true);await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);const completed = await setup.done;assert.equal(completed.code, 0);@@ -104,16 +104,55 @@ test('set up once links three registered boards, later registration and a persisconst fourth = await project(box, 'fourth-project');const allRoots = [...roots, fourth];- assert.equal(existsSync(join(fourth, '.git/pullboard/relay.json')), true, 'registration actually creates the future relay link');- assert.equal(link(fourth).account, '7', 'registration alone linked the fourth project with the saved account');- assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 1, 'no second machine sign-in');+ const approvalFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');+ const waitingState = JSON.parse(readFileSync(approvalFile, 'utf8'));+ const linkProposal = waitingState.approvals.find(entry => entry.root === fourth);+ assert.ok(linkProposal, 'the fourth project stays local with one persisted phone-link proposal');+ const fourthBoard = linkProposal.context.board;+ assert.equal(existsSync(join(fourth, '.git/pullboard/relay.json')), false, 'registration does not grant itself a board credential');+ assert.equal(linkProposal.context.action, 'link');+ assert.equal(linkProposal.context.target, 'fixture/repository');+ assert.ok(linkProposal.context.expires > Date.now(), 'the proposal carries a visible future expiry');+ assert.equal(typeof linkProposal.sealed, 'string', 'the queued link intent is sealed for the paired phone');+ assert.equal(linkProposal.published, true);+ const approvalPosts = () => box.calls.filter(call => call.method === 'POST' && call.path === '/api/v1/devices/approvals').length;+ assert.equal(approvalPosts(), 1, 'registration publishes one proposal');+ const pendingMessage = 'waiting for phone approval: fourth-project; expires ' + new Date(linkProposal.context.expires).toISOString();+ const statusPending = await command(fourth, box.env, ['status']).done;+ assert.equal(statusPending.code, 0, 'status remains available while a new board awaits phone approval');+ const doctor = await command(fourth, box.env, ['doctor']).done;+ assert.equal(doctor.document.problems.some(problem => problem.message === pendingMessage), true);+ const resumedPending = await command(fourth, box.env, ['resume']).done;+ assert.equal(resumedPending.document.relayProblems.some(problem => problem.message === pendingMessage), true);+ const repeatedPending = JSON.parse(readFileSync(approvalFile, 'utf8')).approvals.find(entry => entry.root === fourth);+ assert.equal(repeatedPending.context.id, linkProposal.context.id, 'read-only status and diagnosis keep the same proposal');+ assert.equal(approvalPosts(), 1, 'status and doctor do not replace or duplicate the request');await chrome.navigate(box.origin);+ const approveLinkButton = '#phone-approve-' + linkProposal.context.id;+ await chrome.waitFor(`document.querySelector(${JSON.stringify(approveLinkButton)}) !== null`);+ const linkCard = await chrome.evaluate(`({text: document.querySelector('.phone-approval[data-request="${linkProposal.context.id}"]').innerText,+ action: document.querySelector(${JSON.stringify(approveLinkButton)}).innerText})`);+ assert.match(linkCard.text, /Link fourth-project\?/u);+ assert.match(linkCard.text, /fixture\/repository/u);+ assert.match(linkCard.text, new RegExp(new Date(linkProposal.context.expires).toISOString().replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')));+ assert.equal(linkCard.action, 'Link project', 'the paired phone presents an explicit one-tap link action');+ const approvalsBeforeLinkTap = box.calls.filter(call => call.path.endsWith('/authorize')).length;+ await chrome.evaluate(`document.querySelector(${JSON.stringify(approveLinkButton)}).click()`);+ await chrome.waitFor(`document.querySelector(${JSON.stringify(approveLinkButton)}) === null`);+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, approvalsBeforeLinkTap + 1,+ 'one explicit phone tap authorizes the link proposal once');+ const linkedFourth = await command(fourth, box.env, ['status']).done;+ assert.equal(linkedFourth.code, 0);+ assert.equal(link(fourth).account, '7', 'a fresh native status consumes the phone-approved link reply');+ assert.equal(JSON.parse(readFileSync(approvalFile, 'utf8')).approvals.some(entry => entry.root === fourth), false);+ assert.equal(approvalPosts(), 1, 'consuming the phone reply does not submit another proposal');+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 1, 'no second machine sign-in');await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 4");assert.deepEqual(await chrome.evaluate(browserDeviceExpression()), device, 'a new page retrieves the same private device key');await chrome.close();rmSync(join(profileDirectory, 'DevToolsActivePort'), { force: true });chrome = await startChrome({ profileDirectory });- assert.equal((await chrome.send('Network.setCookie', { name: 'pb_session', value: link(box.root).token, url: box.origin, httpOnly: true, sameSite: 'Lax' })).success, true);+ assert.equal((await chrome.send('Network.setCookie', { name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax' })).success, true);await chrome.navigate(box.origin);await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 4");assert.deepEqual(await chrome.evaluate(browserDeviceExpression()), device, 'a new browser process retrieves the original non-extractable key');@@ -123,14 +162,64 @@ test('set up once links three registered boards, later registration and a persis'the actual browser unwrapped each board key, including the later board');}- // Every CLI invocation is a new process. The saved settings and device eliminate renewed setup.+ // Explicit --all always signs in again, while retaining the paired phone key and avoiding re-pairing.const resumed = await command(box.root, box.env, ['relay', 'on', '--all']).done;assert.equal(resumed.code, 0);assert.equal(resumed.document.linked.length, 4);assert.equal(resumed.document.paired, true);- assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 1);+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 2, 'explicit relay on --all performs a fresh foreground sign-in');+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path.startsWith('/api/v1/devices/enrollments/')).length, 1,+ 'the existing paired phone is retained without another pairing enrollment');assert.deepEqual(await chrome.evaluate(browserDeviceExpression()), device);+ const off = await command(fourth, box.env, ['relay', 'off']).done;+ assert.equal(off.code, 0);+ assert.match(off.document.notice, /Local link removed\. The relay copy stays until you approve deleting it on your phone\./u);+ assert.equal(existsSync(join(fourth, '.git/pullboard/relay.json')), false, 'relay off immediately removes the local link');+ assert.equal(JSON.parse(readFileSync(machineFile, 'utf8')).excluded.includes(fourth), true, 'the local opt-out is durable');+ const deletePost = box.transit.findLast(record => record.method === 'POST' && record.path === '/api/v1/devices/approvals');+ const deleteApproval = JSON.parse(deletePost.request.toString('utf8')).context;+ assert.equal(deleteApproval.action, 'delete-board', 'remote deletion is a separate phone-approved action');+ assert.equal(deleteApproval.target, fourthBoard);+ await chrome.waitFor(`document.querySelector('.phone-approval[data-request="${deleteApproval.id}"]') !== null`);+ const deleteCard = await chrome.evaluate(`({text: document.querySelector('.phone-approval[data-request="${deleteApproval.id}"]').innerText,+ action: document.querySelector('.phone-approval[data-request="${deleteApproval.id}"] button').innerText})`);+ assert.match(deleteCard.text, new RegExp(deleteApproval.target));+ assert.equal(deleteCard.action, 'Delete relay copy');+ const phone = await box.phoneSession();+ const boardsBeforeDeleteTap = await fetch(box.origin + '/auth/boards', { headers: { cookie: 'pb_session=' + phone.token } });+ assert.equal(boardsBeforeDeleteTap.status, 200);+ assert.equal((await boardsBeforeDeleteTap.json()).boards.some(board => board.id === fourthBoard), true,+ 'relay off leaves the remote board in place while its phone approval is pending');+ const beforeDeleteTap = box.calls.filter(call => call.path.endsWith('/authorize')).length;+ await chrome.evaluate(`document.querySelector('.phone-approval[data-request="${deleteApproval.id}"] button').click()`);+ await chrome.waitFor(`document.querySelector('.phone-approval[data-request="${deleteApproval.id}"]') === null`);+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, beforeDeleteTap + 1,+ 'the remote copy is deleted only after the deliberate phone tap');+ const boardsAfterDeleteTap = await fetch(box.origin + '/auth/boards', { headers: { cookie: 'pb_session=' + phone.token } });+ assert.equal(boardsAfterDeleteTap.status, 200);+ assert.equal((await boardsAfterDeleteTap.json()).boards.some(board => board.id === fourthBoard), false,+ 'the explicit phone approval removes the relay copy before relinking');++ assert.equal((await command(fourth, box.env, ['init']).done).code, 0);+ assert.equal(existsSync(join(fourth, '.git/pullboard/relay.json')), false, 'registration respects the explicit local opt-out');+ const excludedSetup = await command(box.root, box.env, ['relay', 'on', '--all']).done;+ assert.equal(excludedSetup.code, 0);+ assert.equal(excludedSetup.document.linked.length, 3, 'explicit machine setup does not undo the fourth-board opt-out');+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 3,+ 'each explicit relay on --all performs a fresh foreground sign-in');+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path.startsWith('/api/v1/devices/enrollments/')).length, 1,+ 'the paired phone is not enrolled again while excluding a board');+ assert.equal((await command(fourth, box.env, ['relay', 'on', '--url', box.origin]).done).code, 0,+ 'explicitly linking the board again requires a foreground sign-in');+ assert.equal(JSON.parse(readFileSync(machineFile, 'utf8')).excluded.includes(fourth), false,+ 'explicit board linking clears its opt-out');+ await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 4");+ assert.deepEqual(await chrome.evaluate(browserDeviceExpression()), device,+ 'relinking wraps the board for the same paired phone key');+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 4);+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path.startsWith('/api/v1/devices/enrollments/')).length, 1);+const publicBytes = Buffer.concat(box.transit.flatMap(record => [record.request, record.response]));const durableBytes = readFileSync(join(box.relayDirectory, 'devices.sqlite'));assert.equal(publicBytes.includes(pending.secret), false, 'the pairing secret never reaches the relay');@@ -140,20 +229,21 @@ test('set up once links three registered boards, later registration and a persisassert.equal(durableBytes.includes(raw), false, 'no clear board key in relay device records');assert.equal(durableBytes.includes(Buffer.from(raw, 'base64url')), false, 'no raw board-key bytes in relay records');}- assert.equal((await command(fourth, box.env, ['relay', 'off']).done).code, 0);- assert.equal((await command(fourth, box.env, ['init']).done).code, 0);- assert.equal(existsSync(join(fourth, '.git/pullboard/relay.json')), false, 'an excluded board stays off on later registration');- const stillExcluded = await command(box.root, box.env, ['relay', 'on', '--all']).done;- assert.equal(stillExcluded.code, 0);- assert.equal(stillExcluded.document.linked.length, 3, 'machine setup does not undo an explicit board opt-out');- assert.equal((await command(fourth, box.env, ['relay', 'on', '--url', box.origin]).done).code, 0);- assert.equal(JSON.parse(readFileSync(machineFile, 'utf8')).excluded.includes(fourth), false, 'explicit board linking clears its opt-out');- await chrome.navigate(box.origin);- await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 4");- assert.deepEqual(await chrome.evaluate(browserDeviceExpression()), device, 'the paired phone opens a relinked board with its new wrapped key');- const revoked = await command(box.root, box.env, ['relay', 'revoke', device.id]).done;++ const revokeCommand = command(box.root, box.env, ['relay', 'revoke', device.id]);+ t.after(async () => { if (revokeCommand.child.exitCode === null) revokeCommand.child.kill('SIGTERM'); await revokeCommand.done.catch(() => {}); });+ await chrome.waitFor(`[...document.querySelectorAll('.phone-approval')].some(node => node.textContent.includes(${JSON.stringify(device.id)}))`);+ const revocationCard = await chrome.evaluate(`({text: [...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(${JSON.stringify(device.id)})).innerText,+ action: [...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(${JSON.stringify(device.id)})).querySelector('button').innerText})`);+ assert.match(revocationCard.text, new RegExp(device.id));+ assert.equal(revocationCard.action, 'Approve revocation');+ const beforeRevokeTap = box.calls.filter(call => call.path.endsWith('/authorize')).length;+ await chrome.evaluate(`[...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(${JSON.stringify(device.id)})).querySelector('button').click()`);+ const revoked = await revokeCommand.done;assert.equal(revoked.code, 0);assert.match(revoked.document.notice, /already received remain known/u);+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, beforeRevokeTap + 1,+ 'the named-device revocation uses exactly one explicit phone tap');assert.equal(JSON.parse(readFileSync(machineFile, 'utf8')).devices.length, 0);});@@ -188,7 +278,8 @@ test('set up once keeps completed links on interruption and names partial failurassert.equal(completed.code, 0, 'successful links exit zero even when phone pairing was interrupted');assert.equal(completed.document.linked.length, 2);assert.equal(link(box.root).board, retained, 'rerunning setup keeps the existing board and key');- assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 1);+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 2,+ 'retrying explicit relay on --all signs in again before starting a fresh pairing');});test('set up once reports a newly registered project when its stored session is gone [H5,H17]', async t => {@@ -199,7 +290,7 @@ test('set up once reports a newly registered project when its stored session isassert.equal(saved.code, 0);const unlinked = await project(box, 'needs-signin-project');assert.equal(existsSync(join(unlinked, '.git/pullboard/relay.json')), false);- const message = 'not linked: needs-signin-project (sign in again: pullboard relay on --all)';+ const message = 'not linked: needs-signin-project; run pullboard relay on --all';const doctor = await command(unlinked, box.env, ['doctor']).done;assert.equal(doctor.document.problems.some(problem => problem.message === message), true);const resume = await command(unlinked, box.env, ['resume']).done;diff --git a/test/relay-snapshot-recovery.test.js b/test/relay-snapshot-recovery.test.jsindex cea10596..8a2831bd 100644--- a/test/relay-snapshot-recovery.test.js+++ b/test/relay-snapshot-recovery.test.js@@ -49,7 +49,7 @@ test('a delayed native checkpoint recovers the real page after its visible timeoconst key = decodeBoardKey(encodedKey);const chrome = await startChrome();t.after(() => chrome.close());- const cookie = await chrome.send('Network.setCookie', { name: 'pb_session', value: link.token,+ const cookie = await chrome.send('Network.setCookie', { name: 'pb_session', value: (await box.phoneSession()).token,url: box.origin, httpOnly: true, sameSite: 'Lax' });assert.equal(cookie.success, true);await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encodedKey);@@ -65,7 +65,14 @@ test('a delayed native checkpoint recovers the real page after its visible timeolet move;try { move = prepareEngineMove(board, 'addItem', [{ by: 'coordinator', lane: box.lane, title: recovered }]); }finally { closeBoard(board); }- const sent = await upload(box, link, 'moves', 1, await encoded(key, move, link.board, 'move', 1));+ const coordinator = await fetch(box.origin + '/auth/tokens', {+ method: 'POST', headers: { authorization: 'Bearer ' + link.token,+ 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) },+ body: JSON.stringify({ board: link.board, agent: 'coordinator' }),+ });+ assert.equal(coordinator.status, 201, 'the board machine mints an ordinary coordinator token without a phone tap');+ const agent = await coordinator.json();+ const sent = await upload(box, { ...link, token: agent.token }, 'moves', 1, await encoded(key, move, link.board, 'move', 1));const started = Date.now();const timeoutText = 'The relay snapshot has not caught up to this move. Retry this board.';await chrome.waitFor('document.querySelector("#relay-notice")?.textContent.includes(' + JSON.stringify(timeoutText) + ')',diff --git a/test/relay-snapshot-size.test.js b/test/relay-snapshot-size.test.jsindex c3bd388d..2fd96d1c 100644--- a/test/relay-snapshot-size.test.js+++ b/test/relay-snapshot-size.test.js@@ -85,7 +85,7 @@ test('a large board syncs to the relay compressed [H5,H15,H17]', {const chrome = await startChrome();t.after(() => chrome.close());await chrome.send('Network.setCookie', {- name: 'pb_session', value: sourceState.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',});const encodedKey = readFileSync(box.keyFile, 'utf8').trim();await chrome.navigate(box.origin + '/#board=' + sourceState.board + '&key=' + encodedKey);diff --git a/test/relay.test.js b/test/relay.test.jsindex 613886e6..457b4773 100644--- a/test/relay.test.js+++ b/test/relay.test.js@@ -389,21 +389,32 @@ test('an explicit read role still hides a public board below triage [H13,H14,H8]await assert.rejects(box.auth.issueToken(signed.token, { board: 'alpha', agent: 'worker' }), { code: 'BOARD_NOT_LINKED' });});-test('relay off forgets expired and independently unlinked boards while preserving local rows [H1,H7,H18]', async (t) => {+test('relay off forgets expired and remotely deleted boards while preserving local rows [H1,H7,H18]', async (t) => {for (const cause of ['expired', 'other-client']) await t.test(cause, async (t) => {const box = await relayClientFixture(t);await box.link();- const localBeforeDeletion = (await box.cli('export')).document.tables;+ const localBeforeOff = (await box.cli('export')).document.tables;+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));if (cause === 'expired') box.advance(90);- else assert.equal(await box.otherDeviceOff(), 0, 'a second real CLI device unlinks the shared board');+ else {+ const phone = await box.phoneSession();+ const deleted = await fetchFresh(`${box.origin}/api/v1/boards/${link.board}`, {+ method: 'DELETE', headers: { authorization: `Bearer ${phone.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },+ });+ assert.equal(deleted.status, 200, 'an explicit person HTTP DELETE removes the remote board');+ }+ const callsBeforeOff = box.calls.length;const off = await box.cli('relay', 'off');assert.equal(off.code, 0);assert.equal(off.document.linked, false);- assert.equal(off.document.alreadyDeleted, true);- assert.match(off.document.notice, /already deleted/);+ assert.match(off.document.notice, /Local link removed/u);assert.equal(existsSync(box.linkFile), false, 'local link metadata is forgotten');assert.equal(existsSync(box.keyFile), false, 'device-only fallback key is forgotten');- assert.deepEqual((await box.cli('export')).document.tables, localBeforeDeletion, 'local board is complete after remote deletion');+ assert.deepEqual((await box.cli('export')).document.tables, localBeforeOff, 'local rows and event history survive remote deletion or expiry');+ assert.ok(JSON.parse(readFileSync(join(box.env.PULLBOARD_HOME, 'relay-machine/state.json'), 'utf8')).excluded.includes(box.root),+ 'the local opt-out remains durable after unlink');+ assert.equal(box.calls.slice(callsBeforeOff).some(call => call.method === 'DELETE'), false,+ 'relay off never deletes the relay copy without its separate phone approval');const count = box.calls.length;assert.equal((await box.cli('relay', 'off')).code, 0);assert.equal((await box.cli('status')).code, 0);@@ -411,23 +422,22 @@ test('relay off forgets expired and independently unlinked boards while preservi});});-test('relay off retains credentials and metadata after non-missing or unsupported refusals [H1,H7]', async (t) => {+test('relay off completes local unlink when the relay is offline [H1,H7,H18]', async (t) => {const box = await relayClientFixture(t);await box.link();- for (const failure of [- { status: 403, code: 'NO_REPO_ACCESS' },- { status: 401, code: 'AUTH_REQUIRED' },- { status: 500, code: 'NO_BOARD' },- { status: 404, code: 'NO_BOARD', version: 2 },- ]) {- box.overrideDelete(failure);- assert.notEqual((await box.cli('relay', 'off')).code, 0, 'only a supported missing-board response permits cleanup');- assert.equal(existsSync(box.linkFile), true);- assert.equal(existsSync(box.keyFile), true);- }- box.overrideDelete(null);- assert.equal((await box.cli('relay', 'off')).code, 0);+ const localBeforeOff = (await box.cli('export')).document.tables;+ await box.stopRelay();+ const callsBeforeOff = box.calls.length;+ const off = await box.cli('relay', 'off');+ assert.equal(off.code, 0, 'local unlink succeeds without a reachable relay');+ assert.match(off.document.notice, /relay copy stays until you approve deleting it on your phone/u);+ assert.equal(existsSync(box.linkFile), false);assert.equal(existsSync(box.keyFile), false);+ assert.ok(JSON.parse(readFileSync(join(box.env.PULLBOARD_HOME, 'relay-machine/state.json'), 'utf8')).excluded.includes(box.root),+ 'the local opt-out remains durable');+ assert.deepEqual((await box.cli('export')).document.tables, localBeforeOff, 'offline unlink preserves all local rows');+ assert.equal(box.calls.length, callsBeforeOff, 'offline local unlink makes no relay request');+ assert.equal(box.calls.some(call => call.method === 'DELETE'), false, 'offline local unlink cannot delete the remote copy');});test('BOARD_INACTIVE appears once per command and resets for a second command in the same process [H18]', async (t) => {@@ -763,20 +773,29 @@ test('a linked device with an unreadable key reads locally and refuses moves witassert.equal(box.calls.length, callsBefore, 'no read or refused move reaches the relay');});-test('plain relay off explains an already-deleted board without printing credentials [H1,H18]', async (t) => {+test('plain relay off explains the retained relay copy without printing credentials [H1,H18]', async (t) => {const box = await relayClientFixture(t);await box.link();- box.advance(90);+ const localBeforeOff = (await box.cli('export')).document.tables;+ const callsBeforeOff = box.calls.length;const result = await box.script(`import { main } from ${JSON.stringify(box.mainURL)};let output = '';const code = await main(['relay', 'off'], {cwd: process.cwd(), stdout: { write(part) { output += part; } }, stderr: { write() {} },});- console.log(JSON.stringify({ code, explained: output.includes('already deleted'), credential: /ps_|key=/.test(output) }));+ console.log(JSON.stringify({ code,+ retained: output.includes('relay copy stays until you approve deleting it on your phone'),+ credential: /(?:ps|pm|pa|pg)_[A-Za-z0-9_-]{43}|key=/u.test(output) }));`);assert.equal(result.code, 0);- assert.deepEqual(result.document, { code: 0, explained: true, credential: false });+ assert.deepEqual(result.document, { code: 0, retained: true, credential: false });+ assert.equal(existsSync(box.linkFile), false, 'plain local off removes the device link');+ assert.equal(existsSync(box.keyFile), false, 'plain local off forgets the device key');+ assert.ok(JSON.parse(readFileSync(join(box.env.PULLBOARD_HOME, 'relay-machine/state.json'), 'utf8')).excluded.includes(box.root));+ assert.deepEqual((await box.cli('export')).document.tables, localBeforeOff, 'plain local off preserves native rows');+ assert.equal(box.calls.slice(callsBeforeOff).some(call => call.method === 'DELETE'), false,+ 'plain local off never deletes the remote copy without phone approval');});@@ -785,11 +804,13 @@ test('every real CLI relay request declares its engine including sign-in, reads,await box.link();assert.equal((await box.cli('export')).code, 0);assert.equal((await box.cli('add', box.lane, 'Declared-engine fixture move')).code, 0);- assert.equal((await box.cli('relay', 'off')).code, 0);+ const off = await box.cli('relay', 'off');+ assert.equal(off.code, 0);+ assert.match(off.document.notice, /relay copy stays until you approve deleting it on your phone/u);assert.ok(box.calls.some(call => call.path.startsWith('/auth/')));assert.ok(box.calls.some(call => call.method === 'GET' && call.path.includes('/events')));assert.ok(box.calls.some(call => call.method === 'POST' && call.path.endsWith('/moves')));assert.ok(box.calls.some(call => call.method === 'PUT' && call.path.endsWith('/state')));- assert.ok(box.calls.some(call => call.method === 'DELETE'));+ assert.equal(box.calls.some(call => call.method === 'DELETE'), false, 'local off does not send remote deletion without phone approval');assert.ok(box.calls.every(call => call.engine === String(ENGINE_VERSION)), 'every request from the real CLI carries the current engine version');});