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
chore(merge): integrate relay pairing [H17,H15]
Corey Olson5b10fc386604
diff --cc src/cli.jsindex 9d3bfd18,117b45b6..793ace21--- a/src/cli.js+++ b/src/cli.js@@@ -60,7 -53,8 +60,8 @@@ import { mainPolicy, itemPolicy, submisimport { 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';+import { relayLinked, relayOff, relayOn, relayOperation, relayStatus, syncRelay } from './relay.js';+ import { relayJoin, relayPair } from './relay-pairing-client.js';const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));export const VERSION = PACKAGE.version;diff --cc src/pairing.jsindex 00000000,1a811a9c..ccb57d3cmode 000000,100644..100644--- a/src/pairing.js+++ b/src/pairing.js@@@ -1,0 -1,108 +1,109 @@@+ /** Client-side one-time pairing envelope; the relay sees only locator-bound ciphertext [H15,H17]. */+ import { randomBytes, webcrypto } from 'node:crypto';++import { ENGINE_VERSION } from './machine.js';+ import { Refused } from './refused.js';++ const LOCATOR = /^[A-Za-z0-9_-]{22}$/;+ const SECRET = /^[A-Za-z0-9_-]{43}$/;+ const KEY = /^[A-Za-z0-9_-]{43}$/;+ const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;+ const MAX_PACKAGE_BYTES = 14_000_000;++ /** Refuse noncanonical unpadded base64url instead of accepting aliases for a pairing secret. */+ function decode(encoded, bytes, code, next) {+ if (typeof encoded !== 'string' || !/^[A-Za-z0-9_-]+$/.test(encoded)) throw new Refused(code, next);+ const value = Buffer.from(encoded, 'base64url');+ if ((bytes !== undefined && value.length !== bytes) || value.toString('base64url') !== encoded) throw new Refused(code, next);+ return new Uint8Array(value);+ }++ /** Generate a random locator and independent 256-bit secret; only the locator is sent to the relay. */+ export function createPairingCode(board) {+ if (typeof board !== 'string' || !/^[0-9a-f]{32}$/.test(board)) throw new Refused('BAD_BOARD', 'use this board’s persistent identifier before creating a pairing code');+ const locator = randomBytes(16).toString('base64url');+ const secret = randomBytes(32).toString('base64url');+ return { board, locator, secret, code: board + '.' + locator + '.' + secret };+ }++ /** Parse a human pairing code without including any supplied part in a refusal. */+ export function parsePairingCode(code) {+ if (typeof code !== 'string') throw new Refused('PAIR_CODE_INVALID', 'use the full one-time code printed by the linked device');+ const parts = code.split('.');+ if (parts.length !== 3 || !/^[0-9a-f]{32}$/.test(parts[0]) || !LOCATOR.test(parts[1]) || !SECRET.test(parts[2])) {+ throw new Refused('PAIR_CODE_INVALID', 'use the full one-time code printed by the linked device');+ }+ return { board: parts[0], locator: parts[1], secret: decode(parts[2], 32, 'PAIR_CODE_INVALID', 'use the full one-time code printed by the linked device') };+ }++ /** Validate a native v1 board snapshot and pairing metadata before sealing or installing it. */+ function validateBundle(value) {+ const fields = ['version', 'board', 'url', 'repository', 'mode', 'sequence', 'cursor', 'key', 'snapshot'];+ if (!value || typeof value !== 'object' || Array.isArray(value) ||+ JSON.stringify(Object.keys(value).sort()) !== JSON.stringify([...fields].sort()) || value.version !== 1 ||+ typeof value.board !== 'string' || !/^[0-9a-f]{32}$/.test(value.board) ||+ typeof value.url !== 'string' || typeof value.repository !== 'string' || !REPOSITORY.test(value.repository) ||+ !['mirror', 'ordered'].includes(value.mode) ||+ !Number.isSafeInteger(value.sequence) || value.sequence < 0 || !Number.isSafeInteger(value.cursor) || value.cursor < 0 ||+ typeof value.key !== 'string' || !KEY.test(value.key) ||+ !value.snapshot || typeof value.snapshot !== 'object' || Array.isArray(value.snapshot) ||+ value.snapshot.version !== 1 || !value.snapshot.tables || typeof value.snapshot.tables !== 'object' || Array.isArray(value.snapshot.tables)) {+ throw new Refused('PAIR_PACKAGE', 'the encrypted pairing package is not a supported board link; create a new code on the linked device');+ }+ const metadata = value.snapshot.tables.board_meta;+ const events = value.snapshot.tables.event;+ if (!Array.isArray(metadata) || !Array.isArray(events) ||+ metadata.filter((row) => row?.meta_key === 'board_id').length !== 1 ||+ metadata.find((row) => row?.meta_key === 'board_id')?.meta_value !== value.board ||+ !Number.isSafeInteger(events.at(-1)?.event_id ?? 0) || (events.at(-1)?.event_id ?? 0) !== value.cursor) {+ throw new Refused('PAIR_PACKAGE', 'the encrypted pairing snapshot does not match its board identity and local cursor; create a fresh code');+ }+ const meta = new Map(metadata.map((row) => [row?.meta_key, row?.meta_value]));+ const hasApplied = meta.has('relay_applied_sequence');+ const hasEngine = meta.has('relay_engine_version');- if (hasApplied !== hasEngine || (value.mode === 'ordered' && (!hasApplied || meta.get('relay_engine_version') !== '1' ||++ if (hasApplied !== hasEngine || (value.mode === 'ordered' && (!hasApplied || meta.get('relay_engine_version') !== String(ENGINE_VERSION) ||+ !Number.isSafeInteger(Number(meta.get('relay_applied_sequence'))) || String(Number(meta.get('relay_applied_sequence'))) !== meta.get('relay_applied_sequence') ||+ Number(meta.get('relay_applied_sequence')) !== value.sequence)) || (value.mode === 'mirror' && hasApplied)) {+ throw new Refused('PAIR_PACKAGE', 'the encrypted relay checkpoint does not match its ordering mode; create a fresh code after sync');+ }+ let origin;+ try { origin = new URL(value.url); } catch { throw new Refused('PAIR_PACKAGE', 'the encrypted pairing package has an invalid relay origin; create a new code'); }+ if (origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash ||+ (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname)))) {+ throw new Refused('PAIR_PACKAGE', 'the encrypted pairing package has an invalid relay origin; create a new code');+ }+ decode(value.key, 32, 'PAIR_PACKAGE', 'the encrypted pairing package has an invalid board key; create a new code');+ return value;+ }++ /** Bind a native local export and board key to the one-time code before upload to the relay. */+ export async function sealPairingBundle(code, bundle) {+ const { board, locator, secret } = parsePairingCode(code);+ const value = validateBundle(bundle);+ if (value.board !== board) throw new Refused('PAIR_PACKAGE', 'the pairing code belongs to another board; create a new code on this device');+ const iv = randomBytes(12);+ const key = await webcrypto.subtle.importKey('raw', secret, 'AES-GCM', false, ['encrypt']);+ const aad = new TextEncoder().encode(JSON.stringify(['pullboard-pairing', 1, locator]));+ const plaintext = new TextEncoder().encode(JSON.stringify(value));+ if (plaintext.length > MAX_PACKAGE_BYTES) throw new Refused('PAIR_PACKAGE_SIZE', 'this board export is too large for one-time pairing; use a smaller local board export before trying again');+ const ciphertext = new Uint8Array(await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad, tagLength: 128 }, key, plaintext));+ return Buffer.concat([iv, ciphertext]).toString('base64url');+ }++ /** Authenticate and validate a relayed pairing envelope using only the human-held secret. */+ export async function openPairingBundle(code, sealed) {+ const { board, locator, secret } = parsePairingCode(code);+ const blob = decode(sealed, undefined, 'PAIR_CODE_INVALID', 'the one-time code is invalid or already used; ask the linked device for a new code');+ if (blob.length < 12 + 16) throw new Refused('PAIR_CODE_INVALID', 'the one-time code is invalid or already used; ask the linked device for a new code');+ const key = await webcrypto.subtle.importKey('raw', secret, 'AES-GCM', false, ['decrypt']);+ const aad = new TextEncoder().encode(JSON.stringify(['pullboard-pairing', 1, locator]));+ let plaintext;+ try { plaintext = await webcrypto.subtle.decrypt({ name: 'AES-GCM', iv: blob.slice(0, 12), additionalData: aad, tagLength: 128 }, key, blob.slice(12)); }+ catch { throw new Refused('PAIR_CODE_INVALID', 'the one-time code is invalid or already used; ask the linked device for a new code'); }+ let value;+ if (plaintext.byteLength > MAX_PACKAGE_BYTES) throw new Refused('PAIR_PACKAGE_SIZE', 'the encrypted board export exceeds the pairing limit; ask the linked device for a smaller package');+ try { value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plaintext)); }+ catch { throw new Refused('PAIR_PACKAGE', 'the encrypted pairing package is invalid; ask the linked device for a new code'); }+ const bundle = validateBundle(value);+ if (bundle.board !== board) throw new Refused('PAIR_PACKAGE', 'the encrypted package is for another board; ask for a fresh one-time code');+ return bundle;+ }diff --cc src/relay-pairing-client.jsindex 00000000,40d1cb5b..40d6210amode 000000,100644..100644--- a/src/relay-pairing-client.js+++ b/src/relay-pairing-client.js@@@ -1,0 -1,218 +1,221 @@@+ /** CLI pairing flow: the relay stores only a one-use client-encrypted package [H15,H17]. */+ 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, importBoard } from './exchange.js';+ import { repoInfo } from './git.js';+ import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';+ import { encodeBoardKey } from './seal.js';+ import { createPairingCode, openPairingBundle, parsePairingCode, sealPairingBundle } from './pairing.js';+ import { terminalQr } from './qr.js';+ import { DEFAULT_RELAY, originRepository, relayStatus, syncRelay } from './relay.js';++import { ENGINE_VERSION } from './machine.js';+ import { Refused } from './refused.js';++ const TOKEN = /^ps_[A-Za-z0-9_-]{43}$/;+ const BOARD = /^[0-9a-f]{32}$/;+ const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;++ /** Restrict pairing traffic to a trusted HTTPS origin or a loopback test relay. */+ 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 relay origin without credentials, path, query or fragment; loopback HTTP is for local testing');+ }+ return url.origin;+ }++ /** Locate the private link metadata shared by this repository's worktrees. */+ function linkFile(root) {+ return join(repoInfo(root).commonDir, 'pullboard', 'relay.json');+ }++ /** Load and validate relay state before it supplies a destination or credential. */+ function loadState(file) {+ if (!existsSync(file)) throw new Refused('RELAY_NOT_LINKED', 'link this board with pullboard relay on before pairing a device');+ 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 pairing this board'); }+ if (!state || state.version !== 1 || !BOARD.test(state.board) || !TOKEN.test(state.token) ||+ typeof state.repository !== 'string' || !REPOSITORY.test(state.repository) ||+ (state.mode !== undefined && !['mirror', 'ordered'].includes(state.mode)) ||+ !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 pairing this board');+ }+ relayOrigin(state.url);+ return state;+ }++ /** Persist a joined-device link with owner-only permissions and atomic replacement. */+ function saveState(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 }); }+ }++ /** Send one authenticated, bounded JSON request without including credentials in errors. */+ async function relayRequest(url, token, path, body) {+ let response;+ try {+ response = await fetch(new URL(path, url), {+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),+ headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body: JSON.stringify(body),+ });+ } catch { throw new Refused('RELAY_UNAVAILABLE', 'the relay did not answer; retry pairing with the same code before it expires'); }+ let document;+ try { document = await response.json(); } catch { throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid pairing response; ask for a fresh code'); }+ if (!response.ok) throw new Refused(document.error?.code || 'RELAY_UNAVAILABLE', document.error?.message || 'the relay refused pairing; ask the linked device for a fresh code');+ if (document.version !== 1) throw new Refused('RELAY_VERSION', 'the relay pairing API version is unsupported; upgrade Pullboard before pairing');+ return document;+ }++ /** Sign this device into the relay so its person session can fetch the encrypted package. */+ async function signIn(url, io) {+ const start = await relayRequest(url, '', '/auth/device/start', {});+ io.stderr.write(`Sign in with GitHub: open ${start.verificationURL} and enter ${start.userCode}\n`);+ const deadline = Date.now() + start.expiresIn * 1000;+ let wait = start.interval;+ while (true) {+ await new Promise((resolve) => setTimeout(resolve, Math.max(1, wait) * 1000));+ if (Date.now() >= deadline) throw new Refused('OAUTH_EXPIRED', 'GitHub device sign-in expired; run pullboard relay join again with a fresh code');+ const result = await relayRequest(url, '', '/auth/device/poll', { ticket: start.ticket });+ if (!result.pending) {+ if (!TOKEN.test(result.token)) throw new Refused('RELAY_RESPONSE', 'the relay did not issue a person session; sign in again');+ return result;+ }+ wait = result.retryAfter ?? start.interval;+ }+ }++ /** Return an exported local board with its persistent identity. */+ function localSnapshot(root) {+ const info = repoInfo(root);+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));+ try { return { board: store.boardId(board), snapshot: exportBoard(board) }; }+ finally { store.closeBoard(board); }+ }++ /** Create a one-use code and publish only an encrypted board package to the relay. */+ export async function relayPair(root, io) {+ await syncRelay(root, io);+ const file = linkFile(root);+ const state = loadState(file);+ if (state.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish unlinking this board before creating a pairing code');+ if (originRepository(root) !== state.repository) throw new Refused('RELAY_ORIGIN', 'the origin repository no longer matches this relay link; restore the linked GitHub origin first');+ const local = localSnapshot(root);+ if (local.board !== state.board) throw new Refused('RELAY_STORAGE', 'the local board identity differs from its relay link; restore the matching board before pairing');+ const cursor = local.snapshot.tables.event.at(-1)?.event_id ?? 0;+ if (cursor !== state.cursor) throw new Refused('PAIR_BUSY', 'a local move changed during pairing; run pullboard relay pair again after sync completes');+ if (state.pending || state.pendingMove || state.snapshot || state.linkPending) {+ throw new Refused('PAIR_PENDING', 'finish the pending relay acknowledgement or snapshot before creating a pairing code; retry relay sync first');+ }+ const metadata = new Map(local.snapshot.tables.board_meta.map((row) => [row.meta_key, row.meta_value]));+ const applied = metadata.get('relay_applied_sequence');+ const engine = metadata.get('relay_engine_version');+ const ordered = state.mode === 'ordered' || (applied !== undefined && engine !== undefined);+ let sequence = state.sequence;+ if (ordered) {+ const value = Number(applied);- if (engine !== '1' || !Number.isSafeInteger(value) || value < 0 || String(value) !== applied || value !== state.sequence) {++ if (engine !== String(ENGINE_VERSION) || !Number.isSafeInteger(value) || value < 0 || String(value) !== applied || value !== state.sequence) {+ throw new Refused('PAIR_STATE', 'the ordered relay checkpoint does not match its acknowledged sequence; sync this device before pairing');+ }+ sequence = value;+ }+ const key = readBoardKey(state.board);+ const bundle = {+ version: 1, board: state.board, url: state.url, repository: state.repository,+ mode: ordered ? 'ordered' : 'mirror', sequence, cursor, key: encodeBoardKey(key), snapshot: local.snapshot,+ };+ const code = createPairingCode(state.board);+ const sealed = await sealPairingBundle(code.code, bundle);+ const response = await relayRequest(state.url, state.token,+ `/api/v1/pairings/${code.board}/${code.locator}`, { sealed });+ const viewLink = relayStatus(root).link;+ io.result?.({ code: code.code, link: viewLink, expiresIn: response.expiresIn });+ io.say(`One-time code (10 minutes, one use): ${code.code}`);+ io.say(`Phone link: ${viewLink}`);+ io.say(terminalQr(viewLink));+ return 0;+ }++ /** Refuse a nonempty target board before spending its one-use code. */+ function requireFreshTarget(root) {+ const local = localSnapshot(root);+ const tables = local.snapshot.tables;+ const nonempty = Object.entries(tables).filter(([name, rows]) => !['board_meta', 'agent', 'event', 'sqlite_sequence'].includes(name) && rows.length);+ const meta = tables.board_meta;++ const metadata = new Map(meta.map((row) => [row.meta_key, row.meta_value]));+ const agents = tables.agent;+ const events = tables.event;+ const sequence = tables.sqlite_sequence;+ let initialDetail = false;+ try { initialDetail = JSON.stringify(JSON.parse(events[0]?.event_detail)) === JSON.stringify({ lane: 'coordinator' }); }+ catch { /* A non-init history cannot be safely replaced by a paired snapshot. */ }- if (meta.length !== 1 || meta[0].meta_key !== 'board_id' || !BOARD.test(meta[0].meta_value) ||++ if (meta.length !== 2 || !BOARD.test(metadata.get('board_id') ?? '') ||++ metadata.get('event_log_version') !== String(store.EVENT_LOG_VERSION) ||+ agents.length !== 1 || agents[0].agent_id !== 'coordinator' || agents[0].agent_lane !== 'coordinator' ||+ agents[0].agent_route !== 'strong' || agents[0].agent_last_shout_id !== 0 || !agents[0].agent_path ||+ events.length !== 1 || events[0].event_by !== 'coordinator' || events[0].event_kind !== 'join' ||+ events[0].item_id !== null || !initialDetail || sequence.length !== 1 || sequence[0].name !== 'event' ||+ sequence[0].seq !== 1 || nonempty.length) {+ throw new Refused('IMPORT_NOT_EMPTY', 'pair into a freshly initialized clone with no board work; preserve this board and use another clone');+ }+ }++ /** Refuse to overwrite an unrelated device key under the same persistent board id. */+ function requireMissingKey(board) {+ try {+ readBoardKey(board);+ throw new Refused('RELAY_KEY_EXISTS', 'this clone already has a key for that board; preserve it and use a fresh device home');+ } catch (error) {+ if (error.code !== 'RELAY_KEY_MISSING') throw error;+ }+ }++ /** Consume a printed one-time code, restore the board and save this device's own link. */+ export async function relayJoin(root, code, address, io) {+ const parsed = parsePairingCode(code);+ const url = relayOrigin(address || DEFAULT_RELAY);+ requireFreshTarget(root);+ requireMissingKey(parsed.board);+ const repository = originRepository(root);+ const signed = await signIn(url, io);+ const response = await relayRequest(url, signed.token,+ `/api/v1/pairings/${parsed.board}/${parsed.locator}/consume`, {});+ const bundle = await openPairingBundle(code, response.sealed);+ if (bundle.repository !== repository) throw new Refused('PAIR_REPOSITORY', 'this code belongs to another GitHub repository and was consumed; ask the linked device for a fresh code, then join inside the matching clone');+ if (new URL(bundle.url).origin !== new URL(url).origin) throw new Refused('PAIR_RELAY', 'this code belongs to another relay; rerun join with that relay address');+ const file = linkFile(root);+ if (existsSync(file)) throw new Refused('RELAY_LINKED', 'this clone already has relay link metadata; use a fresh clone to join another device');+ let keyStorage;+ try {+ keyStorage = storeBoardKey(bundle.board, Buffer.from(bundle.key, 'base64url'));+ const info = repoInfo(root);+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));+ try { importBoard(board, bundle.snapshot); }+ finally { store.closeBoard(board); }+ saveState(file, {+ version: 1, board: bundle.board, url: bundle.url, repository: bundle.repository,+ mode: bundle.mode,+ token: signed.token, tokenId: signed.id, keyStorage,+ sequence: bundle.sequence, cursor: bundle.cursor,+ });+ } catch (error) {+ if (keyStorage) {+ try { forgetBoardKey(bundle.board, keyStorage); } catch { /* Keep the original refusal as the useful next step. */ }+ }+ throw error;+ }+ await syncRelay(root, io);+ const result = { linked: true, board: bundle.board, url: bundle.url, sequence: bundle.sequence, behind: 0 };+ io.result?.(result);+ io.say(`paired board ${bundle.board}; run pullboard status to read it`);+ return 0;+ }diff --cc test/pairing.test.jsindex 00000000,36d8e132..2dd18ea9mode 000000,100644..100644--- a/test/pairing.test.js+++ b/test/pairing.test.js@@@ -1,0 -1,329 +1,342 @@@+ /** One-time pairing keeps its secret off the relay and rejects replay or expiry [H15,H17]. */+ import assert from 'node:assert/strict';+ import { randomBytes, webcrypto } from 'node:crypto';+ import { createServer } from 'node:http';+ import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+ import { tmpdir } from 'node:os';+ import { join } from 'node:path';+ import { test } from 'node:test';+ import { createPairingCode, openPairingBundle, parsePairingCode, sealPairingBundle } from '../src/pairing.js';+ import { decodeBoardKey } from '../src/seal.js';++import { ENGINE_VERSION } from '../src/machine.js';+ import { createPairingStore } from '../relay/pairing-store.js';+ import { createPairingHandler } from '../relay/pairing-http.js';+ import { createRelayHandler } from '../relay/service.js';+ import { Refused } from '../src/refused.js';+ import { relayClientFixture } from './relay-client-fixture.js';++ const BOARD = '0123456789abcdef0123456789abcdef';+ const OTHER_BOARD = 'fedcba9876543210fedcba9876543210';++ /** Serve only the pairing adapter on a private loopback port for actual HTTP boundary checks. */+ async function servePairing(t, authorize, pairings = createPairingStore()) {+ const handler = createPairingHandler({ authenticate: authorize, pairings });+ const server = createServer(async (req, res) => {+ if (!(await handler(req, res))) res.writeHead(404).end();+ });+ server.listen(0, '127.0.0.1');+ await new Promise((resolve, reject) => {+ server.once('listening', resolve);+ server.once('error', reject);+ });+ t.after(async () => {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ });+ return 'http://127.0.0.1:' + server.address().port;+ }++ /** Create the exact native-export envelope expected from a linked device. */+ function bundle(overrides = {}) {+ return {+ version: 1, board: BOARD, url: 'https://app.pullboard.dev', repository: 'owner/repository', mode: 'mirror',+ sequence: 9, cursor: 14, key: 'A'.repeat(43), snapshot: { version: 1, tables: {+ board_meta: [{ meta_key: 'board_id', meta_value: BOARD }], event: [{ event_id: 14 }],+ } },+ ...overrides,+ };+ }++ /** Make a valid encrypted package for another board to exercise the receiver's identity guard. */+ async function sealedOtherBoardPackage(code) {+ const { locator, secret } = parsePairingCode(code);+ const value = bundle({ board: OTHER_BOARD, snapshot: { version: 1, tables: {+ board_meta: [{ meta_key: 'board_id', meta_value: OTHER_BOARD }], event: [{ event_id: 14 }],+ } } });+ const key = await webcrypto.subtle.importKey('raw', secret, 'AES-GCM', false, ['encrypt']);+ const iv = randomBytes(12);+ const aad = new TextEncoder().encode(JSON.stringify(['pullboard-pairing', 1, locator]));+ const plaintext = new TextEncoder().encode(JSON.stringify(value));+ const ciphertext = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad, tagLength: 128 }, key, plaintext);+ return Buffer.concat([iv, Buffer.from(ciphertext)]).toString('base64url');+ }++ /** Read relay-owned files only; local device homes intentionally retain their own keys. */+ function relayFiles(directory) {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const path = join(directory, entry.name);+ return entry.isDirectory() ? relayFiles(path) : [readFileSync(path)];+ });+ }++ test('[H15,H17] client seals board key and native snapshot under a one-time code the relay cannot read', async () => {+ const issued = createPairingCode(BOARD);+ assert.match(issued.locator, /^[A-Za-z0-9_-]{22}$/);+ assert.match(issued.secret, /^[A-Za-z0-9_-]{43}$/);+ assert.equal(parsePairingCode(issued.code).locator, issued.locator);+ assert.equal(parsePairingCode(issued.code).board, BOARD);+ const sealed = await sealPairingBundle(issued.code, bundle());+ assert.match(sealed, /^[A-Za-z0-9_-]+$/);+ assert.ok(!sealed.includes(issued.secret), 'the relay envelope does not contain the human-held code secret');+ assert.ok(!sealed.includes(bundle().key), 'the relay envelope does not contain the board key as readable text');+ assert.deepEqual(await openPairingBundle(issued.code, sealed), bundle());++ const ordered = bundle({ mode: 'ordered', sequence: 14, snapshot: { version: 1, tables: {+ board_meta: [+ { meta_key: 'board_id', meta_value: BOARD },+ { meta_key: 'relay_applied_sequence', meta_value: '14' },- { meta_key: 'relay_engine_version', meta_value: '1' },++ { meta_key: 'relay_engine_version', meta_value: String(ENGINE_VERSION) },+ ],+ event: [{ event_id: 14 }],+ } } });+ assert.deepEqual(await openPairingBundle(issued.code, await sealPairingBundle(issued.code, ordered)), ordered,+ 'ordered pairing binds the native checkpoint to the acknowledged relay sequence');++ const futureEngine = bundle({ mode: 'ordered', sequence: 14, snapshot: { version: 1, tables: {++ board_meta: [++ { meta_key: 'board_id', meta_value: BOARD },++ { meta_key: 'relay_applied_sequence', meta_value: '14' },++ { meta_key: 'relay_engine_version', meta_value: String(ENGINE_VERSION + 1) },++ ],++ event: [{ event_id: 14 }],++ } } });++ await assert.rejects(sealPairingBundle(issued.code, futureEngine), { code: 'PAIR_PACKAGE' },++ 'pairing refuses a checkpoint from a future relay engine');++ const tampered = sealed.slice(0, -1) + (sealed.endsWith('A') ? 'B' : 'A');+ await assert.rejects(openPairingBundle(issued.code, tampered), { code: 'PAIR_CODE_INVALID' });+ const wrong = createPairingCode(BOARD);+ await assert.rejects(openPairingBundle(wrong.code, sealed), { code: 'PAIR_CODE_INVALID' });+ const wrongBoardBundle = bundle({ board: OTHER_BOARD, snapshot: { version: 1, tables: {+ board_meta: [{ meta_key: 'board_id', meta_value: OTHER_BOARD }], event: [{ event_id: 14 }],+ } } });+ await assert.rejects(sealPairingBundle(issued.code, wrongBoardBundle), { code: 'PAIR_PACKAGE' },+ 'the linked client will not seal a snapshot for a different board');+ await assert.rejects(openPairingBundle(issued.code, await sealedOtherBoardPackage(issued.code)), { code: 'PAIR_PACKAGE' },+ 'the joining client rejects a valid encrypted package for a different board');+ });++ test('[H15,H17] package validation excludes sender credentials and validates relay and board identity', async () => {+ const { code } = createPairingCode(BOARD);+ for (const invalid of [+ { ...bundle(), token: 'ps_' + 'x'.repeat(43) },+ bundle({ board: '../outside' }),+ bundle({ repository: 'owner' }),+ bundle({ url: 'https://user:[email protected]' }),+ bundle({ sequence: -1 }),+ bundle({ cursor: 1.5 }),+ bundle({ key: 'x'.repeat(42) }),+ bundle({ snapshot: { version: 2, tables: {} } }),+ bundle({ mode: 'ordered' }),+ bundle({ mode: 'ordered', sequence: 14, snapshot: { version: 1, tables: {- board_meta: [{ meta_key: 'board_id', meta_value: BOARD }, { meta_key: 'relay_applied_sequence', meta_value: '14' }, { meta_key: 'relay_engine_version', meta_value: '1' }],++ board_meta: [{ meta_key: 'board_id', meta_value: BOARD }, { meta_key: 'relay_applied_sequence', meta_value: '14' }, { meta_key: 'relay_engine_version', meta_value: String(ENGINE_VERSION) }],+ event: [{ event_id: 13 }],+ } } }),+ ]) {+ await assert.rejects(sealPairingBundle(code, invalid), { code: 'PAIR_PACKAGE' });+ }+ const oversized = bundle({ snapshot: { version: 1, tables: {+ board_meta: [{ meta_key: 'board_id', meta_value: BOARD }], event: [{ event_id: 14 }], marker: [{ value: 'x'.repeat(14_000_000) }],+ } } });+ await assert.rejects(sealPairingBundle(code, oversized), { code: 'PAIR_PACKAGE_SIZE' });+ for (const invalid of ['', 'abc', 'x'.repeat(98), BOARD + '.A'.repeat(22) + '.B'.repeat(43), null]) {+ assert.throws(() => parsePairingCode(invalid), { code: 'PAIR_CODE_INVALID' });+ }+ });++ test('[H15,H17] relay pairing envelopes expire after ten minutes and are consumed exactly once', () => {+ let now = 1_800_000_000_000;+ const store = createPairingStore({ now: () => now, maxCodes: 2 });+ const first = createPairingCode(BOARD);+ const firstEnvelope = 'A'.repeat(60);+ assert.deepEqual(store.publish(BOARD, first.locator, firstEnvelope), { expiresIn: 600 });+ assert.deepEqual(store.consume(BOARD, first.locator), { sealed: firstEnvelope });+ assert.throws(() => store.consume(BOARD, first.locator), { code: 'PAIR_CODE_USED' });+ assert.equal(store.size(), 1, 'the store retains a small tombstone so reuse has a precise refusal');++ const expired = createPairingCode(BOARD);+ store.publish(BOARD, expired.locator, 'B'.repeat(60));+ now += 600_000;+ assert.throws(() => store.consume(BOARD, expired.locator), { code: 'PAIR_CODE_EXPIRED' });+ assert.throws(() => store.consume(BOARD, 'C'.repeat(22)), { code: 'PAIR_CODE_UNKNOWN' });+ now += 600_000;+ assert.equal(store.size(), 0, 'expired and used tombstones are eventually pruned');+ });++ test('[H15,H17] a pairing code cannot be consumed as another board', () => {+ const store = createPairingStore();+ const issued = createPairingCode(BOARD);+ const opaque = 'A'.repeat(60);+ store.publish(BOARD, issued.locator, opaque);++ assert.throws(() => store.consume(OTHER_BOARD, issued.locator), { code: 'PAIR_CODE_INVALID' },+ 'the relay record is bound to the board that published the code');+ assert.deepEqual(store.consume(BOARD, issued.locator), { sealed: opaque },+ 'a mismatched-board attempt does not spend the original code');+ });++ test('[H15,H17] relay refuses malformed, duplicate and over-capacity pairing envelopes', () => {+ const store = createPairingStore({ maxCodes: 1 });+ const first = createPairingCode(BOARD);+ assert.throws(() => store.publish(BOARD, first.locator, 'not base64!'), { code: 'PAIR_PACKAGE' });+ store.publish(BOARD, first.locator, 'A'.repeat(60));+ assert.throws(() => store.publish(BOARD, first.locator, 'A'.repeat(60)), { code: 'PAIR_EXISTS' });+ const second = createPairingCode(BOARD);+ assert.throws(() => store.publish(BOARD, second.locator, 'B'.repeat(60)), { code: 'PAIR_BUSY' });+ assert.throws(() => createPairingStore({ ttl: 1 }), { code: 'PAIR_CONFIG' });+ });++ test('[H15,H17] pairing HTTP authenticates repository access before publishing or consuming', async (t) => {+ let allowed = true;+ const checks = [];+ const origin = await servePairing(t, async (req, { board, write }) => {+ checks.push({ credential: req.headers.authorization, board, write });+ if (!allowed) throw new Refused('NO_REPO_ACCESS', 'ask the repository owner for read access');+ if (req.headers.authorization !== 'Bearer receiver-session') throw new Refused('AUTH_REQUIRED', 'sign in');+ });+ const issued = createPairingCode(BOARD);+ const sealed = await sealPairingBundle(issued.code, bundle());+ const base = origin + '/api/v1/pairings/' + BOARD + '/' + issued.locator;+ const publish = await fetch(base, {+ method: 'POST', headers: { authorization: 'Bearer receiver-session', 'content-type': 'application/json' },+ body: JSON.stringify({ sealed }),+ });+ assert.equal(publish.status, 201);+ assert.equal(publish.headers.get('cache-control'), 'no-store');+ assert.deepEqual(await publish.json(), { version: 1, expiresIn: 600 });++ allowed = false;+ const blocked = await fetch(base + '/consume', {+ method: 'POST', headers: { authorization: 'Bearer receiver-session', 'content-type': 'application/json' }, body: '{}',+ });+ assert.equal(blocked.status, 403);+ assert.equal((await blocked.json()).error.code, 'NO_REPO_ACCESS');+ allowed = true;+ const consumed = await fetch(base + '/consume', {+ method: 'POST', headers: { authorization: 'Bearer receiver-session', 'content-type': 'application/json' }, body: '{}',+ });+ assert.equal(consumed.status, 200);+ const response = await consumed.json();+ assert.equal(response.sealed, sealed);+ assert.ok(!JSON.stringify(response).includes(issued.secret), 'HTTP returns opaque ciphertext only');+ assert.deepEqual(await openPairingBundle(issued.code, response.sealed), bundle(),+ 'the authorized receiver can decrypt the same package after the rejected attempt');+ assert.ok(checks.every((check) => check.board === BOARD && check.write === false));++ const replay = await fetch(base + '/consume', {+ method: 'POST', headers: { authorization: 'Bearer receiver-session', 'content-type': 'application/json' }, body: '{}',+ });+ assert.equal((await replay.json()).error.code, 'PAIR_CODE_USED');+ });++ test('[H15,H17] relay service holds only bounded opaque pairing bytes and preserves its existing board files', async (t) => {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-pair-service-'));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const boardFile = join(root, 'existing.journal.sqlite');+ const marker = Buffer.from('existing relay journal fixture');+ writeFileSync(boardFile, marker, { mode: 0o600 });+ const sourceToken = 'ps_' + 'S'.repeat(43);+ const receiverToken = 'ps_' + 'R'.repeat(43);+ const blockedToken = 'ps_' + 'B'.repeat(43);+ const links = new Map([[BOARD, { id: BOARD, repository: 'owner/repository', linkedAt: Date.now() }]]);+ const auth = {+ async authenticate(token, { board } = {}) {+ if (![sourceToken, receiverToken, blockedToken].includes(token)) throw new Refused('AUTH_REQUIRED', 'sign in');+ if (board && !links.has(board)) throw new Refused('BOARD_NOT_LINKED', 'link the board');+ if (token === blockedToken) throw new Refused('NO_REPO_ACCESS', 'ask the repository owner for read access');+ return { id: token, kind: 'session', user: { id: token, login: 'fixture' } };+ },+ linkedBoards() { return [...links.values()]; },+ withBoard(board, work) {+ const link = links.get(board);+ if (!link) throw new Refused('BOARD_NOT_LINKED', 'link the board');+ return work(link);+ },+ forgetBoard(board) { links.delete(board); },+ pendingCleanup() { return []; },+ finishCleanup() {},+ withCleanup(_board, work) { return work(); },+ };+ const service = createRelayHandler({ directory: root, auth, maintenanceMs: 0 });+ const server = createServer((req, res) => { void service(req, res); });+ server.listen(0, '127.0.0.1');+ await new Promise((resolve, reject) => {+ server.once('listening', resolve);+ server.once('error', reject);+ });+ t.after(async () => {+ service.close();+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ });++ const issued = createPairingCode(BOARD);+ const sealed = await sealPairingBundle(issued.code, bundle());+ const base = 'http://127.0.0.1:' + server.address().port + '/api/v1/pairings/' + BOARD + '/' + issued.locator;+ const published = await fetch(base, {+ method: 'POST', headers: { authorization: 'Bearer ' + sourceToken, 'content-type': 'application/json' },+ body: JSON.stringify({ sealed }),+ });+ assert.equal(published.status, 201);+ const unauthorized = await fetch(base + '/consume', {+ method: 'POST', headers: { authorization: 'Bearer ' + blockedToken, 'content-type': 'application/json' }, body: '{}',+ });+ assert.equal((await unauthorized.json()).error.code, 'NO_REPO_ACCESS');+ const consumed = await fetch(base + '/consume', {+ method: 'POST', headers: { authorization: 'Bearer ' + receiverToken, 'content-type': 'application/json' }, body: '{}',+ });+ const response = await consumed.json();+ assert.equal(consumed.status, 200);+ assert.deepEqual(await openPairingBundle(issued.code, response.sealed), bundle());+ assert.deepEqual(readFileSync(boardFile), marker, 'pairing does not replace or rewrite a journal');+ assert.deepEqual(readdirSync(root).sort(), ['existing.journal.sqlite'], 'pairing bytes stay in bounded memory, not durable relay storage');+ });++ test('[H15,H17] production CLI pairs a real second clone and reads the same board', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();++ const linkedSource = await box.cli('export');++ assert.equal(linkedSource.code, 0, 'the linked source exports its current checkpoint');+ const printed = await box.cli('relay', 'pair');+ assert.equal(printed.code, 0, 'the linked CLI publishes a one-use pairing envelope');+ assert.match(printed.document.code, /^[0-9a-f]{32}\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/);+ assert.equal(printed.document.expiresIn, 600);+ assert.match(printed.document.link, /^https:\/\/app\.pullboard\.dev\/#board=/);+ const paired = await box.otherDeviceJoin(printed.document.code);+ assert.equal(paired.joined.board, box.before.tables.board_meta.find((row) => row.meta_key === 'board_id').meta_value);- assert.deepEqual(paired.exported, box.before, 'the second clone imports the same native rows and counters');++ assert.deepEqual(paired.exported, linkedSource.document, 'the second clone imports the source checkpoint and counters after linking');+ assert.ok(!box.calls.some((call) => call.path.includes(printed.document.code)), 'the code secret never appears in a relay request path');+ });++ test('[H15,H17] a paired clone synchronizes without a key file from PULLBOARD_RELAY_KEY', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ const printed = await box.cli('relay', 'pair');+ const paired = await box.otherDeviceJoin(printed.document.code);+ const beforeSyncCalls = box.calls.length;+ const synchronized = await paired.syncWithEnvironmentKey('export');+ assert.equal(synchronized.code, 0, 'the paired clone reads the relay using its local environment key');+ assert.equal(paired.keyFileExists(), false, 'the synchronization ran with no stored key file');+ assert.ok(box.calls.slice(beforeSyncCalls).some(({ method, path }) => method === 'GET' && /\/events\?after=/.test(path)),+ 'the clone fetched linked relay state with no stored key file');+ assert.deepEqual(synchronized.document, paired.exported, 'sync reads the paired board without changing its native rows');++ const encodedKey = readFileSync(box.keyFile, 'utf8').trim();+ const keyBytes = decodeBoardKey(encodedKey);+ const secretText = printed.document.code.split('.')[2];+ const secretBytes = parsePairingCode(printed.document.code).secret;+ const wireBytes = Buffer.concat(box.transit.flatMap(({ request, response }) => [request, response]));+ const relayDiskBytes = Buffer.concat([...relayFiles(box.relayDirectory), readFileSync(box.authDatabase)]);+ const output = JSON.stringify(synchronized.document);+ for (const [label, value] of [+ ['raw board key bytes', keyBytes],+ ['encoded board key', Buffer.from(encodedKey)],+ ['raw pairing secret bytes', Buffer.from(secretBytes)],+ ['encoded pairing secret', Buffer.from(secretText)],+ ]) {+ assert.equal(wireBytes.includes(value), false, `relay HTTP bodies contain no ${label}`);+ assert.equal(relayDiskBytes.includes(value), false, `relay-owned files contain no ${label}`);+ }+ assert.equal(box.calls.some(({ path }) => path.includes(secretText)), false, 'the pairing secret never appears in a relay URL');+ assert.equal(output.includes(encodedKey), false, 'the environment key is not echoed in the clone command result');+ assert.equal(output.includes(secretText), false, 'the pairing secret is not echoed in the clone command result');+ });