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
fix(relay): retain authenticated senders on sealed records [A4,H7]
Corey Olsonc429c9d47327
diff --git a/relay/README.md b/relay/README.mdindex e979286a..3a7d1243 100644--- a/relay/README.md+++ b/relay/README.md@@ -87,14 +87,15 @@ The client owns the encryption format and engine-version checks.- PUT /api/v1/boards/:id/state takes {sequence, sealed}. The first snapshotnormally covers sequence 0. A later snapshot may cover only committed moves,cannot move behind the previous snapshot, and removes the covered move prefix.+ Snapshot replacement requires a person's signed-in session, not an agent token.- GET /api/v1/boards/:id/state returns- {version: 1, state: {sequence, receivedAt, sealed}}.+ {version: 1, state: {sequence, receivedAt, sender, sealed}}.- POST /api/v1/boards/:id/moves takes {sequence, sealed}. The client proposesthe next position before sealing; the relay allocates it atomically only ifsequence is its next position and returns {version: 1, event, result: {sequence}}.A loser receives SEQUENCE_REPEAT (409), reads the latest prefix, reseals witha fresh nonce bound to the next position, and retries. Gaps are refused too.- An event is {event_id, event_at, kind, sealed}. Requests use the same sealed append+ An event is {event_id, event_at, kind, sender, sealed}. Requests use the same sealed appendthrough POST /api/v1/boards/:id/requests. The public transport kind is move orrequest, letting clients select their associated-data binding; content stays sealed.- GET /api/v1/boards/:id/events?after=N returns sealed events in sequence.@@ -102,12 +103,13 @@ The client owns the encryption format and engine-version checks.A cursor older than the latest snapshot gets SNAPSHOT_REQUIRED (409), namingthe need to fetch state and resume after its coverage cursor.- DELETE /api/v1/boards/:id removes that board's database and SQLite sidecars.+ It requires a person's signed-in session and current write access.GitHub link/credential lifecycle remains owned by the sign-in/linking layer.All responses and refusals retain API version 1. Moves use the shared 100,000byte JSON-body limit. Snapshots allow a bounded 14,000,000 byte JSON body and10,000,000 decoded bytes. One private SQLite journal per board stores only its-identity, format, head cursor, receive times and sealed payloads. Compaction+identity, format, head cursor, receive times, public sender identities and sealed payloads. Compactionkeeps the head cursor, so the next move never reuses an earlier sequence.Bearer credentials work for agents and CLI calls. Browser session-cookie reads@@ -118,6 +120,17 @@ after body reading; live streams recheck the credential between polls. A boardcredential cannot reach another board. Code previews are unavailable on therelay: source files stay local.+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+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.+test/relay-journal.test.js races real processes and checks restart/compaction.test/relay-sealed.test.js seals actual CLI records on two test clients, uses anactual loopback sign-in stand-in, and checks order, snapshots, live delivery,diff --git a/relay/journal.js b/relay/journal.jsindex acc10576..9a30a89e 100644--- a/relay/journal.js+++ b/relay/journal.js@@ -4,7 +4,7 @@ import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs';import { join, resolve } from 'node:path';import { Refused } from '../src/refused.js';-const FORMAT = 1;+const FORMAT = 2;const DEFAULT_BYTES = 100_000;/** Validate a persistent identity before it can name an internal file. */@@ -16,7 +16,7 @@ function identity(value) {/*** Own a private per-board journal of uninterpreted bytes. It does not compute board state or* promise that a payload is encrypted. Its caller must authenticate and authorize every use.- * This separate transport foundation does not replace the frozen #104 engine replay criterion.+ * Sender metadata is public authentication context, not an interpretation of a sealed payload.*/export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTES, now = () => new Date() }) {const id = identity(boardId);@@ -34,7 +34,12 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTElet closed = false;try {db.exec('PRAGMA busy_timeout = 30000; PRAGMA journal_mode = WAL; BEGIN IMMEDIATE');- db.exec('CREATE TABLE IF NOT EXISTS journal_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN (\'move\',\'request\')), payload BLOB NOT NULL)');+ db.exec(`CREATE TABLE IF NOT EXISTS journal_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);+ CREATE TABLE IF NOT EXISTS journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL,+ kind TEXT NOT NULL CHECK(kind IN ('move','request')), payload BLOB NOT NULL,+ sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','agent')), sender_user TEXT NOT NULL,+ sender_agent TEXT, CHECK((sender_kind='person' AND sender_agent IS NULL) OR+ (sender_kind='agent' AND sender_agent IS NOT NULL)))`);const saved = db.prepare('SELECT key, value FROM journal_meta ORDER BY key').all();if (saved.length === 0) {if (db.prepare('SELECT 1 FROM journal_record LIMIT 1').get()) throw new Refused('RELAY_STORAGE', 'restore the journal with its original identity and format metadata');@@ -42,7 +47,10 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE} else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== id || saved[1].key !== 'format' || saved[1].value !== String(FORMAT)) {throw new Refused('RELAY_STORAGE', 'open this journal with its original board identity and supported transport format');}- db.exec('CREATE TABLE IF NOT EXISTS journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS journal_snapshot (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL, received_at TEXT NOT NULL, payload BLOB NOT NULL)');+ db.exec(`CREATE TABLE IF NOT EXISTS journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL);+ CREATE TABLE IF NOT EXISTS journal_snapshot (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL,+ received_at TEXT NOT NULL, payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind='person'),+ sender_user TEXT NOT NULL, sender_agent TEXT CHECK(sender_agent IS NULL))`);db.exec('INSERT OR IGNORE INTO journal_head (slot,sequence) SELECT 1, COALESCE(MAX(sequence),0) FROM journal_record');db.exec('COMMIT');} catch (error) {@@ -55,7 +63,22 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEfunction open() { if (closed) throw new Refused('RELAY_CLOSED', 'open the journal before reading or appending records'); }/** Convert an SQLite row to detached opaque bytes so callers cannot mutate a stored record. */- function record(row) { return { sequence: row.sequence, receivedAt: row.received_at, kind: row.kind ?? 'snapshot', bytes: Buffer.from(row.payload) }; }+ function record(row) {+ return { sequence: row.sequence, receivedAt: row.received_at, kind: row.kind ?? 'snapshot',+ sender: { kind: row.sender_kind, userId: row.sender_user,+ ...(row.sender_kind === 'agent' ? { agent: row.sender_agent } : {}) }, bytes: Buffer.from(row.payload) };+ }++ /** Require server-derived attribution, copying only its public identity and never a credential. */+ function sender(value, personOnly = false) {+ if (!value || !['person', 'agent'].includes(value.kind) || typeof value.userId !== 'string' ||+ !value.userId.length || value.userId.length > 256 ||+ (value.kind === 'agent' && (typeof value.agent !== 'string' || !value.agent.length || value.agent.length > 256))) {+ throw new Refused('RELAY_PRINCIPAL', 'supply the authenticated sender before storing a sealed record');+ }+ if (personOnly && value.kind !== 'person') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to replace a board snapshot');+ return { kind: value.kind, userId: value.userId, agent: value.kind === 'agent' ? value.agent : null };+ }/** Read the latest committed sequence, including an empty journal's initial cursor. */function latest() {@@ -70,10 +93,11 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE}/** Serialize prefix checking or sequence allocation with the opaque append. */- function insert(sequence, bytes, kind) {+ function insert(sequence, bytes, kind, principal) {open();if (sequence !== null && (!Number.isSafeInteger(sequence) || sequence < 1)) throw new Refused('BAD_SEQUENCE', 'upload a positive safe integer sequence');const sealed = payload(bytes);+ const who = sender(principal);if (!['move', 'request'].includes(kind)) throw new Refused('BAD_UPLOAD', 'use the move or request transport kind');db.exec('BEGIN IMMEDIATE');try {@@ -84,7 +108,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEif (sequence > next) throw new Refused('SEQUENCE_GAP', 'send the next sequence after the latest committed record before later uploads');const at = now();if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');- db.prepare('INSERT INTO journal_record (sequence,received_at,kind,payload) VALUES (?,?,?,?)').run(sequence, at.toISOString(), kind, sealed);+ db.prepare('INSERT INTO journal_record (sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent) VALUES (?,?,?,?,?,?,?)').run(sequence, at.toISOString(), kind, sealed, who.kind, who.userId, who.agent);db.prepare('UPDATE journal_head SET sequence=? WHERE slot=1').run(sequence);const result = record(db.prepare('SELECT * FROM journal_record WHERE sequence=?').get(sequence));db.exec('COMMIT');@@ -96,10 +120,10 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE}/** Append a transport retry only at its explicitly named next sequence. */- function append(sequence, bytes, kind = 'move') { return insert(sequence, bytes, kind); }+ function append(sequence, bytes, kind = 'move', principal) { return insert(sequence, bytes, kind, principal); }/** Allocate the next sequence under the same lock as the append, as the live relay requires. */- function appendNext(bytes, kind = 'move') { return insert(null, bytes, kind); }+ function appendNext(bytes, kind = 'move', principal) { return insert(null, bytes, kind, principal); }/** Read the latest sealed snapshot without interpreting its contents. */function snapshot() {@@ -109,10 +133,11 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE}/** Replace a covered snapshot and compact only its acknowledged prefix, keeping the head. */- function saveSnapshot(sequence, bytes) {+ function saveSnapshot(sequence, bytes, principal) {open();if (!Number.isSafeInteger(sequence) || sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence this snapshot covers');const sealed = payload(bytes);+ const who = sender(principal, true);db.exec('BEGIN IMMEDIATE');try {if (sequence > latest()) throw new Refused('SEQUENCE_GAP', 'upload the missing moves before a snapshot that covers them');@@ -120,7 +145,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEif (previous && sequence < previous.sequence) throw new Refused('SNAPSHOT_STALE', 'use the latest stored snapshot and seal a snapshot that covers at least its sequence');const at = now();if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');- db.prepare('INSERT INTO journal_snapshot (slot,sequence,received_at,payload) VALUES (1,?,?,?) ON CONFLICT(slot) DO UPDATE SET sequence=excluded.sequence,received_at=excluded.received_at,payload=excluded.payload').run(sequence, at.toISOString(), sealed);+ db.prepare('INSERT INTO journal_snapshot (slot,sequence,received_at,payload,sender_kind,sender_user,sender_agent) VALUES (1,?,?,?,?,?,?) ON CONFLICT(slot) DO UPDATE SET sequence=excluded.sequence,received_at=excluded.received_at,payload=excluded.payload,sender_kind=excluded.sender_kind,sender_user=excluded.sender_user,sender_agent=excluded.sender_agent').run(sequence, at.toISOString(), sealed, who.kind, who.userId, who.agent);db.prepare('DELETE FROM journal_record WHERE sequence <= ?').run(sequence);const result = snapshot();db.exec('COMMIT');diff --git a/relay/service.js b/relay/service.jsindex edc056b6..4b948c10 100644--- a/relay/service.js+++ b/relay/service.js@@ -55,10 +55,17 @@ function sealed(body) {}/** Give live events the common API cursor while keeping all board contents sealed. */-function event(row) { return { event_id: row.sequence, event_at: row.receivedAt, kind: row.kind, sealed: row.bytes.toString('base64url') }; }+function event(row) { return { event_id: row.sequence, event_at: row.receivedAt, kind: row.kind, sender: row.sender, sealed: row.bytes.toString('base64url') }; }/** Give a snapshot its coverage cursor; clients unseal it and replay the following sealed events. */-function state(row) { return { sequence: row.sequence, receivedAt: row.receivedAt, sealed: row.bytes.toString('base64url') }; }+function state(row) { return { sequence: row.sequence, receivedAt: row.receivedAt, sender: row.sender, sealed: row.bytes.toString('base64url') }; }++/** Project a freshly authenticated credential to public sender metadata, never taking body fields. */+function sender(who, personOnly = false) {+ if (personOnly && who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to replace a snapshot or unlink a board');+ return { kind: who.kind === 'session' ? 'person' : 'agent', userId: who.user.id,+ ...(who.kind === 'board' ? { agent: who.agent } : {}) };+}/** Create a private relay handler; the caller owns sign-in lifecycle and service shutdown. */export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin }) {@@ -89,9 +96,9 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginasync function append(board, body, who, kind = 'move') {const bytes = sealed(body);if (!Number.isSafeInteger(body.sequence) || body.sequence < 1) throw new Refused('BAD_SEQUENCE', 'seal this move for the next positive sequence after the latest committed prefix');- await auth.authenticate(who.credential, { board: board.id, write: true });+ const principal = sender(await auth.authenticate(who.credential, { board: board.id, write: true }));return withJournal(board.id, (journal) => {- const row = journal.append(body.sequence, bytes, kind);+ const row = journal.append(body.sequence, bytes, kind, principal);return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };});}@@ -128,17 +135,17 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginconst deletion = /^\/api\/v1\/boards\/([^/]+)$/.exec(url.pathname);if (req.method === 'PUT' && snapshot) {const id = identity(snapshot[1]);- await auth.authenticate(credential(req, origin, true), { board: id, write: true });+ sender(await auth.authenticate(credential(req, origin, true), { board: id, write: true }), true);const body = await readApiBody(req, { maxBytes: SNAPSHOT_BODY });const bytes = sealed(body);if (!Number.isSafeInteger(body.sequence) || body.sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence covered by the sealed snapshot');- await auth.authenticate(credential(req, origin, true), { board: id, write: true });- const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes), true);+ const principal = sender(await auth.authenticate(credential(req, origin, true), { board: id, write: true }), true);+ const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes, principal), true);return apiJson(res, 200, { state: state(saved) });}if (req.method === 'DELETE' && deletion) {const id = identity(deletion[1]);- await auth.authenticate(credential(req, origin, true), { board: id, write: true });+ sender(await auth.authenticate(credential(req, origin, true), { board: id, write: true }), true);withJournal(id, () => undefined);const file = join(root, id + '.journal.sqlite');for (const suffix of ['', '-wal', '-shm']) {diff --git a/src/api-http.js b/src/api-http.jsindex 276b2e7d..2eaf4b27 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -142,7 +142,7 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {/** Choose the same HTTP refusal class for local and sealed relay adapters. */export function apiStatus(error) {- return { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);+ return { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);}// Relay-only snapshot/delete routes reuse the exact shared bounded-body and refusal boundary.diff --git a/test/relay-journal.test.js b/test/relay-journal.test.jsindex 956042cc..cd46759a 100644--- a/test/relay-journal.test.js+++ b/test/relay-journal.test.js@@ -8,6 +8,8 @@ import { test } from 'node:test';import { createRelayJournal } from '../relay/journal.js';const ID = 'a'.repeat(32);+const AGENT = { kind: 'agent', userId: '101', agent: 'client-one' };+const PERSON = { kind: 'person', userId: '101' };/** Give each test a private directory and close every journal before deleting its files. */function fixture(t, options = {}) {@@ -16,7 +18,14 @@ function fixture(t, options = {}) {t.after(() => { for (const journal of opened) journal.close(); rmSync(directory, { recursive: true, force: true }); });/** Open the same durable journal through its public interface. */function open(overrides = {}) {- const journal = createRelayJournal({ directory, boardId: ID, ...options, ...overrides });+ const raw = createRelayJournal({ directory, boardId: ID, ...options, ...overrides });+ /** Supply the synthetic authenticated agent for this transport-only fixture. */+ function append(sequence, bytes, kind = 'move', principal = AGENT) { return raw.append(sequence, bytes, kind, principal); }+ /** Supply the synthetic authenticated agent when the server allocates a position. */+ function appendNext(bytes, kind = 'move', principal = AGENT) { return raw.appendNext(bytes, kind, principal); }+ /** Only the fixture's signed-in person may replace a compacted snapshot. */+ function saveSnapshot(sequence, bytes, principal = PERSON) { return raw.saveSnapshot(sequence, bytes, principal); }+ const journal = { ...raw, append, appendNext, saveSnapshot };opened.push(journal);return journal;}@@ -31,6 +40,9 @@ test('[A4,H7] ordered opaque bytes survive restart without parsing or aliasing',assert.equal(first.sequence, 1);assert.equal(first.receivedAt, '2026-10-07T00:00:00.000Z');assert.deepEqual(first.bytes, bytes);+ assert.deepEqual(first.sender, AGENT);+ first.sender.agent = 'forged';+ assert.deepEqual(box.journal.after()[0].sender, AGENT, 'returned sender objects never alias stored attribution');bytes.fill(0);first.bytes.fill(0);assert.deepEqual(box.journal.after()[0].bytes, Buffer.from([0, 255, 1, 128, 0]));@@ -58,6 +70,8 @@ test('[A4] gaps, repeats, invalid uploads and clock failures leave the prefix un}assert.throws(() => box.journal.after(-1), { code: 'BAD_CURSOR' });assert.throws(() => box.journal.after('0'), { code: 'BAD_CURSOR' });+ assert.throws(() => box.journal.append(2, Buffer.from('x'), 'move', null), { code: 'RELAY_PRINCIPAL' });+ assert.throws(() => box.journal.saveSnapshot(0, Buffer.from('x'), AGENT), { code: 'HUMAN_REQUIRED' });assert.equal(box.journal.latest(), 1);box.journal.close();const badClock = box.open({ now: () => new Date(NaN) });@@ -74,8 +88,9 @@ test('[A4,H7] two real processes cannot publish the same next sequence', async (writeFileSync(worker, ['import { createRelayJournal } from ' + JSON.stringify(module) + ';','const journal = createRelayJournal({ directory: process.argv[2], boardId: process.argv[3] });',+ 'const sender = {kind:"agent",userId:"101",agent:"worker"};','try {',- ' const row = process.argv[4].startsWith("auto ") ? journal.appendNext(Buffer.from(process.argv[4])) : journal.append(1, Buffer.from(process.argv[4]));',+ ' const row = process.argv[4].startsWith("auto ") ? journal.appendNext(Buffer.from(process.argv[4]),"move",sender) : journal.append(1, Buffer.from(process.argv[4]),"move",sender);',' process.stdout.write(JSON.stringify({ sequence: row.sequence }));','} catch (error) { process.stdout.write(JSON.stringify({ code: error.code })); }','finally { journal.close(); }',@@ -136,6 +151,7 @@ test('[A4,H7] a sealed snapshot compacts its prefix without reusing sequence numbox.journal.appendNext(Buffer.from('opaque move three'));box.journal.saveSnapshot(2, Buffer.from('snapshot through two'));assert.equal(box.journal.snapshot().sequence, 2);+ assert.deepEqual(box.journal.snapshot().sender, PERSON);assert.equal(box.journal.snapshot().bytes.toString(), 'snapshot through two');assert.deepEqual(box.journal.after().map((row) => row.sequence), [3]);assert.equal(box.journal.latest(), 3);diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.jsindex b22a1c30..f4f8c6b4 100644--- a/test/relay-sealed.test.js+++ b/test/relay-sealed.test.js@@ -88,9 +88,10 @@ test('[A4,H7] two clients append sealed moves in one order and no plaintext or cassert.equal(listed.status, 200);assert.deepEqual(listed.body.boards, [{ id: box.id, repository: 'fixture/repository' }]);const initial = box.clientSeal(box.document, 'snapshot', 0);- const uploaded = await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 0, sealed: initial } });+ const uploaded = await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: initial } });assert.equal(uploaded.status, 200);assert.equal(uploaded.body.version, 1);+ assert.deepEqual(uploaded.body.state.sender, { kind: 'person', userId: box.person.user.id });assert.deepEqual(box.clientOpen(uploaded.body.state.sealed, 'snapshot', 0), box.document);const sent = [{ client: 'one', title: 'PRIVATE_MOVE_FROM_CLIENT_ONE' },@@ -122,12 +123,12 @@ test('[A4,H7] two clients append sealed moves in one order and no plaintext or ctest('[A4,H7] snapshots compact covered moves, preserve the tail and deletion removes only its database', async (t) => {const box = await fixture(t);- await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 0, sealed: box.clientSeal(box.document, 'snapshot', 0) } });+ await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: box.clientSeal(box.document, 'snapshot', 0) } });for (let n = 1; n <= 3; n++) {const reply = await box.call(box.path + '/moves', { method: 'POST', body: { sequence: n, sealed: box.clientSeal({ move: n }, 'move', n) } });assert.equal(reply.body.event.event_id, n);}- const compacted = await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 2, sealed: box.clientSeal({ covered: 2 }, 'snapshot', 2) } });+ const compacted = await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 2, sealed: box.clientSeal({ covered: 2 }, 'snapshot', 2) } });assert.equal(compacted.status, 200);assert.equal(compacted.body.state.sequence, 2);assert.deepEqual(box.clientOpen((await box.call(box.path + '/state')).body.state.sealed, 'snapshot', 2), { covered: 2 });@@ -141,7 +142,7 @@ test('[A4,H7] snapshots compact covered moves, preserve the tail and deletion reawait box.auth.linkBoard(box.person.token, other, 'fixture/repository');const otherPath = '/api/v1/boards/' + other;assert.equal((await box.call(otherPath + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: box.clientSeal({ other: true }, 'snapshot', 0, other) } })).status, 200);- assert.equal((await box.call(box.path, { method: 'DELETE' })).status, 200);+ assert.equal((await box.call(box.path, { method: 'DELETE', token: box.person.token })).status, 200);for (const suffix of ['', '-wal', '-shm']) assert.equal(existsSync(join(box.data, box.id + '.journal.sqlite' + suffix)), false);assert.equal((await box.call(box.path + '/state')).status, 404);assert.deepEqual(box.clientOpen((await box.call(otherPath + '/state', { token: box.person.token })).body.state.sealed, 'snapshot', 0, other), { other: true });@@ -156,10 +157,10 @@ test('[A4,H7] malformed or unauthorized calls cannot store clear records, keys oassert.equal(wrong.status, 403);assert.equal(wrong.body.error.code, 'TOKEN_BOARD');for (const body of [{ sequence: 0, sealed: 'a' }, { sequence: 0, sealed: 'abc=' }, { sequence: 0, sealed: box.clientSeal({}, 'snapshot', 0), key: 'client key stays on device' }, { sequence: '0', sealed: box.clientSeal({}, 'snapshot', 0) }]) {- assert.equal((await box.call(box.path + '/state', { method: 'PUT', body })).status, 400);+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body })).status, 400);}assert.deepEqual(readdirSync(box.data), []);- await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 0, sealed: box.clientSeal(box.document, 'snapshot', 0) } });+ await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: box.clientSeal(box.document, 'snapshot', 0) } });assert.equal((await box.call(box.path + '/moves', { method: 'POST', body: { verb: 'add', args: { title: 'clear' } } })).body.error.code, 'BAD_UPLOAD');const deniedCookie = await box.call(box.path + '/moves', { method: 'POST', token: null, headers: { cookie: 'pb_session=' + box.person.token, origin: 'https://foreign.example' }, body: { sequence: 1, sealed: box.clientSeal({}, 'move', 1) } });assert.equal(deniedCookie.status, 403);@@ -172,6 +173,7 @@ test('[A4,H7] malformed or unauthorized calls cannot store clear records, keys o});assert.equal(request.status, 200);assert.equal(request.body.event.kind, 'request');+ assert.deepEqual(request.body.event.sender, { kind: 'agent', userId: box.person.user.id, agent: 'client-one' });assert.deepEqual(box.clientOpen(request.body.event.sealed, request.body.event.kind, request.body.event.event_id), { request: true });assert.throws(() => box.clientOpen(request.body.event.sealed, 'move', request.body.event.event_id));@@ -188,9 +190,49 @@ test('[A4,H7] malformed or unauthorized calls cannot store clear records, keys oassert.equal((await box.call(box.path + '/state')).status, 401);});+test('[A4,H2,H7,H16] trusted sender attribution exposes impersonation and agent tokens cannot erase a board', async (t) => {+ const box = await fixture(t);+ const initial = box.clientSeal(box.document, 'snapshot', 0);+ const uploaded = await box.call(box.path + '/state', {+ method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: initial },+ });+ assert.equal(uploaded.status, 200);+ const forged = { agent: 'client-two', verb: 'claim', item: 1 };+ const reply = await box.call(box.path + '/moves', {+ method: 'POST', body: { sequence: 1, sealed: box.clientSeal(forged, 'move', 1) },+ });+ assert.equal(reply.status, 200, 'the relay stores opaque bytes without reading their claimed agent');+ const expected = { kind: 'agent', userId: box.person.user.id, agent: 'client-one' };+ assert.deepEqual(reply.body.event.sender, expected, 'the sender comes from the credential, not sealed contents');+ const events = (await box.call(box.path + '/events?after=0')).body.events;+ assert.equal(events.length, 1);+ assert.deepEqual(events[0].sender, expected, 'attribution survives the closed/reopened journal');+ const opened = box.clientOpen(events[0].sealed, events[0].kind, events[0].event_id);+ assert.notEqual(opened.agent, events[0].sender.agent, 'the client can detect impersonation before engine replay');+ assert.deepEqual(opened, forged, 'the server never rewrites or interprets the sealed move');++ const compact = await box.call(box.path + '/state', {+ method: 'PUT', body: { sequence: 1, sealed: box.clientSeal({ covered: 1 }, 'snapshot', 1) },+ });+ assert.equal(compact.status, 403);+ assert.equal(compact.body.error.code, 'HUMAN_REQUIRED');+ const deleted = await box.call(box.path, { method: 'DELETE' });+ assert.equal(deleted.status, 403);+ assert.equal(deleted.body.error.code, 'HUMAN_REQUIRED');+ assert.deepEqual((await box.call(box.path + '/state')).body.state, uploaded.body.state);+ assert.deepEqual((await box.call(box.path + '/events?after=0')).body.events, events);+ assert.ok(existsSync(join(box.data, box.id + '.journal.sqlite')));+ const personMove = await box.call(box.path + '/moves', {+ method: 'POST', token: box.person.token,+ body: { sequence: 2, sealed: box.clientSeal({ person: true }, 'move', 2) },+ });+ assert.deepEqual(personMove.body.event.sender, { kind: 'person', userId: box.person.user.id });+ assert.equal((await box.call(box.path, { method: 'DELETE', token: box.person.token })).status, 200);+});+test('[A4,H7] live streams follow the same order, resume by cursor and stop after revocation', async (t) => {const box = await fixture(t);- await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 0, sealed: box.clientSeal(box.document, 'snapshot', 0) } });+ await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: box.clientSeal(box.document, 'snapshot', 0) } });const controllers = [];t.after(() => { for (const controller of controllers) controller.abort(); });/** Open a live API stream and bound each observation without exposing its credential. */@@ -242,7 +284,7 @@ test('[A4,H7] live streams follow the same order, resume by cursor and stop aftetest('[A4,H7] a bounded large sealed snapshot is independent of the smaller move-body limit', async (t) => {const box = await fixture(t);const document = { record: 'a'.repeat(150_000) };- const uploaded = await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 0, sealed: box.clientSeal(document, 'snapshot', 0) } });+ const uploaded = await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: box.clientSeal(document, 'snapshot', 0) } });assert.equal(uploaded.status, 200);assert.deepEqual(box.clientOpen(uploaded.body.state.sealed, 'snapshot', 0), document);const oversizeMove = await box.call(box.path + '/moves', { method: 'POST', body: { sequence: 1, sealed: box.clientSeal(document, 'move', 1) } });