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
feat(relay): set up every board with one phone pairing [H5,H17]
Corey Olsond4a67ebb30d4
diff --git a/docs/api.md b/docs/api.mdindex d7a5a193..d8c2849a 100644--- a/docs/api.md+++ b/docs/api.md@@ -151,6 +151,12 @@ 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 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.++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.+The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js` by `docs/api.test.js`.When `verify <id> accept` runs a frozen check and refuses with `CHECK_RED` or `CHECK_UNVERIFIED`, `error.message` includes its output digest, up to 40 sanitized tail lines, and `full output file: <path>`. The file is written with owner-only permissions. If diagnostic storage fails, the message says `full output file: (unavailable: CODE)` while retaining the bounded sanitized lines; the JSON error object remains `{ code, message, next }`. An item with no frozen check produces no check-output section.diff --git a/docs/formats.md b/docs/formats.mdindex 7235641f..96cb1619 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -99,6 +99,12 @@ 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`.++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.+The in-place upgrade behavior is exercised by `exerciseUpgrade` in `docs/formats.test.js`:<!-- upgrade-rules:start -->diff --git a/relay/browser-client.js b/relay/browser-client.jsindex 6e4e56ed..26b42cb1 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -1,5 +1,6 @@/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15]. */-import { decodeBoardKey, seal, unseal } from './seal.js';+import { rememberDevicePairing, enrollPhone, deviceBoardKeys } 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';import { ENGINE_VERSION } from './engine.js';@@ -20,6 +21,7 @@ function stored(storage, name, fallback) {/** Keep an unauthenticated pairing fragment on the device through the GitHub redirect. */export function rememberPairing() {+ rememberDevicePairing();const fragment = new URLSearchParams(location.hash.slice(1));if (!fragment.has('board') && !fragment.has('key')) return null;const board = fragment.get('board');@@ -263,14 +265,15 @@ export async function createTransport({ onUpdate = () => {} } = {}) {/** Reauthorize the listing, pair only visible boards, and close streams for lost access. */async function listing() {const document = await documentAt('/api/v1/boards', denied);+ Object.assign(keys, stored(localStorage, KEYS, {}));+ Object.assign(keys, await deviceBoardKeys((path, options) => documentAt(path, denied, options)));available = document.boards.filter(board => BOARD.test(board.id) && typeof board.repository === 'string');warnings = document.warnings ?? [];const visible = new Set(available.map(board => board.id));for (const [id, entry] of paired) if (!visible.has(id)) { entry.stream?.close(); paired.delete(id); }for (const board of available) {- if (paired.has(board.id) && pair?.board !== board.id) continue;- Object.assign(keys, stored(localStorage, KEYS, {}));const encoded = pair?.board === board.id ? pair.key : keys[board.id];+ if (paired.has(board.id) && pair?.board !== board.id && encodeBoardKey(paired.get(board.id).key) === encoded) continue;if (!encoded) continue;try {const entry = { id: board.id, key: decodeBoardKey(encoded), cursor: -1, state: null, outbox: null };@@ -390,11 +393,12 @@ export async function createTransport({ onUpdate = () => {} } = {}) {/** Pair a link opened in this already-loaded page as well as one opened on a fresh visit. */async function pairingChanged() {- try { pair = rememberPairing() ?? pair; await listing(); onUpdate(); }+ try { pair = rememberPairing() ?? pair; await enrollPhone((path, options) => documentAt(path, denied, options)); await listing(); onUpdate(); }catch { failure = 'The pairing link is invalid. Get a new link from a linked machine.'; notice(); }}addEventListener('hashchange', pairingChanged);addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });+ await enrollPhone((path, options) => documentAt(path, denied, options));await listing();return {/** Return decoded API state or seal narrow person intent; no board key or plaintext leaves the device. */diff --git a/relay/browser-devices.js b/relay/browser-devices.jsnew file mode 100644index 00000000..105127d2--- /dev/null+++ b/relay/browser-devices.js@@ -0,0 +1,99 @@+/** Keep the phone's non-extractable key in IndexedDB and receive only locally unwrapped keys [H5,H17]. */+import { createDeviceKeys, signDeviceEnrollment, unwrapDeviceBoardKey } from './device-keys.js';+import { encodeBoardKey } from './seal.js';+import { ENGINE_VERSION } from './engine.js';+import { Refused } from './refused.js';++const PENDING = 'pullboard.relay.device-pair.v1';++/** Remove the secret fragment before sign-in or any request and retain it only on this device. */+export function rememberDevicePairing() {+ const fragment = new URLSearchParams(location.hash.slice(1));+ if (!fragment.has('device')) return;+ const code = fragment.get('device');+ if (!/^[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/u.test(code ?? '')) throw new Refused('DEVICE_PAIR_CODE', 'Open a fresh one-time phone pairing link from the Mac.');+ try { sessionStorage.setItem(PENDING, JSON.stringify({ code, expires: Date.now() + 600_000 })); }+ catch { throw new Refused('DEVICE_STORAGE', 'Enable device storage before pairing this phone.'); }+ history.replaceState(null, '', location.pathname + location.search);+}++/** Complete one IndexedDB transaction before its connection is closed or the page continues. */+async function deviceStorage(value) {+ if (!globalThis.indexedDB) throw new Refused('DEVICE_STORAGE', 'Use a secure browser with IndexedDB enabled to pair this phone.');+ const db = await new Promise((resolve, reject) => {+ const request = indexedDB.open('pullboard-relay-device-v1', 1);+ request.onupgradeneeded = () => request.result.createObjectStore('keys');+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(new Refused('DEVICE_STORAGE', 'Enable IndexedDB before pairing this phone.'));+ });+ try {+ return await new Promise((resolve, reject) => {+ const transaction = db.transaction('keys', value === undefined ? 'readonly' : 'readwrite');+ const store = transaction.objectStore('keys');+ const request = value === undefined ? store.get('device') : store.put(value, 'device');+ let result;+ request.onsuccess = () => { result = request.result; };+ transaction.oncomplete = () => resolve(value === undefined ? result ?? null : value);+ transaction.onerror = transaction.onabort = () => reject(new Refused('DEVICE_STORAGE', 'The phone could not retain its private key. Enable device storage and pair again.'));+ });+ } finally { db.close(); }+}++/** Send a public authenticated enrollment while the private key and QR secret remain on the phone. */+export async function enrollPhone(documentAt) {+ rememberDevicePairing();+ let pending;+ try { pending = JSON.parse(sessionStorage.getItem(PENDING)); } catch { return; }+ if (!pending) return;+ if (!/^[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/u.test(pending.code ?? '') || Date.now() >= pending.expires) {+ sessionStorage.removeItem(PENDING);+ throw new Refused('DEVICE_PAIR_EXPIRED', 'Run pullboard relay on --all at the Mac for a fresh phone pairing link.');+ }+ const [locator, secret] = pending.code.split('.');+ const identity = await documentAt('/api/v1/devices/session');+ let device = await deviceStorage();+ if (device?.locator !== locator || device.account !== identity.account) {+ device = { ...await createDeviceKeys(), account: identity.account, locator };+ await deviceStorage(device);+ }+ const body = await signDeviceEnrollment(secret, { v: 1, account: identity.account, locator,+ deviceId: device.deviceId, publicKey: device.publicKey, label: 'Phone browser', createdAt: new Date().toISOString() });+ await documentAt('/api/v1/devices/enrollments/' + locator, {+ method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),+ });+ sessionStorage.removeItem(PENDING);+ // Keep the page open while the foreground Mac authenticates the enrollment and delivers keys.+ while (Date.now() < pending.expires) {+ try {+ const response = await documentAt('/api/v1/devices/' + device.deviceId + '/boards');+ if (response.wraps.length) return;+ } catch (error) { if (error.code !== 'DEVICE_NOT_ENROLLED') throw error; }+ await new Promise(resolve => setTimeout(resolve, 250));+ }+ throw new Refused('DEVICE_PAIR_EXPIRED', 'Keep the Mac setup command open and run pullboard relay on --all for a fresh code.');+}++/** Fetch only the signed-in account's grants and authenticate their context with the stored private key. */+export async function deviceBoardKeys(documentAt) {+ let device;+ try { device = await deviceStorage(); }+ catch (error) { if (error.code === 'DEVICE_STORAGE') return {}; throw error; }+ if (!device) return {};+ const identity = await documentAt('/api/v1/devices/session');+ if (identity.account !== device.account) return {};+ let response;+ try { response = await documentAt('/api/v1/devices/' + device.deviceId + '/boards'); }+ catch (error) { if (error.code === 'DEVICE_NOT_ENROLLED') return {}; throw error; }+ const keys = {};+ for (const row of response.wraps) {+ if (!/^[0-9a-f]{32}$/u.test(row.board ?? '') || row.engine !== ENGINE_VERSION || typeof row.wrapped !== 'string') {+ throw new Refused('DEVICE_WRAP_AUTH', 'Upgrade this phone to read the linked board engine, or pair again.');+ }+ let envelope;+ try { envelope = JSON.parse(atob(row.wrapped.replaceAll('-', '+').replaceAll('_', '/'))); }+ catch { throw new Refused('DEVICE_WRAP_AUTH', 'The wrapped board key could not be authenticated. Pair again.'); }+ keys[row.board] = encodeBoardKey(await unwrapDeviceBoardKey(device.privateKey, envelope,+ { board: row.board, device: device.deviceId, engine: ENGINE_VERSION }));+ }+ return keys;+}diff --git a/relay/browser-page.js b/relay/browser-page.jsindex 8807d394..52202d82 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -23,6 +23,8 @@ function respond(res, type, content, scriptHashes = []) {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/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')]],['/relay/browser-stream.js', ['text/javascript', readFileSync(new URL('./browser-stream.js', import.meta.url), 'utf8')]],diff --git a/relay/device-http.js b/relay/device-http.jsnew file mode 100644index 00000000..27c613c3--- /dev/null+++ b/relay/device-http.js@@ -0,0 +1,71 @@+/** Person-authorized account device enrollment and opaque key delivery [H5,H15,H17]. */+import { apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js';+import { Refused } from '../src/refused.js';+import { devicePublicKey } from '../src/relay-device-keys.js';++/** Require exact bounded action fields, excluding secrets and unrecognized relay metadata. */+function exact(value, fields) {+ if (!value || JSON.stringify(Object.keys(value).sort()) !== JSON.stringify([...fields].sort())) {+ throw new Refused('BAD_REQUEST', 'Send only the documented device action fields.');+ }+ return value;+}++/** Route only fixed device endpoints; ownership always comes from the authenticated session. */+export function createDeviceHandler({ authenticate, authorizeBoard, boardsFor, devices }) {+ 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/session' && req.method === 'GET') {+ apiJson(res, 200, { account }); return true;+ }+ const enrollment = /^\/api\/v1\/devices\/enrollments\/([A-Za-z0-9_-]{22})$/.exec(url.pathname);+ if (enrollment) {+ const locator = enrollment[1];+ if (req.method === 'GET') { apiJson(res, 200, devices.enrollment(account, locator)); return true; }+ if (req.method === 'POST') {+ exact(await readApiBody(req), []);+ devices.begin(account, locator);+ } else if (req.method === 'PUT') {+ const body = exact(await readApiBody(req, { maxBytes: 4096 }), ['v', 'account', 'locator', 'deviceId', 'publicKey', 'label', 'createdAt', 'mac']);+ if (body.v !== 1 || body.account !== account || body.locator !== locator || !/^device-[0-9a-f]{32}$/u.test(body.deviceId ?? '') ||+ !/^[A-Za-z0-9_-]{43}$/u.test(body.mac ?? '') || typeof body.label !== 'string' || !body.label.trim() || body.label.length > 80 ||+ typeof body.createdAt !== 'string' || !Number.isFinite(Date.parse(body.createdAt))) {+ throw new Refused('DEVICE_ENROLLMENT', 'Pair with a fresh link signed in to the same account as the Mac.');+ }+ devicePublicKey(body.publicKey);+ devices.enroll(account, locator, body);+ } else if (req.method === 'DELETE') devices.consume(account, locator);+ else throw new Refused('NO_ENDPOINT', 'Use the supported device enrollment action.');+ apiJson(res, 200, { recorded: true }); return true;+ }+ const route = /^\/api\/v1\/devices\/(device-[0-9a-f]{32})(?:\/boards(?:\/([0-9a-f]{32}))?)?$/.exec(url.pathname);+ if (!route) throw new Refused('NO_ENDPOINT', 'Use a valid paired device id.');+ const [, id, board] = route;+ if (url.pathname.endsWith('/boards') && req.method === 'GET') {+ const visible = new Set((await boardsFor(req)).map(value => value.id));+ apiJson(res, 200, { wraps: devices.wraps(account, id).filter(value => visible.has(value.board)) }); return true;+ }+ if (board && req.method === 'PUT') {+ const principal = await authorizeBoard(req, board);+ if (principal.kind !== 'session' || principal.user.id !== account) throw new Refused('HUMAN_REQUIRED', 'Use the board owner session.');+ const body = exact(await readApiBody(req, { maxBytes: 8192 }), ['engine', 'wrapped']);+ if (!Number.isSafeInteger(body.engine) || body.engine < 1 || typeof body.wrapped !== 'string' || !/^[A-Za-z0-9_-]{1,6000}$/u.test(body.wrapped)) {+ throw new Refused('DEVICE_WRAP', 'Send a versioned client-encrypted device wrap.');+ }+ const bytes = Buffer.from(body.wrapped, 'base64url');+ if (bytes.toString('base64url') !== body.wrapped) throw new Refused('DEVICE_WRAP', 'Send canonical opaque transport bytes.');+ devices.put(account, id, board, body.engine, body.wrapped);+ } else if (!url.pathname.endsWith('/boards') && !board && req.method === 'POST') {+ exact(await readApiBody(req), []); devices.register(account, id);+ } else if (!url.pathname.endsWith('/boards') && !board && req.method === 'DELETE') devices.revoke(account, id);+ else throw new Refused('NO_ENDPOINT', 'Use the supported device action.');+ apiJson(res, 200, { recorded: true }); return true;+ } catch (error) { apiJson(res, apiStatus(error), apiRefusal(error)); return true; }+ };+}diff --git a/relay/device-store.js b/relay/device-store.jsnew file mode 100644index 00000000..c71ad0d8--- /dev/null+++ b/relay/device-store.js@@ -0,0 +1,77 @@+/** Durable account-scoped opaque device wraps and expiring enrollment transport [H5,H15,H17]. */+import { chmodSync } from 'node:fs';+import { join } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { Refused } from '../src/refused.js';++/** Keep device revocations durable so an in-flight native wrap cannot recreate deleted grants. */+export function createDeviceStore({ directory, now = Date.now }) {+ const file = join(directory, 'devices.sqlite');+ const db = new DatabaseSync(file);+ chmodSync(file, 0o600);+ db.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));`);+ /** Require an active account device for reads and writes alike. */+ function active(account, id) {+ if (!db.prepare('SELECT 1 FROM device WHERE account=? AND id=? AND revoked=0').get(account, id)) {+ throw new Refused('DEVICE_NOT_ENROLLED', 'Pair this device from the linked Mac before receiving wrapped board keys.');+ }+ }+ /** Require a live enrollment without renewing its lifetime through subsequent contacts. */+ function pending(account, locator) {+ db.prepare('DELETE FROM enrollment WHERE expires<=?').run(now());+ const row = db.prepare('SELECT * FROM enrollment WHERE account=? AND locator=?').get(account, locator);+ if (!row) throw new Refused('DEVICE_PAIR_EXPIRED', 'Run pullboard relay on --all for a fresh one-time pairing link.');+ return row;+ }+ return {+ /** Initialize an account-owned ten-minute locator without storing its secret. */+ begin(account, locator) {+ db.prepare('DELETE FROM enrollment WHERE expires<=?').run(now());+ db.prepare('INSERT INTO enrollment(account,locator,expires) VALUES(?,?,?)').run(account, locator, now() + 600_000);+ },+ /** Carry the signed public enrollment; the native Mac authenticates its MAC independently. */+ enroll(account, locator, payload) {+ pending(account, locator);+ db.prepare('UPDATE enrollment SET payload=? WHERE account=? AND locator=?').run(JSON.stringify(payload), account, locator);+ },+ /** Return only this account's current public enrollment to its authenticated Mac. */+ enrollment(account, locator) {+ const row = pending(account, locator);+ return { enrollment: row.payload ? JSON.parse(row.payload) : null };+ },+ /** Consume the public transport after the Mac has durably accepted the device key. */+ consume(account, locator) { db.prepare('DELETE FROM enrollment WHERE account=? AND locator=?').run(account, locator); },+ /** Register a Mac-authenticated device id without allowing a revoked id to be reused. */+ register(account, id) {+ const row = db.prepare('SELECT revoked FROM device WHERE account=? AND id=?').get(account, id);+ if (row?.revoked) throw new Refused('DEVICE_REVOKED', 'Create a fresh device key and pair again.');+ db.prepare('INSERT OR IGNORE INTO device(account,id) VALUES(?,?)').run(account, id);+ },+ /** Persist opaque client ciphertext; there is no public-key lookup or decryption operation. */+ put(account, id, board, engine, wrapped) {+ active(account, id);+ db.prepare('INSERT INTO wrapped_key VALUES(?,?,?,?,?) ON CONFLICT(account,device,board) DO UPDATE SET engine=excluded.engine,wrapped=excluded.wrapped').run(account, id, board, engine, wrapped);+ },+ /** List only this account/device's opaque grants; the HTTP boundary rechecks board access. */+ wraps(account, id) {+ active(account, id);+ return db.prepare('SELECT board,engine,wrapped FROM wrapped_key WHERE account=? AND device=? ORDER BY board').all(account, id);+ },+ /** Tombstone first and delete grants atomically, refusing any stale in-flight upload. */+ revoke(account, id) {+ db.exec('BEGIN IMMEDIATE');+ try {+ db.prepare('INSERT INTO device VALUES(?,?,1) ON CONFLICT(account,id) DO UPDATE SET revoked=1').run(account, id);+ db.prepare('DELETE FROM wrapped_key WHERE account=? AND device=?').run(account, id);+ db.exec('COMMIT');+ } catch (error) { db.exec('ROLLBACK'); throw error; }+ },+ /** Delete the unlinked board's grants without changing unrelated devices or boards. */+ unlink(board) { db.prepare('DELETE FROM wrapped_key WHERE board=?').run(board); },+ /** Close the owned database before removing a private test or service directory. */+ close() { db.close(); },+ };+}diff --git a/relay/service.js b/relay/service.jsindex 7dc9dbc6..0d5510fe 100644--- a/relay/service.js+++ b/relay/service.js@@ -7,6 +7,8 @@ import { createApiHandler, apiJson, apiRefusal, apiStatus, readApiBody } from '.import { Refused } from '../src/refused.js';import { createRelayJournal } from './journal.js';import { createRelayRetention } from './retention.js';+import { createDeviceStore } from './device-store.js';+import { createDeviceHandler } from './device-http.js';import { createPairingStore } from './pairing-store.js';import { createPairingHandler } from './pairing-http.js';import { createRelayBrowserHandler } from './browser-page.js';@@ -102,6 +104,13 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginreturn who;}+ const deviceStore = createDeviceStore({ directory: root, now });+ const deviceHandler = createDeviceHandler({+ authenticate: (req, write) => auth.authenticate(credential(req, origin, write)),+ authorizeBoard: (req, id) => authorizedRequest(req, id, true),+ boardsFor: req => auth.boardsFor(credential(req, origin)),+ devices: deviceStore,+ });const pairingStore = createPairingStore({ now });const pairing = createPairingHandler({authenticate: (req, { board, write }) => authorizedRequest(req, board, write),@@ -190,6 +199,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin/** Add authenticated snapshot replacement and deletion to the common versioned read/move paths. */async function handle(req, res) {+ if (await deviceHandler(req, res)) return;if (await pairing(req, res)) return;try {if (browser && await browser(req, res)) return;@@ -229,7 +239,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginconst id = identity(deletion[1]);const who = await authorizedRequest(req, id, true);sender(who, true);- auth.withBoard(id, () => { requireClientVersion(id, who.engineVersion); retention.unlink(id); });+ auth.withBoard(id, () => { requireClientVersion(id, who.engineVersion); retention.unlink(id); deviceStore.unlink(id); });return apiJson(res, 200, { deleted: id });}return await common(req, res);@@ -241,7 +251,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginhandle.maintenance = maintain;handle.backup = retention.backup;handle.maintenanceStatus = () => ({ error: maintenanceError });- handle.close = () => { clearInterval(timer); common.close(); };+ handle.close = () => { clearInterval(timer); common.close(); deviceStore.close(); };return handle;}diff --git a/src/cli.js b/src/cli.jsindex 2e09f19a..e3109acc 100644--- a/src/cli.js+++ b/src/cli.js@@ -54,7 +54,7 @@ import { parseProblems, sweepItems } from './sweep.js';import { renderSpecView } from './view.js';import { tour } from './tour.js';import { commandOutput } from './json.js';-import { forgetProject, registerProject } from './projects.js';+import { forgetProject, registerProjectAndLink } from './projects.js';import { milestoneRoadmap } from './roadmap.js';import { listResources } from './resources.js';import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';@@ -68,6 +68,8 @@ import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';import { relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';+import { 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';@@ -124,6 +126,10 @@ Set uppullboard relay [on|off|pair|join <code>] [--url <address>] link, inspect or unlink this board's sealed relayon signs in through GitHub; the address defaults to https://app.pullboard.devpair prints a one-use machine code; join stores it in another clone+ pullboard relay on --all [--url <address>] link every registered project after one sign-in; pair the phone once+ keep this command open until pairing finishes; later projects link on registration+ pullboard relay devices list paired device ids and their public-key fingerprints+ pullboard relay revoke <device> stop future key delivery; already received keys remain knownpullboard relay tokens list this board's agent token ids, agents and expiry, never credentialspullboard relay revoke <token-id> revoke one token from that list; other agents keep workingpullboard resume where you are: your claim, branch, uncommitted work, what came back,@@ -1091,6 +1097,7 @@ function resumeHere(io) {newest: store.peekShouts(board, me.id, 1),};});+ card.relayProblems = unlinkedRelayProjects();const { me } = card;card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows, ctx.doctrine.rows).map((item) => ({ ...item, ...staleItemFinding(item) }));if (isMain) {@@ -1100,6 +1107,7 @@ function resumeHere(io) {card.reviewQueue = { items: card.toVerify, awaiting: card.awaiting };}const say = (line) => io.say(line);+ for (const problem of card.relayProblems) say(problem.message);const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;say(`resume: ${me.id}${me.family ? ` (${me.family})` : ''}, ${me.lane} lane${isMain ? ', the main checkout' : ''}, at ${root}`);const dirty = dirtyFiles(root).length;@@ -1188,7 +1196,7 @@ async function viewHere(io, values) {}try {const info = repoInfo(io.cwd);- if (info.isMain && existsSync(join(info.root, CONFIG_FILE))) registerProject(info.root, new Date(), loadConfig(info.root));+ if (info.isMain && existsSync(join(info.root, CONFIG_FILE))) await registerProjectAndLink(info.root, new Date(), loadConfig(info.root), io);} catch (error) {if (!(error instanceof Refused)) throw error;}@@ -1215,7 +1223,7 @@ async function viewHere(io, values) {async function serveHere(io, values) {const ctx = context(io);const mainRoot = git(ctx.info.root, ['worktree', 'list', '--porcelain']).split('\n')[0].slice('worktree '.length);- registerProject(mainRoot, new Date(), loadConfig(mainRoot));+ await registerProjectAndLink(mainRoot, new Date(), loadConfig(mainRoot), io);const port = values.port === undefined ? 0 : Number(values.port);if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Refused('USAGE', '--port is a number from 0 to 65535; use 0 to choose a free one');const api = await serveApi({ port, runCommand: main });@@ -1237,11 +1245,11 @@ async function serveHere(io, values) {** @param {any} io* @param {{ first?: string }} args- * @returns {Record<string, () => number>}+ * @returns {Record<string, () => number | Promise<number>>}*/function setupCommands(io, { first, values }) {return {- init: () => {+ init: async () => {const info = repoInfo(io.cwd);const notes = initRepo({info,@@ -1259,7 +1267,7 @@ function setupCommands(io, { first, values }) {io.result?.({ root: info.root, notes });const staging = notes.at(-1)?.startsWith('git add -f -- ') ? notes.at(-1) : null;(staging ? notes.slice(0, -1) : notes).forEach((note) => io.say(note));- if (registerProject(info.root, new Date(), loadConfig(info.root))) io.say('registered this project on this machine, so pullboard view lists it');+ if (await registerProjectAndLink(info.root, new Date(), loadConfig(info.root), io)) io.say('registered this project on this machine, so pullboard view lists it');io.say('next: write SPEC.md rows, declare lanes in pullboard.json, then: pullboard add <lane> <title>');io.say('with an agent: start a new Claude Code session here, which loads the pullboard skills, then tell it what to build; the pullboard-run skill runs the team');if (staging) io.say(staging);@@ -1567,7 +1575,7 @@ function readCommands(io, { first, second, rest, values }) {return 1;}const ctx = context(io);- const problems = [...doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config), ...doctrineProblems(ctx.info.root, ctx.config)];+ const problems = [...doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config), ...doctrineProblems(ctx.info.root, ctx.config), ...unlinkedRelayProjects()];io.result?.({ problems });if (!problems.length) {io.say('board is clean');@@ -2670,6 +2678,24 @@ async function runCommand(argv, io) {if (command === 'hook') return await hookCommand(io, args);if (command === 'settings') return settingsCommand(io, args);if (command === 'relay') {+ if (first === 'devices') {+ if (second || rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay devices');+ const devices = readRelayMachine().devices.map(({ deviceId, label, fingerprint, createdAt }) => ({ deviceId, label, fingerprint, createdAt }));+ io.result?.({ devices });+ for (const device of devices) io.say(`${device.deviceId} ${device.label} ${device.fingerprint}`);+ if (!devices.length) io.say('no paired devices; run pullboard relay on --all');+ return 0;+ }+ if (first === 'revoke' && /^device-[0-9a-f]{32}$/u.test(second ?? '')) {+ if (rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay revoke <device>');+ const result = await revokeRelayDevice(second, io);+ io.result?.(result); io.say(result.notice); return 0;+ }+ if (values.all) {+ if (first !== 'on' || second || rest.length) throw new Refused('USAGE', 'pullboard relay on --all [--url <address>]');+ const result = await relayOnAll(values.url, io);+ io.result?.(result); return result.failed.length ? 1 : 0;+ }if (['tokens', 'revoke'].includes(first)) {if (rest.length || values.url || (first === 'tokens' && second) || (first === 'revoke' && !second)) {throw new Refused('USAGE', 'pullboard relay tokens, or pullboard relay revoke <token-id>');diff --git a/src/projects.js b/src/projects.jsindex 87fdf8ec..d753574f 100644--- a/src/projects.js+++ b/src/projects.js@@ -259,3 +259,11 @@ export function forgetProject(path) {return true;});}++/** Register locally and complete opted-in automatic relay linking before the CLI returns. */+export async function registerProjectAndLink(root, now, config, io) {+ const added = registerProject(root, now, config);+ const { autoLinkProject } = await import('./relay-setup.js');+ await autoLinkProject(root, io);+ return added;+}diff --git a/src/relay-device-keys.js b/src/relay-device-keys.jsnew file mode 100644index 00000000..b875937d--- /dev/null+++ b/src/relay-device-keys.js@@ -0,0 +1,160 @@+/** Authenticate device enrollment and wrap board keys only on clients [H5,H15,H17]. */+import { Refused } from './refused.js';++const encoder = new TextEncoder();+const DEVICE = /^device-[0-9a-f]{32}$/u;+const BOARD = /^[0-9a-f]{32}$/u;+const LOCATOR = /^[A-Za-z0-9_-]{22}$/u;++/** Encode transport bytes canonically without relying on a Node-only Buffer. */+function encode(bytes) {+ return btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');+}++/** Refuse malformed or noncanonical bytes without echoing a secret. */+function decode(value, length) {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/u.test(value)) throw new Refused('DEVICE_FORMAT', 'Use a fresh device pairing link.');+ let bytes;+ try {+ bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), character => character.charCodeAt(0));+ } catch { throw new Refused('DEVICE_FORMAT', 'Use a fresh device pairing link.'); }+ if (bytes.length !== length || encode(bytes) !== value) throw new Refused('DEVICE_FORMAT', 'Use a fresh device pairing link.');+ return bytes;+}++/** Require browser or Node WebCrypto; no private key is exported as a fallback. */+function platform() {+ if (!globalThis.crypto?.subtle) throw new Refused('DEVICE_CRYPTO', 'Use Node 22 or a secure browser with WebCrypto.');+ return globalThis.crypto;+}++/** Copy only the public coordinates of a P-256 key, rejecting a supplied private half. */+export function devicePublicKey(value) {+ if (!value || value.kty !== 'EC' || value.crv !== 'P-256' || value.d !== undefined ||+ Object.keys(value).some(key => !['kty', 'crv', 'x', 'y', 'ext', 'key_ops'].includes(key))) {+ throw new Refused('DEVICE_KEY', 'Pair a device with a public ECDH P-256 key.');+ }+ decode(value.x, 32);+ decode(value.y, 32);+ return { kty: 'EC', crv: 'P-256', x: value.x, y: value.y };+}++/** Make a persistent non-extractable private device key for IndexedDB storage. */+export async function createDeviceKeys() {+ const crypto = platform();+ const pair = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits']);+ return { deviceId: 'device-' + [...crypto.getRandomValues(new Uint8Array(16))].map(byte => byte.toString(16).padStart(2, '0')).join(''),+ privateKey: pair.privateKey, publicKey: devicePublicKey(await crypto.subtle.exportKey('jwk', pair.publicKey)) };+}++/** Bind the exact public key and account to one short-lived pairing locator. */+function enrollment(value) {+ if (!value || value.v !== 1 || !DEVICE.test(value.deviceId ?? '') || !LOCATOR.test(value.locator ?? '') ||+ typeof value.account !== 'string' || !value.account || value.account.length > 128 ||+ typeof value.label !== 'string' || !value.label.trim() || value.label.length > 80 || /[\u0000-\u001f\u007f]/u.test(value.label) ||+ typeof value.createdAt !== 'string' || !Number.isFinite(Date.parse(value.createdAt))) {+ throw new Refused('DEVICE_ENROLLMENT', 'Create a fresh one-time device pairing link.');+ }+ decode(value.locator, 16);+ return { v: 1, account: value.account, locator: value.locator, deviceId: value.deviceId,+ publicKey: devicePublicKey(value.publicKey), label: value.label, createdAt: value.createdAt };+}++/** Serialize an enrollment in one fixed field order for its authenticated MAC. */+function enrollmentBytes(value) {+ return encoder.encode(JSON.stringify(['pullboard-device-enroll', 1, value.account, value.locator,+ value.deviceId, value.publicKey, value.label, value.createdAt]));+}++/** Derive a domain-separated HMAC key from the QR-only secret and enrollment context. */+async function enrollmentKey(secret, value) {+ if (typeof secret !== 'string' && !(secret instanceof Uint8Array)) throw new Refused('DEVICE_PAIR_SECRET', 'Use the one-time secret from the pairing QR fragment.');+ const bytes = typeof secret === 'string' ? decode(secret, 32) : new Uint8Array(secret);+ if (bytes.length !== 32) throw new Refused('DEVICE_PAIR_SECRET', 'Use the one-time secret from the pairing QR fragment.');+ const subtle = platform().subtle;+ const material = await subtle.importKey('raw', bytes, 'HKDF', false, ['deriveKey']);+ return await subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: decode(value.locator, 16),+ info: encoder.encode(JSON.stringify(['pullboard-device-auth', 1, value.account, value.locator])) },+ material, { name: 'HMAC', hash: 'SHA-256', length: 256 }, false, ['sign', 'verify']);+}++/** Sign a phone's enrollment locally; the relay receives the public key and MAC, never the secret. */+export async function signDeviceEnrollment(secret, value) {+ const body = enrollment(value);+ const key = await enrollmentKey(secret, body);+ return { ...body, mac: encode(new Uint8Array(await platform().subtle.sign('HMAC', key, enrollmentBytes(body)))) };+}++/** Authenticate the relay-carried enrollment before the Mac records a device or wraps any key. */+export async function authenticateDeviceEnrollment(secret, value, expected) {+ const body = enrollment(value);+ if (body.account !== expected.account || body.locator !== expected.locator) {+ throw new Refused('DEVICE_ENROLL_AUTH', 'The pairing account or locator changed. Create a fresh pairing link.');+ }+ const mac = decode(value.mac, 32);+ const key = await enrollmentKey(secret, body);+ if (!await platform().subtle.verify('HMAC', key, mac, enrollmentBytes(body))) {+ throw new Refused('DEVICE_ENROLL_AUTH', 'The device public key was changed or the pairing secret is wrong. Create a fresh pairing link.');+ }+ try { await platform().subtle.importKey('jwk', body.publicKey, { name: 'ECDH', namedCurve: 'P-256' }, false, []); }+ catch { throw new Refused('DEVICE_KEY', 'Pair again with a valid ECDH P-256 public key.'); }+ return { deviceId: body.deviceId, publicKey: body.publicKey,+ fingerprint: [...new Uint8Array(await platform().subtle.digest('SHA-256', encoder.encode(JSON.stringify(body.publicKey))))]+ .map(byte => byte.toString(16).padStart(2, '0')).join(''), label: body.label, createdAt: body.createdAt };+}++/** Validate the expected board, device and engine instead of trusting a relay envelope's context. */+function binding(value) {+ if (!value || !BOARD.test(value.board ?? '') || !DEVICE.test(value.device ?? '') ||+ !Number.isSafeInteger(value.engine) || value.engine < 1) {+ throw new Refused('DEVICE_WRAP_BINDING', 'Name the linked board, paired device and supported engine version.');+ }+ return { board: value.board, device: value.device, engine: value.engine };+}++/** Derive one AES key with the ephemeral public key as salt and board/device-specific HKDF info. */+async function wrappingKey(privateKey, publicKey, ephemeral, context, usages) {+ const subtle = platform().subtle;+ const peer = await subtle.importKey('jwk', devicePublicKey(publicKey), { name: 'ECDH', namedCurve: 'P-256' }, false, []);+ const shared = await subtle.deriveBits({ name: 'ECDH', public: peer }, privateKey, 256);+ const material = await subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey']);+ const salt = await subtle.exportKey('raw', await subtle.importKey('jwk', devicePublicKey(ephemeral), { name: 'ECDH', namedCurve: 'P-256' }, true, []));+ return await subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt,+ info: encoder.encode(JSON.stringify(['pullboard-wrap-v1', context.board, context.device])) },+ material, { name: 'AES-GCM', length: 256 }, false, usages);+}++/** Bind the versioned wrap to the expected device, board and executable engine. */+function wrapAAD(context) {+ return encoder.encode(JSON.stringify(['pullboard-device-wrap', 1, context.board, context.device, context.engine]));+}++/** Wrap a board key to a locally trusted public key; roster selection belongs to the native caller. */+export async function wrapDeviceBoardKey(key, publicKey, value) {+ const context = binding(value);+ if (!(key instanceof Uint8Array) || key.length !== 32) throw new Refused('DEVICE_WRAP_KEY', 'Use this linked board’s 32-byte device-only key.');+ const raw = new Uint8Array(key);+ const recipient = devicePublicKey(publicKey);+ const crypto = platform();+ const pair = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits']);+ const ephemeral = devicePublicKey(await crypto.subtle.exportKey('jwk', pair.publicKey));+ let derived;+ try { derived = await wrappingKey(pair.privateKey, recipient, ephemeral, context, ['encrypt']); }+ catch { throw new Refused('DEVICE_KEY', 'Pair again with a valid ECDH P-256 public key.'); }+ const nonce = crypto.getRandomValues(new Uint8Array(12));+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: wrapAAD(context), tagLength: 128 }, derived, raw);+ return { v: 1, ...context, ephemeral, nonce: encode(nonce), ciphertext: encode(new Uint8Array(ciphertext)) };+}++/** Unwrap only with the phone's stored private key and caller-supplied expected context. */+export async function unwrapDeviceBoardKey(privateKey, envelope, expected) {+ const context = binding(expected);+ if (!envelope || envelope.v !== 1 || envelope.board !== context.board || envelope.device !== context.device || envelope.engine !== context.engine) {+ throw new Refused('DEVICE_WRAP_AUTH', 'The wrapped board key belongs to another device or board. Pair again.');+ }+ try {+ const derived = await wrappingKey(privateKey, envelope.ephemeral, envelope.ephemeral, context, ['decrypt']);+ return new Uint8Array(await platform().subtle.decrypt({ name: 'AES-GCM', iv: decode(envelope.nonce, 12),+ additionalData: wrapAAD(context), tagLength: 128 }, derived, decode(envelope.ciphertext, 48)));+ } catch { throw new Refused('DEVICE_WRAP_AUTH', 'The wrapped board key could not be authenticated. Pair again.'); }+}diff --git a/src/relay-machine.js b/src/relay-machine.jsnew file mode 100644index 00000000..c0b1a4c0--- /dev/null+++ b/src/relay-machine.js@@ -0,0 +1,142 @@+/** Owner-only machine sessions, 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 { homedir } from 'node:os';+import { join } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { authenticateDeviceEnrollment, devicePublicKey, wrapDeviceBoardKey } from './relay-device-keys.js';+import { createPairingCode } from './pairing.js';+import { Refused } from './refused.js';++const DEVICE = /^device-[0-9a-f]{32}$/u;++/** Locate only the private machine directory; repositories never carry these credentials. */+function directory() {+ return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'relay-machine');+}++/** Refuse symlinks, non-owner files or broader permissions before reading machine secrets. */+function privateEntry(path, folder = false) {+ const stat = lstatSync(path);+ if (stat.isSymbolicLink() || (folder ? !stat.isDirectory() : !stat.isFile()) || (stat.mode & 0o077) ||+ (typeof process.getuid === 'function' && stat.uid !== process.getuid())) {+ throw new Refused('RELAY_MACHINE_STORAGE', 'Restore owner-only relay-machine storage: directory mode 700, files mode 600.');+ }+}++/** 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: [] };+}++/** 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) ||+ !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 ?? '') ||+ 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.');+ }+ 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() {+ const folder = directory();+ if (!existsSync(folder)) return emptyState();+ privateEntry(folder, true);+ const file = join(folder, 'state.json');+ if (!existsSync(file)) return emptyState();+ privateEntry(file);+ let state;+ try { state = JSON.parse(readFileSync(file, 'utf8')); }+ catch { throw new Refused('RELAY_MACHINE_STORAGE', 'Restore valid machine relay settings before signing in or pairing again.'); }+ return validate(state);+}++/** Serialize cross-process read-modify-write and atomically replace the private machine file. */+export function updateRelayMachine(mutate) {+ const folder = directory();+ mkdirSync(folder, { recursive: true, mode: 0o700 });+ privateEntry(folder, true);+ const lock = join(folder, 'lock.sqlite');+ try { closeSync(openSync(lock, 'wx', 0o600)); } catch (error) { if (error.code !== 'EEXIST') throw error; }+ privateEntry(lock);+ const db = new DatabaseSync(lock);+ let temporary;+ try {+ 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();+ const result = mutate(state);+ validate(state);+ temporary = join(folder, `state.${process.pid}.${randomUUID()}.tmp`);+ const fd = openSync(temporary, 'wx', 0o600);+ try { writeFileSync(fd, JSON.stringify(state) + '\n'); fsyncSync(fd); }+ finally { closeSync(fd); }+ renameSync(temporary, join(folder, 'state.json'));+ db.exec('COMMIT');+ return result;+ } catch (error) {+ try { db.exec('ROLLBACK'); } catch { /* No transaction may have started. */ }+ throw error;+ } finally {+ db.close();+ if (temporary) rmSync(temporary, { force: true });+ }+}++/** Persist a fresh ten-minute pairing secret locally before publishing its public locator. */+export function beginDeviceEnrollment(board, session, now = Date.now()) {+ const code = createPairingCode(board);+ const pending = { ...code, account: session.account, url: session.url, expires: now + 10 * 60_000 };+ updateRelayMachine(state => { state.pending = pending; });+ return pending;+}++/** Authenticate before recording, and consume the local secret atomically so no relay replay can enroll twice. */+export async function acceptDeviceEnrollment(value, now = Date.now()) {+ const pending = readRelayMachine().pending;+ if (!pending || now >= pending.expires) throw new Refused('DEVICE_PAIR_EXPIRED', 'Run pullboard relay on --all again for a fresh pairing link.');+ const device = await authenticateDeviceEnrollment(pending.secret, value, pending);+ return updateRelayMachine(state => {+ if (!state.pending || state.pending.locator !== pending.locator || state.pending.secret !== pending.secret || Date.now() >= state.pending.expires) {+ throw new Refused('DEVICE_PAIR_USED', 'The one-time pairing link was used or expired. Run pullboard relay on --all again.');+ }+ if (state.devices.some(entry => entry.deviceId === device.deviceId)) throw new Refused('DEVICE_EXISTS', 'Use a fresh device key for this pairing link.');+ const recorded = { ...device, account: pending.account, url: pending.url };+ state.devices.push(recorded);+ state.pending = null;+ return recorded;+ });+}++/** Wrap only to a key authenticated into this Mac's roster, never to a relay-returned public key. */+export async function wrapForRecordedDevice(boardKey, context, owner) {+ const device = readRelayMachine().devices.find(entry => entry.deviceId === context.device && entry.account === owner.account && entry.url === owner.url);+ if (!device) throw new Refused('DEVICE_NOT_ENROLLED', 'Pair this device with this Mac before sending it any board keys.');+ const wrapped = await wrapDeviceBoardKey(boardKey, device.publicKey, context);+ const current = readRelayMachine().devices.find(entry => entry.deviceId === context.device && entry.account === owner.account && entry.url === owner.url);+ if (!current || current.fingerprint !== device.fingerprint) throw new Refused('DEVICE_REVOKED', 'This device was revoked while wrapping; pair again before sending keys.');+ return wrapped;+}++/** Stop local wrapping first and retain a durable remote deletion intent until the relay acknowledges it. */+export function removeRecordedDevice(deviceId) {+ if (!DEVICE.test(deviceId ?? '')) throw new Refused('DEVICE_ID', 'Name the paired device id printed by pullboard relay devices.');+ return updateRelayMachine(state => {+ const device = state.devices.find(entry => entry.deviceId === deviceId);+ const queued = state.revocations.find(entry => entry.deviceId === deviceId);+ if (!device && !queued) throw new Refused('DEVICE_NOT_ENROLLED', 'List paired devices with pullboard relay devices, then name one to revoke.');+ state.devices = state.devices.filter(entry => entry.deviceId !== deviceId);+ if (device && !queued) state.revocations.push({ deviceId, account: device.account, url: device.url });+ return queued ?? { deviceId, account: device.account, url: device.url };+ });+}diff --git a/src/relay-setup.js b/src/relay-setup.jsnew file mode 100644index 00000000..d5389363--- /dev/null+++ b/src/relay-setup.js@@ -0,0 +1,130 @@+/** Set up a machine once, enroll its phone in the foreground and link later registrations [H5,H17]. */+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 { terminalQr } from './qr.js';+import { Refused } from './refused.js';++/** Return local opt-in gaps without contacting the relay or renewing a person session. */+export function unlinkedRelayProjects() {+ const machine = readRelayMachine();+ 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' }];+ });+}++/** Link one registered project through the previously authorized machine session, with no prompt. */+export async function autoLinkProject(root, io) {+ const machine = readRelayMachine();+ const project = repoInfo(root).root;+ if (!machine.autoLink || machine.excluded.includes(project)) 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 });+ } 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'}`);+ }+}++/** 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);+ 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. */+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.' };+}++/** Link every non-excluded registry entry, collecting project-specific partial failures. */+async function linkProjects(session, io) {+ const machine = readRelayMachine();+ const linked = [];+ const failed = [];+ for (const project of listApiProjects()) {+ if (machine.excluded.includes(project.root)) continue;+ try {+ const result = await relayOn(project.root, session.url, io, { session, quiet: true, strict: true });+ linked.push({ project: project.name, root: project.root, board: result.board });+ io.say(`linked: ${project.name}`);+ } catch (error) {+ const reason = error instanceof Refused ? error.message : 'Restore this registered project and retry.';+ failed.push({ project: project.name, root: project.root, reason });+ io.err(`not linked: ${project.name}; ${reason}`);+ }+ }+ return { linked, failed };+}++/** Publish a one-use public locator and wait in this command; no service or unattended daemon is added. */+async function pairFirstDevice(session, board, linked, io) {+ const pending = beginDeviceEnrollment(board, session);+ const path = '/api/v1/devices/enrollments/' + pending.locator;+ await relayDeviceRequest(session, path, { method: 'POST', body: {} }, io);+ const link = session.url + '/#device=' + pending.locator + '.' + pending.secret;+ io.say('Pair your phone once: ' + link);+ try { io.say(terminalQr(link)); }+ catch (error) { if (error.code !== 'PAIR_LINK_LONG') throw error; io.say('Open the pairing link above.'); }+ let interrupted = false;+ /** End foreground pairing without discarding successful board links or saving a partial device. */+ const stop = () => { interrupted = true; };+ process.once('SIGINT', stop);+ process.once('SIGTERM', stop);+ try {+ while (!interrupted && Date.now() < pending.expires) {+ const result = await relayDeviceRequest(session, path, {}, io);+ if (interrupted) break;+ if (result.enrollment) {+ const device = await acceptDeviceEnrollment(result.enrollment);+ await relayDeviceRequest(session, '/api/v1/devices/' + device.deviceId, { method: 'POST', body: {} }, io);+ await relayDeviceRequest(session, path, { method: 'DELETE' }, io);+ for (const project of linked) await deliverDeviceWraps(project.root, io);+ io.say('Phone paired; current and future linked boards will appear here.');+ return { paired: true, deviceId: device.deviceId };+ }+ await new Promise(resolve => { setTimeout(resolve, 500); });+ }+ io.say('Boards linked; phone pairing stopped. Run pullboard relay on --all for a fresh code.');+ return { paired: false, interrupted };+ } finally {+ process.off('SIGINT', stop); process.off('SIGTERM', stop);+ updateRelayMachine(state => { if (state.pending?.locator === pending.locator) state.pending = null; });+ // Best-effort remove the public locator. Its relay lifetime remains ten minutes on an outage.+ try { await relayDeviceRequest(session, path, { method: 'DELETE' }, io); } catch { /* Never undo completed links after a pairing timeout. */ }+ }+}++/** Save the account session once, link all projects and only wait when this Mac has no paired phone. */+export async function relayOnAll(address, io) {+ 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);+ 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 }+ : await pairFirstDevice(session, result.linked[0].board, result.linked, io);+ return { ...result, ...pairing, autoLink: true };+}diff --git a/src/relay.js b/src/relay.jsindex c80acfa2..b84b5f09 100644--- a/src/relay.js+++ b/src/relay.js@@ -1,4 +1,4 @@-/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H16,P5]. */+/** 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 { dirname, join } from 'node:path';@@ -14,6 +14,7 @@ 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';export const DEFAULT_RELAY = 'https://app.pullboard.dev';@@ -22,7 +23,7 @@ const WARNED_COMMANDS = new WeakSet();const KEY_WARNED_COMMANDS = new WeakSet();/** Require a trusted origin; HTTP exists only for loopback development and test relays. */-function relayOrigin(address) {+export function relayOrigin(address) {let url;try { url = new URL(address); } catch { throw new Refused('RELAY_URL', 'use an HTTPS relay address, such as https://app.pullboard.dev'); }if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||@@ -543,6 +544,7 @@ export async function syncRelay(root, io) {io.err(`pullboard: the relay ${state.url} did not sequence the previous move; retry that move explicitly if still wanted`);}if (state.checkpoint || state.presentationDigest !== presentationDigest(relayPresentation(root))) await publishCheckpoint(root, file, state, io);+ await deliverDeviceWraps(root, io);return summary(root, state);}catch (error) {@@ -671,7 +673,7 @@ 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) {+export async function relayOn(root, address, io, { session, quiet = false, strict = false } = {}) {const repository = originRepository(root);const file = linkFile(root);return locked(file, async () => {@@ -680,7 +682,8 @@ export async function relayOn(root, address, io) {const 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 = await deviceSignIn(url, io);+ const signed = 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) => {startRelayEpoch(board);@@ -693,6 +696,7 @@ export async function relayOn(root, address, io) {tokenId: signed.id, keyStorage, presentationDigest: presentationDigest(snapshot.document.presentation), sequence: 0, cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, 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) {@@ -710,16 +714,19 @@ export async function relayOn(root, address, io) {}await ensureOrdered(root, file, state, io);await catchUp(root, file, state, io);- result = summary(root, state, { pairing: true });+ await deliverDeviceWraps(root, io);+ updateRelayMachine(machine => { machine.excluded = machine.excluded.filter(entry => entry !== repoInfo(root).root); });+ result = summary(root, state, { pairing: !quiet });}- catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}; pending records are queued for the next command`); result = summary(root, state, { pairing: true }); }- io.say(terminalQr(result.link));+ catch (error) { if (strict || !(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}; pending records are queued for the next command`); result = summary(root, state, { pairing: !quiet }); }+ if (!quiet) io.say(terminalQr(result.link));return result;});}/** Remove the remote board and its link before forgetting this device's private key and metadata. */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);@@ -749,3 +756,33 @@ export async function relayRequestDevice(root) {return state.requestDevice;});}++/** Sign in once for machine setup; the saved account is the provider-authenticated identity. */+export async function relayMachineSignIn(address, io) {+ 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.');+ return { token: signed.token, id: signed.id, account: signed.user.id, url };+}++/** Share the existing bounded transport only with fixed account/device endpoints. */+export async function relayDeviceRequest(session, path, options, io) {+ if (!path.startsWith('/api/v1/devices/')) throw new Refused('DEVICE_ENDPOINT', 'Use a supported relay device action.');+ return await request(session, path, options, io);+}++/** Deliver wraps only from the private local roster, rechecking revocation before each upload. */+export async function deliverDeviceWraps(root, io) {+ const state = loadLink(linkFile(root));+ if (!state || state.unlinking || !state.account) return;+ const devices = readRelayMachine().devices.filter(device => device.account === state.account && device.url === state.url);+ if (!devices.length) return;+ const key = readBoardKey(state.board);+ 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);+ }+}diff --git a/src/tour.js b/src/tour.jsindex 92f10234..d2aecdda 100644--- a/src/tour.js+++ b/src/tour.js@@ -10,7 +10,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';import { loadConfig } from './config.js';-import { registerProject } from './projects.js';+import { registerProjectAndLink } from './projects.js';const BIN = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));@@ -79,9 +79,9 @@ function pause(ms) {* Run the tour. Pauses only when a person is watching a terminal.** @param {{ say: (line: string) => void, stdout: any }} io- * @returns {number}+ * @returns {Promise<number>}*/-export function tour(io) {+export async function tour(io) {const color = colorEnabled(io);const pace = io.stdout.isTTY ? 1 : 0;const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-tour-')));@@ -188,7 +188,7 @@ export function tour(io) {io.say(`The repo is at ${repo}`);return 1;}- registerProject(repo, new Date(), loadConfig(repo));+ await registerProjectAndLink(repo, new Date(), loadConfig(repo), io);io.say('\nNothing shipped until a second agent verified it.');io.say(`Look around: cd ${repo} && pullboard log`);io.say('see it: pullboard view');diff --git a/test/relay-device-http.test.js b/test/relay-device-http.test.jsnew file mode 100644index 00000000..ef97c094--- /dev/null+++ b/test/relay-device-http.test.js@@ -0,0 +1,226 @@+/** Real auth, SQLite and loopback HTTP [H5,H15,H17]. */+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import { once } from 'node:events';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { randomBytes } from 'node:crypto';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { createAuthHandler } from '../relay/auth-http.js';+import { createGitHubClient } from '../relay/github.js';+import { createRelayAuth } from '../relay/auth.js';+import { createRelayHandler } from '../relay/service.js';+import { ENGINE_VERSION } from '../src/machine.js';+import {+ authenticateDeviceEnrollment,+ createDeviceKeys,+ signDeviceEnrollment,+ unwrapDeviceBoardKey,+ wrapDeviceBoardKey,+} from '../src/relay-device-keys.js';+import { githubFixture } from './relay-fixture.js';++/** Start actual relay/auth HTTP handlers with private SQLite and a real GitHub protocol fixture. */+async function relayDeviceFixture(t) {+ const provider = await githubFixture(t);+ const root = mkdtempSync(join(tmpdir(), 'pullboard-device-http-'));+ const relayDirectory = join(root, 'relay');+ let now = Date.now();+ let auth;+ let relay;+ let authHandler;+ const server = createServer(async (req, res) => {+ if (await authHandler(req, res)) return;+ await relay(req, res);+ });+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ const origin = `http://127.0.0.1:${server.address().port}`;+ const githubConfig = { ...provider.config, callbackURL: origin + '/auth/github/callback' };++ /** Reopen both persistent databases as a new relay process would. */+ function restart() {+ relay?.close();+ auth?.close();+ auth = createRelayAuth({ database: join(root, 'auth.sqlite'), github: createGitHubClient(githubConfig), now: () => now });+ relay = createRelayHandler({ directory: relayDirectory, auth, publicOrigin: origin, now: () => now, maintenanceMs: 0 });+ authHandler = createAuthHandler({ auth, publicOrigin: origin });+ }+ restart();+ t.after(() => {+ server.closeAllConnections();+ server.close();+ relay?.close();+ auth?.close();+ rmSync(root, { recursive: true, force: true });+ });+ return { ...provider, root, relayDirectory, origin, get auth() { return auth; }, advance(ms) { now += ms; }, restart };+}++/** Complete the real browser redirect flow and retain only the person session cookie. */+async function browserSession(box) {+ const start = await fetch(box.origin + '/auth/github/start', { redirect: 'manual' });+ const binding = start.headers.getSetCookie()[0].split(';')[0];+ const grant = await fetch(start.headers.get('location'), { redirect: 'manual' });+ const callback = await fetch(grant.headers.get('location'), { redirect: 'manual', headers: { cookie: binding } });+ assert.equal(callback.status, 303);+ return callback.headers.getSetCookie().find(value => value.startsWith('pb_session=')).split(';')[0];+}++/** Send one JSON request to the real relay endpoint with a bearer or browser session. */+async function deviceRequest(box, path, { method = 'GET', token, cookie, origin, body, engine } = {}) {+ const headers = {+ ...(token ? { authorization: `Bearer ${token}` } : {}),+ ...(cookie ? { cookie } : {}),+ ...(origin ? { origin } : {}),+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),+ ...(engine === undefined ? {} : { 'x-pullboard-engine': String(engine) }),+ };+ const response = await fetch(box.origin + path, { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { response, document: await response.json() };+}++/** Create the exact public enrollment body that the paired phone signs with its one-use secret. */+async function signedDevice(box, account, locator) {+ const keys = await createDeviceKeys();+ const secret = randomBytes(32);+ const input = { v: 1, account, locator, deviceId: keys.deviceId, publicKey: keys.publicKey,+ label: 'Fixture phone', createdAt: new Date().toISOString() };+ return { keys, secret, input, signed: await signDeviceEnrollment(secret, input) };+}++test('relay devices isolate accounts, persist opaque wraps, expire enrollments and tombstone revocation [H5,H15,H17]', async (t) => {+ const box = await relayDeviceFixture(t);+ const cookieA = await browserSession(box);+ const identityA = await deviceRequest(box, '/auth/session', { cookie: cookieA });+ assert.equal(identityA.document.session.user.id, '7');+ const boardA = 'a'.repeat(32);+ const linkA = await deviceRequest(box, '/auth/boards/link', { method: 'POST', cookie: cookieA, origin: box.origin,+ body: { board: boardA, repository: 'fixture/repository' } });+ assert.equal(linkA.response.status, 200);++ // A cookie write from another origin is refused before it creates the pending enrollment.+ const rejectedCookieWrite = await deviceRequest(box, '/api/v1/devices/enrollments/AAAAAAAAAAAAAAAAAAAAAA', {+ method: 'POST', cookie: cookieA, origin: 'https://foreign.invalid', body: {},+ });+ assert.equal(rejectedCookieWrite.document.error?.code, 'BAD_ORIGIN');++ const locator = Buffer.from(randomBytes(16)).toString('base64url');+ const pair = await signedDevice(box, identityA.document.session.user.id, locator);+ const begin = await deviceRequest(box, `/api/v1/devices/enrollments/${locator}`, {+ method: 'POST', cookie: cookieA, origin: box.origin, body: {},+ });+ assert.equal(begin.response.status, 200);+ const upload = await deviceRequest(box, `/api/v1/devices/enrollments/${locator}`, {+ method: 'PUT', cookie: cookieA, origin: box.origin, body: pair.signed,+ });+ assert.equal(upload.response.status, 200);++ // A second real GitHub account cannot read this account's enrollment or use its device id.+ box.state.accountID = 8;+ const cookieB = await browserSession(box);+ const identityB = await deviceRequest(box, '/auth/session', { cookie: cookieB });+ assert.equal(identityB.document.session.user.id, '8');+ const hiddenEnrollment = await deviceRequest(box, `/api/v1/devices/enrollments/${locator}`, { cookie: cookieB });+ assert.equal(hiddenEnrollment.document.error?.code, 'DEVICE_PAIR_EXPIRED');++ // Restore provider identity for the existing A session; the enrollment arrives unchanged for local MAC validation.+ box.state.accountID = 7;+ const delivered = await deviceRequest(box, `/api/v1/devices/enrollments/${locator}`, { cookie: cookieA, origin: box.origin });+ assert.deepEqual(delivered.document.enrollment, pair.signed);+ const accepted = await authenticateDeviceEnrollment(pair.secret, delivered.document.enrollment, {+ account: identityA.document.session.user.id, locator,+ });+ assert.deepEqual(accepted.publicKey, pair.keys.publicKey);+ const registered = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}`, {+ method: 'POST', cookie: cookieA, origin: box.origin, body: {},+ });+ assert.equal(registered.response.status, 200);+ const consumed = await deviceRequest(box, `/api/v1/devices/enrollments/${locator}`, {+ method: 'DELETE', cookie: cookieA, origin: box.origin,+ });+ assert.equal(consumed.response.status, 200);++ const boardKey = new Uint8Array(randomBytes(32));+ const wrap = await wrapDeviceBoardKey(boardKey, accepted.publicKey, {+ board: boardA, device: pair.keys.deviceId, engine: ENGINE_VERSION,+ });+ const wrapped = Buffer.from(JSON.stringify(wrap)).toString('base64url');+ const putWrap = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards/${boardA}`, {+ method: 'PUT', cookie: cookieA, origin: box.origin, engine: ENGINE_VERSION,+ body: { engine: ENGINE_VERSION, wrapped },+ });+ assert.equal(putWrap.response.status, 200);+ const wraps = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards`, {+ cookie: cookieA, origin: box.origin,+ });+ const deliveredWrap = JSON.parse(Buffer.from(wraps.document.wraps[0].wrapped, 'base64url').toString('utf8'));+ assert.deepEqual(await unwrapDeviceBoardKey(pair.keys.privateKey, deliveredWrap, {+ board: boardA, device: pair.keys.deviceId, engine: ENGINE_VERSION,+ }), boardKey);++ // Neither the raw key nor its transport string appears in the durable relay device database.+ const deviceDb = readFileSync(join(box.relayDirectory, 'devices.sqlite'));+ assert.equal(deviceDb.includes(boardKey), false);+ assert.equal(deviceDb.includes(Buffer.from(boardKey).toString('base64url')), false);++ // The independent account and an agent credential cannot retrieve the owner's wraps.+ const crossAccount = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards`, {+ cookie: cookieB,+ });+ assert.equal(crossAccount.document.error?.code, 'DEVICE_NOT_ENROLLED');+ // Even if the other account can write this repository, it cannot add data to A's device id.+ box.state.permissionAccountID = 8;+ const foreignPut = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards/${boardA}`, {+ method: 'PUT', cookie: cookieB, origin: box.origin, engine: ENGINE_VERSION,+ body: { engine: ENGINE_VERSION, wrapped },+ });+ assert.equal(foreignPut.document.error?.code, 'DEVICE_NOT_ENROLLED');+ box.state.permissionAccountID = 7;+ const issued = await deviceRequest(box, '/auth/tokens', { method: 'POST', cookie: cookieA, origin: box.origin,+ body: { board: boardA, agent: 'fixture-agent' } });+ assert.equal(issued.response.status, 201);+ const agentRead = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards`, { token: issued.document.token });+ assert.equal(agentRead.document.error?.code, 'TOKEN_BOARD');++ // A new service/auth process sees the same persisted device and ciphertext without the key in its DB.+ box.restart();+ const afterRestart = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards`, {+ cookie: cookieA, origin: box.origin,+ });+ assert.equal(afterRestart.response.status, 200);+ const persistedWrap = JSON.parse(Buffer.from(afterRestart.document.wraps[0].wrapped, 'base64url').toString('utf8'));+ assert.deepEqual(await unwrapDeviceBoardKey(pair.keys.privateKey, persistedWrap, {+ board: boardA, device: pair.keys.deviceId, engine: ENGINE_VERSION,+ }), boardKey);++ // Expiration is bounded and does not refresh on read; revocation tombstones the id and deletes wraps.+ const expiringLocator = Buffer.from(randomBytes(16)).toString('base64url');+ await deviceRequest(box, `/api/v1/devices/enrollments/${expiringLocator}`, {+ method: 'POST', cookie: cookieA, origin: box.origin, body: {},+ });+ box.advance(600_001);+ const expired = await deviceRequest(box, `/api/v1/devices/enrollments/${expiringLocator}`, {+ cookie: cookieA, origin: box.origin,+ });+ assert.equal(expired.document.error?.code, 'DEVICE_PAIR_EXPIRED');++ const revoked = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}`, {+ method: 'DELETE', cookie: cookieA, origin: box.origin,+ });+ assert.equal(revoked.response.status, 200);+ const staleUpload = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards/${boardA}`, {+ method: 'PUT', cookie: cookieA, origin: box.origin, engine: ENGINE_VERSION,+ body: { engine: ENGINE_VERSION, wrapped },+ });+ assert.equal(staleUpload.document.error?.code, 'DEVICE_NOT_ENROLLED');+ const staleRegistration = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}`, {+ method: 'POST', cookie: cookieA, origin: box.origin, body: {},+ });+ assert.equal(staleRegistration.document.error?.code, 'DEVICE_REVOKED');+ const noWrapsAfterRevoke = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}/boards`, {+ cookie: cookieA, origin: box.origin,+ });+ assert.equal(noWrapsAfterRevoke.document.error?.code, 'DEVICE_NOT_ENROLLED');+});diff --git a/test/relay-device-keys.test.js b/test/relay-device-keys.test.jsnew file mode 100644index 00000000..a4ff7ee8--- /dev/null+++ b/test/relay-device-keys.test.js@@ -0,0 +1,147 @@+/** Real device enrollment and key wraps; actual WebCrypto only [H5,H15,H17]. */+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { acceptDeviceEnrollment, beginDeviceEnrollment, readRelayMachine, removeRecordedDevice, wrapForRecordedDevice } from '../src/relay-machine.js';+import {+ authenticateDeviceEnrollment,+ createDeviceKeys,+ signDeviceEnrollment,+ unwrapDeviceBoardKey,+ wrapDeviceBoardKey,+} from '../src/relay-device-keys.js';++/** Encode test bytes using the protocol's canonical unpadded base64url representation. */+function b64url(bytes) {+ return Buffer.from(bytes).toString('base64url');+}++/** Make a structurally valid enrollment around a newly generated real P-256 public key. */+async function enrollmentFor(keys, overrides = {}) {+ return {+ v: 1,+ account: 'github-user-42',+ locator: 'AAAAAAAAAAAAAAAAAAAAAA',+ deviceId: keys.deviceId,+ publicKey: keys.publicKey,+ label: 'Phone',+ createdAt: '2026-10-09T12:00:00.000Z',+ ...overrides,+ };+}++test('device enrollment keeps its private P-256 key non-extractable and authenticates the exact key [H5,H15,H17]', async () => {+ const phone = await createDeviceKeys();+ const otherPhone = await createDeviceKeys();+ assert.equal(phone.privateKey.extractable, false);+ await assert.rejects(crypto.subtle.exportKey('jwk', phone.privateKey));+ assert.equal(phone.publicKey.kty, 'EC');+ assert.equal(phone.publicKey.crv, 'P-256');+ assert.equal(phone.publicKey.d, undefined);++ const secret = crypto.getRandomValues(new Uint8Array(32));+ const base = await enrollmentFor(phone);+ const signed = await signDeviceEnrollment(secret, base);+ const expected = { account: base.account, locator: base.locator };+ const accepted = await authenticateDeviceEnrollment(secret, signed, expected);+ assert.equal(accepted.deviceId, phone.deviceId);+ assert.deepEqual(accepted.publicKey, phone.publicKey);+ assert.match(accepted.fingerprint, /^[0-9a-f]{64}$/u);+ assert.equal(accepted.label, base.label);+ assert.equal(accepted.createdAt, base.createdAt);++ const substituted = await signDeviceEnrollment(secret, await enrollmentFor(otherPhone));+ await assert.rejects(authenticateDeviceEnrollment(secret, { ...signed, publicKey: substituted.publicKey }, expected),+ { code: 'DEVICE_ENROLL_AUTH' }, 'a relay-substituted but valid public key fails the MAC');+ await assert.rejects(authenticateDeviceEnrollment(secret, signed, { ...expected, account: 'another-account' }),+ { code: 'DEVICE_ENROLL_AUTH' }, 'the expected account is checked locally');+ await assert.rejects(authenticateDeviceEnrollment(secret, signed, { ...expected, locator: 'AAAAAAAAAAAAAAAAAAAAAQ' }),+ { code: 'DEVICE_ENROLL_AUTH' }, 'the expected one-use pairing locator is checked locally');+ const changedMac = Buffer.from(signed.mac, 'base64url');+ changedMac[0] ^= 1;+ await assert.rejects(authenticateDeviceEnrollment(secret, { ...signed, mac: b64url(changedMac) }, expected),+ { code: 'DEVICE_ENROLL_AUTH' }, 'tampered enrollment authentication is refused');+});++test('device wraps encrypt a board key to one device and authenticate board, device and engine [H5,H15,H17]', async () => {+ const phone = await createDeviceKeys();+ const stranger = await createDeviceKeys();+ const boardKey = crypto.getRandomValues(new Uint8Array(32));+ const context = { board: 'a'.repeat(32), device: phone.deviceId, engine: 5 };+ const first = await wrapDeviceBoardKey(boardKey, phone.publicKey, context);+ const second = await wrapDeviceBoardKey(boardKey, phone.publicKey, context);+ const serialized = JSON.stringify(first);+ assert.equal(first.v, 1);+ assert.equal(first.board, context.board);+ assert.equal(first.device, phone.deviceId);+ assert.equal(first.engine, context.engine);+ assert.notEqual(first.ephemeral.x + first.ephemeral.y, second.ephemeral.x + second.ephemeral.y,+ 'each wrap uses a fresh ephemeral ECDH key');+ assert.equal(serialized.includes(Buffer.from(boardKey).toString('base64url')), false,+ 'the serialized relay envelope never contains the raw board key');+ assert.deepEqual(await unwrapDeviceBoardKey(phone.privateKey, first, context), boardKey);++ await assert.rejects(unwrapDeviceBoardKey(stranger.privateKey, first, context), { code: 'DEVICE_WRAP_AUTH' },+ 'a non-recipient device cannot open this key');+ for (const expected of [+ { ...context, board: 'b'.repeat(32) },+ { ...context, device: stranger.deviceId },+ { ...context, engine: context.engine + 1 },+ ]) {+ await assert.rejects(unwrapDeviceBoardKey(phone.privateKey, first, expected), { code: 'DEVICE_WRAP_AUTH' });+ }+ await assert.rejects(unwrapDeviceBoardKey(phone.privateKey, { ...first, engine: context.engine + 1 },+ { ...context, engine: context.engine + 1 }), { code: 'DEVICE_WRAP_AUTH' },+ 'changing both the relay envelope and expected engine still fails GCM authentication');+ const changed = { ...first, ciphertext: b64url(Buffer.from(first.ciphertext, 'base64url').map((byte, index) => index === 0 ? byte ^ 1 : byte)) };+ await assert.rejects(unwrapDeviceBoardKey(phone.privateKey, changed, context), { code: 'DEVICE_WRAP_AUTH' },+ 'ciphertext tampering is rejected by AES-GCM');+});++/** Exercise the actual owner-only machine file, one-use enrollment and trusted wrapping boundary. */+test('machine device enrollment survives a new process and refuses unrecorded or revoked recipients [H5,H15,H17]', async (t) => {+ const home = mkdtempSync(join(tmpdir(), 'pullboard-device-roster-'));+ const priorHome = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = home;+ t.after(() => {+ if (priorHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = priorHome;+ rmSync(home, { recursive: true, force: true });+ });+ const phone = await createDeviceKeys();+ const other = await createDeviceKeys();+ const owner = { account: 'github-user-42', url: 'http://127.0.0.1:12345' };+ const board = 'c'.repeat(32);+ const key = crypto.getRandomValues(new Uint8Array(32));+ const context = { board, device: phone.deviceId, engine: 5 };+ await assert.rejects(wrapForRecordedDevice(key, context, owner), { code: 'DEVICE_NOT_ENROLLED' });+ const pending = beginDeviceEnrollment(board, owner);+ const signed = await signDeviceEnrollment(pending.secret, await enrollmentFor(phone, {+ account: owner.account, locator: pending.locator,+ }));+ await assert.rejects(acceptDeviceEnrollment({ ...signed, publicKey: other.publicKey }), { code: 'DEVICE_ENROLL_AUTH' });+ assert.equal(readRelayMachine().devices.length, 0, 'a relay substitution cannot enter the trusted roster');+ assert.equal(readRelayMachine().pending.locator, pending.locator, 'an invalid MAC cannot consume the real phone pairing');+ await acceptDeviceEnrollment(signed);+ assert.equal(readRelayMachine().pending, null, 'the authenticated one-use secret is consumed locally');+ await assert.rejects(acceptDeviceEnrollment(signed), error => error.code.startsWith('DEVICE_PAIR_'));+ const wrapped = await wrapForRecordedDevice(key, context, owner);+ assert.deepEqual(await unwrapDeviceBoardKey(phone.privateKey, wrapped, context), key);+ await assert.rejects(wrapForRecordedDevice(key, { ...context, device: other.deviceId }, owner), { code: 'DEVICE_NOT_ENROLLED' });+ await assert.rejects(wrapForRecordedDevice(key, context, { ...owner, account: 'other-account' }), { code: 'DEVICE_NOT_ENROLLED' });+ assert.equal(statSync(join(home, 'relay-machine/state.json')).mode & 0o777, 0o600);+ const module = new URL('../src/relay-machine.js', import.meta.url).href;+ const restarted = spawnSync(process.execPath, ['--input-type=module', '-e',+ `import {readRelayMachine} from ${JSON.stringify(module)}; console.log(JSON.stringify(readRelayMachine().devices.map(device => device.deviceId)));`],+ { env: process.env, encoding: 'utf8', timeout: 10_000 });+ assert.equal(restarted.status, 0, restarted.stderr);+ assert.deepEqual(JSON.parse(restarted.stdout), [phone.deviceId], 'a fresh process sees the same authenticated device');+ removeRecordedDevice(phone.deviceId);+ await assert.rejects(wrapForRecordedDevice(key, context, owner), { code: 'DEVICE_NOT_ENROLLED' });+ assert.equal(readRelayMachine().devices.length, 0);+ assert.equal(readRelayMachine().revocations[0].deviceId, phone.deviceId, 'remote deletion remains queued until acknowledged');+ assert.deepEqual(await unwrapDeviceBoardKey(phone.privateKey, wrapped, context), key, 'revocation does not un-know a delivered key');+});diff --git a/test/relay-setup-once.test.js b/test/relay-setup-once.test.jsnew file mode 100644index 00000000..f6934f0b--- /dev/null+++ b/test/relay-setup-once.test.js@@ -0,0 +1,208 @@+/** One real machine setup reaches current and future projects through one phone key [H5,H15,H17]. */+import assert from 'node:assert/strict';+import { spawn, spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { test } from 'node:test';+import { relayClientFixture } from './relay-client-fixture.js';+import { startChrome, findChromeExecutable } from './relay-browser-fixture.js';++const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');++/** Poll a real state change with a finite deadline and no retries of the operation being tested. */+async function waitFor(read, message, timeout = 20_000) {+ const until = Date.now() + timeout;+ do {+ const result = read();+ if (result) return result;+ await new Promise(resolve => setTimeout(resolve, 25));+ } while (Date.now() < until);+ assert.fail(message);+}++/** Launch the production CLI against an isolated real repository and retain only private diagnostics. */+function command(root, env, args, timeout = 25_000) {+ const child = spawn(process.execPath, [CLI, ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ let stderr = '';+ child.stdout.setEncoding('utf8').on('data', value => { stdout += value; });+ child.stderr.setEncoding('utf8').on('data', value => { stderr += value; });+ const done = new Promise((resolveResult, reject) => {+ const timer = setTimeout(() => child.kill('SIGKILL'), timeout);+ child.once('error', error => { clearTimeout(timer); reject(error); });+ child.once('close', (code, signal) => {+ clearTimeout(timer);+ if (signal) return reject(new Error('The private setup command exceeded its bounded fixture lifetime.'));+ let document;+ try { document = JSON.parse(stdout); } catch { return reject(new Error('The private setup command did not return JSON.')); }+ resolveResult({ code, document, stderr });+ });+ });+ return { child, done };+}++/** Initialize an independent committed project with origin in place before its registration. */+async function project(box, name) {+ const root = join(dirname(box.root), name);+ mkdirSync(root);+ for (const args of [['init', '-q', '-b', 'main'], ['-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-q', '-m', 'fixture base'],+ ['remote', 'add', 'origin', '[email protected]:fixture/repository.git']]) {+ assert.equal(spawnSync('git', args, { cwd: root, env: box.env }).status, 0);+ }+ const initialized = await command(root, box.env, ['init']).done;+ assert.equal(initialized.code, 0, 'the additional project registers through the actual init command');+ return root;+}++/** Read one private link without exposing credentials in test diagnostics. */+function link(root) { return JSON.parse(readFileSync(join(root, '.git/pullboard/relay.json'), 'utf8')); }++/** Inspect the actual persisted browser key without exporting its private half. */+function browserDeviceExpression() {+ return `new Promise((resolve, reject) => { const request = indexedDB.open('pullboard-relay-device-v1', 1);+ request.onsuccess = () => { const db=request.result; const transaction=db.transaction('keys'); const read=transaction.objectStore('keys').get('device');+ read.onsuccess = () => { const value=read.result; db.close(); resolve({id:value.deviceId,extractable:value.privateKey.extractable}); }; read.onerror=reject; }; request.onerror=reject; })`;+}++test('set up once links three registered boards, later registration and a persistent phone without another pairing [H5,H15,H17]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ let chrome;+ let setup;+ t.after(async () => {+ await chrome?.close();+ if (setup?.child.exitCode === null) setup.child.kill('SIGTERM');+ await setup?.done.catch(() => {});+ });+ const box = await relayClientFixture(t);+ const second = await project(box, 'second-project');+ const third = await project(box, 'third-project');+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');+ setup = command(box.root, box.env, ['relay', 'on', '--all', '--url', box.origin], 90_000);+ const pending = await waitFor(() => {+ if (!existsSync(machineFile)) return null;+ return JSON.parse(readFileSync(machineFile, 'utf8')).pending;+ }, 'the foreground setup publishes one pending phone enrollment');+ const roots = [box.root, second, third];+ assert.ok(roots.every(root => existsSync(join(root, '.git/pullboard/relay.json'))), 'all three boards linked before first phone enrollment');+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 1, 'one GitHub device sign-in covers the entire machine');++ const 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);+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);+ const completed = await setup.done;+ assert.equal(completed.code, 0);+ assert.equal(completed.document.linked.length, 3);+ assert.equal(completed.document.paired, true);+ await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 3");+ assert.equal(await chrome.evaluate('location.hash'), '', 'the one-use secret is stripped from browser history');+ const device = await chrome.evaluate(browserDeviceExpression());+ assert.equal(device.extractable, false, 'the private phone key is persisted non-extractable in IndexedDB');+ assert.equal(JSON.parse(readFileSync(machineFile, 'utf8')).devices[0].deviceId, device.id);+ assert.equal(JSON.parse(readFileSync(machineFile, 'utf8')).pending, null);++ const 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');+ 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 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);+ 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');+ for (const root of allRoots) {+ const board = link(root).board;+ assert.equal(await chrome.evaluate(`Object.hasOwn(JSON.parse(localStorage.getItem('pullboard.relay.keys.v1')), ${JSON.stringify(board)})`), true,+ '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.+ 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.deepEqual(await chrome.evaluate(browserDeviceExpression()), device);++ 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');+ for (const root of allRoots) {+ const raw = readFileSync(join(box.env.PULLBOARD_HOME, 'relay-keys', link(root).board + '.key'), 'utf8').trim();+ assert.equal(publicBytes.includes(raw), false, 'no clear board key in actual relay traffic');+ assert.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;+ assert.equal(revoked.code, 0);+ assert.match(revoked.document.notice, /already received remain known/u);+ assert.equal(JSON.parse(readFileSync(machineFile, 'utf8')).devices.length, 0);+});+++test('set up once keeps completed links on interruption and names partial failures [H5,H17]', async t => {+ const box = await relayClientFixture(t);+ const bad = await project(box, 'invalid-origin-project');+ assert.equal(spawnSync('git', ['remote', 'set-url', 'origin', 'https://invalid.example/repository.git'], { cwd: bad, env: box.env }).status, 0);+ const file = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');+ const started = command(box.root, box.env, ['relay', 'on', '--all', '--url', box.origin]);+ t.after(async () => { if (started.child.exitCode === null) started.child.kill('SIGTERM'); await started.done.catch(() => {}); });+ await waitFor(() => box.calls.some(call => call.method === 'GET' && call.path.startsWith('/api/v1/devices/enrollments/')),+ 'first pairing is waiting in the foreground');+ started.child.kill('SIGINT');+ const partial = await started.done;+ assert.equal(partial.code, 1, 'a named project failure produces a nonzero status even when the other board linked');+ assert.equal(partial.document.linked.length, 1);+ assert.equal(partial.document.failed[0].root, bad);+ assert.match(partial.document.failed[0].reason, /GitHub/u);+ assert.equal(partial.document.paired, false);+ assert.equal(JSON.parse(readFileSync(file, 'utf8')).pending, null, 'interruption leaves no half device enrollment');+ assert.equal(JSON.parse(readFileSync(file, 'utf8')).devices.length, 0);+ const retained = link(box.root).board;+ assert.equal(spawnSync('git', ['remote', 'set-url', 'origin', '[email protected]:fixture/repository.git'], { cwd: bad, env: box.env }).status, 0);+ const before = box.calls.length;+ const retry = command(box.root, box.env, ['relay', 'on', '--all']);+ t.after(async () => { if (retry.child.exitCode === null) retry.child.kill('SIGTERM'); await retry.done.catch(() => {}); });+ await waitFor(() => box.calls.slice(before).some(call => call.method === 'GET' && call.path.startsWith('/api/v1/devices/enrollments/')),+ 'a later process can obtain a fresh pairing link without repeating sign-in');+ retry.child.kill('SIGINT');+ const completed = await retry.done;+ assert.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);+});++test('set up once reports a newly registered project when its stored session is gone [H5,H17]', async t => {+ const box = await relayClientFixture(t);+ const machine = new URL('../src/relay-machine.js', import.meta.url).href;+ const saved = await box.script(`import { updateRelayMachine } from ${JSON.stringify(machine)};+ updateRelayMachine(state => {state.autoLink=true;state.session=null;}); console.log(JSON.stringify({saved:true}));`);+ assert.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 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;+ assert.equal(resume.document.relayProblems.some(problem => problem.message === message), true);+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, 0, 'registration never silently starts another GitHub sign-in');+});