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): require current clients after agent tokens [H16,H3]

Corey Olson8e65d06b6ad3
diff --git a/docs/formats.md b/docs/formats.md
index 8ad7d0ee..2e7073e7 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -75,6 +75,14 @@ The board file is in the repository's Git common directory at `.git/pullboard/bo
Pullboard 0.6.1 released engine 1. The first change to released move semantics raises the engine once for the next release; later changes developed before that release keep the same version. Engine 2 records a fresh explicit-build claim's skipped-review snapshot. Older clients refuse engine-2 moves before changing rows or replay cursors; engine 2 still accepts engine-1 moves.
+The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.
+A linked board requires at least engine 3 after issuing any agent token, including
+revoked or expired tokens. The minimum survives reopening the auth database;
+unlink removes the board and ends its lifetime. A missing declaration is legacy
+engine 1. Board-content requests below their minimum, and malformed declarations,
+receive `ENGINE_VERSION` with upgrade guidance before records are returned or
+changed. The service checks again under its board lock and on live-stream polls.
+
Engine 3 checks each move or request against the relay's authenticated sender before replay. An agent token acts only as its named agent and cannot act as the person. Refused attribution attempts advance the sequence with a `relay_refusal_<sequence>` receipt and a `relay_refused` event naming the sender, attempted actor and refusal code. They change no item, shout or verdict and do not reserve the forged operation id. Snapshot restoration requires a person sender. The event log remains version 1.
A board without `event_log_version` is a legacy version-0 event log. Opening an older board writes the current marker without replacing its events. Opening a newer event log refuses with `EVENT_LOG_VERSION`, naming the stored and supported versions and asking you to upgrade Pullboard. `doctor` reports that version conflict read-only.
diff --git a/relay/README.md b/relay/README.md
index 8fbfdf4a..3a8bdabe 100644
--- a/relay/README.md
+++ b/relay/README.md
@@ -159,6 +159,16 @@ byte JSON-body limit. Snapshots allow a bounded 14,000,000 byte JSON body and
identity, format, head cursor, receive times, public sender identities and sealed payloads. Compaction
keeps the head cursor, so the next move never reuses an earlier sequence.
+Every CLI relay request carries `X-Pullboard-Engine` with its executable engine
+version. Board-content requests require engine 3 once the board has issued any
+agent token. Revocation, expiry and a service restart do not lower that minimum;
+unlink ends that board lifetime. Boards without agent tokens remain compatible
+with engine 1 and 2. An omitted header means legacy engine 1; a malformed or
+older declaration receives `ENGINE_VERSION` with upgrade guidance before any
+record is read, accepted or deleted. Live streams recheck this minimum between
+polls. Listing board identities and signing in do not expose sealed records and
+remain available to older clients.
+
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
diff --git a/relay/auth.js b/relay/auth.js
index c220f321..a94b6f0a 100644
--- a/relay/auth.js
+++ b/relay/auth.js
@@ -1,4 +1,4 @@
-/** Hash-only relay sessions and board credentials, authorized by current GitHub roles [H8, H1, H13, H14]. */
+/** Hash-only relay sessions and board credentials, authorized by current GitHub roles [H8, H1, H13, H14, H16, H3]. */
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
import { chmodSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
@@ -273,6 +273,12 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
}
return visible;
},
+ /** Keep the minimum replay engine at three after any agent token, including revoked or expired tokens. */
+ minimumEngineVersion(board) {
+ open();
+ identifier(board, 'BAD_BOARD');
+ return db.prepare("SELECT 1 FROM relay_credentials WHERE board=? AND kind='board' LIMIT 1").get(board) ? 3 : 1;
+ },
/** Mint an agent credential scoped to a single readable board and immutable human identity. */
async issueToken(token, { board, agent, expiresIn = tokenTTL }) {
identifier(board, 'BAD_BOARD');
diff --git a/relay/service.js b/relay/service.js
index a0afcf95..4bbb664c 100644
--- a/relay/service.js
+++ b/relay/service.js
@@ -1,4 +1,4 @@
-/** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7]. */
+/** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7,H16,H3]. */
import { createServer } from 'node:http';
import { lstatSync, mkdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
@@ -98,6 +98,23 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
return who;
}
+ /** Refuse an old or ambiguous client before the opaque journal can return or accept board records. */
+ async function authorizedRequest(req, id, write = false) {
+ const who = await authorized(credential(req, origin, write), id, write);
+ const declared = req.headers['x-pullboard-engine'];
+ const version = declared === undefined ? 1 : typeof declared === 'string' && /^[1-9][0-9]*$/.test(declared) ? Number(declared) : NaN;
+ requireClientVersion(id, version);
+ return { ...who, engineVersion: version };
+ }
+
+ /** Recheck the minimum under the board lock so issuing a token cannot race a record read or write. */
+ function requireClientVersion(id, version) {
+ const minimum = auth.minimumEngineVersion(id);
+ if (!Number.isSafeInteger(version) || version < minimum) {
+ throw new Refused('ENGINE_VERSION', `this board requires engine version ${minimum} or newer; upgrade pullboard before reading or sending relay records`);
+ }
+ }
+
/** Add an authorized next-contact warning without exposing any plaintext board contents. */
function annotated(row, id) {
const warning = retention.notice(id);
@@ -105,7 +122,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
}
/** Open only an existing journal on reads; each synchronous operation closes its connection. */
- function withJournal(id, work, create = false) {
+ function withJournal(id, work, create = false, engineVersion) {
const file = join(root, identity(id) + '.journal.sqlite');
if (!create) {
try {
@@ -117,6 +134,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
}
}
return auth.withBoard(id, () => {
+ requireClientVersion(id, engineVersion);
const journal = createRelayJournal({ directory: root, boardId: id, maxBytes: STORED_BYTES, now: () => new Date(now()) });
try { return work(journal); } finally { journal.close(); }
});
@@ -130,31 +148,31 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
return withJournal(board.id, (journal) => {
const row = journal.append(body.sequence, bytes, kind, principal);
return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };
- });
+ }, false, who.engineVersion);
}
const common = createApiHandler({
authenticate: async (req, { board, write }) => {
const token = credential(req, origin, write);
return board === null ? { visible: await auth.boardsFor(token) }
- : { ...await authorized(token, board, write), credential: token };
+ : { ...await authorizedRequest(req, board, write), credential: token };
},
boards: (who) => {
const boards = who.visible.filter((board) => !retention.expire(board.id));
const warnings = boards.map((board) => retention.notice(board.id)).filter(Boolean);
return { boards, ...(warnings.length ? { warnings } : {}) };
},
- board: (id) => { withJournal(id, () => undefined); return { id }; },
+ board: (id, who) => { withJournal(id, () => undefined, false, who.engineVersion); return { id, engineVersion: who.engineVersion }; },
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 annotated(snapshot, board.id);
- }),
+ }, false, board.engineVersion),
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);
- }),
+ }, false, board.engineVersion),
warning: (board) => retention.notice(board.id),
move: append,
request: async (board, body, who) => (await append(board, body, who, 'request')).body,
@@ -170,18 +188,20 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
const deletion = /^\/api\/v1\/boards\/([^/]+)$/.exec(url.pathname);
if (req.method === 'PUT' && snapshot) {
const id = identity(snapshot[1]);
- sender(await authorized(credential(req, origin, true), id, true), true);
+ sender(await authorizedRequest(req, id, 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');
- const principal = sender(await authorized(credential(req, origin, true), id, true), true);
- const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes, principal), true);
+ const who = await authorizedRequest(req, id, true);
+ const principal = sender(who, true);
+ const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes, principal), true, who.engineVersion);
return apiJson(res, 200, { state: annotated(saved, id) });
}
if (req.method === 'DELETE' && deletion) {
const id = identity(deletion[1]);
- sender(await authorized(credential(req, origin, true), id, true), true);
- retention.unlink(id);
+ const who = await authorizedRequest(req, id, true);
+ sender(who, true);
+ auth.withBoard(id, () => { requireClientVersion(id, who.engineVersion); retention.unlink(id); });
return apiJson(res, 200, { deleted: id });
}
return await common(req, res);
diff --git a/src/relay.js b/src/relay.js
index ed0f9340..6b25809d 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -118,7 +118,7 @@ async function request(state, path, { method = 'GET', body, allowMissing = false
try {
response = await fetch(relayOrigin(state.url) + path, {
method, redirect: 'error', signal: AbortSignal.timeout(10000),
- headers: { ...(state.token ? { authorization: 'Bearer ' + state.token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(state.token ? { authorization: 'Bearer ' + state.token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
} catch { throw new Refused('RELAY_UNAVAILABLE', `the relay ${state.url} did not answer; read the local board offline, then retry this move when the relay is reachable`); }
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.js
index b1ed883f..e05e031c 100644
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@ -63,7 +63,7 @@ export async function relayClientFixture(t) {
let api;
const calls = [];
const server = createServer(async (req, res) => {
- calls.push({ method: req.method, path: req.url });
+ calls.push({ method: req.method, path: req.url, engine: req.headers['x-pullboard-engine'] });
if (override && req.method === 'DELETE') {
res.writeHead(override.status, { 'content-type': 'application/json' });
res.end(JSON.stringify({ version: override.version ?? 1, error: { code: override.code, message: 'fixture refusal' } }));
diff --git a/test/relay-client.test.js b/test/relay-client.test.js
index b1129089..06109d9f 100644
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@ -192,7 +192,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
/** Fetch a public sealed document and authenticate it locally with the device-only key. */
async function get(path) {
- const response = await fetch(relay.origin + path, { headers: { authorization: `Bearer ${person.token}` } });
+ const response = await fetch(relay.origin + path, { headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}` } });
return { status: response.status, body: await response.json() };
}
const remoteState = await get(`/api/v1/boards/${boardId}/state`);
@@ -286,7 +286,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
assert.equal(off.linked, false);
assert.deepEqual((await cli(root, env, 'export')).tables, localBeforeOff.tables, 'unlink leaves local rows and counters unchanged');
assert.deepEqual(await auth.boardsFor(person.token), [], 'unlink removes the repository link');
- const session = await fetch(relay.origin + '/auth/session', { headers: { authorization: `Bearer ${person.token}` } });
+ const session = await fetch(relay.origin + '/auth/session', { headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}` } });
assert.equal(session.status, 200, 'unlink preserves the person session');
assert.equal((await get(`/api/v1/boards/${boardId}/state`)).status, 404);
assert.equal(readdirSync(relayDirectory).some((name) => name.startsWith(boardId + '.journal.sqlite')), false,
@@ -416,7 +416,7 @@ test('[H3,H16] two cloned linked replicas order competing claims and retain the
boardId, kind: 'snapshot', sequence: 0,
})).toString('base64url');
const uploaded = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, {
- method: 'PUT', headers: { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ method: 'PUT', headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
body: JSON.stringify({ sequence: 0, sealed }),
});
assert.equal(uploaded.status, 200, await uploaded.text());
@@ -503,7 +503,7 @@ test('[H3,H16] two cloned linked replicas order competing claims and retain the
const earlierSealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(earlier)), {
boardId, kind: 'move', sequence: next,
})).toString('base64url');
- const headers = { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' };
+ const headers = { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' };
assert.equal((await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {
method: 'POST', headers, body: JSON.stringify({ sequence: next, sealed: earlierSealed }),
})).status, 200);
@@ -601,7 +601,7 @@ async function legacyMirrorQueueFragment({
assert.deepEqual(localEvents(boardFile), queuedRows, 'migration checkpoints existing rows instead of replaying them');
assert.deepEqual(relay.uploads.slice(initialUploadCount).map((upload) => upload.sequence), [4, 5]);
- const authorization = { authorization: `Bearer ${currentPersonToken}` };
+ const authorization = { 'x-pullboard-engine': '3', authorization: `Bearer ${currentPersonToken}` };
const stateResponse = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, { headers: authorization });
assert.equal(stateResponse.status, 200);
const stateDocument = await stateResponse.json();
@@ -636,7 +636,7 @@ async function legacyForeignPrefixFragment({
const foreign = await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {
method: 'POST',
- headers: { authorization: `Bearer ${currentPersonToken}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${currentPersonToken}`, 'content-type': 'application/json' },
body: JSON.stringify({ sequence: link.sequence + 1, sealed: 'AQ' }),
});
assert.equal(foreign.status, 200, await foreign.text());
diff --git a/test/relay-retention.test.js b/test/relay-retention.test.js
index 239c52b5..4bc24a69 100644
--- a/test/relay-retention.test.js
+++ b/test/relay-retention.test.js
@@ -60,7 +60,7 @@ async function fixture(t) {
/** Return status/body without ever placing credentials in diagnostic text or URLs. */
async function call(id, { path = '/state', method = 'GET', token = signed.token, body } = {}) {
const response = await fetch('http://127.0.0.1:' + relay.port + '/api/v1/boards' + (id ? '/' + id + path : ''), {
- method, headers: { authorization: 'Bearer ' + token, ...(body ? { 'content-type': 'application/json' } : {}) },
+ method, headers: { 'x-pullboard-engine': '3', authorization: 'Bearer ' + token, ...(body ? { 'content-type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
return { status: response.status, body: await response.json() };
@@ -88,7 +88,7 @@ test('[H18] warnings begin at sixty days on authorized contact; compaction and r
warningTimeout.unref();
t.after(() => { clearTimeout(warningTimeout); controller.abort(); });
const stream = await fetch('http://127.0.0.1:' + box.relay.port + '/api/v1/boards/' + A + '/events?after=0', {
- headers: { authorization: 'Bearer ' + box.signed.token, accept: 'text/event-stream' }, signal: controller.signal,
+ headers: { 'x-pullboard-engine': '3', authorization: 'Bearer ' + box.signed.token, accept: 'text/event-stream' }, signal: controller.signal,
});
const reader = stream.body.getReader();
let delivered = '';
diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.js
index 48afe0bd..d3207aa3 100644
--- a/test/relay-sealed.test.js
+++ b/test/relay-sealed.test.js
@@ -75,7 +75,7 @@ async function fixture(t) {
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 },
+ headers: { 'x-pullboard-engine': '3', ...(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() };
@@ -327,7 +327,7 @@ test('[A4,H7] live streams follow the same order, resume by cursor and stop afte
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) }) },
+ headers: { 'x-pullboard-engine': '3', authorization: 'Bearer ' + box.two.token, accept: 'text/event-stream', ...(last === null ? {} : { 'last-event-id': String(last) }) },
signal: controller.signal,
});
assert.equal(reply.status, 200);
diff --git a/test/relay-version.test.js b/test/relay-version.test.js
new file mode 100644
index 00000000..a7cf1b5c
--- /dev/null
+++ b/test/relay-version.test.js
@@ -0,0 +1,122 @@
+/** Real authenticated client version gates before opaque board records [H16,H3]. */
+import assert from 'node:assert/strict';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { createRelayAuth } from '../relay/auth.js';
+import { createGitHubClient } from '../relay/github.js';
+import { serveRelay } from '../relay/service.js';
+import { githubFixture } from './relay-fixture.js';
+
+const A = 'a'.repeat(32); // no board credential has ever existed
+const B = 'b'.repeat(32); // historical board credential, even after revocation
+
+test('relay enforces the minimum engine ever required by each board [H16,H3]', async t => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-relay-version-'));
+ const provider = await githubFixture(t);
+ let time = Date.now();
+ const authConfig = { database: join(directory, 'auth.sqlite'), github: createGitHubClient(provider.config), now: () => time };
+ let auth = createRelayAuth(authConfig);
+ const flow = auth.beginWeb();
+ const grant = await fetch(flow.authorizationURL, { redirect: 'manual' });
+ const callback = new URL(grant.headers.get('location'));
+ const person = await auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), flow.binding);
+ await auth.linkBoard(person.token, A, 'fixture/repository');
+ await auth.linkBoard(person.token, B, 'fixture/repository');
+ const historical = await auth.issueToken(person.token, { board: B, agent: 'once-issued', expiresIn: 1 });
+ await auth.revoke(person.token, historical.id);
+ time += 10;
+ assert.equal(auth.minimumEngineVersion(A), 1);
+ assert.equal(auth.minimumEngineVersion(B), 3);
+ auth.close();
+ auth = createRelayAuth(authConfig);
+ assert.equal(auth.minimumEngineVersion(B), 3, 'the minimum survives revocation, expiry and reopening the real auth database');
+ const relay = await serveRelay({ directory: join(directory, 'data'), auth, maintenanceMs: 0, pollMs: 10 });
+ t.after(async () => { await relay.close(); auth.close(); rmSync(directory, { recursive: true, force: true }); });
+ const base = `http://127.0.0.1:${relay.port}/api/v1/boards/`;
+ const opaque = Buffer.from('opaque-test-ciphertext').toString('base64url');
+ /** Read or mutate only this private relay with an explicit client engine declaration. */
+ async function call(board, path = '/state', { engine, method = 'GET', body, token = person.token, accept } = {}) {
+ const headers = { authorization: `Bearer ${token}`, ...(engine === undefined ? {} : { 'x-pullboard-engine': String(engine) }),
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(accept ? { accept } : {}) };
+ const response = await fetch(base + board + path, { method, headers, ...(body === undefined ? {} : { body }) });
+ const text = await response.text();
+ let document;
+ try { document = JSON.parse(text); } catch { document = null; }
+ return { status: response.status, text, document, response };
+ }
+ // Seed opaque snapshots so eligible reads reach actual state and event handlers.
+ for (const board of [A, B]) {
+ const seeded = await call(board, '/state', { engine: 3, method: 'PUT', body: JSON.stringify({ sequence: 0, sealed: opaque }) });
+ assert.equal(seeded.status, 200, seeded.text);
+ }
+
+ for (const board of [A, B]) {
+ assert.equal((await call(board, '/state', { engine: 3 })).status, 200);
+ assert.equal((await call(board, '/events?after=0', { engine: 3 })).status, 200);
+ }
+ for (const board of [A, B]) {
+ const controller = new AbortController();
+ const streamed = await fetch(base + board + '/events?after=0', {
+ headers: { authorization: `Bearer ${person.token}`, 'x-pullboard-engine': '3', accept: 'text/event-stream' }, signal: controller.signal,
+ });
+ assert.equal(streamed.status, 200);
+ await streamed.body.cancel(); controller.abort();
+ }
+
+ assert.equal((await call(A, '/state', { engine: 2 })).status, 200, 'an unclaimed legacy board remains readable by engine 2');
+ assert.equal((await call(A, '/events?after=0', { engine: 2 })).status, 200);
+ for (const path of ['/state', '/events?after=0', '/moves', '/requests']) {
+ const method = path === '/state' ? 'GET' : path.startsWith('/events') ? 'GET' : 'POST';
+ const blocked = await call(B, path, { engine: 2, method, body: method === 'POST' ? 'this body must never be parsed' : undefined });
+ assert.equal(blocked.status, 400, blocked.text);
+ assert.equal(blocked.document?.error?.code, 'ENGINE_VERSION', blocked.text);
+ assert.match(blocked.document.error.message + ' ' + (blocked.document.error.next ?? ''), /upgrade/i);
+ assert.equal(blocked.text.includes(opaque), false, 'no stored ciphertext reaches the old client');
+ }
+ for (const [path, method] of [['/state', 'PUT'], ['', 'DELETE']]) {
+ const blocked = await call(B, path, { engine: 2, method, body: method === 'PUT' ? 'not-json' : undefined });
+ assert.equal(blocked.status, 400, blocked.text);
+ assert.equal(blocked.document?.error?.code, 'ENGINE_VERSION', 'the version gate precedes write-body parsing or deletion');
+ }
+ const oldStream = await call(B, '/events?after=0', { engine: 2, accept: 'text/event-stream' });
+ assert.equal(oldStream.status, 400);
+ assert.equal(oldStream.document.error.code, 'ENGINE_VERSION');
+ const legacyA = await call(A, '/state');
+ assert.equal(legacyA.status, 200, 'missing header is legacy engine 1 where no agent was ever issued');
+ const legacyB = await call(B, '/state');
+ assert.equal(legacyB.document?.error?.code, 'ENGINE_VERSION');
+ for (const malformed of ['2, 3', 'not-an-integer']) {
+ const refused = await call(B, '/state', { engine: malformed });
+ assert.equal(refused.document?.error?.code, 'ENGINE_VERSION');
+ }
+
+ // Engine 2 can still perform each supported write against the unclaimed board.
+ assert.equal((await call(A, '/moves', { engine: 2, method: 'POST', body: JSON.stringify({ sequence: 1, sealed: opaque }) })).status, 200);
+ assert.equal((await call(A, '/requests', { engine: 2, method: 'POST', body: JSON.stringify({ sequence: 2, sealed: opaque }) })).status, 200);
+ assert.equal((await call(A, '/state', { engine: 2, method: 'PUT', body: JSON.stringify({ sequence: 2, sealed: opaque }) })).status, 200);
+ const deleted = await call(A, '', { engine: 2, method: 'DELETE' });
+ assert.equal(deleted.status, 200, deleted.text);
+
+ // A new board lifetime starts at the legacy minimum; issuing a token stops its already-open old stream.
+ await auth.linkBoard(person.token, A, 'fixture/repository');
+ assert.equal((await call(A, '/state', { engine: 2, method: 'PUT', body: JSON.stringify({ sequence: 0, sealed: opaque }) })).status, 200);
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 5000);
+ t.after(() => { clearTimeout(timeout); controller.abort(); });
+ const live = await fetch(base + A + '/events?after=0', { headers: { authorization: `Bearer ${person.token}`, 'x-pullboard-engine': '2', accept: 'text/event-stream' }, signal: controller.signal });
+ assert.equal(live.status, 200);
+ const reader = live.body.getReader();
+ let received = new TextDecoder().decode((await reader.read()).value);
+ await auth.issueToken(person.token, { board: A, agent: 'new-agent' });
+ for (;;) {
+ const part = await reader.read();
+ if (part.done) break;
+ received += new TextDecoder().decode(part.value);
+ }
+ assert.match(received, /event: error/);
+ assert.match(received, /ENGINE_VERSION/);
+ assert.doesNotMatch(received, new RegExp(opaque), 'the now-old stream closes without returning stored records');
+ clearTimeout(timeout);
+});
diff --git a/test/relay.test.js b/test/relay.test.js
index 1dd10663..541d5f16 100644
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@ -4,6 +4,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { test } from 'node:test';
+import { ENGINE_VERSION } from '../src/machine.js';
import { createGitHubClient } from '../relay/github.js';
import { createRelayAuth, ACCESS_WINDOW_MS } from '../relay/auth.js';
import { serveRelay } from '../relay/service.js';
@@ -150,7 +151,7 @@ test('revoking a board credential while its upload body is open stores nothing [
const origin = `http://127.0.0.1:${service.port}`;
const snapshot = await fetch(`${origin}/api/v1/boards/${board}/state`, {
method: 'PUT',
- headers: { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
body: JSON.stringify({ sequence: 0, sealed: 'AQ' }),
});
assert.equal(snapshot.status, 200);
@@ -170,7 +171,7 @@ test('revoking a board credential while its upload body is open stores nothing [
let stream;
const upload = fetch(`${origin}/api/v1/boards/${board}/moves`, {
method: 'POST',
- headers: { authorization: `Bearer ${agent.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${agent.token}`, 'content-type': 'application/json' },
body: new ReadableStream({ start(controller) { stream = controller; controller.enqueue(Buffer.from('{"sequence":1,"sealed":"')); } }),
duplex: 'half',
});
@@ -186,7 +187,7 @@ test('revoking a board credential while its upload body is open stores nothing [
assert.equal(response.status, 401, JSON.stringify(refusal));
assert.equal(refusal.error.code, 'AUTH_REQUIRED');
const events = await fetch(`${origin}/api/v1/boards/${board}/events?after=0`, {
- headers: { authorization: `Bearer ${person.token}` },
+ headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}` },
});
assert.equal(events.status, 200);
assert.deepEqual((await events.json()).events, [], 'the revoked upload never appends a move');
@@ -207,7 +208,7 @@ test('revoking a person token during snapshot upload preserves the prior snapsho
const origin = `http://127.0.0.1:${service.port}`;
const firstSnapshot = await fetch(`${origin}/api/v1/boards/${board}/state`, {
method: 'PUT',
- headers: { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
body: JSON.stringify({ sequence: 0, sealed: 'AQ' }),
});
assert.equal(firstSnapshot.status, 200);
@@ -227,7 +228,7 @@ test('revoking a person token during snapshot upload preserves the prior snapsho
let stream;
const upload = fetch(`${origin}/api/v1/boards/${board}/state`, {
method: 'PUT',
- headers: { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
body: new ReadableStream({ start(controller) { stream = controller; controller.enqueue(Buffer.from('{"sequence":0,"sealed":"')); } }),
duplex: 'half',
});
@@ -243,7 +244,7 @@ test('revoking a person token during snapshot upload preserves the prior snapsho
assert.equal(response.status, 401, JSON.stringify(refusal));
assert.equal(refusal.error.code, 'AUTH_REQUIRED');
const current = await fetch(`${origin}/api/v1/boards/${board}/state`, {
- headers: { authorization: `Bearer ${observer.token}` },
+ headers: { 'x-pullboard-engine': '3', authorization: `Bearer ${observer.token}` },
});
assert.equal(current.status, 200);
const saved = await current.json();
@@ -460,3 +461,18 @@ test('plain relay off explains an already-deleted board without printing credent
assert.equal(result.code, 0);
assert.deepEqual(result.document, { code: 0, explained: true, credential: false });
});
+
+
+test('every real CLI relay request declares its engine including sign-in, reads, writes and unlink [H16,H3]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ assert.equal((await box.cli('export')).code, 0);
+ assert.equal((await box.cli('add', box.lane, 'Declared-engine fixture move')).code, 0);
+ assert.equal((await box.cli('relay', 'off')).code, 0);
+ assert.ok(box.calls.some(call => call.path.startsWith('/auth/')));
+ assert.ok(box.calls.some(call => call.method === 'GET' && call.path.includes('/events')));
+ assert.ok(box.calls.some(call => call.method === 'POST' && call.path.endsWith('/moves')));
+ assert.ok(box.calls.some(call => call.method === 'PUT' && call.path.endsWith('/state')));
+ assert.ok(box.calls.some(call => call.method === 'DELETE'));
+ assert.ok(box.calls.every(call => call.engine === String(ENGINE_VERSION)), 'every request from the real CLI carries the current engine version');
+});