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.

test(core): integrate landed phone authority [C7]

Corey Olson3f111754c9f0
diff --cc test/relay-agent.test.js
index 542e03c3,e54baef8..325da448
--- a/test/relay-agent.test.js
+++ b/test/relay-agent.test.js
@@@ -1,6 -1,6 +1,6 @@@
/** Private end-to-end proof for ordered agent enrollment and scoped relay credentials [H2,H9,A4]. */
import assert from 'node:assert/strict';
- import { runFixtureChild as spawnSync, cleanupFixtureChildren, runFixtureChild, runFixtureChildAsync } from './fixture-child.js';
-import { spawn, spawnSync } from 'node:child_process';
++import { startFixtureChild as spawn, runFixtureChild as spawnSync, cleanupFixtureChildren, runFixtureChild, runFixtureChildAsync } from './fixture-child.js';
import { createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { chmodSync, existsSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
@@@ -15,22 -15,122 +15,112 @@@ import { decodeBoardKey, unseal } from
import { frozenCriterion, parseSpec } from '../src/spec.js';
import { relayClientFixture } from './relay-client-fixture.js';
import { fetchFresh } from './http-fixture.js';
+ import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';
+ import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
-/** Invoke one real CLI command without retaining stderr or exposing private command output. */
+after(cleanupFixtureChildren);
+
+/** Invoke one real CLI command and retain only redacted child diagnostics on failure. */
function runCli(root, env, cli, args) {
- return new Promise((resolveResult, reject) => {
- const child = spawn(process.execPath, [cli, ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });
- let stdout = '';
- const timer = setTimeout(() => child.kill('SIGKILL'), 25000);
- child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });
- child.stderr.resume();
- child.once('error', (error) => { clearTimeout(timer); reject(error); });
- child.once('close', (code, signal) => {
- clearTimeout(timer);
- if (signal) return reject(new Error('private agent CLI exceeded its deadline'));
- try { resolveResult({ code, document: JSON.parse(stdout) }); }
- catch { reject(new Error(`private agent CLI ${args[0]} did not return JSON (exit ${code ?? 'signal'})`)); }
- });
+ return runFixtureChildAsync(process.execPath, [cli, ...args, '--json'], { cwd: root, env }).then((result) => {
+ if (result.error) throw new Error(result.failure);
+ try { return { code: result.status, document: JSON.parse(result.stdout), stderr: result.failure ?? result.stderr, failure: result.failure }; }
+ catch { throw new Error(result.failure ?? result.context); }
});
}
+ /** Run a foreground private CLI command while another actor completes its phone approval. */
+ function startCli(root, env, cli, args) {
+ const child = spawn(process.execPath, [cli, ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let stdout = '';
- const timer = setTimeout(() => child.kill('SIGKILL'), 90000);
+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });
+ child.stderr.resume();
+ const done = new Promise((resolveResult, reject) => {
- child.once('error', error => { clearTimeout(timer); reject(error); });
+ child.once('close', (code, signal) => {
- clearTimeout(timer);
- if (signal) return reject(new Error('private phone-approved command ended with a signal'));
- try { resolveResult({ code, document: JSON.parse(stdout) }); }
- catch { reject(new Error(`private phone-approved command ${args[0]} did not return JSON (exit ${code ?? 'signal'})`)); }
++ if (signal) return reject(new Error(child.fixtureFailure));
++ try { resolveResult({ code, document: JSON.parse(stdout), failure: child.fixtureFailure }); }
++ catch { reject(new Error(child.fixtureFailure ?? `private phone-approved command ${args[0]} did not return JSON (exit ${code ?? 'signal'})`)); }
+ });
+ });
+ return { child, done };
+ }
+
+ /** Poll a real fixture condition without retrying the operation under test. */
+ async function waitFor(read, message, timeout = 30000) {
+ const deadline = Date.now() + timeout;
+ do {
+ const value = await read();
+ if (value) return value;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ } while (Date.now() < deadline);
+ assert.fail(message);
+ }
+
+ /** Read a phone approval proposal from the real relay traffic without exposing its sealed payload. */
+ async function waitForPhoneProposal(box, start, target) {
+ return waitFor(() => {
+ const record = box.transit.slice(start).findLast(row => row.method === 'POST' && row.path === '/api/v1/devices/approvals');
+ if (!record) return null;
+ try {
+ const context = JSON.parse(record.request.toString('utf8')).context;
+ if (context?.action !== 'revoke-token' || context.target !== target) return null;
+ const response = JSON.parse(record.response.toString('utf8'));
+ assert.equal(response.error?.code, undefined, 'the relay accepts the exact native approval proposal');
+ assert.equal(response.approval?.state, 'waiting', 'the proposal is durably waiting before any phone tap');
+ assert.equal(response.approval?.context?.id, context.id, 'the relay acknowledges the same proposal id');
+ return context;
+ } catch (error) {
+ if (error?.code === 'ERR_ASSERTION') throw error;
+ return null;
+ }
+ }, 'the revocation publishes one exact phone approval request');
+ }
+
+ /** Read and click only the paired-phone card for this opaque target id. */
+ async function approvePhoneProposal(box, chrome, proposal) {
+ const selector = `.phone-approval[data-request="${proposal.id}"]`;
+ try {
+ await chrome.waitFor(`Boolean(document.querySelector(${JSON.stringify(selector)})?.querySelector('button'))`);
+ } catch (error) {
+ let page = { capture: 'unavailable' };
+ try {
+ page = await chrome.evaluate(`(() => {
+ const panel = document.getElementById('phone-approvals');
+ let boardKeyKnown = false;
+ try { boardKeyKnown = Object.hasOwn(JSON.parse(localStorage.getItem('pullboard.relay.keys.v1') || '{}'), ${JSON.stringify(proposal.publisher)}); } catch {}
+ return { readyState: document.readyState, path: location.pathname, panel: Boolean(panel),
+ panelError: (panel?.getAttribute('data-error') || '').slice(0, 200),
+ cards: panel?.children.length ?? 0, boardKeyKnown,
+ signIn: Boolean(document.querySelector('a[href="/auth/github/start"]')) };
+ })()`, 'redacted phone approval failure capture', 1000);
+ } catch { /* Preserve the original failure when the renderer cannot answer diagnostics. */ }
+ const inboxPath = '/api/v1/devices/' + proposal.device + '/approvals';
+ const inbox = box.transit.findLast(row => row.method === 'GET' && row.path === inboxPath);
+ let response = null;
+ try {
+ const document = JSON.parse(inbox?.response.toString('utf8') || '{}');
+ const row = document.approvals?.find(value => value.context?.id === proposal.id);
+ response = { error: document.error?.code ?? null, pending: document.approvals?.length ?? null,
+ targetPresent: Boolean(row), state: row?.state ?? null };
+ } catch { /* Transport diagnostics retain only known metadata, never ciphertext or credentials. */ }
+ error.message += '; redacted approval evidence: ' + JSON.stringify({ page, response,
+ inboxReads: box.calls.filter(row => row.method === 'GET' && row.path === inboxPath).length });
+ throw error;
+ }
+ const card = await chrome.evaluate(`(() => {
+ const node = document.querySelector(${JSON.stringify(selector)});
+ return { text: node.querySelector('p')?.textContent, action: node.querySelector('button')?.textContent };
+ })()`);
+ assert.match(card.text, /revoke/u);
+ assert.match(card.text, new RegExp(proposal.target));
+ assert.equal(card.action, 'Approve revocation', 'the paired phone presents an explicit revocation action');
+ await chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).querySelector('button').click(); true`);
+ }
+
/** Run Git in a private fixture and keep all diagnostics credential-free. */
function git(root, env, args) {
- const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });
- assert.equal(result.status, 0, `private Git fixture ${args[0]} succeeds: ${result.stderr}`);
+ const result = runFixtureChild('git', args, { cwd: root, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.failure ?? `private Git fixture ${args[0]} succeeds: ${result.stderr}`);
}
/** Return private Git output for a structural assertion without surfacing command diagnostics. */
@@@ -112,10 -215,32 +205,32 @@@ test('ordered agent joins mint scoped t
git(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-one', firstRoot, 'HEAD']);
git(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-two', secondRoot, 'HEAD']);
- await box.link();
+ const personEnv = { ...box.env };
+ for (const key of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete personEnv[key];
+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');
+ const setup = startCli(box.root, personEnv, cli, ['relay', 'on', '--all', '--url', box.origin]);
+ t.after(async () => {
+ if (setup.child.exitCode === null) setup.child.kill('SIGTERM');
+ await setup.done.catch(() => {});
+ });
+ const pending = await waitFor(() => existsSync(machineFile) && JSON.parse(readFileSync(machineFile, 'utf8')).pending,
+ 'foreground setup publishes a one-use phone enrollment');
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ const phone = await box.phoneSession();
+ assert.equal((await chrome.send('Network.setCookie', {
+ name: 'pb_session', value: phone.token, url: box.origin, httpOnly: true, sameSite: 'Lax',
+ })).success, true);
+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);
+ assert.equal((await setup.done).code, 0, 'foreground sign-in links and pairs the relay');
+ await chrome.waitFor("document.querySelector('#phone-approvals') !== null");
+ assert.match(JSON.parse(readFileSync(box.linkFile, 'utf8')).token, /^pm_[A-Za-z0-9_-]{43}$/u,
+ 'the native link holds only a machine credential');
+ assert.equal(Object.hasOwn(JSON.parse(readFileSync(machineFile, 'utf8')), 'session'), false,
+ 'the phone session is not persisted in the machine state');
const firstStart = box.calls.length;
const firstJoin = await runCli(firstRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);
- assert.equal(firstJoin.code, 0, 'the first worktree joins through the real linked CLI');
+ assert.equal(firstJoin.code, 0, firstJoin.failure ?? 'the first worktree joins through the real linked CLI');
const firstAgent = firstJoin.document.agent;
const firstCalls = box.calls.slice(firstStart);
const firstRegistration = firstCalls.findIndex((call) => call.method === 'POST' && call.path.endsWith('/moves'));
@@@ -169,17 -297,37 +287,37 @@@
const firstVerify = await runCli(firstRoot, { ...box.env, PULLBOARD_RELAY_TOKEN: firstToken }, cli,
['verify', String(oneItem.document.item.item_id), 'accept', '--note', 'checked the private submitted proof']);
- assert.equal(firstVerify.code, 0, `the first agent gives an ACCEPT verdict using only its scoped token (${firstVerify.document.error?.code ?? 'no refusal'})`);
+ assert.equal(firstVerify.code, 0, firstVerify.failure ?? `the first agent gives an ACCEPT verdict using only its scoped token (${firstVerify.document.error?.code ?? 'no refusal'})`);
const secondVerify = await runCli(secondRoot, { ...box.env, PULLBOARD_RELAY_TOKEN: secondToken }, cli,
['verify', String(twoItem.document.item.item_id), 'accept', '--note', 'checked the other private submitted proof']);
- assert.equal(secondVerify.code, 0, `the second agent gives an ACCEPT verdict using only its scoped token (${secondVerify.document.error?.code ?? 'no refusal'})`);
+ assert.equal(secondVerify.code, 0, secondVerify.failure ?? `the second agent gives an ACCEPT verdict using only its scoped token (${secondVerify.document.error?.code ?? 'no refusal'})`);
- const revoke = await box.cli('relay', 'revoke', firstTokenRow.id);
+ const firstApprovalCount = box.calls.filter((call) => call.path.endsWith('/authorize')).length;
+ const nativeRevokeStart = box.transit.length;
+ const nativeRevoke = startCli(box.root, personEnv, cli, ['relay', 'revoke', firstTokenRow.id]);
+ t.after(async () => { if (nativeRevoke.child.exitCode === null) nativeRevoke.child.kill('SIGTERM'); await nativeRevoke.done.catch(() => {}); });
+ const nativeProposal = await waitForPhoneProposal(box, nativeRevokeStart, firstTokenRow.id);
+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, firstApprovalCount,
+ 'native revocation waits for a phone tap');
+ await approvePhoneProposal(box, chrome, nativeProposal);
+ const revoke = await nativeRevoke.done;
- assert.equal(revoke.code, 0, 'CLI revokes one listed opaque token id');
+ assert.equal(revoke.code, 0, revoke.failure ?? 'CLI revokes one listed opaque token id');
- const apiRevokeResponse = await fetchFresh(tokenUrl, {
+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, firstApprovalCount + 1,
+ 'one explicit phone approval authorizes native revocation');
+
+ const apiApprovalCount = box.calls.filter((call) => call.path.endsWith('/authorize')).length;
+ const apiRevokeStart = box.transit.length;
+ const apiRevokePending = fetchFresh(tokenUrl, {
method: 'POST', headers: apiHeaders, body: JSON.stringify({ id: firstTokenRow.id }),
});
+ const apiProposal = await waitForPhoneProposal(box, apiRevokeStart, firstTokenRow.id);
+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, apiApprovalCount,
+ 'local API revocation waits for a phone tap');
+ await approvePhoneProposal(box, chrome, apiProposal);
+ const apiRevokeResponse = await apiRevokePending;
assert.equal(apiRevokeResponse.status, 200, 'local API accepts the opaque id-only revocation body');
+ assert.equal(box.calls.filter((call) => call.path.endsWith('/authorize')).length, apiApprovalCount + 1,
+ 'one explicit phone approval authorizes local API revocation');
const apiRevoke = await apiRevokeResponse.json();
assert.equal(apiRevoke.id, firstTokenRow.id);
assert.equal(apiRevoke.revoked, true);
@@@ -226,9 -374,9 +364,9 @@@
const secondEnv = { ...box.env, PULLBOARD_RELAY_TOKEN: secondToken };
const tokenOnlyRead = await runCli(secondRoot, secondEnv, cli, ['list', '--all']);
- assert.equal(tokenOnlyRead.code, 0, tokenOnlyRead.failure ?? 'the other agent reads through its scoped token after person revocation');
- assert.equal(tokenOnlyRead.code, 0, 'the other agent reads through its scoped token after PM revocation');
++ assert.equal(tokenOnlyRead.code, 0, tokenOnlyRead.failure ?? 'the other agent reads through its scoped token after PM revocation');
const tokenOnlyWrite = await runCli(secondRoot, secondEnv, cli, ['claim', String(workItem.document.item.item_id)]);
- assert.equal(tokenOnlyWrite.code, 0, tokenOnlyWrite.failure ?? 'the other agent writes through its scoped token after person revocation');
- assert.equal(tokenOnlyWrite.code, 0, 'the other agent writes through its scoped token after PM revocation');
++ assert.equal(tokenOnlyWrite.code, 0, tokenOnlyWrite.failure ?? 'the other agent writes through its scoped token after PM revocation');
const native = nativeEvents(boardFile);
assert.ok(native.some((row) => row.event_by === secondAgent && row.event_kind === 'claim' && row.item_id === workItem.document.item.item_id),
diff --cc test/relay-client.test.js
index cb4b992b,f612c361..f3bf9b65
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@@ -24,9 -24,9 +24,10 @@@ import { storeBoardKey } from '../src/r
import { ENGINE_VERSION } from '../src/machine.js';
import { presentationShout } from '../src/relay-presentation.js';
import { fetchFresh } from './http-fixture.js';
+ import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';
const SIGN_INS = new Map();
+after(cleanupFixtureChildren);
/** Read native gzip snapshots while retaining checks against historical uncompressed records. */
function snapshotDocument(plain) {
diff --cc test/relay-person-credential.test.js
index 00000000,6148ac89..6bb78c1f
mode 000000,100644..100644
--- a/test/relay-person-credential.test.js
+++ b/test/relay-person-credential.test.js
@@@ -1,0 -1,204 +1,203 @@@
+ /** Same-user agents keep working while only the paired phone holds person authority [H5,H16,H17,B26]. */
+ import assert from 'node:assert/strict';
-import { spawn, spawnSync } from 'node:child_process';
++import { startFixtureChild as spawn, runFixtureChild as spawnSync } from './fixture-child.js';
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs';
+ import { join, resolve } from 'node:path';
+ import { test } from 'node:test';
+ import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';
+ import { ENGINE_VERSION } from '../src/machine.js';
+ import { relayClientFixture } from './relay-client-fixture.js';
+ import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
+
+ const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');
+
+ /** Run a real native command while allowing a phone tap before the foreground process finishes. */
+ function command(root, environment, args) {
+ const child = spawn(process.execPath, [CLI, ...args, '--json'], { cwd: root, env: environment, stdio: ['ignore', 'pipe', 'pipe'] });
+ let output = '';
+ child.stdout.setEncoding('utf8').on('data', part => { output += part; });
+ child.stderr.resume();
+ const done = new Promise((resolveResult, reject) => {
- child.once('error', reject);
+ child.once('close', (code, signal) => {
- if (signal) return reject(new Error('private native command ended with ' + signal));
++ if (signal) return reject(new Error(child.fixtureFailure));
+ try { resolveResult({ code, document: JSON.parse(output) }); }
- catch { reject(new Error('private native command returned invalid JSON for ' + args[0])); }
++ catch { reject(new Error(child.fixtureFailure ?? 'private native command returned invalid JSON for ' + args[0])); }
+ });
+ });
+ return { child, done };
+ }
+
+ /** Poll an actual persisted or HTTP-observed condition without retrying a move. */
+ async function waitFor(read, message, milliseconds = 30000) {
+ const deadline = Date.now() + milliseconds;
+ do {
+ const value = await read();
+ if (value) return value;
+ await new Promise(resolve => { setTimeout(resolve, 25); });
+ } while (Date.now() < deadline);
+ assert.fail(message);
+ }
+
+ /** Inspect every regular client file without following symlinks outside the private fixture. */
+ function assertNoPersonPower(directory) {
+ for (const name of readdirSync(directory)) {
+ const path = join(directory, name);
+ const stat = lstatSync(path);
+ if (stat.isDirectory()) assertNoPersonPower(path);
+ else if (stat.isFile()) assert.equal(/(?:ps_|pg_)[A-Za-z0-9_-]{43}/u.test(readFileSync(path).toString('latin1')), false,
+ 'no client file stores a person session or native grant');
+ }
+ }
+
+ /** Run actual private Git with fixed identity and no credential-bearing diagnostics. */
+ function git(root, env, ...args) {
+ const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, 'private Git ' + args[0] + ' succeeds: ' + result.stderr.replace(/(?:ps_|pm_|pa_|pg_)[A-Za-z0-9_-]{43}/gu, '[private credential]'));
+ return result.stdout.trim();
+ }
+
+ test('same-user agents never act as their person while the phone approves native actions [H5,H16,H17,B26]', {
+ timeout: 180000,
+ }, async t => {
+ assert.ok(findChromeExecutable(), 'the security proof requires actual Chrome');
+ const box = await relayClientFixture(t);
+ symlinkSync('/bin/sh', join(box.env.PATH, 'sh'));
+ writeFileSync(join(box.env.PATH, 'pullboard'), '#!/bin/sh\nexec node ' + "'" + CLI.replaceAll("'", "'\\''") + "'" + ' "$@"\n', { mode: 0o700 });
+ const personEnv = { ...box.env };
+ for (const key of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete personEnv[key];
+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');
+ const fixtureSource = join(box.root, 'src/security-fixture.js');
+ mkdirSync(join(box.root, 'src'), { recursive: true });
+ writeFileSync(fixtureSource, 'export const ready = true;\n');
+ const configFile = join(box.root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configFile, 'utf8'));
+ const buildLane = 'core';
+ config.lanes[buildLane] = { owns: ['src/'], specs: ['G'] };
+ config.gate = 'node --check src/security-fixture.js';
+ writeFileSync(configFile, JSON.stringify(config, null, 2) + '\n');
+ writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8') + '\n- G1 [approved, must] A private security fixture parses. | gate: node --check src/security-fixture.js\n');
+ git(box.root, personEnv, 'add', '-A');
+ git(box.root, personEnv, 'commit', '-q', '-m', 'test(fixture): prepare native security proof [G1]');
+ const item = await box.cli('add', buildLane, 'native scoped work', '--specs', 'G1', '--criterion', 'the private source parses');
+ assert.equal(item.code, 0);
+ const itemId = item.document.item.item_id;
+
+ const setup = command(box.root, personEnv, ['relay', 'on', '--all', '--url', box.origin]);
+ t.after(async () => { if (setup.child.exitCode === null) setup.child.kill('SIGTERM'); await setup.done.catch(() => {}); });
+ const pending = await waitFor(() => existsSync(machineFile) && JSON.parse(readFileSync(machineFile)).pending,
+ 'foreground setup publishes the one-use phone enrollment');
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ const phone = await box.phoneSession();
+ await chrome.send('Network.setCookie', { name: 'pb_session', value: phone.token, url: box.origin, httpOnly: true, sameSite: 'Lax' });
+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);
+ assert.equal((await setup.done).code, 0, 'one foreground sign-in links and pairs without saving the session');
+ await chrome.waitFor("document.querySelector('#phone-approvals') !== null");
+ const machine = JSON.parse(readFileSync(machineFile));
+ const link = JSON.parse(readFileSync(box.linkFile));
+ assert.match(link.token, /^pm_[A-Za-z0-9_-]{43}$/u);
+ assert.equal(Object.hasOwn(machine, 'session'), false);
+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);
+
+ const joined = await command(box.root, personEnv, ['worktree', buildLane]).done;
+ assert.equal(joined.code, 0, 'machine credential enrolls the real agent without a tap: ' + joined.document.error?.code + ' ' + joined.document.error?.message);
+ const agentRoot = joined.document.path;
+ const agentId = joined.document.agent;
+ const agentEnv = { ...personEnv, AI_AGENT: '1', CODEX_SHELL: '1', CODEX_THREAD_ID: 'private-security-agent', SSH_CONNECTION: '127.0.0.1 1 127.0.0.1 2' };
+ const approvedBefore = box.calls.filter(call => call.path.endsWith('/authorize')).length;
+ const claim = await command(agentRoot, agentEnv, ['claim', String(itemId)]).done;
+ assert.equal(claim.code, 0, 'the SSH agent claims with its own PA while the phone remains active');
+ writeFileSync(join(agentRoot, 'src/security-fixture.js'), 'export const ready = true;\nexport const built = true;\n');
+ git(agentRoot, agentEnv, 'add', 'src/security-fixture.js');
+ git(agentRoot, agentEnv, 'commit', '-q', '-m', 'feat(fixture): prove scoped agent submit [G1]');
+ const submitted = await command(agentRoot, agentEnv, ['submit', String(itemId)]).done;
+ assert.equal(submitted.code, 0, 'the SSH agent submits a clean native commit with its gate green');
+ assert.equal((await command(agentRoot, agentEnv, ['shout', 'coordinator', 'scoped agent completed its work']).done).code, 0);
+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, approvedBefore, 'agent enroll/claim/submit/shout asks for no phone approval');
+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);
+ const state = JSON.parse(readFileSync(box.linkFile));
+ const pa = state.agentTokens[agentId];
+ assert.match(pa.token, /^pa_[A-Za-z0-9_-]{43}$/u);
+ const listed = await command(agentRoot, agentEnv, ['relay', 'tokens']).done;
+ assert.equal(listed.code, 0, 'board-scoped token ids need no tap');
+ assert.equal(listed.document.tokens.some(row => Object.hasOwn(row, 'token') || Object.hasOwn(row, 'hash')), false);
+ const nativeCalls = box.calls.filter(call => !call.browser).length;
+ const denied = await command(agentRoot, agentEnv, ['relay', 'revoke', machine.devices[0].deviceId]).done;
+ assert.equal(denied.code, 1);
+ assert.equal(denied.document.error.code, 'B26_PERSON_CHANNEL');
+ assert.equal(box.calls.filter(call => !call.browser).length, nativeCalls, 'an agent shell refuses before every approval/network request');
+
+ await t.test('saved PM and PA never acquire HTTP person authority [H16,B26]', async () => {
+ const other = await box.additionalBoard('independent board remains private');
+ for (const token of [state.token, pa.token]) {
+ const headers = { authorization: 'Bearer ' + token, 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) };
+ const inventory = await fetch(box.origin + '/auth/boards', { headers });
+ assert.equal(inventory.status, 200);
+ assert.deepEqual((await inventory.json()).boards.map(value => value.id), [state.board]);
+ for (const [path, body, method = 'POST'] of [
+ ['/auth/boards/link', { board: 'c'.repeat(32), repository: 'fixture/repository' }],
+ ['/auth/machines', { board: state.board, machine: 'forged-machine' }],
+ ['/auth/tokens/revoke', { id: phone.id }],
+ ['/auth/tokens', { board: other.id, agent: 'cross-board' }],
+ ['/api/v1/boards/' + state.board + '/requests', { sequence: 1, sealed: 'AA' }],
+ ['/api/v1/devices/' + machine.devices[0].deviceId, undefined, 'DELETE'],
+ ['/api/v1/boards/' + other.id + '/state', undefined, 'GET'],
+ ]) {
+ const response = await fetch(box.origin + path, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}) });
+ assert.ok(response.status >= 400 && response.status < 500, 'a stored credential cannot exercise ' + method + ' ' + path);
+ }
+ const cookie = await fetch(box.origin + '/auth/boards', { headers: { cookie: 'pb_session=' + token } });
+ assert.equal(cookie.status, 401, 'a saved delegate cannot become the phone cookie');
+ }
+ });
+
+ await t.test('the paired phone still sends person intent through the actual page [H12,H16,B26]', async () => {
+ await chrome.navigate(box.origin + '/#board=' + state.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());
+ await chrome.waitFor('typeof data !== "undefined" && !!data?.project && !!transport');
+ await chrome.evaluate(`document.querySelector('[data-tab=shouts]').click(); document.querySelector('#shout-to').value='coordinator'; document.querySelector('#shout-text').value='PRIVATE_PHONE_PERSON_ACTION'; document.querySelector('#shout-form').requestSubmit(); true`);
+ await chrome.waitFor('data.project.personRequests?.some(row => row.move?.args?.text === "PRIVATE_PHONE_PERSON_ACTION")');
+ assert.equal((await command(agentRoot, agentEnv, ['status']).done).code, 0, 'the native machine fulfils the ordered phone request while the agent keeps working');
+ const exported = await command(box.root, personEnv, ['export']).done;
+ assert.equal(exported.code, 0);
+ assert.equal(exported.document.tables.shout.filter(row => row.shout_from === 'person' && row.shout_text === 'PRIVATE_PHONE_PERSON_ACTION').length, 1);
+ assertNoPersonPower(box.root); assertNoPersonPower(agentRoot); assertNoPersonPower(box.env.HOME);
+ });
+
+ await t.test('native token revocation needs exactly one phone tap and the grant cannot replay [H16,B26]', async () => {
+ const revoke = command(box.root, personEnv, ['relay', 'revoke', pa.id]);
+ t.after(async () => { if (revoke.child.exitCode === null) revoke.child.kill('SIGTERM'); await revoke.done.catch(() => {}); });
+ await chrome.waitFor("[...document.querySelectorAll('.phone-approval')].some(node => node.textContent.includes(" + JSON.stringify(pa.id) + '))');
+ const before = box.calls.filter(call => call.path.endsWith('/authorize')).length;
+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);
+ await chrome.evaluate("[...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(" + JSON.stringify(pa.id) + ')).querySelector("button").click()');
+ assert.equal((await revoke.done).code, 0);
+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, before + 1, 'one tap issues one grant');
+ const execution = box.transit.findLast(record => record.path.endsWith('/execute'));
+ const replay = await fetch(box.origin + execution.path, { method: 'POST', headers: { authorization: 'Bearer ' + state.token,
+ 'content-type': 'application/json', 'x-pullboard-engine': String(ENGINE_VERSION) }, body: execution.request });
+ assert.notEqual(replay.status, 200, 'the exact already consumed grant refuses replay');
+ assert.equal((await replay.json()).error.code, 'PHONE_APPROVAL_USED');
+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);
+ });
+ await t.test('native device revocation needs one phone tap and offline agent unlink always works [H5,H16,H17,B26]', async () => {
+ const target = machine.devices[0].deviceId;
+ const revoke = command(box.root, personEnv, ['relay', 'revoke', target]);
+ t.after(async () => { if (revoke.child.exitCode === null) revoke.child.kill('SIGTERM'); await revoke.done.catch(() => {}); });
+ await chrome.waitFor("[...document.querySelectorAll('.phone-approval')].some(node => node.textContent.includes(" + JSON.stringify(target) + '))');
+ const before = box.calls.filter(call => call.path.endsWith('/authorize')).length;
+ assertNoPersonPower(box.root); assertNoPersonPower(box.env.HOME);
+ await chrome.evaluate("[...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(" + JSON.stringify(target) + ')).querySelector("button").click()');
+ assert.equal((await revoke.done).code, 0);
+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, before + 1);
+ assert.equal(JSON.parse(readFileSync(machineFile)).devices.length, 0);
+ await box.stopRelay();
+ const calls = box.calls.length;
+ const off = await command(agentRoot, agentEnv, ['relay', 'off']).done;
+ assert.equal(off.code, 0, 'an offline SSH agent can always stop local syncing');
+ assert.equal(existsSync(box.linkFile), false);
+ assert.match(off.document.notice, /relay copy stays until you approve/u);
+ assert.equal(box.calls.length, calls, 'local unlink needs no reachable relay and no phone tap');
+ assertNoPersonPower(box.root); assertNoPersonPower(agentRoot); assertNoPersonPower(box.env.HOME);
+ });
+
+ });
diff --cc test/relay-person-recovery.test.js
index 0f7f7593,03a627cc..b60a8260
--- a/test/relay-person-recovery.test.js
+++ b/test/relay-person-recovery.test.js
@@@ -5,10 -5,10 +5,11 @@@ import { mkdirSync, readFileSync, rmSyn
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { test } from 'node:test';
+import { cleanupFixtureChildren, runFixtureChildAsync, runFixtureGit } from './fixture-child.js';
import * as store from '../src/board.js';
import { preparePersonRequest } from '../src/person-request.js';
- import { personRequestRecords, personRequestStatuses } from '../src/relay-requests.js';
+ import { personRequestRecords, personRequestStatuses, requestIntentDigest } from '../src/relay-requests.js';
+ import { ENGINE_VERSION } from '../src/machine.js';
import { decodeBoardKey, seal } from '../src/seal.js';
import { relayClientFixture } from './relay-client-fixture.js';
@@@ -17,8 -17,8 +18,9 @@@ const BOARD_MODULE = pathToFileURL(reso
const EXCHANGE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/exchange.js')).href;
const RELAY_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/relay.js')).href;
const CONFIG_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/config.js')).href;
+ const REQUESTS_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/relay-requests.js')).href;
const LANES_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/lanes.js')).href;
+after(cleanupFixtureChildren);
/** Run an isolated fixture child without copying its private output into assertion diagnostics. */
function child(cwd, env, argv) {