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): relink explicit opt-outs as fresh sealed boards [H15,H17]

Corey Olson8b807da37857
diff --git a/src/engine.js b/src/engine.js
index c3ea90f7..e9ebf895 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -72,8 +72,12 @@ export function checkpointSequence(board, sequence) {
}
/** Start an explicitly relinked remote epoch while keeping all local board rows and history. */
-export function startRelayEpoch(board) {
+export function startRelayEpoch(board, boardId) {
store.atomic(board, () => {
+ if (boardId !== undefined) {
+ if (!/^[0-9a-f]{32}$/u.test(boardId)) throw new Refused('RELAY_STORAGE', 'restore a valid native board identity before starting its relay epoch');
+ metadata(board, 'board_id', boardId);
+ }
board.db.prepare("DELETE FROM board_meta WHERE meta_key LIKE 'relay_receipt_%'").run();
board.db.prepare("DELETE FROM board_meta WHERE meta_key LIKE 'relay_refusal_%'").run();
metadata(board, 'relay_applied_sequence', '0');
diff --git a/src/relay-relink.js b/src/relay-relink.js
new file mode 100644
index 00000000..da988035
--- /dev/null
+++ b/src/relay-relink.js
@@ -0,0 +1,69 @@
+/** Keep explicit local unlinking distinct from joining somebody else's existing remote board [H17]. */
+import { randomBytes, randomUUID } from 'node:crypto';
+import { existsSync, lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { repoInfo } from './git.js';
+import { Refused } from './refused.js';
+
+/** Locate the key-free next-epoch intent beside the shared local board. */
+function markerFile(root) {
+ return join(repoInfo(root).commonDir, 'pullboard', 'relay-relink.json');
+}
+
+/** Read a bounded private intent; it supplies identity, never a key, token or relay destination. */
+export function relayRelink(root) {
+ const file = markerFile(root);
+ if (!existsSync(file)) return null;
+ const stat = lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) || stat.size > 1024) {
+ throw new Refused('RELAY_STORAGE', 'restore the private relink intent before linking this board');
+ }
+ let value;
+ try { value = JSON.parse(readFileSync(file, 'utf8')); }
+ catch { throw new Refused('RELAY_STORAGE', 'restore the private relink intent before linking this board'); }
+ if (value?.version !== 1 || !/^[0-9a-f]{32}$/u.test(value.previous ?? '')
+ || !/^[0-9a-f]{32}$/u.test(value.next ?? '') || value.previous === value.next) {
+ throw new Refused('RELAY_STORAGE', 'restore the supported relink intent before linking this board');
+ }
+ return value;
+}
+
+/** Bind phone approval and native snapshot preparation to the same durable fresh board identity. */
+export function plannedRelayBoard(root, current) {
+ const marker = relayRelink(root);
+ if (!marker) return current;
+ if (current !== marker.previous && current !== marker.next) {
+ throw new Refused('RELAY_STORAGE', 'the relink intent belongs to another local board; restore its matching board before linking');
+ }
+ return marker.next;
+}
+
+/** Persist the next identity before OFF forgets the only local key, without changing native history. */
+export function rememberRelink(root, previous) {
+ const existing = relayRelink(root);
+ if (existing?.previous === previous) return existing;
+ const value = { version: 1, previous, next: randomBytes(16).toString('hex') };
+ const file = markerFile(root);
+ const temporary = file + '.' + randomUUID() + '.tmp';
+ try {
+ writeFileSync(temporary, JSON.stringify(value) + '\n', { flag: 'wx', mode: 0o600 });
+ renameSync(temporary, file);
+ } finally { rmSync(temporary, { force: true }); }
+ return value;
+}
+
+/** Retain old encrypted queued obligations without replaying their already-local effects into a new epoch. */
+export function archiveRelinkOutbox(root, state) {
+ const directory = join(repoInfo(root).commonDir, 'pullboard');
+ const file = join(directory, 'relay-outbox.sealed');
+ if (!existsSync(file)) return;
+ const name = 'relay-outbox-' + state.board + '-' + randomUUID();
+ writeFileSync(join(directory, name + '.json'), JSON.stringify({ version: 1, board: state.board,
+ url: state.url, sequence: state.sequence, encryptedFile: name + '.sealed' }) + '\n', { flag: 'wx', mode: 0o600 });
+ renameSync(file, join(directory, name + '.sealed'));
+}
+
+/** Consume the intent only after the new link and its exact sealed baseline are durable. */
+export function finishRelink(root) {
+ rmSync(markerFile(root), { force: true });
+}
diff --git a/src/relay-setup.js b/src/relay-setup.js
index 888735ce..36339334 100644
--- a/src/relay-setup.js
+++ b/src/relay-setup.js
@@ -46,6 +46,7 @@ import {
} from './init.js';
import { relayOfferEnabled } from './settings.js';
import { Refused } from './refused.js';
+import { plannedRelayBoard } from './relay-relink.js';
/** Say which paired phone must approve a new board's link, and when the request ends in this computer's time. */
function approvalWait(name, pending, devices) {
@@ -68,7 +69,7 @@ export function unlinkedRelayProjects() {
/** Read the registered local board identity without executing any person action. */
function projectBoard(root) {
const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });
- try { return store.boardId(board); } finally { store.closeBoard(board); }
+ try { return plannedRelayBoard(root, store.boardId(board)); } finally { store.closeBoard(board); }
}
/**
diff --git a/src/relay.js b/src/relay.js
index 7ae99f97..cef1e0b0 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -120,6 +120,7 @@ import {
} from './relay-outbox.js';
import { stampCoordinatorHolder } from './coordinator-hold.js';
import { relayFiles } from './local-state.js';
+import { archiveRelinkOutbox, finishRelink, plannedRelayBoard, relayRelink, rememberRelink } from './relay-relink.js';
import { Refused } from './refused.js';
import { landingRelayCallbacks } from './landing-relay.js';
import { relayOrigin } from './relay-origin.js';
@@ -1571,13 +1572,15 @@ export async function relayOn(root, address, io, { session, credential, quiet =
const url = relayOrigin(address || state?.url || DEFAULT_RELAY);
if (state && (state.url !== url || state.repository !== repository)) throw new Refused('RELAY_LINKED', 'this board is linked to another relay or repository; run relay off before changing its link');
const key = state ? readBoardKey(state.board) : await generateBoardKey();
- const intent = remoteShell ? { board: state?.board ?? localRecords(root, store.boardId), repository,
+ const nextBoard = state?.board ?? plannedRelayBoard(root, localRecords(root, store.boardId));
+ const relink = state ? null : relayRelink(root);
+ const intent = remoteShell ? { board: nextBoard, repository,
host: hostname(), boardName: basename(root) } : undefined;
const signed = remoteShell ? await deviceSignIn(url, io, { intent }) : reusableCredential ?? reusableSession ?? await deviceSignIn(url, io);
if (reusableSession && reusableSession.url !== url) throw new Refused('RELAY_SESSION', 'Sign in again to this relay with pullboard relay on --all.');
if (!state) {
const snapshot = localRecords(root, (board) => {
- startRelayEpoch(board);
+ startRelayEpoch(board, nextBoard);
return { board: store.boardId(board) };
});
snapshot.document = relaySnapshot(root);
@@ -1588,10 +1591,12 @@ export async function relayOn(root, address, io, { session, credential, quiet =
cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, baselineCursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0,
baselineAccepted: false, linkPending: true };
state.snapshot = { sequence: 0, sealed: await sealedRecord(key, snapshot.document, state, 'snapshot', 0) };
+ if (relink) state.previousBoardNotice = relink.previous;
}
const account = signed.account ?? signed.user?.id;
// Persist the exact sealed snapshot and a recoverable link intent before making the remote link.
saveLink(file, state);
+ if (relink) finishRelink(root);
if (state.linkPending) {
if (signed.linkConfirmed && signed.linkedBoard !== state.board) throw new Refused('RELAY_RESPONSE', 'the relay confirmed a different board; sign in again');
if (!reusableCredential && !signed.linkConfirmed) await request({ ...state, token: signed.token }, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository } }, io);
@@ -1638,6 +1643,12 @@ export async function relayOn(root, address, io, { session, credential, quiet =
}
catch (error) { if (strict || !(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}; pending records are queued for the next command`); result = summary(root, state, { pairing: !quiet }); }
if (!quiet) io.say(terminalQr(result.link));
+ if (state.previousBoardNotice) {
+ result.notice = 'Linked a fresh relay board. The old remote copy stays until you delete it from your phone.';
+ io.err(result.notice);
+ delete state.previousBoardNotice;
+ saveLink(file, state);
+ }
return result;
});
}
@@ -1661,6 +1672,8 @@ export async function relayOff(root, io) {
let proposal;
try { proposal = await phoneProposal(state, 'delete-board', state.board, { root }); }
catch { /* Missing key or pairing cannot stop local unlinking. */ }
+ rememberRelink(root, state.board);
+ archiveRelinkOutbox(root, state);
rmSync(file, { force: true });
try { forgetBoardKey(state.board, state.keyStorage); }
catch { /* The local opt-out is complete even when secure key storage is temporarily locked. */ }
diff --git a/test/relay-relink.test.js b/test/relay-relink.test.js
index b409f12d..46c90f7c 100644
--- a/test/relay-relink.test.js
+++ b/test/relay-relink.test.js
@@ -1,10 +1,12 @@
/** Explicit relinking creates a new sealed epoch without accepting the forgotten key [H15,H17]. */
import assert from 'node:assert/strict';
-import { readFileSync } from 'node:fs';
+import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { test } from 'node:test';
+import { fileURLToPath } from 'node:url';
import { decodeBoardKey, seal, unseal } from '../src/seal.js';
import { relayClientFixture } from './relay-client-fixture.js';
+import { runFixtureGit } from './fixture-child.js';
test('a relink after relay off seals moves with the new key [H15,H17]', async t => {
const box = await relayClientFixture(t);
@@ -37,3 +39,57 @@ test('a relink after relay off seals moves with the new key [H15,H17]', async t
});
assert.equal(response.status, 200, 'the old remote copy remains until the person deletes it');
});
+
+test('a durable pending relink retries the same fresh identity and key [H15,H17]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const previous = JSON.parse(readFileSync(box.linkFile, 'utf8')).board;
+ assert.equal((await box.cli('relay', 'off')).code, 0);
+ box.refuseBoardLinks(true);
+ assert.notEqual((await box.cli('relay', 'on', '--url', box.origin)).code, 0);
+ const pending = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ assert.notEqual(pending.board, previous);
+ assert.equal(pending.linkPending, true);
+ const keyFile = join(box.env.PULLBOARD_HOME, 'relay-keys', pending.board + '.key');
+ const key = readFileSync(keyFile, 'utf8');
+ box.refuseBoardLinks(false);
+ const retry = await box.cli('relay', 'on', '--url', box.origin);
+ assert.equal(retry.code, 0);
+ assert.equal(JSON.parse(readFileSync(box.linkFile, 'utf8')).board, pending.board);
+ assert.equal(readFileSync(keyFile, 'utf8') === key, true, 'retry retains the exact saved device key');
+ assert.match(retry.document.notice, /old remote copy stays/u);
+ assert.equal((await box.cli('relay', 'on', '--url', box.origin)).document.notice, undefined,
+ 'the old-copy notice is not repeated after the successful retry');
+});
+
+test('relink snapshots actual local queued effects and retains old encrypted obligations separately [H15,H17,B26]', async t => {
+ const box = await relayClientFixture(t);
+ const configFile = join(box.root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configFile, 'utf8'));
+ writeFileSync(configFile, JSON.stringify({ ...config, relay: { outbox: true } }) + '\n');
+ const cli = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));
+ writeFileSync(join(box.env.PATH, 'pullboard'), `#!/bin/sh\nexec node "${cli}" "$@"\n`, { mode: 0o700 });
+ runFixtureGit(['add', 'pullboard.json'], { cwd: box.root, env: box.env });
+ runFixtureGit(['commit', '-q', '-m', 'private relay outbox configuration'], { cwd: box.root, env: box.env });
+ await box.link();
+ const old = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ await box.stopRelay();
+ assert.equal((await box.cli('shout', 'all', 'actual locally queued effect')).code, 0);
+ const directory = join(box.root, '.git', 'pullboard');
+ const outbox = readFileSync(join(directory, 'relay-outbox.sealed'));
+ assert.equal((await box.cli('relay', 'off')).code, 0);
+ assert.equal(existsSync(join(directory, 'relay-outbox.sealed')), false);
+ const archived = readdirSync(directory).find(name => name.startsWith('relay-outbox-' + old.board + '-') && name.endsWith('.sealed'));
+ assert.ok(archived);
+ assert.equal(readFileSync(join(directory, archived)).equals(outbox), true,
+ 'old obligations retain their exact ciphertext, not a new-key re-encryption or success receipt');
+ const context = JSON.parse(readFileSync(join(directory, archived.replace(/\.sealed$/u, '.json')), 'utf8'));
+ assert.equal(context.board, old.board);
+ assert.equal(context.url, old.url);
+ await box.restartRelay();
+ assert.equal((await box.cli('relay', 'on', '--url', box.origin)).code, 0);
+ const exported = (await box.cli('export')).document;
+ assert.equal(exported.tables.shout.filter(row => row.shout_text === 'actual locally queued effect').length, 1,
+ 'the fresh baseline contains the native effect once, without replaying old queued moves');
+ assert.equal((await box.cli('shout', 'all', 'new epoch after queued effect')).code, 0);
+});