Skip to content

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.

fix(relay): declare engines across clients [H16,H3]

Corey Olson65cff4a448b9
diff --cc relay/browser-client.js
index 30e18297,00000000..0c0cc570
mode 100644,000000..100644
--- a/relay/browser-client.js
+++ b/relay/browser-client.js
@@@ -1,391 -1,0 +1,442 @@@
+/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15]. */
+import { decodeBoardKey, seal, unseal } from './seal.js';
+import { preparePersonRequest, validatePersonRequest } from './person-request.js';
+import { snapshotState, presentationState } from './model.js';
+import { ENGINE_VERSION } from './engine.js';
+import { Refused } from './refused.js';
+
+const KEYS = 'pullboard.relay.keys.v1';
+const PENDING = 'pullboard.relay.pair.v1';
+const OUTBOX = 'pullboard.relay.requests.v1.';
+const BOARD = /^[0-9a-f]{32}$/;
+
+/** Read private browser storage without turning unavailable storage into a credential diagnostic. */
+function stored(storage, name, fallback) {
+ try { return JSON.parse(storage.getItem(name)) ?? fallback; } catch { return fallback; }
+}
+
+/** Keep an unauthenticated pairing fragment on the device through the GitHub redirect. */
+export function rememberPairing() {
+ const fragment = new URLSearchParams(location.hash.slice(1));
+ if (!fragment.has('board') && !fragment.has('key')) return null;
+ const board = fragment.get('board');
+ const key = fragment.get('key');
+ if (!BOARD.test(board ?? '')) throw new Error('The pairing link is invalid. Get a new link from a linked machine.');
+ decodeBoardKey(key);
+ const pair = { board, key };
+ try { sessionStorage.setItem(PENDING, JSON.stringify(pair)); } catch { /* Current visit can still pair in memory. */ }
+ history.replaceState(null, '', location.pathname + location.search);
+ return pair;
+}
+
+/** Decode canonical sealed transport bytes without putting their value in an error. */
+function transportBytes(value) {
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value) || value.length > 14000000) throw new Error('The sealed board response is invalid. Refresh this board.');
+ const binary = atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4));
+ return Uint8Array.from(binary, character => character.charCodeAt(0));
+}
+
+/** Fetch only same-origin API documents, retaining stable refusal guidance and no provider details. */
+async function documentAt(path, onDenied, options = {}) {
- const response = await fetch(path, { ...options, credentials: 'same-origin', cache: 'no-store', redirect: 'error' });
++ const headers = new Headers(options.headers ?? {});
++ headers.set('x-pullboard-engine', String(ENGINE_VERSION));
++ const response = await fetch(path, { ...options, headers, credentials: 'same-origin', cache: 'no-store', redirect: 'error' });
+ const document = await response.json();
+ if (!response.ok) {
+ const error = document.error;
+ if ([401, 403].includes(response.status) || error?.code === 'NO_BOARD') onDenied?.();
+ if (error) throw new Refused(error.code, error.message);
+ throw new Refused('RELAY_UNAVAILABLE', 'The relay did not answer. Sign in again or retry.');
+ }
+ if (document.version !== 1) throw new Error('This relay API version is unsupported. Upgrade this browser client.');
+ return document;
+}
+
+/** Build the API adapter the existing cockpit consumes; no board key enters an HTTP request. */
+export async function createTransport({ onUpdate = () => {} } = {}) {
+ const savedKeys = stored(localStorage, KEYS, {});
+ const keys = savedKeys && typeof savedKeys === 'object' && !Array.isArray(savedKeys) ? savedKeys : {};
+ const paired = new Map();
+ let available = [];
+ let warnings = [];
+ let failure = '';
+ let accessLost = false;
+ let pair = rememberPairing() ?? stored(sessionStorage, PENDING, null);
+ if (pair && (!BOARD.test(pair.board ?? '') || typeof pair.key !== 'string')) pair = null;
+ try { if (pair) decodeBoardKey(pair.key); } catch { pair = null; }
+
+ /** Discard decrypted memory and this document when relay authorization is lost. */
+ function denied() {
+ if (accessLost) return;
+ accessLost = true;
+ for (const entry of paired.values()) { entry.stream?.close(); entry.state = null; }
+ paired.clear();
+ document.querySelector('main')?.replaceChildren();
+ location.replace('/');
+ }
+
+ /** Render only authorized board names, safe warnings and pairing guidance into the generic page. */
+ function notice() {
+ const element = document.getElementById('relay-notice');
+ if (!element) return;
+ element.replaceChildren();
+ const lines = ['Requests from this device wait for a linked machine to run Pullboard.'];
+ const unpaired = available.filter(board => !paired.has(board.id));
+ for (const board of unpaired) lines.push(board.repository + ': pair this browser using a link or QR from a linked machine.');
+ for (const warning of warnings) if (warning?.code === 'BOARD_INACTIVE' && Number.isInteger(warning.daysLeft)) {
+ lines.push('BOARD_INACTIVE: ' + warning.daysLeft + ' days left before this relay board is deleted. Make a board move from a linked machine to keep it.');
+ }
+ if (failure) lines.push(failure);
+ if (!available.length) lines.push('No linked boards are available for this account.');
+ for (const text of lines) {
+ const paragraph = document.createElement('p');
+ paragraph.textContent = text;
+ element.append(paragraph);
+ }
+ }
+
+ /** Retain one warning per board without duplicating it on the next live poll. */
+ function warning(value, boardId) {
+ if (!value || value.code !== 'BOARD_INACTIVE') return;
+ warnings = warnings.filter(entry => entry.board !== boardId);
+ warnings.push({ ...value, board: boardId });
+ notice();
+ }
+
+ /** Authenticate the latest native snapshot before installing its presentation in this device. */
+ async function snapshot(entry) {
+ const response = await fetch('/api/v1/boards/' + entry.id + '/state', {
+ credentials: 'same-origin', cache: 'no-store', redirect: 'error',
- headers: entry.state && entry.snapshotTag ? { 'if-none-match': entry.snapshotTag } : {},
++ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(entry.state && entry.snapshotTag ? { 'if-none-match': entry.snapshotTag } : {}) },
+ });
+ if (response.status === 304 && entry.state) return;
+ const document = await response.json();
+ if (!response.ok) {
+ if ([401, 403].includes(response.status) || document.error?.code === 'NO_BOARD') denied();
+ throw new Error(document.error ? '[' + document.error.code + '] ' + document.error.message : 'The relay snapshot is unavailable. Retry.');
+ }
+ if (document.version !== 1) throw new Error('This relay API version is unsupported. Upgrade this browser client.');
+ const row = document.state;
+ if (!row || !Number.isSafeInteger(row.sequence) || row.sequence < 0) throw new Error('The relay snapshot cursor is invalid. Refresh this board.');
+ warning(row.warning, entry.id);
+ const plain = await unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: 'snapshot', sequence: row.sequence });
+ const value = JSON.parse(new TextDecoder().decode(plain));
+ const state = snapshotState(value, entry.id);
+ if (accessLost) throw new Error('Sign in again to read this board.');
+ entry.snapshotTag = response.headers.get('etag');
+ if (row.sequence >= entry.cursor) {
+ entry.state = state;
+ entry.cursor = row.sequence;
+ }
+ }
+
+ /** Wait for an acknowledged device snapshot instead of consuming an event with no projection. */
+ async function waitForSnapshot(entry, sequence) {
+ const deadline = Date.now() + 15000;
+ while (Date.now() < deadline) {
+ await snapshot(entry);
+ if (entry.state && entry.cursor >= sequence) return;
+ await new Promise(resolveSnapshot => setTimeout(resolveSnapshot, 100));
+ }
+ throw new Error('The relay snapshot has not caught up to this move. Retry this board.');
+ }
+
+ /** Apply a sealed presentation in strict sequence; newer executable formats are never guessed. */
+ async function receive(entry, row, history = false) {
+ if (!row || !Number.isSafeInteger(row.event_id) || !['move', 'request'].includes(row.kind)) throw new Error('The relay event is invalid. Refresh this board.');
+ if (row.event_id <= entry.cursor) return;
+ if (row.event_id !== entry.cursor + 1) {
+ if (history) throw new Error('The relay returned an incomplete event prefix. Refresh this board.');
+ await catchUp(entry);
+ if (row.event_id <= entry.cursor) return;
+ if (row.event_id !== entry.cursor + 1) throw new Error('The relay event prefix is incomplete. Refresh this board.');
+ }
+ const plain = await unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: row.kind, sequence: row.event_id });
+ const move = JSON.parse(new TextDecoder().decode(plain));
+ if (accessLost) throw new Error('Sign in again to read this board.');
+ if (row.kind === 'request') {
+ let request;
+ let error;
+ try {
+ request = validatePersonRequest(move);
+ if (row.sender?.kind !== 'person' || typeof row.sender.userId !== 'string' || !row.sender.userId) throw new Refused('RELAY_PERSON_ONLY', 'Only the authenticated person sends requests. Sign in with the person session.');
+ } catch (cause) { if (!(cause instanceof Refused)) throw cause; error = { code: cause.code, message: cause.message, next: 'Read the reason and send a revised request from the view.' }; }
+ const record = { id: request?.id ?? 'refused-' + row.event_id, sequence: row.event_id, at: row.event_at,
+ by: row.sender?.kind === 'person' ? 'person' : row.sender?.agent ?? '(unknown sender)',
+ move: request?.move ?? null, status: error ? 'refused' : 'waiting', ...(error ? { error } : {}) };
+ entry.state.personRequests ??= [];
+ if (!entry.state.personRequests.some(value => value.id === record.id)) entry.state.personRequests.push(record);
+ entry.cursor = row.event_id;
+ return;
+ }
+ if (move.version !== 1 || !Number.isSafeInteger(move.engine) || move.engine < 1) throw new Error('This sealed move has an unsupported format. Refresh it from a linked machine.');
+ if (move.engine !== ENGINE_VERSION) throw new Refused('RELAY_ENGINE_VERSION', 'This board needs engine ' + move.engine + '; this browser reads engine ' + ENGINE_VERSION + '. Upgrade the browser client.');
+ if (move.presentation) {
+ entry.state = presentationState(move.presentation, entry.id);
+ entry.cursor = row.event_id;
+ } else {
+ // A snapshot may be uploaded just after this ACK and compact the event immediately. Keep
+ // the cursor where it is until a valid snapshot actually covers this row.
+ await waitForSnapshot(entry, row.event_id);
+ }
+ }
+
+ /** Read any durable prefix before attaching the live stream, including compaction repair. */
+ async function catchUp(entry) {
+ let document;
+ try { document = await documentAt('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor, denied); }
+ catch (error) {
+ if (!error.message.includes('[SNAPSHOT_REQUIRED]')) throw error;
+ await snapshot(entry);
+ document = await documentAt('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor, denied);
+ }
+ warning(document.warning, entry.id);
+ for (const row of document.events) await receive(entry, row, true);
+ }
+
- /** Subscribe to real relay events and retention warnings without sending a key or bearer token. */
++ /** Parse a complete SSE message, keeping multi-line data in the standard joined form. */
++ function sseMessage(packet) {
++ let event = 'message';
++ const data = [];
++ for (const line of packet.split(/\r?\n/u)) {
++ if (line.startsWith('event:')) event = line.slice(6).trimStart();
++ else if (line.startsWith('data:')) data.push(line.slice(5).trimStart());
++ }
++ return { event, data: data.join('\n') };
++ }
++
++ /** Handle a relay stream message in sequence, matching EventSource behavior with an engine header. */
++ async function streamMessage(entry, message, stream) {
++ if (!message.data) return;
++ const document = JSON.parse(message.data);
++ if (message.event === 'warning') { warning(document.warning, entry.id); return; }
++ if (message.event === 'error') {
++ stream.close();
++ const error = document.error;
++ if (error?.code === 'SNAPSHOT_REQUIRED') {
++ await snapshot(entry);
++ await catchUp(entry);
++ subscribe(entry);
++ onUpdate();
++ } else {
++ if (['AUTH_REQUIRED', 'NO_REPO_ACCESS', 'TOKEN_BOARD', 'NO_BOARD'].includes(error?.code)) denied();
++ failure = error ? '[' + error.code + '] ' + error.message : 'The relay stream ended. Refresh this board.';
++ notice();
++ }
++ return;
++ }
++ if (document.version !== 1) throw new Error('Upgrade this browser client to read the relay API.');
++ await receive(entry, document.event);
++ failure = '';
++ notice();
++ onUpdate();
++ }
++
++ /** Subscribe to real relay events with an explicit engine declaration and no bearer token or key. */
+ function subscribe(entry) {
+ entry.stream?.close();
- const stream = new EventSource('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor);
++ const controller = new AbortController();
++ const stream = { close: () => controller.abort() };
+ entry.stream = stream;
+ entry.queue ??= Promise.resolve();
- stream.onmessage = event => {
- entry.queue = entry.queue.then(async () => {
- const document = JSON.parse(event.data);
- if (document.version !== 1) throw new Error('Upgrade this browser client to read the relay API.');
- await receive(entry, document.event);
- failure = '';
- notice();
- onUpdate();
- }).catch(error => { stream.close(); failure = error.message; notice(); });
- };
- stream.addEventListener('warning', event => {
- try { warning(JSON.parse(event.data).warning, entry.id); } catch { /* Malformed warnings never become board content. */ }
- });
- stream.addEventListener('error', event => {
- if (!event.data) return;
- stream.close();
- entry.queue = entry.queue.then(async () => {
- const error = JSON.parse(event.data).error;
- if (error?.code === 'SNAPSHOT_REQUIRED') {
- await snapshot(entry);
- await catchUp(entry);
- subscribe(entry);
- onUpdate();
- } else { if (['AUTH_REQUIRED', 'NO_REPO_ACCESS', 'TOKEN_BOARD', 'NO_BOARD'].includes(error?.code)) denied(); failure = error ? '[' + error.code + '] ' + error.message : 'The relay stream ended. Refresh this board.'; notice(); }
- }).catch(error => { failure = error.message; notice(); });
- });
++ (async () => {
++ while (!controller.signal.aborted && !accessLost) {
++ try {
++ const response = await fetch('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor, {
++ credentials: 'same-origin', cache: 'no-store', redirect: 'error', signal: controller.signal,
++ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), accept: 'text/event-stream' },
++ });
++ if (!response.ok) {
++ const document = await response.json();
++ if ([401, 403].includes(response.status) || document.error?.code === 'NO_BOARD') denied();
++ throw new Refused(document.error?.code ?? 'RELAY_UNAVAILABLE', document.error?.message ?? 'The relay stream ended. Refresh this board.');
++ }
++ if (!response.body) throw new Error('The relay stream is unavailable. Refresh this board.');
++ const reader = response.body.getReader();
++ const decoder = new TextDecoder();
++ let buffer = '';
++ while (!controller.signal.aborted) {
++ const { value, done } = await reader.read();
++ buffer += decoder.decode(value, { stream: !done });
++ const packets = buffer.split(/\r?\n\r?\n/u);
++ buffer = packets.pop() ?? '';
++ for (const packet of packets) {
++ const message = sseMessage(packet);
++ entry.queue = entry.queue.then(() => streamMessage(entry, message, stream));
++ await entry.queue;
++ }
++ if (done) break;
++ }
++ } catch (error) {
++ if (controller.signal.aborted || accessLost) return;
++ failure = error.message;
++ notice();
++ await new Promise(resolveRetry => setTimeout(resolveRetry, 1000));
++ }
++ }
++ })();
+ }
+
+ /** Reauthorize the listing, pair only visible boards, and close streams for lost access. */
+ async function listing() {
+ const document = await documentAt('/api/v1/boards', denied);
+ 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 (!encoded) continue;
+ try {
+ const entry = { id: board.id, key: decodeBoardKey(encoded), cursor: -1, state: null, outbox: null };
+ await snapshot(entry);
+ await catchUp(entry);
+ if (accessLost) throw new Error('Sign in again to read this board.');
+ paired.get(board.id)?.stream?.close();
+ paired.set(board.id, entry);
+ keys[board.id] = encoded;
+ try { localStorage.setItem(KEYS, JSON.stringify({ ...stored(localStorage, KEYS, {}), [board.id]: encoded })); } catch { failure = 'This browser cannot save pairing. Use the pairing link again on your next visit.'; }
+ if (pair?.board === board.id) {
+ pair = null;
+ try { sessionStorage.removeItem(PENDING); } catch { /* Device storage can be unavailable. */ }
+ }
+ subscribe(entry);
+ } catch (error) { failure = error.code === 'RELAY_ENGINE_VERSION' ? error.message : 'Could not open this board with its saved key. Pair this browser again from a linked machine.'; }
+ }
+ notice();
+ return {
+ version: 1, boards: available.filter(board => paired.has(board.id)).map(board => ({ id: board.id, root: board.id, name: board.repository, project: board.repository })), warnings: [],
+ };
+ }
+
+ /** Save only ciphertext on the device so an interrupted send retains its stable request id. */
+ function saveOutbox(entry) {
+ try {
+ if (entry.outbox) localStorage.setItem(OUTBOX + entry.id + '.' + entry.outbox.id, JSON.stringify(entry.outbox));
+ } catch { throw new Refused('REQUEST_STORAGE', 'This browser cannot save the sealed request. Enable device storage before sending it.'); }
+ }
+
+ /** Read each independently saved request so another tab cannot overwrite or clear its intent. */
+ function pendingRequests(entry) {
+ const values = [];
+ try {
+ const prefix = OUTBOX + entry.id + '.';
+ for (let index = 0; index < localStorage.length; index += 1) {
+ const key = localStorage.key(index);
+ if (key?.startsWith(prefix)) {
+ const value = stored(localStorage, key, null);
+ if (!value || typeof value.id !== 'string' || key !== prefix + value.id) throw new Error('invalid saved request');
+ values.push(value);
+ }
+ }
+ } catch { throw new Refused('REQUEST_STORAGE', 'The browser cannot read its saved sealed requests. Restore device storage before sending again.'); }
+ return values.sort((left, right) => left.sequence - right.sequence || left.id.localeCompare(right.id));
+ }
+
+ /** Remove only the acknowledged request's storage entry, preserving another tab's pending intent. */
+ function acknowledge(entry, id) {
+ try { localStorage.removeItem(OUTBOX + entry.id + '.' + id); }
+ catch { throw new Refused('REQUEST_STORAGE', 'The request was received, but device storage could not record that acknowledgement. Retry this board.'); }
+ entry.outbox = null;
+ }
+
+ /** Reconcile previously authorized sealed sends before returning state or accepting another action. */
+ async function flushOutbox(entry) {
+ for (const pending of pendingRequests(entry)) {
+ entry.outbox = pending;
+ await sendOutbox(entry);
+ }
+ }
+
+ /** Serialize browser reads, sends and live events through the same per-board cursor owner. */
+ function enqueue(entry, work) {
+ const task = (entry.queue ?? Promise.resolve()).then(work);
+ entry.queue = task.catch(() => {});
+ return task;
+ }
+
+ /** Seal an unchanged intent at its current public sequence after another client wins the order. */
+ async function requestEnvelope(entry, value, sequence) {
+ const bytes = await seal(entry.key, new TextEncoder().encode(JSON.stringify(value)), { boardId: entry.id, kind: 'request', sequence });
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return { id: value.id, sequence, sealed: btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '') };
+ }
+
+ /** Send a durable opaque intent, repairing order collisions without creating another request. */
+ async function sendOutbox(entry) {
+ const pending = entry.outbox;
+ if (!pending) return null;
+ const plain = await unseal(entry.key, transportBytes(pending.sealed), { boardId: entry.id, kind: 'request', sequence: pending.sequence });
+ const value = validatePersonRequest(JSON.parse(new TextDecoder().decode(plain)));
+ if (value.id !== pending.id) throw new Refused('REQUEST_STORAGE', 'The saved request is inconsistent. Pair this browser again.');
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ await snapshot(entry);
+ await catchUp(entry);
+ const received = entry.state.personRequests?.find(record => record.id === value.id);
+ if (received) { acknowledge(entry, value.id); return { version: 1, event: null, result: { request: received } }; }
+ if (entry.outbox.sequence !== entry.cursor + 1) {
+ entry.outbox = await requestEnvelope(entry, value, entry.cursor + 1);
+ saveOutbox(entry);
+ }
+ const envelope = entry.outbox;
+ let response;
+ try {
+ response = await documentAt('/api/v1/boards/' + entry.id + '/requests', denied, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sequence: envelope.sequence, sealed: envelope.sealed }),
+ });
+ } catch (error) { if (['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) continue; throw error; }
+ if (response.event?.event_id !== envelope.sequence || response.event.kind !== 'request' || response.event.sealed !== envelope.sealed) throw new Refused('RELAY_RESPONSE', 'The relay acknowledgement differs from this request. Retry this board.');
+ await receive(entry, response.event);
+ const record = entry.state.personRequests.find(request => request.id === value.id);
+ if (!record) throw new Refused('RELAY_RESPONSE', 'The request acknowledgement has no receipt. Retry this board.');
+ acknowledge(entry, value.id);
+ onUpdate();
+ return { version: 1, event: response.event, result: { request: structuredClone(record) } };
+ }
+ throw new Refused('RELAY_BUSY', 'Other clients kept winning the relay order. Retry this saved request.');
+ }
+
+ /** 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(); }
+ 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 listing();
+ return {
+ /** Return decoded API state or seal narrow person intent; no board key or plaintext leaves the device. */
+ async request(path, body) {
+ 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(); }
+ const match = /^\/api\/v1\/boards\/([0-9a-f]{32})\/(state|events|moves|requests)$/.exec(url.pathname);
+ const entry = match && paired.get(match[1]);
+ if (!entry) throw new Error('Pair this browser to read that board.');
+ if (body !== undefined && body !== null) {
+ if (!['moves', 'requests'].includes(match[2])) throw new Refused('BAD_REQUEST', 'Send person intent to this board’s moves endpoint.');
+ const value = preparePersonRequest(body);
+ const send = enqueue(entry, async () => {
+ await flushOutbox(entry);
+ await snapshot(entry); await catchUp(entry);
+ entry.outbox = await requestEnvelope(entry, value, entry.cursor + 1);
+ saveOutbox(entry);
+ return sendOutbox(entry);
+ });
+ return send;
+ }
+ if (!['state', 'events'].includes(match[2])) throw new Refused('BAD_REQUEST', 'Read this board’s state or events endpoint.');
+ return enqueue(entry, async () => {
+ await flushOutbox(entry);
+ await snapshot(entry);
+ await catchUp(entry);
+ if (entry.stream?.readyState === EventSource.CLOSED) subscribe(entry);
+ if (match[2] === 'state') return { version: 1, state: entry.state };
+ return { version: 1, events: [...entry.state.events].reverse() };
+ });
+ },
+ };
+}
diff --cc relay/service.js
index 4352f1c5,4bbb664c..7dc6a3c1
--- a/relay/service.js
+++ b/relay/service.js
@@@ -1,6 -1,5 +1,6 @@@
- /** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7]. */
+ /** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7,H16,H3]. */
import { createServer } from 'node:http';
+import { createHash } from 'node:crypto';
import { lstatSync, mkdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { createApiHandler, apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js';
@@@ -132,10 -148,9 +150,10 @@@ export function createRelayHandler({ di
return withJournal(board.id, (journal) => {
const row = journal.append(body.sequence, bytes, kind, principal);
return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };
- });
+ }, false, who.engineVersion);
}
+ const browser = origin ? createRelayBrowserHandler({ authenticate: (req) => auth.authenticate(credential(req, origin)) }) : null;
const common = createApiHandler({
authenticate: async (req, { board, write }) => {
const token = credential(req, origin, write);
@@@ -172,25 -186,9 +190,25 @@@
catch { throw new Refused('BAD_REQUEST', 'use a valid path under /api/v1/boards'); }
const snapshot = /^\/api\/v1\/boards\/([^/]+)\/state$/.exec(url.pathname);
const deletion = /^\/api\/v1\/boards\/([^/]+)$/.exec(url.pathname);
+ if (req.method === 'GET' && snapshot) {
+ const id = identity(snapshot[1]);
- await authorized(credential(req, origin), id);
++ const who = await authorizedRequest(req, id);
+ const saved = withJournal(id, journal => {
+ const row = journal.snapshot();
+ if (!row) throw new Refused('NO_SNAPSHOT', 'upload a sealed snapshot before reading this board');
+ return annotated(row, id);
- });
++ }, false, who.engineVersion);
+ const tag = '"' + createHash('sha256').update(JSON.stringify(saved)).digest('hex') + '"';
+ res.setHeader('etag', tag);
+ if (req.headers['if-none-match'] === tag) {
+ res.writeHead(304, { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });
+ return res.end();
+ }
+ return apiJson(res, 200, { state: saved });
+ }
if (req.method === 'PUT' && snapshot) {
const id = identity(snapshot[1]);
- sender(await authorized(credential(req, origin, true), id, true), true);
+ sender(await authorizedRequest(req, id, true), true);
const body = await readApiBody(req, { maxBytes: SNAPSHOT_BODY });
const bytes = sealed(body);
if (!Number.isSafeInteger(body.sequence) || body.sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence covered by the sealed snapshot');
diff --cc test/relay-browser.test.js
index b91f7b26,00000000..8078b091
mode 100644,000000..100644
--- a/test/relay-browser.test.js
+++ b/test/relay-browser.test.js
@@@ -1,302 -1,0 +1,308 @@@
+/** Real Chrome reads and follows device-sealed boards; the relay never receives its key [H5,H15,H18]. */
+import assert from 'node:assert/strict';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { snapshotState, presentationState } from '../relay/browser-model.js';
+import { decodeBoardKey, seal, unseal } from '../src/seal.js';
+import { relaySnapshot } from '../src/relay-presentation.js';
+import { ENGINE_VERSION } from '../src/machine.js';
+import { addItem, closeBoard, openBoard } from '../src/board.js';
+import { relayClientFixture } from './relay-client-fixture.js';
+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
+
+/** Sign a browser in with the real stand-in device grant, without exposing its credential. */
+async function signIn(chrome, box) {
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const result = await chrome.send('Network.setCookie', {
+ name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',
+ });
+ assert.equal(result.success, true, 'the real authorized person session is installed in this private browser');
+ return state;
+}
+
+test('older native snapshots project into read-only API state and reject wrong board/version [H5,H15]', async t => {
+ const box = await relayClientFixture(t);
+ const id = box.before.tables.board_meta.find(row => row.meta_key === 'board_id').meta_value;
+ const state = snapshotState(box.before, id);
+ assert.equal(state.items[0].title, box.before.tables.item[0].item_title);
+ assert.equal(Array.isArray(state.products), true);
+ const held = structuredClone(box.before);
+ held.tables.hold = [{ hold_lane: box.lane, hold_reason: 'fixture hold', hold_by: 'coordinator', hold_at: '2026-01-01T00:00:00.000Z' }];
+ Object.assign(held.tables.item[0], { item_status: 'submitted', item_review_by: 'expired-reviewer', item_review_until: '2000-01-01T00:00:00.000Z' });
+ const projected = snapshotState(held, id);
+ assert.deepEqual(projected.holds, held.tables.hold);
+ assert.equal(projected.items[0].reviewer, null);
+ assert.throws(() => snapshotState(box.before, '0'.repeat(32)), { code: 'RELAY_SNAPSHOT' });
+ assert.throws(() => snapshotState({ ...box.before, version: 2 }, id), { code: 'RELAY_SNAPSHOT' });
+ assert.throws(() => presentationState({ version: 2, state }, id), { code: 'RELAY_PRESENTATION' });
+});
+
+test('conditional sealed snapshots reauthorize before 304 and refresh spec-only presentation [H5,H15]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const endpoint = box.origin + '/api/v1/boards/' + link.board + '/state';
- const headers = { authorization: 'Bearer ' + link.token };
++ const headers = { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) };
+ const first = await fetch(endpoint, { headers });
+ assert.equal(first.status, 200);
+ const tag = first.headers.get('etag');
+ assert.equal(typeof tag, 'string');
+ const body = await first.json();
+ const unchanged = await fetch(endpoint, { headers: { ...headers, 'if-none-match': tag } });
+ assert.equal(unchanged.status, 304);
+ const unauthorized = await fetch(endpoint, { headers: { 'if-none-match': tag } });
+ assert.equal(unauthorized.status, 401, 'a cached ciphertext tag never grants access');
+ writeFileSync(join(box.root, 'SPEC.md'), '# Browser fixture spec\n\n## G · Goals\n\n- G1 [draft, must] SPEC_PRESENTATION_ONLY_108 | gate: review\n');
+ assert.equal((await box.cli('status')).code, 0, 'a board read publishes changed spec presentation without a move');
+ const changed = await fetch(endpoint, { headers: { ...headers, 'if-none-match': tag } });
+ assert.equal(changed.status, 200);
+ assert.equal(changed.headers.get('etag') === tag, false);
+ const row = (await changed.json()).state;
+ assert.equal(row.sequence, body.state.sequence, 'spec refresh preserves the acknowledged move sequence');
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const document = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(row.sealed, 'base64url'), { boardId: link.board, kind: 'snapshot', sequence: row.sequence })));
+ assert.equal(document.presentation.state.spec.some(rule => rule.text === 'SPEC_PRESENTATION_ONLY_108'), true);
+});
+
- test('real Chrome pairs, retains its device key, follows SSE without polling and shows inactivity [H5,H15,H18]', {
++test('real Chrome pairs, retains its device key, declares its engine on every relay request and shows inactivity [H5,H15,H18,H16,H3]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const firstTitle = 'SEALED_BROWSER_INITIAL_108';
+ const liveTitle = 'SEALED_BROWSER_LIVE_108';
+ const secondTitle = 'SECOND_LINKED_BOARD_108';
+ assert.equal((await box.cli('add', box.lane, firstTitle)).code, 0);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const encoded = readFileSync(box.keyFile, 'utf8').trim();
+ const second = await box.additionalBoard(secondTitle);
+ const unauthenticated = await fetch(box.origin + '/');
+ const signInPage = await unauthenticated.text();
+ assert.equal(signInPage.includes('Sign in with GitHub'), true);
+ assert.equal(signInPage.includes(firstTitle), false);
+ assert.equal(signInPage.includes(encoded), false);
+
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', {
+ source: 'window.setInterval = () => 0;',
+ });
+ await signIn(chrome, box);
++ const firstBrowserCall = box.calls.length;
+ const beforeUnpaired = box.calls.length;
+ await chrome.navigate(box.origin);
+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes('pair this browser')");
+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(firstTitle) + ')'), false);
+ assert.equal(box.calls.slice(beforeUnpaired).some(call => /\/(state|events)(?:\?|$)/.test(call.path)), false,
+ 'a browser without the key sees only authorized board names and pairing guidance');
+
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(firstTitle) + ')');
+ assert.equal(await chrome.evaluate('location.hash === ""'), true, 'the pairing key is removed from browser history');
+ assert.equal(await chrome.evaluate("JSON.parse(localStorage.getItem('pullboard.relay.keys.v1'))[" + JSON.stringify(link.board) + '].length === 43'), true);
+ assert.equal(await chrome.evaluate("getComputedStyle(document.querySelector('#new-item')).display === 'none'"), true, 'the relay page hides action controls');
+ assert.equal(box.calls.some(call => call.accept.includes('text/event-stream')), true, 'the page opened a real authorized event stream');
++ const browserApiCalls = box.calls.slice(firstBrowserCall).filter(call => call.path.startsWith('/api/v1/'));
++ assert.ok(browserApiCalls.length > 0, 'the browser made authenticated relay API requests');
++ assert.ok(browserApiCalls.every(call => call.engine === String(ENGINE_VERSION)), 'every browser API request, including catch-up and the live stream, declares the current engine');
++ const browserEngine = await fetch(box.origin + '/relay/engine.js');
++ assert.equal(await browserEngine.text(), 'export const ENGINE_VERSION = ' + ENGINE_VERSION + ';\n', 'the served browser engine matches the current relay engine');
+ await chrome.navigate(box.origin + '/#board=' + second.id + '&key=' + second.encoded);
+ await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 2");
+ assert.equal(await chrome.evaluate("Object.keys(JSON.parse(localStorage.getItem('pullboard.relay.keys.v1'))).length === 2"), true,
+ 'pairing another board retains both device-only keys');
+ const firstSelector = '#proj-list .proj.repo[data-root="' + link.board + '"]';
+ await chrome.evaluate('document.querySelector(' + JSON.stringify(firstSelector) + ').click()');
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(firstTitle) + ')');
+
+
+ assert.equal((await box.cli('add', box.lane, liveTitle)).code, 0);
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(liveTitle) + ')');
+ assert.equal(await chrome.evaluate("document.querySelector('#relay-notice').textContent.includes('Requests from this device wait for a linked machine')"), true);
+ await chrome.navigate(box.origin);
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(liveTitle) + ')');
+ assert.equal(await chrome.evaluate('location.hash === ""'), true, 'a later visit needs no new pairing link');
+ box.advance(80);
+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes('BOARD_INACTIVE') && document.querySelector('#relay-notice').textContent.includes('10 days left')");
+ assert.equal(box.keyInRequest(), false, 'the key was never in an HTTP URL or header');
+ await box.revokeSession();
+ await chrome.waitFor("document.body.textContent.includes('Sign in with GitHub') && !document.body.textContent.includes(" + JSON.stringify(liveTitle) + ')');
+});
+
+/** Append an authenticated synthetic sealed move without writing it to the private local board. */
+async function appendEngineMove(box, link, key, sequence, engine, presentation) {
+ const event = { event_id: sequence, event_kind: 'add', event_by: 'fixture', event_at: new Date().toISOString(), event_detail: '{}' };
+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify({ version: 1, engine, event, ...(presentation ? { presentation } : {}) })), {
+ boardId: link.board, kind: 'move', sequence,
+ })).toString('base64url');
+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/moves', {
- method: 'POST', headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },
++ method: 'POST', headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },
+ body: JSON.stringify({ sequence, sealed }),
+ });
+ assert.equal(response.status, 200, 'the private stand-in accepts the synthetic sealed sequence');
+ return response.json();
+}
+
+test('real Chrome refuses a newer engine in the initial replay without exposing board contents [H5,H15]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const privateTitle = 'ENGINE_TWO_PRIVATE_108';
+ assert.equal((await box.cli('add', box.lane, privateTitle)).code, 0);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const presentation = relaySnapshot(box.root).presentation;
+ presentation.state.items[0].title = privateTitle;
+ await appendEngineMove(box, link, key, 1, ENGINE_VERSION + 1, presentation);
+
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await signIn(chrome, box);
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());
+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes(" + JSON.stringify('This board needs engine ' + (ENGINE_VERSION + 1)) + ")");
+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(privateTitle) + ')'), false,
+ 'an unsupported initial event cannot install its attached presentation');
+});
+
+test('real Chrome refuses a newer engine delivered over the live stream [H5,H15]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const initialTitle = 'ENGINE_ONE_INITIAL_108';
+ const privateTitle = 'ENGINE_TWO_LIVE_PRIVATE_108';
+ assert.equal((await box.cli('add', box.lane, initialTitle)).code, 0);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.setInterval = () => 0;' });
+ await signIn(chrome, box);
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(initialTitle) + ')');
+ const presentation = relaySnapshot(box.root).presentation;
+ presentation.state.items[0].title = privateTitle;
+ await appendEngineMove(box, link, key, 1, ENGINE_VERSION + 1, presentation);
+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes(" + JSON.stringify('This board needs engine ' + (ENGINE_VERSION + 1)) + ")");
+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(privateTitle) + ')'), false,
+ 'a newer live engine is refused before its presentation changes the page');
+});
+
+test('real Chrome waits for and installs the late snapshot that compacts a legacy move [H5,H15]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const initialTitle = 'LATE_SNAPSHOT_INITIAL_108';
+ const finalTitle = 'LATE_SNAPSHOT_REPAIRED_108';
+ assert.equal((await box.cli('add', box.lane, initialTitle)).code, 0);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.setInterval = () => 0;' });
+ await signIn(chrome, box);
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(initialTitle) + ')');
+
+ await appendEngineMove(box, link, key, 1, ENGINE_VERSION);
+ await new Promise(resolveLate => setTimeout(resolveLate, 350));
+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(finalTitle) + ')'), false,
+ 'the event position is not consumed while the current snapshot is behind it');
+
+ const checkpoint = relaySnapshot(box.root);
+ checkpoint.tables.item[0].item_title = finalTitle;
+ checkpoint.presentation.state.items[0].title = finalTitle;
+ const bytes = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(checkpoint)), {
+ boardId: link.board, kind: 'snapshot', sequence: 1,
+ })).toString('base64url');
+ const uploaded = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {
- method: 'PUT', headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },
++ method: 'PUT', headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },
+ body: JSON.stringify({ sequence: 1, sealed: bytes }),
+ });
+ assert.equal(uploaded.status, 200, 'the stand-in acknowledges a snapshot covering the move');
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(finalTitle) + ')');
- const replay = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + link.token } });
++ const replay = 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(replay.status, 409, 'the relay compacted the covered event and requires the new snapshot cursor');
+ assert.equal(box.keyInRequest(), false, 'the key remains absent from browser requests');
+});
+
+test('an unauthenticated pairing link stays device-only through sign-in and a wrong key shows no contents [H5,H15]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const marker = 'PRIVATE_BOARD_WITH_PAIRING_108';
+ assert.equal((await box.cli('add', box.lane, marker)).code, 0);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const encoded = readFileSync(box.keyFile, 'utf8').trim();
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);
+ await chrome.waitFor("document.body.textContent.includes('Sign in with GitHub') && location.hash === ''");
+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(marker) + ')'), false);
+ await chrome.navigate(box.origin + '/auth/github/start');
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(marker) + ')');
+
+ const wrong = await startChrome();
+ t.after(() => wrong.close());
+ await signIn(wrong, box);
+ await wrong.navigate(box.origin + '/#board=' + link.board + '&key=' + 'A'.repeat(43));
+ await wrong.waitFor("document.querySelector('#relay-notice')?.textContent.includes('Could not open')");
+ assert.equal(await wrong.evaluate('document.body.textContent.includes(' + JSON.stringify(marker) + ')'), false);
+ assert.equal(box.keyInRequest(), false);
+});
+
+/** A pre-ordered mirror's durable local outbox keeps its final browser projection recoverable. */
+test('legacy queued presentations never disclose later unacknowledged moves [H5,H15]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ // Recreate the historical pre-161 link metadata, then commit two local-first rows directly.
+ link.cursor = box.before.tables.event.at(-1)?.event_id ?? 0;
+ delete link.mode;
+ delete link.presentationDigest;
+ writeFileSync(box.linkFile, JSON.stringify(link) + '\n', { mode: 0o600 });
+ const board = openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));
+ try {
+ addItem(board, { by: 'coordinator', lane: box.lane, title: 'FIRST_QUEUED_108' });
+ addItem(board, { by: 'coordinator', lane: box.lane, title: 'SECOND_QUEUED_108' });
+ } finally { closeBoard(board); }
+ box.refuseSnapshotWrites(true);
+ const status = await box.cli('status');
+ assert.equal(status.code, 0);
+ assert.equal((status.document.diagnostics ?? []).some(line => line.includes('[RELAY_UNAVAILABLE]')), true,
+ 'a refused snapshot keeps the final projection pending for retry');
+ assert.equal(box.calls.filter(call => call.method === 'POST' && /\/moves$/.test(call.path)).length, 2, 'both queued moves reached the real stand-in route');
+ assert.equal(box.moveAcks.length, 2, 'both encrypted move acknowledgements were captured before snapshot compaction');
+ const pendingLink = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ assert.equal(pendingLink.needsPresentation, true);
+ assert.equal(Boolean(pendingLink.snapshot), true);
- const oldState = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', { headers: { authorization: 'Bearer ' + link.token } });
++ const oldState = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', { headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });
+ assert.equal((await oldState.json()).state.sequence, 0, 'the relay did not acknowledge the refused checkpoint');
+
+ box.refuseSnapshotWrites(false);
+ const retried = await box.cli('status');
+ assert.equal(retried.code, 0);
+ assert.equal(retried.document.diagnostics?.length ?? 0, 0, 'the saved checkpoint retries without re-sending acknowledged moves');
+ assert.equal(box.moveAcks.length, 2);
+ const completedLink = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ assert.equal(completedLink.needsPresentation, false, 'only a matching snapshot acknowledgement clears the pending presentation');
+ assert.equal(Boolean(completedLink.snapshot), false);
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const moves = await Promise.all(box.moveAcks.map(async row => JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(row.sealed, 'base64url'), { boardId: link.board, kind: row.kind, sequence: row.event_id })))));
+ assert.equal(moves[0].presentation, undefined, 'the earlier record cannot attest the already-advanced whole board');
+ assert.equal(moves[1].presentation.state.events[0].event_id, moves[1].event.event_id);
+ assert.equal(moves[1].presentation.state.items.some(item => item.title === 'SECOND_QUEUED_108'), true);
- const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', { headers: { authorization: 'Bearer ' + link.token } });
++ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', { headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });
+ assert.equal(response.status, 200);
+ const checkpoint = (await response.json()).state;
+ assert.equal(checkpoint.sequence, box.moveAcks[1].event_id, 'the acknowledged final checkpoint covers the omitted presentation');
+ const document = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(checkpoint.sealed, 'base64url'), { boardId: link.board, kind: 'snapshot', sequence: checkpoint.sequence })));
+ assert.equal(document.presentation.state.items.some(item => item.title === 'FIRST_QUEUED_108'), true);
+ assert.equal(document.presentation.state.items.some(item => item.title === 'SECOND_QUEUED_108'), true);
- const compacted = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + link.token } });
++ 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');
+});
diff --cc test/relay-client-fixture.js
index ad3dc9f7,e05e031c..6f4f8a0c
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@@ -66,27 -62,8 +66,27 @@@ export async function relayClientFixtur
let signIn;
let api;
const calls = [];
+ const moveAcks = [];
+ const privateKeys = new Set();
+ let keyLeaked = false;
const server = createServer(async (req, res) => {
- calls.push({ method: req.method, path: req.url, engine: req.headers['x-pullboard-engine'] });
+ const end = res.end.bind(res);
+ res.end = (chunk, ...args) => {
+ if (req.method === 'POST' && /\/api\/v1\/boards\/[0-9a-f]{32}\/moves$/.test(req.url ?? '') && (typeof chunk === 'string' || Buffer.isBuffer(chunk))) {
+ try {
+ const response = JSON.parse(Buffer.isBuffer(chunk) ? chunk.toString('utf8') : chunk);
+ if (typeof response.event?.sealed === 'string') moveAcks.push(response.event);
+ } catch { /* Capture only valid move acknowledgements; the production response remains unchanged. */ }
+ }
+ return end(chunk, ...args);
+ };
- calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '' });
++ calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '', engine: req.headers['x-pullboard-engine'] });
+ if ([...privateKeys].some(key => JSON.stringify({ url: req.url, headers: req.headers }).includes(key))) keyLeaked = true;
+ if (refuseEventReads && req.method === 'GET' && /\/events(?:\?|$)/.test(req.url)) {
+ res.writeHead(503, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture read outage' } }));
+ return;
+ }
if (override && req.method === 'DELETE') {
res.writeHead(override.status, { 'content-type': 'application/json' });
res.end(JSON.stringify({ version: override.version ?? 1, error: { code: override.code, message: 'fixture refusal' } }));
diff --cc test/relay-client.test.js
index e5330240,06109d9f..6f20e3de
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@@ -603,15 -599,9 +603,15 @@@ async function legacyMirrorQueueFragmen
const resumed = await cli(root, relayEnv, 'status');
assert.equal(resumed.relay.behind, 0, 'the next reachable command drains the queued legacy rows');
assert.deepEqual(localEvents(boardFile), queuedRows, 'migration checkpoints existing rows instead of replaying them');
- assert.deepEqual(relay.uploads.slice(initialUploadCount).map((upload) => upload.sequence), [4, 5]);
+ const legacyUploads = relay.uploads.slice(initialUploadCount);
+ assert.deepEqual(legacyUploads.map((upload) => upload.sequence), [4, 5]);
+ const openedLegacy = await Promise.all(legacyUploads.map(async (upload) => JSON.parse(new TextDecoder().decode(await unseal(
+ key, Buffer.from(upload.sealed, 'base64url'), { boardId, kind: 'move', sequence: upload.sequence },
+ )))));
+ assert.equal(openedLegacy[0].presentation, undefined, 'the historical first move cannot attest the later row');
+ assert.equal(openedLegacy[1].presentation.state.events[0].event_id, queuedEvents.at(-1).event_id, 'the final legacy move carries only its matching projection');
- const authorization = { authorization: `Bearer ${currentPersonToken}` };
+ const authorization = { 'x-pullboard-engine': '3', authorization: `Bearer ${currentPersonToken}` };
const stateResponse = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, { headers: authorization });
assert.equal(stateResponse.status, 200);
const stateDocument = await stateResponse.json();
diff --cc test/relay-person-actions.test.js
index efdb833b,00000000..75a762a5
mode 100644,000000..100644
--- a/test/relay-person-actions.test.js
+++ b/test/relay-person-actions.test.js
@@@ -1,206 -1,0 +1,206 @@@
+/** A paired person can use narrow CLI actions; agents cannot impersonate those actions [H12,H16,B26]. */
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { prepareEngineMove } from '../src/engine.js';
+import { openBoard, closeBoard } from '../src/board.js';
+import { executeMove } from '../src/api.js';
+import { main } from '../src/cli.js';
+import { decodeBoardKey, seal } from '../src/seal.js';
+import { ENGINE_VERSION } from '../src/machine.js';
+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
+import { relayClientFixture } from './relay-client-fixture.js';
+
+/** Install only the private fixture's person cookie in the real browser. */
+async function signIn(chrome, box) {
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const result = await chrome.send('Network.setCookie', {
+ name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',
+ });
+ assert.equal(result.success, true);
+}
+
+/** Pair a real browser and initialize the same transport used by the relay cockpit. */
+async function pairedTransport(chrome, box, title) {
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const key = readFileSync(box.keyFile, 'utf8').trim();
+ await signIn(chrome, box);
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');
+ await chrome.evaluate(`(async () => {
+ const { createTransport } = await import('/relay/client.js');
+ window.__personActionTransport = await createTransport({ onUpdate: () => {} });
+ return true;
+ })()`);
+ return link;
+}
+
+/** Submit literal person intent through the browser-owned transport. */
+async function personAction(chrome, board, move) {
+ return chrome.evaluate('window.__personActionTransport.request('
+ + JSON.stringify('/api/v1/boards/' + board + '/moves') + ',' + JSON.stringify(move) + ')');
+}
+
+/** Poll checkpoint completion separately from CDP's 15-second per-evaluation deadline. */
+async function waitRequest(chrome, board, id, status) {
+ const path = '/api/v1/boards/' + board + '/state';
+ const predicate = `value.state?.personRequests?.some(entry => entry.id === ${JSON.stringify(id)} && entry.status === ${JSON.stringify(status)})`;
+ // A serialized stream task may wait up to 15 seconds for a checkpoint. Let the page finish
+ // that task and perform another state read, while each CDP evaluation remains synchronous.
+ await chrome.evaluate(`(() => {
+ window.__personActionReceipt = null;
+ (async () => {
+ const deadline = Date.now() + 30000;
+ while (Date.now() < deadline) {
+ try {
+ const value = await window.__personActionTransport.request(${JSON.stringify(path)});
+ if (${predicate}) { window.__personActionReceipt = { value }; return; }
+ } catch { /* A checkpoint still being uploaded leaves the request waiting. */ }
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ window.__personActionReceipt = { error: 'The native request status did not reach the paired browser.' };
+ })();
+ return true;
+ })()`);
+ await chrome.waitFor('window.__personActionReceipt !== null', 45000);
+ const receipt = await chrome.evaluate('window.__personActionReceipt');
+ assert.equal(receipt.error, undefined, receipt.error);
+ return receipt.value;
+}
+
+test('real paired person adds, answers a person decision, and holds then releases a lane [H12,H16,B26]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const title = 'PERSON_ACTION_ITEM_FIXTURE';
+ const decisionText = 'PERSON_ACTION_DECISION_FIXTURE';
+ assert.equal((await box.cli('add', box.lane, 'PERSON_ACTION_BROWSER_READY')).code, 0);
+ const asked = await box.cli('shout', 'person', decisionText, '--decision');
+ assert.equal(asked.code, 0);
+ const decision = asked.document.id;
+ assert.ok(Number.isSafeInteger(decision));
+ await box.link();
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ const link = await pairedTransport(chrome, box, 'PERSON_ACTION_BROWSER_READY');
+
+ const added = await personAction(chrome, link.board, {
+ verb: 'add', args: { lane: box.lane, title },
+ });
+ assert.equal(added.result.request.status, 'waiting');
+ assert.equal((await box.cli('status')).code, 0);
+ await waitRequest(chrome, link.board, added.result.request.id, 'done');
+ let exported = (await box.cli('export')).document;
+ const item = exported.tables.item.find(row => row.item_title === title);
+ assert.ok(item, 'the actual CLI created the requested item');
+ assert.equal(item.item_created_by, 'person');
+ const addEvent = exported.tables.event.find(row => row.event_kind === 'add' && row.item_id === item.item_id);
+ assert.equal(addEvent.event_by, 'person');
+
+ const answered = await personAction(chrome, link.board, {
+ verb: 'answer', item: decision, args: { text: 'PERSON_ACTION_ANSWER_FIXTURE' },
+ });
+ assert.equal(answered.result.request.status, 'waiting');
+ assert.equal((await box.cli('status')).code, 0);
+ await waitRequest(chrome, link.board, answered.result.request.id, 'done');
+ exported = (await box.cli('export')).document;
+ const answer = exported.tables.event.find(row => row.event_kind === 'answer' && row.event_by === 'person');
+ assert.ok(answer);
+ assert.equal(JSON.parse(answer.event_detail).channel, 'view');
+
+ const held = await personAction(chrome, link.board, {
+ verb: 'hold', args: { lane: box.lane, reason: 'PERSON_ACTION_HOLD_FIXTURE' },
+ });
+ assert.equal(held.result.request.status, 'waiting');
+ assert.equal((await box.cli('status')).code, 0);
+ await waitRequest(chrome, link.board, held.result.request.id, 'done');
+ exported = (await box.cli('export')).document;
+ assert.deepEqual(exported.tables.hold.map(row => [row.hold_lane, row.hold_by]), [[box.lane, 'person']]);
+ const holdEvent = exported.tables.event.find(row => row.event_kind === 'hold' && JSON.parse(row.event_detail).reason === 'PERSON_ACTION_HOLD_FIXTURE');
+ assert.equal(holdEvent.event_by, 'person');
+
+ const released = await personAction(chrome, link.board, { verb: 'hold', args: { lane: box.lane, off: true } });
+ assert.equal(released.result.request.status, 'waiting');
+ assert.equal((await box.cli('status')).code, 0);
+ await waitRequest(chrome, link.board, released.result.request.id, 'done');
+ exported = (await box.cli('export')).document;
+ assert.equal(exported.tables.hold.some(row => row.hold_lane === box.lane), false);
+ const unholdEvent = exported.tables.event.find(row => row.event_kind === 'unhold' && JSON.parse(row.event_detail).lane === box.lane);
+ assert.equal(unholdEvent.event_by, 'person');
+ const actionEvents = exported.tables.event.filter(row => ['add', 'answer', 'hold', 'unhold'].includes(row.event_kind) && row.event_by === 'person');
+ assert.deepEqual(actionEvents.map(row => row.event_kind), ['add', 'answer', 'hold', 'unhold']);
+
+ const invalid = await personAction(chrome, link.board, {
+ verb: 'hold', args: { lane: 'PERSON_ACTION_NO_SUCH_LANE', reason: 'must refuse' },
+ });
+ assert.equal((await box.cli('status')).code, 0);
+ await waitRequest(chrome, link.board, invalid.result.request.id, 'refused');
+ const state = await chrome.evaluate('window.__personActionTransport.request(' + JSON.stringify('/api/v1/boards/' + link.board + '/state') + ')');
+ const refusal = state.state.personRequests.find(row => row.id === invalid.result.request.id).error;
+ assert.equal(refusal.code, 'NO_LANE');
+ exported = (await box.cli('export')).document;
+ assert.equal(exported.tables.event.some(row => row.event_kind === 'hold' && JSON.parse(row.event_detail).lane === 'PERSON_ACTION_NO_SUCH_LANE'), false);
+ const brief = 'Files:\n- ../foreign.js\nTest:\n- Keep the file in its own lane';
+ const foreign = await personAction(chrome, link.board, { verb: 'add', args: { lane: box.lane, title: 'PERSON_ACTION_FOREIGN_BRIEF', brief } });
+ assert.equal((await box.cli('status')).code, 0);
+ const rejected = (await chrome.evaluate('window.__personActionTransport.request(' + JSON.stringify('/api/v1/boards/' + link.board + '/state') + ')')).state.personRequests.find(row => row.id === foreign.result.request.id);
+ assert.equal(rejected.status, 'refused');
+ assert.equal(rejected.error.code, 'BRIEF_LANE');
+ const terminal = await box.cli('add', box.lane, 'PERSON_ACTION_FOREIGN_BRIEF', '--brief', brief);
+ assert.equal(terminal.code, 1);
+ assert.deepEqual(rejected.error, terminal.document.error, 'lane preflight retains the ordinary CLI refusal and repair');
+
+});
+
+test('local view attribution is person-only and an agent token cannot seal person-attributed holds [H12,H16,B26]', async t => {
+ const box = await relayClientFixture(t);
+ const localHold = await executeMove(box.root, { verb: 'hold', args: { lane: box.lane, reason: 'LOCAL_PERSON_HOLD_FIXTURE' } }, main);
+ assert.equal(localHold.status, 200);
+ assert.equal(localHold.body.event.event_by, 'person');
+ assert.equal(JSON.parse(localHold.body.event.event_detail).channel, 'view');
+ const localRelease = await executeMove(box.root, { verb: 'hold', args: { lane: box.lane, off: true } }, main);
+ assert.equal(localRelease.status, 200);
+ assert.equal(localRelease.body.event.event_by, 'person');
+ assert.equal(JSON.parse(localRelease.body.event.event_detail).channel, 'view');
+
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const tokenResponse = await fetch(box.origin + '/auth/tokens', {
+ method: 'POST', headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },
+ body: JSON.stringify({ board: link.board, agent: 'person-action-agent' }),
+ });
+ assert.equal(tokenResponse.status, 201);
+ const agentToken = (await tokenResponse.json()).token;
+ const stateResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {
- headers: { authorization: 'Bearer ' + link.token },
++ headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(stateResponse.status, 200);
+ let sequence = (await stateResponse.json()).state.sequence;
+ const board = openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));
+ let attempted;
+ try {
+ attempted = [
+ prepareEngineMove(board, 'holdLane', [box.lane, { agentId: 'coordinator', asPerson: true, reason: 'forged person hold' }]),
+ prepareEngineMove(board, 'releaseLane', [box.lane, { agentId: 'coordinator', asPerson: true }]),
+ ];
+ } finally { closeBoard(board); }
+ for (const move of attempted) {
+ sequence += 1;
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(move)), { boardId: link.board, kind: 'move', sequence })).toString('base64url');
+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/moves', {
- method: 'POST', headers: { authorization: 'Bearer ' + agentToken, 'content-type': 'application/json' },
++ method: 'POST', headers: { authorization: 'Bearer ' + agentToken, 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },
+ body: JSON.stringify({ sequence, sealed }),
+ });
+ assert.equal(response.status, 200, 'the relay stores the opaque agent-authenticated envelope');
+ }
+ assert.equal((await box.cli('status')).code, 0, 'native replay records both sender refusals');
+ const exported = (await box.cli('export')).document;
+ const refusals = exported.tables.event.filter(row => row.event_kind === 'relay_refused' && row.event_by === 'person-action-agent');
+ assert.deepEqual(refusals.map(row => JSON.parse(row.event_detail).code), ['RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY']);
+ assert.equal(exported.tables.event.some(row => ['hold', 'unhold'].includes(row.event_kind)
+ && JSON.parse(row.event_detail).reason === 'forged person hold'), false);
+ assert.equal(exported.tables.hold.some(row => row.hold_lane === box.lane && row.hold_reason === 'forged person hold'), false);
+ assert.ok(Number.isSafeInteger(ENGINE_VERSION), 'the test follows the current engine envelope without pinning a version');
+});
diff --cc test/relay-person-requests.test.js
index 271f3346,00000000..d2146672
mode 100644,000000..100644
--- a/test/relay-person-requests.test.js
+++ b/test/relay-person-requests.test.js
@@@ -1,217 -1,0 +1,218 @@@
+/** A paired browser seals person intent; only native Pullboard executes it [H12,H16,B26]. */
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { decodeBoardKey, seal } from '../src/seal.js';
++import { ENGINE_VERSION } from '../src/machine.js';
+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
+import { relayClientFixture } from './relay-client-fixture.js';
+
+/** Install the fixture's person session without exposing its cookie in browser diagnostics. */
+async function signIn(chrome, box) {
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const result = await chrome.send('Network.setCookie', {
+ name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',
+ });
+ assert.equal(result.success, true, 'the real person session is installed in the isolated browser');
+}
+
+/** Pair a real browser, then create the same transport module used by the relay cockpit. */
+async function pairedTransport(chrome, box, title) {
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const encoded = readFileSync(box.keyFile, 'utf8').trim();
+ await signIn(chrome, box);
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');
+ await chrome.evaluate(`(async () => {
+ const { createTransport } = await import('/relay/client.js');
+ window.__personRequestTransport = await createTransport({ onUpdate: () => {} });
+ return true;
+ })()`);
+ return link;
+}
+
+/** Send one exact person intent through the browser transport rather than constructing a move. */
+async function sendPersonIntent(chrome, board, move) {
+ const path = '/api/v1/boards/' + board + '/moves';
+ return chrome.evaluate('window.__personRequestTransport.request('
+ + JSON.stringify(path) + ',' + JSON.stringify(move) + ')');
+}
+
+/** Poll the browser's authenticated, device-decrypted presentation for one durable receipt. */
+async function waitForRequest(chrome, board, id, status, requireCoordinatorRequest = false) {
+ const path = '/api/v1/boards/' + board + '/state';
+ const predicate = `(() => { const row = documentValue.state?.personRequests?.find(entry => entry.id === ${JSON.stringify(id)}); return row?.status === ${JSON.stringify(status)}${requireCoordinatorRequest ? ' && Number.isSafeInteger(row.coordinatorRequest)' : ''}; })()`;
+ await chrome.waitFor(`(async () => { try { const documentValue = await window.__personRequestTransport.request(${JSON.stringify(path)}); return ${predicate}; } catch { return false; } })()`);
+ return chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(path) + ')');
+}
+
+/** Add a private pending spec row without changing shared or submitted repository files. */
+function addPendingSpecRow(box, id) {
+ const path = join(box.root, 'SPEC.md');
+ const original = readFileSync(path, 'utf8');
+ assert.equal(original.includes(id + ' ['), false, 'the synthetic row id is unused');
+ writeFileSync(path, original + `\n## Person request fixture\n\n- ${id} [pending, aim] Person requests wait for coordinator application. | gate: review\n`);
+ return { path, original };
+}
+
+test('real paired Chrome transports one person shout, and native status makes one authored shout [H12,H16]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const title = 'PERSON_REQUEST_SHOUT_FIXTURE';
+ assert.equal((await box.cli('add', box.lane, title)).code, 0);
+ await box.link();
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ const link = await pairedTransport(chrome, box, title);
+ const move = { verb: 'shout', args: { to: 'coordinator', text: 'PERSON_REQUEST_SHOUT_LITERAL' } };
+ const receipt = await sendPersonIntent(chrome, link.board, move);
+
+ assert.equal(receipt.version, 1);
+ assert.equal(receipt.result.request.status, 'waiting');
+ assert.deepEqual(receipt.result.request.move, move);
+ assert.equal(typeof receipt.result.request.id, 'string');
+ assert.equal(box.calls.some(call => call.method === 'POST' && call.path === `/api/v1/boards/${link.board}/requests`), true,
+ 'the browser posts a sealed request document, not an executable engine move');
+ assert.equal(box.keyInRequest(), false, 'the device key never enters an HTTP request');
+ const session = JSON.parse(readFileSync(box.linkFile, 'utf8'));
- const rawResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + session.token } });
++ const rawResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + session.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });
+ assert.equal(rawResponse.status, 200);
+ const raw = await rawResponse.json();
+ assert.equal(JSON.stringify(raw).includes(move.args.text), false, 'the relay response contains opaque ciphertext rather than request text');
+ const sealedRequest = raw.events.find(row => row.kind === 'request');
+ assert.ok(sealedRequest && typeof sealedRequest.sealed === 'string');
+
+
+ assert.equal((await box.cli('status')).code, 0, 'the next native status receives and executes the queued intent');
+ const latest = await waitForRequest(chrome, link.board, receipt.result.request.id, 'done');
+ const personShouts = latest.state.shouts.filter(shout => shout.shout_from === 'person' && shout.shout_text === move.args.text);
+ assert.equal(personShouts.length, 1, 'the authored person shout occurs exactly once');
+ const exported = (await box.cli('export')).document;
+ assert.equal(exported.tables.shout.filter(shout => shout.shout_from === 'person' && shout.shout_text === move.args.text).length, 1);
+});
+
+test('real paired Chrome approval remains pending until coordinator applies and answers; invalid add keeps its CLI refusal [H12,H16,B26]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const title = 'PERSON_REQUEST_APPROVAL_FIXTURE';
+ const id = 'G98';
+ const row = addPendingSpecRow(box, id);
+ assert.equal((await box.cli('add', box.lane, title)).code, 0);
+ await box.link();
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ const link = await pairedTransport(chrome, box, title);
+
+ const before = readFileSync(row.path, 'utf8');
+ const approval = await sendPersonIntent(chrome, link.board, { verb: 'spec-approve', args: { ids: id } });
+ assert.equal(approval.result.request.status, 'waiting');
+ assert.deepEqual(approval.result.request.move, { verb: 'spec-approve', args: { ids: id } });
+ assert.equal((await box.cli('status')).code, 0);
+ const pendingState = await waitForRequest(chrome, link.board, approval.result.request.id, 'waiting', true);
+ assert.equal(readFileSync(row.path, 'utf8'), before, 'the received approval records a row decision but does not edit SPEC.md');
+ const decisionEvents = (await box.cli('export')).document.tables.event.filter(event => event.event_kind === 'row_decision' && event.event_by === 'person');
+ assert.equal(decisionEvents.length, 1, 'the native row decision is attributed to the person');
+ assert.equal(JSON.parse(decisionEvents[0].event_detail).record.id, id);
+ const coordinatorRequest = pendingState.state.personRequests.find(entry => entry.id === approval.result.request.id).coordinatorRequest;
+ const resume = (await box.cli('resume')).document;
+ assert.equal(resume.requests[0].shout_id, coordinatorRequest, 'coordinator resume presents the pending repository request first');
+
+
+ assert.equal((await box.cli('spec', 'apply')).code, 0, 'the coordinator applies the recorded decision locally');
+ assert.match(readFileSync(row.path, 'utf8'), new RegExp(`- ${id} \\[approved, aim\\]`));
+ const requestId = pendingState.state.personRequests.find(entry => entry.id === approval.result.request.id).coordinatorRequest;
+ assert.equal((await box.cli('answer', String(requestId), 'done')).code, 0, 'the coordinator resolves the original request after applying it');
+ const completed = await waitForRequest(chrome, link.board, approval.result.request.id, 'done');
+ assert.equal(completed.state.personRequests.find(entry => entry.id === approval.result.request.id).status, 'done');
+
+ const invalid = await sendPersonIntent(chrome, link.board, {
+ verb: 'add', args: { lane: box.lane, title: 'PERSON_REQUEST_INVALID_SPEC', specs: 'G999' },
+ });
+ assert.equal(invalid.result.request.status, 'waiting');
+ assert.equal((await box.cli('status')).code, 0, 'native CLI status records the exact command refusal without creating an item');
+ const afterInvalid = (await box.cli('export')).document;
+ assert.equal(afterInvalid.tables.item.some(item => item.item_title === 'PERSON_REQUEST_INVALID_SPEC'), false, 'the native CLI refuses unknown specs before an ordinary add move');
+ const refused = await waitForRequest(chrome, link.board, invalid.result.request.id, 'refused');
+ const refusal = refused.state.personRequests.find(entry => entry.id === invalid.result.request.id).error;
+ assert.equal(refusal.code, 'UNKNOWN_SPEC');
+ assert.equal(refusal.message, 'G999 is not in SPEC.md');
+ const terminalRefusal = await box.cli('add', box.lane, 'PERSON_REQUEST_INVALID_SPEC', '--specs', 'G999');
+ assert.equal(terminalRefusal.code, 1);
+ assert.deepEqual(refusal, terminalRefusal.document.error, 'the request carries the same complete CLI refusal document');
+ const local = (await box.cli('export')).document;
+ assert.equal(local.tables.item.some(item => item.item_title === 'PERSON_REQUEST_INVALID_SPEC'), false);
+ assert.equal(local.tables.event.some(event => event.event_kind === 'row_decision' && JSON.parse(event.event_detail).record.id === 'G999'), false);
+});
+
+test('an agent-sealed row approval is refused before any row receipt or spec edit [H12,H16,B26]', async t => {
+ const box = await relayClientFixture(t);
+ const id = 'G97';
+ const row = addPendingSpecRow(box, id);
+ const before = readFileSync(row.path, 'utf8');
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const personToken = link.token;
+ const tokenResponse = await fetch(box.origin + '/auth/tokens', {
+ method: 'POST', headers: { authorization: 'Bearer ' + personToken, 'content-type': 'application/json' },
+ body: JSON.stringify({ board: link.board, agent: 'request-fixture-agent' }),
+ });
+ assert.equal(tokenResponse.status, 201, 'the signed-in person can issue a scoped agent token');
+ const agentToken = (await tokenResponse.json()).token;
+ const snapshotResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {
- headers: { authorization: 'Bearer ' + personToken },
++ headers: { authorization: 'Bearer ' + personToken, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(snapshotResponse.status, 200);
+ const sequence = (await snapshotResponse.json()).state.sequence + 1;
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const document = { version: 1, type: 'person-request', id: randomUUID(), move: { verb: 'spec-approve', args: { ids: id } } };
+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(document)), {
+ boardId: link.board, kind: 'request', sequence,
+ })).toString('base64url');
+ const uploaded = await fetch(box.origin + '/api/v1/boards/' + link.board + '/requests', {
- method: 'POST', headers: { authorization: 'Bearer ' + agentToken, 'content-type': 'application/json' },
++ method: 'POST', headers: { authorization: 'Bearer ' + agentToken, 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },
+ body: JSON.stringify({ sequence, sealed }),
+ });
+ assert.equal(uploaded.status, 200, 'the opaque journal accepts authenticated ciphertext without interpreting it');
+ assert.equal((await box.cli('status')).code, 0, 'native replay records the sender refusal');
+ const exported = (await box.cli('export')).document;
+ const receipts = JSON.parse(exported.tables.board_meta.find(row => row.meta_key === 'relay_person_requests').meta_value);
+ const refused = receipts.find(entry => entry.id === document.id);
+ assert.equal(refused.status, 'refused');
+ assert.equal(refused.error.code, 'RELAY_PERSON_ONLY');
+ assert.equal(exported.tables.event.some(event => event.event_kind === 'row_decision' && JSON.parse(event.event_detail).record.id === id), false);
+ assert.equal(readFileSync(row.path, 'utf8'), before, 'agent intent cannot create a person receipt or change SPEC.md');
+});
+
+test('coordinator decline resolves a paired approval request with a reason and leaves repo files unchanged [H12,H16,B26]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const row = addPendingSpecRow(box, 'G96');
+ const before = readFileSync(row.path, 'utf8');
+ const title = 'PERSON_REQUEST_DECLINE_FIXTURE';
+ assert.equal((await box.cli('add', box.lane, title)).code, 0);
+ await box.link();
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ const link = await pairedTransport(chrome, box, title);
+ const queued = await sendPersonIntent(chrome, link.board, { verb: 'spec-approve', args: { ids: 'G96' } });
+ assert.equal((await box.cli('status')).code, 0);
+ const statePath = '/api/v1/boards/' + link.board + '/state';
+ const pending = (await chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(statePath) + ')')).state.personRequests.find(record => record.id === queued.result.request.id);
+ assert.equal(pending.status, 'waiting');
+ assert.ok(Number.isSafeInteger(pending.coordinatorRequest));
+ const missingReason = await box.cli('answer', String(pending.coordinatorRequest), 'declined');
+ assert.equal(missingReason.code, 1);
+ assert.equal(missingReason.document.error.code, 'REQUEST_OUTCOME');
+ const reason = 'Waiting for a revised requirement';
+ assert.equal((await box.cli('answer', String(pending.coordinatorRequest), 'declined ' + reason)).code, 0);
+ const completed = (await chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(statePath) + ')')).state.personRequests.find(record => record.id === queued.result.request.id);
+ assert.equal(completed.status, 'refused');
+ assert.deepEqual(completed.error, { code: 'REQUEST_DECLINED', message: reason, next: 'Read the coordinator reason and send a revised request from the view.' });
+ assert.equal(readFileSync(row.path, 'utf8'), before, 'declining the repository request does not edit any row');
+ assert.deepEqual((await box.cli('resume')).document.requests, [], 'the declined request leaves the open coordinator queue');
+});
diff --cc test/relay-sealed.test.js
index 46ed25f3,d3207aa3..8d8c963a
--- a/test/relay-sealed.test.js
+++ b/test/relay-sealed.test.js
@@@ -105,127 -104,6 +105,131 @@@ function replayClient(root, env, ...arg
});
}
+/** Keep each client on its own replay path by blocking checkpoint publication, forwarding all reads to the real relay. */
+async function independentReplayOrigin(t, origin) {
+ const proxy = createServer(async (request, response) => {
+ if (request.method === 'PUT' && request.url.endsWith('/state')) {
+ response.writeHead(403, { 'content-type': 'application/json' });
+ response.end(JSON.stringify({ version: 1, error: { code: 'HUMAN_REQUIRED', message: 'fixture checkpoint publication disabled' } }));
+ return;
+ }
+ try {
- const reply = await fetch(origin + request.url, { headers: { authorization: request.headers.authorization ?? '' } });
++ const reply = await fetch(origin + request.url, { headers: {
++ authorization: request.headers.authorization ?? '',
++ 'x-pullboard-engine': request.headers['x-pullboard-engine'] ?? '',
++ ...(request.headers.accept ? { accept: request.headers.accept } : {}),
++ } });
+ response.writeHead(reply.status, { 'content-type': 'application/json' });
+ response.end(Buffer.from(await reply.arrayBuffer()));
+ } catch {
+ response.writeHead(502, { 'content-type': 'application/json' });
+ response.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture relay unavailable' } }));
+ }
+ });
+ await new Promise((done, fail) => { proxy.once('error', fail); proxy.listen(0, '127.0.0.1', done); });
+ t.after(() => new Promise(done => proxy.close(done)));
+ return 'http://127.0.0.1:' + proxy.address().port;
+}
+
+/** Capture a real linked command's warnings and structured refusal without changing its exit status. */
+function replayResult(root, env, ...args) {
+ return new Promise((done, fail) => {
+ const child = spawn(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let stdout = '', stderr = '';
+ const timer = setTimeout(() => child.kill('SIGKILL'), 25000);
+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });
+ child.stderr.setEncoding('utf8').on('data', part => { stderr += part; });
+ child.once('error', error => { clearTimeout(timer); fail(error); });
+ child.once('close', code => {
+ clearTimeout(timer);
+ if (code === null) return fail(new Error('isolated relay command did not finish'));
+ try { done({ document: JSON.parse(stdout), stderr, status: code }); }
+ catch { fail(new Error('isolated relay read did not return JSON')); }
+ });
+ });
+}
+
+test('two real clients stop before sender checks for newer operations and actor layouts without advancing [H16]', async t => {
+ const unknown = { version: 1, engine: 4, id: 'future-operation', operation: 'futureOp', args: [{ agentId: 'remote-1' }] };
+ const shifted = { version: 1, engine: 4, id: 'future-claim', operation: 'claim', args: [1, {}, { agentId: 'remote-1' }] };
+ for (const [name, moves] of [['new operation', [unknown]], ['new actor layout', [shifted]], ['current engine sender checks', [unknown, shifted].map(move => ({ ...move, engine: 3 }))]]) {
+ await t.test(name, async sub => {
+ const box = await fixture(sub);
+ const source = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));
+ let document;
+ try {
+ checkpointSequence(source, 0);
+ document = JSON.parse(JSON.stringify(exportBoard(source)));
+ } finally { store.closeBoard(source); }
+ const remote = await box.auth.issueToken(box.person.token, { board: box.id, agent: 'remote-1' });
+ const roots = [box.root, join(box.directory, 'second-client')];
+ const homes = [box.home, join(box.directory, 'second-home')];
+ const envs = homes.map(home => ({ ...box.env, HOME: home, PULLBOARD_HOME: home }));
+ mkdirSync(roots[1]); mkdirSync(homes[1], { mode: 0o700 });
+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: roots[1], env: envs[1] }).status, 0);
+ await replayClient(roots[1], envs[1], 'init');
+ const native = join(box.directory, 'native.json');
+ writeFileSync(native, JSON.stringify(document), { mode: 0o600 });
+ await replayClient(roots[1], envs[1], 'import', native);
+ const links = roots.map(root => join(root, '.git/pullboard/relay.json'));
+ for (let index = 0; index < roots.length; index += 1) {
+ const keyDirectory = join(homes[index], 'relay-keys');
+ mkdirSync(keyDirectory, { mode: 0o700 });
+ writeFileSync(join(keyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });
+ const replayOrigin = await independentReplayOrigin(sub, box.origin);
+ writeFileSync(links[index], JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: replayOrigin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });
+ }
+ const originalLinks = links.map(file => readFileSync(file, 'utf8'));
+ const initialSnapshot = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(document)), { boardId: box.id, kind: 'snapshot', sequence: 0 })).toString('base64url');
+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: initialSnapshot } })).status, 200);
+ for (let index = 0; index < moves.length; index += 1) {
+ const sequence = index + 1;
+ const sealed = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(moves[index])), { boardId: box.id, kind: 'move', sequence })).toString('base64url');
+ const uploaded = await box.call(box.path + '/moves', { method: 'POST', token: remote.token, body: { sequence, sealed } });
+ assert.equal(uploaded.status, 200);
+ assert.equal(uploaded.body.event.sender.agent, 'remote-1');
+ }
+ const results = [];
+ for (let index = 0; index < roots.length; index += 1) {
+ const result = await replayResult(roots[index], envs[index], 'export');
+ assert.equal(result.status, 0);
+ results.push(result.document);
+ if (moves[0].engine === 4) {
+ assert.match((result.document.diagnostics ?? []).join('\n'), /\[ENGINE_VERSION\].*engine version 4.*engine version 3.*upgrade pullboard/, 'future records stop before interpreting the sending agent');
+ assert.deepEqual(result.document.tables, document.tables, 'no board row, receipt or persisted cursor changes');
+ assert.equal(readFileSync(links[index], 'utf8'), originalLinks[index], 'the saved transport cursor is unchanged');
+ const retried = await replayResult(roots[index], envs[index], 'export');
+ assert.match((retried.document.diagnostics ?? []).join('\n'), /\[ENGINE_VERSION\]/);
+ assert.equal(retried.status, 0);
+ assert.deepEqual(retried.document.tables, document.tables, 'retry still stops at the same unapplied record');
+ const attempted = await replayResult(roots[index], envs[index], 'add', document.tables.item[0].item_lane, 'Later local move must wait');
+ assert.equal(attempted.status, 1);
+ assert.equal(attempted.document.error.code, 'ENGINE_VERSION');
+ assert.match(attempted.document.error.message, /engine version 4.*engine version 3/);
+ assert.equal(readFileSync(links[index], 'utf8'), originalLinks[index]);
+ const board = store.openBoard(join(roots[index], '.git/pullboard/board.sqlite'));
+ try { assert.deepEqual(JSON.parse(JSON.stringify(exportBoard(board))).tables, document.tables, 'a later local mutation cannot pass the future record'); }
+ finally { store.closeBoard(board); }
+ } else {
+ assert.doesNotMatch((result.document.diagnostics ?? []).join('\n'), /\[ENGINE_VERSION\]/);
+ assert.deepEqual(result.document.tables.item, document.tables.item);
+ assert.deepEqual(result.document.tables.shout, document.tables.shout);
+ assert.deepEqual(result.document.tables.verdict, document.tables.verdict);
+ const refused = result.document.tables.event.filter(row => row.event_kind === 'relay_refused');
+ assert.deepEqual(refused.map(row => JSON.parse(row.event_detail).code), ['RELAY_SENDER_MISMATCH', 'RELAY_SENDER_MISMATCH']);
+ assert.ok(refused.every(row => row.event_by === 'remote-1'));
+ assert.equal(result.document.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '2');
+ assert.equal(JSON.parse(readFileSync(links[index], 'utf8')).sequence, 2);
+ }
+ }
+ assert.deepEqual(results[0].tables, results[1].tables, 'the two independent clients retain identical board rows');
+ const snapshot = await box.call(box.path + '/state');
+ assert.equal(snapshot.body.state.sequence, 0);
+ assert.equal(snapshot.body.state.sealed, initialSnapshot, 'neither client replaced independent replay with a shared checkpoint');
+ });
+ }
+});
+
test('two real clients refuse forged relay actors and person-only requests while advancing identically [H2,H16]', async t => {
const box = await fixture(t);
const source = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));
diff --cc test/relay-version.test.js
index 00000000,a7cf1b5c..efac9635
mode 000000,100644..100644
--- a/test/relay-version.test.js
+++ b/test/relay-version.test.js
@@@ -1,0 -1,122 +1,123 @@@
+ /** Real authenticated client version gates before opaque board records [H16,H3]. */
+ import assert from 'node:assert/strict';
+ import { mkdtempSync, rmSync } from 'node:fs';
+ import { tmpdir } from 'node:os';
+ import { join } from 'node:path';
+ import { test } from 'node:test';
+ import { createRelayAuth } from '../relay/auth.js';
+ import { createGitHubClient } from '../relay/github.js';
+ import { serveRelay } from '../relay/service.js';
+ import { githubFixture } from './relay-fixture.js';
+
+ const A = 'a'.repeat(32); // no board credential has ever existed
+ const B = 'b'.repeat(32); // historical board credential, even after revocation
+
+ test('relay enforces the minimum engine ever required by each board [H16,H3]', async t => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-relay-version-'));
+ const provider = await githubFixture(t);
+ let time = Date.now();
+ const authConfig = { database: join(directory, 'auth.sqlite'), github: createGitHubClient(provider.config), now: () => time };
+ let auth = createRelayAuth(authConfig);
+ const flow = auth.beginWeb();
+ const grant = await fetch(flow.authorizationURL, { redirect: 'manual' });
+ const callback = new URL(grant.headers.get('location'));
+ const person = await auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), flow.binding);
+ await auth.linkBoard(person.token, A, 'fixture/repository');
+ await auth.linkBoard(person.token, B, 'fixture/repository');
+ const historical = await auth.issueToken(person.token, { board: B, agent: 'once-issued', expiresIn: 1 });
+ await auth.revoke(person.token, historical.id);
+ time += 10;
+ assert.equal(auth.minimumEngineVersion(A), 1);
+ assert.equal(auth.minimumEngineVersion(B), 3);
+ auth.close();
+ auth = createRelayAuth(authConfig);
+ assert.equal(auth.minimumEngineVersion(B), 3, 'the minimum survives revocation, expiry and reopening the real auth database');
+ const relay = await serveRelay({ directory: join(directory, 'data'), auth, maintenanceMs: 0, pollMs: 10 });
+ t.after(async () => { await relay.close(); auth.close(); rmSync(directory, { recursive: true, force: true }); });
+ const base = `http://127.0.0.1:${relay.port}/api/v1/boards/`;
+ const opaque = Buffer.from('opaque-test-ciphertext').toString('base64url');
+ /** Read or mutate only this private relay with an explicit client engine declaration. */
+ async function call(board, path = '/state', { engine, method = 'GET', body, token = person.token, accept } = {}) {
+ const headers = { authorization: `Bearer ${token}`, ...(engine === undefined ? {} : { 'x-pullboard-engine': String(engine) }),
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(accept ? { accept } : {}) };
+ const response = await fetch(base + board + path, { method, headers, ...(body === undefined ? {} : { body }) });
+ const text = await response.text();
+ let document;
+ try { document = JSON.parse(text); } catch { document = null; }
+ return { status: response.status, text, document, response };
+ }
+ // Seed opaque snapshots so eligible reads reach actual state and event handlers.
+ for (const board of [A, B]) {
+ const seeded = await call(board, '/state', { engine: 3, method: 'PUT', body: JSON.stringify({ sequence: 0, sealed: opaque }) });
+ assert.equal(seeded.status, 200, seeded.text);
+ }
+
+ for (const board of [A, B]) {
- assert.equal((await call(board, '/state', { engine: 3 })).status, 200);
++ const currentState = await call(board, '/state', { engine: 3 });
++ assert.equal(currentState.status, 200, currentState.text);
+ assert.equal((await call(board, '/events?after=0', { engine: 3 })).status, 200);
+ }
+ for (const board of [A, B]) {
+ const controller = new AbortController();
+ const streamed = await fetch(base + board + '/events?after=0', {
+ headers: { authorization: `Bearer ${person.token}`, 'x-pullboard-engine': '3', accept: 'text/event-stream' }, signal: controller.signal,
+ });
+ assert.equal(streamed.status, 200);
+ await streamed.body.cancel(); controller.abort();
+ }
+
+ assert.equal((await call(A, '/state', { engine: 2 })).status, 200, 'an unclaimed legacy board remains readable by engine 2');
+ assert.equal((await call(A, '/events?after=0', { engine: 2 })).status, 200);
+ for (const path of ['/state', '/events?after=0', '/moves', '/requests']) {
+ const method = path === '/state' ? 'GET' : path.startsWith('/events') ? 'GET' : 'POST';
+ const blocked = await call(B, path, { engine: 2, method, body: method === 'POST' ? 'this body must never be parsed' : undefined });
+ assert.equal(blocked.status, 400, blocked.text);
+ assert.equal(blocked.document?.error?.code, 'ENGINE_VERSION', blocked.text);
+ assert.match(blocked.document.error.message + ' ' + (blocked.document.error.next ?? ''), /upgrade/i);
+ assert.equal(blocked.text.includes(opaque), false, 'no stored ciphertext reaches the old client');
+ }
+ for (const [path, method] of [['/state', 'PUT'], ['', 'DELETE']]) {
+ const blocked = await call(B, path, { engine: 2, method, body: method === 'PUT' ? 'not-json' : undefined });
+ assert.equal(blocked.status, 400, blocked.text);
+ assert.equal(blocked.document?.error?.code, 'ENGINE_VERSION', 'the version gate precedes write-body parsing or deletion');
+ }
+ const oldStream = await call(B, '/events?after=0', { engine: 2, accept: 'text/event-stream' });
+ assert.equal(oldStream.status, 400);
+ assert.equal(oldStream.document.error.code, 'ENGINE_VERSION');
+ const legacyA = await call(A, '/state');
+ assert.equal(legacyA.status, 200, 'missing header is legacy engine 1 where no agent was ever issued');
+ const legacyB = await call(B, '/state');
+ assert.equal(legacyB.document?.error?.code, 'ENGINE_VERSION');
+ for (const malformed of ['2, 3', 'not-an-integer']) {
+ const refused = await call(B, '/state', { engine: malformed });
+ assert.equal(refused.document?.error?.code, 'ENGINE_VERSION');
+ }
+
+ // Engine 2 can still perform each supported write against the unclaimed board.
+ assert.equal((await call(A, '/moves', { engine: 2, method: 'POST', body: JSON.stringify({ sequence: 1, sealed: opaque }) })).status, 200);
+ assert.equal((await call(A, '/requests', { engine: 2, method: 'POST', body: JSON.stringify({ sequence: 2, sealed: opaque }) })).status, 200);
+ assert.equal((await call(A, '/state', { engine: 2, method: 'PUT', body: JSON.stringify({ sequence: 2, sealed: opaque }) })).status, 200);
+ const deleted = await call(A, '', { engine: 2, method: 'DELETE' });
+ assert.equal(deleted.status, 200, deleted.text);
+
+ // A new board lifetime starts at the legacy minimum; issuing a token stops its already-open old stream.
+ await auth.linkBoard(person.token, A, 'fixture/repository');
+ assert.equal((await call(A, '/state', { engine: 2, method: 'PUT', body: JSON.stringify({ sequence: 0, sealed: opaque }) })).status, 200);
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 5000);
+ t.after(() => { clearTimeout(timeout); controller.abort(); });
+ const live = await fetch(base + A + '/events?after=0', { headers: { authorization: `Bearer ${person.token}`, 'x-pullboard-engine': '2', accept: 'text/event-stream' }, signal: controller.signal });
+ assert.equal(live.status, 200);
+ const reader = live.body.getReader();
+ let received = new TextDecoder().decode((await reader.read()).value);
+ await auth.issueToken(person.token, { board: A, agent: 'new-agent' });
+ for (;;) {
+ const part = await reader.read();
+ if (part.done) break;
+ received += new TextDecoder().decode(part.value);
+ }
+ assert.match(received, /event: error/);
+ assert.match(received, /ENGINE_VERSION/);
+ assert.doesNotMatch(received, new RegExp(opaque), 'the now-old stream closes without returning stored records');
+ clearTimeout(timeout);
+ });