Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(relay): enforce the authenticated replay sender [H2,H16]

Corey Olsonab375e62f5aa
diff --git a/relay/README.md b/relay/README.md
index fde19000..8fbfdf4a 100644
--- a/relay/README.md
+++ b/relay/README.md
@@ -171,9 +171,16 @@ Sender is derived only from the freshly authenticated credential: a board token
gives {kind: 'agent', userId, agent}; a person's session gives {kind: 'person', userId}.
It contains no credential, token id, login or board key. This attribution is saved
with every event and snapshot and returned unchanged through reads and streams.
-An agent's client must compare the unsealed move's agent with sender.agent before
-applying it; a mismatch is an impersonation attempt. The opaque relay cannot do
-that comparison itself. Snapshot replacement and deletion refuse agent tokens
+Each receiving client compares the unsealed operation's acting agent with
+sender.agent before applying moves or requests. Agent senders cannot answer as
+the person, approve or decline spec rows, or create the person's requests.
+Missing attribution and mismatched actors are refused. A refusal advances the
+replica's sequence atomically with a durable receipt and a `relay_refused` log
+entry naming the authenticated sender and attempted actor; it changes no item,
+shout or verdict. The opaque relay cannot do that comparison itself. Receivers
+also require a person sender before restoring a snapshot. This replay behavior
+uses engine version 3; the event-log format remains version 1.
+Snapshot replacement and deletion refuse agent tokens
with HUMAN_REQUIRED (403), before reading their bodies or changing storage.
Journal format 2 requires attribution; the unshipped format-1 prototype is refused
rather than inventing an identity for historical records.
diff --git a/src/board.js b/src/board.js
index 60db3e95..a7f77d0d 100644
--- a/src/board.js
+++ b/src/board.js
@@ -365,6 +365,11 @@ function logEvent(board, by, kind, itemId, detail = {}) {
(board.emittedEvents ??= []).push(board.lastEvent);
}
+/** Log an authenticated relay refusal without making an item, shout or verdict move [H2,H16]. */
+export function recordRelayRefusal(board, { by, sequence, kind, operation, actor, code }) {
+ logEvent(board, by, 'relay_refused', null, { sequence, kind, operation, actor, code });
+}
+
/**
* The item with this id, or a refusal naming the id.
*
diff --git a/src/engine.js b/src/engine.js
index 7829cc77..b503745a 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -4,6 +4,7 @@ import * as store from './board.js';
import { refusalDocument } from './json.js';
import { ENGINE_VERSION } from './machine.js';
import { Refused } from './refused.js';
+import { relayMoveActor, relaySenderProblem } from './relay-sender.js';
/** Only these public board operations may be requested by an encrypted move. */
export const ENGINE_OPERATIONS = Object.freeze([
@@ -41,6 +42,7 @@ export function checkpointSequence(board, sequence) {
export function startRelayEpoch(board) {
store.atomic(board, () => {
board.db.prepare("DELETE FROM board_meta WHERE meta_key LIKE 'relay_receipt_%'").run();
+ board.db.prepare("DELETE FROM board_meta WHERE meta_key LIKE 'relay_refusal_%'").run();
metadata(board, 'relay_applied_sequence', '0');
metadata(board, 'relay_engine_version', String(ENGINE_VERSION));
});
@@ -99,6 +101,39 @@ export function engineReceipt(board, id) {
return row ? JSON.parse(row.meta_value) : null;
}
+/** Authorize each public relay position before replay, retaining refusals atomically with its cursor. */
+export function applyRelayMove(board, move, { sequence, at, sender, kind }) {
+ const problem = relaySenderProblem(move, sender, kind);
+ if (!problem) return applyEngineMove(board, move, { sequence, at });
+ if (!Number.isSafeInteger(sequence) || sequence < 1 || !Number.isFinite(Date.parse(at))) throw new Refused('RELAY_MOVE', 'supply a valid relay sequence and receipt timestamp');
+ return store.atomic(board, () => {
+ const cursor = appliedSequence(board);
+ const key = 'relay_refusal_' + sequence;
+ const encoded = JSON.stringify({ move, sender, kind });
+ const saved = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key);
+ if (sequence <= cursor) {
+ const receipt = saved && JSON.parse(saved.meta_value);
+ if (!receipt || receipt.record !== encoded) throw new Refused('RELAY_CURSOR', 'this earlier refused position has no matching receipt; fetch a consistent relay snapshot');
+ return receipt.outcome;
+ }
+ if (sequence !== cursor + 1) throw new Refused('RELAY_ORDER', `relay sequence ${sequence} does not follow applied sequence ${cursor}; fetch and apply the missing prefix first`);
+ const outcome = { error: refusalDocument(problem).error };
+ const clock = board.clock;
+ board.clock = { now: () => new Date(at) };
+ try {
+ store.recordRelayRefusal(board, {
+ by: sender?.kind === 'agent' && typeof sender.agent === 'string' ? sender.agent : 'relay',
+ sequence, kind, operation: typeof move?.operation === 'string' ? move.operation : null,
+ actor: typeof relayMoveActor(move) === 'string' ? relayMoveActor(move) : null, code: problem.code,
+ });
+ } finally { board.clock = clock; }
+ metadata(board, key, JSON.stringify({ record: encoded, outcome }));
+ metadata(board, 'relay_applied_sequence', String(sequence));
+ metadata(board, 'relay_engine_version', String(ENGINE_VERSION));
+ return outcome;
+ });
+}
+
/**
* Apply one relay position with the same board functions as the CLI, preserving its refusal.
* A receipt and prefix commit atomically; duplicate ids return that receipt without another move.
diff --git a/src/machine.js b/src/machine.js
index d93cce97..f3933b9b 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -10,7 +10,7 @@
*/
/** Executable move semantics; bump once per release after a released move's meaning changes [H16]. */
-export const ENGINE_VERSION = 2;
+export const ENGINE_VERSION = 3;
/** @typedef {'agent' | 'coordinator' | 'clock'} Role */
diff --git a/src/relay-sender.js b/src/relay-sender.js
new file mode 100644
index 00000000..a362c0a9
--- /dev/null
+++ b/src/relay-sender.js
@@ -0,0 +1,31 @@
+/** Compare sealed actors with the relay's independently authenticated sender [H2,H16]. */
+import { Refused } from './refused.js';
+
+/** Read only the actor field used by each public engine operation; unknown operations fail closed. */
+export function relayMoveActor(move) {
+ const args = move?.args;
+ if (!Array.isArray(args)) return null;
+ if (move.operation === 'addItem') return args[0]?.by ?? null;
+ if (move.operation === 'shout') return args[0]?.from ?? null;
+ if (move.operation === 'release') return args[1] ?? null;
+ if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions'].includes(move.operation)) return args[0]?.agentId ?? null;
+ if (['appendFact', 'editItem', 'escalate', 'recordAttempt', 'claim', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze',
+ 'passDecision', 'answerDecision', 'holdLane', 'releaseLane', 'editMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone'].includes(move.operation)) return args[1]?.agentId ?? null;
+ return null;
+}
+
+/** Make the same authorization decision on every device, without inspecting its shell or checkout. */
+export function relaySenderProblem(move, sender, kind) {
+ if (!sender || !['person', 'agent'].includes(sender.kind) || typeof sender.userId !== 'string' || !sender.userId.length || sender.userId.length > 256 ||
+ (sender.kind === 'agent' && (typeof sender.agent !== 'string' || !sender.agent.length || sender.agent.length > 256))) {
+ return new Refused('RELAY_SENDER', 'this relay record has no authenticated sender; restore attribution before replaying it');
+ }
+ if (sender.kind === 'person') return null;
+ if (kind === 'snapshot' || move?.operation === 'recordRowDecisions' || move?.operation === 'answerDecision' && move.args?.[1]?.asPerson ||
+ move?.operation === 'shout' && move.args?.[0]?.request || relayMoveActor(move) === 'person') {
+ return new Refused('RELAY_PERSON_ONLY', `agent ${sender.agent} cannot make a person-only relay ${kind}; use the person's authenticated session`);
+ }
+ const actor = relayMoveActor(move);
+ if (actor !== sender.agent) return new Refused('RELAY_SENDER_MISMATCH', `agent ${sender.agent} cannot act as ${typeof actor === 'string' ? actor : '(no declared agent)'}; send this operation as the authenticated agent`);
+ return null;
+}
diff --git a/src/relay.js b/src/relay.js
index 61985dde..ed0f9340 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -4,7 +4,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, wri
import { dirname, join } from 'node:path';
import * as store from './board.js';
import { exportBoard, restoreRelaySnapshot } from './exchange.js';
-import { appliedSequence, applyEngineMove, checkpointSequence, engineReceipt, prepareEngineMove, startRelayEpoch } from './engine.js';
+import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, startRelayEpoch } from './engine.js';
import { ENGINE_VERSION } from './machine.js';
import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';
import { repoInfo, tryGit } from './git.js';
@@ -12,6 +12,7 @@ import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
import { encodeBoardKey, generateBoardKey, seal, unseal } from './seal.js';
import { terminalQr } from './qr.js';
import { Refused } from './refused.js';
+import { relaySenderProblem } from './relay-sender.js';
export const DEFAULT_RELAY = 'https://app.pullboard.dev';
const LINK_FILES = new WeakMap();
@@ -282,6 +283,8 @@ async function restoreCheckpoint(root, state, io, key) {
const document = await request(state, '/api/v1/boards/' + state.board + '/state', {}, io);
const snapshot = document.state;
if (!snapshot || !Number.isSafeInteger(snapshot.sequence) || snapshot.sequence < 0) throw new Refused('RELAY_RESPONSE', 'the relay snapshot has no valid coverage sequence; fetch it again');
+ const senderProblem = relaySenderProblem(null, snapshot.sender, 'snapshot');
+ if (senderProblem) throw senderProblem;
const native = await decoded(key, snapshot, state, 'snapshot', snapshot.sequence);
localRecords(root, (board) => restoreRelaySnapshot(board, native, snapshot.sequence));
}
@@ -304,7 +307,7 @@ async function catchUp(root, file, state, io) {
for (const record of remote.events) {
const move = await decoded(key, record, state, record.kind, record.event_id);
localRecords(root, (board) => {
- applyEngineMove(board, move, { sequence: record.event_id, at: record.event_at });
+ applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind });
});
}
state.sequence = localRecords(root, appliedSequence);
diff --git a/test/engine.test.js b/test/engine.test.js
index 09a8a235..be7e5a66 100644
--- a/test/engine.test.js
+++ b/test/engine.test.js
@@ -6,7 +6,7 @@ import { join } from 'node:path';
import { test } from 'node:test';
import * as store from '../src/board.js';
import { exportBoard, importBoard, restoreRelaySnapshot } from '../src/exchange.js';
-import { applyEngineMove, prepareEngineMove, appliedSequence, engineReceipt, startRelayEpoch } from '../src/engine.js';
+import { applyEngineMove, applyRelayMove, prepareEngineMove, appliedSequence, engineReceipt, startRelayEpoch } from '../src/engine.js';
import { ENGINE_VERSION } from '../src/machine.js';
import { Refused } from '../src/refused.js';
@@ -94,6 +94,39 @@ test('person answer channel replays identically on agent and plain replicas [B26
}
});
+test('missing relay senders are refused deterministically without poisoning a later legitimate move id [H2,H16]', t => {
+ const { copies, item } = engineCopies(t);
+ const [one, two] = copies;
+ const move = claimMove(one, item, 'web-1');
+ for (const board of copies) {
+ const before = store.getItem(board, item);
+ const refused = applyRelayMove(board, move, { sequence: 1, at: CLAIM_AT, kind: 'request' });
+ assert.equal(refused.error.code, 'RELAY_SENDER');
+ assert.deepEqual(store.getItem(board, item), before);
+ assert.equal(appliedSequence(board), 1);
+ assert.equal(engineReceipt(board, move.id), null, 'a forged move id cannot reserve a legitimate operation receipt');
+ assert.equal(store.events(board).at(-1).event_kind, 'relay_refused');
+ assert.equal(store.events(board).at(-1).event_by, 'relay');
+ const accepted = applyRelayMove(board, move, { sequence: 2, at: CLAIM_AT, kind: 'move', sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } });
+ assert.equal(Boolean(accepted.error), false);
+ assert.equal(store.getItem(board, item).item_owner, 'web-1');
+ const after = exportBoard(board);
+ assert.deepEqual(applyRelayMove(board, move, { sequence: 1, at: CLAIM_AT, kind: 'request' }), refused);
+ assert.deepEqual(exportBoard(board), after, 'repeated refusal returns its own receipt without moving the cursor backwards');
+ }
+ assert.deepEqual(exportBoard(one).tables, exportBoard(two).tables);
+});
+
+test('a relay refusal receipt failure rolls back its log and cursor together [H2,H16]', t => {
+ const { copies, item } = engineCopies(t);
+ const board = copies[0];
+ const before = exportBoard(board);
+ board.db.exec("CREATE TEMP TRIGGER refuse_receipt BEFORE INSERT ON board_meta WHEN NEW.meta_key LIKE 'relay_refusal_%' BEGIN SELECT RAISE(ABORT, 'refusal receipt rollback'); END");
+ assert.throws(() => applyRelayMove(board, claimMove(board, item, 'web-1'), { sequence: 1, at: CLAIM_AT, kind: 'move' }), /refusal receipt rollback/);
+ assert.deepEqual(exportBoard(board), before);
+ assert.equal(appliedSequence(board), 0);
+});
+
test('the same sealed claim replays to identical rows and sequence retries are idempotent [H3,H16]', (t) => {
const { copies, item } = engineCopies(t);
const [one, two] = copies;
diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.js
index 78a5edd1..48afe0bd 100644
--- a/test/relay-sealed.test.js
+++ b/test/relay-sealed.test.js
@@ -1,8 +1,8 @@
/** Two real clients and encrypted CLI records exercise the relay without sharing their key [A4,H7]. */
import assert from 'node:assert/strict';
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
-import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync } from 'node:fs';
+import { spawn, spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { test } from 'node:test';
@@ -10,6 +10,10 @@ import { serveRelay } from '../relay/service.js';
import { createRelayAuth } from '../relay/auth.js';
import { createGitHubClient } from '../relay/github.js';
import { githubFixture } from './relay-fixture.js';
+import * as store from '../src/board.js';
+import { exportBoard } from '../src/exchange.js';
+import { checkpointSequence, prepareEngineMove } from '../src/engine.js';
+import { seal as sealMove } from '../src/seal.js';
/** Seal on the test client only; nonce, authentication tag and ciphertext are opaque to the server. */
function seal(key, value, binding) {
@@ -38,6 +42,7 @@ async function fixture(t) {
const data = join(directory, 'relay');
mkdirSync(root); mkdirSync(home);
const env = { ...process.env, HOME: home, PULLBOARD_HOME: home, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
+ delete env.PULLBOARD_RELAY_TOKEN;
const git = spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: root, env, encoding: 'utf8' });
assert.equal(git.status, 0, git.stderr);
/** Run the current CLI only in the fixture's private home and Git repository. */
@@ -79,9 +84,90 @@ async function fixture(t) {
function clientSeal(value, kind, sequence, board = id) { return seal(key, value, { board, kind, sequence }); }
/** Unseal received records at their actual committed position, never the client's old proposal. */
function clientOpen(value, kind, sequence, board = id) { return unseal(key, value, { board, kind, sequence }); }
- return { directory, root, data, cli, document, id, marker, auth, person, one, two, relay, origin, key, call, clientSeal, clientOpen, path: '/api/v1/boards/' + id };
+ return { directory, root, home, env, data, cli, document, id, marker, auth, person, one, two, relay, origin, key, call, clientSeal, clientOpen, path: '/api/v1/boards/' + id };
}
+/** Run a linked CLI asynchronously so the real relay can serve it, keeping credentials out of diagnostics. */
+function replayClient(root, env, ...args) {
+ return new Promise((done, fail) => {
+ const child = spawn(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let stdout = '';
+ const timer = setTimeout(() => child.kill('SIGKILL'), 25000);
+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });
+ child.stderr.resume();
+ child.once('error', error => { clearTimeout(timer); fail(error); });
+ child.once('close', code => {
+ clearTimeout(timer);
+ if (code !== 0) return fail(new Error('isolated linked CLI command failed'));
+ try { done(JSON.parse(stdout)); } catch { fail(new Error('isolated linked CLI did not return JSON')); }
+ });
+ });
+}
+
+test('two real clients refuse forged relay actors and person-only requests while advancing identically [H2,H16]', async t => {
+ const box = await fixture(t);
+ const source = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));
+ let document, question, moves;
+ try {
+ const lane = store.getItem(source, 1).item_lane;
+ assert.equal(store.register(source, { lane: 'remote', path: join(box.directory, 'remote') }), 'remote-1');
+ store.claim(source, 1, { agentId: 'remote-1', lane, leaseMs: 3600000, freeze: () => ({ text: '{}', digest: 'd'.repeat(64) }) });
+ store.submit(source, 1, { agentId: 'remote-1', commit: 'a'.repeat(40), tree: 'b'.repeat(40) });
+ question = store.shout(source, { from: 'coordinator', to: 'person', text: 'Private person decision', decision: true, lanes: [lane] });
+ checkpointSequence(source, 0);
+ moves = [
+ prepareEngineMove(source, 'verify', [1, { agentId: 'coordinator', decision: 'ACCEPT', reason: 'CRITERION_MET', note: 'forged acceptance', head: 'a'.repeat(40), digest: 'd'.repeat(64), policy: 'any' }]),
+ prepareEngineMove(source, 'answerDecision', [question, { agentId: 'coordinator', asPerson: true, text: 'forged person answer', lanes: [lane] }]),
+ prepareEngineMove(source, 'shout', [{ from: 'person', to: 'coordinator', request: true, text: 'forged person request', lanes: [lane] }]),
+ prepareEngineMove(source, 'recordRowDecisions', [{ agentId: 'remote-1', channel: 'view', decisions: [] }]),
+ prepareEngineMove(source, 'shout', [{ from: 'remote-1', to: 'all', text: 'valid remote observation', lanes: [lane] }]),
+ ];
+ document = JSON.parse(JSON.stringify(exportBoard(source)));
+ } finally { store.closeBoard(source); }
+ const remote = await box.auth.issueToken(box.person.token, { board: box.id, agent: 'remote-1' });
+ const roots = [box.root, join(box.directory, 'second-client')];
+ const homes = [box.home, join(box.directory, 'second-home')];
+ const envs = homes.map(home => ({ ...box.env, HOME: home, PULLBOARD_HOME: home }));
+ mkdirSync(roots[1]); mkdirSync(homes[1], { mode: 0o700 });
+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: roots[1], env: envs[1] }).status, 0);
+ await replayClient(roots[1], envs[1], 'init');
+ const snapshotFile = join(box.directory, 'native.json');
+ writeFileSync(snapshotFile, JSON.stringify(document), { mode: 0o600 });
+ await replayClient(roots[1], envs[1], 'import', snapshotFile);
+ for (let index = 0; index < roots.length; index += 1) {
+ const keyDirectory = join(homes[index], 'relay-keys');
+ mkdirSync(keyDirectory, { mode: 0o700 });
+ writeFileSync(join(keyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });
+ writeFileSync(join(roots[index], '.git/pullboard/relay.json'), JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: box.origin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });
+ }
+ /** Seal production-format records on this client; the relay stores only their opaque envelopes. */
+ async function upload(value, kind, sequence, token = remote.token) {
+ const sealed = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(value)), { boardId: box.id, kind, sequence })).toString('base64url');
+ const reply = await box.call(box.path + (kind === 'snapshot' ? '/state' : kind === 'request' ? '/requests' : '/moves'), { method: kind === 'snapshot' ? 'PUT' : 'POST', token, body: { sequence, sealed } });
+ assert.equal(reply.status, 200, 'the real relay accepts the opaque authorized upload');
+ }
+ await upload(document, 'snapshot', 0, box.person.token);
+ for (let index = 0; index < moves.length; index += 1) await upload(moves[index], index === 2 ? 'request' : 'move', index + 1);
+ const exported = await Promise.all(roots.map((root, index) => replayClient(root, envs[index], 'export')));
+ assert.deepEqual(exported[0].tables, exported[1].tables, 'every replica keeps exactly the same rows and refusal receipts');
+ const result = exported[0];
+ assert.deepEqual(result.tables.item, document.tables.item, 'forged verification changes no item');
+ assert.deepEqual(result.tables.verdict, document.tables.verdict, 'forged acceptance leaves the verdict unchanged');
+ const newShouts = result.tables.shout.filter(row => row.shout_id > document.tables.shout.at(-1).shout_id);
+ assert.equal(newShouts.length, 1, 'only the permitted observation creates a shout');
+ assert.equal(newShouts[0].shout_from, 'remote-1');
+ assert.equal(newShouts[0].shout_text, 'valid remote observation');
+ const refused = result.tables.event.filter(row => row.event_kind === 'relay_refused');
+ assert.equal(refused.length, 4);
+ assert.ok(refused.every(row => row.event_by === 'remote-1'), 'the log attributes every attempted forgery to its authenticated sender');
+ assert.deepEqual(refused.map(row => JSON.parse(row.event_detail).code), ['RELAY_SENDER_MISMATCH', 'RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY', 'RELAY_PERSON_ONLY']);
+ assert.equal(JSON.parse(refused[0].event_detail).actor, 'coordinator');
+ assert.equal(result.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '5');
+ const log = await replayClient(roots[1], envs[1], 'log');
+ assert.deepEqual(log.events.filter(row => row.event_kind === 'relay_refused'), refused, 'pullboard log exposes the sending agent and attempted actor');
+ assert.deepEqual((await replayClient(roots[0], envs[0], 'export')).tables, result.tables, 'repeat catch-up does not duplicate refusals or actions');
+});
+
test('[A4,H7] two clients append sealed moves in one order and no plaintext or client key reaches storage', async (t) => {
const box = await fixture(t);
const listed = await box.call('/api/v1/boards');