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(person): only the built-in relay vouches for a passkey [E22,H16]
Corey Olson698364fe9d40
diff --git a/bin/run-tests.js b/bin/run-tests.jsindex b1422924..7d3cf495 100644--- a/bin/run-tests.js+++ b/bin/run-tests.js@@ -1677,6 +1677,9 @@ if (process.argv[1] && resolve(process.argv[1]) === runner) {}}// After any browser wait, so a file never holds a core while it queues for a browser (#1046).+ // Test-only, never published: the CLI under test may read its person authority from the loopback fixture relay (#408).+ const fixtureOrigin = new URL('../test/person-authority-fixture-origin.js', import.meta.url);+ if (process.env.NODE_TEST_CONTEXT === 'child-v8' && existsSync(fileURLToPath(fixtureOrigin))) process.env.NODE_OPTIONS = [process.env.NODE_OPTIONS, `--import=${fixtureOrigin.href}`].filter(Boolean).join(' ');if (process.env.NODE_TEST_CONTEXT === 'child-v8') tokenWaitMs = await takeTestFileToken();if (!landingWorker) installTestWatchdog();}diff --git a/src/cli-main.js b/src/cli-main.jsindex 5458bad3..4450614a 100644--- a/src/cli-main.js+++ b/src/cli-main.js@@ -283,7 +283,7 @@ async function runMain(argv, streams) {const [command, verb] = parsed.positionals;const remoteRelayOn = command === 'relay' && verb === 'on' && !parsed.values.all;if (!parsed.values.help && !parsed.values.version &&- (parsed.values.as === 'person' && command !== 'decisions' && !(await import('./person-signing-cli.js')).signsPersonMoves(io.cwd) || command === 'relay' && ['on', 'join', 'revoke'].includes(verb) && !remoteRelayOn)) {+ (parsed.values.as === 'person' && command !== 'decisions' && !await (await import('./person-signing-cli.js')).personMovesSigned(io.cwd, io) || command === 'relay' && ['on', 'join', 'revoke'].includes(verb) && !remoteRelayOn)) {(await import('./person.js')).requirePersonChannel(io.personChannel);io.caller('person');}diff --git a/src/cli-sync.js b/src/cli-sync.jsindex e516e0b1..b83b9a48 100644--- a/src/cli-sync.js+++ b/src/cli-sync.js@@ -35,6 +35,9 @@ export async function retrySync(io) {export async function syncBefore(io, main) {try { await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }await retrySync(io);+ // An off that only the relay can vouch for is checked against the relay's own authority before anything reads it (#408).+ try { await (await import('./person-signing-cli.js')).attestBeforeCommand(io.cwd, io); }+ catch (error) { reportQuietly(io, error); }try { await executePersonRequests(io.cwd, io, main); }catch (error) { reportQuietly(io, error); }}diff --git a/src/commands/spec.js b/src/commands/spec.jsindex 2a5eaa7f..c7c9797c 100644--- a/src/commands/spec.js+++ b/src/commands/spec.js@@ -210,10 +210,12 @@ export async function specCommand(io, { first, second, rest, values }) {refuseNamedSigners(shown, ids);if (values.by !== undefined && values.by !== 'person') throw new Refused('PERSON_SIGNER_REQUIRED', `the requested SSH signer ${values.by} has no passkey identity`, 'confirm as the person without --by, or wait until signing is off');}- const sources = shownDecisionRows(ctx.info.root, ctx.config, ids);+ // The rows are read only when a passkey request is built, so an unpaired board refuses before reading them.const confirmed = await requireSignedPerson(ctx, board, me, { verb: `spec-${first}`, args: { ids: ids.join(','),- ...(values.text === undefined ? {} : { text: values.text }), ...(values.reason === undefined ? {} : { reason: values.reason }) } }, sources);+ ...(values.text === undefined ? {} : { text: values.text }), ...(values.reason === undefined ? {} : { reason: values.reason }) } },+ () => shownDecisionRows(ctx.info.root, ctx.config, ids));if (confirmed !== null) return confirmed;+ const sources = shownDecisionRows(ctx.info.root, ctx.config, ids);requirePersonChannel(io.personChannel);if (!ctx.info.isMain || me.id !== COORDINATOR) throw new Refused('B26_PERSON_APPROVAL', 'only the person from the main checkout approves or declines rows; use pullboard view for the person to decide');if (personSigning(board).signed) {@@ -294,7 +296,8 @@ export async function specCommand(io, { first, second, rest, values }) {const me = whoAmI(ctx, board);if (!ctx.info.isMain || me.id !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'only the coordinator applies row decisions; ask your coordinator to run pullboard spec apply');// Every automatic proposal is preflighted before any draft or decision changes a file.- planRowApply(ctx.info.root, ctx.config, store.rowDecisions(board));+ const passkeyDecision = record => verifiedPasskeyRowDecision(board, record);+ planRowApply(ctx.info.root, ctx.config, store.rowDecisions(board), { passkeyDecision });const automatic = planAutomaticRigorApply(ctx.info.root, ctx.config, store.rowDrafts(board), store.rowDecisions(board));writeRowApply(ctx.info.root, automatic);automatic.files.forEach(file => io.say(`${file.file}: materialized unproved Rigor drafts for the person's review`));@@ -302,7 +305,7 @@ export async function specCommand(io, { first, second, rest, values }) {const drafted = pendingRowDrafts(loadSpec(ctx.info.root, ctx.config), store.rowDrafts(board)).map((draft) => draftRow(ctx.info.root, ctx.config, { target: 'spec', text: draft.text, gate: draft.gate, tier: draft.tier, section: /^(.*?)\d+$/u.exec(draft.id)[1], id: draft.id }));drafted.forEach((row) => io.say(`${row.file}: ${row.id} drafted from a lane, for the person to approve`));clashingRowDrafts(loadSpec(ctx.info.root, ctx.config), store.rowDrafts(board)).forEach((draft) => io.say(`${ctx.config.spec}: ${draft.id} holds other text, so the draft by ${draft.by} was not written; shout ${draft.by} to run pullboard spec draft again and cite the new id`));- const plan = planRowApply(ctx.info.root, ctx.config, store.rowDecisions(board), { passkeyDecision: record => verifiedPasskeyRowDecision(board, record) });+ const plan = planRowApply(ctx.info.root, ctx.config, store.rowDecisions(board), { passkeyDecision });writeRowApply(ctx.info.root, plan);let applied;try { applied = await ordered(ctx, board, 'applyRowDecisions', [{ agentId: me.id, events: plan.records.map((record) => record.event) }]); }diff --git a/src/person-attested.js b/src/person-attested.jsnew file mode 100644index 00000000..9ed409ed--- /dev/null+++ b/src/person-attested.js@@ -0,0 +1,21 @@+/**+ * The person authority this process read itself over TLS from a built-in relay origin, by board id (#408). Why not+ * the board's own row: any row the user's shell can write, an agent in that shell can write too, including the very+ * first pin, so every strict passkey check trusts only what this process fetched.+ */+const ATTESTED = new Map();++/** Remember the authority the relay vouched for, for this board id, for the rest of this process. */+export function rememberAttested(boardId, authority) {+ ATTESTED.set(boardId, authority);+}++/**+ * The relay-attested authority for a board id, or null when this process has not read one.+ *+ * @param {string | null} boardId+ * @returns {{ origin: string, publicKey: string } | null}+ */+export function attestedAuthority(boardId) {+ return ATTESTED.get(boardId) ?? null;+}diff --git a/src/person-confirmation.js b/src/person-confirmation.jsindex b2ca4cf8..cd53323a 100644--- a/src/person-confirmation.js+++ b/src/person-confirmation.js@@ -34,7 +34,9 @@ function confirmedResult(record, board) {* waitMs bounds polling, not a transport already in flight; existing transport deadlines remain authoritative.*/export async function awaitPersonConfirmation(ctx, board, request, where, { waitMs = 120_000 } = {}) {- ctx.io.err(`pullboard: confirm request ${request.id} with your passkey at ${where}; this terminal is waiting`);+ const waiting = `pullboard: confirm request ${request.id} with your passkey at ${where}; this terminal is waiting`;+ // A waiting terminal says where to confirm while it waits, even when its result is one JSON document at the end.+ if (typeof ctx.io.stderr?.write === 'function') ctx.io.stderr.write(`${waiting}\n`); else ctx.io.err(waiting);// Current trunk owns main in cli-main.js, unlike the old 015ae feature's monolithic cli.js.const { main } = await import('./cli-main.js');const until = Date.now() + waitMs;diff --git a/src/person-row-proof.js b/src/person-row-proof.jsindex 29395e9c..43539d0d 100644--- a/src/person-row-proof.js+++ b/src/person-row-proof.js@@ -8,6 +8,7 @@ import {validPresence,} from './person-presence.js';import { rowDecisionReplacement } from './row-decision-text.js';+import { attestedAuthority } from './person-attested.js';/** Keep the original signed request's complete row effect, including source fields and optional signer boundaries. */export function signedRowDecisionsMatch(request, rows) {@@ -45,7 +46,8 @@ export function verifiedPasskeyRowDecision(board, decision) {if (!request || !Number.isSafeInteger(request.resultSequence) || request.resultSequence < 1) return false;const source = JSON.parse(request.received);const stamp = source.sender?.presence;- const pin = JSON.parse(read('person_authority_local') ?? 'null');+ // Only the authority the relay vouched for in this process checks the stamp, never the board's own row (#408).+ const pin = attestedAuthority(read('board_id') ?? null);if (source.sender?.kind !== 'person' || typeof source.sender.userId !== 'string' || !source.sender.userId|| JSON.stringify(source.document) !== request.encoded || JSON.stringify(source.document.move) !== JSON.stringify(request.move)|| stamp?.board !== read('board_id') || stamp?.request !== request.iddiff --git a/src/person-signing-cli.js b/src/person-signing-cli.jsindex 0bc2f19c..c1f62723 100644--- a/src/person-signing-cli.js+++ b/src/person-signing-cli.js@@ -4,7 +4,10 @@*/import * as store from './board.js';import {- localAuthority,+ attestAuthority,+ authorityAttested,+ authorityNeeded,+ offPending,passkeyConfirmed,personSigning,pinAuthority,@@ -16,7 +19,10 @@ import { preparePersonRequest } from './person-request.js';import { personRequestRecords } from './relay-requests.js';import { Refused } from './refused.js';import { awaitPersonConfirmation } from './person-confirmation.js';-import { relayStatus } from './relay.js';+import {+ DEFAULT_RELAY,+ relayStatus,+} from './relay.js';import { loadMachineSettings } from './settings.js';import { repoInfo } from './git.js';import { existsSync } from 'node:fs';@@ -28,29 +34,66 @@ import {const AUTHORITY_PATH = '/.well-known/pullboard-person-authority';+/** The relay origin built into this code: the only place a board's first person authority is read from. */+const BUILT_IN_AUTHORITY_ORIGIN = new URL(DEFAULT_RELAY).origin;+/**- * Pin the relay's passkey stamp key for a linked board that has none yet, read from the board's own relay origin.- * A relay that cannot be reached leaves the board unpinned, and every passkey check then fails closed.+ * Whether a person authority may be read from this origin: the built-in relay over TLS, or the loopback fixture relay+ * only when the test runner's own preload admits it. Never pullboard.json or a board row (#408 trust-anchor ruling).+ */+function authorityOrigin(origin) {+ if (origin === BUILT_IN_AUTHORITY_ORIGIN) return process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0';+ const fixture = globalThis[Symbol.for('pullboard.personAuthorityFixtureOrigin')];+ return typeof fixture === 'function' && fixture(origin) === true;+}++/**+ * Read this board's person authority from its relay, every time a process needs one, even when the board already+ * pinned a key: a local row may have been written by anyone with the shell, so only the relay's answer counts. The+ * first answer is pinned; a local row that differs is ignored and reported by name. A relay that cannot be reached,+ * or an origin that is not the built-in relay, leaves the process without an authority, and passkey checks fail closed.** @param {string} root* @param {any} board* @param {{ err?: (line: string) => void }} [io]+ * @returns {Promise<{ origin: string, publicKey: string } | null>}*/-export async function pinRelayAuthority(root, board, io = {}) {- if (localAuthority(board)) return localAuthority(board);+export async function pinRelayAuthority(root, board, io = {}, { timeoutMs = 10_000 } = {}) {const relay = relayStatus(root);if (!relay.linked || !relay.url) return null;const origin = new URL(relay.url).origin;+ if (!authorityOrigin(origin)) {+ io.err?.(`pullboard: [PERSON_AUTHORITY_ORIGIN] ${origin} is not the built-in relay ${BUILT_IN_AUTHORITY_ORIGIN} over TLS, so it cannot vouch for the person; person moves wait for the built-in relay`);+ return null;+ }let document;try {- const response = await fetch(new URL(AUTHORITY_PATH, origin), { redirect: 'error', signal: AbortSignal.timeout(10_000) });+ const response = await fetch(new URL(AUTHORITY_PATH, origin), { redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });document = await response.json();if (!response.ok) throw new Refused(document?.error?.code ?? 'PERSON_AUTHORITY', document?.error?.message ?? 'the relay refused');} catch (error) {io.err?.(`pullboard: [PERSON_AUTHORITY] could not read the passkey stamp key from ${origin} (${error.code ?? error.name ?? 'error'}); passkey-confirmed moves wait until it can`);return null;}- return pinAuthority(board, origin, document.authority);+ const { attested, ignored } = attestAuthority(board, origin, document.authority);+ if (ignored) io.err?.(`pullboard: [PERSON_AUTHORITY_MISMATCH] this board's stored key for ${ignored.origin} does not match what ${origin} attests, so it is ignored; only the relay's key checks passkeys`);+ return attested;+}++/**+ * Before a command on a board that signs person moves, read the relay's authority once, so every strict check in this+ * process (signing state, passkey-confirmed rows and requests) sees the relay's answer. Other boards fetch nothing.+ *+ * @param {string} root+ * @param {{ err?: (line: string) => void }} io+ */+export async function attestBeforeCommand(root, io) {+ let board;+ try { board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite')); }+ catch { return; } // No board here: nothing to vouch for, and the command reports its own refusal.+ // Budget: ceiling for one small read before a command; a slow relay leaves passkey checks failing closed instead.+ try { if (authorityNeeded(board) && !authorityAttested(board)) await pinRelayAuthority(root, board, io, { timeoutMs: 2_000 }); }+ finally { store.closeBoard(board); }}/**@@ -63,22 +106,26 @@ export async function pinRelayAuthority(root, board, io = {}) {* @param {any} board* @param {{ id: string }} me* @param {{ verb: string, item?: number, args: any } | null} intent - the request the passkey device shows, or null when it cannot carry this move+ * @param {any[] | (() => any[])} [rows] - the rows the device shows, or a reader called only when a request is built*/export async function requireSignedPerson(ctx, board, me, intent, rows, effect) {if (!personSigning(board).signed) return null;- // A board that has not pinned its relay key yet cannot check a passkey stamp, including an off it replayed: pin first.- if (!localAuthority(board) && await pinRelayAuthority(ctx.info.root, board, ctx.io) && !personSigning(board).signed) return null;+ const relay = relayStatus(ctx.info.root);+ if (!relay.linked && !ctx.io.personRequest) throw signedRefusal('no passkey device is paired with this board');+ // Only the relay can vouch for a passkey stamp, including an off this board replayed: read its authority first.+ if (!authorityAttested(board) && !await pinRelayAuthority(ctx.info.root, board, ctx.io)) {+ throw signedRefusal('the relay could not vouch for your passkey, so a person move cannot be confirmed from here');+ }+ if (!personSigning(board).signed) return null;if (ctx.io.personRequest) {if (passkeyConfirmed(board, ctx.io.personRequest)) return null;throw signedRefusal('this request reached the board without a passkey confirmation', 'send it again from the relay view and confirm it with your passkey');}- const relay = relayStatus(ctx.info.root);- if (!relay.linked) throw signedRefusal('no passkey device is paired with this board');const origin = new URL(relay.url).origin;const where = `${origin}/#board=${relay.board}`;let sent = '';if (intent && me.id !== store.PERSON) {- const request = preparePersonRequest(intent, undefined, rows, effect);+ const request = preparePersonRequest(intent, undefined, typeof rows === 'function' ? rows() : rows, effect);try {await ordered(ctx, board, 'proposePersonMove', [{ agentId: me.id, request }]);sent = 'proposed';@@ -125,6 +172,28 @@ export function signsPersonMoves(cwd) {finally { db?.close(); }}+/**+ * Whether person moves on this board are signed, as the relay vouches for it: the read the command line uses to let+ * the passkey step stand in for the shell checks. Only an off after the last on needs the relay; then it is read+ * once, here, so a genuine off brings the shell checks back and a forged one leaves signing on (#408).+ *+ * @param {string} cwd+ * @param {{ err?: (line: string) => void }} io+ * @returns {Promise<boolean>}+ */+export async function personMovesSigned(cwd, io) {+ if (!signsPersonMoves(cwd)) return false;+ let board;+ try { board = store.openBoard(join(repoInfo(cwd).commonDir, 'pullboard', 'board.sqlite')); }+ catch { return true; } // Unreadable here: keep the passkey step, which refuses by name if it cannot go on.+ try {+ if (!offPending(board) || authorityAttested(board)) return personSigning(board).signed;+ // Budget: ceiling for one small read before a person command; an unreachable relay leaves signing on.+ await pinRelayAuthority(cwd, board, io, { timeoutMs: 2_000 });+ return personSigning(board).signed;+ } finally { store.closeBoard(board); }+}+export { signingLine } from './person-signing-words.js';import { signingLine } from './person-signing-words.js';@@ -145,7 +214,10 @@ export function signingSetting(io, value) {const confirmed = await requireSignedPerson(ctx, board, me, { verb: 'signing', args: { signed: value } });if (confirmed !== null) return confirmed;}- else await pinRelayAuthority(ctx.info.root, board, io);+ else if (!await pinRelayAuthority(ctx.info.root, board, io)) {+ throw new Refused('PERSON_SIGNING_RELAY', 'signed person moves need the built-in relay to vouch for your passkey, and it could not be reached from this board',+ 'link this board to the relay with pullboard relay on --all, then turn signing on');+ }await ordered(ctx, board, 'setPersonSigning', [signed ? { agentId: ctx.io.personRequest ? store.PERSON : me.id, signed }: { agentId: store.PERSON, signed, request: ctx.io.personRequest.id }]);io.result?.({ settings: loadMachineSettings(), person: { signed } });diff --git a/src/person-signing.js b/src/person-signing.jsindex 3a5fc3f6..25706f15 100644--- a/src/person-signing.js+++ b/src/person-signing.js@@ -22,6 +22,10 @@ import {} from './relay-requests.js';import { validPresence } from './relay-sender.js';import { presenceSigned } from './person-presence.js';+import {+ attestedAuthority,+ rememberAttested,+} from './person-attested.js';const PROPOSALS = 'person_proposals';const AUTHORITY = 'person_authority_local';@@ -63,6 +67,14 @@ export function localAuthority(board) {return read(board, AUTHORITY, null);}+/** The authority a relay published, checked for shape; refused when it names no usable stamp key. */+function validAuthority(origin, authority) {+ if (authority?.version !== 1 || authority.algorithm !== 'Ed25519' || typeof authority.publicKey !== 'string' || !/^[A-Za-z0-9_-]{40,200}$/u.test(authority.publicKey)) {+ throw new Refused('PERSON_AUTHORITY', `the relay at ${origin} published no usable passkey stamp key; upgrade the relay and retry`);+ }+ return { origin, publicKey: authority.publicKey };+}+/*** Pin the relay's public stamp key, once. A later different key, or the same key from another origin, is refused:* nothing replaces the first pin, so a key written in by hand later never verifies a stamp.@@ -72,9 +84,7 @@ export function localAuthority(board) {* @param {any} authority - the relay's published `{version: 1, algorithm: 'Ed25519', publicKey}`*/export function pinAuthority(board, origin, authority) {- if (authority?.version !== 1 || authority.algorithm !== 'Ed25519' || typeof authority.publicKey !== 'string' || !/^[A-Za-z0-9_-]{40,200}$/u.test(authority.publicKey)) {- throw new Refused('PERSON_AUTHORITY', `the relay at ${origin} published no usable passkey stamp key; upgrade the relay and retry`);- }+ validAuthority(origin, authority);return atomic(board, () => {const existing = localAuthority(board);if (existing) {@@ -95,8 +105,52 @@ export function pinAuthority(board, origin, authority) {function stampHolds(board, stamp, strict) {if (!validPresence(stamp)) return false;if (!strict) return true;- const pinned = localAuthority(board);- return Boolean(pinned) && stamp.board === boardId(board) && presenceSigned(stamp, pinned.publicKey);+ const attested = attestedAuthority(boardId(board));+ return Boolean(attested) && stamp.board === boardId(board) && presenceSigned(stamp, attested.publicKey);+}++/**+ * Record the authority this process fetched from the relay, and pin it as the board's first pin when none exists.+ * A local row that differs is ignored, never trusted and never replaced (its triggers keep it), and is returned so+ * the caller reports it by name.+ *+ * @param {any} board+ * @param {string} origin - the built-in relay origin the authority was read from over TLS+ * @param {any} authority - the relay's published `{version: 1, algorithm: 'Ed25519', publicKey}`+ * @returns {{ attested: { origin: string, publicKey: string }, ignored: { origin: string, publicKey: string } | null }}+ */+export function attestAuthority(board, origin, authority) {+ const local = localAuthority(board);+ const attested = local && local.origin === origin && local.publicKey === authority?.publicKey+ ? local : local ? validAuthority(origin, authority) : pinAuthority(board, origin, authority);+ rememberAttested(boardId(board), attested);+ return { attested, ignored: attested === local || !local ? null : local };+}++/** Whether this process holds a relay-attested authority for the board. */+export function authorityAttested(board) {+ return Boolean(attestedAuthority(boardId(board)));+}++/**+ * Whether this board's strict reading of person moves depends on the relay's authority: it has ever signed person+ * moves, so its signing state and every passkey-confirmed row or request can only be checked against the relay.+ * A board that never signed fetches nothing.+ */+export function authorityNeeded(board) {+ return Boolean(board.db.prepare("SELECT 1 FROM event WHERE event_kind = 'person_signing' LIMIT 1").get());+}++/** Whether an off comes after the last on: the board reads as signed only until the relay vouches for that off. */+export function offPending(board) {+ const rows = board.db.prepare("SELECT event_detail FROM event WHERE event_kind = 'person_signing' ORDER BY event_id DESC").all();+ for (const row of rows) {+ let detail;+ try { detail = JSON.parse(row.event_detail); } catch { continue; }+ if (detail?.signed === true) return false;+ if (detail?.signed === false) return true;+ }+ return false;}/**diff --git a/src/relay-presentation.js b/src/relay-presentation.jsindex 4a5939bb..72dbcf59 100644--- a/src/relay-presentation.js+++ b/src/relay-presentation.js@@ -64,7 +64,10 @@ function readRelayPresentation(root, providedBoard) {let personBars = [];if (signed) {const entries = store.listItems(board, { all: true }).map(item => ({ item, status: barReadiness(board, item, { signature: false }) }));- const plans = previewBarCoverage(root, entries.map(({ item, status }) => ({ item, coverage: status.signed?.coverage })), mainPolicy(root));+ // A board with no committed policy yet still shows its bars, only without their coverage preview.+ let policy = null;+ try { policy = mainPolicy(root); } catch (error) { if (!(error instanceof Refused)) throw error; }+ const plans = policy ? previewBarCoverage(root, entries.map(({ item, status }) => ({ item, coverage: status.signed?.coverage })), policy) : [];personBars = entries.map(({ item, status }, index) => ({ id: item.item_id,before: { revision: status.revision?.revision ?? 0, digest: barDigest(item) }, ...(plans[index] ? { coverage: plans[index] } : {}) }));}diff --git a/src/relay-sender.js b/src/relay-sender.jsindex 05cbd2f0..e55fc0a9 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -80,7 +80,8 @@ export function relaySenderProblem(move, sender, kind, { phoneReceipt = false }return sender.approver === false && (kind === 'snapshot' || personAuthority(move))? new Refused('NOT_APPROVER', `${sender.login ?? 'this person'} is not an approver of this board; only an approver it names answers person decisions, approves rows or replaces its snapshot`) : null;}- if (personFact(move)) {+ // A machine may carry out the person's own never-again only as the request the person confirmed (#408).+ if (personFact(move) && !(sender.kind === 'machine' && phoneReceipt)) {return new Refused('RELAY_PERSON_ONLY', `${sender.kind === 'agent' ? `agent ${sender.agent}` : 'a machine'} cannot record the person's never-again; the person marks it from their own session`);}if (sender.kind === 'machine') {diff --git a/test/person-authority-fixture-origin.js b/test/person-authority-fixture-origin.jsnew file mode 100644index 00000000..513a10b9--- /dev/null+++ b/test/person-authority-fixture-origin.js@@ -0,0 +1,6 @@+/**+ * Test-only preload (#408): lets the CLI under test read its person authority from a loopback fixture relay, which+ * has no TLS. Only bin/run-tests.js adds it, to each test file's NODE_OPTIONS; it is never in the published package,+ * and without it the CLI reads a first pin only from the built-in relay origin over TLS.+ */+globalThis[Symbol.for('pullboard.personAuthorityFixtureOrigin')] = (origin) => /^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5}$/u.test(origin);diff --git a/test/person-first-pin-fixture.js b/test/person-first-pin-fixture.jsindex 7e8722f3..ecbf0ead 100644--- a/test/person-first-pin-fixture.js+++ b/test/person-first-pin-fixture.js@@ -8,12 +8,20 @@ import {} from 'node:crypto';import {mkdtempSync,+ readFileSync,rmSync,+ writeFileSync,} from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { join, resolve } from 'node:path';import * as store from '../src/board.js';import { presenceAttestation } from '../src/person-presence.js';+import {+ relayClientFixture,+ relayFixtureChild,+} from './relay-client-fixture.js';++const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');/** A local first-row insertion cannot supply the missing person/relay trust anchor on an unpaired signed board. */export function firstUnpairedAuthorityInsertion(t) {@@ -42,3 +50,31 @@ export function firstUnpairedAuthorityInsertion(t) {assert.equal(store.personSigning(board).signed, true,'an initial raw local authority row cannot turn signing off on an unpaired board');}++/**+ * Without the test runner's preload, the real CLI takes a first pin only from the built-in relay over TLS: a linked+ * loopback relay over http, or any other origin, cannot vouch for the person, so signing stays off and nothing is pinned.+ */+export async function firstPinNeedsBuiltInRelay(t) {+ const box = await relayClientFixture(t);+ assert.equal((await box.link()).code, 0);+ const env = { ...box.env, NODE_OPTIONS: (box.env.NODE_OPTIONS ?? '').split(' ').filter(option => !option.includes('person-authority-fixture-origin')).join(' ') };+ const pinned = () => {+ const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ try { return board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='person_authority_local'").get(); }+ finally { store.closeBoard(board); }+ };+ const turnOn = async () => relayFixtureChild(box.root, env, [CLI, 'settings', 'person.signed', 'on', '--json']);+ const overHttp = await turnOn();+ assert.equal(overHttp.document.error?.code, 'PERSON_SIGNING_RELAY', `an http relay cannot vouch: ${JSON.stringify(overHttp.document)}`);+ assert.equal(pinned(), undefined, 'nothing is pinned from an http origin');+ // Another https origin is refused by name before any request leaves the machine.+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ writeFileSync(box.linkFile, JSON.stringify({ ...link, url: 'https://relay.example.invalid' }));+ const calls = box.calls.length;+ const elsewhere = await turnOn();+ assert.equal(elsewhere.document.error?.code, 'PERSON_SIGNING_RELAY', `a non-built-in origin cannot vouch: ${JSON.stringify(elsewhere.document)}`);+ assert.equal(pinned(), undefined, 'nothing is pinned from a non-built-in origin');+ assert.equal(box.calls.slice(calls).filter(call => call.path === '/.well-known/pullboard-person-authority').length, 0, 'no authority request was made');+ writeFileSync(box.linkFile, JSON.stringify(link));+}diff --git a/test/person-off-replay-fixture.js b/test/person-off-replay-fixture.jsindex bdccde07..0cd6dce3 100644--- a/test/person-off-replay-fixture.js+++ b/test/person-off-replay-fixture.js@@ -2,7 +2,6 @@import assert from 'node:assert/strict';import {createHash,- generateKeyPairSync,randomUUID,sign,} from 'node:crypto';@@ -23,21 +22,22 @@ import {requestStageText,} from '../src/relay-requests.js';import { relayClientFixture } from './relay-client-fixture.js';+import { relayStampKey } from './person-relay-stamp.js';/** A consumed genuine OFF stamp cannot disable signing a second time after ordinary re-enable [E22,H16]. */export async function rejectConsumedOffReplay(t) {const box = await relayClientFixture(t);const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));t.after(() => store.closeBoard(board));- const authority = generateKeyPairSync('ed25519');- signing.pinAuthority(board, 'https://fixture-relay.invalid', { version: 1, algorithm: 'Ed25519',- publicKey: authority.publicKey.export({ format: 'der', type: 'spki' }).toString('base64url') });+ // The relay's own stamp key, as the relay vouches for it to this process (#408).+ const relayKey = relayStampKey(box);+ signing.attestAuthority(board, box.origin, relayKey.authority);signing.setPersonSigning(board, { agentId: 'coordinator', signed: true });const document = preparePersonRequest({ verb: 'signing', args: { signed: 'off' } }, randomUUID());const boardId = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value;const presence = { board: boardId, request: document.id, digest: createHash('sha256').update(JSON.stringify(document)).digest('hex'),credential: 'fixture-passkey', at: Date.now() };- presence.signature = sign(null, presenceAttestation(presence), authority.privateKey).toString('base64url');+ presence.signature = sign(null, presenceAttestation(presence), relayKey.privateKey).toString('base64url');const at = new Date().toISOString();receivePersonRequest(board, document, { sequence: 1, at, sender: { kind: 'person', userId: 'fixture-user', presence } });const executor = 'fixture-executor';diff --git a/test/person-optional-apply-fixture.js b/test/person-optional-apply-fixture.jsindex 0f3c4051..98a8a51a 100644--- a/test/person-optional-apply-fixture.js+++ b/test/person-optional-apply-fixture.js@@ -32,6 +32,7 @@ import {requestStageText,} from '../src/relay-requests.js';import { relayClientFixture } from './relay-client-fixture.js';+import { relayStampKey } from './person-relay-stamp.js';import { runFixtureGit } from './fixture-child.js';/** A valid OpenSSH public line for a fixture-only public key; no SSH private key or signing subprocess exists. */@@ -56,15 +57,15 @@ export async function optionalPasskeyApply(t, { throughCli = false, fabricatedMewriteFileSync(join(box.root, '.pullboard', 'first-commit'), runFixtureGit(['rev-list', '--max-parents=0', 'HEAD'], { cwd: box.root, env: box.env }) + '\n');const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));t.after(() => store.closeBoard(board));- const authority = generateKeyPairSync('ed25519');- signing.pinAuthority(board, 'https://fixture-relay.invalid', { version: 1, algorithm: 'Ed25519',- publicKey: authority.publicKey.export({ format: 'der', type: 'spki' }).toString('base64url') });+ // The relay's own stamp key, as the relay vouches for it to this process (#408).+ const relayKey = relayStampKey(box);+ signing.attestAuthority(board, box.origin, relayKey.authority);signing.setPersonSigning(board, { agentId: 'coordinator', signed: true });const document = preparePersonRequest({ verb: 'spec-approve', args: { ids: 'G21' } }, randomUUID(), [{ id: 'G21', text, source: readFileSync(specFile, 'utf8').split(/\r?\n/u).find(line => line.startsWith('- G21 ')) }]);const boardId = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value;const presence = { board: boardId, request: document.id, digest: createHash('sha256').update(JSON.stringify(document)).digest('hex'),credential: 'fixture-passkey', at: Date.now() };- presence.signature = sign(null, presenceAttestation(presence), authority.privateKey).toString('base64url');+ presence.signature = sign(null, presenceAttestation(presence), relayKey.privateKey).toString('base64url');const at = new Date().toISOString();receivePersonRequest(board, document, { sequence: 1, at, sender: { kind: 'person', userId: 'fixture-user', presence } });const executor = 'fixture-executor';@@ -127,16 +128,13 @@ export async function optionalPasskeyApply(t, { throughCli = false, fabricatedMereturn;}if (throughCli) {+ // An unlinked CLI has no relay to vouch for the stamp, so the decision this process attested does not apply there:+ // only the relay's own answer counts, never a key stored on the board (#408). The linked apply is in team.test.js.+ const before = readFileSync(specFile, 'utf8');const applied = await box.cli('spec', 'apply');- assert.equal(applied.code, 0, JSON.stringify(applied.document));- assert.match(readFileSync(specFile, 'utf8'), /- G21 \[approved, must\] An optional SSH row approved by its exact passkey request\./u);- const status = await box.cli('status');- assert.equal(status.code, 0, JSON.stringify(status.document));- assert.equal(status.document.specApprovalBaseline?.pending, false, 'the approval projection must not skip behind an uncaptured baseline');- assert.equal(status.document.needs.some(need => need.kind === 'agent-approved' && need.id === 'G21'), false,- 'the actual status projection recognizes the applied passkey approval');- assert.equal((status.document.specApprovalEvidenceErrors ?? []).some(error => error.id === 'G21'), false,- 'the optional SSH approval carries valid provenance through the real CLI');+ assert.equal(applied.code, 1, JSON.stringify(applied.document));+ assert.equal(applied.document.error.code, 'MISSING_SIGNATURE', 'the unverified passkey approval is not applied');+ assert.equal(readFileSync(specFile, 'utf8'), before, 'the row stays a draft');return;}const plan = planRowApply(box.root, loadConfig(box.root), store.rowDecisions(board), {diff --git a/test/person-relay-stamp.js b/test/person-relay-stamp.jsnew file mode 100644index 00000000..53601c28--- /dev/null+++ b/test/person-relay-stamp.js@@ -0,0 +1,19 @@+/** The fixture relay's own passkey stamp key, so a test signs stamps the way the relay does [E22,H16]. */+import { createPrivateKey } from 'node:crypto';+import { DatabaseSync } from 'node:sqlite';++/**+ * Read the fixture relay's published authority and the private half it signs passkey stamps with. Why the relay's+ * own key: a board trusts only the authority its relay vouches for (#408), so a stamp made with any other key fails.+ *+ * @param {{ auth: { personAuthority: () => any }, authDatabase: string }} box - a relay client fixture+ * @returns {{ authority: { version: 1, algorithm: 'Ed25519', publicKey: string }, privateKey: import('node:crypto').KeyObject }}+ */+export function relayStampKey(box) {+ const authority = box.auth.personAuthority();+ const db = new DatabaseSync(box.authDatabase, { readOnly: true });+ try {+ const { private_key: key } = db.prepare('SELECT private_key FROM relay_person_authority WHERE slot=1').get();+ return { authority, privateKey: createPrivateKey({ key: Buffer.from(key, 'base64url'), format: 'der', type: 'pkcs8' }) };+ } finally { db.close(); }+}diff --git a/test/team.test.js b/test/team.test.jsindex 51c9f5a5..450083c7 100644--- a/test/team.test.js+++ b/test/team.test.js@@ -61,7 +61,10 @@ import {rejectSyntheticPasskeyEvent,} from './person-optional-apply-fixture.js';import { rejectConsumedOffReplay } from './person-off-replay-fixture.js';-import { firstUnpairedAuthorityInsertion } from './person-first-pin-fixture.js';+import {+ firstPinNeedsBuiltInRelay,+ firstUnpairedAuthorityInsertion,+} from './person-first-pin-fixture.js';import { refuseNamedSigners } from '../src/person-signing-cli.js';import { createE2eHelpers } from './e2e-helpers.js';import {@@ -974,11 +977,18 @@ test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(const early = (await box.cli('shout', 'person', 'A decision before signing', '--decision')).document.id;assert.equal((await cli(box.env, 'answer', String(early), 'Off answers as today', '--as', 'person')).code, 0, 'off: the terminal answers as the person');- // Turning signing on is allowed from the terminal, even an agent's.+ // A board with no relay cannot turn signing on: only the relay can vouch for a passkey (#408 trust-anchor ruling).+ const offline = await cli(marked, 'settings', 'person.signed', 'on');+ assert.equal(offline.document.error?.code, 'PERSON_SIGNING_RELAY', `no relay, no signing: ${JSON.stringify(offline.document)}`);+ // Linked, turning signing on is allowed from the terminal, even an agent's; unlinking then still works with no tap.+ assert.equal((await box.link()).code, 0);const on = await cli(marked, 'settings', 'person.signed', 'on');assert.equal(on.code, 0, `an agent may turn signing on: ${JSON.stringify(on.document)}`);assert.equal(on.document.person.signed, true);const ask = (await box.cli('shout', 'person', 'A decision only the person answers', '--decision')).document.id;+ // The same board on a device that is not paired: its link set aside, restored below without linking again, and no+ // move succeeds meanwhile, so the relay and the board still agree when it returns.+ renameSync(box.linkFile, `${box.linkFile}.unpaired`);// S10a and the on-and-unpaired case: every person move fails closed at once, naming how to pair a passkey.const calls = box.calls.length;@@ -1008,7 +1018,7 @@ test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(assert.equal(viewed.body.error?.code, 'PERSON_SIGNED', 'the view channel is not the person once signing is on');// Linked, a terminal person move goes to the passkey as an action-bound request and says where to confirm.- assert.equal((await box.link()).code, 0);+ renameSync(`${box.linkFile}.unpaired`, box.linkFile);assert.ok(holdsNoPersonCredential(box.root) && holdsNoPersonCredential(box.env.HOME), 'no file holds a person session or grant');const terminal = helpers.launch({ ...box, env: { ...cleared, SSH_CONNECTION: '127.0.0.1 40000 127.0.0.1 22' } },box.root, process.execPath, [CLI, 'answer', String(ask), 'Signed on the passkey', '--as', 'person', '--json']);@@ -1117,7 +1127,8 @@ test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(const shown = { id: 'G1', text: 'A row the person decides on the passkey.' };writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8').replace('## G · Goals: what the client asked for\n',`## G · Goals: what the client asked for\n\n- G1 [draft, must] ${shown.text} | gate: review\n`));- shown.source = readFileSync(join(box.root, 'SPEC.md'), 'utf8').split(/\r?\n/u).find(line => line.startsWith('- G1 '));+ // The template's own placeholder G1 may sit beside it; the person sees the row this test wrote.+ shown.source = readFileSync(join(box.root, 'SPEC.md'), 'utf8').split(/\r?\n/u).find(line => line.startsWith('- G1 ') && line.includes(shown.text));const blind = { version: 1, type: 'person-request', id: randomUUID(), move: { verb: 'spec-approve', args: { ids: 'G1' } } };const seen = { ...blind, id: randomUUID(), rows: [shown] };for (const request of [blind, seen]) {@@ -1129,6 +1140,10 @@ test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(assert.notEqual(received[seen.id].status, 'refused', JSON.stringify(received[seen.id]));const decided = (await box.cli('export')).document.tables.event.filter((row) => row.event_kind === 'row_decision');assert.deepEqual(decided.map((row) => [row.event_by, JSON.parse(row.event_detail).record.id]), [['person', 'G1']], 'the passkey decided exactly the row it showed');+ // The real CLI applies that decision, checked against the authority its relay vouches for, never a stored key (#408).+ const applied = await box.cli('spec', 'apply');+ assert.equal(applied.code, 0, JSON.stringify(applied.document));+ assert.match(readFileSync(join(box.root, 'SPEC.md'), 'utf8'), /- G1 \[approved, must\] A row the person decides on the passkey\./u, 'the native CLI applies the passkey approval');assert.throws(() => refuseNamedSigners([{ id: 'G2', signers: ['[email protected]'] }], ['G2']), { code: 'PERSON_SIGNER_REQUIRED', message: /G2 names its SSH signers alice@example\.com/u });/** One live SSH command, one confirmation, no status/export/other CLI before its original exit. */@@ -1159,7 +1174,7 @@ test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(}}// Each newly mapped action must complete on its original terminal, with exact target/meaning.- const factItem = (await box.cli('add', box.lane, 'SIGNED_FACT_TARGET')).document.id;+ const factItem = (await box.cli('add', box.lane, 'SIGNED_FACT_TARGET')).document.item.item_id;const fact = await confirmTerminal(['fact', String(factItem), 'decision', 'Keep this exact rule', '--as', 'person', '--cause', 'row:G1', '--never-again'], 'fact');assert.equal(fact.item, factItem);assert.equal(fact.fact.text, 'Keep this exact rule');@@ -1221,11 +1236,13 @@ test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(/** Keep the initial-unpaired local-edit clause distinct from the post-pin trigger controls. */test('person-only moves are signed before the first authority pin [E22,B26,H16]', firstUnpairedAuthorityInsertion);+test('person-only moves are signed only from the built-in relay over TLS [E22,B26,H16]', { timeout: relayWorkBudgetMs(8) }, firstPinNeedsBuiltInRelay); // budget: hang ceiling for one link and two refused CLI runs; not a speed target.+/** Optional SSH policy must accept a genuinely bound passkey row decision without using an SSH key. */test('person-only moves are signed through optional SSH apply [E22,H16]', optionalPasskeyApply);/** The actual CLI applies and projects the recorded passkey approval even with optional SSH enabled. */-test('person-only moves are signed through native CLI apply [E22,H16]', optionalPasskeyApplyThroughCli);+test('person-only moves are signed: an unlinked CLI applies no passkey decision it cannot verify [E22,H16]', optionalPasskeyApplyThroughCli);/** Initial trust and committed execution provenance are separate signing boundaries. */test('person-only moves are signed against fabricated receipt metadata [E22,H16]', rejectFabricatedPasskeyMetadata);