Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(relay): link sealed board mirrors [H1,H7,H15,P5]
Corey Olson339a140b4f59
diff --git a/docs/api.md b/docs/api.mdindex 6b99d102..0f46d078 100644--- a/docs/api.md+++ b/docs/api.md@@ -24,6 +24,7 @@ A successful command returns the fields listed below. `version` is always the nu| `lanes` | `version:number`, `lanes:object`, `shared:array`, `coordinator:string` || `resources` | `version:number`, `resources:array` || `settings` | `version:number`, `settings:object` |+| `relay` | `version:number`, `linked:boolean`, `board:string`, `url:string`, `link:string`, `sequence:number`, `behind:number` || `list` | `version:number`, `items:array` || `show` | `version:number`, `item_id:number`, `item_title:string`, `item_lane:string`, `item_status:string`, `verdicts:array` || `status` | `version:number`, `me:object`, `mine:array`, `stats:object`, `unread:number` |@@ -97,6 +98,8 @@ A refusal keeps the command's existing exit status and prints exactly one versio| `error` | `code:string`, `message:string`, `next:string` |<!-- api-refusal-shapes:end -->+`relay on`, `relay`, and `relay off` share the relay result shape. `status` adds a `relay` object with the current sequence and pending upload count. Successful results may include `diagnostics` for a relay refusal or inactivity notice; a local move still succeeds when its upload must wait. Device sign-in instructions are written immediately to stderr, including with `--json`, so the person can sign in before the command returns.+The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js` by `docs/api.test.js`.## Local HTTP API v1diff --git a/src/cli.js b/src/cli.jsindex 1f731846..453599dd 100644--- a/src/cli.js+++ b/src/cli.js@@ -53,6 +53,7 @@ import { doctorProblems } from './doctor.js';import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';+import { relayOff, relayOn, relayStatus, syncRelay } from './relay.js';const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));export const VERSION = PACKAGE.version;@@ -74,6 +75,8 @@ Set uppullboard view --export <dir> a read-only snapshot with event replay, for any static hostpullboard serve [--port N] local API v1: boards, state, moves, requests and live events,behind the session secret in its printed address+ pullboard relay [on|off] [--url <address>] link, inspect or unlink this board's sealed relay mirror+ on signs in through GitHub; the address defaults to https://app.pullboard.devpullboard resume where you are: your claim, branch, uncommitted work, what came back,unread shouts, what to do next; run it to start any sessionpullboard hooks reinstall the git hooks (e.g. after a fresh clone)@@ -182,6 +185,7 @@ const OPTIONS = {run: { type: 'string' },max: { type: 'string' },'dry-run': { type: 'boolean' },+ url: { type: 'string' },wait: { type: 'string' },verify: { type: 'boolean' },all: { type: 'boolean' },@@ -984,12 +988,13 @@ function readCommands(io, { first, second, rest, values }) {const summary = withBoard(ctx, (board) => {const me = whoAmI(ctx, board);const mine = store.listItems(board).filter((item) => item.item_status === 'claimed' && item.item_owner === me.id);- return { me, mine, stats: store.stats(board), unread: store.unreadCount(board, me.id) };+ return { me, mine, stats: store.stats(board), unread: store.unreadCount(board, me.id), relay: relayStatus(ctx.info.root) };});if (values.json) {io.result(summary);return 0;}+ if (summary.relay.linked) io.say(`relay: sequence ${summary.relay.sequence}; ${summary.relay.behind} pending uploads`);const { items, accepted, rejected } = summary.stats;io.say(`${summary.me.id}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);io.say(`board: ${items.open} open, ${items.claimed} claimed, ${items.submitted} awaiting verification, ${items.verified} verified, ${items.withdrawn} withdrawn`);@@ -1799,6 +1804,16 @@ async function runCommand(argv, io) {}if (command === 'hook') return await hookCommand(io, args);if (command === 'settings') return settingsCommand(io, args);+ if (command === 'relay') {+ if (second || rest.length || (first && !['on', 'off'].includes(first)) || (values.url && first !== 'on')) throw new Refused('USAGE', 'pullboard relay [on|off] [--url <address>]');+ const ctx = context(io);+ if (!first) await syncRelay(ctx.info.root, io);+ const result = first === 'on' ? await relayOn(ctx.info.root, values.url, io)+ : first === 'off' ? await relayOff(ctx.info.root, io) : relayStatus(ctx.info.root);+ io.result?.(result);+ io.say(result.linked ? `${result.link}\nrelay: sequence ${result.sequence}; ${result.behind} pending uploads` : 'relay off; the local board is complete');+ return 0;+ }if (command === 'gate') {const ctx = context(io);const gate = await runGate(ctx.info.root, ctx.config, { onWait: gateWaitReporter(io) });@@ -1826,7 +1841,23 @@ async function runCommand(argv, io) {/** Run one command and emit its single versioned JSON result when requested (A1). */export async function main(argv, streams) {const io = commandOutput(argv, streams);+ let sync = true;+ try {+ const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });+ const command = parsed.positionals[0];+ sync = Boolean(command) && !parsed.values.help && !parsed.values.version && !['help', 'version', 'hook', 'init', 'relay', 'tour'].includes(command);+ } catch { sync = false; }+ /** A network refusal reports lag but cannot reverse or prevent a successful local command. */+ const retry = async () => {+ try { await syncRelay(io.cwd, io); }+ catch (error) {+ if (!(error instanceof Refused)) throw error;+ if (!['NO_REPO', 'NO_CONFIG'].includes(error.code)) io.err(`pullboard: ${error.message}`);+ }+ };+ if (sync) await retry();const code = await runCommand(argv, io);+ if (sync && code === 0) await retry();io.flush(code);return code;}@@ -1838,6 +1869,6 @@ export function resultCommands() {...Object.keys(setupCommands({}, args)),...Object.keys(readCommands({}, args)),...Object.keys(workCommands({}, args)),- 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'forget', 'spec', 'prompt', 'hook', 'gate', 'settings',+ 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'forget', 'spec', 'prompt', 'hook', 'gate', 'settings', 'relay',])].sort();}diff --git a/src/json.js b/src/json.jsindex 31546f91..76d97dd9 100644--- a/src/json.js+++ b/src/json.js@@ -20,6 +20,7 @@ export const JSON_SHAPES = {lanes: shape({ lanes: 'object', shared: 'array', coordinator: 'string' }),resources: shape({ resources: 'array' }),settings: shape({ settings: 'object' }),+ relay: shape({ linked: 'boolean', board: 'string', url: 'string', link: 'string', sequence: 'number', behind: 'number' }),list: shape({ items: 'array' }),show: shape({ item_id: 'number', item_title: 'string', item_lane: 'string', item_status: 'string', verdicts: 'array' }),status: shape({ me: 'object', mine: 'array', stats: 'object', unread: 'number' }),@@ -117,7 +118,7 @@ export function commandOutput(argv, streams) {const message = refusal ? text.replace(/^\[[A-Z][A-Z0-9_]*\] /, '') : match?.[2] ?? text;document = refusalDocument({ code: refusal?.code ?? match?.[1] ?? (code === 2 ? 'USAGE' : 'COMMAND_FAILED'), message });} else if (result !== undefined) {- document = { version: JSON_SHAPES.version, ...result };+ document = { version: JSON_SHAPES.version, ...result, ...(diagnostics.length ? { diagnostics } : {}) };} else {// A native versioned document, such as export, already owns its public shape.let native;@@ -125,7 +126,7 @@ export function commandOutput(argv, streams) {try { native = JSON.parse(messages[0]); } catch { /* Ordinary command prose is kept as messages. */ }}document = native && !Array.isArray(native) && typeof native.version === 'number'- ? native : { version: JSON_SHAPES.version, messages, ...(diagnostics.length ? { diagnostics } : {}) };+ ? { ...native, ...(diagnostics.length ? { diagnostics } : {}) } : { version: JSON_SHAPES.version, messages, ...(diagnostics.length ? { diagnostics } : {}) };}streams.stdout.write(`${JSON.stringify(document, null, 2)}\n`);};diff --git a/src/qr.js b/src/qr.jsnew file mode 100644index 00000000..8872a64b--- /dev/null+++ b/src/qr.js@@ -0,0 +1,106 @@+/** Fixed version-6/L byte-mode QR symbols for device pairing links [H1,H17]. */+import { Refused } from './refused.js';++/** Multiply in QR's GF(256), with the primitive polynomial x^8+x^4+x^3+x^2+1. */+function multiply(a, b) {+ let value = 0;+ for (let i = 0; i < 8; i++) {+ if (b & 1) value ^= a;+ b >>>= 1;+ a <<= 1;+ if (a & 256) a ^= 0x11d;+ }+ return value;+}++/** Produce the eighteen Reed-Solomon check bytes required by each version-6/L block. */+function parity(data) {+ let generator = [1];+ let root = 1;+ for (let degree = 0; degree < 18; degree++) {+ const next = Array(generator.length + 1).fill(0);+ generator.forEach((value, index) => { next[index] ^= value; next[index + 1] ^= multiply(value, root); });+ generator = next;+ root = multiply(root, 2);+ }+ const check = Array(18).fill(0);+ for (const value of data) {+ const leading = value ^ check.shift();+ check.push(0);+ generator.slice(1).forEach((coefficient, index) => { check[index] ^= multiply(coefficient, leading); });+ }+ return check;+}++/** Encode a bounded pairing URL without fetching an image or sending its key to any service. */+export function qrModules(text) {+ const bytes = new TextEncoder().encode(text);+ if (bytes.length > 134) throw new Refused('PAIR_LINK_LONG', 'the pairing address is too long for the printed QR code; open the printed link');+ const bits = [0, 1, 0, 0];+ /** Append one big-endian field to the byte-mode segment. */+ const append = (value, width) => { for (let shift = width - 1; shift >= 0; shift--) bits.push((value >>> shift) & 1); };+ append(bytes.length, 8);+ for (const value of bytes) append(value, 8);+ for (let count = 0; count < 4 && bits.length < 1088; count++) bits.push(0);+ while (bits.length % 8) bits.push(0);+ const data = [];+ for (let start = 0; start < bits.length; start += 8) data.push(bits.slice(start, start + 8).reduce((value, bit) => value * 2 + bit, 0));+ while (data.length < 136) data.push(data.length % 2 === Math.ceil(bits.length / 8) % 2 ? 0xec : 0x11);+ const blocks = [data.slice(0, 68), data.slice(68)];+ const checks = blocks.map(parity);+ const codewords = [];+ for (let index = 0; index < 68; index++) for (const block of blocks) codewords.push(block[index]);+ for (let index = 0; index < 18; index++) for (const check of checks) codewords.push(check[index]);+ const size = 41;+ const matrix = Array.from({ length: size }, () => Array(size).fill(null));+ /** Mark one reserved module, clipping finder separators at the outer edges. */+ const set = (x, y, dark) => { if (x >= 0 && y >= 0 && x < size && y < size) matrix[y][x] = Boolean(dark); };+ for (let index = 0; index < size; index++) { set(6, index, index % 2 === 0); set(index, 6, index % 2 === 0); }+ for (const [x, y] of [[3, 3], [37, 3], [3, 37]]) {+ for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {+ const distance = Math.max(Math.abs(dx), Math.abs(dy));+ set(x + dx, y + dy, distance !== 2 && distance !== 4);+ }+ }+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(34 + dx, 34 + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);+ let remainder = 8; // L error correction (01), mask 0 (000).+ for (let index = 0; index < 10; index++) remainder = (remainder << 1) ^ ((remainder >>> 9) * 0x537);+ const format = ((8 << 10) | remainder) ^ 0x5412;+ /** Read a format bit in its least-significant-first placement order. */+ const formatBit = (index) => (format >>> index) & 1;+ for (let index = 0; index < 6; index++) set(8, index, formatBit(index));+ set(8, 7, formatBit(6)); set(8, 8, formatBit(7)); set(7, 8, formatBit(8));+ for (let index = 9; index < 15; index++) set(14 - index, 8, formatBit(index));+ for (let index = 0; index < 8; index++) set(size - 1 - index, 8, formatBit(index));+ for (let index = 8; index < 15; index++) set(8, size - 15 + index, formatBit(index));+ set(8, size - 8, true);+ let cursor = 0;+ for (let right = size - 1; right >= 1; right -= 2) {+ if (right === 6) right = 5;+ for (let vertical = 0; vertical < size; vertical++) {+ const y = ((right + 1) & 2) === 0 ? size - 1 - vertical : vertical;+ for (let offset = 0; offset < 2; offset++) {+ const x = right - offset;+ if (matrix[y][x] !== null) continue;+ const bit = cursor < codewords.length * 8 ? (codewords[cursor >>> 3] >>> (7 - (cursor & 7))) & 1 : 0;+ matrix[y][x] = Boolean(bit ^ ((x + y) % 2 === 0));+ cursor++;+ }+ }+ }+ return matrix;+}++/** Print square modules with a four-module white quiet zone, two rows per terminal character. */+export function terminalQr(text) {+ const modules = qrModules(text);+ /** A module outside the symbol is part of its scanner-visible white quiet zone. */+ const dark = (x, y) => Boolean(modules[y]?.[x]);+ const lines = [];+ for (let y = -4; y < 45; y += 2) {+ let line = '';+ for (let x = -4; x < 45; x++) line += [' ', '▀', '▄', '█'][Number(dark(x, y)) + 2 * Number(dark(x, y + 1))];+ lines.push('\x1b[30;47m' + line + '\x1b[0m');+ }+ return lines.join('\n');+}diff --git a/src/relay-key.js b/src/relay-key.jsnew file mode 100644index 00000000..b32ed80c--- /dev/null+++ b/src/relay-key.js@@ -0,0 +1,99 @@+/** Device-only board keys, kept outside repositories and relay requests [H1,H15,H17]. */+import { spawnSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { decodeBoardKey, encodeBoardKey } from './seal.js';+import { Refused } from './refused.js';++/** Validate a persistent board identity before using it as a file or credential name. */+function identity(boardId) {+ if (typeof boardId !== 'string' || !/^[0-9a-f]{32}$/.test(boardId)) throw new Refused('BAD_BOARD', 'use this board\'s persistent identifier');+ return boardId;+}++/** Locate the private fallback without putting a board key in a repository. */+function keyFile(boardId) {+ return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'relay-keys', identity(boardId) + '.key');+}++/** Probe an available operating-system credential service without requiring a particular shell. */+function keychain() {+ if (process.platform === 'darwin') {+ const probe = spawnSync('security', ['list-keychains'], { encoding: 'utf8', timeout: 5000 });+ if (probe.status === 0) return 'security';+ } else if (process.platform === 'linux') {+ const probe = spawnSync('secret-tool', ['search', 'application', 'pullboard-probe'], { encoding: 'utf8', timeout: 5000 });+ if (!probe.error && [0, 1].includes(probe.status) && !probe.stderr) return 'secret-tool';+ }+ return null;+}++/** Save a generated key in the keychain, or atomically in an owner-only fallback file. */+export function storeBoardKey(boardId, key) {+ const id = identity(boardId);+ const encoded = encodeBoardKey(key);+ const service = keychain();+ if (service) {+ // security's interactive mode receives the key through a pipe, never process arguments.+ const saved = spawnSync(service, service === 'security' ? ['-i']+ : ['store', '--label=Pullboard board key', 'application', 'pullboard', 'board', id], {+ encoding: 'utf8', timeout: 10000,+ input: service === 'security' ? `add-generic-password -U -a ${id} -s pullboard.board-key -w ${encoded}\n` : encoded,+ });+ if (saved.status !== 0) throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay on again');+ // Interactive security may exit successfully after a failed command; check the stored value.+ if (service === 'security') {+ const found = spawnSync(service, ['find-generic-password', '-a', id, '-s', 'pullboard.board-key', '-w'], { encoding: 'utf8', timeout: 10000 });+ if (found.status !== 0 || found.stdout.trim() !== encoded) throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay on again');+ }+ return 'keychain';+ }+ const file = keyFile(id);+ const directory = join(file, '..');+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ const parent = lstatSync(directory);+ if (!parent.isDirectory() || parent.isSymbolicLink() || (parent.mode & 0o077)) throw new Refused('RELAY_KEY_STORAGE', 'use an owner-only relay-keys directory with mode 700');+ const temporary = file + '.' + randomUUID() + '.tmp';+ try {+ writeFileSync(temporary, encoded + '\n', { mode: 0o600, flag: 'wx' });+ renameSync(temporary, file);+ } finally { rmSync(temporary, { force: true }); }+ return 'file';+}++/** Read a board key only from this device's private file or operating-system keychain. */+export function readBoardKey(boardId) {+ const id = identity(boardId);+ const file = keyFile(id);+ if (existsSync(file)) {+ const stat = lstatSync(file);+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_KEY_STORAGE', 'restore the board key as an owner-only regular file with mode 600');+ return decodeBoardKey(readFileSync(file, 'utf8').trim());+ }+ const service = keychain();+ if (service) {+ const args = service === 'security'+ ? ['find-generic-password', '-a', id, '-s', 'pullboard.board-key', '-w']+ : ['lookup', 'application', 'pullboard', 'board', id];+ const found = spawnSync(service, args, { encoding: 'utf8', timeout: 10000 });+ if (found.status === 0) return decodeBoardKey(found.stdout.trim());+ }+ throw new Refused('RELAY_KEY_MISSING', 'the board key is missing on this device; pair this device again, or run pullboard relay off then relay on to upload a new sealed snapshot');+}++/** Remove the device key after a successful unlink, leaving all local board records untouched. */+export function forgetBoardKey(boardId, storage) {+ const id = identity(boardId);+ const service = keychain();+ if (!service && storage === 'keychain') throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay off again to finish forgetting its key');+ if (service) {+ const removed = spawnSync(service, service === 'security'+ ? ['delete-generic-password', '-a', id, '-s', 'pullboard.board-key']+ : ['clear', 'application', 'pullboard', 'board', id], { encoding: 'utf8', timeout: 10000 });+ const absent = service === 'security' ? removed.status === 44 : removed.status === 1 && !removed.stderr;+ if (removed.status !== 0 && !absent) throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay off again to finish forgetting its key');+ }+ rmSync(keyFile(id), { force: true });+}diff --git a/src/relay.js b/src/relay.jsnew file mode 100644index 00000000..c6f90df7--- /dev/null+++ b/src/relay.js@@ -0,0 +1,291 @@+/** Opt-in, local-first sealed mirroring; relay-first execution is a later stage [H1,H7,P5]. */+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 { repoInfo, tryGit } from './git.js';+import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';+import { encodeBoardKey, generateBoardKey, seal } from './seal.js';+import { terminalQr } from './qr.js';+import { Refused } from './refused.js';++export const DEFAULT_RELAY = 'https://app.pullboard.dev';++/** Require a trusted origin; HTTP exists only for loopback development and test relays. */+function relayOrigin(address) {+ let url;+ try { url = new URL(address); } catch { throw new Refused('RELAY_URL', 'use an HTTPS relay address, such as https://app.pullboard.dev'); }+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) {+ throw new Refused('RELAY_URL', 'use an HTTPS origin without credentials, a path, query or fragment; loopback HTTP is allowed for a local relay');+ }+ return url.origin;+}++/** Resolve the GitHub owner/repository named by the actual origin remote, never a guessed repo. */+export function originRepository(root) {+ const remote = tryGit(root, ['remote', 'get-url', 'origin']);+ if (remote.status !== 0) throw new Refused('RELAY_ORIGIN', 'add a GitHub origin remote before running pullboard relay on');+ let repository;+ const ssh = /^git@github\.com:([^\s?#]+)$/.exec(remote.stdout);+ if (ssh) repository = ssh[1];+ else {+ try {+ const url = new URL(remote.stdout);+ if (url.hostname === 'github.com' && !url.password && !url.search && !url.hash &&+ ((url.protocol === 'https:' && !url.username) || (url.protocol === 'ssh:' && url.username === 'git')) && !url.port) repository = url.pathname.slice(1);+ } catch { /* A local path or another host is not a GitHub repository. */ }+ }+ repository = repository?.replace(/\.git$/, '');+ if (!repository || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || repository.split('/').some((part) => ['.', '..'].includes(part))) {+ throw new Refused('RELAY_ORIGIN', 'origin must name a GitHub owner/repository using HTTPS or git SSH; fix origin and run pullboard relay on');+ }+ return repository;+}++/** Find the shared local link metadata without opening a board or connecting for an unlinked repo. */+function linkFile(root) { return join(repoInfo(root).commonDir, 'pullboard', 'relay.json'); }++/** Validate private link metadata before trusting its destination or acknowledgement cursor. */+function loadLink(file) {+ if (!existsSync(file)) return null;+ const stat = lstatSync(file);+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_STORAGE', 'restore relay.json as an owner-only regular file with mode 600');+ let state;+ try { state = JSON.parse(readFileSync(file, 'utf8')); } catch { throw new Refused('RELAY_STORAGE', 'restore valid relay link metadata before syncing this board'); }+ if (!state || typeof state !== 'object' || state.version !== 1 || !/^[0-9a-f]{32}$/.test(state.board) || !/^ps_[A-Za-z0-9_-]{43}$/.test(state.token) ||+ !Number.isSafeInteger(state.sequence) || state.sequence < 0 || !Number.isSafeInteger(state.cursor) || state.cursor < 0) {+ throw new Refused('RELAY_STORAGE', 'restore supported relay link metadata before syncing this board');+ }+ relayOrigin(state.url);+ return state;+}++/** Atomically persist acknowledgements and an exact sealed retry before attempting its send. */+function saveLink(file, state) {+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });+ const temporary = file + '.' + randomUUID() + '.tmp';+ try {+ writeFileSync(temporary, JSON.stringify(state) + '\n', { flag: 'wx', mode: 0o600 });+ renameSync(temporary, file);+ } finally { rmSync(temporary, { force: true }); }+}++/** Wait briefly for another worktree's upload, recovering a lock only when its owner is gone. */+async function locked(file, work) {+ const lock = file + '.lock';+ mkdirSync(dirname(file), { recursive: true });+ const deadline = Date.now() + 15000;+ while (true) {+ try { mkdirSync(lock, { mode: 0o700 }); writeFileSync(join(lock, 'pid'), String(process.pid)); break; }+ catch (error) {+ if (error.code !== 'EEXIST') throw error;+ try {+ const pid = Number(readFileSync(join(lock, 'pid'), 'utf8'));+ if (Number.isInteger(pid) && pid > 0) {+ try { process.kill(pid, 0); } catch (dead) { if (dead.code === 'ESRCH') { rmSync(lock, { recursive: true, force: true }); continue; } }+ }+ } catch {+ try { if (Date.now() - lstatSync(lock).mtimeMs > 30000) { rmSync(lock, { recursive: true, force: true }); continue; } }+ catch (gone) { if (gone.code === 'ENOENT') continue; throw gone; }+ }+ if (Date.now() >= deadline) throw new Refused('RELAY_BUSY', 'another worktree is sending this board; the local move is safe and the next command retries');+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ }+ try { return await work(); } finally { rmSync(lock, { recursive: true, force: true }); }+}++/** Surface retention notices on the very command that receives them, without exposing credentials. */+function notices(document, io) {+ const warnings = [document.warning, document.state?.warning, ...(document.warnings ?? [])].filter(Boolean);+ for (const warning of warnings) if (warning.code === 'BOARD_INACTIVE') {+ io.err(`pullboard: [BOARD_INACTIVE] ${warning.daysLeft} days left before this relay board is deleted; ${warning.next || 'make a board move before the deadline to keep it'}`);+ }+}++/** The sole outbound transport in the CLI: explicit sign-in or a saved, opted-in board link. */+async function request(state, path, { method = 'GET', body } = {}, io) {+ let response;+ try {+ response = await fetch(relayOrigin(state.url) + path, {+ method, redirect: 'error', signal: AbortSignal.timeout(10000),+ headers: { ...(state.token ? { authorization: 'Bearer ' + state.token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ } catch { throw new Refused('RELAY_UNAVAILABLE', 'the relay did not answer; the local board is safe and the next command retries pending sends'); }+ let document;+ try { document = await response.json(); } catch { throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid response; retry with the configured relay address'); }+ notices(document, io);+ if (!response.ok) throw new Refused(document.error?.code || 'RELAY_UNAVAILABLE', (document.error?.code === 'AUTH_REQUIRED' ? 'the relay sign-in expired or was revoked; run pullboard relay on to sign in again without changing the board key' : document.error?.message) || 'the relay refused this send; the next command retries it');+ if (document.version !== 1) throw new Refused('RELAY_VERSION', 'the relay API version is unsupported; upgrade Pullboard before syncing');+ return document;+}++/** Read durable local event rows; their ids are the crash-safe outbox after the saved cursor. */+function localRecords(root, work) {+ const info = repoInfo(root);+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));+ try { return work(board); } finally { store.closeBoard(board); }+}++/** Count unapplied uploads using durable event ids, without counting relay transport metadata. */+function behind(root, state) {+ return localRecords(root, (board) => board.db.prepare('SELECT COUNT(*) AS count FROM event WHERE event_id > ?').get(state.cursor).count);+}++/** Expose pairing information while keeping the human relay credential out of output. */+function summary(root, state) {+ if (!state) return { linked: false, board: '', url: '', link: '', sequence: 0, behind: 0 };+ if (state.unlinking) return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, cleanup: true };+ const key = encodeBoardKey(readBoardKey(state.board));+ return { linked: true, board: state.board, url: state.url,+ link: 'https://app.pullboard.dev/#board=' + state.board + '&key=' + key,+ sequence: state.sequence, behind: behind(root, state) + Number(Boolean(state.snapshot)) };+}++/** Seal a client record at its proposed public sequence, with no board key in its envelope. */+async function sealedRecord(key, value, state, kind, sequence) {+ return Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(value)), { boardId: state.board, kind, sequence })).toString('base64url');+}++/** Catch up in local order, retaining exact ciphertext so a lost response cannot duplicate a move. */+async function flush(root, file, state, io) {+ const key = readBoardKey(state.board);+ const path = '/api/v1/boards/' + state.board;+ if (state.linkPending) {+ await request(state, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository: state.repository } }, io);+ delete state.linkPending;+ saveLink(file, state);+ }+ if (state.snapshot) {+ 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 queued snapshot; retry the configured relay');+ delete state.snapshot;+ saveLink(file, state);+ }+ // Reading on every linked command also delivers the relay's inactivity warning.+ const remote = await request(state, path + '/events?after=' + state.sequence, {}, io);+ const received = remote.events;+ if (!Array.isArray(received) || received.some((event, index) => !event ||+ event.event_id !== (index ? received[index - 1].event_id : state.sequence) + 1 ||+ !['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');+ }+ 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 (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;+ saveLink(file, state);+ const rows = localRecords(root, (board) => store.events(board).filter((event) => event.event_id > state.cursor));+ 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) };+ saveLink(file, state);+ }+ const { sequence, sealed } = state.pending;+ const reply = await request(state, path + '/moves', { method: 'POST', body: { sequence, sealed } }, 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;+ delete state.pending;+ saveLink(file, state);+ }+ return summary(root, state);+}++/** Retry an opted-in board before/after a CLI command; transport failure never undoes a local move. */+export async function syncRelay(root, io) {+ const file = linkFile(root);+ if (!existsSync(file)) return null;+ return locked(file, async () => {+ const state = loadLink(file);+ if (!state) return null;+ if (state.unlinking) { io.err('pullboard: [RELAY_UNLINK_PENDING] the remote board is deleted; run pullboard relay off to finish forgetting this device key'); return summary(root, state); }+ try { return await flush(root, file, state, io); }+ catch (error) {+ if (!(error instanceof Refused)) throw error;+ io.err(`pullboard: ${error.message}; run pullboard status to see pending uploads`);+ return { linked: true, board: state.board, url: state.url, sequence: state.sequence,+ behind: behind(root, state) + Number(Boolean(state.snapshot)) };+ }+ });+}++/** Read the local link and lag without opening a network connection or revealing its relay token. */+export function relayStatus(root) { return summary(root, loadLink(linkFile(root))); }++/** Renew a person session through the relay without changing this device's board key or cursors. */+async function deviceSignIn(url, io) {+ const client = { url };+ const flow = await request(client, '/auth/device/start', { method: 'POST', body: {} }, io);+ io.stderr.write(`Sign in with GitHub: open ${flow.verificationURL} and enter ${flow.userCode}\n`);+ const expires = Date.now() + flow.expiresIn * 1000;+ let signed;+ let wait = flow.interval;+ do {+ await new Promise((resolve) => setTimeout(resolve, Math.max(1, wait) * 1000));+ if (Date.now() >= expires) throw new Refused('OAUTH_EXPIRED', 'GitHub device sign-in expired; run pullboard relay on again');+ signed = await request(client, '/auth/device/poll', { method: 'POST', body: { ticket: flow.ticket } }, io);+ wait = signed.retryAfter ?? flow.interval;+ } while (signed.pending);+ const token = signed.token;+ if (!/^ps_[A-Za-z0-9_-]{43}$/.test(token)) throw new Refused('RELAY_RESPONSE', 'the relay did not issue a person session; sign in again');+ return signed;+}++/** Explicitly sign in through the relay and persist a sealed initial snapshot before uploading it. */+export async function relayOn(root, address, io) {+ const repository = originRepository(root);+ const file = linkFile(root);+ return locked(file, async () => {+ let state = loadLink(file);+ if (state?.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish this device key cleanup with pullboard relay off before linking again');+ const url = relayOrigin(address || state?.url || DEFAULT_RELAY);+ if (state && (state.url !== url || state.repository !== repository)) throw new Refused('RELAY_LINKED', 'this board is linked to another relay or repository; run relay off before changing its link');+ const key = state ? readBoardKey(state.board) : await generateBoardKey();+ const signed = await deviceSignIn(url, io);+ if (!state) {+ const snapshot = localRecords(root, (board) => ({ board: store.boardId(board), document: exportBoard(board) }));+ // 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 };+ 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.+ saveLink(file, state);+ if (state.linkPending) {+ await request(state, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository } }, io);+ delete state.linkPending;+ saveLink(file, state);+ }+ let result;+ try { result = await flush(root, file, state, io); }+ catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}; pending records are queued for the next command`); result = summary(root, state); }+ io.say(terminalQr(result.link));+ return result;+ });+}++/** Remove the remote board and its link before forgetting this device's private key and metadata. */+export async function relayOff(root, io) {+ const file = linkFile(root);+ return locked(file, async () => {+ const state = loadLink(file);+ if (!state) return summary(root, null);+ if (!state.unlinking) {+ await request(state, '/api/v1/boards/' + state.board, { method: 'DELETE' }, io);+ state.unlinking = true;+ saveLink(file, state);+ }+ forgetBoardKey(state.board, state.keyStorage);+ rmSync(file, { force: true });+ return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0 };+ });+}diff --git a/test/api.test.js b/test/api.test.jsindex db01beae..1457f6b2 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -504,6 +504,8 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>assert.equal(humanImport.status, 0, humanImport.stderr || humanImport.stdout);assert.match(humanImport.stdout, /imported version 1 board tables/);+ json(source, source.repo, 'relay');+ json(source, source.repo, 'relay', ['off']);const missing = Object.keys(JSON_SHAPES.commands).filter((key) => !covered.has(key));assert.deepEqual(missing, [], `add real-repo invocations for undocumented coverage gaps: ${missing.join(', ')}`);assert.deepEqual([...coveredRoots].sort(), resultCommands(), 'every actual root/factory command has an invocation');diff --git a/test/boundary.test.js b/test/boundary.test.jsindex 7d5d67b7..7fbc76c3 100644--- a/test/boundary.test.js+++ b/test/boundary.test.js@@ -34,8 +34,8 @@ test('the core names no model, engine or vendor; secret patterns may name the keassert.deepEqual(found, []);});-test('the core opens no outbound connection; the view and API listen on loopback, and the page calls only them [P5, N26, A2]', () => {- const allowed = (file, line) =>+test('only opted-in relay sync opens outbound connections; the view and API stay on loopback [P5, N26, A2]', () => {+ const allowed = (file, line) => file === 'src/relay.js' ||(['src/serve.js', 'src/api.js'].includes(file) && line.trim() === "import { createServer } from 'node:http';") ||(file === 'src/serve.js' && line.trim() === "const reply = await fetch(address.origin + path, { headers: { 'x-pullboard-key': address.searchParams.get('k') } });") ||(file === 'src/cockpit.js' && /^\s*const res = await fetch\(path, /.test(line));diff --git a/test/qr.test.js b/test/qr.test.jsnew file mode 100644index 00000000..cd866969--- /dev/null+++ b/test/qr.test.js@@ -0,0 +1,27 @@+/** Independent QR reference vector for an actual device pairing URL [H1,H17]. */+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { test } from 'node:test';+import { qrModules, terminalQr } from '../src/qr.js';++// Reference: Project Nayuki byte-mode, version 6, LOW, mask 0, no ECC boost.+// https://github.com/nayuki/QR-Code-generator/blob/master/python/qrcodegen.py+// Reference source SHA256: 9f4ed1dd201dcb92b1bc0d6e14f46c754bcff0ce48580c5d7e8ace8f6926c8ef+// Only this independent vector is needed at runtime; no external generator or image service.+test('a pairing QR matches the independent complete symbol and prints its quiet zone [H1,H17]', () => {+ const link = 'https://app.pullboard.dev/#board=' + 'a'.repeat(32) + '&key=' + 'b'.repeat(43);+ const modules = qrModules(link);+ const bits = modules.flat().map(Number).join('');+ assert.equal(createHash('sha256').update(bits).digest('hex'), '70689b83f53e6813762b77ad38f85359a99ce51b6b290173ef520335fa86fb37');+ const lines = terminalQr(link).replace(/\x1b\[[0-9;]+m/g, '').split('\n');+ assert.equal(lines.length, 25);+ assert.ok(lines.every((line) => line.length === 49 && line.startsWith(' ') && line.endsWith(' ')));+ assert.ok(lines.slice(0, 2).every((line) => /^ +$/.test(line)));+ assert.ok(/^ +$/.test(lines.at(-1)));+ const decoded = lines.flatMap((line) => [+ [...line].map((cell) => ['▀', '█'].includes(cell)),+ [...line].map((cell) => ['▄', '█'].includes(cell)),+ ]).slice(4, 45).map((row) => row.slice(4, 45));+ assert.deepEqual(decoded, modules, 'half-block rendering preserves every module');+ assert.throws(() => qrModules('x'.repeat(135)), { code: 'PAIR_LINK_LONG' });+});diff --git a/test/relay-client.test.js b/test/relay-client.test.jsnew file mode 100644index 00000000..0b0e009f--- /dev/null+++ b/test/relay-client.test.js@@ -0,0 +1,262 @@+/** Real device-flow CLI mirroring through the opaque relay [H1,H7,H15]. */+import assert from 'node:assert/strict';+import { spawn, spawnSync } from 'node:child_process';+import { createServer } from 'node:http';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync } from 'node:fs';+import { delimiter, join, resolve } from 'node:path';+import { tmpdir } from 'node:os';+import { test } from 'node:test';+import { DatabaseSync } from 'node:sqlite';+import { createAuthHandler } from '../relay/auth-http.js';+import { createRelayAuth } from '../relay/auth.js';+import { createRelayHandler } from '../relay/service.js';+import { createGitHubClient } from '../relay/github.js';+import { decodeBoardKey, encodeBoardKey, unseal } from '../src/seal.js';+import { githubFixture } from './relay-fixture.js';++const SIGN_INS = new Map();++/** Run the actual CLI asynchronously so this process can continue serving its HTTP requests. */+function cli(root, env, ...args) {+ return new Promise((resolveResult, reject) => {+ const child = spawn(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args, '--json'], {+ cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stdout = '';+ let stderr = '';+ const timer = setTimeout(() => child.kill('SIGKILL'), 25_000);+ child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });+ let signInStarted = false;+ child.stderr.setEncoding('utf8').on('data', (part) => {+ stderr += part;+ if (!signInStarted && stderr.includes('enter TEST-ONLY') && SIGN_INS.has(root)) {+ signInStarted = true;+ Promise.resolve(SIGN_INS.get(root)()).catch(() => child.kill('SIGKILL'));+ }+ });+ child.once('error', (error) => { clearTimeout(timer); reject(error); });+ child.once('close', (code, signal) => {+ clearTimeout(timer);+ if (signal) return reject(new Error(`pullboard ${args.join(' ')} was killed by ${signal}: ${stderr}`));+ if (code !== 0) return reject(new Error(`pullboard ${args.join(' ')} exited ${code}: ${stderr}\n${stdout}`));+ try { resolveResult(JSON.parse(stdout)); }+ catch { reject(new Error(`pullboard ${args.join(' ')} did not print JSON: ${stdout}\n${stderr}`)); }+ });+ });+}++/** Read local events directly so inspection itself cannot drain the durable retry queue. */+function localEvents(file) {+ const db = new DatabaseSync(file, { readOnly: true });+ try { return JSON.parse(JSON.stringify(db.prepare('SELECT * FROM event ORDER BY event_id').all())); }+ finally { db.close(); }+}++/** Run the real auth and opaque board handlers together on a private loopback port. */+async function relayServer(t, directory, auth) {+ let signIn;+ let api;+ let refuseMoves = false;+ let loseReply = false;+ let now = Date.now();+ const calls = [];+ const server = createServer(async (req, res) => {+ calls.push({ method: req.method, path: req.url });+ if (loseReply && req.method === 'POST' && /\/moves$/.test(req.url)) {+ loseReply = false;+ res.end = () => { res.destroy(); return res; };+ }+ if (refuseMoves && req.method === 'POST' && /\/api\/v1\/boards\/[^/]+\/moves$/.test(req.url)) {+ for await (const _chunk of req) { /* consume sealed bytes without logging them */ }+ res.writeHead(503, { 'content-type': 'application/json' }).end('{"version":1,"error":{"code":"TEMPORARY","message":"retry","next":"retry"}}');+ return;+ }+ if (await signIn(req, res)) return;+ await api(req, res);+ });+ server.listen(0, '127.0.0.1');+ await new Promise((ready, reject) => {+ server.once('listening', ready);+ server.once('error', reject);+ });+ const origin = `http://127.0.0.1:${server.address().port}`;+ signIn = createAuthHandler({ auth, publicOrigin: origin });+ api = createRelayHandler({ directory, auth, publicOrigin: origin, pollMs: 10, maintenanceMs: 0, now: () => now });+ t.after(async () => {+ api.close();+ server.closeAllConnections();+ await new Promise((ready) => server.close(ready));+ });+ return { origin, calls, failMoves(value) { refuseMoves = value; }, dropNextReply() { loseReply = true; }, advance(days) { now = Date.now() + days * 86400000; } };+}++test('[H1,H7,H15] relay on snapshots and mirrors ciphertext, retries local moves in order, and off preserves the board', async (t) => {+ const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-client-')));+ const root = join(scratch, 'repo');+ const home = join(scratch, 'home');+ const pullboardHome = join(home, '.pullboard');+ const privateBin = join(scratch, 'path');+ const relayDirectory = join(scratch, 'relay');+ mkdirSync(root); mkdirSync(home, { mode: 0o700 }); mkdirSync(privateBin, { mode: 0o700 });+ chmodSync(home, 0o700); chmodSync(privateBin, 0o700);+ const gitBinary = process.env.PATH.split(delimiter).map((entry) => join(entry, 'git')).find(existsSync);+ assert.ok(gitBinary, 'the fixture PATH contains git');+ symlinkSync(realpathSync(gitBinary), join(privateBin, 'git'));+ symlinkSync(realpathSync(process.execPath), join(privateBin, 'node'));+ const env = {+ ...process.env,+ HOME: home,+ PULLBOARD_HOME: pullboardHome,+ PATH: privateBin,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Relay Test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Relay Test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const provider = await githubFixture(t);+ let signIns = 0;+ SIGN_INS.set(root, async () => {+ signIns++;+ assert.equal((await fetch(provider.origin + '/login/device')).status, 200);+ });+ t.after(() => SIGN_INS.delete(root));+ const auth = createRelayAuth({ database: join(scratch, 'auth.sqlite'), github: createGitHubClient(provider.config) });+ t.after(() => { auth.close(); });+ const relay = await relayServer(t, relayDirectory, auth);+ t.after(() => { rmSync(scratch, { recursive: true, force: true }); });+ const flow = auth.beginWeb();+ const authorization = await fetch(flow.authorizationURL, { redirect: 'manual' });+ const callback = new URL(authorization.headers.get('location'));+ const person = await auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), flow.binding);++ const git = spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: root, env, encoding: 'utf8' });+ assert.equal(git.status, 0, git.stderr);+ await cli(root, env, 'init');+ const config = JSON.parse(readFileSync(join(root, 'pullboard.json'), 'utf8'));+ const originRemote = spawnSync('git', ['remote', 'add', 'origin', '[email protected]:fixture/repository.git'], { cwd: root, env, encoding: 'utf8' });+ assert.equal(originRemote.status, 0, originRemote.stderr);+ const marker = 'RELAY_CLIENT_KNOWN_PRIVATE_CRITERION';+ const lane = Object.keys(config.lanes)[0];+ await cli(root, env, 'add', lane, 'initial private item', '--criterion', marker);+ const boardFile = join(root, '.git', 'pullboard', 'board.sqlite');+ const beforeLink = await cli(root, env, 'export');+ const boardId = beforeLink.tables.board_meta.find((row) => row.meta_key === 'board_id').meta_value;++ const relayEnv = env;+ assert.deepEqual(relay.calls, [], 'unlinked commands open no relay connection');+ const keysDirectory = join(pullboardHome, 'relay-keys');+ mkdirSync(keysDirectory, { recursive: true, mode: 0o755 });+ await assert.rejects(cli(root, relayEnv, 'relay', 'on', '--url', relay.origin), /RELAY_KEY_STORAGE/);+ assert.deepEqual(await auth.boardsFor(person.token), [], 'a failed device key save creates no remote link');+ assert.ok(!relay.calls.some((call) => call.path === '/auth/boards/link'));+ chmodSync(keysDirectory, 0o700);+ const on = await cli(root, relayEnv, 'relay', 'on', '--url', relay.origin);+ assert.deepEqual(await auth.boardsFor(person.token), [{ id: boardId, repository: 'fixture/repository' }]);+ assert.equal(on.version, 1);+ assert.equal(on.linked, true);+ assert.equal(on.board, boardId);+ assert.match(on.link, /^https:\/\/app\.pullboard\.dev\/#board=/);+ assert.match(on.link, /(?:^|&)key=[A-Za-z0-9_-]{43}(?:&|$)/);+ assert.equal(on.url, relay.origin);+ const keyFile = join(pullboardHome, 'relay-keys', `${boardId}.key`);+ assert.equal(statSync(keyFile).mode & 0o777, 0o600);+ const keyText = readFileSync(keyFile, 'utf8').trim();+ const key = decodeBoardKey(keyText);+ const fragment = new URL(on.link).hash.slice(1);+ assert.equal(new URLSearchParams(fragment).get('board'), boardId);+ assert.equal(new URLSearchParams(fragment).get('key'), keyText, 'the phone link carries this board key only after #');++ /** Fetch a public sealed document and authenticate it locally with the device-only key. */+ async function get(path) {+ const response = await fetch(relay.origin + path, { headers: { authorization: `Bearer ${person.token}` } });+ return { status: response.status, body: await response.json() };+ }+ const remoteState = await get(`/api/v1/boards/${boardId}/state`);+ assert.equal(remoteState.status, 200);+ 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');++ await cli(root, relayEnv, 'add', lane, 'mirrored private move');+ await cli(root, relayEnv, 'shout', 'person', 'mirrored private shout');+ const firstMoves = localEvents(boardFile).slice(beforeLink.tables.event.length);+ assert.deepEqual(firstMoves.map((row) => row.event_kind), ['add', 'shout']);+ let remoteEvents = await get(`/api/v1/boards/${boardId}/events?after=0`);+ assert.deepEqual(remoteEvents.body.events.map((event) => event.event_id), [1, 2]);+ for (const [index, event] of remoteEvents.body.events.entries()) {+ assert.equal(event.kind, 'move');+ 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] });+ }++ const linkFile = join(root, '.git', 'pullboard', 'relay.json');+ const oldLink = JSON.parse(readFileSync(linkFile, 'utf8'));+ await auth.revoke(person.token, oldLink.tokenId);+ const expired = await cli(root, relayEnv, 'status');+ assert.match((expired.diagnostics ?? []).join('\n'), /sign-in expired or was revoked.*relay on/);+ const renewed = await cli(root, relayEnv, 'relay', 'on');+ assert.equal(renewed.link, on.link, 'renewing sign-in preserves the device pairing key');+ assert.equal(renewed.sequence, 2, 'renewing sign-in preserves the relay cursor');+ assert.equal((await get(`/api/v1/boards/${boardId}/state`)).body.state.sealed, remoteState.body.state.sealed,+ 'renewing sign-in does not replace the original snapshot');+ assert.ok(signIns >= 3, 'JSON mode exposes each device code before waiting for sign-in');++ relay.failMoves(true);+ await cli(root, relayEnv, 'add', lane, 'queued private move');+ await cli(root, relayEnv, 'shout', 'person', 'second queued private move');+ const allNewRows = localEvents(boardFile).slice(beforeLink.tables.event.length);+ assert.deepEqual(allNewRows.map((row) => row.event_kind), ['add', 'shout', 'add', 'shout']);+ const behind = await cli(root, relayEnv, 'status');+ assert.equal(behind.relay.behind, 2, 'the local command succeeds and status reports its durable failed upload');+ relay.failMoves(false);+ const caughtUp = await cli(root, relayEnv, 'status');+ assert.equal(caughtUp.relay.behind, 0, 'the next successful command drains the queue');+ remoteEvents = await get(`/api/v1/boards/${boardId}/events?after=0`);+ assert.deepEqual(remoteEvents.body.events.map((event) => event.event_id), [1, 2, 3, 4]);+ for (const [offset, queued] of remoteEvents.body.events.slice(2).entries()) {+ const sequence = offset + 3;+ assert.equal(queued.kind, 'move');+ 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');+ }+ relay.dropNextReply();+ await cli(root, relayEnv, 'add', lane, 'committed reply lost');+ const recovered = await cli(root, relayEnv, 'status');+ assert.equal(recovered.relay.behind, 0);+ assert.equal(recovered.relay.sequence, 5);+ remoteEvents = await get(`/api/v1/boards/${boardId}/events?after=0`);+ assert.deepEqual(remoteEvents.body.events.map((event) => event.event_id), [1, 2, 3, 4, 5], 'a committed send with a lost reply is acknowledged without duplication');+ relay.advance(80);+ const warned = await cli(root, relayEnv, 'status');+ assert.match((warned.diagnostics ?? []).join('\n'), /BOARD_INACTIVE.*10 days left.*Make a board move/i, 'the next linked command shows the real relay retention notice and repair');+ relay.advance(0);++ const stored = Buffer.concat(readdirSync(relayDirectory).map((name) => readFileSync(join(relayDirectory, name))));+ for (const secret of [marker, 'initial private item', 'mirrored private move', 'mirrored private shout', 'queued private move', 'second queued private move', 'committed reply lost', root]) {+ assert.equal(stored.includes(Buffer.from(secret)), false, `relay journal does not contain known plaintext ${secret}`);+ }+ assert.equal(stored.includes(key), false, 'relay journal does not contain raw key bytes');+ assert.equal(stored.includes(Buffer.from(encodeBoardKey(key))), false, 'relay journal does not contain the encoded key');++ const localBeforeOff = await cli(root, relayEnv, 'export');+ const off = await cli(root, relayEnv, 'relay', 'off');+ assert.equal(off.linked, false);+ assert.deepEqual(await cli(root, env, 'export'), localBeforeOff, 'unlink leaves local rows and counters unchanged');+ assert.deepEqual(await auth.boardsFor(person.token), [], 'unlink removes the repository link');+ const session = await fetch(relay.origin + '/auth/session', { headers: { authorization: `Bearer ${person.token}` } });+ assert.equal(session.status, 200, 'unlink preserves the person session');+ assert.equal((await get(`/api/v1/boards/${boardId}/state`)).status, 404);+ assert.equal(readdirSync(relayDirectory).some((name) => name.startsWith(boardId + '.journal.sqlite')), false,+ 'off removes the relay journal and SQLite sidecars');+ const afterOffCalls = relay.calls.length;+ await cli(root, env, 'status');+ assert.equal(relay.calls.length, afterOffCalls, 'unlinked commands stop connecting immediately');+ assert.equal(existsSync(keyFile), false, 'successful off removes this device copy of the board key');+});diff --git a/test/relay-key.test.js b/test/relay-key.test.jsnew file mode 100644index 00000000..aed20958--- /dev/null+++ b/test/relay-key.test.js@@ -0,0 +1,89 @@+/**+ * Private device key persistence and refusals [H1,H15,H17].+ */+import assert from 'node:assert/strict';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { generateBoardKey, seal, unseal } from '../src/seal.js';+import { forgetBoardKey, readBoardKey, storeBoardKey } from '../src/relay-key.js';++/**+ * Give one test a private home and a PATH with no keychain executable, forcing the documented file fallback.+ * @param {import('node:test').TestContext} t+ * @returns {{ home: string, pullboardHome: string, keyDirectory: string }}+ */+function privateFallback(t) {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-relay-key-'));+ const home = join(root, 'home');+ const pullboardHome = join(home, '.pullboard');+ const noCommands = join(root, 'empty-bin');+ mkdirSync(home, { mode: 0o700 });+ mkdirSync(noCommands, { mode: 0o700 });+ chmodSync(home, 0o700);+ chmodSync(noCommands, 0o700);+ const prior = Object.fromEntries(['HOME', 'PULLBOARD_HOME', 'PATH'].map((name) => [name, process.env[name]]));+ process.env.HOME = home;+ process.env.PULLBOARD_HOME = pullboardHome;+ process.env.PATH = noCommands;+ t.after(() => {+ for (const [name, value] of Object.entries(prior)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ rmSync(root, { recursive: true, force: true });+ });+ return { home, pullboardHome, keyDirectory: join(pullboardHome, 'relay-keys') };+}++test('file fallback stores a generated board key privately and reads it independently of keyRef [H1,H15,H17]', async (t) => {+ const box = privateFallback(t);+ const boardId = 'a'.repeat(32);+ const raw = await generateBoardKey();+ assert.equal(raw.byteLength, 32);++ const keyRef = await storeBoardKey(boardId, raw);+ assert.equal(typeof keyRef, 'string', 'store returns a descriptive reference, not a required read handle');+ assert.deepEqual(await readBoardKey(boardId), raw, 'the board id retrieves the same 256-bit key');++ const directory = statSync(box.keyDirectory);+ const keyFile = join(box.keyDirectory, `${boardId}.key`);+ const file = statSync(keyFile);+ assert.equal(directory.mode & 0o777, 0o700, 'the fallback key directory is private to its owner');+ assert.equal(file.mode & 0o777, 0o600, 'the fallback key file is readable and writable only by its owner');+ assert.ok(file.isFile());+ assert.ok(readFileSync(keyFile).length > 0, 'a durable local key representation was written');++ const binding = { boardId, kind: 'snapshot', sequence: 0 };+ const plaintext = new TextEncoder().encode('sealed board snapshot');+ const ciphertext = await seal(raw, plaintext, binding);+ assert.deepEqual(await unseal(await readBoardKey(boardId), ciphertext, binding), plaintext,+ 'the stored key opens a real RFC 0004 sealed record');+ await assert.rejects(unseal(await generateBoardKey(), ciphertext, binding), { code: 'SEAL_AUTH_FAILED' },+ 'a different device key cannot open this board record');+});++test('fallback refuses missing or wrong board identities, invalid/corrupt keys, and forget removes only that key [H1,H15,H17]', async (t) => {+ const box = privateFallback(t);+ const boardId = 'b'.repeat(32);+ const otherBoardId = 'c'.repeat(32);+ const raw = await generateBoardKey();+ assert.throws(() => readBoardKey(boardId), { code: 'RELAY_KEY_MISSING' });+ assert.throws(() => storeBoardKey('../outside', raw), { code: 'BAD_BOARD' },+ 'a board id cannot escape the private key directory');+ assert.throws(() => storeBoardKey(boardId, raw.slice(1)), { code: 'SEAL_KEY' },+ 'the fallback accepts only a full generated 32-byte key');++ await storeBoardKey(boardId, raw);+ assert.throws(() => readBoardKey(otherBoardId), { code: 'RELAY_KEY_MISSING' },+ 'a key stored for one persistent board id is not returned for another');+ const corrupt = join(box.keyDirectory, `${boardId}.key`);+ writeFileSync(corrupt, Buffer.from('corrupt non-key data'), { mode: 0o600 });+ assert.throws(() => readBoardKey(boardId), { code: 'SEAL_KEY' },+ 'corrupt persisted key material is refused');++ await forgetBoardKey(boardId);+ assert.equal(existsSync(corrupt), false, 'forget removes the local key file');+ assert.throws(() => readBoardKey(boardId), { code: 'RELAY_KEY_MISSING' });+});