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.

feat(relay): serve a device-decrypted live browser view [H5,H15]

Corey Olson676dbdf28061
diff --git a/relay/browser-client.js b/relay/browser-client.js
new file mode 100644
index 00000000..1afd55a7
--- /dev/null
+++ b/relay/browser-client.js
@@ -0,0 +1,246 @@
+/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15]. */
+import { decodeBoardKey, unseal } from './seal.js';
+import { snapshotState, presentationState } from './model.js';
+
+const KEYS = 'pullboard.relay.keys.v1';
+const PENDING = 'pullboard.relay.pair.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) {
+ const response = await fetch(path, { 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?.();
+ throw new Error(error ? '[' + error.code + '] ' + error.message : '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();
+ 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 = ['Read-only relay view. Acting from the relay is coming.'];
+ 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 } : {},
+ });
+ 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);
+ entry.snapshotTag = response.headers.get('etag');
+ if (row.sequence >= entry.cursor) {
+ entry.state = state;
+ entry.cursor = row.sequence;
+ }
+ }
+
+ /** 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 (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 !== 1) throw new Error('This board needs engine ' + move.engine + '; this browser reads engine 1. Upgrade the browser client.');
+ if (move.presentation) {
+ entry.state = presentationState(move.presentation, entry.id);
+ entry.cursor = row.event_id;
+ } else {
+ await snapshot(entry);
+ if (entry.cursor < row.event_id) throw new Error('This move needs a refreshed presentation from a linked machine. Run pullboard status there.');
+ }
+ }
+
+ /** 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. */
+ function subscribe(entry) {
+ entry.stream?.close();
+ const stream = new EventSource('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor);
+ 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(); });
+ });
+ }
+
+ /** 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)) 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 };
+ await snapshot(entry);
+ await catchUp(entry);
+ 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 { failure = '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: [],
+ };
+ }
+
+ addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });
+ await listing();
+ return {
+ /** Supply the same decoded API documents as the local view, refusing every browser action. */
+ async request(path, body) {
+ if (body !== undefined && body !== null) throw new Error('This is a read-only relay view. Acting from the relay is coming.');
+ 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') return listing();
+ const match = /^\/api\/v1\/boards\/([0-9a-f]{32})\/(state|events)$/.exec(url.pathname);
+ const entry = match && paired.get(match[1]);
+ if (!entry) throw new Error('Pair this browser to read that board.');
+ await entry.queue;
+ 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 --git a/relay/browser-model.js b/relay/browser-model.js
new file mode 100644
index 00000000..e4750b5e
--- /dev/null
+++ b/relay/browser-model.js
@@ -0,0 +1,49 @@
+/** Read-only projection of older native snapshots; new uploads carry the actual API state [H5]. */
+import { Refused } from '../src/refused.js';
+
+/** Validate an authenticated snapshot and preserve its importable native tables. */
+export function snapshotState(document, boardId) {
+ const identity = document?.tables?.board_meta?.find(row => row.meta_key === 'board_id')?.meta_value;
+ if (document?.version !== 1 || identity !== boardId) throw new Refused('RELAY_SNAPSHOT', 'This snapshot belongs to another board or version. Pair again from a linked machine.');
+ if (document.presentation) return presentationState(document.presentation, boardId);
+ const tables = document.tables;
+ for (const name of ['item', 'agent', 'event', 'shout', 'verdict']) if (!Array.isArray(tables[name])) {
+ throw new Refused('RELAY_SNAPSHOT', 'The board snapshot is incomplete. Refresh it from a linked machine.');
+ }
+ const log = tables.event;
+ /** Map a native verdict to the local view's public presentation. */
+ const verdict = row => ({ decision: row.verdict_decision, reason: row.verdict_reason, note: row.verdict_note, by: row.verdict_by, at: row.verdict_at, commit: row.verdict_commit });
+ const statuses = new Map(tables.item.map(item => [item.item_id, item.item_status]));
+ const shouts = tables.shout.slice(-40).reverse();
+ const answered = new Set(tables.shout.filter(row => row.shout_answers !== null).map(row => row.shout_answers));
+ const decisions = tables.shout.filter(row => row.shout_decision && !answered.has(row.shout_id));
+ return {
+ root: boardId, lanes: [...new Set(tables.agent.map(row => row.agent_lane))],
+ owning: [...new Set(tables.item.map(row => row.item_lane))],
+ items: tables.item.map(item => {
+ const verdicts = tables.verdict.filter(row => row.item_id === item.item_id).map(verdict);
+ return {
+ id: item.item_id, title: item.item_title, lane: item.item_lane, status: item.item_status,
+ route: item.item_route, owner: item.item_owner, reviewer: item.item_review_by,
+ reviewUntil: item.item_review_until, builtBy: item.item_built_by, verifiedBy: item.item_verified_by,
+ specs: item.item_spec_ids ? item.item_spec_ids.split(',') : [], criterion: item.item_criterion,
+ brief: item.item_brief, commit: item.item_commit, merged: item.item_merged_commit,
+ blockedBy: (item.item_after ? item.item_after.split(',').map(Number) : []).filter(id => statuses.get(id) !== 'verified'),
+ updatedAt: item.item_updated_at, verdict: verdicts.at(-1) ?? null, verdicts,
+ history: log.filter(event => event.item_id === item.item_id).map(event => ({ kind: event.event_kind, by: event.event_by, at: event.event_at })),
+ };
+ }),
+ agents: tables.agent.map(agent => ({ ...agent, lastMoveAt: log.filter(event => event.event_by === agent.agent_id).at(-1)?.event_at ?? null })),
+ shouts, decisions: decisions.filter(row => row.shout_to === 'person'), asked: decisions.filter(row => row.shout_to !== 'person'),
+ events: log.slice(-80).reverse(), holds: tables.lane_hold ?? [], spec: [], practice: [], products: [], unseen: null,
+ };
+}
+
+/** Accept only a complete API presentation, then use a board identity for device routing. */
+export function presentationState(document, boardId) {
+ const state = document?.state;
+ if (document?.version !== 1 || !state || !['items', 'agents', 'shouts', 'decisions', 'asked', 'events', 'holds', 'spec', 'practice', 'lanes', 'owning'].every(key => Array.isArray(state[key]))) {
+ throw new Refused('RELAY_PRESENTATION', 'This board presentation is unsupported. Refresh it from a linked machine.');
+ }
+ return { ...structuredClone(state), root: boardId };
+}
diff --git a/relay/browser-page.js b/relay/browser-page.js
new file mode 100644
index 00000000..17d0966c
--- /dev/null
+++ b/relay/browser-page.js
@@ -0,0 +1,54 @@
+/** The relay serves the existing cockpit over a device-only decrypting transport [H5,H15]. */
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { cockpitPage } from '../src/cockpit.js';
+import { Refused } from '../src/refused.js';
+
+const STYLES = readFileSync(new URL('../src/view.css', import.meta.url), 'utf8');
+const SIGN_IN = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Pullboard</title><link rel="stylesheet" href="/view.css"><body><main class="card-panel"><h1>Pullboard</h1><p>Sign in to see your linked boards.</p><a href="/auth/github/start">Sign in with GitHub</a></main><script type="module">import { rememberPairing } from "/relay/client.js"; try { rememberPairing(); } catch { document.querySelector("main p").textContent = "The pairing link is invalid. Get a new link from a linked machine."; }</script></body></html>';
+
+/** Serve a fixed asset with cache and browser isolation boundaries, never a filesystem-derived URL. */
+function respond(res, type, content, scriptHashes = []) {
+ const hashes = scriptHashes.map(hash => "'sha256-" + hash + "'").join(' ');
+ res.writeHead(200, {
+ 'content-type': type + '; charset=utf-8', 'cache-control': 'no-store',
+ 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer',
+ 'content-security-policy': "default-src 'none'; script-src 'self' " + hashes + "; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
+ });
+ res.end(content);
+}
+
+/** Serve generic assets publicly and board-free sign-in HTML until a person is authenticated. */
+export function createRelayBrowserHandler({ authenticate }) {
+ const assets = new Map([
+ ['/view.css', ['text/css', STYLES]],
+ ['/relay/client.js', ['text/javascript', readFileSync(new URL('./browser-client.js', import.meta.url), 'utf8')]],
+ ['/relay/model.js', ['text/javascript', readFileSync(new URL('./browser-model.js', import.meta.url), 'utf8').replace("'../src/refused.js'", "'./refused.js'")]],
+ ['/relay/seal.js', ['text/javascript', readFileSync(new URL('../src/seal.js', import.meta.url), 'utf8')]],
+ ['/relay/refused.js', ['text/javascript', readFileSync(new URL('../src/refused.js', import.meta.url), 'utf8')]],
+ ]);
+ return async function handleBrowser(req, res) {
+ const path = new URL(req.url, 'http://localhost').pathname;
+ if (req.method !== 'GET') return false;
+ if (assets.has(path)) {
+ const [type, content] = assets.get(path);
+ respond(res, type, content);
+ return true;
+ }
+ if (path !== '/') return false;
+ try {
+ const who = await authenticate(req);
+ if (who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'Sign in as a person to open the relay view.');
+ } catch (error) {
+ if (!(error instanceof Refused) || !['AUTH_REQUIRED', 'HUMAN_REQUIRED'].includes(error.code)) throw error;
+ const script = /<script type="module">([\s\S]*?)<\/script>/.exec(SIGN_IN)[1];
+ respond(res, 'text/html', SIGN_IN, [createHash('sha256').update(script).digest('base64')]);
+ return true;
+ }
+ const page = cockpitPage('', { readOnly: true, transportModule: '/relay/client.js', apiHeaders: {}, stylesheet: '/view.css' })
+ .replace('<main>', '<main><section class="card-panel" id="relay-notice" role="status"><p>Pairing this browser…</p></section>');
+ const scripts = [...page.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(match => createHash('sha256').update(match[1]).digest('base64'));
+ respond(res, 'text/html', page, scripts);
+ return true;
+ };
+}
diff --git a/relay/service.js b/relay/service.js
index a0afcf95..4352f1c5 100644
--- a/relay/service.js
+++ b/relay/service.js
@@ -1,11 +1,13 @@
/** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7]. */
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';
import { Refused } from '../src/refused.js';
import { createRelayJournal } from './journal.js';
import { createRelayRetention } from './retention.js';
+import { createRelayBrowserHandler } from './browser-page.js';
const SNAPSHOT_BODY = 14_000_000;
const STORED_BYTES = 10_000_000;
@@ -133,6 +135,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
});
}
+ 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);
@@ -163,11 +166,28 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
/** Add authenticated snapshot replacement and deletion to the common versioned read/move paths. */
async function handle(req, res) {
try {
+ if (browser && await browser(req, res)) return;
let url;
try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); }
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 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);
+ });
+ 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);
diff --git a/src/relay.js b/src/relay.js
index 6a1e7af8..68e3659d 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import * as store from './board.js';
-import { exportBoard } from './exchange.js';
+import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';
import { repoInfo, tryGit } from './git.js';
import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
import { encodeBoardKey, generateBoardKey, seal } from './seal.js';
@@ -178,9 +178,13 @@ async function flush(root, file, state, io) {
!['move', 'request'].includes(event.kind) || typeof event.sealed !== 'string' || !/^[A-Za-z0-9_-]+$/.test(event.sealed))) {
throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid ordered event prefix; retry the configured relay');
}
+ // A mirror-only client cannot attest a checkpoint covering another device's unseen moves.
+ if (received.some(event => !(state.pending && event.event_id === state.pending.sequence && event.sealed === state.pending.sealed && event.kind === 'move'))) {
+ throw new Refused('RELAY_REPLAY_REQUIRED', 'another device changed this board; upgrade to a relay-order client before publishing a checkpoint or further queued moves');
+ }
if (state.pending) {
const accepted = received.find((event) => event.event_id === state.pending.sequence && event.sealed === state.pending.sealed && event.kind === 'move');
- if (accepted) { state.cursor = state.pending.localEvent; delete state.pending; }
+ if (accepted) { state.cursor = state.pending.localEvent; if (state.pending.presentationDigest) state.presentationDigest = state.pending.presentationDigest; delete state.pending; }
}
if (received.length) state.sequence = Math.max(state.sequence, ...received.map((event) => event.event_id));
if (state.pending && state.pending.sequence <= state.sequence) delete state.pending;
@@ -189,8 +193,9 @@ async function flush(root, file, state, io) {
for (const event of rows) {
if (!state.pending) {
const sequence = state.sequence + 1;
- state.pending = { localEvent: event.event_id, sequence,
- sealed: await sealedRecord(key, { version: 1, engine: 1, event }, state, 'move', sequence) };
+ const presentation = relayPresentation(root);
+ state.pending = { localEvent: event.event_id, sequence, presentationDigest: presentationDigest(presentation),
+ sealed: await sealedRecord(key, { version: 1, engine: 1, event, presentation }, state, 'move', sequence) };
saveLink(file, state);
}
const { sequence, sealed } = state.pending;
@@ -198,9 +203,22 @@ async function flush(root, file, state, io) {
if (reply.event?.event_id !== sequence || reply.event.sealed !== sealed) throw new Refused('RELAY_RESPONSE', 'the relay acknowledgement does not match the queued record; retry after checking the relay');
state.sequence = sequence;
state.cursor = event.event_id;
+ state.presentationDigest = state.pending.presentationDigest;
delete state.pending;
saveLink(file, state);
}
+ const presentation = relayPresentation(root);
+ const digest = presentationDigest(presentation);
+ if (state.presentationDigest !== digest) {
+ const document = relaySnapshot(root);
+ state.snapshot = { sequence: state.sequence, sealed: await sealedRecord(key, document, state, 'snapshot', state.sequence) };
+ state.presentationDigest = presentationDigest(document.presentation);
+ saveLink(file, state);
+ const uploaded = await request(state, path + '/state', { method: 'PUT', body: state.snapshot }, io);
+ if (uploaded.state?.sequence !== state.snapshot.sequence || uploaded.state.sealed !== state.snapshot.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the refreshed presentation; retry the configured relay');
+ delete state.snapshot;
+ saveLink(file, state);
+ }
return summary(root, state);
}
@@ -260,11 +278,12 @@ export async function relayOn(root, address, io) {
const key = state ? readBoardKey(state.board) : await generateBoardKey();
const signed = await deviceSignIn(url, io);
if (!state) {
- const snapshot = localRecords(root, (board) => ({ board: store.boardId(board), document: exportBoard(board) }));
+ const document = relaySnapshot(root);
+ const snapshot = { board: document.tables.board_meta.find(row => row.meta_key === 'board_id').meta_value, document };
// Save the device key before creating any remote link; a locked keychain cannot strand it.
const keyStorage = storeBoardKey(snapshot.board, key);
state = { version: 1, board: snapshot.board, url, repository, token: signed.token,
- tokenId: signed.id, keyStorage, sequence: 0, cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, linkPending: true };
+ tokenId: signed.id, keyStorage, presentationDigest: presentationDigest(snapshot.document.presentation), sequence: 0, cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, linkPending: true };
state.snapshot = { sequence: 0, sealed: await sealedRecord(key, snapshot.document, state, 'snapshot', 0) };
} else { state.token = signed.token; state.tokenId = signed.id; }
// Persist the exact sealed snapshot and a recoverable link intent before making the remote link.
diff --git a/test/relay-browser.test.js b/test/relay-browser.test.js
new file mode 100644
index 00000000..9819edf7
--- /dev/null
+++ b/test/relay-browser.test.js
@@ -0,0 +1,131 @@
+/** 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, unseal } from '../src/seal.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);
+ 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 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]', {
+ 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';
+ 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 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 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');
+
+ 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('Acting from the relay is coming')"), 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');
+});
+
+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 signIn(chrome, box);
+ await chrome.navigate(box.origin);
+ 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);
+});
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.js
index b1ed883f..91379f5d 100644
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@ -62,8 +62,11 @@ export async function relayClientFixture(t) {
let signIn;
let api;
const calls = [];
+ let privateKey = '';
+ let keyLeaked = false;
const server = createServer(async (req, res) => {
- calls.push({ method: req.method, path: req.url });
+ calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '' });
+ if (privateKey && JSON.stringify({ url: req.url, headers: req.headers }).includes(privateKey)) keyLeaked = true;
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' } }));
@@ -98,7 +101,10 @@ export async function relayClientFixture(t) {
const keyFile = join(env.PULLBOARD_HOME, 'relay-keys', id + '.key');
/** Start a saved real relay link without exposing the pairing fragment. */
- async function link() { assert.equal((await cli('relay', 'on', '--url', origin)).code, 0, 'real device sign-in links the board'); }
+ async function link() {
+ assert.equal((await cli('relay', 'on', '--url', origin)).code, 0, 'real device sign-in links the board');
+ privateKey = readFileSync(keyFile, 'utf8').trim();
+ }
/** Pair and unlink from a second real repository with its own private device home and key. */
async function otherDeviceOff() {
const otherRoot = join(scratch, 'other-device');
@@ -122,9 +128,10 @@ export async function relayClientFixture(t) {
return childResult(root, env, ['--input-type=module', '-e', source]);
}
return {
- root, env, lane, before, linkFile, keyFile, calls, cli, link, otherDeviceOff, script,
+ root, env, origin, lane, before, linkFile, keyFile, calls, cli, link, otherDeviceOff, script,
advance(days) { time = Date.now() + days * 86400000; },
overrideDelete(value) { override = value; },
mainURL: new URL('../src/cli.js', import.meta.url).href,
+ keyInRequest() { return keyLeaked; },
};
}
diff --git a/test/relay-client.test.js b/test/relay-client.test.js
index 0b0e009f..a0ec76af 100644
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@ -178,7 +178,10 @@ test('[H1,H7,H15] relay on snapshots and mirrors ciphertext, retries local moves
const openedSnapshot = JSON.parse(new TextDecoder().decode(await unseal(
key, Buffer.from(remoteState.body.state.sealed, 'base64url'), { boardId, kind: 'snapshot', sequence: 0 },
)));
- assert.deepEqual(openedSnapshot, beforeLink, 'the first sealed record is the exact native board snapshot');
+ assert.equal(openedSnapshot.version, beforeLink.version);
+ assert.deepEqual(openedSnapshot.tables, beforeLink.tables, 'the first sealed record preserves every native board row and counter');
+ assert.equal(openedSnapshot.presentation.version, 1);
+ assert.ok(openedSnapshot.presentation.state.items.some(item => item.criterion === marker), 'the optional encrypted API presentation has the same board contents');
await cli(root, relayEnv, 'add', lane, 'mirrored private move');
await cli(root, relayEnv, 'shout', 'person', 'mirrored private shout');
@@ -191,7 +194,8 @@ test('[H1,H7,H15] relay on snapshots and mirrors ciphertext, retries local moves
const opened = JSON.parse(new TextDecoder().decode(await unseal(
key, Buffer.from(event.sealed, 'base64url'), { boardId, kind: 'move', sequence: index + 1 },
)));
- assert.deepEqual(opened, { version: 1, engine: 1, event: firstMoves[index] });
+ assert.deepEqual({ version: opened.version, engine: opened.engine, event: opened.event }, { version: 1, engine: 1, event: firstMoves[index] });
+ assert.equal(opened.presentation.version, 1);
}
const linkFile = join(root, '.git', 'pullboard', 'relay.json');
@@ -224,7 +228,8 @@ test('[H1,H7,H15] relay on snapshots and mirrors ciphertext, retries local moves
const openedQueued = JSON.parse(new TextDecoder().decode(await unseal(
key, Buffer.from(queued.sealed, 'base64url'), { boardId, kind: 'move', sequence },
)));
- assert.deepEqual(openedQueued, { version: 1, engine: 1, event: allNewRows[offset + 2] }, 'queued records retain their local order');
+ assert.deepEqual({ version: openedQueued.version, engine: openedQueued.engine, event: openedQueued.event }, { version: 1, engine: 1, event: allNewRows[offset + 2] }, 'queued records retain their local order');
+ assert.equal(openedQueued.presentation.version, 1);
}
relay.dropNextReply();
await cli(root, relayEnv, 'add', lane, 'committed reply lost');