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.

feat(relay): serve sealed snapshots and ordered moves [A4,H7]

Corey Olson09004eddb7ef
diff --git a/relay/README.md b/relay/README.md
index d8c7905a..bedcec05 100644
--- a/relay/README.md
+++ b/relay/README.md
@@ -67,3 +67,56 @@ it. Call `auth.close()` when the relay shuts down.
`test/relay-github.test.js`, `test/relay.test.js`, and `test/relay-http.test.js` use
real loopback HTTP, generated RSA keys, and private SQLite files. No live GitHub
credentials, repositories, or board databases are needed.
+
+## Sealed API relay
+
+createRelayHandler({ directory, auth, publicOrigin, pollMs }) from service.js
+mounts API v1 on the existing sign-in component. Mount the auth handler first,
+then this handler, on one HTTP server; call the handler's close() at shutdown.
+serveRelay({ directory, auth, port, host, publicOrigin }) is a convenience
+server for these API routes. Its default address is loopback and its default
+port is chosen by the operating system. It does not deploy a public service or
+close the caller-owned auth component.
+
+Per accepted RFC 0004, this service has no board engine or board key. Clients
+seal records before sending them; the server validates only the outer transport
+envelope and stores uninterpreted bytes. A sealed field is canonical base64url.
+The client owns the encryption format and engine-version checks.
+
+- GET /api/v1/boards returns visible board/repository identities.
+- PUT /api/v1/boards/:id/state takes {sequence, sealed}. The first snapshot
+ normally covers sequence 0. A later snapshot may cover only committed moves,
+ cannot move behind the previous snapshot, and removes the covered move prefix.
+- GET /api/v1/boards/:id/state returns
+ {version: 1, state: {sequence, receivedAt, sealed}}.
+- POST /api/v1/boards/:id/moves takes {sealed}. The relay allocates the next
+ sequence atomically and returns {version: 1, event, result: {sequence}}.
+ An event is {event_id, event_at, sealed}. Requests use the same sealed append
+ through POST /api/v1/boards/:id/requests; clients interpret their contents.
+- GET /api/v1/boards/:id/events?after=N returns sealed events in sequence.
+ Accept: text/event-stream follows the same records; Last-Event-ID resumes.
+ A cursor older than the latest snapshot gets SNAPSHOT_REQUIRED (409), naming
+ the need to fetch state and resume after its coverage cursor.
+- DELETE /api/v1/boards/:id removes that board's database and SQLite sidecars.
+ 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,000
+byte JSON-body limit. Snapshots allow a bounded 14,000,000 byte JSON body and
+10,000,000 decoded bytes. One private SQLite journal per board stores only its
+identity, format, head cursor, receive times and sealed payloads. Compaction
+keeps the head cursor, so the next move never reuses an earlier sequence.
+
+Bearer credentials work for agents and CLI calls. Browser session-cookie reads
+require a configured trusted publicOrigin; cookie writes require that exact
+Origin. Duplicate cookies are refused, and neither credentials nor board keys
+are accepted through query parameters. Writes recheck current repository access
+after body reading; live streams recheck the credential between polls. A board
+credential cannot reach another board. Code previews are unavailable on the
+relay: source files stay local.
+
+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 an
+actual loopback sign-in stand-in, and checks order, snapshots, live delivery,
+revocation, deletion and absence of known plaintext/client keys in database
+bytes. Test encryption is client-only; it is not a public client pairing API.
+The relay/ service stays outside the npm package.
diff --git a/relay/journal.js b/relay/journal.js
index fe425628..0c94a1d8 100644
--- a/relay/journal.js
+++ b/relay/journal.js
@@ -42,6 +42,8 @@ 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('INSERT OR IGNORE INTO journal_head (slot,sequence) SELECT 1, COALESCE(MAX(sequence),0) FROM journal_record');
db.exec('COMMIT');
} catch (error) {
try { db.exec('ROLLBACK'); } catch { /* Initialization may have failed before its transaction. */ }
@@ -58,23 +60,31 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
/** Read the latest committed sequence, including an empty journal's initial cursor. */
function latest() {
open();
- return db.prepare('SELECT COALESCE(MAX(sequence), 0) AS sequence FROM journal_record').get().sequence;
+ return db.prepare('SELECT sequence FROM journal_head WHERE slot=1').get().sequence;
}
- /** Serialize the prefix check and append so concurrent senders cannot both claim one sequence. */
- function append(sequence, bytes) {
- open();
- if (!Number.isSafeInteger(sequence) || sequence < 1) throw new Refused('BAD_SEQUENCE', 'upload a positive safe integer sequence');
+ /** Require detached bounded opaque bytes before opening a write transaction. */
+ function payload(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > maxBytes) throw new Refused('BAD_UPLOAD', 'send nonempty opaque bytes within the configured upload limit');
- const payload = Buffer.from(bytes);
+ return Buffer.from(bytes);
+ }
+
+ /** Serialize prefix checking or sequence allocation with the opaque append. */
+ function insert(sequence, bytes) {
+ open();
+ if (sequence !== null && (!Number.isSafeInteger(sequence) || sequence < 1)) throw new Refused('BAD_SEQUENCE', 'upload a positive safe integer sequence');
+ const sealed = payload(bytes);
db.exec('BEGIN IMMEDIATE');
try {
const next = latest() + 1;
+ if (!Number.isSafeInteger(next)) throw new Refused('SEQUENCE_LIMIT', 'link a new board before the journal exhausts safe sequence numbers');
+ if (sequence === null) sequence = next;
if (sequence < next) throw new Refused('SEQUENCE_REPEAT', 'this sequence is already stored; resume after the latest committed sequence');
if (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,payload) VALUES (?,?,?)').run(sequence, at.toISOString(), payload);
+ db.prepare('INSERT INTO journal_record (sequence,received_at,payload) VALUES (?,?,?)').run(sequence, at.toISOString(), sealed);
+ 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');
return result;
@@ -84,6 +94,39 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
}
}
+ /** Append a transport retry only at its explicitly named next sequence. */
+ function append(sequence, bytes) { return insert(sequence, bytes); }
+
+ /** Allocate the next sequence under the same lock as the append, as the live relay requires. */
+ function appendNext(bytes) { return insert(null, bytes); }
+
+ /** Read the latest sealed snapshot without interpreting its contents. */
+ function snapshot() {
+ open();
+ const row = db.prepare('SELECT * FROM journal_snapshot WHERE slot=1').get();
+ return row ? record(row) : null;
+ }
+
+ /** Replace a covered snapshot and compact only its acknowledged prefix, keeping the head. */
+ function saveSnapshot(sequence, bytes) {
+ open();
+ if (!Number.isSafeInteger(sequence) || sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence this snapshot covers');
+ const sealed = payload(bytes);
+ db.exec('BEGIN IMMEDIATE');
+ try {
+ if (sequence > latest()) throw new Refused('SEQUENCE_GAP', 'upload the missing moves before a snapshot that covers them');
+ const previous = snapshot();
+ if (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('DELETE FROM journal_record WHERE sequence <= ?').run(sequence);
+ const result = snapshot();
+ db.exec('COMMIT');
+ return result;
+ } catch (error) { db.exec('ROLLBACK'); throw error; }
+ }
+
/** Replay the committed prefix in order, without parsing or executing its payloads. */
function after(sequence = 0) {
open();
@@ -98,5 +141,5 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
closed = true;
}
- return { board: id, latest, append, after, close };
+ return { board: id, latest, append, appendNext, after, snapshot, saveSnapshot, close };
}
diff --git a/relay/service.js b/relay/service.js
new file mode 100644
index 00000000..d8bdf736
--- /dev/null
+++ b/relay/service.js
@@ -0,0 +1,170 @@
+/** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7]. */
+import { createServer } from 'node:http';
+import { lstatSync, mkdirSync, unlinkSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { createApiHandler, apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js';
+import { Refused } from '../src/refused.js';
+import { createRelayJournal } from './journal.js';
+
+const SNAPSHOT_BODY = 14_000_000;
+const STORED_BYTES = 10_000_000;
+
+/** Validate a board identity before deriving its private, internal database path. */
+function identity(id) {
+ if (typeof id !== 'string' || !/^[0-9a-f]{32}$/.test(id)) throw new Refused('BAD_BOARD', 'use the persistent board id, never a path');
+ return id;
+}
+
+/**
+ * Resolve the existing relay session cookie or bearer boundary. Cookie writes require a configured
+ * exact public Origin; duplicate cookies, URL credentials and client-controlled hosts never win.
+ */
+function credential(req, publicOrigin, write = false) {
+ const authorization = req.headers.authorization;
+ if (authorization) {
+ const match = /^Bearer ((?:ps_|pa_)[A-Za-z0-9_-]{43})$/.exec(String(authorization));
+ if (!match) throw new Refused('AUTH_REQUIRED', 'supply a current relay bearer credential');
+ return match[1];
+ }
+ const cookies = String(req.headers.cookie ?? '').split(';').map((part) => part.trim()).filter((part) => part.startsWith('pb_session='));
+ if (cookies.length !== 1 || !publicOrigin) throw new Refused('AUTH_REQUIRED', 'sign in to the configured relay origin');
+ if (write && req.headers.origin !== publicOrigin) throw new Refused('BAD_ORIGIN', 'send cookie-authorized writes from the configured relay origin');
+ return cookies[0].slice('pb_session='.length);
+}
+
+/** Validate an optional trusted browser origin, never inferring one from a request header. */
+function trustedOrigin(value) {
+ if (value === undefined) return null;
+ let url;
+ try { url = new URL(value); } catch { throw new Refused('RELAY_CONFIG', 'configure the relay public origin'); }
+ if (url.username || url.password || url.pathname !== '/' || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)))) {
+ throw new Refused('RELAY_CONFIG', 'use an HTTPS public origin or a loopback HTTP origin for local tests');
+ }
+ return url.origin;
+}
+
+/** Decode only canonical transport bytes; sealed payloads are never parsed or unsealed. */
+function sealed(body, snapshot = false) {
+ const keys = snapshot ? ['sealed', 'sequence'] : ['sealed'];
+ if (!body || Object.keys(body).some((key) => !keys.includes(key)) || typeof body.sealed !== 'string' || !/^[A-Za-z0-9_-]+$/.test(body.sealed)) {
+ throw new Refused('BAD_UPLOAD', 'send only a nonempty base64url sealed payload, plus sequence for a snapshot; keep keys on your device');
+ }
+ const bytes = Buffer.from(body.sealed, 'base64url');
+ if (bytes.length === 0 || bytes.toString('base64url') !== body.sealed) throw new Refused('BAD_UPLOAD', 'send canonical nonempty base64url bytes sealed on your device');
+ return bytes;
+}
+
+/** 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, 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') }; }
+
+/** Create a private relay handler; the caller owns sign-in lifecycle and service shutdown. */
+export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin }) {
+ 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);
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ const stat = lstatSync(root);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0) throw new Refused('RELAY_STORAGE', 'use a private directory with mode 700 for relay storage');
+
+ /** Open only an existing journal on reads; each synchronous operation closes its connection. */
+ function withJournal(id, work, create = false) {
+ const file = join(root, identity(id) + '.journal.sqlite');
+ if (!create) {
+ try {
+ const entry = lstatSync(file);
+ if (!entry.isFile() || entry.isSymbolicLink()) throw new Refused('RELAY_STORAGE', 'restore this board as a private regular journal');
+ } catch (error) {
+ if (error.code === 'ENOENT') throw new Refused('NO_BOARD', 'upload the sealed snapshot for this linked board first');
+ throw error;
+ }
+ }
+ const journal = createRelayJournal({ directory: root, boardId: id, maxBytes: STORED_BYTES });
+ try { return work(journal); } finally { journal.close(); }
+ }
+
+ /** Append ciphertext under its server-allocated sequence, with no engine or filesystem access. */
+ async function append(board, body, who) {
+ const bytes = sealed(body);
+ await auth.authenticate(who.credential, { board: board.id, write: true });
+ return withJournal(board.id, (journal) => {
+ const row = journal.appendNext(bytes);
+ return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };
+ });
+ }
+
+ const common = createApiHandler({
+ authenticate: async (req, { board, write }) => {
+ const token = credential(req, origin, write);
+ return board === null ? { visible: await auth.boardsFor(token) }
+ : { ...await auth.authenticate(token, { board: identity(board), write }), credential: token };
+ },
+ boards: (who) => who.visible,
+ board: (id) => { withJournal(id, () => undefined); return { id }; },
+ state: (board) => withJournal(board.id, (journal) => {
+ const snapshot = journal.snapshot();
+ if (!snapshot) throw new Refused('NO_SNAPSHOT', 'upload a sealed snapshot before reading this board');
+ return state(snapshot);
+ }),
+ events: (board, after) => withJournal(board.id, (journal) => {
+ const snapshot = journal.snapshot();
+ if (snapshot && after < snapshot.sequence) throw new Refused('SNAPSHOT_REQUIRED', 'fetch the latest sealed state, then resume after its sequence');
+ return journal.after(after).map(event);
+ }),
+ move: append,
+ request: async (board, body, who) => (await append(board, body, who)).body,
+ }, { pollMs });
+
+ /** Add authenticated snapshot replacement and deletion to the common versioned read/move paths. */
+ async function handle(req, res) {
+ try {
+ let 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'); }
+ const snapshot = /^\/api\/v1\/boards\/([^/]+)\/state$/.exec(url.pathname);
+ const 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 });
+ const body = await readApiBody(req, { maxBytes: SNAPSHOT_BODY });
+ const bytes = sealed(body, true);
+ 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);
+ 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 });
+ withJournal(id, () => undefined);
+ const file = join(root, id + '.journal.sqlite');
+ for (const suffix of ['', '-wal', '-shm']) {
+ try { unlinkSync(file + suffix); } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ }
+ return apiJson(res, 200, { deleted: id });
+ }
+ return await common(req, res);
+ } catch (error) {
+ if (!res.headersSent) apiJson(res, apiStatus(error), apiRefusal(error));
+ else res.end();
+ }
+ }
+ handle.close = () => common.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 }) {
+ const handler = createRelayHandler({ directory, auth, pollMs, publicOrigin });
+ const server = createServer(handler);
+ server.requestTimeout = 15_000;
+ return new Promise((ready, fail) => {
+ server.once('error', (error) => { handler.close(); fail(new Refused(error.code === 'EADDRINUSE' ? 'PORT_BUSY' : 'RELAY_LISTEN', 'cannot listen on the configured relay address; choose a free port and retry')); });
+ server.listen(port, host, () => ready({
+ port: server.address().port,
+ close: () => new Promise((done) => { handler.close(); server.close(done); server.closeAllConnections(); }),
+ }));
+ });
+}
diff --git a/src/api-http.js b/src/api-http.js
index 02483780..7a87aa60 100644
--- a/src/api-http.js
+++ b/src/api-http.js
@@ -16,15 +16,16 @@ function json(res, status, value) {
}
/** Read a bounded JSON object, draining oversize requests so a refusal reaches the caller. */
-async function readBody(req) {
+async function readBody(req, { maxBytes = BODY_BYTES } = {}) {
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 20_000_000) throw new TypeError('API body limit needs a positive safe integer no larger than twenty million');
if (!/^application\/json(?:\s*;|$)/i.test(String(req.headers['content-type'] ?? ''))) throw new Refused('BAD_REQUEST', 'send an application/json object as the request body');
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
- if (size <= BODY_BYTES) chunks.push(chunk);
+ if (size <= maxBytes) chunks.push(chunk);
}
- if (size > BODY_BYTES) throw new Refused('BAD_REQUEST', 'the body exceeds ' + BODY_BYTES + ' bytes; send one move or request at a time');
+ if (size > maxBytes) throw new Refused('BAD_REQUEST', 'the body exceeds ' + maxBytes + ' bytes; send one move or request at a time');
let value;
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new Refused('BAD_REQUEST', 'the body is not JSON; send an application/json object'); }
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Refused('BAD_REQUEST', 'the body needs a JSON object; send one move or request at a time');
@@ -129,7 +130,7 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
if (req.method === 'POST' && route[2] === 'requests') return json(res, 200, await adapter.request(board, await readBody(req), who));
return json(res, 400, refusal(new Refused('BAD_REQUEST', 'use GET for reads and POST for moves and requests')));
} catch (error) {
- const status = { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, WRITE_REQUIRED: 403, NO_BOARD: 404, BOARD_NOT_LINKED: 404 }[error.code] ?? (error instanceof Refused ? 400 : 500);
+ const status = apiStatus(error);
if (!res.headersSent) json(res, status, refusal(error));
else res.end();
}
@@ -137,3 +138,12 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
handle.close = () => { for (const res of streams) res.end(); };
return handle;
}
+
+
+/** 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 }[error.code] ?? (error instanceof Refused ? 400 : 500);
+}
+
+// Relay-only snapshot/delete routes reuse the exact shared bounded-body and refusal boundary.
+export { json as apiJson, refusal as apiRefusal, readBody as readApiBody };
diff --git a/test/relay-journal.test.js b/test/relay-journal.test.js
index 1af8836d..956042cc 100644
--- a/test/relay-journal.test.js
+++ b/test/relay-journal.test.js
@@ -75,7 +75,7 @@ test('[A4,H7] two real processes cannot publish the same next sequence', async (
'import { createRelayJournal } from ' + JSON.stringify(module) + ';',
'const journal = createRelayJournal({ directory: process.argv[2], boardId: process.argv[3] });',
'try {',
- ' const row = journal.append(1, Buffer.from(process.argv[4]));',
+ ' const row = process.argv[4].startsWith("auto ") ? journal.appendNext(Buffer.from(process.argv[4])) : journal.append(1, Buffer.from(process.argv[4]));',
' process.stdout.write(JSON.stringify({ sequence: row.sequence }));',
'} catch (error) { process.stdout.write(JSON.stringify({ code: error.code })); }',
'finally { journal.close(); }',
@@ -104,6 +104,11 @@ test('[A4,H7] two real processes cannot publish the same next sequence', async (
assert.equal(journal.latest(), 1);
assert.equal(journal.after().length, 1);
assert.ok(['first record', 'second record'].includes(journal.after()[0].bytes.toString()));
+ journal.close();
+ const allocated = await Promise.all([run('auto first'), run('auto second')]);
+ assert.deepEqual(allocated.map((row) => row.sequence).sort(), [2, 3]);
+ const ordered = box.open();
+ assert.deepEqual(ordered.after().map((row) => row.sequence), [1, 2, 3]);
});
test('[H7] board identities isolate journals and cannot follow a symlink', (t) => {
@@ -120,3 +125,30 @@ test('[H7] board identities isolate journals and cannot follow a symlink', (t) =
box.journal.close();
assert.throws(() => box.journal.latest(), { code: 'RELAY_CLOSED' });
});
+
+
+test('[A4,H7] a sealed snapshot compacts its prefix without reusing sequence numbers', (t) => {
+ const box = fixture(t);
+ assert.equal(box.journal.snapshot(), null);
+ box.journal.saveSnapshot(0, Buffer.from('initial opaque snapshot'));
+ box.journal.appendNext(Buffer.from('opaque move one'));
+ box.journal.appendNext(Buffer.from('opaque move two'));
+ box.journal.appendNext(Buffer.from('opaque move three'));
+ box.journal.saveSnapshot(2, Buffer.from('snapshot through two'));
+ assert.equal(box.journal.snapshot().sequence, 2);
+ 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);
+ assert.throws(() => box.journal.saveSnapshot(1, Buffer.from('stale')), { code: 'SNAPSHOT_STALE' });
+ assert.throws(() => box.journal.saveSnapshot(4, Buffer.from('gap')), { code: 'SEQUENCE_GAP' });
+ assert.equal(box.journal.snapshot().sequence, 2);
+ assert.deepEqual(box.journal.after().map((row) => row.sequence), [3]);
+ box.journal.saveSnapshot(3, Buffer.from('snapshot through three'));
+ assert.deepEqual(box.journal.after(), []);
+ box.journal.close();
+ const restarted = box.open();
+ assert.equal(restarted.latest(), 3);
+ assert.equal(restarted.snapshot().sequence, 3);
+ assert.equal(restarted.appendNext(Buffer.from('move after compaction')).sequence, 4);
+ assert.throws(() => restarted.append(2, Buffer.from('retry old prefix')), { code: 'SEQUENCE_REPEAT' });
+});
diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.js
new file mode 100644
index 00000000..18ffaf85
--- /dev/null
+++ b/test/relay-sealed.test.js
@@ -0,0 +1,222 @@
+/** 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 { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { test } from 'node:test';
+import { serveRelay } from '../relay/service.js';
+import { createRelayAuth } from '../relay/auth.js';
+import { createGitHubClient } from '../relay/github.js';
+import { githubFixture } from './relay-fixture.js';
+
+/** Seal on the test client only; nonce, authentication tag and ciphertext are opaque to the server. */
+function seal(key, value) {
+ const nonce = randomBytes(12);
+ const cipher = createCipheriv('aes-256-gcm', key, nonce);
+ const bytes = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);
+ return Buffer.concat([nonce, cipher.getAuthTag(), bytes]).toString('base64url');
+}
+
+/** Open on the test client only, proving that received ciphertext still represents the sent record. */
+function unseal(key, value) {
+ const bytes = Buffer.from(value, 'base64url');
+ const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12));
+ decipher.setAuthTag(bytes.subarray(12, 28));
+ return JSON.parse(Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString());
+}
+
+/** Create a real private CLI board, actual stand-in GitHub sign-in, and an ephemeral relay server. */
+async function fixture(t) {
+ const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-sealed-http-')));
+ const root = join(directory, 'repo');
+ const home = join(directory, 'home');
+ 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' };
+ 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. */
+ function cli(...args) {
+ const result = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args], { cwd: root, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ return result.stdout;
+ }
+ cli('init');
+ const config = JSON.parse(readFileSync(join(root, 'pullboard.json'), 'utf8'));
+ const marker = 'PRIVATE_BOARD_CRITERION_DO_NOT_RELAY_IN_CLEAR';
+ cli('add', Object.keys(config.lanes)[0], 'A sealed board item', '--criterion', marker);
+ const document = JSON.parse(cli('export'));
+ const id = document.tables.board_meta.find((row) => row.meta_key === 'board_id').meta_value;
+ const provider = await githubFixture(t);
+ const auth = createRelayAuth({ database: join(directory, 'auth.sqlite'), github: createGitHubClient(provider.config) });
+ const flow = auth.beginWeb();
+ const redirect = await fetch(flow.authorizationURL, { redirect: 'manual' });
+ const callback = new URL(redirect.headers.get('location'));
+ const person = await auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), flow.binding);
+ await auth.linkBoard(person.token, id, 'fixture/repository');
+ const one = await auth.issueToken(person.token, { board: id, agent: 'client-one' });
+ const two = await auth.issueToken(person.token, { board: id, agent: 'client-two' });
+ const relay = await serveRelay({ directory: data, auth, port: 0, pollMs: 20, publicOrigin: 'http://127.0.0.1:44444' });
+ t.after(async () => { await relay.close(); auth.close(); rmSync(directory, { recursive: true, force: true }); });
+ const origin = 'http://127.0.0.1:' + relay.port;
+ const key = randomBytes(32);
+
+ /** Send one private API call without putting credentials or board keys in its URL or diagnostics. */
+ async function call(path, { method = 'GET', body, token = one.token, headers = {} } = {}) {
+ const response = await fetch(origin + path, {
+ method,
+ headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...headers },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json() };
+ }
+ return { directory, root, data, cli, document, id, marker, auth, person, one, two, relay, origin, key, call, path: '/api/v1/boards/' + id };
+}
+
+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');
+ assert.equal(listed.status, 200);
+ assert.deepEqual(listed.body.boards, [{ id: box.id, repository: 'fixture/repository' }]);
+ const initial = seal(box.key, box.document);
+ const uploaded = await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 0, sealed: initial } });
+ assert.equal(uploaded.status, 200);
+ assert.equal(uploaded.body.version, 1);
+ assert.deepEqual(unseal(box.key, uploaded.body.state.sealed), box.document);
+ const sent = [
+ { client: 'one', title: 'PRIVATE_MOVE_FROM_CLIENT_ONE' },
+ { client: 'two', title: 'PRIVATE_MOVE_FROM_CLIENT_TWO' },
+ ];
+ const results = await Promise.all(sent.map((move, index) => box.call(box.path + '/moves', {
+ method: 'POST', token: index ? box.two.token : box.one.token, body: { sealed: seal(box.key, move) },
+ })));
+ assert.ok(results.every((reply) => reply.status === 200 && reply.body.version === 1));
+ assert.deepEqual(results.map((reply) => reply.body.event.event_id).sort(), [1, 2]);
+ const read = await box.call(box.path + '/events?after=0');
+ assert.deepEqual(read.body.events.map((row) => row.event_id), [1, 2]);
+ assert.deepEqual(read.body.events.map((row) => unseal(box.key, row.sealed)).sort((a, b) => a.client.localeCompare(b.client)), sent);
+ const bytes = Buffer.concat(readdirSync(box.data).map((file) => readFileSync(join(box.data, file))));
+ for (const text of [box.marker, ...sent.map((move) => move.title), box.root]) {
+ assert.equal(bytes.includes(Buffer.from(text)), false, 'a known client plaintext must never occur in relay database bytes');
+ }
+ assert.equal(bytes.includes(box.key), false, 'the client key must never occur in relay database bytes');
+ assert.deepEqual(JSON.parse(box.cli('export')), box.document, 'the complete local board remains unchanged');
+});
+
+test('[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: seal(box.key, box.document) } });
+ for (let n = 1; n <= 3; n++) {
+ const reply = await box.call(box.path + '/moves', { method: 'POST', body: { sealed: seal(box.key, { move: n }) } });
+ assert.equal(reply.body.event.event_id, n);
+ }
+ const compacted = await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 2, sealed: seal(box.key, { covered: 2 }) } });
+ assert.equal(compacted.status, 200);
+ assert.equal(compacted.body.state.sequence, 2);
+ assert.deepEqual(unseal(box.key, (await box.call(box.path + '/state')).body.state.sealed), { covered: 2 });
+ const oldCursor = await box.call(box.path + '/events?after=0');
+ assert.equal(oldCursor.status, 409);
+ assert.equal(oldCursor.body.error.code, 'SNAPSHOT_REQUIRED');
+ assert.deepEqual((await box.call(box.path + '/events?after=2')).body.events.map((row) => row.event_id), [3]);
+ const next = await box.call(box.path + '/moves', { method: 'POST', body: { sealed: seal(box.key, { move: 4 }) } });
+ assert.equal(next.body.event.event_id, 4);
+ const other = 'f'.repeat(32) === box.id ? 'e'.repeat(32) : 'f'.repeat(32);
+ await 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: seal(box.key, { other: true }) } })).status, 200);
+ assert.equal((await box.call(box.path, { method: 'DELETE' })).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(unseal(box.key, (await box.call(otherPath + '/state', { token: box.person.token })).body.state.sealed), { other: true });
+ assert.deepEqual(JSON.parse(box.cli('export')), box.document);
+});
+
+test('[A4,H7] malformed or unauthorized calls cannot store clear records, keys or another board', async (t) => {
+ const box = await fixture(t);
+ assert.equal((await box.call(box.path + '/state', { token: null })).status, 401);
+ const other = 'b'.repeat(32) === box.id ? 'c'.repeat(32) : 'b'.repeat(32);
+ const wrong = await box.call('/api/v1/boards/' + other + '/state');
+ assert.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: seal(box.key, {}), key: 'client key stays on device' }, { sequence: '0', sealed: seal(box.key, {}) }]) {
+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', body })).status, 400);
+ }
+ assert.deepEqual(readdirSync(box.data), []);
+ await box.call(box.path + '/state', { method: 'PUT', body: { sequence: 0, sealed: seal(box.key, box.document) } });
+ 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: { sealed: seal(box.key, {}) } });
+ assert.equal(deniedCookie.status, 403);
+ assert.equal(deniedCookie.body.error.code, 'BAD_ORIGIN');
+ assert.equal((await box.call(box.path + '/state', { token: null, headers: { cookie: 'pb_session=' + box.person.token } })).status, 200);
+ const cookieMove = await box.call(box.path + '/moves', { method: 'POST', token: null, headers: { cookie: 'pb_session=' + box.person.token, origin: 'http://127.0.0.1:44444' }, body: { sealed: seal(box.key, { cookie: true }) } });
+ assert.equal(cookieMove.status, 200);
+ await box.auth.revoke(box.person.token, box.one.id);
+ assert.equal((await box.call(box.path + '/state')).status, 401);
+});
+
+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: seal(box.key, box.document) } });
+ const controllers = [];
+ t.after(() => { for (const controller of controllers) controller.abort(); });
+ /** Open a live API stream and bound each observation without exposing its credential. */
+ async function stream(last = null) {
+ const controller = new AbortController();
+ controllers.push(controller);
+ const reply = await fetch(box.origin + box.path + '/events?after=0', {
+ headers: { authorization: 'Bearer ' + box.two.token, accept: 'text/event-stream', ...(last === null ? {} : { 'last-event-id': String(last) }) },
+ signal: controller.signal,
+ });
+ assert.equal(reply.status, 200);
+ const reader = reply.body.getReader();
+ let text = '';
+ /** Wait only until the requested synthetic cursor or refusal appears. */
+ async function until(fragment) {
+ const deadline = Date.now() + 3000;
+ while (!text.includes(fragment)) {
+ let timer;
+ const part = await Promise.race([
+ reader.read(),
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('sealed stream timed out')), Math.max(1, deadline - Date.now())); }),
+ ]).finally(() => clearTimeout(timer));
+ assert.equal(part.done, false, 'stream ended before expected delivery');
+ text += Buffer.from(part.value).toString('utf8');
+ }
+ return text;
+ }
+ return { until, cancel: () => reader.cancel() };
+ }
+ const first = await stream();
+ await first.until(': API v1\n');
+ const one = await box.call(box.path + '/moves', { method: 'POST', body: { sealed: seal(box.key, { live: 1 }) } });
+ assert.equal(one.body.event.event_id, 1);
+ const firstText = await first.until('id: 1\n');
+ assert.ok(firstText.includes(JSON.stringify({ version: 1, event: one.body.event })));
+ const resumed = await stream(1);
+ await resumed.until(': API v1\n');
+ const two = await box.call(box.path + '/moves', { method: 'POST', body: { sealed: seal(box.key, { live: 2 }) } });
+ assert.equal(two.body.event.event_id, 2);
+ const resumedText = await resumed.until('id: 2\n');
+ assert.equal(resumedText.includes('id: 1\n'), false);
+ await box.auth.revoke(box.person.token, box.two.id);
+ const revoked = await resumed.until('event: error\n');
+ assert.ok(revoked.includes('"code":"AUTH_REQUIRED"'));
+ await first.cancel();
+ await resumed.cancel();
+});
+
+test('[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: seal(box.key, document) } });
+ assert.equal(uploaded.status, 200);
+ assert.deepEqual(unseal(box.key, uploaded.body.state.sealed), document);
+ const oversizeMove = await box.call(box.path + '/moves', { method: 'POST', body: { sealed: seal(box.key, document) } });
+ assert.equal(oversizeMove.status, 400);
+ assert.equal(oversizeMove.body.error.code, 'BAD_REQUEST');
+ assert.deepEqual((await box.call(box.path + '/events?after=0')).body.events, []);
+ const packageInfo = JSON.parse(readFileSync(resolve(import.meta.dirname, '../package.json'), 'utf8'));
+ assert.equal(packageInfo.files.some((entry) => entry === 'relay' || entry.startsWith('relay/')), false);
+});