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(link): deliver sealed state through board consent [E32,H17]
Corey Olsonadce6255d794
diff --git a/relay/board-link-inbox.js b/relay/board-link-inbox.jsnew file mode 100644index 00000000..1cdc9091--- /dev/null+++ b/relay/board-link-inbox.js@@ -0,0 +1,74 @@+/** Cross-board envelopes live beside existing opaque board records, under the same retention [E32,H16,H17]. */+import { DatabaseSync } from 'node:sqlite';+import { Refused } from '../src/refused.js';+import { boardLinkEnvelope } from '../src/board-link-envelope.js';+import { boardLinkEnvelopeDigest } from '../src/board-link-envelope.js';++/** Check optional additive storage without creating tables on an incoming-page read. */+function installed(db) {+ return Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='board_link_delivery'").get());+}++/** Open a journal only inside the service's already-authorized lifecycle boundary. */+function withDatabase(file, write, work) {+ const db = new DatabaseSync(file, { readOnly: !write });+ try {+ db.exec('PRAGMA busy_timeout=30000');+ if (!write) return work(db);+ db.exec('BEGIN IMMEDIATE');+ try {+ db.exec(`CREATE TABLE IF NOT EXISTS board_link_delivery (+ delivery_id INTEGER PRIMARY KEY AUTOINCREMENT, source_board TEXT NOT NULL,+ correlation TEXT NOT NULL, link_id TEXT NOT NULL, generation INTEGER NOT NULL,+ position INTEGER NOT NULL, digest TEXT NOT NULL, envelope TEXT NOT NULL, receipt TEXT NOT NULL,+ UNIQUE(source_board,correlation))`);+ db.exec('CREATE INDEX IF NOT EXISTS board_link_delivery_position ON board_link_delivery(source_board,link_id,generation,position DESC)');+ const result = work(db);+ db.exec('COMMIT');+ return result;+ } catch (error) {+ try { db.exec('ROLLBACK'); } catch { /* Preserve the original failure if SQLite already ended the transaction. */ }+ throw error;+ }+ } finally { db.close(); }+}++/** Commit a new correlation once; reject changed retries and backward source positions. */+export function appendBoardLinkEnvelope(file, value, { now, store }) {+ const envelope = boardLinkEnvelope(value);+ const encoded = JSON.stringify(envelope);+ const digest = boardLinkEnvelopeDigest(envelope);+ return withDatabase(file, true, db => {+ const existing = db.prepare('SELECT digest,receipt FROM board_link_delivery WHERE source_board=? AND correlation=?')+ .get(envelope.sourceBoardId, envelope.correlationId);+ if (existing) {+ if (existing.digest !== digest) throw new Refused('BOARD_LINK_CONFLICT', 'retry the exact sealed bytes or choose a new delivery correlation ID');+ return JSON.parse(existing.receipt);+ }+ const latest = db.prepare('SELECT position FROM board_link_delivery WHERE source_board=? AND link_id=? AND generation=? ORDER BY position DESC LIMIT 1')+ .get(envelope.sourceBoardId, envelope.linkId, envelope.generation);+ if (latest && latest.position >= envelope.position) throw new Refused('BOARD_LINK_REPLAY', 'send the next source position rather than replaying old state');+ const inserted = db.prepare('INSERT INTO board_link_delivery(source_board,correlation,link_id,generation,position,digest,envelope,receipt) VALUES (?,?,?,?,?,?,?,?)')+ .run(envelope.sourceBoardId, envelope.correlationId, envelope.linkId, envelope.generation, envelope.position, digest, encoded, '{}');+ const receipt = { version: 1, deliveryId: Number(inserted.lastInsertRowid), sourceBoardId: envelope.sourceBoardId,+ destinationBoardId: envelope.destinationBoardId, linkId: envelope.linkId, generation: envelope.generation,+ correlationId: envelope.correlationId, position: envelope.position, digest, at: new Date(now()).toISOString() };+ const saved = JSON.stringify(receipt);+ // The insertion remains uncommitted: quota's separate read sees the old total, and a refusal+ // rolls back the entire envelope. Its independent warning notice retains existing behavior.+ return store(Buffer.byteLength(encoded) + Buffer.byteLength(saved), () => {+ db.prepare('UPDATE board_link_delivery SET receipt=? WHERE delivery_id=?').run(saved, receipt.deliveryId);+ return receipt;+ });+ });+}++/** Read a bounded page without DDL or unrelated private board contents. */+export function readBoardLinkEnvelopes(file, after) {+ if (!Number.isSafeInteger(after) || after < 0) throw new Refused('BOARD_LINK_TRANSPORT', 'use the last nonnegative incoming delivery ID');+ return withDatabase(file, false, db => {+ if (!installed(db)) return [];+ return db.prepare('SELECT envelope,receipt FROM board_link_delivery WHERE delivery_id>? ORDER BY delivery_id LIMIT 100')+ .all(after).map(row => ({ envelope: JSON.parse(row.envelope), receipt: JSON.parse(row.receipt) }));+ });+}diff --git a/relay/board-links.js b/relay/board-links.jsnew file mode 100644index 00000000..6bccbf24--- /dev/null+++ b/relay/board-links.js@@ -0,0 +1,110 @@+/** Authenticated cross-board dispatch shares existing relay credentials and opaque storage [E32,H16,H17]. */+import { closeSync } from 'node:fs';+import { lstatSync } from 'node:fs';+import { openSync } from 'node:fs';+import { join } from 'node:path';+import { Refused } from '../src/refused.js';+import { apiJson } from '../src/api-http.js';+import { readApiBody } from '../src/api-http.js';+import { openBoard } from '../src/board.js';+import { closeBoard } from '../src/board.js';+import { atomic } from '../src/board-event-log.js';+import { readBoardLinks } from '../src/board-link.js';+import { verifyBoardLink } from '../src/board-link.js';+import { commitVerifiedBoardLink } from '../src/board-link.js';+import { boardReferenceId } from '../src/board-reference.js';+import { boardLinkName } from '../src/board-link-format.js';+import { boardLinkEnvelope } from '../src/board-link-envelope.js';+import { appendBoardLinkEnvelope } from './board-link-inbox.js';+import { readBoardLinkEnvelopes } from './board-link-inbox.js';++/** Create one private authoritative DAG catalog without deriving any paths from message fields. */+function catalogBoard(directory, now) {+ const file = join(directory, 'board-links.sqlite');+ try { closeSync(openSync(file, 'wx', 0o600)); } catch (error) { if (error.code !== 'EEXIST') throw error; }+ const stat = lstatSync(file);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.mode & 0o077) throw new Refused('RELAY_STORAGE', 'keep the board-link catalog in a private regular database');+ return openBoard(file, { now: () => new Date(now()) }, { writeContext: { command: 'relay board-link catalog', seat: 'relay' } });+}++/** Refuse stale, reversed or revoked delivery before it reaches a recipient's opaque inbox. */+function currentLink(catalog, envelope) {+ const record = readBoardLinks(catalog).find(row => row.linkId === envelope.linkId);+ if (!record || record.revocation || record.generation !== envelope.generation+ || record.child.boardId !== envelope.sourceBoardId || record.parent.boardId !== envelope.destinationBoardId) {+ throw new Refused('BOARD_LINK_INACTIVE', 'use the current consenting child-to-parent link generation');+ }+ return record;+}++/**+ * Attach only the common link boundary. Existing authorization owns credentials, origins, engine+ * floors and expiry; existing journal lifecycle, backups, retention and quota own opaque payloads.+ */+export function createRelayBoardLinks({ directory, authority, authorize, auth, withJournal, store, now }) {+ const catalog = catalogBoard(directory, now);+ let closed = false;+ /** Stop an awaited authority/provider result from using a catalog closed during shutdown. */+ function open() { if (closed) throw new Refused('RELAY_CLOSED', 'open the relay link dispatcher before using it'); }+ return {+ /** Handle only narrow bilateral-consent and incoming-envelope endpoints. */+ async handle(req, res, url) {+ const link = /^\/api\/v1\/boards\/([^/]+)\/links(?:\/([^/]+))?$/u.exec(url.pathname);+ const deliveries = /^\/api\/v1\/boards\/([^/]+)\/link-deliveries$/u.exec(url.pathname);+ if (!link && !deliveries) return false;+ open();+ const id = boardReferenceId((link ?? deliveries)[1]);+ if (link && req.method === 'PUT' && link[2]) {+ const body = await readApiBody(req);+ if (Object.keys(body).join(',') !== 'record') throw new Refused('BOARD_LINK_FORMAT', 'send exactly one signed link record');+ const record = await verifyBoardLink(body.record, authority);+ if (record.linkId !== boardLinkName(link[2]) || ![record.parent.boardId, record.child.boardId].includes(id)) {+ throw new Refused('BOARD_LINK_AUTH', 'publish consent through one of its exact endpoint boards');+ }+ await authorize(req, id, true); // Last awaited operation before committing under lifecycle locks.+ open();+ const result = auth.withBoard(id, () => commitVerifiedBoardLink(catalog, record));+ apiJson(res, 200, { link: result });+ return true;+ }+ if (link && req.method === 'GET' && !link[2]) {+ await authorize(req, id);+ open();+ const records = readBoardLinks(catalog).filter(row => [row.parent.boardId, row.child.boardId].includes(id));+ apiJson(res, 200, { links: records });+ return true;+ }+ if (deliveries && req.method === 'POST') {+ const envelope = boardLinkEnvelope(await readApiBody(req));+ if (envelope.destinationBoardId !== id) throw new Refused('BOARD_LINK_AUTH', 'send the envelope to its exact receiving board');+ const record = currentLink(catalog, envelope);+ await verifyBoardLink(record, authority);+ // Authenticate the claimed SOURCE with the existing board-bound credential. A destination+ // path or another board's token cannot assert that identity. No provider await holds SQLite.+ const who = await authorize(req, envelope.sourceBoardId, true);+ open();+ const receipt = auth.withBoard(id, () => atomic(catalog, () => {+ if (JSON.stringify(currentLink(catalog, envelope)) !== JSON.stringify(record)) {+ throw new Refused('BOARD_LINK_CONFLICT', 'retry after consent changed during authorization');+ }+ return withJournal(id, () => appendBoardLinkEnvelope(join(directory, id + '.journal.sqlite'), envelope,+ { now, store: (delta, write) => store(id, { userId: who.user.id }, delta, write) }), false, who.engineVersion);+ }));+ apiJson(res, 200, { receipt });+ return true;+ }+ if (deliveries && req.method === 'GET') {+ const raw = url.searchParams.get('after') ?? '0';+ if (!/^(0|[1-9][0-9]*)$/u.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Refused('BOARD_LINK_TRANSPORT', 'use a nonnegative incoming delivery cursor');+ const who = await authorize(req, id);+ open();+ const rows = withJournal(id, () => readBoardLinkEnvelopes(join(directory, id + '.journal.sqlite'), Number(raw)), false, who.engineVersion);+ apiJson(res, 200, { deliveries: rows });+ return true;+ }+ throw new Refused('BOARD_LINK_TRANSPORT', 'use PUT for consent, POST for sealed delivery, and GET for this board’s incoming page');+ },+ /** Close exactly the catalog connection owned by this dispatcher. */+ close() { if (!closed) { closed = true; closeBoard(catalog); } },+ };+}diff --git a/relay/service.js b/relay/service.jsindex 631fd1e2..c3dc7a2f 100644--- a/relay/service.js+++ b/relay/service.js@@ -17,6 +17,7 @@ import { SEALED_SNAPSHOT_BYTES, SNAPSHOT_BODY_BYTES } from '../src/relay-limits.import { createRelayPagesHandler, snapshotPageRoot } from './pages-http.js';import { createStorageQuota } from './storage-quota.js';import { createUploadStatusHandler } from './upload-status.js';+import { createRelayBoardLinks } from './board-links.js';const SNAPSHOT_BODY = SNAPSHOT_BODY_BYTES;const STORED_BYTES = SEALED_SNAPSHOT_BYTES;@@ -120,7 +121,7 @@ function sender(who, personOnly = false) {}/** Create a private relay handler; the caller owns sign-in lifecycle and service shutdown. */-export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin, now = Date.now, backupsDirectory, maintenanceMs = 60_000, accountStorageBytes }) {+export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin, now = Date.now, backupsDirectory, maintenanceMs = 60_000, accountStorageBytes, boardLinkAuthority }) {const origin = trustedOrigin(publicOrigin);if (typeof directory !== 'string' || !directory.trim() || !auth) throw new Refused('RELAY_CONFIG', 'configure a private relay directory and sign-in component');const root = resolve(directory);@@ -342,6 +343,14 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin}, { pollMs });const uploadStatus = createUploadStatusHandler({ authorize: authorizedRequest, withJournal, sender });+ let boardLinks = null;+ try {+ if (boardLinkAuthority) boardLinks = createRelayBoardLinks({ directory: root, authority: boardLinkAuthority,+ authorize: authorizedRequest, auth, withJournal, store: storing, now });+ } catch (error) {+ clearInterval(timer); common.close(); releaseSessionGuard?.(); deviceStore.close(); quota?.close();+ throw error;+ }/** Add authenticated snapshot replacement and deletion to the common versioned read/move paths. */async function handle(req, res) {@@ -353,6 +362,10 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginlet url;try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); }catch { throw new Refused('BAD_REQUEST', 'use a valid path under /api/v1/boards'); }+ if (/^\/api\/v1\/boards\/[^/]+\/(links(?:\/[^/]+)?|link-deliveries)$/u.test(url.pathname)) {+ if (!boardLinks) throw new Refused('BOARD_LINK_AUTH', 'configure the trusted board signer-authority port before linking boards');+ if (await boardLinks.handle(req, res, url)) return;+ }if (await uploadStatus(req, res, url)) return;const approvers = /^\/api\/v1\/boards\/([^/]+)\/approvers$/.exec(url.pathname);if (approvers && req.method === 'GET') {@@ -423,13 +436,13 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginhandle.maintenance = maintain;handle.backup = retention.backup;handle.maintenanceStatus = () => ({ error: maintenanceError });- handle.close = () => { clearInterval(timer); common.close(); releaseSessionGuard?.(); deviceStore.close(); quota?.close(); };+ handle.close = () => { clearInterval(timer); common.close(); releaseSessionGuard?.(); deviceStore.close(); quota?.close(); boardLinks?.close(); };return handle;}/** Start the opt-in service on a configured address; tests use loopback and an ephemeral port. */-export function serveRelay({ directory, auth, port = 0, host = '127.0.0.1', pollMs = 200, publicOrigin, now, backupsDirectory, maintenanceMs, accountStorageBytes }) {- const handler = createRelayHandler({ directory, auth, pollMs, publicOrigin, now, backupsDirectory, maintenanceMs, accountStorageBytes });+export function serveRelay({ directory, auth, port = 0, host = '127.0.0.1', pollMs = 200, publicOrigin, now, backupsDirectory, maintenanceMs, accountStorageBytes, boardLinkAuthority }) {+ const handler = createRelayHandler({ directory, auth, pollMs, publicOrigin, now, backupsDirectory, maintenanceMs, accountStorageBytes, boardLinkAuthority });const server = createServer(handler);server.requestTimeout = 15_000;return new Promise((ready, fail) => {diff --git a/relay/storage-quota.js b/relay/storage-quota.jsindex 8b1ecf8b..38177291 100644--- a/relay/storage-quota.js+++ b/relay/storage-quota.js@@ -19,6 +19,7 @@ function storedBytes(file) {if (tables.has(name)) bytes += db.prepare(`SELECT COALESCE(SUM(length(payload)),0) AS bytes FROM ${name}`).get().bytes;}if (tables.has('page_object')) bytes += db.prepare('SELECT COALESCE(SUM(length(payload)+length(children)),0) AS bytes FROM page_object').get().bytes;+ if (tables.has('board_link_delivery')) bytes += db.prepare('SELECT COALESCE(SUM(length(envelope)+length(receipt)),0) AS bytes FROM board_link_delivery').get().bytes;return bytes;} finally { db.close(); }}diff --git a/src/board-link-envelope.js b/src/board-link-envelope.jsnew file mode 100644index 00000000..2c9c1a34--- /dev/null+++ b/src/board-link-envelope.js@@ -0,0 +1,124 @@+/** A per-link capability reuses existing seals without holding another board's full key [E32,H17]. */+import { createHash } from 'node:crypto';+import { Refused } from './refused.js';+import { seal } from './seal.js';+import { unseal } from './seal.js';+import { boardReferenceId } from './board-reference.js';+import { boardLinkBody } from './board-link-format.js';+import { boardLinkName } from './board-link-format.js';+import { boardLinkFormat } from './board-link-format.js';+import { discloseBoardState } from './board-link-format.js';++const LIMIT = 65536;++/** Copy only bounded routing fields; opaque ciphertext never supplies its own identity. */+export function boardLinkEnvelope(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)+ || Object.keys(value).some(key => !['version', 'linkId', 'generation', 'sourceBoardId', 'destinationBoardId', 'position', 'correlationId', 'sealed'].includes(key))+ || value.version !== 1 || !Number.isSafeInteger(value.generation) || value.generation < 1+ || !Number.isSafeInteger(value.position) || value.position < 0) boardLinkFormat('Use an exact bounded delivery envelope');+ const sourceBoardId = boardReferenceId(value.sourceBoardId);+ const destinationBoardId = boardReferenceId(value.destinationBoardId);+ if (sourceBoardId === destinationBoardId || typeof value.sealed !== 'string' || value.sealed.length > 90000+ || !/^[A-Za-z0-9_-]+$/u.test(value.sealed)) boardLinkFormat('Use a sealed envelope between distinct boards');+ const bytes = Buffer.from(value.sealed, 'base64url');+ if (bytes.length < 29 || bytes.length > LIMIT || bytes.toString('base64url') !== value.sealed) boardLinkFormat('Use canonical bounded sealed bytes');+ return { version: 1, linkId: boardLinkName(value.linkId), generation: value.generation,+ sourceBoardId, destinationBoardId, position: value.position, correlationId: boardLinkName(value.correlationId), sealed: value.sealed };+}++/** Bind a retry to every routing field and the exact already-sealed bytes. */+export function boardLinkEnvelopeDigest(value) {+ return createHash('sha256').update(JSON.stringify(boardLinkEnvelope(value))).digest('hex');+}++/** Accept a server outcome only when it names these exact routing fields and ciphertext bytes. */+export function boardLinkDeliveryReceipt(value, input) {+ const envelope = boardLinkEnvelope(input);+ const fields = ['version', 'deliveryId', 'sourceBoardId', 'destinationBoardId', 'linkId', 'generation', 'correlationId', 'position', 'digest', 'at'];+ if (!value || Object.keys(value).some(key => !fields.includes(key)) || value.version !== 1+ || !Number.isSafeInteger(value.deliveryId) || value.deliveryId < 1 || typeof value.at !== 'string'+ || !Number.isFinite(Date.parse(value.at)) || new Date(value.at).toISOString() !== value.at+ || value.digest !== boardLinkEnvelopeDigest(envelope)) {+ throw new Refused('BOARD_LINK_TRANSPORT', 'read the exact durable receipt for this sealed delivery');+ }+ for (const key of ['sourceBoardId', 'destinationBoardId', 'linkId', 'generation', 'correlationId', 'position']) {+ if (value[key] !== envelope[key]) throw new Refused('BOARD_LINK_TRANSPORT', 'the receipt must match every delivery identity field');+ }+ return Object.fromEntries(fields.map(key => [key, value[key]]));+}++/** Validate decrypted state against the signed mode; unknown fields never become disclosed content. */+function announcement(value, body) {+ if (!value || typeof value !== 'object' || Array.isArray(value)+ || Object.keys(value).some(key => !['version', 'linkId', 'generation', 'sourceBoardId', 'destinationBoardId', 'position', 'disclosure', 'rows'].includes(key))+ || value.version !== 1 || value.linkId !== body.linkId || value.generation !== body.generation+ || value.sourceBoardId !== body.child.boardId || value.destinationBoardId !== body.parent.boardId+ || value.disclosure !== body.disclosure || !Number.isSafeInteger(value.position) || value.position < 0) boardLinkFormat('The announcement does not match its signed link');+ let rows;+ if (body.disclosure === 'counts') {+ if (!value.rows || typeof value.rows !== 'object' || Array.isArray(value.rows)) boardLinkFormat('Use only native state counts');+ rows = {};+ let count = 0;+ for (const [state, amount] of Object.entries(value.rows)) {+ if (!['open', 'claimed', 'submitted', 'verified', 'withdrawn'].includes(state)+ || !Number.isSafeInteger(amount) || amount < 1 || amount > 10000) boardLinkFormat('Use bounded positive native state counts');+ rows[state] = amount; count += amount;+ }+ if (count > 10000) boardLinkFormat('The state-count payload exceeds its bound');+ } else {+ rows = discloseBoardState(body.disclosure, value.rows);+ if (JSON.stringify(rows) !== JSON.stringify(value.rows)+ || rows.some(row => row.board !== body.child.boardId)) boardLinkFormat('The state payload contains forbidden fields or another board’s items');+ }+ return { version: 1, linkId: body.linkId, generation: body.generation,+ sourceBoardId: body.child.boardId, destinationBoardId: body.parent.boardId,+ position: value.position, disclosure: body.disclosure, rows };+}++/**+ * Bind an independently provisioned per-link key to one signed generation. This capability has+ * neither a parent board key nor a key-distribution endpoint; missing capability refuses at use.+ */+export function createBoardLinkCapability(record, key) {+ const body = boardLinkBody(record);+ if (!(key instanceof Uint8Array) || key.length !== 32) throw new Refused('BOARD_LINK_AUTH', 'provide the independently provisioned 32-byte key for this link only');+ const raw = new Uint8Array(key);+ const binding = JSON.stringify(body);+ let closed = false;+ /** Keep the existing seal's authenticated domain unique to these exact endpoints and generation. */+ function context(position) {+ if (closed) throw new Refused('BOARD_LINK_AUTH', 'open a current per-link sealing capability before delivery');+ return { boardId: `board-link:${body.linkId}:${body.child.boardId}:${body.parent.boardId}:${body.generation}`,+ kind: 'request', sequence: position };+ }+ return Object.freeze({ binding,+ /** Seal only already-stripped state; retain these exact bytes for every transport retry. */+ async seal(correlationId, value) {+ const normalized = announcement(value, body);+ const correlation = boardLinkName(correlationId);+ const plain = Buffer.from(JSON.stringify({ version: 1, correlationId: correlation, announcement: normalized }));+ if (plain.length > LIMIT - 29) boardLinkFormat('The disclosed announcement exceeds the envelope bound');+ const bytes = await seal(raw, plain, context(normalized.position));+ return boardLinkEnvelope({ version: 1, linkId: body.linkId, generation: body.generation,+ sourceBoardId: body.child.boardId, destinationBoardId: body.parent.boardId,+ position: normalized.position, correlationId: correlation, sealed: Buffer.from(bytes).toString('base64url') });+ },+ /** Open only this link's envelopes and check every duplicated identity after authentication. */+ async open(value) {+ const envelope = boardLinkEnvelope(value);+ if (envelope.linkId !== body.linkId || envelope.generation !== body.generation+ || envelope.sourceBoardId !== body.child.boardId || envelope.destinationBoardId !== body.parent.boardId) boardLinkFormat('Use this capability only for its bound link generation');+ const plain = await unseal(raw, Buffer.from(envelope.sealed, 'base64url'), context(envelope.position));+ let decoded;+ try { decoded = JSON.parse(Buffer.from(plain).toString('utf8')); } catch { boardLinkFormat('The authenticated link payload is not JSON'); }+ if (!decoded || Object.keys(decoded).sort().join(',') !== 'announcement,correlationId,version'+ || decoded.version !== 1 || decoded.correlationId !== envelope.correlationId) boardLinkFormat('The delivery correlation does not match its authenticated payload');+ const normalized = announcement(decoded.announcement, body);+ if (normalized.position !== envelope.position) boardLinkFormat('The source position changed outside the authenticated payload');+ return normalized;+ },+ /** Drop this instance's key copy without changing any caller-owned key material. */+ close() { raw.fill(0); closed = true; },+ });+}diff --git a/src/board-link-format.js b/src/board-link-format.jsindex 164c9c2e..87e6431a 100644--- a/src/board-link-format.js+++ b/src/board-link-format.js@@ -31,7 +31,8 @@ function proof(value) {if (!value || typeof value !== 'object' || Array.isArray(value)) boardLinkFormat('Use a signed board approval');const allowed = ['version', 'type', 'firstCommit', 'initialHash', 'id', 'file', 'kind', 'source', 'replacement','text', 'decision', 'reason', 'commit', 'by', 'on', 'note', 'signature', 'boardId'];- if (Object.keys(value).some(key => !allowed.includes(key))) boardLinkFormat('The approval has unsupported fields');+ if (Object.keys(value).some(key => !allowed.includes(key))+ || Object.values(value).some(entry => entry !== null && !['string', 'number', 'boolean'].includes(typeof entry))) boardLinkFormat('The approval has unsupported fields');let encoded;try { encoded = JSON.stringify(value); } catch { boardLinkFormat('Use a JSON signature record'); }if (typeof encoded !== 'string' || Buffer.byteLength(encoded) > 20000) boardLinkFormat('The approval exceeds its bound');diff --git a/src/board-link-relay.js b/src/board-link-relay.jsnew file mode 100644index 00000000..c26c945c--- /dev/null+++ b/src/board-link-relay.js@@ -0,0 +1,135 @@+/** One durable cross-board client reuses the authenticated relay and per-link sealing port [E32,H16,H17]. */+import { createHash } from 'node:crypto';+import { Refused } from './refused.js';+import { request } from './relay.js';+import { atomic } from './board-event-log.js';+import { logEvent } from './board-event-log.js';+import { boardId } from './board-query.js';+import { authorizeBoardLink } from './board-link.js';+import { boardStateAnnouncement } from './board-link.js';+import { boardLinkBody } from './board-link-format.js';+import { boardLinkName } from './board-link-format.js';+import { boardReferenceId } from './board-reference.js';+import { boardLinkEnvelope } from './board-link-envelope.js';+import { boardLinkEnvelopeDigest } from './board-link-envelope.js';+import { boardLinkDeliveryReceipt } from './board-link-envelope.js';++/** Read a caller-owned immutable identity cache without exposing mutable stored objects. */+function saved(board, key) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key);+ return row ? JSON.parse(row.meta_value) : null;+}++/** Persist only bounded native JSON metadata inside the caller's transaction. */+function remember(board, key, value) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')+ .run(key, JSON.stringify(value));+}++/** Keep the capability bound to this exact signed generation; a missing port never sends plaintext. */+function capabilityFor(capability, record, method) {+ if (capability?.binding !== JSON.stringify(boardLinkBody(record)) || typeof capability?.[method] !== 'function') {+ throw new Refused('BOARD_LINK_AUTH', 'provide the sealing capability for this exact link generation');+ }+ return capability[method].bind(capability);+}++/** Bind a transport instance to one explicitly authenticated source or receiving board. */+export function createBoardLinkRelayTransport(state) {+ const id = boardReferenceId(state?.board);+ /** Reuse existing credential, engine, origin and deadline behavior without adopting another board's environment token. */+ const sendRequest = (path, options) => request(state, path, options, { ignoreRelayEnvironmentToken: true });+ return Object.freeze({ board: id,+ /** Publish already-signed consent; the server verifies both authorities and its global DAG. */+ async publish(record) {+ return sendRequest(`/api/v1/boards/${id}/links/${boardLinkName(record.linkId)}`, { method: 'PUT', body: { record } });+ },+ /** Post the exact retained sealed bytes; a lost acknowledgement can be retried unchanged. */+ async send(value) {+ const envelope = boardLinkEnvelope(value);+ if (envelope.sourceBoardId !== id) throw new Refused('BOARD_LINK_AUTH', 'use the transport authenticated for the envelope’s source board');+ const result = await sendRequest(`/api/v1/boards/${envelope.destinationBoardId}/link-deliveries`, { method: 'POST', body: envelope });+ return boardLinkDeliveryReceipt(result.receipt, envelope);+ },+ /** Read only this board's bounded incoming page through its own credential. */+ async read(after = 0) {+ if (!Number.isSafeInteger(after) || after < 0) throw new Refused('BOARD_LINK_TRANSPORT', 'use the last nonnegative incoming delivery ID');+ return sendRequest(`/api/v1/boards/${id}/link-deliveries?after=${after}`);+ },+ });+}++/**+ * Strip before sealing and retain one ciphertext per correlation before the first HTTP attempt.+ * Native metadata and queue/ack events commit together; retries cannot reseal into different bytes.+ */+export async function deliverBoardState(board, context, { authority, capability, transport }) {+ if (boardId(board) !== context?.sourceBoardId || transport?.board !== context.sourceBoardId) {+ throw new Refused('BOARD_LINK_AUTH', 'send from the actual source board using its own authenticated transport');+ }+ const record = await authorizeBoardLink(board, context, authority);+ const announcement = boardStateAnnouncement(board, context);+ const text = JSON.stringify(announcement);+ const contentDigest = createHash('sha256').update(text).digest('hex');+ const correlationId = boardLinkName(context.correlationId);+ const key = `board_link_outbox:${context.destinationBoardId}:${correlationId}`;+ let pending = saved(board, key);+ if (pending && pending.contentDigest !== contentDigest) throw new Refused('BOARD_LINK_CONFLICT', 'use a new correlation ID for changed disclosed content');+ if (!pending) {+ const envelope = boardLinkEnvelope(await capabilityFor(capability, record, 'seal')(correlationId, announcement));+ pending = atomic(board, () => {+ if (JSON.stringify(boardStateAnnouncement(board, context)) !== text) throw new Refused('BOARD_LINK_CONFLICT', 'refresh the link after its disclosure changed');+ const existing = saved(board, key);+ if (existing) {+ if (existing.contentDigest !== contentDigest) throw new Refused('BOARD_LINK_CONFLICT', 'use a new correlation ID after a competing send');+ return existing;+ }+ const value = { contentDigest, envelope, receipt: null };+ remember(board, key, value);+ logEvent(board, context.sourceBoardId, 'board_link_send', null, { linkId: record.linkId, correlationId, digest: boardLinkEnvelopeDigest(envelope) });+ return value;+ });+ }+ if (pending.receipt) return boardLinkDeliveryReceipt(pending.receipt, pending.envelope);+ const receipt = boardLinkDeliveryReceipt(await transport.send(pending.envelope), pending.envelope);+ return atomic(board, () => {+ const current = saved(board, key);+ if (!current || current.contentDigest !== contentDigest) throw new Refused('BOARD_LINK_CONFLICT', 'restore the exact queued delivery before recording its acknowledgement');+ if (current.receipt) return boardLinkDeliveryReceipt(current.receipt, current.envelope);+ remember(board, key, { ...current, receipt });+ logEvent(board, context.sourceBoardId, 'board_link_delivered', null, { linkId: record.linkId, correlationId, receipt });+ return receipt;+ });+}++/** Apply a verified incoming state once, with its source-position cursor and durable retry outcome. */+export async function receiveBoardState(board, delivery, { authority, capability }) {+ const envelope = boardLinkEnvelope(delivery?.envelope);+ if (boardId(board) !== envelope.destinationBoardId) throw new Refused('BOARD_LINK_AUTH', 'open this delivery only on its exact receiving board');+ const receipt = boardLinkDeliveryReceipt(delivery.receipt, envelope);+ const record = await authorizeBoardLink(board, envelope, authority);+ const announcement = await capabilityFor(capability, record, 'open')(envelope);+ const key = `board_link_inbox:${envelope.sourceBoardId}:${envelope.correlationId}`;+ const stateKey = `board_link_state:${envelope.linkId}:${envelope.generation}:${envelope.sourceBoardId}`;+ return atomic(board, () => {+ // Decryption and signature verification await: inspect current consent again before effects.+ boardStateAnnouncement(board, { ...envelope, rows: [] });+ const previous = saved(board, key);+ if (previous) {+ if (previous.digest !== receipt.digest) throw new Refused('BOARD_LINK_CONFLICT', 'a received correlation ID cannot name changed ciphertext');+ return previous;+ }+ const latest = saved(board, stateKey);+ if (latest && latest.position >= announcement.position) throw new Refused('BOARD_LINK_REPLAY', 'read the latest source position before applying another announcement');+ remember(board, stateKey, announcement);+ remember(board, key, receipt);+ logEvent(board, envelope.sourceBoardId, 'board_link_state', null, { announcement, receipt });+ return receipt;+ });+}++/** Read the detached latest disclosed state without scanning full board history. */+export function readReceivedBoardState(board, { linkId, generation, sourceBoardId }) {+ if (!Number.isSafeInteger(generation) || generation < 1) throw new Refused('BOARD_LINK_FORMAT', 'use a positive link generation');+ return saved(board, `board_link_state:${boardLinkName(linkId)}:${generation}:${boardReferenceId(sourceBoardId)}`);+}diff --git a/src/board-link.js b/src/board-link.jsindex 9df6d80d..c62754f4 100644--- a/src/board-link.js+++ b/src/board-link.js@@ -13,6 +13,7 @@ export { resolveBoardReference } from './board-reference.js';export { boardItemReference } from './board-reference.js';const PREFIX = 'board_link:';+const VERIFIED_LINKS = new WeakSet();/** Require a genuine authority operation instead of trusting document-supplied keys or flags. */function authorityMethod(authority, method) {@@ -46,6 +47,12 @@ export async function verifyBoardLink(value, authority) {boardLinkSigningText(record, record.revocation.boardId, 'revoke'), record.revocation) !== true) {throw new Refused('BOARD_LINK_AUTH', 'obtain the revoking endpoint’s verified signature');}+ Object.freeze(record.parent); Object.freeze(record.child);+ for (const approval of record.approvals) Object.freeze(approval);+ Object.freeze(record.approvals);+ if (record.revocation) Object.freeze(record.revocation);+ Object.freeze(record);+ VERIFIED_LINKS.add(record);return record;}@@ -95,7 +102,12 @@ function assertAcyclic(records) {* lock; generation, replay and cycle checks then use the catalog under that actual lock.*/export async function applyBoardLink(board, value, authority) {- const record = await verifyBoardLink(value, authority);+ return commitVerifiedBoardLink(board, await verifyBoardLink(value, authority));+}++/** Commit only an immutable object verified in this process, after a caller's final authentication await. */+export function commitVerifiedBoardLink(board, record) {+ if (!VERIFIED_LINKS.has(record)) throw new Refused('BOARD_LINK_AUTH', 'verify both board signatures before committing this link');return atomic(board, () => {const records = readBoardLinks(board);const previous = records.find(row => row.linkId === record.linkId);diff --git a/src/next-step-defaults.js b/src/next-step-defaults.jsindex e75f3dca..8e866947 100644--- a/src/next-step-defaults.js+++ b/src/next-step-defaults.js@@ -1,5 +1,14 @@/** General CLI recovery text; operation-owned codes live in src/moves/ [P4,C7]. */export const DEFAULT_NEXT_STEPS = Object.freeze({+ "BOARD_REFERENCE": "use an immutable board ID or one exact qualified name from the authorized project inventory",+ "BOARD_LINK_FORMAT": "use the exact bounded version 1 board-link, approval, announcement or sealed envelope contract",+ "BOARD_LINK_AUTH": "configure each board’s established signer authority and the per-link sealing capability; never use an unsigned or full-board-key fallback",+ "BOARD_LINK_CONFLICT": "refresh the current link and retain exact retry bytes; use a new generation or correlation ID for changed content",+ "BOARD_LINK_CYCLE": "remove the directed parent-link cycle before obtaining fresh bilateral consent",+ "BOARD_LINK_DISCLOSURE": "send only the consenting child’s states, counts or no entries under its signed disclosure mode",+ "BOARD_LINK_INACTIVE": "use a current non-revoked bilateral link generation for the exact source and receiving boards",+ "BOARD_LINK_TRANSPORT": "read the exact durable delivery receipt or use the last nonnegative incoming cursor through the authenticated relay",+ "BOARD_LINK_REPLAY": "send a newer source position; retry an existing delivery with its original correlation ID and sealed bytes","GIT_SYNC_LOG": "restore the append-only refs/pullboard/board history on origin before running pullboard sync","GIT_SYNC_REMOTE": "restore read/write access to origin, then retry the original command or run pullboard sync; keep its pending sealed move","GIT_SYNC_LOCAL_CHANGED": "run pullboard export to preserve local moves, then ask the coordinator to reconcile the local and remote prefixes before syncing",diff --git a/test/board-link.test.js b/test/board-link.test.jsindex c818eba9..c4c8efc1 100644--- a/test/board-link.test.js+++ b/test/board-link.test.js@@ -11,6 +11,8 @@ import { runFixtureChild, runFixtureGit, fixtureChildMessage } from './fixture-c/** Create an isolated native board with its established SSH signer authority. */function signedBoard(t, name) {const directory = mkdtempSync(join(tmpdir(), 'pullboard-board-link-'));+ let board = null;+ t.after(() => { if (board) store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); });const root = join(directory, 'repo');const key = join(directory, 'signer');mkdirSync(root);@@ -25,8 +27,7 @@ function signedBoard(t, name) {git('add', '.');git('commit', '-q', '-m', 'fixture: establish board signer root');addSigner(root, { by: name, key: key + '.pub' });- const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));- t.after(() => { store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); });+ board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));return { root, key, by: name, board, reference: { boardId: store.boardId(board), organization: 'fixture', handle: name } };}@@ -90,17 +91,23 @@ async function linkRelay(t, boards, authority) {const { request } = await import('../src/relay.js');const { generateBoardKey, seal } = await import('../src/seal.js');const { exportBoard } = await import('../src/exchange.js');+ const { ENGINE_VERSION } = await import('../src/machine.js');const provider = await githubFixture(t);const directory = mkdtempSync(join(tmpdir(), 'pullboard-link-relay-'));let time = Date.now();const auth = createRelayAuth({ database: join(directory, 'auth.sqlite'),github: createGitHubClient(provider.config), now: () => time });+ let service = null;+ t.after(async () => {+ try { if (service) await service.close(); }+ finally { auth.close(); rmSync(directory, { recursive: true, force: true }); }+ });const grant = await auth.beginDevice();provider.state.deviceAuthorized = true;time += grant.interval * 1000;const person = await auth.pollDevice(grant.ticket);for (const box of boards) await auth.linkBoard(person.token, box.reference.boardId, 'fixture/repository');- let service = await serveRelay({ directory: join(directory, 'relay'), auth, maintenanceMs: 0,+ service = await serveRelay({ directory: join(directory, 'relay'), auth, maintenanceMs: 0,now: () => time, boardLinkAuthority: authority });let origin = 'http://127.0.0.1:' + service.port;const states = new Map();@@ -108,12 +115,13 @@ async function linkRelay(t, boards, authority) {const board = box.reference.boardId;const key = await generateBoardKey();const snapshot = await seal(key, Buffer.from(JSON.stringify(exportBoard(box.board))), { boardId: board, kind: 'snapshot', sequence: 0 });- await request({ url: origin, token: person.token, board }, '/api/v1/boards/' + board + '/state',- { method: 'PUT', body: { sequence: 0, sealed: Buffer.from(snapshot).toString('base64url') } }, { ignoreRelayEnvironmentToken: true });+ const uploaded = await fetch(origin + '/api/v1/boards/' + board + '/state', { method: 'PUT',+ headers: { authorization: 'Bearer ' + person.token, 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: 0, sealed: Buffer.from(snapshot).toString('base64url') }) });+ assert.equal(uploaded.status, 200, JSON.stringify(await uploaded.json()));const issued = await auth.issueToken(person.token, { board, agent: 'link-agent' });states.set(board, { url: origin, token: issued.token, board, agent: 'link-agent' });}- t.after(async () => { await service.close(); auth.close(); rmSync(directory, { recursive: true, force: true }); });return { states, request,async restart() {await service.close();diff --git a/test/move-registry-baseline.json b/test/move-registry-baseline.jsonindex 64427929..257539e6 100644--- a/test/move-registry-baseline.json+++ b/test/move-registry-baseline.json@@ -6950,7 +6950,16 @@"WRONG_BOARD": "open the repository registered to this board and confirm its identity with pullboard status","WRONG_LANE": "create a worktree in the required lane with pullboard worktree <lane> --model \"<model name>\", or take an item in your lane with pullboard next","EXCLUDED_REPOSITORY": "restore the GitHub origin of each excluded project, then run pullboard relay on --all",- "EXCLUDED_INVENTORY": "restore at most 256 excluded boards and their active paired devices, then run pullboard relay on --all"+ "EXCLUDED_INVENTORY": "restore at most 256 excluded boards and their active paired devices, then run pullboard relay on --all",+ "BOARD_REFERENCE": "use an immutable board ID or one exact qualified name from the authorized project inventory",+ "BOARD_LINK_FORMAT": "use the exact bounded version 1 board-link, approval, announcement or sealed envelope contract",+ "BOARD_LINK_AUTH": "configure each board\u2019s established signer authority and the per-link sealing capability; never use an unsigned or full-board-key fallback",+ "BOARD_LINK_CONFLICT": "refresh the current link and retain exact retry bytes; use a new generation or correlation ID for changed content",+ "BOARD_LINK_CYCLE": "remove the directed parent-link cycle before obtaining fresh bilateral consent",+ "BOARD_LINK_DISCLOSURE": "send only the consenting child\u2019s states, counts or no entries under its signed disclosure mode",+ "BOARD_LINK_INACTIVE": "use a current non-revoked bilateral link generation for the exact source and receiving boards",+ "BOARD_LINK_TRANSPORT": "read the exact durable delivery receipt or use the last nonnegative incoming cursor through the authenticated relay",+ "BOARD_LINK_REPLAY": "send a newer source position; retry an existing delivery with its original correlation ID and sealed bytes"},"replay": {"initial": {