Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(relay): clear revoked browser authority and cache [H5,E16]
Corey Olson4599e2df1949
diff --git a/docs/api.md b/docs/api.mdindex 282435fa..76366e93 100644--- a/docs/api.md+++ b/docs/api.md@@ -187,7 +187,7 @@ Only the coordinator sets or edits an item's `--check`. `pullboard check [id]` p`relay on --all [--url <address>]` returns `{version, linked: [{project, root, board}], failed: [{project, root, reason}], paired, autoLink: true}`. Its status is nonzero when a project failed; successful links remain available. With no paired phone, the command prints one tappable pairing link and QR, then waits in the foreground up to ten minutes. Interruption or expiration leaves completed links intact and exits zero when no link failed. Every explicit invocation signs in afresh; no person session is retained on the Mac. Later project registrations publish one sealed phone-link proposal and keep working locally until its single approval tap. `doctor` and `resume` name the waiting project and its expiry; expiration requires an explicit fresh sign-in rather than silently asking again. `relay off` excludes that project from automatic linking; explicit `relay on` clears the exclusion.-`relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation waits for one tap on the paired phone and uses a short-lived, single-use, RAM-only grant for that exact device. A failed or interrupted approval needs an explicit retry. Revocation stops future wrapping; it cannot erase board keys already received.+`relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation waits for one tap on the paired phone and uses a short-lived, single-use, RAM-only grant for that exact device. A failed or interrupted approval needs an explicit retry. Revocation stops future wrapping and refuses the removed browser’s enrolled session with `DEVICE_REVOKED` (HTTP 403), including snapshot and event reads. Its next connected page clears the locally held board keys, private device key and board request cache and shows that it was removed; reload retains the refusal. The relay stores only public session ids tied to the enrollment, never an extra bearer credential. A fresh GitHub sign-in remains eligible for recovery; it does not resurrect the revoked device. An offline copy cannot be remotely erased and board key rotation remains separate (#346).Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Enrollment, device listing and direct revocation require a person session. A board-scoped machine credential can PUT only its own board wrap to an already enrolled device. Cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.diff --git a/relay/browser-client.js b/relay/browser-client.jsindex 20644548..01ffade8 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -1,5 +1,5 @@/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15,H16,H17]. */-import { rememberDevicePairing, enrollPhone, deviceBoardKeys, installPhoneApprovals } from './browser-devices.js';+import { rememberDevicePairing, enrollPhone, deviceBoardKeys, installPhoneApprovals, forgetDevice } 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';@@ -71,7 +71,8 @@ async function snapshotDocument(plain) {}/** Confirm session authorization before treating a board-local refusal as global access loss. */-async function checkAuthorization(path, status, onDenied) {+async function checkAuthorization(path, status, onDenied, error) {+ if (error?.code === 'DEVICE_REVOKED' && onDenied) { await onDenied(error); return; }if (![401, 403].includes(status) || !onDenied) return;if (['/api/v1/boards', '/api/v1/devices/session'].includes(new URL(path, location.origin).pathname)) onDenied();else await documentAt('/api/v1/devices/session', onDenied);@@ -85,7 +86,7 @@ async function documentAt(path, onDenied, options = {}) {const document = await response.json();if (!response.ok) {const error = document.error;- await checkAuthorization(path, response.status, onDenied);+ await checkAuthorization(path, response.status, onDenied, error);if (error) throw new Refused(error.code, error.message);throw new Refused('RELAY_UNAVAILABLE', 'The relay did not answer. Sign in again or retry.');}@@ -105,6 +106,8 @@ export async function createTransport({ onUpdate = () => {} } = {}) {let failure = '';let failureBoard = null;let accessLost = false;+ let accessError = null;+ const access = new AbortController();let persistenceRequest = null;rememberPairing();let pair = takePairing() ?? stored(sessionStorage, PENDING, null);@@ -112,17 +115,49 @@ export async function createTransport({ onUpdate = () => {} } = {}) {try { if (pair) decodeBoardKey(pair.key); } catch { pair = null; }/** Discard decrypted memory and this document when relay authorization is lost. */- function denied() {+ async function denied(error) {if (accessLost) return;accessLost = true;- for (const entry of paired.values()) { entry.stream?.close(); entry.state = null; entry.shouts = null; }+ accessError = error ?? new Refused('AUTH_REQUIRED', 'Sign in again to read this board.');+ access.abort();+ for (const entry of paired.values()) {+ entry.stream?.close();+ // The cockpit holds this same projection. Clear its arrays before releasing our reference.+ if (entry.state) for (const [field, value] of Object.entries(entry.state)) {+ if (Array.isArray(value)) value.length = 0;+ else delete entry.state[field];+ }+ if (Array.isArray(entry.shouts)) entry.shouts.length = 0;+ entry.state = null; entry.shouts = null; entry.outbox = null;+ if (entry.key instanceof Uint8Array) entry.key.fill(0);+ entry.key = null;+ }paired.clear();+ available = []; waitingBoards.clear(); warnings = []; pair = null;+ for (const id of Object.keys(keys)) delete keys[id];document.querySelector('main')?.replaceChildren();- location.replace('/');+ if (error?.code !== 'DEVICE_REVOKED') { location.replace('/'); return; }+ let cleanupFailed = false;+ try {+ localStorage.removeItem(KEYS);+ for (const key of Object.keys(localStorage)) if (key.startsWith(OUTBOX) || key.startsWith(OWNED)) localStorage.removeItem(key);+ sessionStorage.removeItem(PENDING);+ sessionStorage.removeItem('pullboard.relay.device-pair.v1');+ } catch { cleanupFailed = true; }+ try { await forgetDevice(); } catch { cleanupFailed = true; }+ const panel = document.createElement('section');+ panel.id = 'relay-removed'; panel.className = 'card-panel'; panel.setAttribute('role', 'status');+ panel.textContent = 'This browser was removed from the board. ' + (cleanupFailed+ ? 'Clear this browser’s site data, then sign in again and get a fresh pairing link from a linked Mac.'+ : 'Sign in again and get a fresh pairing link from a linked Mac.');+ const signIn = document.createElement('a'); signIn.href = '/auth/github/start'; signIn.textContent = 'Sign in with GitHub';+ panel.append(document.createElement('br'), signIn);+ document.querySelector('main')?.replaceChildren(panel);}/** Render only authorized board names, safe warnings and pairing guidance into the generic page. */function notice() {+ if (accessLost) return;const element = document.getElementById('relay-notice');if (!element) return;element.replaceChildren();@@ -184,7 +219,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {if (response.status === 304 && entry.state) return;const document = await response.json();if (!response.ok) {- await checkAuthorization('/api/v1/boards/' + entry.id + '/state', response.status, denied);+ await checkAuthorization('/api/v1/boards/' + entry.id + '/state', response.status, denied, document.error);if (document.error?.code === 'NO_BOARD' || document.error?.code === 'NO_SNAPSHOT') waitForFirstSnapshot(entry);throw new Error(document.error ? '[' + document.error.code + '] ' + document.error.message : 'The relay snapshot is unavailable. Retry.');}@@ -287,6 +322,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {if (message.event === 'error') {stream.close();const error = document.error;+ if (error?.code === 'DEVICE_REVOKED') { await denied(error); return; }if (error?.code === 'SNAPSHOT_REQUIRED') {await snapshot(entry);await catchUp(entry);@@ -332,7 +368,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {if (!response.ok) {let document;try { document = await response.json(); } catch { document = null; }- await checkAuthorization(url, response.status, denied);+ await checkAuthorization(url, response.status, denied, document?.error);if (document?.error?.code === 'NO_BOARD' || document?.error?.code === 'NO_SNAPSHOT') waitForFirstSnapshot(entry);const refusal = new Refused(document?.error?.code ?? 'RELAY_UNAVAILABLE', document?.error?.message ?? 'The relay stream ended. Refresh this board.');if (refusal.code === 'ENGINE_VERSION') refusal.fatal = true;@@ -355,8 +391,10 @@ 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)));+ if (accessLost) throw accessError;+ const receivedKeys = await deviceBoardKeys((path, options) => documentAt(path, denied, options));+ if (accessLost) throw accessError;+ Object.assign(keys, stored(localStorage, KEYS, {}), receivedKeys);available = document.boards.filter(board => BOARD.test(board.id) && typeof board.repository === 'string');waitingBoards = new Map();warnings = document.warnings ?? [];@@ -521,10 +559,11 @@ export async function createTransport({ onUpdate = () => {} } = {}) {addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });if (await enrollPhone((path, options) => documentAt(path, denied, options))) keepPairingStorage();await listing();- await installPhoneApprovals((path, options) => documentAt(path, denied, options), keys, async () => { await listing(); onUpdate(); });+ await installPhoneApprovals((path, options) => documentAt(path, denied, options), keys, async () => { await listing(); onUpdate(); }, access.signal);return {/** Return decoded API state or seal narrow person intent; no board key or plaintext leaves the device. */async request(path, body) {+ if (accessLost) throw accessError;const url = new URL(path, location.origin);if (url.origin !== location.origin) throw new Error('Use this relay origin to read a board.');if (url.pathname === '/api/v1/boards') { if (body !== undefined && body !== null) throw new Refused('BAD_REQUEST', 'Send person intent to a paired board.'); return listing(); }diff --git a/relay/browser-devices.js b/relay/browser-devices.jsindex f894ff85..ea4664d9 100644--- a/relay/browser-devices.js+++ b/relay/browser-devices.js@@ -41,6 +41,25 @@ async function deviceStorage(value) {} finally { db.close(); }}+/** Erase this removed browser's non-extractable private key before its revoked board can be drawn again. */+export async function forgetDevice() {+ if (!globalThis.indexedDB) return;+ 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', 'Clear this removed browser’s site data before pairing again.'));+ });+ try {+ await new Promise((resolve, reject) => {+ const transaction = db.transaction('keys', 'readwrite');+ transaction.objectStore('keys').delete('device');+ transaction.oncomplete = resolve;+ transaction.onerror = transaction.onabort = () => reject(new Refused('DEVICE_STORAGE', 'Clear this removed browser’s site data before pairing again.'));+ });+ } finally { db.close(); }+}+/** Send a public enrollment without exposing private material; return true once new pairing delivers keys. */export async function enrollPhone(documentAt) {rememberDevicePairing();@@ -110,10 +129,10 @@ function approvalDocument(value) {}/** Show exact paired native intent and approve only on one explicit phone tap. */-export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {+export async function installPhoneApprovals(documentAt, boardKeys, onApproved, signal) {if (document.getElementById('phone-approvals')) return;- const device = await deviceStorage();- if (!device) return;+ let device = await deviceStorage();+ if (!device || signal?.aborted) return;const panel = document.createElement('section');panel.className = 'card-panel'; panel.id = 'phone-approvals';panel.setAttribute('aria-label', 'Requests from your Mac');@@ -121,11 +140,15 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {const active = new Set();let stopped = false;let timer;+ /** Release the private device key and pending cards when this page loses relay access. */+ function stop() { stopped = true; clearTimeout(timer); device = null; panel.replaceChildren(); panel.remove(); }+ signal?.addEventListener('abort', stop, { once: true });/** Refresh pending metadata without approving it or replacing a button whose request is in flight. */async function refresh() {if (stopped) return;try {const response = await documentAt('/api/v1/devices/' + device.deviceId + '/approvals');+ if (stopped) return;const ids = new Set(response.approvals.map(value => value.context.id));for (const child of [...panel.children]) if (!ids.has(child.dataset.request) && !active.has(child.dataset.request)) child.remove();for (const row of response.approvals) {@@ -137,6 +160,7 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {const key = Uint8Array.from(atob(raw.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - raw.length % 4) % 4)), char => char.charCodeAt(0));const envelope = await verifyApprovalIntent(key, approvalDocument(row.sealed));const intent = await openApproval(device.privateKey, envelope, context, 'intent');+ if (stopped) return;if (JSON.stringify(approvalContext(intent.context)) !== JSON.stringify(context)) throw new Refused('PHONE_APPROVAL_AUTH', 'The displayed request differs from its sealed action.');const replyKey = devicePublicKey(intent.replyKey);const card = document.createElement('div'); card.className = 'phone-approval'; card.dataset.request = context.id;@@ -146,7 +170,7 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {button.textContent = context.action === 'link' ? 'Link project' : context.action === 'delete-board' ? 'Delete relay copy' : 'Approve revocation';/** Issue once on this tap, then encrypt the result to the native command's private RAM reply key. */button.onclick = async () => {- if (active.has(context.id)) return;+ if (stopped || active.has(context.id)) return;active.add(context.id); button.disabled = true;try {const authorized = await documentAt('/api/v1/devices/approvals/' + context.id + '/authorize', {@@ -167,6 +191,6 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {if (error?.code !== 'DEVICE_NOT_ENROLLED') panel.setAttribute('data-error', 'Approval requests are unavailable. Retry from the Mac.');} finally { if (!stopped) timer = setTimeout(refresh, 1000); }}- addEventListener('pagehide', () => { stopped = true; clearTimeout(timer); }, { once: true });+ addEventListener('pagehide', stop, { once: true });await refresh();}diff --git a/relay/device-http.js b/relay/device-http.jsindex f0b5d876..061d1355 100644--- a/relay/device-http.js+++ b/relay/device-http.js@@ -104,6 +104,7 @@ export function createDeviceHandler({ authenticate, authorizeBoard, boardsFor, d}devicePublicKey(body.publicKey);devices.enroll(account, locator, body);+ devices.bindSession(who, body.deviceId, { enrollment: true });} 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;@@ -113,6 +114,8 @@ export function createDeviceHandler({ authenticate, authorizeBoard, boardsFor, dconst [, id, board] = route;if (url.pathname.endsWith('/boards') && req.method === 'GET') {const visible = new Set((await boardsFor(req)).map(value => value.id));+ // This also binds previously paired browsers that predate session enrollment tracking.+ devices.bindSession(who, id);apiJson(res, 200, { wraps: devices.wraps(account, id).filter(value => visible.has(value.board)) }); return true;}if (board && req.method === 'PUT') {diff --git a/relay/device-store.js b/relay/device-store.jsindex 24c6deec..bb52ed1c 100644--- a/relay/device-store.js+++ b/relay/device-store.js@@ -17,6 +17,7 @@ export function createDeviceStore({ directory, now = Date.now }) {chmodSync(file, 0o600);opened.exec(`PRAGMA busy_timeout=30000;CREATE TABLE IF NOT EXISTS device (account TEXT NOT NULL, id TEXT NOT NULL, revoked INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(account,id));+ CREATE TABLE IF NOT EXISTS device_session (account TEXT NOT NULL, session TEXT NOT NULL, device TEXT NOT NULL, expires INTEGER NOT NULL, PRIMARY KEY(account,session,device));CREATE TABLE IF NOT EXISTS wrapped_key (account TEXT NOT NULL, device TEXT NOT NULL, board TEXT NOT NULL, engine INTEGER NOT NULL, wrapped TEXT NOT NULL, PRIMARY KEY(account,device,board));CREATE TABLE IF NOT EXISTS enrollment (account TEXT NOT NULL, locator TEXT NOT NULL, expires INTEGER NOT NULL, payload TEXT, PRIMARY KEY(account,locator));CREATE TABLE IF NOT EXISTS phone_approval (id TEXT PRIMARY KEY, account TEXT NOT NULL, publisher TEXT NOT NULL,@@ -29,9 +30,9 @@ export function createDeviceStore({ directory, now = Date.now }) {}/** Require an active account device for reads and writes alike. */function active(account, id) {- if (!database().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.');- }+ const row = database().prepare('SELECT revoked FROM device WHERE account=? AND id=?').get(account, id);+ if (row?.revoked) throw new Refused('DEVICE_REVOKED', 'This browser was removed from the board. Sign in again and get a fresh pairing link from a linked Mac.');+ if (!row) 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) {@@ -49,6 +50,22 @@ export function createDeviceStore({ directory, now = Date.now }) {return row ? { context: JSON.parse(row.context), sealed: row.sealed, state: row.state, response: row.response } : null;}return {+ /** Bind the public session id that actually uploaded enrollment, never its bearer credential. */+ bindSession(principal, device, { enrollment = false } = {}) {+ if (principal.kind !== 'session') return;+ if (!enrollment && !database().prepare('SELECT 1 FROM device WHERE account=? AND id=?').get(principal.user.id, device)) return;+ database().prepare('DELETE FROM device_session WHERE expires<=?').run(now());+ database().prepare('INSERT OR IGNORE INTO device_session VALUES(?,?,?,?)')+ .run(principal.user.id, principal.id, device, principal.expires);+ },+ /** A revoked phone cannot reuse its original session to bypass device routes and fetch ciphertext. */+ authorizeSession(principal) {+ if (principal.kind !== 'session' || !db && !existsSync(file)) return principal;+ const revoked = database().prepare(`SELECT 1 FROM device_session AS s JOIN device AS d ON d.account=s.account AND d.id=s.device+ WHERE s.account=? AND s.session=? AND s.expires>? AND d.revoked=1`).get(principal.user.id, principal.id, now());+ if (revoked) throw new Refused('DEVICE_REVOKED', 'This browser was removed from the board. Sign in again and get a fresh pairing link from a linked Mac.');+ return principal;+ },/** Enqueue one immutable action for this account's already enrolled phone; PM cannot approve it. */requestApproval(account, value, sealed) {const context = approvalContext(value);diff --git a/relay/service.js b/relay/service.jsindex 450ef05a..b768ea30 100644--- a/relay/service.js+++ b/relay/service.js@@ -101,14 +101,14 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin/** Check expiry only after normal authorization; the first authorized contact also purges overdue data. */async function authorized(token, id, write = false) {- const who = await auth.authenticate(token, { board: identity(id), write });+ const who = deviceStore.authorizeSession(await auth.authenticate(token, { board: identity(id), write }));if (retention.expire(id)) throw new Refused('NO_BOARD', 'this inactive link expired; link and upload the local board again');return who;}const deviceStore = createDeviceStore({ directory: root, now });const deviceHandler = createDeviceHandler({- authenticate: (req, write) => auth.authenticate(credential(req, origin, write)),+ authenticate: async (req, write) => deviceStore.authorizeSession(await auth.authenticate(credential(req, origin, write))),authorizeBoard: (req, id) => authorizedRequest(req, id, true),boardsFor: req => auth.boardsFor(credential(req, origin)),devices: deviceStore,@@ -185,8 +185,11 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginconst common = createApiHandler({authenticate: async (req, { board, write }) => {const token = credential(req, origin, write);- return board === null ? { visible: await auth.boardsFor(token) }- : { ...await authorizedRequest(req, board, write), credential: token };+ if (board !== null) return { ...await authorizedRequest(req, board, write), credential: token };+ if (token.startsWith('ps_')) deviceStore.authorizeSession(await auth.authenticate(token));+ const visible = await auth.boardsFor(token);+ if (token.startsWith('ps_')) deviceStore.authorizeSession(await auth.authenticate(token));+ return { visible };},boards: (who) => {const boards = who.visible.filter((board) => !retention.expire(board.id));diff --git a/src/api-http.js b/src/api-http.jsindex 1ba76da8..6a10ae0a 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -352,7 +352,7 @@ export function applyStateDelta(state, delta) {/** Choose the same HTTP refusal class for local and sealed relay adapters. */export function apiStatus(error) {- return { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, NO_SHOUT: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, BASELINE_EXISTS: 412, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);+ return { AUTH_REQUIRED: 401, DEVICE_REVOKED: 403, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, NO_SHOUT: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, BASELINE_EXISTS: 412, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);}// Relay-only snapshot/delete routes reuse the exact shared bounded-body and refusal boundary.diff --git a/test/relay-browser.test.js b/test/relay-browser.test.jsindex 2b2653bd..48c4373a 100644--- a/test/relay-browser.test.js+++ b/test/relay-browser.test.js@@ -1,7 +1,7 @@/** Real Chrome reads and follows device-sealed boards; the relay never receives its key [H5,H15,H18]. */import assert from 'node:assert/strict';import { AssertionError } from 'node:assert';-import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { createServer } from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -533,3 +533,121 @@ test('legacy queued presentations never disclose later unacknowledged moves [H5,const compacted = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });assert.equal(compacted.status, 409, 'the relay compacted the moves only after acknowledging their final checkpoint');});++/** Wait for a genuine native enrollment/approval to reach the fixture, without retrying a move. */+async function browserDeviceTransition(read, message) {+ const deadline = Date.now() + 90_000;+ while (Date.now() < deadline) {+ const value = read();+ if (value) return value;+ await new Promise(resolveTransition => setTimeout(resolveTransition, 25));+ }+ assert.fail(message);+}++/** Pair a real Chrome private key through the foreground Mac and its one-use enrollment. */+async function enrolledBrowser(box, t) {+ const setup = box.startCli(['relay', 'on', '--all', '--url', box.origin]);+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');+ const pending = await browserDeviceTransition(() => existsSync(machineFile)+ && JSON.parse(readFileSync(machineFile, 'utf8')).pending, 'the Mac publishes the real phone enrollment');+ const chrome = await startChrome();+ t.after(() => chrome.close());+ await signIn(chrome, box);+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);+ const result = await setup.closed;+ assert.equal(result.code, 0, 'the genuine native phone enrollment succeeds');+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes('private cleanup fixture item') && document.querySelector('#phone-approvals') !== null");+ const state = JSON.parse(readFileSync(machineFile, 'utf8'));+ assert.equal(state.devices.length, 1);+ return { chrome, device: state.devices[0].deviceId };+}++/** Revoke the enrolled browser with the real CLI and one actual phone approval tap. */+async function revokeBrowser(box, chrome, device) {+ const before = box.transit.length;+ const revoke = box.startCli(['relay', 'revoke', device]);+ const posted = await browserDeviceTransition(() => box.transit.slice(before).find(record =>+ record.method === 'POST' && record.path === '/api/v1/devices/approvals'), 'the native revocation requests phone approval');+ const context = JSON.parse(posted.request.toString('utf8')).context;+ assert.equal(context.target, device);+ assert.equal(context.action, 'revoke-device');+ await chrome.waitFor(`document.querySelector('#phone-approve-${context.id}') !== null`);+ await chrome.evaluate(`document.querySelector('#phone-approve-${context.id}').click()`);+ const result = await revoke.closed;+ assert.equal(result.code, 0, 'one actual phone tap completes native revocation');+ assert.equal(JSON.parse(result.stdout).revoked, true);+}++test('a revoked device read is refused as revoked [H5,E16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const { chrome, device } = await enrolledBrowser(box, t);+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const session = await box.phoneSession();+ const headers = { cookie: 'pb_session=' + session.token, 'x-pullboard-engine': String(ENGINE_VERSION) };+ const endpoint = box.origin + '/api/v1/boards/' + link.board + '/state';+ assert.equal((await fetch(endpoint, { headers })).status, 200, 'the genuine enrolled browser can read before revocation');+ await revokeBrowser(box, chrome, device);+ await box.restartRelay();+ const response = await fetch(endpoint, { headers });+ const document = await response.json();+ assert.equal(document.error?.code, 'DEVICE_REVOKED', 'the same browser session cannot keep reading ciphertext after device revocation and relay restart');+ assert.equal(response.ok, false);+ assert.equal('state' in document, false);+ const machine = await fetch(endpoint, { headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });+ assert.equal(machine.status, 200, 'revoking this browser does not revoke the linked computer');+});++test('a revoked browser shows it was removed and no board [H5,E16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const { chrome, device } = await enrolledBrowser(box, t);+ const key = 'pullboard.relay.keys.v1';+ assert.equal(await chrome.evaluate(`Object.keys(JSON.parse(localStorage.getItem(${JSON.stringify(key)}))).length > 0`), true);+ await revokeBrowser(box, chrome, device);+ await chrome.navigate(box.origin);+ await chrome.waitFor("document.body.textContent.includes('This browser was removed') || document.querySelector('#chain')?.textContent.includes('private cleanup fixture item')");+ assert.equal(await chrome.evaluate("document.body.textContent.includes('This browser was removed')"), true, 'reload distinguishes a removed browser from an unpaired browser');+ assert.equal(await chrome.evaluate("document.body.textContent.includes('private cleanup fixture item')"), false, 'the old decrypted board is not drawn');+ assert.equal(await chrome.evaluate(`localStorage.getItem(${JSON.stringify(key)}) === null`), true, 'the cached board keys are erased');+ assert.equal(await chrome.evaluate(`new Promise((resolve, reject) => {+ const open = indexedDB.open('pullboard-relay-device-v1', 1);+ open.onsuccess = () => { const db = open.result; const request = db.transaction('keys').objectStore('keys').get('device');+ request.onsuccess = () => { db.close(); resolve(request.result === undefined); }; request.onerror = () => reject(request.error); };+ open.onerror = () => reject(open.error);+ })`), true, 'the removed browser no longer retains its private device key');+ assert.equal(await chrome.evaluate("Object.keys(localStorage).some(key => key.startsWith('pullboard.relay.requests.v1.') || key.startsWith('pullboard.relay.owned-requests.v1.'))"), false, 'cached board request state is erased');+ assert.equal(box.keyInRequest(), false);+});+++test('revocation clears an already open browser and its cached board request state [H5,E16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const { chrome, device } = await enrolledBrowser(box, t);+ const board = JSON.parse(readFileSync(box.linkFile, 'utf8')).board;+ assert.equal(await chrome.evaluate("(window.__removedBoardReference = data.project).items.some(item => item.title === 'private cleanup fixture item')"), true);+ // These are device-local opaque caches, never authority or a relay response. Use the real key/sealer.+ await chrome.evaluate(`(async () => {+ const module = await import('/relay/seal.js');+ const board = ${JSON.stringify(board)};+ const key = module.decodeBoardKey(JSON.parse(localStorage.getItem('pullboard.relay.keys.v1'))[board]);+ const sealed = await module.seal(key, new TextEncoder().encode('removed cached request'), {boardId:board,kind:'request',sequence:1});+ let binary = ''; for (const value of sealed) binary += String.fromCharCode(value);+ localStorage.setItem('pullboard.relay.requests.v1.'+board+'.cached', JSON.stringify({id:'cached',sequence:1,sealed:btoa(binary)}));+ localStorage.setItem('pullboard.relay.owned-requests.v1.'+board, JSON.stringify(['cached']));+ return true;+ })()`);+ assert.equal(await chrome.evaluate("Object.keys(localStorage).filter(key => key.startsWith('pullboard.relay.requests.v1.') || key.startsWith('pullboard.relay.owned-requests.v1.')).length"), 2);+ await revokeBrowser(box, chrome, device);+ await chrome.waitFor("document.body.textContent.includes('This browser was removed')");+ assert.equal(await chrome.evaluate("document.body.textContent.includes('private cleanup fixture item')"), false, 'live authorization loss clears the actual drawn board before reload');+ assert.equal(await chrome.evaluate("window.__removedBoardReference.items?.length ?? 0"), 0, 'the shared cached board projection held by the cockpit is cleared, not only its DOM');+ assert.equal(await chrome.evaluate("Object.keys(localStorage).some(key => key.startsWith('pullboard.relay.requests.v1.') || key.startsWith('pullboard.relay.owned-requests.v1.'))"), false, 'non-empty opaque board request caches are erased');+ assert.equal(await chrome.evaluate("document.querySelector('#phone-approvals') === null"), true, 'removed browser releases its approval panel and polling loop');+ assert.equal(await chrome.evaluate("document.querySelector('#relay-removed a')?.getAttribute('href')"), '/auth/github/start');+});diff --git a/test/relay-device-http.test.js b/test/relay-device-http.test.jsindex ef97c094..2a1dce3a 100644--- a/test/relay-device-http.test.js+++ b/test/relay-device-http.test.js@@ -214,7 +214,7 @@ test('relay devices isolate accounts, persist opaque wraps, expire enrollments amethod: 'PUT', cookie: cookieA, origin: box.origin, engine: ENGINE_VERSION,body: { engine: ENGINE_VERSION, wrapped },});- assert.equal(staleUpload.document.error?.code, 'DEVICE_NOT_ENROLLED');+ assert.equal(staleUpload.document.error?.code, 'DEVICE_REVOKED');const staleRegistration = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}`, {method: 'POST', cookie: cookieA, origin: box.origin, body: {},});@@ -222,5 +222,20 @@ test('relay devices isolate accounts, persist opaque wraps, expire enrollments aconst 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');+ assert.equal(noWrapsAfterRevoke.document.error?.code, 'DEVICE_REVOKED');++ box.restart();+ const persistedRefusal = await deviceRequest(box, '/api/v1/boards', { cookie: cookieA });+ assert.equal(persistedRefusal.document.error?.code, 'DEVICE_REVOKED', 'closing and reopening the actual auth and device databases retains the browser session revocation');+ assert.equal(persistedRefusal.response.status, 403);+ const freshCookie = await browserSession(box);+ const recovery = await deviceRequest(box, '/api/v1/devices/session', { cookie: freshCookie });+ assert.equal(recovery.response.status, 200, 'a fresh independently provider-authenticated session remains available for lost-phone recovery');+ const visible = await deviceRequest(box, '/api/v1/boards', { cookie: freshCookie });+ assert.equal(visible.response.status, 200);+ assert.equal(visible.document.boards.some(board => board.id === boardA), true);+ const oldId = await deviceRequest(box, `/api/v1/devices/${pair.keys.deviceId}`, {+ method: 'POST', cookie: freshCookie, origin: box.origin, body: {},+ });+ assert.equal(oldId.document.error?.code, 'DEVICE_REVOKED', 'a fresh sign-in does not resurrect the tombstoned device id');});