Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(relay): keep joined boards local after deletion [H17,E9]
Corey Olson9dafeb311f82
diff --git a/docs/api.md b/docs/api.mdindex 822eacaf..fc32b7ae 100644--- a/docs/api.md+++ b/docs/api.md@@ -201,6 +201,10 @@ Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed b`POST /auth/machines {board,machine}` requires a foreground person session and returns a `pm_` credential bound to that board and machine. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.+`GET /auth/machines?board=<id>` returns `{version, machines: [{machine}]}` for the live computer credentials on that board, with duplicate computer ids listed once. It requires that board's machine credential or a person session with current repository write access; agent tokens and credentials from another board are refused. `relay off` excludes its own computer from the list and warns which joined computers lose the shared copy if the phone approves deletion. JSON also returns those ids in `affectedMachines`. Local unlink still succeeds when the relay cannot supply the list.++After phone-approved deletion, a previously live scoped credential receives HTTP 410 / `RELAY_BOARD_DELETED` for that deleted copy. The relay retains only its hash, board id and original expiry as a deletion receipt, prunes expired receipts, and grants no access through them. Unknown, already revoked and already expired credentials receive `AUTH_REQUIRED` as before. Only a versioned deletion response naming this link's own board turns a joined computer back into a local board. The CLI removes the inert link and its device key, excludes the project from automatic relinking, and retains a private credential-free notice that the relay copy was deleted; native board contents remain local. A successful explicit `relay on` starts a new link and clears that notice. A network outage or ordinary credential refusal does not authorize this transition.+A machine publishes an opaque approval with `POST /api/v1/devices/approvals {context,sealed}`. The publishing machine may GET only its own requests. The paired phone reads `/api/v1/devices/:deviceId/approvals`, explicitly POSTs `/:requestId/authorize {}` and completes the encrypted reply through `/:requestId/complete {response}`. The publishing machine executes a native revocation through `/:requestId/execute {grant}`; the two-minute grant binds the entire context and is atomically consumed once. Native reply keys and grants never persist. A refused foreground approval fails immediately with the original refusal code and reason plus its request id. A refused remote approval makes local unlinking or registration exit nonzero while retaining the completed local work: one line names that completion, the refusal code and reason, the request id and the next action. The JSON result preserves the local outcome and includes `remote: {code, reason, requestId}`. New-board linking uses a durable non-person reply key and returns only a board-scoped machine credential. `relay off` immediately unlinks locally even offline or in an agent shell, reports that the relay copy remains, and queues a separate one-tap phone deletion request when possible.The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js` by `docs/api.test.js`.diff --git a/relay/auth-http.js b/relay/auth-http.jsindex 1b0e6cb2..5f7a3e04 100644--- a/relay/auth-http.js+++ b/relay/auth-http.js@@ -67,7 +67,7 @@ export function createAuthHandler({ auth, publicOrigin }) {const secure = origin.protocol === 'https:' ? '; Secure' : '';const routes = new Set(['GET /auth/github/start', 'GET /auth/github/callback', 'POST /auth/device/start', 'POST /auth/device/poll', 'POST /auth/device/cancel','GET /auth/device/confirm', 'POST /auth/device/confirmation/open', 'POST /auth/device/confirmation/status', 'POST /auth/device/confirmation',- 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'POST /auth/machines', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);+ 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'POST /auth/machines', 'GET /auth/machines', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);/** Resolve a bearer or cookie credential; cookie writes require an exact trusted Origin. */function token(req, write = false) {@@ -140,6 +140,8 @@ export function createAuthHandler({ auth, publicOrigin }) {const bearer = token(req, true);const input = await body(req);json(res, 200, { board: await auth.linkBoard(bearer, input.board, input.repository) });+ } else if (route === 'GET /auth/machines') {+ json(res, 200, { machines: await auth.listMachines(token(req), url.searchParams.get('board')) });} else if (route === 'POST /auth/machines') {const bearer = token(req, true);json(res, 201, await auth.issueMachine(bearer, await body(req)));@@ -157,7 +159,7 @@ export function createAuthHandler({ auth, publicOrigin }) {} catch (error) {const code = error instanceof Refused ? error.code : 'INTERNAL_ERROR';const message = error instanceof Refused ? error.message.replace(/^\[[^\]]+\] /, '') : 'the relay could not complete this request; retry or contact its coordinator';- const status = code === 'BOARD_NOT_LINKED' ? 404 : code === 'AUTH_REQUIRED' ? 401 : ['NO_REPO_ACCESS', 'TOKEN_BOARD', 'TOKEN_NOT_OWNED', 'HUMAN_REQUIRED', 'BAD_ORIGIN', 'WRITE_REQUIRED'].includes(code) ? 403 : code === 'GITHUB_UNAVAILABLE' ? 503 : code === 'INTERNAL_ERROR' ? 500 : 400;+ const status = code === 'RELAY_BOARD_DELETED' ? 410 : code === 'BOARD_NOT_LINKED' ? 404 : code === 'AUTH_REQUIRED' ? 401 : ['NO_REPO_ACCESS', 'TOKEN_BOARD', 'TOKEN_NOT_OWNED', 'HUMAN_REQUIRED', 'BAD_ORIGIN', 'WRITE_REQUIRED'].includes(code) ? 403 : code === 'GITHUB_UNAVAILABLE' ? 503 : code === 'INTERNAL_ERROR' ? 500 : 400;json(res, status, { error: { code, message, next: message } });}return true;diff --git a/relay/auth.js b/relay/auth.jsindex 1a1ba65d..4ee6e18d 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -43,6 +43,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =CREATE TABLE IF NOT EXISTS relay_users (id TEXT PRIMARY KEY, login TEXT NOT NULL);CREATE TABLE IF NOT EXISTS relay_boards (id TEXT PRIMARY KEY, repository TEXT NOT NULL, repository_id TEXT NOT NULL);CREATE TABLE IF NOT EXISTS relay_cleanup (board TEXT PRIMARY KEY);+ CREATE TABLE IF NOT EXISTS relay_deleted_credentials (hash TEXT PRIMARY KEY, board TEXT NOT NULL, expires INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS relay_credentials (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, kind TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES relay_users(id), board TEXT REFERENCES relay_boards(id), agent TEXT, expires INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS relay_action_grants (hash TEXT PRIMARY KEY, request TEXT UNIQUE NOT NULL,user_id TEXT NOT NULL, context TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);@@ -55,6 +56,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =db.exec('ALTER TABLE relay_boards ADD COLUMN linked_at INTEGER');}db.prepare('UPDATE relay_boards SET linked_at=? WHERE linked_at IS NULL').run(now());+ db.prepare('DELETE FROM relay_deleted_credentials WHERE expires<=?').run(now());db.exec('COMMIT');} catch (error) { try { db.exec('ROLLBACK'); } finally { db.close(); } throw error; }const permissions = new Map();@@ -96,7 +98,11 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =function credential(token) {open();if (typeof token !== 'string' || !/^(ps_|pa_|pm_)[A-Za-z0-9_-]{43}$/.test(token)) throw new Refused('AUTH_REQUIRED', 'sign in to the relay or supply a current board token');- const row = db.prepare('SELECT c.*, u.login FROM relay_credentials c JOIN relay_users u ON u.id=c.user_id WHERE c.hash=?').get(hash(token));+ db.prepare('DELETE FROM relay_deleted_credentials WHERE expires<=?').run(now());+ const digest = hash(token);+ const row = db.prepare('SELECT c.*, u.login FROM relay_credentials c JOIN relay_users u ON u.id=c.user_id WHERE c.hash=?').get(digest);+ const deleted = !row && db.prepare('SELECT board FROM relay_deleted_credentials WHERE hash=? AND expires>?').get(digest, now());+ if (deleted) throw new Refused('RELAY_BOARD_DELETED', `relay copy ${deleted.board} was deleted; keep working locally, or run pullboard relay on to link it again`);if (!row || row.revoked || row.expires <= now()) throw new Refused('AUTH_REQUIRED', 'this credential is expired or revoked; sign in or obtain a new board token');return row;}@@ -472,6 +478,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =identifier(board, 'BAD_BOARD');lifecycle(() => {db.prepare('INSERT OR IGNORE INTO relay_cleanup (board) VALUES (?)').run(board);+ db.prepare('DELETE FROM relay_deleted_credentials WHERE expires<=?').run(now());+ db.prepare('INSERT OR REPLACE INTO relay_deleted_credentials (hash,board,expires) SELECT hash,board,expires FROM relay_credentials WHERE board=? AND revoked=0 AND expires>?').run(board, now());db.prepare('DELETE FROM relay_credentials WHERE board=?').run(board);db.prepare('DELETE FROM relay_boards WHERE id=?').run(board);});@@ -514,6 +522,14 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =credential(token);return { ...issue(principal.user, 'machine', board, machine, expiresIn), board, machine };},+ /** List live computer identities only for this board's machine or a freshly authorized person. */+ async listMachines(token, board) {+ identifier(board, 'BAD_BOARD');+ const principal = await auth.authenticate(token, { board, write: true });+ if (!['session', 'machine'].includes(principal.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential or the signed-in phone to list joined computers');+ credential(token);+ return db.prepare("SELECT DISTINCT agent AS machine FROM relay_credentials WHERE board=? AND kind='machine' AND revoked=0 AND expires>? ORDER BY agent").all(board, now());+ },/** 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/src/api-http.js b/src/api-http.jsindex 1ba76da8..06f7eaa4 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -352,7 +352,7 @@ export function applyStateDelta(state, delta) {/** 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, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, NO_SHOUT: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, BASELINE_EXISTS: 412, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);+ return { RELAY_BOARD_DELETED: 410, AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, NO_SHOUT: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, BASELINE_EXISTS: 412, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);}// Relay-only snapshot/delete routes reuse the exact shared bounded-body and refusal boundary.diff --git a/src/next-steps.js b/src/next-steps.jsindex af3984f6..ddec6f2c 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -269,6 +269,7 @@ export const NEXT_STEPS = Object.freeze({RELAY_ACTOR: 'send the move with the token of the agent that makes it',RELAY_ANSWER: 'use pullboard answer <id> "<answer>" or pullboard pass <id> --note "<reason>"',RELAY_BASELINE_EXISTS: 'save the board with pullboard export > board.json, then pullboard relay off',+ RELAY_BOARD_DELETED: 'keep working locally, or run pullboard relay on to link the board again',RELAY_BUSY: 'run the command again after the other worktree finishes sending',RELAY_CURSOR: 'fetch a consistent snapshot: pullboard relay',RELAY_DIVERGED: 'run pullboard relay off, then pullboard relay on to link again from this machine',diff --git a/src/relay.js b/src/relay.jsindex 6767a6df..81035e72 100644--- a/src/relay.js+++ b/src/relay.js@@ -35,6 +35,7 @@ const CHECKPOINT_MOVES = new WeakMap();const BASELINE_LOCAL_MOVES = new WeakSet();const BASELINE_FAILURES = new WeakMap();const AUTH_NOTICES = new WeakSet();+const DELETION_NOTICES = new WeakSet();const ORDERED_MOVE_COMMANDS = new Set(['add', 'edit', 'fact', 'escalate', 'run', 'sweep', 'next', 'claim', 'hold', 'release','submit', 'done', 'verify', 'merged', 'land', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget', 'join', 'worktree']);@@ -73,6 +74,45 @@ export function originRepository(root) {/** Find the shared local link metadata without opening a board or connecting for an unlinked repo. */function linkFile(root) { return join(repoInfo(root).commonDir, 'pullboard', 'relay.json'); }+/** Locate the credential-free reason an independently deleted copy no longer syncs. */+function deletedLinkFile(root) { return join(repoInfo(root).commonDir, 'pullboard', 'relay-deleted.json'); }++/** Read only a private, bounded deletion marker; it never supplies credentials or an outbound destination. */+function deletedLink(root) {+ const file = deletedLinkFile(root);+ if (!existsSync(file)) return null;+ const stat = lstatSync(file);+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) || stat.size > 4096) throw new Refused('RELAY_STORAGE', 'restore the private deleted-copy notice before reading relay status');+ let value;+ try { value = JSON.parse(readFileSync(file, 'utf8')); } catch { throw new Refused('RELAY_STORAGE', 'restore the private deleted-copy notice before reading relay status'); }+ if (value?.version !== 1 || !/^[0-9a-f]{32}$/u.test(value.board ?? '') || typeof value.url !== 'string') throw new Refused('RELAY_STORAGE', 'restore the supported deleted-copy notice before reading relay status');+ relayOrigin(value.url);+ return value;+}++/** Accept deletion only from the configured versioned relay for this credential's own board. */+function confirmedDeletion(state, error) {+ return error instanceof Refused && error.httpStatus === 410 && error.relayVersion === 1+ && error.relayCode === 'RELAY_BOARD_DELETED' && error.relayMessage?.startsWith(`relay copy ${state.board} was deleted;`);+}++/** Preserve a truthful local notice before removing an inert link; the native board is never replaced. */+function forgetDeletedCopy(root, file, state, io) {+ const marker = deletedLinkFile(root);+ const temporary = marker + '.' + randomUUID() + '.tmp';+ try {+ writeFileSync(temporary, JSON.stringify({ version: 1, board: state.board, url: state.url }) + '\n', { flag: 'wx', mode: 0o600 });+ renameSync(temporary, marker);+ } finally { rmSync(temporary, { force: true }); }+ updateRelayMachine(machine => { const project = repoInfo(root).root; if (!machine.excluded.includes(project)) machine.excluded.push(project); });+ rmSync(file, { force: true });+ try { forgetBoardKey(state.board, state.keyStorage); } catch { /* An unavailable key store cannot block completed local opt-out. */ }+ if (!DELETION_NOTICES.has(io)) {+ DELETION_NOTICES.add(io);+ io.err(`pullboard: [RELAY_BOARD_DELETED] relay copy ${state.board} was deleted; local work continues; run pullboard relay on only to link it again`);+ }+}+/** Validate private link metadata before trusting its destination or acknowledgement cursor. */function loadLink(file) {if (!existsSync(file)) return null;@@ -245,7 +285,11 @@ function recoverySummary(state) {/** Expose key-free link status; only an explicit link operation includes its pairing carrier. */function summary(root, state, { pairing = false } = {}) {- if (!state) return { linked: false, board: '', url: '', link: '', sequence: 0, behind: 0, recovery: recoverySummary(null) };+ if (!state) {+ const deleted = deletedLink(root);+ return { linked: false, board: deleted?.board ?? '', url: deleted?.url ?? '', link: '', sequence: 0, behind: 0, recovery: recoverySummary(null),+ ...(deleted ? { deleted: true, notice: 'The relay copy was deleted; your local board is complete. Keep working locally, or run pullboard relay on to link it again.' } : {}) };+ }if (state.unlinking) return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, cleanup: true, recovery: recoverySummary(state) };const fragment = pairing ? '&key=' + encodeBoardKey(readBoardKey(state.board)) : '';const oversizedSnapshot = snapshotSize(state);@@ -984,14 +1028,16 @@ export async function relayOperation(root, operation, args, io, command, applyLotry { await publishCheckpoint(root, file, state, io); }catch (error) {if (!(error instanceof Refused)) throw error;- if (error.code === 'AUTH_REQUIRED') reportExpiredSignIn(state, io);+ if (confirmedDeletion(state, error)) forgetDeletedCopy(root, file, state, io);+ else if (error.code === 'AUTH_REQUIRED') reportExpiredSignIn(state, io);else io.err(`pullboard: ${error.message}`);}if (receipt.outcome.error) throw refusalFromReceipt(receipt.outcome.error);- if (['register', 'ensureCoordinator'].includes(operation)) await actorTransport(root, file, state, receipt.outcome.result, io);+ if (existsSync(file) && ['register', 'ensureCoordinator'].includes(operation)) await actorTransport(root, file, state, receipt.outcome.result, io);for (const event of receipt.outcome.events ?? []) io.onEvent?.(event);return receipt.outcome.result;} catch (error) {+ if (confirmedDeletion(state, error)) { forgetDeletedCopy(root, file, state, io); return applyPausedMoveLocally(); }if (error instanceof Refused && error.code === 'AUTH_REQUIRED') throw expiredSignInMoveRefusal(state, error);throw error;}@@ -1026,6 +1072,7 @@ export async function syncRelay(root, io) {}catch (error) {if (!(error instanceof Refused)) throw error;+ if (confirmedDeletion(state, error)) { forgetDeletedCopy(root, file, state, io); return summary(root, null); }if (error.code === 'RELAY_KEY_MISSING') {if (!KEY_WARNED_COMMANDS.has(io)) {KEY_WARNED_COMMANDS.add(io);@@ -1375,6 +1422,7 @@ export async function relayOn(root, address, io, { session, credential, quiet =}if (ready) ready = await ensureOrdered(root, file, state, io);if (ready) {+ rmSync(deletedLinkFile(root), { force: true });await catchUp(root, file, state, io);await deliverDeviceWraps(root, io);updateRelayMachine(machine => { machine.excluded = machine.excluded.filter(entry => entry !== repoInfo(root).root); });@@ -1394,7 +1442,15 @@ export async function relayOff(root, io) {return locked(file, async () => {const state = loadLink(file);if (!state) return summary(root, null);+ let joined = [];+ try {+ const roster = await request(state, '/auth/machines?board=' + state.board, {}, io);+ if (Array.isArray(roster.machines)) joined = roster.machines.filter(entry => typeof entry.machine === 'string' && /^[A-Za-z0-9_.-]{1,128}$/u.test(entry.machine) && entry.machine !== state.machine).map(entry => entry.machine);+ } catch { /* Local unlink still completes when the relay cannot inventory joined computers. */ }+ const warning = joined.length ? ' If you approve deletion, joined computers ' + joined.map(machine => machine.slice(-8)).join(', ') + ' lose the shared copy; their local boards keep working.' : '';+ if (warning) io.err(warning.trim());// Local unlink always completes, including agent shells, outages and a fenced remote baseline.+let proposal;try { proposal = await phoneProposal(state, 'delete-board', state.board); }catch { /* Missing key or pairing cannot stop local unlinking. */ }@@ -1412,7 +1468,8 @@ export async function relayOff(root, io) {}return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, recovery: recoverySummary(null),...(remote ? { remote } : {}),- notice: 'Local link removed. The relay copy stays until you approve deleting it on your phone.' + (requested ? '' : ' Open the phone to manage the relay copy.') };+ ...(joined.length ? { affectedMachines: joined } : {}),+ notice: 'Local link removed. The relay copy stays until you approve deleting it on your phone.' + warning + (requested ? '' : ' Open the phone to manage the relay copy.') };});}diff --git a/test/relay-auth-expired.test.js b/test/relay-auth-expired.test.jsindex 3857cf04..41c258f5 100644--- a/test/relay-auth-expired.test.js+++ b/test/relay-auth-expired.test.js@@ -4,6 +4,8 @@ import { test } from 'node:test';import { existsSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { fileURLToPath } from 'node:url';+import { createDeviceKeys, signDeviceEnrollment } from '../src/relay-device-keys.js';+import { ENGINE_VERSION } from '../src/machine.js';import { relayClientFixture } from './relay-client-fixture.js';import { runFixtureGit } from './fixture-child.js';@@ -207,3 +209,118 @@ test('relay off keeps a board out of auto-link [H1,H7,H16]', async t => {assert.equal(box.calls.length, callsBeforeStatus, 'auto-link does not contact the relay or relink an excluded board');assert.ok(JSON.parse(readFileSync(machineFile, 'utf8')).excluded.includes(box.root));});++/** Enroll one cryptographically authenticated phone through the production native and HTTP paths. */+async function enrollDeletionPhone(box) {+ const machineURL = new URL('../src/relay-machine.js', import.meta.url).href;+ const linked = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const pendingResult = await box.script(`+ const { beginDeviceEnrollment } = await import(${JSON.stringify(machineURL)});+ console.log(JSON.stringify(beginDeviceEnrollment(${JSON.stringify(linked.board)},+ { account: ${JSON.stringify(linked.account)}, url: ${JSON.stringify(box.origin)} })));+ `);+ assert.equal(pendingResult.code, 0, 'the native machine creates a one-use phone enrollment');+ const pending = pendingResult.document;+ const phone = await box.phoneSession();+ const keys = await createDeviceKeys();+ const value = await signDeviceEnrollment(pending.secret, { v: 1, account: pending.account, locator: pending.locator,+ deviceId: keys.deviceId, publicKey: keys.publicKey, label: 'Deletion fixture phone', createdAt: new Date().toISOString() });+ const headers = { authorization: 'Bearer ' + phone.token, 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) };+ const path = '/api/v1/devices/enrollments/' + pending.locator;+ assert.equal((await fetch(box.origin + path, { method: 'POST', headers, body: '{}' })).status, 200);+ assert.equal((await fetch(box.origin + path, { method: 'PUT', headers, body: JSON.stringify(value) })).status, 200);+ const delivered = await (await fetch(box.origin + path, { headers })).json();+ const accepted = await box.script(`+ const { acceptDeviceEnrollment } = await import(${JSON.stringify(machineURL)});+ await acceptDeviceEnrollment(${JSON.stringify(delivered.enrollment)});+ console.log(JSON.stringify({ accepted: true }));+ `);+ assert.equal(accepted.code, 0, 'the native machine authenticates the returned enrollment before trusting it');+ assert.equal((await fetch(box.origin + '/api/v1/devices/' + keys.deviceId, { method: 'POST', headers, body: '{}' })).status, 200);+ assert.equal((await fetch(box.origin + path, { method: 'DELETE', headers })).status, 200);+ return { phone, headers, deviceId: keys.deviceId };+}++/** Pair an actual independent clone and leave one enrolled phone able to approve deletion. */+async function joinedDeletionFixture(t) {+ const box = await relayClientFixture(t);+ await box.link();+ const printed = await box.cli('relay', 'pair');+ assert.equal(printed.code, 0, 'the owner publishes a real one-use computer pairing code');+ const joined = await box.otherDeviceJoin(printed.document.code);+ const phone = await enrollDeletionPhone(box);+ return { box, joined, ...phone };+}++test('a joined computer adds locally after the owner deletes the relay copy [H17,E9]', async (t) => {+ const { box, joined, headers, deviceId } = await joinedDeletionFixture(t);+ const board = JSON.parse(readFileSync(box.linkFile, 'utf8')).board;+ const off = await box.cli('relay', 'off');+ assert.equal(off.code, 0, 'the owner unlinks locally before phone approval');+ const inbox = await (await fetch(box.origin + '/api/v1/devices/' + deviceId + '/approvals', { headers })).json();+ const approval = inbox.approvals.find(entry => entry.context.action === 'delete-board' && entry.context.board === board);+ assert.ok(approval, "the real phone receives the owner's deletion request");+ const removed = await fetch(box.origin + '/api/v1/devices/approvals/' + approval.context.id + '/authorize', { method: 'POST', headers, body: '{}' });+ assert.equal(removed.status, 200, 'the phone approves deletion through the real authorization endpoint');+ assert.equal((await removed.json()).result.deleted, board);+ const added = await joined.cli('add', box.lane, 'local work survives remote deletion');+ assert.equal(added.code, 0, added.document.error ? `${added.document.error.code}: ${added.document.error.message}` : 'the joined computer adds locally after deletion');+ const diagnostics = (added.document.diagnostics ?? []).join('\n');+ assert.match(diagnostics, /relay copy.*deleted|deleted.*relay copy/u, 'the diagnostic names the deleted shared copy');+ assert.doesNotMatch(diagnostics, /sign-in expired|AUTH_REQUIRED/u, 'deletion is never mislabeled as expired sign-in');+ const exported = await joined.cli('export');+ assert.equal(exported.code, 0);+ assert.equal(exported.document.tables.item.filter(row => row.item_title === 'local work survives remote deletion').length, 1,+ 'the successful local move is recorded exactly once');+ const status = await joined.cli('status');+ assert.equal(status.code, 0);+ assert.equal(status.document.relay.linked, false, 'the deleted relay copy no longer intercepts later local moves');+});++test('the owner is warned that deleting the relay copy cuts off joined computers [H17,E9]', async (t) => {+ const { box, joined } = await joinedDeletionFixture(t);+ const off = await box.cli('relay', 'off');+ assert.equal(off.code, 0);+ assert.match(off.document.notice, /joined computer.*lose.*shared copy/u, 'the warning names the consequence before phone approval');+ assert.ok(off.document.affectedMachines.includes(joined.machine), 'the warning identifies exactly which joined computer loses the shared copy');+ assert.equal(box.auth.linkedBoards().length, 1, 'the warning is returned before the phone has approved any deletion');+});+++test('an agent token cannot inventory joined computers [H17,E9]', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const token = await box.auth.issueToken(state.token, { board: state.board, agent: 'roster-probe' });+ const response = await fetch(box.origin + '/auth/machines?board=' + state.board, {+ headers: { authorization: 'Bearer ' + token.token },+ });+ assert.equal(response.status, 403);+ assert.equal((await response.json()).error.code, 'HUMAN_REQUIRED', 'a scoped agent can never list joined computers');+});+++test('another board deletion never turns this board into local mode [H17,E9]', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const other = await box.additionalBoard('separate shared board');+ const phone = await box.phoneSession();+ const token = await box.auth.issueToken(phone.token, { board: other.id, agent: 'foreign-deleted-board' });+ const before = (await box.cli('export')).document.tables;+ const removed = await fetch(box.origin + '/api/v1/boards/' + other.id, { method: 'DELETE',+ headers: { authorization: 'Bearer ' + phone.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });+ assert.equal(removed.status, 200, 'the phone deletes only the independent board copy');+ box.env.PULLBOARD_RELAY_TOKEN = token.token;+ try {+ const refused = await box.cli('add', box.lane, 'must stay ordered on the surviving board');+ assert.equal(refused.code, 1, 'a deletion response naming another board never permits a local move');+ assert.equal(refused.document.error.code, 'RELAY_BOARD_DELETED');+ assert.equal(existsSync(box.linkFile), true, 'the surviving board keeps its ordered link');+ } finally { delete box.env.PULLBOARD_RELAY_TOKEN; }+ const exported = await box.cli('export');+ assert.equal(exported.code, 0);+ assert.deepEqual(exported.document.tables, before, 'the refused move changes no local row');+ assert.equal((await box.cli('status')).document.relay.board, state.board);+ assert.equal((await box.cli('add', box.lane, 'the surviving board still syncs')).code, 0, 'ordinary ordered work remains available with its own credential');+});diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 367bdc45..6e37efc7 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -657,7 +657,7 @@ globalThis.fetch = function tracedFetch(input, init) {const envKey = { ...otherEnv, PULLBOARD_RELAY_KEY: environmentKey };return childResult(otherRoot, envKey, [CLI, ...args, '--json']);}- return { joined: document, exported: exported.document, cli: run, syncWithEnvironmentKey,+ return { joined: document, machine: link.machine, exported: exported.document, cli: run, syncWithEnvironmentKey,/** Check that the paired clone still has no persisted board-key file. */keyFileExists() { return existsSync(otherKeyFile); } };}diff --git a/test/relay-machine-auth.test.js b/test/relay-machine-auth.test.jsindex 96b6aaa0..005fe6f0 100644--- a/test/relay-machine-auth.test.js+++ b/test/relay-machine-auth.test.js@@ -4,6 +4,7 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';+import { DatabaseSync } from 'node:sqlite';import { createRelayAuth } from '../relay/auth.js';import { createGitHubClient } from '../relay/github.js';import { githubFixture } from './relay-fixture.js';@@ -65,3 +66,50 @@ test('machine credentials mint and list same-board agents but cannot link, revokassert.equal((await auth.authenticate(personIssued.token, { board: alpha })).kind, 'board');assert.deepEqual((await auth.boardsFor(person.token)).map(row => row.id), [alpha, beta], 'only the person session can inventory multiple linked boards');});+++test('deleted-copy receipts grant no access and keep revocation and expiry distinct [H16,H17,E9]', async (t) => {+ const provider = await githubFixture(t);+ const root = mkdtempSync(join(tmpdir(), 'pullboard-deleted-credential-'));+ const database = join(root, 'auth.sqlite');+ let now = Date.now();+ const options = { database, github: createGitHubClient(provider.config), now: () => now };+ let auth = createRelayAuth(options);+ t.after(() => { auth.close(); rmSync(root, { recursive: true, force: true }); });+ const person = await signedPerson({ ...provider, advance(ms) { now += ms; } }, auth);+ const alpha = 'a'.repeat(32), beta = 'b'.repeat(32);+ await auth.linkBoard(person.token, alpha, 'fixture/repository');+ await auth.linkBoard(person.token, beta, 'fixture/repository');+ const live = await auth.issueMachine(person.token, { board: alpha, machine: 'joined-alpha' });+ const revoked = await auth.issueMachine(person.token, { board: alpha, machine: 'revoked-alpha' });+ const expired = await auth.issueMachine(person.token, { board: alpha, machine: 'expired-alpha', expiresIn: 1 });+ const other = await auth.issueMachine(person.token, { board: beta, machine: 'joined-beta' });+ await auth.revoke(person.token, revoked.id);+ now += 2;+ assert.deepEqual((await auth.listMachines(live.token, alpha)).map(row => ({ ...row })), [{ machine: 'joined-alpha' }],+ 'the roster excludes revoked and expired computer credentials');+ await assert.rejects(auth.listMachines(live.token, beta), { code: 'TOKEN_BOARD' });+ auth.forgetBoard(alpha);+ auth.close(); auth = createRelayAuth(options);+ await assert.rejects(auth.authenticate(live.token, { board: alpha }), { code: 'RELAY_BOARD_DELETED' }, 'a live former credential receives only a durable deletion refusal');+ await assert.rejects(auth.authenticate(revoked.token, { board: alpha }), { code: 'AUTH_REQUIRED' }, 'an earlier revocation never becomes proof of deletion');+ await assert.rejects(auth.authenticate(expired.token, { board: alpha }), { code: 'AUTH_REQUIRED' }, 'an already expired credential never becomes proof of deletion');+ await assert.rejects(auth.authenticate('pm_' + 'A'.repeat(43), { board: alpha }), { code: 'AUTH_REQUIRED' }, 'an unknown credential learns nothing');+ assert.equal((await auth.authenticate(other.token, { board: beta })).machine, 'joined-beta');+ assert.equal((await auth.authenticate(person.token)).kind, 'session', 'board deletion never revokes the person session');+ let db = new DatabaseSync(database, { readOnly: true });+ try {+ const rows = db.prepare('SELECT hash,board,expires FROM relay_deleted_credentials').all();+ assert.equal(rows.length, 1, 'only the originally live credential has a receipt');+ assert.match(rows[0].hash, /^[0-9a-f]{64}$/u);+ assert.equal(rows[0].board, alpha);+ assert.equal(rows[0].expires, live.expires, 'the receipt never extends the original credential lifetime');+ assert.equal(db.prepare('SELECT COUNT(*) AS count FROM relay_credentials WHERE board=?').get(alpha).count, 0, 'no deleted-board credential retains authority');+ } finally { db.close(); }+ assert.equal(readFileSync(database).includes(live.token), false, 'the deletion receipt persists no bearer value');+ now = live.expires;+ await assert.rejects(auth.authenticate(live.token, { board: alpha }), { code: 'AUTH_REQUIRED' });+ db = new DatabaseSync(database, { readOnly: true });+ try { assert.equal(db.prepare('SELECT COUNT(*) AS count FROM relay_deleted_credentials').get().count, 0, 'expired deletion receipts are pruned'); }+ finally { db.close(); }+});diff --git a/test/relay-retention.test.js b/test/relay-retention.test.jsindex b2601ed0..83bc9a4a 100644--- a/test/relay-retention.test.js+++ b/test/relay-retention.test.js@@ -126,7 +126,7 @@ test('[H18] ninety-day expiry unlinks data and credentials while preserving theconst expired = await box.call(A);assert.equal(expired.status, 404);for (const suffix of ['', '-wal', '-shm']) assert.equal(existsSync(join(box.data, A + '.journal.sqlite' + suffix)), false);- assert.equal((await box.call(A, { token: box.agent.token })).status, 401);+ assert.equal((await box.call(A, { token: box.agent.token })).status, 410, 'the former live credential receives a deleted-copy refusal, never data');assert.equal((await box.call(B, { token: box.other.token })).status, 200);assert.equal((await box.auth.authenticate(box.signed.token)).kind, 'session');assert.deepEqual(box.auth.linkedBoards().map((row) => row.id), [B]);@@ -153,7 +153,7 @@ test('[H18] explicit unlink removes managed backups immediately and a durable crbox.auth.forgetBoard(B);assert.ok(existsSync(join(box.data, B + '.journal.sqlite')));assert.deepEqual(box.auth.pendingCleanup(), [B]);- await assert.rejects(box.auth.authenticate(box.other.token, { board: B }), { code: 'AUTH_REQUIRED' });+ await assert.rejects(box.auth.authenticate(box.other.token, { board: B }), { code: 'RELAY_BOARD_DELETED' });await assert.rejects(box.auth.linkBoard(box.signed.token, B, 'fixture/repository'), { code: 'RELAY_CLEANUP' });const freshAuth = createRelayAuth({ database: join(box.root, 'auth.sqlite'), github: {} });try {diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.jsindex 2dbaa441..dc666fb6 100644--- a/test/relay-sealed.test.js+++ b/test/relay-sealed.test.js@@ -1290,7 +1290,10 @@ test('[A4,H7] snapshots compact covered moves, preserve the tail and deletion reassert.equal((await box.call(box.path, { method: 'DELETE', token: box.person.token })).status, 200);for (const suffix of ['', '-wal', '-shm']) assert.equal(existsSync(join(box.data, box.id + '.journal.sqlite' + suffix)), false);assert.equal((await box.call(box.path + '/state', { token: box.person.token })).status, 404);- assert.equal((await box.call(box.path + '/state')).status, 401, 'unlink revokes board-scoped credentials');+ const deletedCredential = await box.call(box.path + '/state');+ assert.equal(deletedCredential.status, 410, 'a former live board credential names the deleted copy without granting access');+ assert.equal(deletedCredential.body.error.code, 'RELAY_BOARD_DELETED');+ assert.equal(deletedCredential.body.state, undefined, 'the deleted credential receives no sealed board data');assert.deepEqual(box.clientOpen((await box.call(otherPath + '/state', { token: box.person.token })).body.state.sealed, 'snapshot', 0, other), { other: true });assert.deepEqual(JSON.parse(box.cli('export')), box.document);});