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): add encrypted pairing packages [H15,H17]
Corey Olson32859e532f46
diff --git a/relay/pairing-http.js b/relay/pairing-http.jsnew file mode 100644index 00000000..48367860--- /dev/null+++ b/relay/pairing-http.js@@ -0,0 +1,47 @@+/** Authenticated, no-store HTTP boundary for one-use client-encrypted pairing envelopes [H15,H17]. */+import { apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js';+import { Refused } from '../src/refused.js';++const PAIR_BODY = 20_000_000;+const ROUTE = /^\/api\/v1\/pairings\/([0-9a-f]{32})\/([A-Za-z0-9_-]{22})(\/consume)?$/;++/** Accept only the small exact body shape; do not let callers attach tokens or board metadata. */+function exactBody(value, fields) {+ if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify([...fields].sort())) {+ throw new Refused('BAD_REQUEST', 'send only the fields required by this pairing action');+ }+ return value;+}++/** Route publishes and consumes only after the adapter confirms the caller can read this board. */+export function createPairingHandler({ authenticate, pairings }) {+ if (typeof authenticate !== 'function' || !pairings || typeof pairings.publish !== 'function' || typeof pairings.consume !== 'function') {+ throw new Refused('PAIR_CONFIG', 'configure relay authentication and a bounded pairing store');+ }++ /** Handle only pairing paths so the normal relay API may serve every other request. */+ return async function handlePairing(req, res) {+ let url;+ try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); }+ catch { return false; }+ const match = ROUTE.exec(url.pathname);+ if (!match) return false;+ try {+ const [, board, locator, consuming] = match;+ if (url.search) throw new Refused('BAD_REQUEST', 'send pairing fields in the request body, not the URL');+ if (req.method !== 'POST') throw new Refused('NO_ENDPOINT', 'use POST to publish or consume a one-time pairing package');+ await authenticate(req, { board, write: false });+ if (consuming) {+ exactBody(await readApiBody(req), []);+ apiJson(res, 200, pairings.consume(board, locator));+ return true;+ }+ const input = exactBody(await readApiBody(req, { maxBytes: PAIR_BODY }), ['sealed']);+ apiJson(res, 201, pairings.publish(board, locator, input.sealed));+ return true;+ } catch (error) {+ apiJson(res, apiStatus(error), apiRefusal(error));+ return true;+ }+ };+}diff --git a/relay/pairing-store.js b/relay/pairing-store.jsnew file mode 100644index 00000000..7ddacb28--- /dev/null+++ b/relay/pairing-store.js@@ -0,0 +1,86 @@+/** Short-lived opaque pairing envelopes; relay storage never receives or derives the code secret [H15,H17]. */+import { Refused } from '../src/refused.js';++const TEN_MINUTES = 10 * 60_000;+const TOMBSTONE_MINUTES = 10 * 60_000;+const MAX_CODES = 10_000;+const MAX_ENVELOPE_BYTES = 19_000_000;+const MAX_STORED_BYTES = 50_000_000;+const LOCATOR = /^[A-Za-z0-9_-]{22}$/;++/** Validate opaque ciphertext transport without parsing or logging its contents. */+function envelope(value) {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value)) {+ throw new Refused('PAIR_PACKAGE', 'send one encrypted pairing package; create a new code on the linked device');+ }+ const bytes = Buffer.from(value, 'base64url');+ if (bytes.length < 28 || bytes.length > MAX_ENVELOPE_BYTES || bytes.toString('base64url') !== value) {+ throw new Refused('PAIR_PACKAGE', 'send one encrypted pairing package; create a new code on the linked device');+ }+ return value;+}++/** Keep codes for ten minutes and retain short-lived tombstones so reuse and expiry are explicit. */+export function createPairingStore({ now = Date.now, ttl = TEN_MINUTES, maxCodes = MAX_CODES, maxBytes = MAX_STORED_BYTES } = {}) {+ if (typeof now !== 'function' || !Number.isSafeInteger(ttl) || ttl !== TEN_MINUTES ||+ !Number.isSafeInteger(maxCodes) || maxCodes < 1 || maxCodes > MAX_CODES ||+ !Number.isSafeInteger(maxBytes) || maxBytes < MAX_ENVELOPE_BYTES || maxBytes > MAX_STORED_BYTES) {+ throw new Refused('PAIR_CONFIG', 'use the fixed ten-minute code lifetime and a bounded positive pairing capacity');+ }+ const records = new Map();+ let storedBytes = 0;++ /** Drop old tombstones before admitting or consuming more short-lived codes. */+ function prune(at) {+ for (const [locator, record] of records) {+ if (record.status === 'ready' && at >= record.expires) {+ record.status = 'expired';+ storedBytes -= record.bytes;+ record.bytes = 0;+ delete record.sealed;+ }+ if (at >= record.expires + TOMBSTONE_MINUTES) records.delete(locator);+ }+ }++ return Object.freeze({+ /** Store one opaque client-encrypted package under a fresh locator, for ten minutes and one use. */+ publish(board, locator, sealed) {+ const at = now();+ prune(at);+ if (typeof board !== 'string' || !/^[0-9a-f]{32}$/.test(board) || typeof locator !== 'string' || !LOCATOR.test(locator)) throw new Refused('PAIR_CODE_INVALID', 'use a fresh random pairing code for this board');+ const value = envelope(sealed);+ if (records.has(locator)) throw new Refused('PAIR_EXISTS', 'generate a fresh one-time code on the linked device');+ const bytes = Buffer.byteLength(value, 'base64url');+ if (records.size >= maxCodes || storedBytes + bytes > maxBytes) throw new Refused('PAIR_BUSY', 'retry pairing shortly after another code expires');+ records.set(locator, { board, sealed: value, bytes, expires: at + ttl, status: 'ready' });+ storedBytes += bytes;+ return { expiresIn: ttl / 1000 };+ },+ /** Atomically consume an opaque package once; callers authenticate repository access first. */+ consume(board, locator) {+ const at = now();+ prune(at);+ if (typeof board !== 'string' || !/^[0-9a-f]{32}$/.test(board) || typeof locator !== 'string' || !LOCATOR.test(locator)) throw new Refused('PAIR_CODE_INVALID', 'use the full one-time code from the linked device');+ const record = records.get(locator);+ if (!record) throw new Refused('PAIR_CODE_UNKNOWN', 'the one-time code was not found; ask the linked device for a new code');+ if (record.board !== board) throw new Refused('PAIR_CODE_INVALID', 'the one-time code belongs to another board; use the full printed code');+ if (at >= record.expires) {+ record.status = 'expired';+ storedBytes -= record.bytes;+ record.bytes = 0;+ delete record.sealed;+ throw new Refused('PAIR_CODE_EXPIRED', 'the ten-minute pairing code expired; ask the linked device for a new code');+ }+ if (record.status === 'used') throw new Refused('PAIR_CODE_USED', 'the one-time pairing code was already used; ask the linked device for a new code');+ record.status = 'used';+ storedBytes -= record.bytes;+ record.bytes = 0;+ const sealed = record.sealed;+ delete record.sealed;+ return { sealed };+ },+ /** Report only a count for capacity checks and tests; never return board ids or ciphertext. */+ size() { prune(now()); return records.size; },+ });+}diff --git a/relay/service.js b/relay/service.jsindex a0afcf95..e112d5de 100644--- a/relay/service.js+++ b/relay/service.js@@ -6,6 +6,8 @@ import { createApiHandler, apiJson, apiRefusal, apiStatus, readApiBody } from '.import { Refused } from '../src/refused.js';import { createRelayJournal } from './journal.js';import { createRelayRetention } from './retention.js';+import { createPairingStore } from './pairing-store.js';+import { createPairingHandler } from './pairing-http.js';const SNAPSHOT_BODY = 14_000_000;const STORED_BYTES = 10_000_000;@@ -98,6 +100,12 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginreturn who;}+ const pairingStore = createPairingStore({ now });+ const pairing = createPairingHandler({+ authenticate: (req, { board, write }) => authorized(credential(req, origin, write), board, write),+ pairings: pairingStore,+ });+/** Add an authorized next-contact warning without exposing any plaintext board contents. */function annotated(row, id) {const warning = retention.notice(id);@@ -162,6 +170,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin/** Add authenticated snapshot replacement and deletion to the common versioned read/move paths. */async function handle(req, res) {+ if (await pairing(req, res)) return;try {let url;try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); }diff --git a/src/pairing.js b/src/pairing.jsnew file mode 100644index 00000000..cc93aacd--- /dev/null+++ b/src/pairing.js@@ -0,0 +1,91 @@+/** Client-side one-time pairing envelope; the relay sees only locator-bound ciphertext [H15,H17]. */+import { randomBytes, webcrypto } from 'node:crypto';+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', '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) ||+ !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');+ }+ 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 --git a/test/pairing.test.js b/test/pairing.test.jsnew file mode 100644index 00000000..d821797f--- /dev/null+++ b/test/pairing.test.js@@ -0,0 +1,216 @@+/** One-time pairing keeps its secret off the relay and rejects replay or expiry [H15,H17]. */+import assert from 'node:assert/strict';+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 { 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';++const BOARD = '0123456789abcdef0123456789abcdef';++/** 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',+ sequence: 9, cursor: 14, key: 'A'.repeat(43), snapshot: { version: 1, tables: { board_meta: [] } },+ ...overrides,+ };+}++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 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' });+});++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: {} } }),+ ]) {+ await assert.rejects(sealPairingBundle(code, invalid), { code: 'PAIR_PACKAGE' });+ }+ const oversized = bundle({ snapshot: { version: 1, tables: { 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] 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');+});