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): preserve paged workflows and approval cards [C7,H15,H17]

Corey Olsonfaab412f42fc
diff --git a/relay/browser-approval-card.js b/relay/browser-approval-card.js
index 5dc3c499..d6659665 100644
--- a/relay/browser-approval-card.js
+++ b/relay/browser-approval-card.js
@@ -1,5 +1,8 @@
/** The words on a paired phone's approval card: which computer asks, which board, and until when [H17,H5]. */
+/** The transport owns these live nodes even while the View replaces its current board children. */
+const APPROVAL_PANELS = new WeakMap();
+
/** Keep one sealed display name only when it is a short single line; otherwise the card falls back. */
function displayName(value) {
return typeof value === 'string' && value.trim() && value.length <= 200 && !/[\u0000-\u001f\u007f]/u.test(value) ? value.trim() : null;
@@ -47,7 +50,7 @@ export const APPROVAL_CARD_STYLES = `
/** Show the requests feed's own progress without making it a prerequisite for reading a board. */
export function phoneApprovalStatus(doc, message) {
- let panel = doc.getElementById('phone-approvals');
+ let panel = doc.getElementById('phone-approvals') ?? APPROVAL_PANELS.get(doc);
if (!panel && message) {
const main = doc.querySelector('main');
if (!main) return null;
@@ -57,6 +60,7 @@ export function phoneApprovalStatus(doc, message) {
main.prepend(panel);
}
if (!panel) return null;
+ APPROVAL_PANELS.set(doc, panel);
placePhoneApprovals(doc);
let status = panel.querySelector('.phone-approval-status');
if (!message) { status?.remove(); return panel; }
@@ -70,7 +74,7 @@ export function phoneApprovalStatus(doc, message) {
/** Keep the same authenticated cards and live handlers on the phone's visible screen until a board can draw. */
export function placePhoneApprovals(doc) {
- const panel = doc.getElementById('phone-approvals');
+ const panel = doc.getElementById('phone-approvals') ?? APPROVAL_PANELS.get(doc);
if (!panel) return null;
const root = doc.documentElement;
const frame = root?.dataset.relayDevice === 'phone' && root.dataset.relayScreen === 'share'
@@ -82,3 +86,11 @@ export function placePhoneApprovals(doc) {
else host.prepend(panel);
return panel;
}
+
+/** Release retained cards, handlers and progress when this document loses access or leaves the page. */
+export function forgetPhoneApprovals(doc) {
+ const panel = APPROVAL_PANELS.get(doc) ?? doc.getElementById('phone-approvals');
+ APPROVAL_PANELS.delete(doc);
+ panel?.replaceChildren();
+ panel?.remove();
+}
diff --git a/relay/browser-client.js b/relay/browser-client.js
index e407e199..87029e1c 100644
--- a/relay/browser-client.js
+++ b/relay/browser-client.js
@@ -9,7 +9,7 @@ import { enqueueStream, followStream } from './browser-stream.js';
import { emptyBoardStep, homeLineDismissed, homeScreenLine, noticeLines, rememberOwnedRequestId, showRelayScreen, storedOwnedRequestState } from './browser-notice.js';
import { registerApp, requestPairingPersistence } from './install.js';
import { browserJSON, withBrowserDeadline } from './browser-deadline.js';
-import { phoneApprovalStatus, placePhoneApprovals } from './browser-approval-card.js';
+import { phoneApprovalStatus, placePhoneApprovals, forgetPhoneApprovals } from './browser-approval-card.js';
import { phoneSnapshotPages } from './browser-pages.js';
import { createPhoneHistory } from './browser-history.js';
@@ -144,6 +144,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
accessLost = true;
accessError = error ?? new Refused('AUTH_REQUIRED', 'Sign in again to read this board.');
access.abort();
+ forgetPhoneApprovals(document);
for (const entry of paired.values()) {
entry.stream?.close();
entry.history?.close(); entry.pageCache?.clear(); entry.pages = null;
diff --git a/relay/browser-devices.js b/relay/browser-devices.js
index 77e41855..d4cd2b55 100644
--- a/relay/browser-devices.js
+++ b/relay/browser-devices.js
@@ -5,7 +5,7 @@ import { ENGINE_VERSION } from './engine.js';
import { Refused } from './refused.js';
import { approvalContext, openApproval, sealApproval, verifyApprovalIntent } from './relay-approval.js';
import { devicePublicKey } from './device-keys.js';
-import { approvalCardText, approvalNames, deletedText, phoneApprovalStatus } from './browser-approval-card.js';
+import { approvalCardText, approvalNames, deletedText, phoneApprovalStatus, forgetPhoneApprovals } from './browser-approval-card.js';
import { withBrowserDeadline } from './browser-deadline.js';
const PENDING = 'pullboard.relay.device-pair.v1';
@@ -163,7 +163,7 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved, s
let stopped = false;
let timer;
/** Release the private device key and pending cards when this page loses relay access. */
- function stop() { stopped = true; clearTimeout(timer); device = null; panel.replaceChildren(); panel.remove(); }
+ function stop() { stopped = true; clearTimeout(timer); device = null; forgetPhoneApprovals(document); }
signal?.addEventListener('abort', stop, { once: true });
/** Refresh pending metadata without approving it or replacing a button whose request is in flight. */
async function refresh() {
diff --git a/relay/smoke.mjs b/relay/smoke.mjs
index 066d6ba4..17c86b2e 100644
--- a/relay/smoke.mjs
+++ b/relay/smoke.mjs
@@ -7,6 +7,7 @@ import { gunzipSync } from 'node:zlib';
import { Refused } from '../src/refused.js';
import { ENGINE_VERSION } from '../src/machine.js';
import { readBoardKey } from '../src/relay-key.js';
+import { request } from '../src/relay.js';
import { unseal } from '../src/seal.js';
const REPOSITORY = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -24,7 +25,13 @@ function cli(root, args) {
child.once('close', (code, signal) => {
clearTimeout(timer);
if (signal) return reject(new Error('the Pullboard command did not finish before its deadline'));
- if (code !== 0) return reject(new Error('the Pullboard command failed; read its message above and repair the repository before retrying'));
+ if (code !== 0) {
+ let refusal;
+ try { refusal = JSON.parse(stdout).error?.code; } catch { /* Only a typed rule is safe to repeat from a failed child. */ }
+ const rule = typeof refusal === 'string' && /^[A-Z][A-Z0-9_]*$/u.test(refusal) ? ` (${refusal})` : '';
+ const operation = args[0] === 'relay' ? `relay ${args[1]}` : args[0];
+ return reject(new Error(`the Pullboard ${operation} command failed${rule}; read its message above and repair the repository before retrying`));
+ }
try { resolveResult(JSON.parse(stdout)); }
catch { reject(new Error('the Pullboard command did not return its JSON result')); }
});
@@ -78,9 +85,7 @@ async function readMirroredMove({ address, board, token, key, after, item, title
const move = JSON.parse(new TextDecoder().decode(bytes));
if (move.operation === 'addItem') {
if (move.args?.[0]?.title !== title) throw new Error('the decrypted relay operation is not the smoke item');
- const stateResponse = await fetch(new URL(`/api/v1/boards/${board}/state`, address), { headers: { authorization: `Bearer ${token}`, 'x-pullboard-engine': String(ENGINE_VERSION) } });
- if (!stateResponse.ok) throw new Error('the relay did not return its native checkpoint');
- const saved = await stateResponse.json();
+ const saved = await request({ url: address, board, token }, `/api/v1/boards/${board}/state`, {}, { err: line => process.stderr.write(line + '\n') });
const checkpointBytes = await unseal(key, Buffer.from(saved.state.sealed, 'base64url'), {
boardId: board, kind: 'snapshot', sequence: saved.state.sequence,
});
@@ -98,9 +103,7 @@ async function readMirroredMove({ address, board, token, key, after, item, title
/** Read a compacted move from its authenticated native checkpoint when the event tail is gone. */
async function readMirroredCheckpoint({ address, board, token, key, after, item, title }) {
- const response = await fetch(new URL(`/api/v1/boards/${board}/state`, address), { headers: { authorization: `Bearer ${token}`, 'x-pullboard-engine': String(ENGINE_VERSION) } });
- if (!response.ok) throw new Error('the relay did not return the mirrored checkpoint');
- const saved = await response.json();
+ const saved = await request({ url: address, board, token }, `/api/v1/boards/${board}/state`, {}, { err: line => process.stderr.write(line + '\n') });
const sequence = saved.state?.sequence;
if (!Number.isSafeInteger(sequence) || sequence !== after + 1 || typeof saved.state.sealed !== 'string') {
throw new Error('the relay checkpoint does not cover exactly one smoke move');
diff --git a/src/relay-page-cache.js b/src/relay-page-cache.js
index cd608b30..1d977ed4 100644
--- a/src/relay-page-cache.js
+++ b/src/relay-page-cache.js
@@ -80,7 +80,14 @@ export function createRelayPageCache(state) {
if (!saved) return null;
let reference;
try { reference = pageReference(JSON.parse(saved.reference)); } catch { throw invalid(); }
- const actual = await sealedPageFingerprint(reference, { ...context, get: id => object(id).bytes, parents: [] });
+ let actual;
+ try { actual = await sealedPageFingerprint(reference, { ...context, get: id => object(id).bytes, parents: [] }); }
+ catch (error) {
+ // A legitimate off/delete/relink can replace the key at this board/origin. Old local cipher hints cannot
+ // be reused under that key; rebuild from the caller's native data. Actual remote reads still authenticate.
+ if (error instanceof Refused && error.code === 'SEAL_AUTH_FAILED') return null;
+ throw error;
+ }
if (actual !== hash) throw invalid();
return reference;
}
diff --git a/test/relay-agent.test.js b/test/relay-agent.test.js
index c1cce8b0..93815e3f 100644
--- a/test/relay-agent.test.js
+++ b/test/relay-agent.test.js
@@ -320,7 +320,7 @@ test('ordered agent joins mint scoped tokens and retain authenticated native act
assertMetadataOnly(apiRevoke, [firstToken, secondToken, personState.token, boardKey], 'local API refusal contains no credential');
// Capture authenticated journal records before a person command checkpoints their prefix.
- const remoteState = await fetch(`${box.origin}/api/v1/boards/${personState.board}/state`, {
+ const remoteState = await fetch(`${box.origin}/api/v2/boards/${personState.board}/state`, {
headers: { authorization: `Bearer ${secondToken}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
});
assert.equal(remoteState.status, 200, 'the second scoped token can read the sealed relay snapshot');
diff --git a/test/relay-browser.test.js b/test/relay-browser.test.js
index 69b5562e..b14cde3e 100644
--- a/test/relay-browser.test.js
+++ b/test/relay-browser.test.js
@@ -578,7 +578,7 @@ test('a phone not signed in sees one GitHub button and nothing about this comput
await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);
await chrome.waitFor("document.documentElement.dataset.relayScreen === 'sign-in' && location.hash === ''");
await chrome.evaluate("document.querySelector('#relay-screen .relay-github').click()");
- await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(marker) + ") && document.querySelector('#pairing-storage-notice') !== null");
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(marker) + ") && document.querySelector('#pairing-storage-notice') !== null && document.documentElement.dataset.relayScreen === undefined");
const board = await chrome.evaluate(`({ text: document.body.innerText, screen: document.documentElement.dataset.relayScreen ?? null,
after: Boolean(document.querySelector('#chain').compareDocumentPosition(document.querySelector('#pairing-storage-notice')) & Node.DOCUMENT_POSITION_FOLLOWING),
line: (() => { const range = document.createRange(); range.selectNodeContents(document.querySelector('#pairing-storage-notice span')); return range.getClientRects().length; })(),
diff --git a/test/relay-deploy.test.js b/test/relay-deploy.test.js
index beeb5b72..7da1e1d7 100644
--- a/test/relay-deploy.test.js
+++ b/test/relay-deploy.test.js
@@ -347,12 +347,12 @@ test('[H5,H18] the Railway smoke links, reads one unsealed move and unlinks loca
'the smoke only unlinks locally and cannot delete the relay copy without phone approval');
assert.equal(result.remoteCopyRetained, true);
assert.match(result.notice, /relay copy stays until you approve deleting it on your phone/u);
- const retained = await fetch(`${previous.url}/api/v1/boards/${previous.board}/state`, {
+ const retained = await fetch(`${previous.url}/api/v2/boards/${previous.board}/state`, {
headers: { authorization: `Bearer ${phone.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
});
assert.equal(retained.status, 200, 'local smoke cleanup retains the sealed relay copy for explicit phone deletion');
const smokeReads = box.calls.slice(beforeSmoke).filter((call) => call.method === 'GET'
- && new RegExp(`^/api/v1/boards/${previous.board}/(?:events|state)(?:\\?|$)`, 'u').test(call.path));
+ && new RegExp(`^/api/v[12]/boards/${previous.board}/(?:events|state)(?:\\?|$)`, 'u').test(call.path));
assert.ok(smokeReads.length >= 2, 'the smoke reads the mirrored event and its native checkpoint over the real HTTP API');
assert.ok(smokeReads.every((call) => call.engine === String(ENGINE_VERSION)), 'every smoke board-content read declares the current engine after the relay minimum is raised');
const local = (await box.cli('export')).document;
@@ -371,7 +371,7 @@ test('[H5,H18] a linked repository is refused before the smoke can unlink its bo
assert.equal(box.calls.length, before, 'the guard runs before relay on or off can make a network request');
assert.equal(existsSync(box.linkFile), true, 'the existing private link remains intact');
assert.equal(existsSync(box.keyFile), true, 'the existing device key remains intact');
- const state = await fetch(`${previous.url}/api/v1/boards/${previous.board}/state`, {
+ const state = await fetch(`${previous.url}/api/v2/boards/${previous.board}/state`, {
headers: { authorization: `Bearer ${previous.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
});
assert.equal(state.status, 200, 'the linked remote board was not deleted');
diff --git a/test/relay-mint.test.js b/test/relay-mint.test.js
index 76275acd..dec00e3b 100644
--- a/test/relay-mint.test.js
+++ b/test/relay-mint.test.js
@@ -227,7 +227,7 @@ test('an agent in its worktree cannot mint a relay token [H2,V1,E3,E5,P6]', asyn
assert.ok(failed, 'the registration reached the relay');
const body = JSON.parse(failed.request.toString('utf8'));
const state = link(box);
- const snapshot = await call(box.origin, state.token, 'GET', `/api/v1/boards/${state.board}/state`);
+ const snapshot = await call(box.origin, state.token, 'GET', `/api/v2/boards/${state.board}/state`);
const events = await call(box.origin, state.token, 'GET', `/api/v1/boards/${state.board}/events?after=${snapshot.document.state.sequence}`);
assert.equal(events.status, 200, JSON.stringify(events.document.error ?? {}));
assert.ok(events.document.events.some((event) => event.registration?.target === body.registration.target), 'the move and its receipt were published');
diff --git a/test/relay-page-client.test.js b/test/relay-page-client.test.js
index f45f4c71..d13d3de9 100644
--- a/test/relay-page-client.test.js
+++ b/test/relay-page-client.test.js
@@ -10,7 +10,7 @@ import { snapshotPageRoot } from '../relay/pages-http.js';
import { createRelayPageCache, snapshotSourceId } from '../src/relay-page-cache.js';
import { pagedSnapshotRequest, relaySnapshotRequest, relayStorage, relayStorageLine } from '../src/relay-page-client.js';
import { generateBoardKey } from '../src/seal.js';
-import { writeSealedValue } from '../src/sealed-pages.js';
+import { writeSealedValue, sealedPageFingerprint } from '../src/sealed-pages.js';
import { Refused } from '../src/refused.js';
import { createServer } from 'node:http';
import { relayFixtureChild, cliChildDeadlineMs } from './relay-client-fixture.js';
@@ -140,6 +140,22 @@ test('an incorrect root ACK never completes or discards the private durable uplo
try { assert.ok(cache.job(snapshotSourceId(pending.sealed))); } finally { cache.close(); }
});
+test('cache hits from a prior key are misses while actual encrypted reads still refuse the wrong key [H15,H17]', async t => {
+ privateHome(t);
+ const state = { board: 'c'.repeat(32), url: 'https://synthetic-relay.example' };
+ const cache = createRelayPageCache(state);
+ const first = { key: await generateBoardKey(), boardId: state.board, sequence: 0, put: cache.put, get: id => cache.object(id).bytes };
+ try {
+ const reference = await writeSealedValue({ marker: 'private native source' }, first);
+ const hash = await sealedPageFingerprint(reference, first);
+ cache.remember(hash, reference);
+ const relinked = { ...first, key: await generateBoardKey() };
+ assert.equal(await cache.lookup(hash, relinked), null, 'the old-key hint is not reused for a new upload');
+ await assert.rejects(sealedPageFingerprint(reference, relinked), { code: 'SEAL_AUTH_FAILED' }, 'an actual wrong-key encrypted read stays refused');
+ assert.deepEqual(await cache.lookup(hash, first), reference, 'the original authenticated object remains intact for its key');
+ } finally { cache.close(); }
+});
+
test('private reuse authenticates the fingerprint binding rather than trusting an unrelated cached page [H15,H17]', async t => {
privateHome(t);
const state = { board: 'b'.repeat(32), url: 'https://synthetic-relay.example' };
diff --git a/test/relay-person-actions.test.js b/test/relay-person-actions.test.js
index 83dc9ae0..de956383 100644
--- a/test/relay-person-actions.test.js
+++ b/test/relay-person-actions.test.js
@@ -12,7 +12,7 @@ import { main } from '../src/cli.js';
import { decodeBoardKey, seal } from '../src/seal.js';
import { ENGINE_VERSION } from '../src/machine.js';
import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';
-import { assertSnapshotCheckpoints, cliChildDeadlineMs, relayClientFixture } from './relay-client-fixture.js';
+import { assertSnapshotCheckpoints, cliChildDeadlineMs, relayClientFixture, legacyRelayClientFixture } from './relay-client-fixture.js';
/** Record the real phase and wait budget for a late-snapshot failure without changing either wait. */
function lateSnapshotTiming(t) {
@@ -216,7 +216,8 @@ test('a person action completes with late native snapshots after 8 seconds [H12,
const timing = lateSnapshotTiming(t);
try {
timing.begin('fixture setup and item creation', '4 serial private CLI children; each has the existing 55,000 ms child bound');
- const box = await relayClientFixture(t);
+ // This case measures released API1 whole-checkpoint attempts and exact ciphertext retries.
+ const box = await legacyRelayClientFixture(t);
const title = 'PERSON_ACTION_LATE_SNAPSHOT_READY';
assert.equal((await box.cli('add', box.lane, title)).code, 0);
timing.finish();
@@ -283,7 +284,7 @@ test('local view attribution is person-only and an agent token cannot seal perso
});
assert.equal(tokenResponse.status, 201);
const agentToken = (await tokenResponse.json()).token;
- const stateResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {
+ const stateResponse = await fetch(box.origin + '/api/v2/boards/' + link.board + '/state', {
headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) },
});
assert.equal(stateResponse.status, 200);
diff --git a/test/relay-person-page.test.js b/test/relay-person-page.test.js
index 9c8dda7f..d10372df 100644
--- a/test/relay-person-page.test.js
+++ b/test/relay-person-page.test.js
@@ -215,6 +215,20 @@ window.fetch = (input, options) => {
});
await chrome.navigate(box.origin);
await chrome.waitFor("document.readyState === 'complete'");
+ const panelOwnership = await chrome.send('Runtime.evaluate', { awaitPromise: true, returnByValue: true, expression: `(async () => {
+ const { phoneApprovalStatus, placePhoneApprovals, forgetPhoneApprovals } = await import('/relay/browser-approval-card.js');
+ const doc = document.implementation.createHTMLDocument('Private approval ownership');
+ doc.body.innerHTML = '<main></main>';
+ const panel = phoneApprovalStatus(doc, 'Private pending request');
+ const button = doc.createElement('button'); let clicks = 0; button.onclick = () => clicks++; panel.append(button);
+ doc.querySelector('main').replaceChildren(doc.createElement('section'));
+ const restored = placePhoneApprovals(doc); button.click();
+ const retained = restored === panel && doc.querySelector('main').contains(panel) && clicks === 1;
+ forgetPhoneApprovals(doc);
+ return { retained, released: panel.childNodes.length === 0 && placePhoneApprovals(doc) === null };
+ })()` });
+ assert.equal(Boolean(panelOwnership.exceptionDetails), false, 'the real approval component executes');
+ assert.deepEqual(panelOwnership.result?.value, { retained: true, released: true }, 'board redraw retains live handlers; access loss releases them');
// Seed a real non-extractable browser key without exporting it; the authenticated saved board is already readable.
const seeded = await chrome.send('Runtime.evaluate', { awaitPromise: true, returnByValue: true, expression: `(async () => {
const { createDeviceKeys } = await import('/relay/device-keys.js');
@@ -237,8 +251,8 @@ window.fetch = (input, options) => {
await chrome.navigate('about:blank');
await chrome.navigate(box.origin);
await chrome.waitFor('window.approvalsPending899 === true');
- await chrome.waitFor(`document.querySelector('#chain')?.textContent.includes(${JSON.stringify(marker)})`, 3000, // budget: declared #899 three-second ceiling while the late request never answers.
- 'readable board renders while approvals remain pending');
+ await chrome.waitFor(`document.querySelector('#chain')?.textContent.includes(${JSON.stringify(marker)}) && document.documentElement.dataset.relayScreen === undefined && document.body.innerText.includes('Checking requests from your computer')`, 3000, // budget: declared #899 three-second ceiling while the late request never answers.
+ 'readable board and pending guidance render while approvals remain pending');
assert.equal(await chrome.evaluate('window.approvalsPending899 === true'), true);
assert.ok((await chrome.evaluate('document.body.innerText')).includes(marker));
assert.ok((await chrome.evaluate('document.body.innerText')).includes('Checking requests from your computer'),
diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.js
index 0117b479..cc576950 100644
--- a/test/relay-sealed.test.js
+++ b/test/relay-sealed.test.js
@@ -10,7 +10,7 @@ import { pathToFileURL } from 'node:url';
import { gunzipSync } from 'node:zlib';
import { createServer } from 'node:http';
import { after, test } from 'node:test';
-import { serveRelay } from '../relay/service.js';
+import { serveRelay, createRelayHandler } from '../relay/service.js';
import { createRelayAuth } from '../relay/auth.js';
import { createGitHubClient } from '../relay/github.js';
import { githubFixture } from './relay-fixture.js';
@@ -24,6 +24,7 @@ import { appliedSequence, checkpointSequence, engineReceipt, prepareEngineMove,
import { seal as sealMove, unseal as openSealed } from '../src/seal.js';
import { ENGINE_VERSION, VERIFIER_STANDING_ENGINE } from '../src/machine.js';
import { relayRecover, syncRelay } from '../src/relay.js';
+import { createRelayPageCache, snapshotSourceId } from '../src/relay-page-cache.js';
after(cleanupFixtureChildren);
@@ -54,8 +55,26 @@ async function openCheckpoint(box, snapshot) {
return JSON.parse(new TextDecoder().decode(plain));
}
+/** Keep API1 ciphertext-interception cases on an explicitly historical HTTP router; current cases use real API2. */
+async function sealedFixtureRelay(options, legacySnapshots) {
+ if (!legacySnapshots) return serveRelay(options);
+ const handler = createRelayHandler(options);
+ const server = createServer((req, res) => {
+ if (/^\/api\/v2(?:\/|$)/u.test(req.url ?? '')) {
+ req.resume();
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: 1, error: { code: 'NOT_FOUND', message: 'This historical fixture supports API1.' } }));
+ return;
+ }
+ return handler(req, res);
+ });
+ await new Promise((resolveListening, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolveListening); });
+ return { port: server.address().port,
+ close: () => new Promise(done => { handler.close(); server.close(done); server.closeAllConnections(); }) };
+}
+
/** Create a real private CLI board, actual stand-in GitHub sign-in, and an ephemeral relay server. */
-async function fixture(t, { machineCredentials = true } = {}) {
+async function fixture(t, { machineCredentials = true, legacySnapshots = false } = {}) {
const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-sealed-http-')));
const root = join(directory, 'repo');
const home = join(directory, 'home');
@@ -97,7 +116,7 @@ async function fixture(t, { machineCredentials = true } = {}) {
const tokenIssuer = machines[0]?.token ?? person.token;
const one = await auth.issueToken(tokenIssuer, { board: id, agent: 'client-one' });
const two = await auth.issueToken(machines[1]?.token ?? tokenIssuer, { board: id, agent: 'client-two' });
- const relay = await serveRelay({ directory: data, auth, port: 0, pollMs: 20, publicOrigin: 'http://127.0.0.1:44444' });
+ const relay = await sealedFixtureRelay({ directory: data, auth, port: 0, pollMs: 20, publicOrigin: 'http://127.0.0.1:44444' }, legacySnapshots);
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);
@@ -476,7 +495,8 @@ test('two real clients refuse forged relay actors and person-only requests while
});
test('two real clients enforce the verify policy captured in the item freeze [H16,O2]', { timeout: 240_000 }, async t => {
- const box = await fixture(t);
+ // The injected faults address the released whole-ciphertext API1 checkpoint contract.
+ const box = await fixture(t, { legacySnapshots: true });
const configPath = join(box.root, 'pullboard.json');
const config = JSON.parse(readFileSync(configPath, 'utf8'));
config.verify = { ...config.verify, policy: 'coordinator', family: 'require' };
@@ -637,7 +657,8 @@ test('two real clients enforce the verify policy captured in the item freeze [H1
});
test('person recovery explicitly skips one future-engine blocker and publishes a refusal checkpoint [H3,H16]', async (t) => {
- const box = await fixture(t);
+ // The injected faults address the released whole-ciphertext API1 checkpoint contract.
+ const box = await fixture(t, { legacySnapshots: true });
for (const args of [['help', 'relay', 'recover'], ['relay', 'recover', '--help'], ['help', '--all']]) {
const help = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args],
{ cwd: box.root, env: box.env, encoding: 'utf8' });
@@ -963,7 +984,7 @@ test('two future-engine blockers recover one durable position at a time on two r
assert.equal((await syncRelay(box.root, io)).sequence, 5);
const first = await relayRecover(box.root, 6, io);
assert.equal(first.sequence, 6, 'later engine99 record cannot roll back the selected skip');
- assert.equal((await box.call(box.path + '/state')).body.state.sequence, 6, 'skip6 is durably published before skip7');
+ assert.equal((await box.call('/api/v2/boards/' + box.id + '/state')).body.state.sequence, 6, 'skip6 is durably published before skip7');
await replayClient(roots[1], envs[1], 'relay');
const afterFirst = await replayClient(roots[1], envs[1], 'export');
assert.equal(afterFirst.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '6');
@@ -979,7 +1000,8 @@ test('two future-engine blockers recover one durable position at a time on two r
});
test('recovery collision status preserves the retry while the winner catches an appended tail [H16]', async (t) => {
- const box = await fixture(t);
+ // The injected faults address the released whole-ciphertext API1 checkpoint contract.
+ const box = await fixture(t, { legacySnapshots: true });
await blockedRecoveryFixture(box);
const secondRoot = join(box.directory, 'recovery-collision-replica');
const secondHome = join(box.directory, 'recovery-collision-home');
@@ -1147,7 +1169,7 @@ test('lost-ACK recovery retry refuses to overwrite a concurrent local write [H16
let wrote = false;
globalThis.fetch = async (url, options = {}) => {
const response = await priorFetch(url, options);
- if (!wrote && options.method === 'PUT' && String(url).endsWith('/state')) {
+ if (!wrote && options.method === 'POST' && /\/api\/v2\/boards\/[0-9a-f]{32}\/uploads\/[^/]+\/publish$/u.test(new URL(url).pathname)) {
wrote = true;
const board = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));
try {
@@ -1162,7 +1184,16 @@ test('lost-ACK recovery retry refuses to overwrite a concurrent local write [H16
globalThis.fetch = priorFetch;
const recovery = JSON.parse(readFileSync(join(box.root, '.git/pullboard/relay.json'), 'utf8')).recovery;
assert.equal(recovery.skip, 1);
- assert.equal((await box.call(box.path + '/state')).body.state.sealed, recovery.sealed);
+ assert.equal(wrote, true, 'the fault follows an actual API2 publication acknowledgement');
+ const remote = await box.call('/api/v2/boards/' + box.id + '/state');
+ assert.equal(remote.status, 200);
+ const cache = createRelayPageCache({ board: box.id, url: box.origin });
+ try {
+ const prepared = cache.job(snapshotSourceId(recovery.sealed));
+ assert.ok(prepared, 'the original pending checkpoint has a durable encrypted graph');
+ assert.equal(remote.body.state.root.id, prepared.reference.id, 'the relay retained the exact graph published before its ACK was lost');
+ assert.equal(remote.body.state.sequence, recovery.skip);
+ } finally { cache.close(); }
await assert.rejects(() => relayRecover(box.root, 1, { err: () => {}, say: () => {} }),
{ code: 'RELAY_LOCAL_CHANGED', message: /cannot be retried from the changed board/ },
'a local change is preserved and the message does not suggest export alone will unblock retry');
@@ -1304,6 +1335,7 @@ test('[A4,H7] snapshots compact covered moves, preserve the tail and deletion re
test('[A4,H7] malformed or unauthorized calls cannot store clear records, keys or another board', async (t) => {
const box = await fixture(t);
+ const initialFiles = readdirSync(box.data).sort();
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');
@@ -1312,7 +1344,7 @@ test('[A4,H7] malformed or unauthorized calls cannot store clear records, keys o
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', token: box.person.token, body })).status, 400);
}
- assert.deepEqual(readdirSync(box.data), []);
+ assert.deepEqual(readdirSync(box.data).sort(), initialFiles, 'unauthorized or malformed input creates no board data beside pre-existing account metadata');
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) } });
diff --git a/test/relay.test.js b/test/relay.test.js
index 9a5a7342..65a8e3f0 100644
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@ -1204,7 +1204,7 @@ test('offline linked reads use the local board, moves refuse, and the same relay
const afterTables = (await box.cli('export')).document.tables;
assert.equal(afterTables.event.length, beforeEvents.length + 1, 'only the acknowledged recovery move is recorded locally');
assert.equal(afterTables.event.at(-1).event_kind, 'add');
- const remoteStateResponse = await fetch(`${box.origin}/api/v1/boards/${link.board}/state`, {
+ const remoteStateResponse = await fetch(`${box.origin}/api/v2/boards/${link.board}/state`, {
headers: { authorization: `Bearer ${link.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
});
assert.equal(remoteStateResponse.status, 200);
@@ -1444,7 +1444,7 @@ test('every real CLI relay request declares its engine including sign-in, reads,
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 === 'POST' && /^\/api\/v2\/boards\/[0-9a-f]{32}\/uploads\/[^/]+\/publish$/u.test(call.path)), 'the current CLI publishes an authenticated paged checkpoint');
assert.equal(box.calls.some(call => call.method === 'DELETE'), false, 'local off does not send remote deletion without phone approval');
assert.ok(box.calls.every(call => call.engine === String(ENGINE_VERSION)), 'every request from the real CLI carries the current engine version');
});
diff --git a/test/rigor.test.js b/test/rigor.test.js
index f56f47e9..813ebf80 100644
--- a/test/rigor.test.js
+++ b/test/rigor.test.js
@@ -666,7 +666,6 @@ test('a timed-out proof drains only its captured process group before removing i
const { parseProcessCensus } = await import('../src/process-census.js');
const box = freshBoard();
const helper = join(box.repo, 'hold-proof.mjs');
- const parserUrl = new URL('../src/process-census.js', import.meta.url).href;
let resolveMarker;
let rejectMarker;
const marker = new Promise((resolve, reject) => { resolveMarker = resolve; rejectMarker = reject; });
@@ -684,18 +683,13 @@ test('a timed-out proof drains only its captured process group before removing i
const port = ready.address().port;
const timeoutMs = 1000;
writeFileSync(helper, `
- import { spawn, spawnSync } from 'node:child_process';
+ import { spawn } from 'node:child_process';
import { createConnection } from 'node:net';
- import { parseProcessCensus } from ${JSON.stringify(parserUrl)};
const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);
await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
- const ps = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], { encoding: 'utf8', timeout: 2000, env: { ...process.env, LC_ALL: 'C' } });
- const rows = ps.status === 0 ? parseProcessCensus(ps.stdout) : null;
- const owned = rows && [process.pid, child.pid].map(pid => rows.get(pid));
- if (!owned?.every(Boolean) || owned[0].pgid !== owned[1].pgid) process.exit(32);
const socket = createConnection({ host: '127.0.0.1', port: ${port} });
socket.on('error', () => process.exit(33));
- socket.end(JSON.stringify({ rows: owned }));
+ socket.end(JSON.stringify({ pids: [process.pid, child.pid] }));
setInterval(() => {}, 1000);
`);
let runOutcome;
@@ -710,16 +704,20 @@ test('a timed-out proof drains only its captured process group before removing i
executable: process.execPath, args: ['hold-proof.mjs'],
}, { timeoutMs }).then(value => ({ value }), error => ({ error }));
const recorded = await marker;
+ assert.equal(recorded.pids?.length, 2, 'the real helper reports itself and its child');
+ assert.ok(recorded.pids.every(pid => Number.isInteger(pid) && pid > 0) && recorded.pids[0] !== recorded.pids[1]);
const pre = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], { encoding: 'utf8', timeout: 2000, env: { ...process.env, LC_ALL: 'C' } });
assert.equal(pre.status, 0, 'the pre-timeout census completed');
const live = parseProcessCensus(pre.stdout);
assert.ok(live, 'the pre-timeout census is parseable');
- assert.equal(recorded.rows[0].pgid, recorded.rows[1].pgid, 'both captured processes belong to one group');
- for (const identity of recorded.rows) {
- const current = live.get(identity.pid);
- assert.ok(current && current.pgid === identity.pgid && current.started === identity.started
- && current.processSha256 === identity.processSha256 && !current.state.startsWith('Z'),
- 'each real process identity is still present before timeout');
+ // One parent census proves both live identities; do not spend a second two-second census inside the one-second proof.
+ const rows = recorded.pids.map(pid => live.get(pid));
+ assert.ok(rows.every(Boolean), 'both reported processes exist in the actual parent census');
+ assert.equal(rows[0].pgid, rows[1].pgid, 'both captured processes belong to one group');
+ assert.equal(rows[0].pgid, rows[0].pid, 'the proof owns its detached group');
+ for (const [index, identity] of rows.entries()) {
+ assert.equal(identity.pid, recorded.pids[index], 'the actual census identifies the reported process');
+ assert.equal(identity.state.startsWith('Z'), false, 'each process is live before timeout');
}
const outcome = await runOutcome;
if (outcome.error) throw outcome.error;
@@ -728,7 +726,7 @@ test('a timed-out proof drains only its captured process group before removing i
assert.equal(post.status, 0, 'the post-timeout census completed');
const drained = parseProcessCensus(post.stdout);
assert.ok(drained, 'the post-timeout census is parseable');
- for (const identity of recorded.rows) {
+ for (const identity of rows) {
const current = drained.get(identity.pid);
assert.ok(!current || current.state.startsWith('Z') || current.pgid !== identity.pgid
|| current.started !== identity.started || current.processSha256 !== identity.processSha256,