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
feat(person): compose passkeys and terminal completion [E22,B26,H16]
Corey Olsond3fcc0553f8e
diff --git a/docs/api.md b/docs/api.mdindex 8ae17676..b32c4b9e 100644--- a/docs/api.md+++ b/docs/api.md@@ -498,6 +498,28 @@ The initial command output names `.pullboard/signers`, `.pullboard/first-commit`Every signed row and signer-list change binds the initial signer-list hash in its canonical text. Rewriting `.pullboard/signers.initial`, or relabelling that hash in earlier receipts, invalidates those receipts.+## Signed person moves++`pullboard settings person.signed on` makes every person move on the board wait for a passkey: answering a person decision, approving or declining a spec or doctrine row, `spec answer`, `spec signoff`, a fact as the person, a landing waiver, holding a lane as the person, and turning signing off. Anyone may turn it on, from any terminal, before or after linking; it is off by default, and then person moves work as before and `pullboard status` says in one line that they are not signed. Its JSON adds `person: {signed}`.++With signing on, a person move from a terminal, SSH and remote shells included, is refused at once with `PERSON_SIGNED`, whatever the shell markers say. On an unlinked board, or one with no relay, the next step is to pair a phone or a computer browser with `pullboard relay on --all` and add a passkey there. On a linked board the terminal first records the exact move as a request for the person's passkey device (`proposePersonMove`), and the initiating terminal names the request and confirmation address, then waits while the existing native executor carries out the one confirmed action. Its successful JSON keeps the command's usual required fields and adds `request` and `status`; a repository-changing decision may also name its `coordinatorRequest`, which is not a landing receipt. No second terminal command is required. The local view's channel takes the same refusal: a file the user can read is no proof of the person. Turning signing off is refused from every terminal; only a passkey-confirmed request turns it off, and no edit to `pullboard.json`, machine settings or a board row does. `pullboard relay off` still unlinks offline with no tap and leaves signing on. A row whose source names `signers:` is refused with `PERSON_SIGNER_REQUIRED`, naming the row and its principals: a passkey stands in for an optional SSH sign-off but not for a named signer. With signing off, SSH sign-offs work as described below.++A passkey is any WebAuthn credential the person registered on the relay with user presence: a phone's Face ID or Touch ID, or a computer browser's. The relay page offers to add one while a paired board signs person moves, and shows each waiting terminal-started move with a Confirm button. The endpoints, all on the relay's configured origin:++| Endpoint | Who | Body | Answer |+| --- | --- | --- | --- |+| `POST /api/v1/passkeys/challenge` | person session | `{}` | `{challenge, expires, rpId, user: {id, name}}`, single use, five minutes |+| `POST /api/v1/passkeys` | person session | `{challenge, id, clientDataJSON, authenticatorData}` | `{passkey: {id, created}}` |+| `GET /api/v1/passkeys` | person session | none | `{passkeys: [id]}` |+| `POST /api/v1/boards/:board/person-grants` | person session with write access | `{request, digest}` | `{grant, expires, credentials}` |+| `GET /.well-known/pullboard-person-authority` | anyone | none | `{authority: {version: 1, algorithm: "Ed25519", publicKey}}` |++Registration needs `webauthn.create` client data on the relay origin, the RP id hash of the origin's host name, user presence and an ES256 or RS256 key in the attested credential data. Machine and agent credentials are refused with `HUMAN_REQUIRED`. A person grant (`pg_…`, two minutes) binds one board, one request id and `digest`, the SHA-256 of the request document's exact JSON. The browser keeps it in memory and asks a passkey to sign `SHA-256(grant)` as the WebAuthn challenge, then posts the request as `{sequence, sealed, presence: {grant, credential, clientDataJSON, authenticatorData, signature}}`. The relay checks `webauthn.get`, origin, RP id hash, user presence, the signature under the registered key and a rising counter; it refuses `PASSKEY_ASSERTION` or `PASSKEY_PRESENCE`. It then stores the request with `sender.presence: {board, request, digest, credential, at, signature}`, its Ed25519 signature over `["pullboard-person-presence", 1, board, request, digest, credential, at]`, and spends the grant, which a second use refuses with `PHONE_APPROVAL_USED`. The grant is never in a board record.++The native board pins the relay's public key from its own configured relay origin, once, in `board_meta` as `person_authority_local`; a later different key is refused with `PERSON_AUTHORITY_CHANGED`, and SQLite triggers refuse an update, delete or replace of the pin. An export never carries the pin, an import never sets it, and a checkpoint restore keeps it. Commands accept a request as the person's only when its stamp names this board and request, matches the digest of the recorded request and verifies under the pin; a stamp written into the board by hand does not. Whether signing is on is read from the append-only `person_signing` events: an off counts only from the person with a verifying stamp. A checkpoint or import that would turn signing off without one is refused with `PERSON_SIGNING_ERASED`. What this cannot detect: replacing the whole board file, or dropping its triggers and rewriting history, by a process with the user's file access, and a pin written by hand before the board first reached its relay.++The device-only request format adds two verbs while keeping version 1: `land-waive` with `args: {waive, until, reason}`, and `signing` with `args: {signed: "on" | "off"}`. The relay presentation adds `state.personSigning: {signed}` and `state.personProposals`, each `{id, move, by, at, expires}`, without the ones that already have a request.+## Paged relay snapshotsRelay API2 preserves the `version: 1` response envelope, executable moves anddiff --git a/docs/formats.md b/docs/formats.mdindex e7202383..91047a39 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -112,7 +112,7 @@ The board file is in the repository's Git common directory at `.git/pullboard/bo| `CLI JSON envelope` | `1` | `JSON_SHAPES.version` in `src/json.js` | Keep optional fields additive within version 1; bump the envelope version for incompatible command/export shapes. || `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. || `board schema` | `3` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | On a write open of a board whose version is behind: create missing tables and indexes (version 3 adds the hot-path indexes), add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. Read opens never migrate; a board at the current version whose shape differs is reported once on stderr and left as it is. |-| `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |+| `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. A signed board uses event-log format 2; older tools refuse it. Preserve event rows when the board schema changes. || `move engine` | `94` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |<!-- format-versions:end -->@@ -209,6 +209,7 @@ An optional `landing.environment` in `pullboard.json` requires all three exact fEngine 85 also adds `recordLandingTestDefect`. A red batch whose bisection finds no item culprit records a neutral repair item and a `landing-test-defect` event with its test path, content hash, red-tree blob, original trunk blob, failure names, batch ID and trunk branch. Its batch remains `test-defect`, and further landings on that trunk stop before another gate runs. A committed correction to the test on the trunk, or live existing waivers covering every recorded failure, releases the hold. Candidate-only changes and uncommitted edits do not release it. A waiver keeps the red tree and its waived failures explicit. Existing culprit and flake diagnosis retain their meanings; older engines cannot revise or finish a batch carrying these fields.Engine 90 records the parent session a seat joined under and stamps each verdict with its assurance: independent when the builder's and reviewer's recorded parents differ, procedural when either is unknown (#1102). Review eligibility, next and the queue exclude any seat sharing a parent with an author. Older engines replay their recorded verdicts with no parent recorded.+The unassigned signing engine (`PERSON_SIGNING_ENGINE`) signs person moves with a passkey. `setPersonSigning` records a `person_signing` event: anyone may turn signing on, and turning it off is the person's move, carrying out a request whose relay stamp and exact document the event keeps as `request`, `presence` and `intent`; an off counts only when that document turns signing off and its digest is the one the stamp signed. `proposePersonMove` records a terminal-started person move as a `person_proposal` event and keeps the exact request in `board_meta` as `person_proposals`, for the passkey device to show; it grants nothing. While signing is on, every replica refuses with `PERSON_SIGNED` a person-only move (a row or sentinel decision, an answer, hold, fact or waiver as the person, or any move the person makes) unless it carries out a recorded phone request whose sender carries the relay's passkey stamp; that request's claim, refusal and coordinator-request receipts still pass. Older engines refuse both moves with `ENGINE_VERSION`, and moves recorded before signing was turned on replay as before.The CLI declares its engine in every relay request's `X-Pullboard-Engine` header.A linked board requires at least engine 48 after issuing any agent token or machine credential, including@@ -220,7 +221,7 @@ changed. The service checks again under its board lock and on live-stream polls.Engine 3 checks each move or request against the relay's authenticated sender before replay. An agent token acts only as its named agent and cannot act as the person. Refused attribution attempts advance the sequence with a `relay_refusal_<sequence>` receipt and a `relay_refused` event naming the sender, attempted actor and refusal code. They change no item, shout or verdict and do not reserve the forged operation id. Snapshot restoration requires an authenticated person or board machine sender. A machine can register ordinary agents and ensure the coordinator; other person effects require an earlier authenticated phone intent with exact operation, arguments, target and digest. Every replica consumes its execution once, including row decisions waiting for repository application. Receipt shouts have fixed text; refusal details remain in the structured request result. The event log remains version 1.-A board without `event_log_version` is a legacy version-0 event log. Opening an older board writes the current marker without replacing its events. Opening a newer event log refuses with `EVENT_LOG_VERSION`, naming the stored and supported versions and asking you to upgrade Pullboard. `doctor` reports that version conflict read-only.+A board without `event_log_version` is a legacy version-0 event log. Opening an older board writes the current marker without replacing its events. Opening a newer event log refuses with `EVENT_LOG_VERSION`, naming the stored and supported versions and asking you to upgrade Pullboard. `doctor` reports that version conflict read-only. Turning signed person moves on raises the board to format 2 in the same transaction, and an import or checkpoint restore whose events include `person_signing` does too, so a Pullboard from before signed person moves refuses the board instead of ignoring them. Ordinary boards stay at format 1.A native board export includes the marker in its `board_meta` rows. Import refuses a newer event-log version before changing the destination; an older export upgrades its marker in place. Static view exports put `eventLogVersion` beside the data in both `state.json` and `events.json`, separately from the API envelope's `version`.@@ -450,6 +451,8 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `flake-observation` | reporting agent | engine-59 `engine`, `observation` || `flake-repair` | reporting agent | engine-59 `engine`, `key`, `item` || `row_apply` | coordinator | `events` |+| `person_signing` | enabling agent, or person | engine-76 `signed`, `request`, `presence`, `intent` |+| `person_proposal` | proposing agent | engine-76 `request`, `verb` |<!-- events:end -->A CLI `accept` event includes `check: "none"` when no frozen item check ran or `check: "green"` when it passed. Older accept events and records without this field read as `unknown`; the result stays in event detail and does not change the board schema or event-log version.diff --git a/docs/formats.test.js b/docs/formats.test.jsindex 5e97bee8..2311dbe9 100644--- a/docs/formats.test.js+++ b/docs/formats.test.js@@ -1,9 +1,19 @@/** Keep the format guide aligned with parser behavior, live SQLite schema and static export [A5,A10]. */import assert from 'node:assert/strict';import { execFileSync } from 'node:child_process';-import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';-import { join, relative } from 'node:path';+import {+ join,+ relative,+} from 'node:path';import { DatabaseSync } from 'node:sqlite';import { test } from 'node:test';import { submitFixture } from '../test/board-submit-fixture.js';@@ -17,7 +27,10 @@ import { COORDINATOR } from '../src/config.js';import { JSON_SHAPES } from '../src/json.js';import { exportView } from '../src/serve.js';import { ENGINE_VERSION } from '../src/machine.js';-import { applyEngineMove, prepareEngineMove } from '../src/engine.js';+import {+ applyEngineMove,+ prepareEngineMove,+} from '../src/engine.js';import {ACCEPT_REASON,answerDecision,@@ -56,8 +69,21 @@ import {verify,withdraw,} from '../src/board.js';-import { ID_RE, readSignoffs, SPEC_GRAMMAR_VERSION, STATUSES, TIERS, lintSpec, parseSpec, unmetRows } from '../src/spec.js';-import { sha256, signRows } from '../src/signature.js';+import {+ ID_RE,+ readSignoffs,+ SPEC_GRAMMAR_VERSION,+ STATUSES,+ TIERS,+ lintSpec,+ parseSpec,+ unmetRows,+} from '../src/spec.js';+import {+ sha256,+ signRows,+} from '../src/signature.js';+import { recordSigningEvents } from '../test/person-passkey-fixture.js';const guide = readFileSync(new URL('./formats.md', import.meta.url), 'utf8');@@ -358,6 +384,7 @@ function recordEventContract() {withdraw(board, withdrawn, { agentId: coordinator, reason: 'duplicate fixture' });holdLane(board, 'view', { agentId: coordinator, reason: 'fixture hold' });releaseLane(board, 'view', { agentId: coordinator });+ recordSigningEvents(board, coordinator);appendFact(board, first, { agentId: coordinator, kind: 'root-cause', text: 'A typed immediate Rigor format example', cause: 'doctrine:C3', neverAgain: true, asPerson: true, channel: 'terminal' });// A synthetic health observation exercises receipt fields only; the health tests prove scanning.const healthFinding = { key: `CLAIM_LAPSED:item:${corrected}`, cause: 'CLAIM_LAPSED', item: corrected,@@ -658,11 +685,13 @@ test('[A5] schema, versions, event kinds and event detail fields match live beha'sentinel-start': 'running agent','sentinel-run': 'running agent','sentinel-failure': 'sentinel',+ person_proposal: 'proposing agent',};for (const row of actualRows) {const kind = row.event_kind;const entry = actual[kind] ?? { actors: new Set(), fields: new Set() };- const actor = kind === 'refreeze' && row.event_by !== COORDINATOR+ const actor = kind === 'person_signing' && row.event_by !== PERSON ? 'enabling agent'+ : kind === 'refreeze' && row.event_by !== COORDINATOR? 'live holder adopting a pending correction': actorByKind[kind] ?? actors[row.event_by] ?? 'unknown';entry.actors.add(actor);diff --git a/relay/auth.js b/relay/auth.jsindex dd0eb746..800f49ab 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -1,6 +1,17 @@/** Hash-only relay sessions and board credentials, authorized by current GitHub roles [H8, H1, H13, H14, H16, H3]. */-import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';-import { chmodSync, mkdirSync } from 'node:fs';+import {+ createHash,+ createPrivateKey,+ generateKeyPairSync,+ randomBytes,+ randomUUID,+ sign,+ timingSafeEqual,+} from 'node:crypto';+import {+ chmodSync,+ mkdirSync,+} from 'node:fs';import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { Refused } from '../src/refused.js';@@ -8,6 +19,13 @@ import { repositoryName } from './github.js';import { approvalContext } from '../src/relay-approval.js';import { VERIFIER_STANDING_ENGINE } from '../src/machine.js';import { PEOPLE_ENGINE } from '../src/people-engine.js';+import {+ grantChallenge,+ passkeyBytes,+ verifyAssertion,+ verifyRegistration,+} from './passkeys.js';+import { presenceAttestation } from '../src/person-presence.js';export const ACCESS_WINDOW_MS = 10 * 60_000;const MAX_TTL = 30 * 24 * 3600_000;@@ -52,6 +70,9 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =CREATE TABLE IF NOT EXISTS relay_seats (board TEXT NOT NULL, agent TEXT NOT NULL,origin TEXT NOT NULL CHECK(origin IN ('machine','registered','root')), creator TEXT, sequence INTEGER, digest TEXT,first_id TEXT, first_created INTEGER, first_expires INTEGER, PRIMARY KEY (board, agent));+ CREATE TABLE IF NOT EXISTS relay_passkeys (id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES relay_users(id),+ public_key TEXT NOT NULL, algorithm INTEGER NOT NULL, counter INTEGER NOT NULL DEFAULT 0, created INTEGER NOT NULL);+ CREATE TABLE IF NOT EXISTS relay_person_authority (slot INTEGER PRIMARY KEY CHECK(slot=1), private_key TEXT NOT NULL, public_key TEXT NOT NULL);CREATE TABLE IF NOT EXISTS relay_coordinator_events (id TEXT PRIMARY KEY, board TEXT NOT NULL,reason TEXT NOT NULL CHECK(reason IN ('bootstrap','reissue','reset')), session_id TEXT NOT NULL,revoked TEXT NOT NULL, issued_id TEXT NOT NULL, at INTEGER NOT NULL);@@ -94,6 +115,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =const webFlows = new Map();const deviceFlows = new Map();const deviceConfirmations = new Map();+ // Passkey registration challenges by hash, held in memory for their five minutes like the sign-in flows [E22].+ const passkeyChallenges = new Map();// A hashed ticket may revoke only its minted session, retained until that session expires.const deviceSessionReceipts = new Map();const sessionGuards = new Set();@@ -118,6 +141,26 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =finally { locked = false; }}+ /** The relay's own Ed25519 key for passkey stamps; only its public half ever leaves this database [E22]. */+ function personAuthorityKeys() {+ return lifecycle(() => {+ let keys = db.prepare('SELECT private_key,public_key FROM relay_person_authority WHERE slot=1').get();+ if (!keys) {+ const pair = generateKeyPairSync('ed25519');+ keys = { private_key: pair.privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64url'),+ public_key: pair.publicKey.export({ type: 'spki', format: 'der' }).toString('base64url') };+ db.prepare('INSERT INTO relay_person_authority(slot,private_key,public_key) VALUES(1,?,?)').run(keys.private_key, keys.public_key);+ }+ return keys;+ });+ }++ /** Require the person's own session for a passkey action; machine and agent credentials never qualify. */+ function personOnly(principal) {+ if (principal?.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'only the person, signed in on their phone or browser, uses a passkey; agents and machines cannot');+ return principal;+ }+/** Revoke a server-held device session when its person declined or abandoned confirmation. */function discardDeviceSession(flow) {if (!flow.session?.id) return;@@ -810,6 +853,98 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =return db.prepare('SELECT id,reason,session_id,revoked,issued_id,at FROM relay_coordinator_events WHERE board=? ORDER BY at,rowid').all(board).map((row) => ({ id: row.id, reason: row.reason, session: row.session_id, revoked: JSON.parse(row.revoked), issued: row.issued_id, at: row.at }));},+ /** Publish the public half of the passkey stamp key, which boards pin from their own configured relay origin [E22]. */+ personAuthority() {+ return { version: 1, algorithm: 'Ed25519', publicKey: personAuthorityKeys().public_key };+ },+ /** Start a passkey registration for the signed-in person: a single-use challenge, valid five minutes. */+ passkeyChallenge(principal) {+ personOnly(principal);+ const challenge = randomBytes(32).toString('base64url');+ const expires = now() + 300_000;+ for (const [key, entry] of passkeyChallenges) if (entry.expires <= now()) passkeyChallenges.delete(key);+ passkeyChallenges.set(hash(challenge), { user: principal.user.id, expires });+ return { challenge, expires, user: { id: Buffer.from(principal.user.id).toString('base64url'), name: principal.user.login } };+ },+ /** Keep a passkey the person registered with user presence, consuming its challenge once. */+ registerPasskey(principal, body, expected) {+ personOnly(principal);+ if (!body || Object.keys(body).sort().join() !== 'authenticatorData,challenge,clientDataJSON,id' || typeof body.challenge !== 'string') {+ throw new Refused('PASSKEY_REGISTRATION', 'send the challenge, id, clientDataJSON and authenticatorData of one new passkey');+ }+ passkeyBytes(body.id, 'PASSKEY_REGISTRATION', 1400);+ const pending = passkeyChallenges.get(hash(body.challenge));+ passkeyChallenges.delete(hash(body.challenge));+ if (!pending || pending.user !== principal.user.id || pending.expires <= now()) throw new Refused('PASSKEY_REGISTRATION', 'the registration challenge expired or belongs to another sign-in; add the passkey again');+ return lifecycle(() => {+ const passkey = verifyRegistration(body, { ...expected, challenge: body.challenge });+ const owner = db.prepare('SELECT user_id FROM relay_passkeys WHERE id=?').get(passkey.id);+ if (owner && owner.user_id !== principal.user.id) throw new Refused('PASSKEY_REGISTRATION', 'this passkey belongs to another account; add a new passkey');+ db.prepare('INSERT INTO relay_passkeys(id,user_id,public_key,algorithm,counter,created) VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET public_key=excluded.public_key,algorithm=excluded.algorithm,counter=excluded.counter')+ .run(passkey.id, principal.user.id, JSON.stringify(passkey.jwk), passkey.algorithm, passkey.counter, now());+ return { id: passkey.id, created: now() };+ });+ },+ /** The ids of the signed-in person's passkeys, for the browser's allowCredentials list. */+ passkeys(principal) {+ personOnly(principal);+ return db.prepare('SELECT id FROM relay_passkeys WHERE user_id=? ORDER BY created,id').all(principal.user.id).map((row) => row.id);+ },+ /**+ * Mint a single-use grant for one person request on one board, bound to the digest of its exact intent. The+ * grant is a bearer value the browser holds in memory only; its passkey assertion signs the grant's digest.+ */+ issuePersonGrant(principal, board, body) {+ personOnly(principal);+ if (!body || Object.keys(body).sort().join() !== 'digest,request' || typeof body.request !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(body.request)+ || typeof body.digest !== 'string' || !/^[0-9a-f]{64}$/u.test(body.digest)) {+ throw new Refused('BAD_REQUEST', 'ask for a person grant with the request id and the SHA-256 of its exact intent');+ }+ const credentials = auth.passkeys(principal);+ if (!credentials.length) throw new Refused('PASSKEY_REQUIRED', 'add a passkey on this phone or browser first: it confirms each person move with Face ID, Touch ID or a key touch');+ const grant = random('pg_');+ const expires = now() + 120_000;+ lifecycle(() => db.prepare('INSERT INTO relay_action_grants(hash,request,user_id,context,expires) VALUES(?,?,?,?,?)')+ .run(hash(grant), 'person:' + randomUUID(), principal.user.id, JSON.stringify({ kind: 'person', board, request: body.request, digest: body.digest }), expires));+ return { grant, expires, credentials };+ },+ /**+ * Check a passkey answer for a person request on this board and return the relay's signed stamp, with a commit+ * that spends the grant and advances the passkey's counter. The caller commits only once the request is stored.+ */+ personPresence(principal, board, presence, expected) {+ personOnly(principal);+ if (!presence || Object.keys(presence).sort().join() !== 'authenticatorData,clientDataJSON,credential,grant,signature'+ || typeof presence.grant !== 'string' || !/^pg_[A-Za-z0-9_-]{43}$/u.test(presence.grant)) {+ throw new Refused('PASSKEY_ASSERTION', 'send the grant and the passkey answer for this request');+ }+ const row = db.prepare('SELECT * FROM relay_action_grants WHERE hash=?').get(hash(presence.grant));+ let context = null;+ try { context = row ? JSON.parse(row.context) : null; } catch { context = null; } // An unreadable grant row grants nothing.+ if (!row || row.used || row.expires <= now() || row.user_id !== principal.user.id || context?.kind !== 'person' || context.board !== board) {+ throw new Refused('PHONE_APPROVAL_USED', 'this grant was used, expired or names another board; confirm the move again on your passkey');+ }+ const passkey = db.prepare('SELECT * FROM relay_passkeys WHERE id=? AND user_id=?').get(presence.credential, principal.user.id);+ if (!passkey) throw new Refused('PASSKEY_ASSERTION', 'this passkey is not registered to your account; add it on this phone or browser first');+ const counter = verifyAssertion(presence, { ...expected, challenge: grantChallenge(presence.grant),+ passkey: { jwk: JSON.parse(passkey.public_key), algorithm: passkey.algorithm, counter: passkey.counter } });+ const at = now();+ const unsigned = { board, request: context.request, digest: context.digest, credential: passkey.id, at };+ const key = createPrivateKey({ key: Buffer.from(personAuthorityKeys().private_key, 'base64url'), format: 'der', type: 'pkcs8' });+ const stamp = { ...unsigned, signature: sign(null, presenceAttestation(unsigned), key).toString('base64url') };+ return {+ stamp,+ /** Spend the grant once and keep the passkey's new counter, under the caller's board lock. */+ commit() {+ lifecycle(() => {+ if (!db.prepare('UPDATE relay_action_grants SET used=1 WHERE hash=? AND used=0').run(hash(presence.grant)).changes) {+ throw new Refused('PHONE_APPROVAL_USED', 'this grant was already used; confirm the move again on your passkey');+ }+ db.prepare('UPDATE relay_passkeys SET counter=? WHERE id=? AND counter<=?').run(counter, passkey.id, counter);+ });+ },+ };+ },/** Mint a short-lived grant only after an authenticated phone approves an immutable action context. */async issueActionGrant(token, value) {const context = approvalContext(value);@@ -861,7 +996,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =close() {if (closed) return;closed = true;- webFlows.clear(); deviceFlows.clear(); deviceConfirmations.clear(); deviceSessionReceipts.clear(); sessionGuards.clear(); permissions.clear(); db.close();+ webFlows.clear(); deviceFlows.clear(); passkeyChallenges.clear(); deviceConfirmations.clear(); deviceSessionReceipts.clear(); sessionGuards.clear(); permissions.clear(); db.close();},};return auth;diff --git a/relay/browser-client.js b/relay/browser-client.jsindex df304433..d0d172ad 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -1,18 +1,60 @@/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15,H16,H17]. */-import { rememberDevicePairing, enrollPhone, deviceBoardKeyState, installPhoneApprovals, forgetDevice } from './browser-devices.js';-import { decodeBoardKey, encodeBoardKey, seal, unseal } from './seal.js';-import { preparePersonRequest, validatePersonRequest } from './person-request.js';-import { snapshotState, presentationState } from './model.js';+import {+ rememberDevicePairing,+ enrollPhone,+ deviceBoardKeyState,+ installPhoneApprovals,+ forgetDevice,+} from './browser-devices.js';+import {+ decodeBoardKey,+ encodeBoardKey,+ seal,+ unseal,+} from './seal.js';+import {+ preparePersonRequest,+ validatePersonRequest,+} from './person-request.js';+import {+ snapshotState,+ presentationState,+} from './model.js';import { ENGINE_VERSION } from './engine.js';import { Refused } from './refused.js';import { SNAPSHOT_BODY_BYTES } from './relay-limits.js';-import { enqueueStream, followStream } from './browser-stream.js';-import { emptyBoardStep, homeLineDismissed, homeScreenLine, noticeLines, rememberOwnedRequestId, showRelayScreen, storedOwnedRequestState } from './browser-notice.js';-import { registerApp, requestPairingPersistence } from './install.js';-import { browserJSON, withBrowserDeadline } from './browser-deadline.js';-import { phoneApprovalStatus, placePhoneApprovals, forgetPhoneApprovals } from './browser-approval-card.js';+import {+ enqueueStream,+ followStream,+} from './browser-stream.js';+import {+ emptyBoardStep,+ homeLineDismissed,+ homeScreenLine,+ noticeLines,+ rememberOwnedRequestId,+ showRelayScreen,+ storedOwnedRequestState,+} from './browser-notice.js';+import {+ registerApp,+ requestPairingPersistence,+} from './install.js';+import {+ browserJSON,+ withBrowserDeadline,+} from './browser-deadline.js';+import {+ phoneApprovalStatus,+ placePhoneApprovals,+ forgetPhoneApprovals,+} from './browser-approval-card.js';import { phoneSnapshotPages } from './browser-pages.js';import { createPhoneHistory } from './browser-history.js';+import {+ installPersonPasskeys,+ passkeyPresence,+} from './browser-passkeys.js';const CHECKPOINT_WAIT_MS = 15_000;const KEYS = 'pullboard.relay.keys.v1';@@ -119,6 +161,8 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>let accessLost = false;let accessError = null;const access = new AbortController();+ // Passkey answers for requests in flight, by request id: memory only, spent by the relay on first use [E22].+ const presences = new Map();let persistenceRequest = null;// New viewers acknowledge their first actual render; old viewers retain the prior transition contract.let rendered = waitForRender !== true;@@ -701,8 +745,9 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>const envelope = entry.outbox;let response;try {+ const presence = presences.get(value.id);response = await documentAt('/api/v1/boards/' + entry.id + '/requests', denied, {- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sequence: envelope.sequence, sealed: envelope.sealed }),+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sequence: envelope.sequence, sealed: envelope.sealed, ...(presence ? { presence } : {}) }),});} catch (error) { if (['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) continue; throw error; }if (response.event?.event_id !== envelope.sequence || response.event.kind !== 'request' || response.event.sealed !== envelope.sealed) throw new Refused('RELAY_RESPONSE', 'The relay acknowledgement differs from this request. Retry this board.');@@ -710,6 +755,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>const record = entry.state.personRequests.find(request => request.id === value.id);if (!record) throw new Refused('RELAY_RESPONSE', 'The request acknowledgement has no receipt. Retry this board.');acknowledge(entry, value.id);+ presences.delete(value.id);notice();onUpdate();return { version: 1, event: response.event, result: { request: structuredClone(record) } };@@ -782,6 +828,30 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>keys, openApprovedBoard, access.signal).catch(() => {if (!accessLost) phoneApprovalStatus(document, 'Requests from your computer did not load. Open this page again to retry.');});+ /**+ * Seal and send one person request. While the board signs person moves, a passkey confirms this exact request first,+ * with the person present; its answer rides with the send and is never stored [E22].+ */+ function sendPersonRequest(entry, value) {+ return enqueue(entry, async () => {+ await flushOutbox(entry);+ await snapshot(entry); await catchUp(entry);+ // A signed row decision names the exact text of each row this page shows; the passkey confirms that text.+ if (entry.state.personSigning?.signed && ['spec-approve', 'spec-decline'].includes(value.move.verb) && !value.rows) {+ value = preparePersonRequest(value.move, value.id, value.move.args.ids.split(/[\s,]+/u).filter(Boolean).map(id => ({ id,+ text: (id.startsWith('doctrine:') ? entry.state.practice : entry.state.spec).find(row => row.id === id.replace(/^doctrine:/u, ''))?.text ?? '' })));+ }+ if (entry.state.personSigning?.signed && !presences.has(value.id)) {+ presences.set(value.id, await passkeyPresence((path, options) => documentAt(path, denied, { ...options, signal: access.signal }), entry.id, value));+ }+ entry.outbox = await requestEnvelope(entry, value, entry.cursor + 1);+ saveOutbox(entry);+ return sendOutbox(entry);+ });+ }+ installPersonPasskeys(document, { documentAt: (path, options) => documentAt(path, denied, { ...options, signal: access.signal }),+ boards: () => [...paired.values()], signal: access.signal,+ confirm: (board, proposal) => sendPersonRequest(paired.get(board), preparePersonRequest(proposal.move, proposal.id, proposal.rows)) });return {/** Give the startup frame back only after an opted-in viewer has drawn a readable board. */didRender() { rendered = true; notice(); for (const entry of paired.values()) entry.history?.start(); },@@ -802,15 +872,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>if (body !== undefined && body !== null) {if (shoutMatch || itemMatch) throw new Refused('BAD_REQUEST', 'Read item or shout detail with GET; send person intent to the board moves endpoint.');if (!['moves', 'requests'].includes(match[2])) throw new Refused('BAD_REQUEST', 'Send person intent to this board’s moves endpoint.');- const value = preparePersonRequest(body);- const send = enqueue(entry, async () => {- await flushOutbox(entry);- await snapshot(entry); await catchUp(entry);- entry.outbox = await requestEnvelope(entry, value, entry.cursor + 1);- saveOutbox(entry);- return sendOutbox(entry);- });- return send;+ return sendPersonRequest(entry, preparePersonRequest(body));}if (itemMatch) return enqueue(entry, async () => {await flushOutbox(entry); await snapshot(entry); await catchUp(entry);diff --git a/relay/browser-page.js b/relay/browser-page.jsindex b32cee3f..bcb75ac2 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -48,6 +48,7 @@ export function createRelayBrowserHandler({ authenticate }) {['/relay/relay-approval.js', ['text/javascript', readFileSync(new URL('../src/relay-approval.js', import.meta.url), 'utf8').replace("'./relay-device-keys.js'", "'./device-keys.js'")]],['/relay/browser-devices.js', ['text/javascript', readFileSync(new URL('./browser-devices.js', import.meta.url), 'utf8')]],['/relay/browser-approval-card.js', ['text/javascript', readFileSync(new URL('./browser-approval-card.js', import.meta.url), 'utf8')]],+ ['/relay/browser-passkeys.js', ['text/javascript', readFileSync(new URL('./browser-passkeys.js', import.meta.url), 'utf8')]],['/relay/client.js', ['text/javascript', readFileSync(new URL('./browser-client.js', import.meta.url), 'utf8')]],['/relay/relay-limits.js', ['text/javascript', readFileSync(new URL('../src/relay-limits.js', import.meta.url), 'utf8')]],['/relay/sign-in.js', ['text/javascript', SIGN_IN_TRANSPORT]],diff --git a/relay/browser-passkeys.js b/relay/browser-passkeys.jsnew file mode 100644index 00000000..090ea6d8--- /dev/null+++ b/relay/browser-passkeys.js@@ -0,0 +1,132 @@+/**+ * Passkeys in the relay page [E22,H16]: add one, confirm a person request with one, and show the person moves a+ * terminal started so they complete on one confirmation here. The grant and the assertion live only in memory.+ */+import { Refused } from './refused.js';++const JSON_HEADERS = { 'content-type': 'application/json' };++/** Encode bytes as base64url, as the relay reads them. */+function encode(bytes) {+ let binary = '';+ for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');+}++/** Decode base64url text from the relay into bytes. */+function decode(text) {+ const plain = atob(text.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - text.length % 4) % 4));+ return Uint8Array.from(plain, (char) => char.charCodeAt(0));+}++/** Refuse plainly where this browser has no passkeys at all. */+function requirePasskeys() {+ if (!globalThis.PublicKeyCredential || !navigator.credentials) {+ throw new Refused('PASSKEY_UNSUPPORTED', 'This browser has no passkeys. Use a phone or browser with Face ID, Touch ID or a security key.');+ }+}++/** Register a new passkey for the signed-in person; the authenticator asks for the person before it answers. */+export async function addPasskey(documentAt) {+ requirePasskeys();+ const start = await documentAt('/api/v1/passkeys/challenge', { method: 'POST', headers: JSON_HEADERS, body: '{}' });+ const credential = await navigator.credentials.create({ publicKey: {+ challenge: decode(start.challenge), rp: { id: start.rpId, name: 'Pullboard' },+ user: { id: decode(start.user.id), name: start.user.name, displayName: start.user.name },+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],+ authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' }, attestation: 'none', timeout: 120_000,+ } });+ return documentAt('/api/v1/passkeys', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify({ challenge: start.challenge, id: credential.id,+ clientDataJSON: encode(credential.response.clientDataJSON), authenticatorData: encode(credential.response.getAuthenticatorData()) }) });+}++/** The SHA-256 of a request's exact intent, which the board recomputes before it trusts the relay's stamp. */+export async function intentDigest(value) {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(value)));+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');+}++/**+ * Ask the relay for a single-use grant for this exact request, then have a passkey sign the grant's digest with the+ * person present. Returns what the request carries to the relay; nothing here is stored.+ */+export async function passkeyPresence(documentAt, board, value) {+ requirePasskeys();+ const issued = await documentAt('/api/v1/boards/' + board + '/person-grants', { method: 'POST', headers: JSON_HEADERS,+ body: JSON.stringify({ request: value.id, digest: await intentDigest(value) }) });+ const challenge = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(issued.grant)));+ const credential = await navigator.credentials.get({ publicKey: { challenge, userVerification: 'preferred', timeout: 120_000,+ allowCredentials: issued.credentials.map((id) => ({ type: 'public-key', id: decode(id) })) } });+ const response = credential.response;+ return { grant: issued.grant, credential: credential.id, clientDataJSON: encode(response.clientDataJSON),+ authenticatorData: encode(response.authenticatorData), signature: encode(response.signature) };+}++/** Say in words what a terminal-started person move does, so the person confirms what they read. */+export function proposalText(move) {+ const args = move.args ?? {};+ if (move.verb === 'answer') return `Answer decision #${move.item}: ${args.text}`;+ if (move.verb === 'spec-approve') return `Approve ${args.ids}${args.text ? ` as: ${args.text}` : ''}`;+ if (move.verb === 'spec-decline') return `Decline ${args.ids}: ${args.reason ?? ''}`;+ if (move.verb === 'land-waive') return `Waive ${args.waive} until ${args.until}: ${args.reason}`;+ if (move.verb === 'signing') return args.signed === 'off' ? 'Stop signing person moves with your passkey' : 'Sign person moves with your passkey';+ return `${move.verb} ${JSON.stringify(args)}`;+}++/**+ * Keep a small panel on the page while a paired board signs person moves: add a passkey when there is none, and a+ * card per terminal-started move with one button that confirms it on the passkey.+ *+ * @param {Document} doc+ * @param {{ documentAt: Function, boards: () => any[], confirm: (board: string, proposal: any) => Promise<any>, signal?: AbortSignal }} options+ */+export function installPersonPasskeys(doc, { documentAt, boards, confirm, signal }) {+ const done = new Set();+ let passkeys = null;+ let timer;+ /** Draw the panel from the boards' current sealed state. */+ async function render() {+ const signed = boards().filter((entry) => entry.state?.personSigning?.signed);+ let panel = doc.getElementById('person-passkeys');+ if (!signed.length) { panel?.remove(); return; }+ if (!panel) {+ panel = doc.createElement('section'); panel.id = 'person-passkeys'; panel.className = 'card-panel';+ panel.setAttribute('aria-label', 'Person moves waiting for your passkey');+ doc.querySelector('main')?.prepend(panel);+ }+ passkeys ??= (await documentAt('/api/v1/passkeys')).passkeys;+ const cards = [];+ if (!passkeys.length) {+ const add = doc.createElement('button'); add.type = 'button'; add.id = 'person-passkey-add'; add.textContent = 'Add a passkey';+ add.onclick = async () => {+ add.disabled = true;+ try { await addPasskey(documentAt); passkeys = null; add.remove(); await render(); }+ catch (error) { add.textContent = 'Passkey not added: ' + (error.message || 'try again'); add.disabled = false; }+ };+ const why = doc.createElement('p'); why.textContent = 'Person moves on this board are signed. Add a passkey to confirm them with Face ID, Touch ID or a key.';+ cards.push(why, add);+ }+ for (const entry of signed) {+ for (const proposal of entry.state.personProposals ?? []) {+ if (done.has(proposal.id) || Date.parse(proposal.expires) <= Date.now()) continue;+ const card = doc.createElement('div'); card.className = 'phone-approval'; card.dataset.proposal = proposal.id;+ const text = doc.createElement('p'); text.className = 'phone-approval-title'; text.textContent = proposalText(proposal.move) + (proposal.rows?.length ? '\n' + proposal.rows.map(row => `${row.id}: ${row.text}`).join('\n') : '');+ const button = doc.createElement('button'); button.type = 'button'; button.id = 'person-confirm-' + proposal.id; button.textContent = 'Confirm with passkey';+ button.onclick = async () => {+ button.disabled = true;+ try { await confirm(entry.id, proposal); done.add(proposal.id); card.remove(); }+ catch (error) { text.textContent = 'Not confirmed: ' + (error.message || 'try again'); button.disabled = false; }+ };+ card.append(text, button); cards.push(card);+ }+ }+ if (!panel.querySelector('button:disabled')) panel.replaceChildren(...cards);+ }+ /** Refresh once a second until the page loses relay access. */+ async function loop() {+ try { await render(); } catch { /* A failed refresh keeps the last panel; the next tick retries. */ }+ if (!signal?.aborted) timer = setTimeout(loop, 1000);+ }+ signal?.addEventListener('abort', () => { clearTimeout(timer); doc.getElementById('person-passkeys')?.remove(); }, { once: true });+ void loop();+}diff --git a/relay/journal.js b/relay/journal.jsindex 9492cf09..3dbd605a 100644--- a/relay/journal.js+++ b/relay/journal.js@@ -1,7 +1,15 @@/** Durable opaque upload ordering; record interpretation belongs to a later relay adapter [A4,H7]. */import { DatabaseSync } from 'node:sqlite';-import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs';-import { join, resolve } from 'node:path';+import {+ closeSync,+ lstatSync,+ mkdirSync,+ openSync,+} from 'node:fs';+import {+ join,+ resolve,+} from 'node:path';import { Refused } from '../src/refused.js';import { SEALED_SNAPSHOT_BYTES } from '../src/relay-limits.js';import { createRelayPages } from './page-store.js';@@ -87,7 +95,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE// Engine-73 people (#343): the GitHub login behind each record, and whether that person was one of the// board's approvers when it arrived. Older records keep them empty and replay as they did.for (const [column, type] of [['sender_policy', 'INTEGER'], ['sender_root', 'INTEGER'], ['sender_lineage', 'TEXT'], ['registration', 'TEXT'],- ['sender_login', 'TEXT'], ['sender_approver', 'INTEGER'], ['sender_engine', 'INTEGER']]) {+ ['sender_login', 'TEXT'], ['sender_approver', 'INTEGER'], ['sender_engine', 'INTEGER'], ['sender_presence', 'TEXT']]) {if (!db.prepare('PRAGMA table_info(journal_record)').all().some((saved) => saved.name === column)) db.exec(`ALTER TABLE journal_record ADD COLUMN ${column} ${type}`);}// A published seat receipt claims its target for good: compaction keeps it, so no later machine@@ -136,7 +144,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE...(row.sender_policy ? { policy: row.sender_policy } : {}), ...(row.sender_root ? { root: true } : {}),...(row.sender_lineage ? { lineage: row.sender_lineage } : {}),...(row.sender_login ? { login: row.sender_login } : {}), ...(row.sender_approver === null || row.sender_approver === undefined ? {} : { approver: row.sender_approver === 1 }),- ...(row.sender_engine ? { engine: row.sender_engine } : {}) },+ ...(row.sender_engine ? { engine: row.sender_engine } : {}), ...(row.sender_presence ? { presence: JSON.parse(row.sender_presence) } : {}) },...(row.registration ? { registration: JSON.parse(row.registration) } : {}),...(row.api_version === 2 ? { apiVersion: 2, pageBytes: row.page_bytes } : {}), bytes: Buffer.from(row.payload) };}@@ -153,12 +161,14 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEif ((value.policy !== undefined && (!Number.isSafeInteger(value.policy) || value.policy < 1)) || (value.root !== undefined && value.root !== true) ||(value.lineage !== undefined && (typeof value.lineage !== 'string' || !/^[0-9a-f-]{36}$/.test(value.lineage))) ||(value.login !== undefined && (typeof value.login !== 'string' || !/^[A-Za-z0-9-]{1,39}$/u.test(value.login))) ||- (value.approver !== undefined && typeof value.approver !== 'boolean') || (value.engine !== undefined && (!Number.isSafeInteger(value.engine) || value.engine < 1))) {+ (value.approver !== undefined && typeof value.approver !== 'boolean') || (value.engine !== undefined && (!Number.isSafeInteger(value.engine) || value.engine < 1)) ||+ (value.presence !== undefined && (value.kind !== 'person' || !value.presence || typeof value.presence !== 'object'))) {throw new Refused('RELAY_PRINCIPAL', 'supply the relay policy stamp as a positive engine number');}return { kind: value.kind, userId: value.userId, agent: value.kind === 'agent' ? value.agent : value.kind === 'machine' ? value.machine : null,policy: value.policy ?? null, root: value.root === true ? 1 : null, lineage: value.lineage ?? null,- login: value.login ?? null, approver: value.approver === undefined ? null : value.approver ? 1 : 0, engine: value.engine ?? null };+ login: value.login ?? null, approver: value.approver === undefined ? null : value.approver ? 1 : 0, engine: value.engine ?? null,+ presence: value.presence === undefined ? null : JSON.stringify(value.presence) };}/** Keep a seat receipt to its four public fields: target, creator, sequence and ciphertext digest. */@@ -208,8 +218,8 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEif (sequence > next) throw new Refused('SEQUENCE_GAP', 'send the next sequence after the latest committed record before later uploads');const at = now();if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');- db.prepare('INSERT INTO journal_record (sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent,sender_policy,sender_root,sender_lineage,registration,sender_login,sender_approver,sender_engine) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)')- .run(sequence, at.toISOString(), kind, sealed, who.kind, who.userId, who.agent, who.policy, who.root, who.lineage, stored, who.login, who.approver, who.engine);+ db.prepare('INSERT INTO journal_record (sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent,sender_policy,sender_root,sender_lineage,registration,sender_login,sender_approver,sender_engine,sender_presence) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')+ .run(sequence, at.toISOString(), kind, sealed, who.kind, who.userId, who.agent, who.policy, who.root, who.lineage, stored, who.login, who.approver, who.engine, who.presence);if (stored) {const claim = JSON.parse(stored);if (db.prepare('SELECT 1 FROM journal_registration WHERE target=?').get(claim.target)) {diff --git a/relay/passkey-http.js b/relay/passkey-http.jsnew file mode 100644index 00000000..40c21101--- /dev/null+++ b/relay/passkey-http.js@@ -0,0 +1,45 @@+/** Passkey registration, person grants and the public stamp key over HTTP [E22,H16]. */+import {+ apiJson,+ apiRefusal,+ apiStatus,+ readApiBody,+} from '../src/api-http.js';+import { Refused } from '../src/refused.js';++/**+ * Route the fixed passkey endpoints. Every one but the public key needs the person's own session: a machine or agent+ * credential is refused before any passkey work.+ *+ * @param {{ auth: any, origin: () => { origin: string, rpId: string }, person: (req: any, write: boolean) => Promise<any>, board: (req: any, id: string) => Promise<any> }} options+ */+export function createPasskeyHandler({ auth, origin, person, board }) {+ return async function handlePasskeys(req, res) {+ const url = new URL(req.url ?? '/', 'http://localhost');+ const grants = /^\/api\/v1\/boards\/([^/]+)\/person-grants$/u.exec(url.pathname);+ if (url.pathname !== '/.well-known/pullboard-person-authority' && !url.pathname.startsWith('/api/v1/passkeys') && !grants) return false;+ try {+ if (url.search) throw new Refused('BAD_REQUEST', 'keep passkey fields out of URL queries');+ if (url.pathname === '/.well-known/pullboard-person-authority' && req.method === 'GET') {+ apiJson(res, 200, { authority: auth.personAuthority() }); return true;+ }+ if (grants && req.method === 'POST') {+ const who = await board(req, grants[1]);+ apiJson(res, 200, auth.issuePersonGrant(who, grants[1], await readApiBody(req))); return true;+ }+ if (url.pathname === '/api/v1/passkeys/challenge' && req.method === 'POST') {+ const who = await person(req, true);+ await readApiBody(req);+ apiJson(res, 200, { ...auth.passkeyChallenge(who), rpId: origin().rpId }); return true;+ }+ if (url.pathname === '/api/v1/passkeys' && req.method === 'POST') {+ const who = await person(req, true);+ apiJson(res, 200, { passkey: auth.registerPasskey(who, await readApiBody(req), origin()) }); return true;+ }+ if (url.pathname === '/api/v1/passkeys' && req.method === 'GET') {+ apiJson(res, 200, { passkeys: auth.passkeys(await person(req, false)) }); return true;+ }+ throw new Refused('NO_ENDPOINT', 'use the documented passkey endpoints');+ } catch (error) { apiJson(res, apiStatus(error), apiRefusal(error)); return true; }+ };+}diff --git a/relay/passkeys.js b/relay/passkeys.jsnew file mode 100644index 00000000..a0498d95--- /dev/null+++ b/relay/passkeys.js@@ -0,0 +1,146 @@+/**+ * WebAuthn passkeys for signed person moves, verified with node:crypto alone [E22,H16].+ *+ * A passkey signs only after its authenticator sees the person (Face ID, Touch ID or a security-key touch), which+ * is the user-presence flag the relay requires on every registration and assertion. Why the relay checks it: an+ * agent can read every file and key its user's shell can, but it cannot make an authenticator report a person.+ */+import {+ createHash,+ createPublicKey,+ verify,+} from 'node:crypto';+import { Refused } from '../src/refused.js';++const USER_PRESENT = 0x01;+const ATTESTED = 0x40;+export const PASSKEY_ALGORITHMS = Object.freeze([-7, -257]);++/** SHA-256 bytes of a value. */+function sha256(value) { return createHash('sha256').update(value).digest(); }++/** Decode canonical base64url transport bytes, refusing anything else with the given code. */+export function passkeyBytes(value, code = 'PASSKEY_ASSERTION', max = 16_384) {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/u.test(value) || value.length > max) throw passkeyRefusal(code);+ const bytes = Buffer.from(value, 'base64url');+ if (!bytes.length || bytes.toString('base64url') !== value) throw passkeyRefusal(code);+ return bytes;+}++/** A passkey refusal with its next step. */+function passkeyRefusal(code) {+ const why = {+ PASSKEY_REGISTRATION: 'the passkey registration could not be verified; add the passkey again from this browser',+ PASSKEY_ASSERTION: 'the passkey answer does not match this request; confirm it again on your passkey',+ PASSKEY_PRESENCE: 'the passkey answered without a person present; confirm with Face ID, Touch ID or a key touch',+ }[code];+ return new Refused(code, why);+}++/**+ * Read the small CBOR subset a COSE public key uses: unsigned and negative integers, byte strings and one map.+ *+ * @param {Buffer} bytes+ * @param {number} offset+ * @returns {{ value: any, end: number }}+ */+function cbor(bytes, offset) {+ if (offset >= bytes.length) throw passkeyRefusal('PASSKEY_REGISTRATION');+ const major = bytes[offset] >> 5;+ const info = bytes[offset] & 31;+ let length = info;+ let at = offset + 1;+ if (info === 24) { length = bytes[at]; at += 1; }+ else if (info === 25) { length = bytes.readUInt16BE(at); at += 2; }+ else if (info > 25) throw passkeyRefusal('PASSKEY_REGISTRATION');+ if (major === 0) return { value: length, end: at };+ if (major === 1) return { value: -1 - length, end: at };+ if (major === 2) {+ if (at + length > bytes.length) throw passkeyRefusal('PASSKEY_REGISTRATION');+ return { value: bytes.subarray(at, at + length), end: at + length };+ }+ if (major === 5) {+ const map = new Map();+ for (let index = 0; index < length; index += 1) {+ const key = cbor(bytes, at);+ const item = cbor(bytes, key.end);+ map.set(key.value, item.value);+ at = item.end;+ }+ return { value: map, end: at };+ }+ throw passkeyRefusal('PASSKEY_REGISTRATION');+}++/** Turn a COSE ES256 or RS256 key into a JWK node:crypto can verify with, with its algorithm. */+function coseKey(map) {+ const algorithm = map.get(3);+ if (algorithm === -7 && map.get(1) === 2 && map.get(-1) === 1 && map.get(-2)?.length === 32 && map.get(-3)?.length === 32) {+ return { algorithm, jwk: { kty: 'EC', crv: 'P-256', x: map.get(-2).toString('base64url'), y: map.get(-3).toString('base64url') } };+ }+ if (algorithm === -257 && map.get(1) === 3 && Buffer.isBuffer(map.get(-1)) && Buffer.isBuffer(map.get(-2))) {+ return { algorithm, jwk: { kty: 'RSA', n: map.get(-1).toString('base64url'), e: map.get(-2).toString('base64url') } };+ }+ throw passkeyRefusal('PASSKEY_REGISTRATION');+}++/** Split authenticator data into its RP id hash, flags, counter and any attested credential. */+function authenticatorData(bytes, code) {+ if (bytes.length < 37) throw passkeyRefusal(code);+ return { rpIdHash: bytes.subarray(0, 32), flags: bytes[32], counter: bytes.readUInt32BE(33), rest: bytes.subarray(37) };+}++/** Check client data for this ceremony, challenge and origin. */+function clientData(encoded, type, challenge, origin, code) {+ const bytes = passkeyBytes(encoded, code);+ let value;+ try { value = JSON.parse(bytes.toString('utf8')); } catch { throw passkeyRefusal(code); }+ if (value?.type !== type || value.challenge !== challenge || value.origin !== origin || value.crossOrigin === true) throw passkeyRefusal(code);+ return bytes;+}++/**+ * Verify a registration made in a browser on this relay's origin, with the person present. Returns the credential+ * id, its public key as a JWK, its algorithm and its starting counter.+ *+ * @param {{ id: string, clientDataJSON: string, authenticatorData: string }} body+ * @param {{ challenge: string, origin: string, rpId: string }} expected+ */+export function verifyRegistration(body, { challenge, origin, rpId }) {+ clientData(body.clientDataJSON, 'webauthn.create', challenge, origin, 'PASSKEY_REGISTRATION');+ const data = authenticatorData(passkeyBytes(body.authenticatorData, 'PASSKEY_REGISTRATION'), 'PASSKEY_REGISTRATION');+ if (!data.rpIdHash.equals(sha256(rpId)) || !(data.flags & ATTESTED)) throw passkeyRefusal('PASSKEY_REGISTRATION');+ if (!(data.flags & USER_PRESENT)) throw passkeyRefusal('PASSKEY_PRESENCE');+ if (data.rest.length < 18) throw passkeyRefusal('PASSKEY_REGISTRATION');+ const length = data.rest.readUInt16BE(16);+ const id = data.rest.subarray(18, 18 + length);+ if (id.length !== length || !length || id.toString('base64url') !== body.id) throw passkeyRefusal('PASSKEY_REGISTRATION');+ const key = coseKey(cbor(data.rest, 18 + length).value);+ createPublicKey({ key: key.jwk, format: 'jwk' });+ return { id: body.id, ...key, counter: data.counter };+}++/**+ * Verify an assertion from a registered passkey over this challenge, on this origin, with the person present.+ * Returns the authenticator's new counter; a counter that does not rise, when either side counts, is refused.+ *+ * @param {{ clientDataJSON: string, authenticatorData: string, signature: string }} body+ * @param {{ challenge: string, origin: string, rpId: string, passkey: { jwk: any, algorithm: number, counter: number } }} expected+ */+export function verifyAssertion(body, { challenge, origin, rpId, passkey }) {+ const client = clientData(body.clientDataJSON, 'webauthn.get', challenge, origin, 'PASSKEY_ASSERTION');+ const raw = passkeyBytes(body.authenticatorData);+ const data = authenticatorData(raw, 'PASSKEY_ASSERTION');+ if (!data.rpIdHash.equals(sha256(rpId))) throw passkeyRefusal('PASSKEY_ASSERTION');+ const key = createPublicKey({ key: passkey.jwk, format: 'jwk' });+ const signed = Buffer.concat([raw, sha256(client)]);+ if (!verify('sha256', signed, key, passkeyBytes(body.signature))) throw passkeyRefusal('PASSKEY_ASSERTION');+ if (!(data.flags & USER_PRESENT)) throw passkeyRefusal('PASSKEY_PRESENCE');+ if ((data.counter || passkey.counter) && data.counter <= passkey.counter) throw passkeyRefusal('PASSKEY_ASSERTION');+ return data.counter;+}++/** The WebAuthn challenge for a person grant: SHA-256 of the grant, so the bearer grant never reaches an authenticator. */+export function grantChallenge(grant) {+ return sha256(grant).toString('base64url');+}diff --git a/relay/service.js b/relay/service.jsindex c4143ba6..4eaa7e02 100644--- a/relay/service.js+++ b/relay/service.js@@ -1,9 +1,21 @@/** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7,H16,H3]. */import { createServer } from 'node:http';import { createHash } from 'node:crypto';-import { lstatSync, mkdirSync } from 'node:fs';-import { join, resolve } from 'node:path';-import { createApiHandler, apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js';+import {+ lstatSync,+ mkdirSync,+} from 'node:fs';+import {+ join,+ resolve,+} from 'node:path';+import {+ createApiHandler,+ apiJson,+ apiRefusal,+ apiStatus,+ readApiBody,+} from '../src/api-http.js';import { Refused } from '../src/refused.js';import { createRelayJournal } from './journal.js';import { createRelayRetention } from './retention.js';@@ -13,9 +25,16 @@ import { createPairingStore } from './pairing-store.js';import { createPairingHandler } from './pairing-http.js';import { createRelayBrowserHandler } from './browser-page.js';import { VERIFIER_STANDING_ENGINE } from '../src/machine.js';-import { SEALED_SNAPSHOT_BYTES, SNAPSHOT_BODY_BYTES } from '../src/relay-limits.js';-import { createRelayPagesHandler, snapshotPageRoot } from './pages-http.js';+import {+ SEALED_SNAPSHOT_BYTES,+ SNAPSHOT_BODY_BYTES,+} from '../src/relay-limits.js';+import {+ createRelayPagesHandler,+ snapshotPageRoot,+} from './pages-http.js';import { createStorageQuota } from './storage-quota.js';+import { createPasskeyHandler } from './passkey-http.js';const SNAPSHOT_BODY = SNAPSHOT_BODY_BYTES;const STORED_BYTES = SEALED_SNAPSHOT_BYTES;@@ -57,8 +76,8 @@ function trustedOrigin(value) {}/** Decode only canonical transport bytes; sealed payloads are never parsed or unsealed. */-function sealed(body, allowRegistration = false) {- const keys = allowRegistration ? ['sealed', 'sequence', 'registration'] : ['sealed', 'sequence'];+function sealed(body, allowRegistration = false, allowPresence = false) {+ const keys = ['sealed', 'sequence', ...(allowRegistration ? ['registration'] : []), ...(allowPresence ? ['presence'] : [])];if (!body || Object.keys(body).some((key) => !keys.includes(key)) || typeof body.sealed !== 'string' || !/^[A-Za-z0-9_-]+$/.test(body.sealed)) {throw new Refused('BAD_UPLOAD', 'send only sequence and a nonempty base64url sealed payload; keep keys on your device');}@@ -114,6 +133,8 @@ function sender(who, personOnly = false) {// The engine the sender declared: a seal no replica opens, from an engine no newer than the replica's, is junk to set aside [E20]....(Number.isSafeInteger(who.engineVersion) && who.engineVersion > 0 ? { engine: who.engineVersion } : {}),...(who.kind === 'board' ? { agent: who.agent } : who.kind === 'machine' ? { machine: who.machine } : {}),+ // The relay's signed stamp that a passkey confirmed this person request with the person present [E22].+ ...(who.kind === 'session' && who.presence ? { presence: who.presence } : {}),...(personOnly === 'snapshot' ? {} : { policy: VERIFIER_STANDING_ENGINE,...(who.root === true ? { root: true, ...(who.lineage ? { lineage: who.lineage } : {}) } : {}) }) };}@@ -265,14 +286,18 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin/** Append ciphertext under its server-allocated sequence, with no engine or filesystem access. */async function append(board, body, who, kind = 'move') {- const bytes = sealed(body, kind === 'move');+ const bytes = sealed(body, kind === 'move', kind === 'request');if (!Number.isSafeInteger(body.sequence) || body.sequence < 1) throw new Refused('BAD_SEQUENCE', 'seal this move for the next positive sequence after the latest committed prefix');const authenticated = await authorized(who.credential, board.id, true);const principal = sender({ ...authenticated, engineVersion: who.engineVersion });if (body.registration === undefined) {return withJournal(board.id, (journal) => {- const row = body.sequence <= journal.latest() ? journal.append(body.sequence, bytes, kind, principal)- : storing(board.id, principal, bytes.byteLength, () => journal.append(body.sequence, bytes, kind, principal));+ // Under the board lock, a passkey answer is checked, the request stored, then its grant spent, so one grant stamps one request [E22].+ const presence = body.presence === undefined ? null : auth.personPresence(authenticated, board.id, body.presence, passkeyOrigin());+ const stamped = presence ? sender({ ...authenticated, engineVersion: who.engineVersion, presence: presence.stamp }) : principal;+ const row = body.sequence <= journal.latest() ? journal.append(body.sequence, bytes, kind, stamped)+ : storing(board.id, stamped, bytes.byteLength, () => journal.append(body.sequence, bytes, kind, stamped));+ presence?.commit();return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };}, false, who.engineVersion);}@@ -300,6 +325,14 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin}, false, who.engineVersion);}+ /** The origin and RP id a passkey ceremony must name: this relay's configured public origin. */+ function passkeyOrigin() {+ if (!origin) throw new Refused('RELAY_CONFIG', 'configure the relay public origin before using passkeys');+ return { origin, rpId: new URL(origin).hostname };+ }+ const passkeys = createPasskeyHandler({ auth, origin: passkeyOrigin,+ person: async (req, write) => deviceStore.authorizeSession(await auth.authenticate(credential(req, origin, write))),+ board: (req, id) => authorizedRequest(req, identity(id), true) });const browser = origin ? createRelayBrowserHandler({ authenticate: (req) => auth.authenticate(credential(req, origin)) }) : null;const pagesHandler = createRelayPagesHandler({ directory: root, now, authorize: authorizedRequest, withJournal, sender, quota, annotated, refreshStorage, enabled: Boolean(quota) });const common = createApiHandler({@@ -342,6 +375,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin/** Add authenticated snapshot replacement and deletion to the common versioned read/move paths. */async function handle(req, res) {+ if (await passkeys(req, res)) return;if (await pagesHandler(req, res)) return;if (await deviceHandler(req, res)) return;if (await pairing(req, res)) return;diff --git a/src/api-moves.js b/src/api-moves.jsindex 18bc03e6..bdd0d898 100644--- a/src/api-moves.js+++ b/src/api-moves.js@@ -9,9 +9,11 @@ const MOVES = {'sentinel-decline': { prefix: ['sentinel', 'decline'], positions: ['name'], flags: ['digest', 'reason'] },'spec-answer': { prefix: ['spec', 'answer'], positions: ['row', 'answer'] },'check-accept': { prefix: ['check', 'accept'], item: true },+ 'land-waive': { prefix: ['land'], flags: ['waive', 'until', 'reason'] },+ signing: { prefix: ['settings', 'person.signed'], positions: ['signed'] },add: { positions: ['lane', 'title'], flags: ['criterion', 'specs', 'parent', 'after', 'brief', 'route', 'check'], booleans: ['wait'], booleans: ['wait'] },edit: { item: true, flags: ['criterion', 'brief', 'route', 'check', 'reason'], booleans: ['wait'], booleans: ['wait'] },- fact: { item: true, positions: ['kind', 'text'], flags: ['supersedes', 'ref', 'implies'] },+ fact: { item: true, positions: ['kind', 'text'], flags: ['supersedes', 'ref', 'implies', 'as', 'cause'], booleans: ['never-again'] },claim: { item: true },release: { item: true, flags: ['note'] },submit: { item: true },@@ -22,7 +24,7 @@ const MOVES = {refreeze: { item: true },reopen: { item: true, flags: ['note', 'cause'], lists: ['conflict'] },escalate: { item: true, flags: ['note'] },- hold: { positions: ['lane'], flags: ['reason'], booleans: ['off'] },+ hold: { positions: ['lane'], flags: ['reason', 'as'], booleans: ['off'] },shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },answer: { item: true, positions: ['text'], flags: ['as', 'implies', 'supersedes'] },pass: { item: true, positions: ['note'] },diff --git a/src/board-read-open.js b/src/board-read-open.jsindex 5b1c08c6..14d1fa83 100644--- a/src/board-read-open.js+++ b/src/board-read-open.js@@ -6,6 +6,7 @@ import { boardIsCurrent } from './board-migrate.js';import {BOARD_BUSY_TIMEOUT_MS,EVENT_LOG_VERSION,+ SIGNED_EVENT_LOG_VERSION,SCHEMA_DIGEST,SCHEMA_VERSION,} from './board-schema-source.js';@@ -58,8 +59,8 @@ export function readEventLogVersion(db) {if (!Number.isSafeInteger(version) || version < 0) {throw new Refused('EVENT_LOG_VERSION', `event log version ${stored?.meta_value ?? 'missing'} is invalid; restore a valid board or upgrade pullboard`);}- if (version > EVENT_LOG_VERSION) {- throw new Refused('EVENT_LOG_VERSION', `event log version ${version} is newer than this pullboard version ${EVENT_LOG_VERSION}; upgrade pullboard to open this board`);+ if (version > Math.max(EVENT_LOG_VERSION, SIGNED_EVENT_LOG_VERSION)) {+ throw new Refused('EVENT_LOG_VERSION', `event log version ${version} is newer than this pullboard version ${SIGNED_EVENT_LOG_VERSION}; upgrade pullboard to open this board`);}return version;}diff --git a/src/board-schema-source.js b/src/board-schema-source.jsindex cdeade66..de6628f0 100644--- a/src/board-schema-source.js+++ b/src/board-schema-source.js@@ -3,6 +3,8 @@ import { schemaDigest } from './board-migrate.js';/** Version of the persisted append-only event record format; bump for incompatible format changes. */export const EVENT_LOG_VERSION = 1;+/** Signed-person history requires tools that understand its authority stamps [E22]. */+export const SIGNED_EVENT_LOG_VERSION = 2;/** Maximum time a board connection waits for another process to release SQLite's lock. */export const BOARD_BUSY_TIMEOUT_MS = 10_000;diff --git a/src/board.js b/src/board.jsindex a6ec9aee..297bf7a9 100644--- a/src/board.js+++ b/src/board.js@@ -61,8 +61,14 @@ import {checkedLandingCommit,} from './verdict-reviews.js';export { verdictReviewProblem, verdictsFor, acceptedVerdict, checkedLandingCommit };-export { landingTestDefects, recordLandingTestDefect } from './landing-test-defects.js';-export { landingLeaseMove, landingLeaseState } from './landing-lease.js';+export {+ landingTestDefects,+ recordLandingTestDefect,+} from './landing-test-defects.js';+export {+ landingLeaseMove,+ landingLeaseState,+} from './landing-lease.js';import { guardLandingWrite } from './landing-lease.js';import {randomBytes,@@ -88,7 +94,10 @@ import {recordSchemaStamp,reportDrift,} from './board-migrate.js';-export { schemaMissing, writeRefused } from './board-migrate.js';+export {+ schemaMissing,+ writeRefused,+} from './board-migrate.js';import {briefFiles,briefSections,@@ -192,20 +201,56 @@ import { validateLandingRevision } from './submit-invariants.js';import { submissionProof } from './submit-invariants.js';import { SUBMISSION_PROOF_ENGINE } from './submit-invariants.js';export { landingFlakes, landingWaiverCovers, landingWaiverKind };-export { landingWaivers, landingWaiverFor, waivedLandingProof } from './landing-waivers.js';+export {+ landingWaivers,+ landingWaiverFor,+ waivedLandingProof,+} from './landing-waivers.js';export { acceptCheck } from './check-accept.js';-export { declareJob, recordJobRun } from './recurring-jobs.js';-export { proposeSentinel, decideSentinel, beginSentinelRun, finishSentinelRun } from './sentinels.js';-export { flakeLedger, recordFlakeObservation } from './flakes.js';-export { flakeQuarantines, gateRuns, recordGateRun } from './quarantine.js';-+export {+ declareJob,+ recordJobRun,+} from './recurring-jobs.js';+export {+ proposeSentinel,+ decideSentinel,+ beginSentinelRun,+ finishSentinelRun,+} from './sentinels.js';+export {+ flakeLedger,+ recordFlakeObservation,+} from './flakes.js';+export {+ flakeQuarantines,+ gateRuns,+ recordGateRun,+} from './quarantine.js';+export {+ personProposals,+ personSigning,+ proposePersonMove,+ setPersonSigning,+} from './person-signing.js'; // Signed person moves [E22]./** The seat readers live in seats.js; the board re-exports them so `store.*` callers keep one import. */-export { agentAt, agentById, agentCreator, coordinatorHolder, listAgents, nextSeatId, seatEnrolled, seatLineage, takeCoordinator, withVerifierStanding } from './seats.js';+export {+ agentAt,+ agentById,+ agentCreator,+ coordinatorHolder,+ listAgents,+ nextSeatId,+ seatEnrolled,+ seatLineage,+ takeCoordinator,+ withVerifierStanding,+} from './seats.js';export const ACCEPT_REASON = 'CRITERION_MET';export { PERSON } from './board-query.js';export { EVENT_LOG_VERSION } from './board-schema-source.js';+export { SIGNED_EVENT_LOG_VERSION } from './board-schema-source.js';export { BOARD_BUSY_TIMEOUT_MS } from './board-schema-source.js';@@ -2259,10 +2304,27 @@ export function milestones(board) {}// A lane agent's drafted rows live in row-drafts.js (#878); exported here so the engine dispatches them.-export { draftSpecRow, rowDrafts } from './row-drafts.js';-export { recordSpecApprovalBaseline, specApprovalBaseline, specApprovalBaselineExists } from './spec-approval-baseline.js';+export {+ draftSpecRow,+ rowDrafts,+} from './row-drafts.js';+export {+ recordSpecApprovalBaseline,+ specApprovalBaseline,+ specApprovalBaselineExists,+} from './spec-approval-baseline.js';// The roadmap's moves live in milestones.js; the board keeps exporting them so the engine replays them.-export { addMilestone, canonicalMilestoneTarget, editMilestone, editMilestoneItems, orderMilestoneItems, moveMilestone, removeMilestone, roadmap, shipMilestone } from './milestones.js';+export {+ addMilestone,+ canonicalMilestoneTarget,+ editMilestone,+ editMilestoneItems,+ orderMilestoneItems,+ moveMilestone,+ removeMilestone,+ roadmap,+ shipMilestone,+} from './milestones.js';export { rowDecisions } from './board-query.js';@@ -2343,7 +2405,14 @@ export function peekShouts(board, agentId, limit = 2) {.reverse();}-export { recentShouts, eventsOfKinds, recentEvents, lastMoves, decisionAndEvidenceShouts, submitInvariantEvents } from './board-hot.js';+export {+ recentShouts,+ eventsOfKinds,+ recentEvents,+ lastMoves,+ decisionAndEvidenceShouts,+ submitInvariantEvents,+} from './board-hot.js';export { stats } from './board-stats.js';diff --git a/src/cli-main.js b/src/cli-main.jsindex d9a3edf9..67cb1c66 100644--- a/src/cli-main.js+++ b/src/cli-main.js@@ -176,8 +176,8 @@ async function runCommand(argv, io) {? (await import('./cli-help.js')).selectedHelp(command, first, second, rest, values) : null;if (help) return await (await COMMANDS.help()).run(io, args, help);try {- if (values.as === 'person' && !['answer', 'decisions', 'fact'].includes(command)) {- throw new Refused('USAGE', '--as person works only with pullboard answer, decisions, or fact --never-again');+ if (values.as === 'person' && !['answer', 'decisions', 'fact', 'hold'].includes(command)) {+ throw new Refused('USAGE', '--as person works only with pullboard answer, decisions, hold, or fact --never-again');}const load = COMMANDS[command];if (!load) return (await import('./cli-help.js')).unknownCommand(io, command);@@ -276,7 +276,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' || command === 'relay' && ['on', 'join', 'revoke'].includes(verb) && !remoteRelayOn)) {+ (parsed.values.as === 'person' && command !== 'decisions' && !(await import('./person-signing-cli.js')).signsPersonMoves(io.cwd) || command === 'relay' && ['on', 'join', 'revoke'].includes(verb) && !remoteRelayOn)) {(await import('./person.js')).requirePersonChannel(io.personChannel);io.caller('person');}diff --git a/src/cli.js b/src/cli.jsindex 63006de8..f7ac63f5 100644--- a/src/cli.js+++ b/src/cli.js@@ -109,6 +109,8 @@ import {agentSessionDigest,personCommand,} from './person.js';+import { signedMoveProblem } from './person-signing.js';+import { personAuthority } from './relay-sender.js';import {bindLocalSession,HOOK_CHECKOUT_WAIT_MS,@@ -494,7 +496,7 @@ export function checkMainVerifier(ctx, board, values) {*/export function personMode(ctx, me, values) {if (values.as === undefined) return false;- if (values.as !== 'person') throw new Refused('USAGE', '--as person is supported for answer, decisions and fact --never-again');+ if (values.as !== 'person') throw new Refused('USAGE', '--as person is supported for answer, decisions, hold and fact --never-again');if (!ctx.info.isMain || me.id !== COORDINATOR) {throw new Refused('B26_PERSON_ANSWER', 'only the main checkout can act as the person; ask your coordinator to answer or pass this decision');}@@ -559,6 +561,9 @@ export function relayOutboxSetting(root) {}export async function ordered(ctx, board, operation, args) {+ // With signed person moves on, a person-only move counts only as a passkey-confirmed request [E22].+ const unsigned = signedMoveProblem(board, personAuthority({ operation, args }), ctx.io.personRequest, { strict: true });+ if (unsigned) throw unsigned;const initialBaseline = initialSpecApprovalBaseline(ctx, board, operation);// Only a reject or a reopen can open a builder's first-refusal window (#954), so an accept never reads the coordinator's policy.if (operation === 'reopen' || operation === 'verify' && args[1]?.decision === 'REJECT') args = firstRefusalArgs(operation, args, configFromSource(coordinatorFile(ctx.info.root, CONFIG_FILE).stdout));diff --git a/src/commands/answer.js b/src/commands/answer.jsindex a2bc2abe..59393832 100644--- a/src/commands/answer.js+++ b/src/commands/answer.js@@ -9,6 +9,9 @@ import {import {requirePersonChannel,} from '../person.js';+import {+ requireSignedPerson,+} from '../person-signing-cli.js';import {actOn,agentDisplayName,@@ -22,6 +25,10 @@ export async function run(io, { first, second, rest, values }) {const act = (work) => actOn(io, work);return act(async (ctx, board, me) => {const asPerson = personMode(ctx, me, values);+ // With signed person moves on, the answer goes to the person's passkey as this exact request [E22].+ if (asPerson) { const confirmed = await requireSignedPerson(ctx, board, me, { verb: 'answer', item: idArg(first), args: { as: 'person', text: [second, ...rest].filter(Boolean).join(' '),+ ...(values.implies === undefined ? {} : { implies: String(values.implies) }), ...(values.supersedes === undefined ? {} : { supersedes: String(values.supersedes) }) } });+ if (confirmed !== null) return confirmed; }if (asPerson) requirePersonChannel(ctx.io.personChannel);const implies = parseImplies(values.implies);const supersedes = values.supersedes === undefined ? undefined : idArg(String(values.supersedes).replace(/^#/u, ''));diff --git a/src/commands/fact.js b/src/commands/fact.jsindex a0c8e462..9ad303d3 100644--- a/src/commands/fact.js+++ b/src/commands/fact.js@@ -5,6 +5,9 @@ import {import {requirePersonChannel,} from '../person.js';+import {+ requireSignedPerson,+} from '../person-signing-cli.js';import {Refused,} from '../refused.js';@@ -23,6 +26,13 @@ export async function run(io, { first, second, rest, values }) {const id = idArg(first);const implies = parseImplies(values.implies);const asPerson = values.as === 'person' && personMode(ctx, me, values);+ if (asPerson || values['never-again'] || values.cause !== undefined) {+ const confirmed = await requireSignedPerson(ctx, board, me, { verb: 'fact', item: id, args: { kind: second, text: rest[0], as: 'person',+ ...(values.supersedes === undefined ? {} : { supersedes: String(values.supersedes) }), ...(values.ref === undefined ? {} : { ref: String(values.ref) }),+ ...(values.implies === undefined ? {} : { implies: String(values.implies) }), ...(values.cause === undefined ? {} : { cause: String(values.cause) }),+ ...(values['never-again'] ? { 'never-again': true } : {}) } });+ if (confirmed !== null) return confirmed;+ }if (asPerson) requirePersonChannel(ctx.io.personChannel);const marked = asPerson || values['never-again'] || values.cause !== undefined? { cause: values.cause ?? null, neverAgain: Boolean(values['never-again']), asPerson, channel: ctx.io.personChannel ?? 'terminal' } : {};diff --git a/src/commands/hold.js b/src/commands/hold.jsindex 713d1efe..e403e0e4 100644--- a/src/commands/hold.js+++ b/src/commands/hold.js@@ -1,5 +1,7 @@/** The pullboard hold command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';+import { requireSignedPerson } from '../person-signing-cli.js';+import { requirePersonChannel } from '../person.js';import {isLane,} from '../lanes.js';@@ -10,6 +12,7 @@ import {actOn,idArg,ordered,+ personMode,} from '../cli.js';/** Run `pullboard hold` and return its exit code. */@@ -31,11 +34,18 @@ export async function run(io, { first, second, rest, values }) {return 0;}if (!first || !isLane(ctx.config, first)) throw new Refused('NO_LANE', `no lane "${first ?? ''}"; see: pullboard lanes`);+ const asPerson = io.personChannel === 'view' || values.as === 'person' && personMode(ctx, me, values);+ if (asPerson) {+ const confirmed = await requireSignedPerson(ctx, board, me, { verb: 'hold', args: { lane: first,+ ...(values.off ? { off: true } : { reason: String(values.reason ?? '') }) } });+ if (confirmed !== null) return confirmed;+ requirePersonChannel(io.personChannel);+ }if (values.off) {- await ordered(ctx, board, 'releaseLane', [first, { agentId: me.id, asPerson: io.personChannel === 'view', channel: io.personChannel ?? 'terminal' }]);+ await ordered(ctx, board, 'releaseLane', [first, { agentId: me.id, asPerson, channel: io.personChannel ?? 'terminal' }]);io.say(`released the ${first} lane`);} else {- await ordered(ctx, board, 'holdLane', [first, { agentId: me.id, reason: values.reason ?? '', asPerson: io.personChannel === 'view', channel: io.personChannel ?? 'terminal' }]);+ await ordered(ctx, board, 'holdLane', [first, { agentId: me.id, reason: values.reason ?? '', asPerson, channel: io.personChannel ?? 'terminal' }]);io.say(`holding the ${first} lane: ${values.reason}. Release it with: pullboard hold ${first} --off`);}io.result?.({ lane: first, held: !values.off, reason: values.off ? null : values.reason });diff --git a/src/commands/land.js b/src/commands/land.jsindex 9ec251be..d082b8a1 100644--- a/src/commands/land.js+++ b/src/commands/land.js@@ -14,6 +14,9 @@ import {agentSessionDigest,requirePersonChannel,} from '../person.js';+import {+ requireSignedPerson,+} from '../person-signing-cli.js';import {Refused,} from '../refused.js';@@ -35,6 +38,8 @@ export async function run(io, { first, second, rest, values }) {if (me.id !== COORDINATOR || !ctx.info.isMain) throw new Refused('COORDINATOR_ONLY', 'only the coordinator lands verified batches; ask your coordinator to run pullboard land');if (first || second || rest.length) throw new Refused('USAGE', 'pullboard land [--max N] [--dry-run] [--adopt] | --waive <test> --until <date> --reason "why"');if (values.waive !== undefined) {+ const confirmed = await requireSignedPerson(ctx, board, me, { verb: 'land-waive', args: { waive: String(values.waive), until: String(values.until ?? ''), reason: String(values.reason ?? '') } });+ if (confirmed !== null) return confirmed;requirePersonChannel(io.personChannel);const waiver = await ordered(ctx, board, 'recordLandingWaiver', [{ agentId: store.PERSON, channel: io.personChannel ?? 'terminal',id: randomUUID(), test: values.waive, until: values.until, reason: values.reason }]);diff --git a/src/commands/settings.js b/src/commands/settings.jsindex 9f58e0f5..555aa6f1 100644--- a/src/commands/settings.js+++ b/src/commands/settings.js@@ -2,6 +2,9 @@import {SETTING_FORMS,} from '../help.js';+import {+ signingSetting,+} from '../person-signing-cli.js';import {Refused,} from '../refused.js';@@ -33,6 +36,7 @@ export function settingsCommand(io, { first, second, rest }) {io.say(`this board's landing pool: ${second}`);return 0;}+ if (first === 'person.signed' && !rest.length) return signingSetting(io, second);if (!first && !second && !rest.length) {const settings = loadMachineSettings();const queue = gateQueueSettings();diff --git a/src/commands/spec.js b/src/commands/spec.jsindex 54cac868..bd648e1c 100644--- a/src/commands/spec.js+++ b/src/commands/spec.js@@ -42,6 +42,15 @@ import {import {productProblems,} from '../products.js';+import {+ personSigning,+} from '../person-signing.js';+import {+ refuseNamedSigners,+ requireShownRows,+ requireSignedPerson,+ signsPersonMoves,+} from '../person-signing-cli.js';import {Refused,} from '../refused.js';@@ -189,11 +198,22 @@ export async function specCommand(io, { first, second, rest, values }) {return 0;}if (first === 'approve' || first === 'decline') {- requirePersonChannel(io.personChannel);return withBoard(ctx, async (board) => {const me = whoAmI(ctx, board);- 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');const ids = [second, ...rest].filter(Boolean).flatMap((text) => text.split(/[\s,]+/u)).filter(Boolean);+ // With signed person moves on, the decision goes to the person's passkey; a named SSH signer has no passkey yet [E22].+ const shown = [...spec.rows, ...(practice.rows ?? []).map(row => ({ ...row, id: `doctrine:${row.id}` }))].filter(row => ids.includes(row.id));+ if (personSigning(board).signed) refuseNamedSigners(shown, ids);+ 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 }) } }, shown.map(({ id, text }) => ({ id, text })));+ if (confirmed !== null) return confirmed;+ 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) {+ const decidable = [...spec.rows, ...(practice.rows ?? []).map((row) => ({ ...row, id: `doctrine:${row.id}` }))];+ refuseNamedSigners(decidable, ids);+ requireShownRows(board, io.personRequest, decidable, ids);+ }// An approve keeps a pending answer: plain, it approves the answered text; --text says what it replaces.const kept = first === 'approve' ? pendingAnswers(ctx.info.root, ctx.config, ids, store.rowDecisions(board)) : new Map();const decide = { decision: first, reason: values.reason, by: values.by, on: new Date().toISOString(), commit: headCommit(ctx.info.root) ?? '' };@@ -210,7 +230,35 @@ export async function specCommand(io, { first, second, rest, values }) {return 0;});}+ // Read without creating a board: a repo that has none signs nothing [E22].+ if (first === 'signoff' && signsPersonMoves(ctx.info.root)) {+ return withBoard(ctx, async board => {+ const ids = [second, ...rest].filter(Boolean).flatMap(text => idList(text));+ if (!ids.length) throw new Refused('USAGE', 'pullboard spec signoff <ids>');+ const rows = ids.map(id => spec.rows.find(row => row.id === id));+ if (rows.some(row => !row || row.status !== 'approved')) throw new Refused('CANNOT_SIGN', 'only approved rows in this spec are signed');+ refuseNamedSigners(rows, ids);+ if (values.by) throw new Refused('PERSON_SIGNER_REQUIRED', `the requested SSH signer ${values.by} has no passkey identity`, 'omit --by for a person approval, or wait until signing is off to use that named SSH principal');+ if (values.note !== undefined || values['note-file'] !== undefined) throw new Refused('USAGE', 'signed optional sign-off records the exact row approval, without an SSH sign-off note', 'use spec approve <ids> to confirm those rows with your passkey');+ const proof = specProof(ctx);+ const testFiles = citedTestFiles(ctx.info.root);+ const evidence = ids.map(id => ({ id, ...rowEvidence(ctx.info.root, id, { ...proof, testFiles }) }));+ const missing = evidence.filter(row => !row.files.length && !row.verified.length).map(row => row.id);+ if (missing.length) throw new Refused('NO_EVIDENCE', `${missing.join(', ')} has no evidence; build it or cite its id in a test first`);+ const completed = await requireSignedPerson(ctx, board, whoAmI(ctx, board), { verb: 'spec-approve', args: { ids: ids.join(',') } }, rows.map(({ id, text }) => ({ id, text })));+ if (completed === null) throw new Refused('PERSON_SIGNED', 'confirm optional sign-off as a row approval through its original terminal request', 'run spec approve <ids> with your passkey');+ io.result?.({ count: ids.length, by: 'person', ids, evidence });+ return completed;+ });+ }if (first === 'answer') {+ const completed = await withBoard(ctx, async board => {+ const row = spec.rows.find(entry => entry.id === second);+ if (!row) throw new Refused('NO_ROW', `${second} is not a row in ${ctx.config.spec}`);+ if (personSigning(board).signed) refuseNamedSigners([row], [second]);+ return requireSignedPerson(ctx, board, whoAmI(ctx, board), { verb: 'spec-answer', args: { row: second, answer: rest.join(' ').trim() } }, [{ id: row.id, text: row.text }]);+ });+ if (completed !== null) return completed;requirePersonChannel(io.personChannel, process.env, { command: personCommand(primaryCheckoutRoot(ctx.info) ?? ctx.info.root, ['spec', 'answer', second, rest.join(' ')]) });return withBoard(ctx, async (board) => {const me = whoAmI(ctx, board);@@ -220,6 +268,7 @@ export async function specCommand(io, { first, second, rest, values }) {const row = spec.rows.find((entry) => entry.id === second);if (!row) throw new Refused('NO_ROW', `${second} is not a row in ${ctx.config.spec}`, 'list the pending questions with pullboard spec --json, then answer one of them');if (row.status !== 'pending') throw new Refused('SPEC_ANSWER', `${second} is ${row.status}, not a pending question`, `read it with pullboard spec show ${second}; only a pending row takes an answer`);+ if (personSigning(board).signed) requireShownRows(board, io.personRequest, [row], [second]);const { text } = answerQuestion(row.text, given, second);const records = prepareRowDecisions(ctx.info.root, ctx.config, { ids: [second], decision: 'approve', text, on: new Date().toISOString(), commit: headCommit(ctx.info.root) ?? '' });const decisions = await ordered(ctx, board, 'recordRowDecisions', [{ agentId: store.PERSON, channel: io.personChannel ?? 'terminal', decisions: records }]);diff --git a/src/commands/status.js b/src/commands/status.jsindex 9e5bb7e9..cf38321a 100644--- a/src/commands/status.js+++ b/src/commands/status.js@@ -17,6 +17,9 @@ import { originRepository } from '../github-origin.js';import {loadSpec,} from '../spec.js';+import {+ signingLine,+} from '../person-signing-words.js';import {submitInvariantLine,submitInvariantProposals,@@ -33,12 +36,14 @@ export async function run(io, { values }) {const relay = hasRelayState ? await import('../relay.js') : null;const environment = hasRelayState && process.env.PULLBOARD_RELAY_TOKEN !== undefined? await import('../relay-environment.js') : null;- const summary = await withBoardRead(ctx, (board, readers) => {+ const summary = await withBoardRead(ctx, async (board, readers) => {const me = identifyCaller(ctx, board, { environmentAgent: environment?.environmentAgent ?? (() => null),relayLinked: relay?.relayLinked ?? (() => false) }, readers);const mine = store.itemsInStatus(board, 'claimed', me.id);const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config });- return { me, mine, ruleCounts: ruleProofCounts(ctx.info.root, board, approvalState.spec), needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relay ? relay.relayStatus(ctx.info.root) : unlinkedRelayStatus(),+ const person = board.db.prepare("SELECT 1 FROM event WHERE event_kind='person_signing' LIMIT 1").get()+ ? { signed: (await import('../person-signing.js')).personSigning(board).signed } : { signed: false };+ return { me, mine, person, ruleCounts: ruleProofCounts(ctx.info.root, board, approvalState.spec), needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relay ? relay.relayStatus(ctx.info.root) : unlinkedRelayStatus(),submitInvariantProposals: submitInvariantProposals(store.submitInvariantEvents(board, ctx.config), ctx.config) };});if (values.json) {@@ -53,6 +58,7 @@ export async function run(io, { values }) {if (summary.specApprovalBaseline?.pending) io.say('approval baseline pending: the next coordinator or person command in the main checkout records the existing approved rows; lane work may continue and none are flagged until then');if (summary.specApprovalBaseline?.invalid) io.say('approval baseline unreadable: existing rows need approval evidence; restore a known-good board export to recover the original baseline');io.say(reviewQueueLine(ctx, summary.reviewQueue, span));+ io.say(signingLine(summary.person));for (const proposal of summary.submitInvariantProposals) io.say(submitInvariantLine(proposal));for (const need of summary.needs.filter(need => need.kind === 'agent-approved')) io.say(`${need.text}; ${need.what}`);if (!summary.relay.linked && !originRepository(ctx.info.root, { optional: true })) {diff --git a/src/engine.js b/src/engine.jsindex 85a0c830..576866a0 100644--- a/src/engine.js+++ b/src/engine.js@@ -50,6 +50,7 @@ import {requestPerson,} from './relay-requests.js';import {+ personAuthority,relayMoveActor,relaySenderProblem,validRelaySender,@@ -71,6 +72,8 @@ import { LANDING_ENVIRONMENT_ENGINE } from './landing-environment-engine.js';import { carriesLandingEnvironment } from './execution-environment.js';import { LANDING_LEASE_ENGINE } from './landing-lease-engine.js';import { LANDING_LOCAL_LEASE_ENGINE } from './landing-local-lease-engine.js';+import { PERSON_SIGNING_ENGINE } from './person-signing-engine.js';+import { signedMoveProblem } from './person-signing.js';const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);@@ -83,12 +86,13 @@ export const ENGINE_OPERATIONS = Object.freeze(['recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact', 'recordSpecApprovalBaseline','recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'recordLandingTestDefect', 'finishLandingBatch', 'acceptCheck','recordHealthFindings', 'proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun',- 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove',+ 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove', 'setPersonSigning', 'proposePersonMove',]);/** Engine version at which each ordered operation first has stable replay semantics. */const OPERATION_ENGINE = Object.freeze({ draftSpecRow: ROW_DRAFT_ENGINE, orderMilestoneItems: MILESTONE_RANK_ENGINE, reopen: 8, recordLandingBatch: 8, recordLandingWaiver: 8, recordLandingFlake: 8, finishLandingBatch: 8, acceptCheck: CHECK_ACCEPT_ENGINE,- shipMilestone: MILESTONE_SHIP_ENGINE, recordSpecApprovalBaseline: SPEC_APPROVAL_ENGINE, takeCoordinator: COORDINATOR_HOLD_ENGINE });+ shipMilestone: MILESTONE_SHIP_ENGINE, recordSpecApprovalBaseline: SPEC_APPROVAL_ENGINE, takeCoordinator: COORDINATOR_HOLD_ENGINE,+ setPersonSigning: PERSON_SIGNING_ENGINE, proposePersonMove: PERSON_SIGNING_ENGINE });/** Dependency edits, causes, sealed reviews, submission proofs, trunk conflicts, health observations and milestone targets retain distinct recorded engine meanings. */function minimumOperationEngine(operation, args, board, at) {@@ -331,7 +335,9 @@ function registrationProblem(board, move, { sender, registration, sequence, digeexport function applyRelayMove(board, move, { sequence, at, sender, kind, digest = null, registration }) {requireSupportedEngine(move);const phoneReceipt = sender?.kind === 'machine' && move?.engine >= 6 && Boolean(move.personRequest) && !requestMoveProblem(board, move, { checkExecutorLease: false });- const problem = relaySenderProblem(move, sender, kind, { phoneReceipt }) ?? (kind === 'move' ? registrationProblem(board, move, { sender, registration, sequence, digest }) : null);+ const problem = relaySenderProblem(move, sender, kind, { phoneReceipt }) ?? (kind === 'move' ? registrationProblem(board, move, { sender, registration, sequence, digest }) : null)+ // With signing on, a person-only move counts only when it carries out a passkey-confirmed request [E22].+ ?? (kind === 'move' ? signedMoveProblem(board, personAuthority(move), phoneReceipt ? move.personRequest : null) : null);if (!problem) {// Engine-48 relay moves run under linked verifier standing; older recorded moves replay as they did.// The person is above every seat; their own moves act with the coordinator's standing.diff --git a/src/exchange.js b/src/exchange.jsindex 99742957..12054dbb 100644--- a/src/exchange.js+++ b/src/exchange.js@@ -13,8 +13,13 @@ import {} from './machine.js';import {EVENT_LOG_VERSION,+ SIGNED_EVENT_LOG_VERSION,specApprovalBaseline,} from './board.js';+import {+ exportedMeta,+ guardRestore,+} from './person-signing.js';const VERSION = 1;@@ -67,6 +72,8 @@ export function exportBoard(board) {nativeRows(db, table),]));db.exec('COMMIT');+ // The pinned relay key stays with this board file; an export never carries it to another [E22].+ tables.board_meta = exportedMeta(tables.board_meta ?? []);return { version: VERSION, tables };} catch (error) {db.exec('ROLLBACK');@@ -127,8 +134,8 @@ function validateDocument(db, document, names) {if (!Number.isSafeInteger(eventLogVersion) || eventLogVersion < 0) {throw new Refused('EVENT_LOG_VERSION', `event log version ${eventLog?.meta_value ?? 'missing'} in this export is invalid; export it again or upgrade pullboard`);}- if (eventLogVersion > EVENT_LOG_VERSION) {- throw new Refused('EVENT_LOG_VERSION', `event log version ${eventLogVersion} in this export is newer than this pullboard version ${EVENT_LOG_VERSION}; upgrade pullboard to read it`);+ if (eventLogVersion > Math.max(EVENT_LOG_VERSION, SIGNED_EVENT_LOG_VERSION)) {+ throw new Refused('EVENT_LOG_VERSION', `event log version ${eventLogVersion} in this export is newer than this pullboard version ${SIGNED_EVENT_LOG_VERSION}; upgrade pullboard to read it`);}}@@ -230,6 +237,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigesttable,nativeRows(db, table),])) };+ current.tables.board_meta = exportedMeta(current.tables.board_meta);const actual = semanticBoardDigest(current);if (actual !== expectedNativeDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed before checkpoint restore; its changes were preserved, export them and retry recovery');localAgentCursors = new Map(current.tables.agent.map((row) => [row.agent_id, row.agent_last_shout_id]));@@ -240,6 +248,8 @@ function restoreDocument(board, document, replace = false, expectedNativeDigestif (occupied.length && !initCoordinator && !replace) {throw new Refused('IMPORT_NOT_EMPTY', `board tables already have rows (${occupied.join(', ')}); import into a repo with an empty board`);}+ // Signed person moves survive a restore: this board keeps its own relay key pin and its signing state [E22].+ const signing = guardRestore(db, document);const triggers = db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'machine_%'").all();for (const { name } of triggers) db.exec(`DROP TRIGGER ${identifier(name)}`);if (replace) {@@ -265,6 +275,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigest}db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?) ON CONFLICT(meta_key) DO UPDATE SET meta_value = excluded.meta_value').run('event_log_version', String(EVENT_LOG_VERSION));+ signing();const setSequence = db.prepare('UPDATE sqlite_sequence SET seq = ? WHERE name = ?');for (const row of document.tables.sqlite_sequence ?? []) {if (!setSequence.run(row.seq, row.name).changes) db.prepare('INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)').run(row.name, row.seq);diff --git a/src/help.js b/src/help.jsindex 5b099785..66174eda 100644--- a/src/help.js+++ b/src/help.js@@ -31,6 +31,7 @@ Set uprelease priority is opt-in: gate.queue.currentReleaseFirst (default false), within each board's otherwise-tied positionsmemory hold is opt-in: gate.memoryFloorMB in ~/.pullboard/settings.json holds the queue under that many MB free or critical pressure (default off)short slots for runs that name their test files are opt-in: pullboard settings gate.shortSlots <n> (default 0)+ signed person moves are opt-in: pullboard settings person.signed on makes each wait for your passkey; only the passkey turns it offpullboard runner add <ssh-host> --slots <n> --browser <n> [--node <remote-path>] [--root <remote-path>]register SSH test capacity; no runner sign-in; root defaults to ~/.pullboard-runnerpullboard runner list each runner's registered slots and browsers, which it runs atdiff --git a/src/next-step-words.js b/src/next-step-words.jsindex cb930781..cc415d2a 100644--- a/src/next-step-words.js+++ b/src/next-step-words.js@@ -56,6 +56,17 @@ export function personRequestGuidance(message, { caller, leading = false } = {})/** @type {Readonly<Record<string, string>>} */export const NEXT_STEPS = Object.freeze({+ PASSKEY_ASSERTION: 'confirm the move again on your passkey from the relay view',+ PASSKEY_PRESENCE: 'confirm the move again with Face ID, Touch ID or a key touch',+ PASSKEY_REGISTRATION: 'add the passkey again from the relay view on this phone or browser',+ PASSKEY_REQUIRED: 'add a passkey in the relay view on your phone or browser, then confirm the move',+ PERSON_AUTHORITY: 'upgrade the relay so it publishes its passkey stamp key, then retry',+ PERSON_AUTHORITY_CHANGED: 'check which relay this board belongs to; link it to the relay it pinned',+ PERSON_PROPOSAL: 'start the person move from a terminal seat, then confirm it with your passkey',+ PERSON_SIGNED: 'confirm it with your passkey in the relay view; pair a phone or browser first with pullboard relay on --all',+ PERSON_SIGNER_REQUIRED: 'decide the other rows with your passkey; a row that names SSH signers waits until signing is off',+ PERSON_SIGNING_CORRUPT: 'restore the board from a known-good export',+ PERSON_SIGNING_ERASED: 'restore a known-good board that keeps its signing history',ACCOUNT_STORAGE_LIMIT: 'remove an unneeded relay copy through the approved phone flow, or ask the relay operator to increase the account quota; uploads resume when space is available',BAD_PAGE: 'retry the saved upload with a current linked CLI; send only its original bounded encrypted objects',BAD_PAGE_PATH: 'refresh the board on the phone, then follow the encrypted references from its new read pin',diff --git a/src/person-confirmation.js b/src/person-confirmation.jsnew file mode 100644index 00000000..c853f300--- /dev/null+++ b/src/person-confirmation.js@@ -0,0 +1,59 @@+/** Wait for one passkey-confirmed terminal request to finish through the ordinary native executor [E22,H16]. */+import { setTimeout as delay } from 'node:timers/promises';+import { syncRelay } from './relay.js';+import { executePersonRequests } from './relay-request-execution.js';+import { personRequestRecords } from './relay-requests.js';+import { Refused } from './refused.js';+import { loadMachineSettings } from './settings.js';++/** Preserve the ordinary command's required JSON fields while adding its confirmed request receipt. */+function confirmedResult(record) {+ switch (record.move.verb) {+ case 'answer': return { id: record.result, answers: record.move.item };+ case 'spec-approve':+ case 'spec-decline':+ case 'spec-answer': return { decisions: record.result };+ case 'fact': return { item: record.move.item, fact: record.result };+ case 'hold': return { lane: record.move.args.lane, held: !record.move.args.off, reason: record.move.args.off ? null : record.move.args.reason };+ case 'sentinel-approve':+ case 'sentinel-decline': return { sentinel: record.result };+ case 'land-waive': return { batch: null, landed: [], conflicts: [], blocked: [], culprits: [], flakes: [], waiver: record.result };+ case 'signing': return { settings: loadMachineSettings(), person: { signed: record.result.signed } };+ default: throw new Refused('PERSON_PROPOSAL', 'this terminal cannot render the confirmed request result', 'read its original receipt in the relay view before retrying');+ }+}++/**+ * Keep the initiating terminal alive until its exact signed request executes or refuses.+ * Native executor elects/records the existing executor and checks the signed intent; this creates no authority.+ * The caller returns immediately after this resolves: it must never run the original unsigned action again.+ * 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`);+ // 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;+ for (;;) {+ await syncRelay(ctx.info.root, ctx.io);+ await executePersonRequests(ctx.info.root, ctx.io, main);+ const record = personRequestRecords(board).find(entry => entry.id === request.id && !entry.duplicateOf);+ if (record?.status === 'refused') {+ throw new Refused(record.error.code, record.error.message, record.error.next);+ }+ // Repo-changing spec decisions finish the native CLI stage by creating a coordinator request.+ // This reports that stage, never promises its eventual merge/landing outcome.+ if (record?.status === 'done' || record?.coordinatorRequest && Object.hasOwn(record, 'result')) {+ const result = { ...confirmedResult(record), request: request.id, status: record.status,+ ...(record.coordinatorRequest ? { coordinatorRequest: record.coordinatorRequest } : {}) };+ ctx.io.result?.(result);+ ctx.io.say(`passkey-confirmed request ${request.id} ${record.coordinatorRequest ? 'sent to the coordinator' : 'completed'}`);+ return 0;+ }+ if (Date.now() >= until) {+ throw new Refused('PERSON_SIGNED', `request ${request.id} is still waiting for passkey confirmation`,+ `confirm the existing request at ${where}; inspect its receipt before sending the action again`);+ }+ await delay(Math.min(250, Math.max(1, until - Date.now())));+ }+}diff --git a/src/person-presence.js b/src/person-presence.jsnew file mode 100644index 00000000..7118863a--- /dev/null+++ b/src/person-presence.js@@ -0,0 +1,25 @@+/** The relay's signed passkey stamp on a person request, shared by the relay that signs it and the boards that check it [E22,H16]. */+import {+ createPublicKey,+ verify,+} from 'node:crypto';++/** The exact bytes the relay signs when it stamps a passkey-confirmed request; every board verifies the same bytes. */+export function presenceAttestation({ board, request, digest, credential, at }) {+ return Buffer.from(JSON.stringify(['pullboard-person-presence', 1, board, request, digest, credential, at]));+}++/**+ * Whether a stamp carries the relay's Ed25519 signature under the pinned public key (base64url DER SPKI).+ * Why a signature and not the stamp alone: board files are the user's to edit, so only a key no local process holds+ * tells a stamp the relay made from one written into the board by hand.+ *+ * @param {{ board: string, request: string, digest: string, credential: string, at: number, signature: string }} stamp+ * @param {string} publicKey+ */+export function presenceSigned(stamp, publicKey) {+ try {+ const key = createPublicKey({ key: Buffer.from(publicKey, 'base64url'), format: 'der', type: 'spki' });+ return key.asymmetricKeyType === 'ed25519' && verify(null, presenceAttestation(stamp), key, Buffer.from(stamp.signature, 'base64url'));+ } catch { return false; } // An unreadable key or signature verifies nothing; the caller fails closed.+}diff --git a/src/person-request.js b/src/person-request.jsindex 6cfa4695..2039f86f 100644--- a/src/person-request.js+++ b/src/person-request.js@@ -3,40 +3,56 @@ import { moveArgs } from './api-moves.js';import { Refused } from './refused.js';export const PERSON_REQUEST_VERSION = 1;-const VERBS = Object.freeze(['add', 'shout', 'answer', 'hold', 'spec-approve', 'spec-decline', 'sentinel-approve', 'sentinel-decline']);+const VERBS = Object.freeze(['add', 'shout', 'answer', 'hold', 'spec-approve', 'spec-decline', 'sentinel-approve', 'sentinel-decline', 'land-waive', 'signing', 'fact', 'spec-answer']);/** Validate a narrow person intent while retaining literal arguments for the actual CLI parser. */export function personRequestMove(body) {if (!body || typeof body !== 'object' || Array.isArray(body)|| Object.keys(body).some(key => !['verb', 'item', 'args'].includes(key))|| !VERBS.includes(body.verb)) {- throw new Refused('BAD_REQUEST', 'a person request takes add, shout, answer, hold, spec-approve, spec-decline, sentinel-approve or sentinel-decline with item and args; use the view controls');+ throw new Refused('BAD_REQUEST', 'a person request takes add, shout, answer, hold, spec-approve, spec-decline, sentinel-approve, sentinel-decline, land-waive signing, fact or spec-answer with item and args; use the view controls');}const move = structuredClone(body);move.args ??= {};if (typeof move.args !== 'object' || Array.isArray(move.args)) throw new Refused('BAD_REQUEST', 'args needs the move arguments as a JSON object; use the view controls');- if (move.verb === 'answer') {+ if (['answer', 'fact'].includes(move.verb)) {if (move.args.as !== undefined && move.args.as !== 'person') throw new Refused('B26_PERSON_ANSWER', 'the relay person answers as person; use the view to answer the decision');move.args.as = 'person';}+ // A passkey turns signing on or off; nothing else rides on this verb [E22].+ if (move.verb === 'signing' && !['on', 'off'].includes(move.args.signed)) throw new Refused('BAD_REQUEST', 'signing takes args.signed "on" or "off"; use the view controls');moveArgs(move);return move;}-/** Create the distinct versioned request document before the browser seals it for request-kind AAD. */-export function preparePersonRequest(body, id = crypto.randomUUID()) {- const document = { version: PERSON_REQUEST_VERSION, type: 'person-request', id, move: personRequestMove(body) };+/**+ * Create the distinct versioned request document before the browser seals it for request-kind AAD. A row decision on+ * a board that signs person moves also carries `rows`, the exact text of each row as the person saw it [E22].+ */+export function preparePersonRequest(body, id = crypto.randomUUID(), rows) {+ const document = { version: PERSON_REQUEST_VERSION, type: 'person-request', id, move: personRequestMove(body), ...(rows ? { rows } : {}) };return validatePersonRequest(document);}+/** Keep shown rows to bounded `{id, text}` pairs, one per decided row. */+function shownRows(rows) {+ if (!Array.isArray(rows) || !rows.length || rows.length > 200 || rows.some((row) => !row || typeof row !== 'object' || Object.keys(row).sort().join() !== 'id,text'+ || typeof row.id !== 'string' || !/^(?:doctrine:)?[A-Za-z][A-Za-z0-9._-]{0,79}$/u.test(row.id) || typeof row.text !== 'string' || row.text.length > 8000)) {+ throw new Refused('BAD_REQUEST', 'a signed row decision names each row it shows with its id and exact text; reload the paired view and retry');+ }+ return rows.map(({ id, text }) => ({ id, text }));+}+/** Refuse malformed or newer request formats before any CLI can interpret their intent. */export function validatePersonRequest(document) {if (document?.version !== PERSON_REQUEST_VERSION || document?.type !== 'person-request') {throw new Refused('PERSON_REQUEST_VERSION', 'this person request format is unsupported; upgrade Pullboard on the browser and linked machine');}if (typeof document.id !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(document.id)- || Object.keys(document).some(key => !['version', 'type', 'id', 'move'].includes(key))) {+ || Object.keys(document).some(key => !['version', 'type', 'id', 'move', 'rows'].includes(key))) {throw new Refused('BAD_REQUEST', 'a sealed person request needs its stable id and literal move; reload the paired view and retry');}- return { version: PERSON_REQUEST_VERSION, type: 'person-request', id: document.id, move: personRequestMove(document.move) };+ const move = personRequestMove(document.move);+ if (document.rows !== undefined && !['spec-approve', 'spec-decline', 'spec-answer'].includes(move.verb)) throw new Refused('BAD_REQUEST', 'only a row decision carries the rows it shows');+ return { version: PERSON_REQUEST_VERSION, type: 'person-request', id: document.id, move, ...(document.rows === undefined ? {} : { rows: shownRows(document.rows) }) };}diff --git a/src/person-signing-cli.js b/src/person-signing-cli.jsnew file mode 100644index 00000000..eaba27d0--- /dev/null+++ b/src/person-signing-cli.js@@ -0,0 +1,190 @@+/**+ * The terminal side of signed person moves [E22,B26,H16]: the passkey step a person-only command takes, the+ * `pullboard settings person.signed` switch, and pinning the relay's stamp key from this board's own relay origin.+ */+import * as store from './board.js';+import {+ localAuthority,+ passkeyConfirmed,+ personSigning,+ pinAuthority,+ signedMoveProblem,+ signedRefusal,+} from './person-signing.js';+import { personAuthority } from './relay-sender.js';+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 { loadMachineSettings } from './settings.js';+import { repoInfo } from './git.js';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import {+ actOn,+ ordered,+} from './cli.js';++const AUTHORITY_PATH = '/.well-known/pullboard-person-authority';++/**+ * 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.+ *+ * @param {string} root+ * @param {any} board+ * @param {{ err?: (line: string) => void }} [io]+ */+export async function pinRelayAuthority(root, board, io = {}) {+ if (localAuthority(board)) return localAuthority(board);+ const relay = relayStatus(root);+ if (!relay.linked || !relay.url) return null;+ const origin = new URL(relay.url).origin;+ let document;+ try {+ const response = await fetch(new URL(AUTHORITY_PATH, origin), { redirect: 'error', signal: AbortSignal.timeout(10_000) });+ 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);+}++/**+ * The step a person-only command takes while signing is on. A command carrying out a passkey-confirmed request goes+ * ahead. Unpaired commands refuse at once with the pairing step. A linked command sends its exact supported move+ * to the passkey device and waits for one confirmation, reporting where; its caller then returns without a duplicate move.+ *+ * @returns {Promise<number | null>} Completed terminal exit code, or null when the original command may proceed.+ * @param {any} ctx+ * @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+ */+export async function requireSignedPerson(ctx, board, me, intent, rows) {+ 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;+ 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);+ try {+ await ordered(ctx, board, 'proposePersonMove', [{ agentId: me.id, request }]);+ sent = 'proposed';+ } catch (error) {+ if (!(error instanceof Refused)) throw error;+ sent = `; the request did not reach the relay (${error.code}), so start it there`;+ }+ if (sent === 'proposed') return awaitPersonConfirmation(ctx, board, request, where);+ }+ throw signedRefusal(`confirm it on your passkey${sent}`,+ `confirm it with your passkey at ${where} (Face ID, Touch ID or a key touch); keep the initiating terminal open while confirming. No passkey there yet? Add one on that page, or pair a new device with pullboard relay on --all`);+}++/**+ * Refuse, before ordering it, a person-only move that no passkey confirmed while the board signs person moves. Every+ * command's move passes here, so a person move a command does not ask about itself is still refused.+ *+ * @param {any} board+ * @param {string} operation+ * @param {any[]} args+ * @param {any} personRequest - the request the command carries out, if any+ */+export function refuseUnsignedMove(board, operation, args, personRequest) {+ const unsigned = signedMoveProblem(board, personAuthority({ operation, args }), personRequest, { strict: true });+ if (unsigned) throw unsigned;+}++/**+ * Whether the board of the checkout at `cwd` signs person moves, read without opening it for writing. Why the CLI+ * asks before parsing a person command: with signing on, a person move from any shell, SSH included, takes the+ * passkey step, so the shell-marker check that would otherwise stop it first gives way to that step.+ *+ * @param {string} cwd+ * @returns {boolean}+ */+export function signsPersonMoves(cwd) {+ let file;+ try { file = join(repoInfo(cwd).commonDir, 'pullboard', 'board.sqlite'); }+ catch { return false; } // Outside a repository there is no board to sign for; the usual checks apply.+ if (!existsSync(file)) return false;+ let db;+ try { db = store.openBoardReadOnly(file); return personSigning({ db }).signed; }+ catch { return false; } // An unreadable board keeps the stricter shell checks; the command then reports why it cannot open.+ finally { db?.close(); }+}++export { signingLine } from './person-signing-words.js';+import { signingLine } from './person-signing-words.js';++/**+ * `pullboard settings person.signed on|off`. Anyone may turn signing on; off is a person move, so with signing on it+ * takes the passkey step like every other.+ */+export function signingSetting(io, value) {+ if (!['on', 'off'].includes(value)) throw new Refused('USAGE', 'pullboard settings person.signed on|off');+ return actOn(io, async (ctx, board, me) => {+ const signed = value === 'on';+ if (personSigning(board).signed === signed) {+ io.result?.({ settings: loadMachineSettings(), person: { signed } });+ io.say(`person moves are already ${signed ? '' : 'not '}signed`);+ return 0;+ }+ if (!signed) {+ 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);+ 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 } });+ io.say(signingLine({ signed }));+ return 0;+ });+}++/**+ * Refuse a signed row decision on a row that names required SSH signers. Why by name: a passkey stands in for an+ * optional SSH sign-off, but a row that names its signers asked for those people's keys, and no passkey identity can+ * say which person it is yet.+ *+ * @param {{ id: string, signers?: string[] }[]} rows - the spec rows, and doctrine rows as `doctrine:<id>`+ * @param {string[]} ids - the rows being decided+ */+export function refuseNamedSigners(rows, ids) {+ const named = ids.map((id) => rows.find((row) => row.id === id)).filter((row) => row?.signers?.length);+ if (!named.length) return;+ throw new Refused('PERSON_SIGNER_REQUIRED', `${named.map((row) => `${row.id} names its SSH signers ${row.signers.join(', ')}`).join('; ')}, and a passkey cannot sign as a named signer yet`,+ 'decide the other rows with your passkey; a row that names SSH signers waits until passkeys carry a signer identity, or until signing is off');+}++/**+ * Refuse a signed row decision unless the passkey-confirmed request names every decided row with the exact text the+ * person saw, and that text is still the row's. Why: the passkey confirms what was on the screen, so a row edited+ * after it was shown needs to be shown and decided again.+ *+ * @param {any} board+ * @param {any} personRequest - the request this command carries out+ * @param {{ id: string, text: string }[]} rows - the spec rows, and doctrine rows as `doctrine:<id>`+ * @param {string[]} ids - the rows being decided+ */+export function requireShownRows(board, personRequest, rows, ids) {+ const record = personRequestRecords(board).find((entry) => entry.id === personRequest?.id && !entry.duplicateOf);+ const shown = record ? JSON.parse(record.encoded).rows : undefined;+ const changed = ids.filter((id) => !Array.isArray(shown) || shown.find((row) => row.id === id)?.text !== rows.find((row) => row.id === id)?.text);+ if (changed.length) {+ throw new Refused('STALE_ROW_DECISION', `${changed.join(', ')} changed after the person saw ${changed.length === 1 ? 'it' : 'them'}, or the passkey request did not show ${changed.length === 1 ? 'it' : 'them'}`,+ 'read the rows again in the relay view and decide them again with your passkey');+ }+}diff --git a/src/person-signing-engine.js b/src/person-signing-engine.jsnew file mode 100644index 00000000..4d925079--- /dev/null+++ b/src/person-signing-engine.js@@ -0,0 +1,3 @@+/** First engine with signed person moves; numbered by landing (#408) [E22,B26,H16]. */+import { unassignedEngine } from './engine-next.js';+export const PERSON_SIGNING_ENGINE = unassignedEngine();diff --git a/src/person-signing-words.js b/src/person-signing-words.jsnew file mode 100644index 00000000..2e8b8860--- /dev/null+++ b/src/person-signing-words.js@@ -0,0 +1,7 @@+/** One status line about signing: whether person moves are signed, and where they are confirmed. */+export function signingLine(signing) {+ return signing.signed+ ? 'person moves are signed: each one waits for your passkey on the relay'+ : 'person moves are not signed; pullboard settings person.signed on makes each one wait for your passkey';+}+diff --git a/src/person-signing.js b/src/person-signing.jsnew file mode 100644index 00000000..21712062--- /dev/null+++ b/src/person-signing.js@@ -0,0 +1,268 @@+/**+ * Signed person moves [E22,B26,H16]. A board can require that every person-only move (answering a person decision,+ * deciding a spec or doctrine row, waiving a test, turning signing off) is confirmed on a passkey the person+ * registered on the relay with user presence. Why a passkey and not a key on disk: any key the user's shell can use,+ * an agent in that shell can use too, while an authenticator signs only with a person present.+ *+ * The policy is read from the board's append-only event log, never from a row an edit can change, and turning it+ * off counts only with the relay's signed passkey stamp, checked against the relay key this board pinned itself.+ */+import {+ atomic,+ logEvent,+ PERSON,+ SIGNED_EVENT_LOG_VERSION,+} from './board.js';+import { createHash } from 'node:crypto';+import { Refused } from './refused.js';+import { validatePersonRequest } from './person-request.js';+import {+ personRequestRecords,+ requestIntentDigest,+} from './relay-requests.js';+import { validPresence } from './relay-sender.js';+import { presenceSigned } from './person-presence.js';++const PROPOSALS = 'person_proposals';+const AUTHORITY = 'person_authority_local';+const PROPOSAL_MS = 10 * 60_000;+const KEPT_PROPOSALS = 50;++/** Triggers that keep the pinned relay key from being changed, removed or replaced through SQLite. */+const AUTHORITY_TRIGGERS = [+ ['person_authority_update', `BEFORE UPDATE ON board_meta WHEN OLD.meta_key = '${AUTHORITY}'`],+ ['person_authority_delete', `BEFORE DELETE ON board_meta WHEN OLD.meta_key = '${AUTHORITY}'`],+ ['person_authority_replace', `BEFORE INSERT ON board_meta WHEN NEW.meta_key = '${AUTHORITY}' AND EXISTS (SELECT 1 FROM board_meta WHERE meta_key = '${AUTHORITY}')`],+].map(([name, on]) => ({ name, sql: `CREATE TRIGGER IF NOT EXISTS ${name} ${on}\nBEGIN SELECT RAISE(ABORT, 'PERSON_AUTHORITY: the pinned relay key is kept for good'); END` }));++/** Write one board metadata value inside the caller's transaction. */+function meta(board, key, value) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value').run(key, value);+}++/** Read one JSON board metadata value, or a fallback when it was never written. */+function read(board, key, fallback) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key);+ if (!row) return fallback;+ try { return JSON.parse(row.meta_value); }+ catch { throw new Refused('PERSON_SIGNING_CORRUPT', `the board's ${key} record is unreadable; restore the board from a known-good export`); }+}++/** This board's id, which every passkey stamp names. */+function boardId(board) {+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('board_id')?.meta_value ?? null;+}++/**+ * The relay key this board pinned from its own configured relay origin, or null before it first reached one.+ *+ * @param {any} board+ * @returns {{ origin: string, publicKey: string } | null}+ */+export function localAuthority(board) {+ return read(board, AUTHORITY, null);+}++/**+ * 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.+ *+ * @param {any} board+ * @param {string} origin - the relay origin this board is linked to+ * @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`);+ }+ return atomic(board, () => {+ const existing = localAuthority(board);+ if (existing) {+ if (existing.origin === origin && existing.publicKey === authority.publicKey) return existing;+ throw new Refused('PERSON_AUTHORITY_CHANGED', `this board pinned the relay key of ${existing.origin}, and ${origin} now presents another; check which relay this board belongs to before linking it there`);+ }+ const pinned = { origin, publicKey: authority.publicKey };+ meta(board, AUTHORITY, JSON.stringify(pinned));+ for (const { sql } of AUTHORITY_TRIGGERS) board.db.exec(sql);+ return pinned;+ });+}++/**+ * Whether a passkey stamp is genuine: syntactically whole and, when `strict`, signed for this board under the pinned+ * relay key. Without a pin a strict check fails closed.+ */+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);+}++/**+ * Whether person moves on this board must be confirmed on a passkey: the latest `person_signing` event that counts.+ * Anyone may turn signing on; an off counts only from the person with a passkey stamp, which `strict` also checks+ * against the pinned relay key. Commands use the strict reading, so an off written into the event log by hand+ * leaves signing on; replay uses the replicated reading, so every replica reaches the same state.+ *+ * @param {any} board+ * @param {{ strict?: boolean }} [options]+ * @returns {{ signed: boolean, by?: string, at?: string }}+ */+export function personSigning(board, { strict = true } = {}) {+ let state = { signed: false };+ for (const row of board.db.prepare("SELECT event_by, event_at, event_detail FROM event WHERE event_kind = 'person_signing' ORDER BY event_id").all()) {+ let detail;+ try { detail = JSON.parse(row.event_detail); }+ catch { continue; } // An unreadable record turns nothing off; an on before it still holds.+ if (detail?.signed === true) state = { signed: true, by: row.event_by, at: row.event_at };+ else if (detail?.signed === false && row.event_by === PERSON && offIntent(detail) && stampHolds(board, detail.presence, strict)) {+ state = { signed: false, by: PERSON, at: row.event_at };+ }+ }+ return state;+}++/**+ * Whether an off event carries the very request a passkey confirmed: a request to turn signing off, whose exact+ * JSON the stamp's digest names. Why the event keeps the request itself: a stamp for some other request, copied into+ * a hand-written off, then names a different digest and turns nothing off.+ */+function offIntent(detail) {+ const intent = detail.intent;+ return Boolean(intent && intent.id === detail.request && detail.presence?.request === detail.request && intent.move?.verb === 'signing'+ && intent.move.args?.signed === 'off' && createHash('sha256').update(JSON.stringify(intent)).digest('hex') === detail.presence.digest);+}++/** Raise a board's event-log format once it has signed person moves, so an older Pullboard cannot open it. */+export function stampSigningFormat(db) {+ if (!db.prepare("SELECT 1 FROM event WHERE event_kind = 'person_signing' LIMIT 1").get()) return;+ db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')+ .run('event_log_version', String(SIGNED_EVENT_LOG_VERSION));+}++/**+ * Turn signing on or off as one ordered move. Anyone may turn it on. Only the person turns it off, carrying out a+ * passkey-confirmed request whose relay stamp the event keeps, so every reader can check it.+ *+ * @param {any} board+ * @param {{ agentId: string, signed: boolean, request?: string }} options+ */+export function setPersonSigning(board, { agentId, signed, request }) {+ if (typeof agentId !== 'string' || !agentId || typeof signed !== 'boolean') throw new Refused('USAGE', 'pullboard settings person.signed on|off');+ const presence = signed ? null : requestPresence(board, request, { strict: false });+ const record = presence && personRequestRecords(board).find((entry) => entry.id === request && !entry.duplicateOf);+ const detail = presence ? { signed, request, presence, intent: JSON.parse(record.encoded) } : { signed };+ if (!signed && (agentId !== PERSON || !presence || !offIntent(detail))) throw signedRefusal('only the person turns signing off, on their passkey');+ return atomic(board, () => {+ logEvent(board, agentId, 'person_signing', null, detail);+ stampSigningFormat(board.db);+ return { signed, by: agentId };+ });+}++/** The person moves waiting for a passkey, oldest first, each with the exact request the passkey confirms. */+export function personProposals(board) {+ return read(board, PROPOSALS, []);+}++/**+ * Record a person move started in a terminal as a request the person's passkey device shows, so it completes on one+ * confirmation there. It grants nothing: the device sends the same request, and only a passkey makes it count.+ *+ * @param {any} board+ * @param {{ agentId: string, request: any }} options+ */+export function proposePersonMove(board, { agentId, request }) {+ if (typeof agentId !== 'string' || !agentId || agentId === PERSON) throw new Refused('PERSON_PROPOSAL', 'a terminal proposes a person move for the person to confirm on their passkey');+ const document = validatePersonRequest(request);+ return atomic(board, () => {+ const at = board.clock.now();+ const entry = { id: document.id, move: document.move, ...(document.rows ? { rows: document.rows } : {}), by: agentId, at: at.toISOString(), expires: new Date(at.getTime() + PROPOSAL_MS).toISOString() };+ const kept = personProposals(board).filter((proposal) => proposal.id !== document.id);+ meta(board, PROPOSALS, JSON.stringify([...kept, entry].slice(-KEPT_PROPOSALS)));+ logEvent(board, agentId, 'person_proposal', null, { request: document.id, verb: document.move.verb });+ return entry;+ });+}++/**+ * The relay's passkey stamp on a recorded person request, or null. It counts only when it names this request and+ * the digest of its exact intent, and, when `strict`, carries the relay's signature under the pinned key.+ *+ * @param {any} board+ * @param {string} id+ * @param {{ strict?: boolean }} [options]+ */+export function requestPresence(board, id, { strict = true } = {}) {+ const record = personRequestRecords(board).find((entry) => entry.id === id && !entry.duplicateOf);+ if (!record) return null;+ let received;+ try { received = JSON.parse(record.received); }+ catch { return null; } // A receipt without readable provenance carries no presence; the gates refuse it.+ const presence = received?.sender?.presence;+ // The stamp names the digest of the request as received; the move the board carries out must be that request's.+ const bound = JSON.stringify(received.document) === record.encoded && JSON.stringify(received.document?.move) === JSON.stringify(record.move);+ return received?.sender?.kind === 'person' && bound && presence?.request === record.id && presence.digest === requestIntentDigest(record)+ && stampHolds(board, presence, strict) ? presence : null;+}++/** Whether this command or move carries out a person request a passkey confirmed. */+export function passkeyConfirmed(board, personRequest, { strict = true } = {}) {+ return personRequest?.phase === 'execute' && typeof personRequest.id === 'string' && Boolean(requestPresence(board, personRequest.id, { strict }));+}++/** The refusal every unsigned person move gets while signing is on, naming where the passkey step happens. */+export function signedRefusal(message, next = 'pair your phone or a computer browser with pullboard relay on --all, add a passkey there, then confirm person moves on it') {+ return new Refused('PERSON_SIGNED', `person moves on this board are signed with your passkey: ${message}`, next);+}++/**+ * Refuse a person-only move while signing is on unless it carries out a passkey-confirmed request. Commands check it+ * strictly before ordering a move; every replica checks it again on replay with the replicated reading.+ *+ * A request's claim, refusal and coordinator-request receipts are fixed-text shouts the request binds (see+ * requestMoveProblem), not person decisions, so they pass; the move that carries the request out needs the passkey.+ *+ * @param {any} board+ * @param {boolean} personOnly - whether the move is one only the person makes+ * @param {any} personRequest - the verified request receipt the move carries out, if any+ * @param {{ strict?: boolean }} [options]+ * @returns {Refused | null}+ */+export function signedMoveProblem(board, personOnly, personRequest, { strict = false } = {}) {+ if (!personOnly || !personSigning(board, { strict }).signed) return null;+ if (['claim', 'refuse', 'repo-request'].includes(personRequest?.phase) || passkeyConfirmed(board, personRequest, { strict })) return null;+ return signedRefusal('no passkey confirmed this move');+}++/**+ * Restore a checkpoint or import without losing what this board alone knows: the pinned relay key never comes from+ * a document and survives a restore, and a board that had signing on refuses a restore that turns it off without a+ * stamped off. Returns the function to run once the rows are in, before the restore commits.+ *+ * @param {any} db - the board's database, inside the restore transaction+ * @param {any} document - the export or checkpoint being restored, whose own pin row is dropped+ */+export function guardRestore(db, document) {+ const board = { db };+ const pinned = localAuthority(board);+ const wasSigned = personSigning(board).signed;+ if (Array.isArray(document?.tables?.board_meta)) document.tables.board_meta = document.tables.board_meta.filter((row) => row.meta_key !== AUTHORITY);+ for (const { name } of AUTHORITY_TRIGGERS) db.exec(`DROP TRIGGER IF EXISTS ${name}`);+ return () => {+ if (pinned) {+ meta(board, AUTHORITY, JSON.stringify(pinned));+ for (const { sql } of AUTHORITY_TRIGGERS) db.exec(sql);+ }+ stampSigningFormat(db);+ if (wasSigned && !personSigning(board).signed) {+ throw new Refused('PERSON_SIGNING_ERASED', 'this board signs person moves, and the checkpoint or import turns that off without the passkey; restore a known-good board instead');+ }+ };+}++/** Rows a board export leaves out: the pinned relay key belongs to this board file alone. */+export function exportedMeta(rows) {+ return rows.filter((row) => row.meta_key !== AUTHORITY);+}diff --git a/src/relay-outbox.js b/src/relay-outbox.jsindex 96eccee0..77e5841e 100644--- a/src/relay-outbox.js+++ b/src/relay-outbox.js@@ -163,7 +163,7 @@ export const ITEM_SLOTS = Object.freeze({recordRowDecisions: [], applyRowDecisions: [], draftSpecRow: [], recordSpecApprovalBaseline: [],recordLandingBatch: [], recordLandingWaiver: [], recordLandingFlake: [], recordLandingTestDefect: [], finishLandingBatch: [],recordHealthFindings: [], decideSentinel: [], beginSentinelRun: [], finishSentinelRun: [],- recordFlakeObservation: [], recordGateRun: [], declareJob: [], recordJobRun: [], takeCoordinator: [], landingLeaseMove: [],+ recordFlakeObservation: [], recordGateRun: [], declareJob: [], recordJobRun: [], takeCoordinator: [], landingLeaseMove: [], setPersonSigning: [], proposePersonMove: [],...Object.fromEntries(FIRST_ITEM.map((operation) => [operation, [[0]]])),addItem: [[0, 'parentId'], [0, 'after', '*']],editItem: [[0], [1, 'after', '*']],diff --git a/src/relay-presentation.js b/src/relay-presentation.jsindex 01f83f8b..05b4af28 100644--- a/src/relay-presentation.js+++ b/src/relay-presentation.js@@ -13,7 +13,10 @@ import { loadConfig } from './config.js';import { projectState } from './serve.js';import { personNeeds } from './needs.js';import { personBlockWords } from './blocks.js';-import { personRequestStatuses } from './relay-requests.js';+import {+ personRequestRecords,+ personRequestStatuses,+} from './relay-requests.js';import {cachedVerdictStates,verdictProjector,@@ -42,7 +45,11 @@ function readRelayPresentation(root, providedBoard) {const verdictState = derived.get(item.id);return verdictState ? { ...item, verdictState } : item;});- return { version: 1, state: { ...store.projectItemThreads(board, state), personRequests: personRequestStatuses(board) }, config: loadConfig(root), shouts: store.allShouts(board) }; }+ // The passkey device reads whether person moves are signed and which terminal-started moves wait for it [E22].+ const requested = new Set(personRequestRecords(board).map((record) => record.id));+ const personProposals = store.personProposals(board).filter((proposal) => !requested.has(proposal.id));+ return { version: 1, state: { ...store.projectItemThreads(board, state), personRequests: personRequestStatuses(board),+ personSigning: { signed: store.personSigning(board).signed }, personProposals }, config: loadConfig(root), shouts: store.allShouts(board) }; }finally { if (!providedBoard) store.closeBoard(board); }}/** Resolve one shout from the complete history carried only inside the sealed presentation. */diff --git a/src/relay-request-execution.js b/src/relay-request-execution.jsindex e46aa404..06435ac9 100644--- a/src/relay-request-execution.js+++ b/src/relay-request-execution.js@@ -80,7 +80,7 @@ export async function executePersonRequests(root, io, runCommand) {}}const completed = requests(coordinatorRoot).find(entry => entry.id === record.id);- if (['spec-approve', 'spec-decline'].includes(record.move.verb) && completed.status === 'waiting' && !completed.coordinatorRequest) {+ if (['spec-approve', 'spec-decline', 'spec-answer'].includes(record.move.verb) && completed.status === 'waiting' && !completed.coordinatorRequest) {await receipt(coordinatorRoot, completed, executor, 'repo-request', io);}} catch (error) {diff --git a/src/relay-requests.js b/src/relay-requests.jsindex be8536ae..a71ce86b 100644--- a/src/relay-requests.js+++ b/src/relay-requests.js@@ -3,6 +3,7 @@ import * as store from './board.js';import { createHash } from 'node:crypto';import { recordedRefusal } from './recorded-refusal.js';import { Refused } from './refused.js';+import { answerQuestion } from './blueprints.js';import { parseImplies } from './implies.js';import { validatePersonRequest } from './person-request.js';import { relayMoveActor } from './relay-sender.js';@@ -69,7 +70,7 @@ export function receivePersonRequest(board, document, { sequence, at, sender })if (sender?.kind !== 'person' || typeof sender.userId !== 'string' || !sender.userId || sender.userId.length > 256) throw new Refused('RELAY_PERSON_ONLY', 'only the authenticated person can send a relay request; use the paired view with the person session');request = validatePersonRequest(document);// On a board that names approvers, a phone request that acts as the person must come from one [E4].- if (sender.approver === false && ['answer', 'hold', 'spec-approve', 'spec-decline', 'sentinel-approve', 'sentinel-decline'].includes(request.move?.verb)) {+ if (sender.approver === false && ['answer', 'hold', 'spec-approve', 'spec-decline', 'spec-answer', 'fact', 'sentinel-approve', 'sentinel-decline'].includes(request.move?.verb)) {throw new Refused('NOT_APPROVER', `${sender.login ?? 'this person'} is not an approver of this board; ask an approver to answer, hold or decide rows and sentinels`);}} catch (cause) {@@ -122,6 +123,24 @@ function fulfilsIntent(record, move) {// item or superseded answer the phone did not name, and none it named left out.if (intent.verb === 'answer') return value === intent.item && options?.asPerson === true && options.channel === 'view' && options.text === args.text&& JSON.stringify(options.implies ?? []) === JSON.stringify(requestedImplies(args.implies)) && (options.supersedes ?? null) === requestedAnswer(args.supersedes);+ if (intent.verb === 'fact') return value === intent.item && options?.asPerson === true && options.channel === 'view'+ && options.kind === args.kind && options.text === args.text && (options.supersedes ?? null) === (args.supersedes ?? null)+ && (options.ref ?? null) === (args.ref ?? null) && (options.cause ?? null) === (args.cause ?? null)+ && Boolean(options.neverAgain) === Boolean(args['never-again'])+ && JSON.stringify(options.implies ?? []) === JSON.stringify(requestedImplies(args.implies));+ if (intent.verb === 'spec-answer') {+ let document;+ let text;+ try {+ document = JSON.parse(record.encoded);+ const shown = document.rows?.find(row => row.id === args.row);+ if (!shown) return false;+ text = answerQuestion(shown.text, args.answer, args.row).text;+ } catch { return false; }+ return value?.agentId === 'person' && value.channel === 'view' && value.decisions?.length === 1+ && value.decisions[0].id === args.row && value.decisions[0].kind === 'spec'+ && value.decisions[0].decision === 'approve' && value.decisions[0].text === text;+ }if (intent.verb === 'hold') return value === args.lane && options?.asPerson === true && options.channel === 'view'&& (args.off || options.reason === (args.reason ?? ''));if (['sentinel-approve', 'sentinel-decline'].includes(intent.verb)) {@@ -132,7 +151,12 @@ function fulfilsIntent(record, move) {&& (value.reason ?? '') === (decline ? args.reason.trim() : '')&& Object.keys(value).every(key => ['agentId', 'channel', 'name', 'digest', 'decision', 'reason'].includes(key));}+ // Signed person moves [E22]: the waiver and the signing switch carry exactly the request's values, and its id.+ if (intent.verb === 'land-waive') return value?.agentId === 'person' && value.channel === 'view' && value.test === args.waive+ && value.until === args.until && value.reason === args.reason;+ if (intent.verb === 'signing') return value?.signed === (args.signed === 'on') && (args.signed === 'on' || value.agentId === 'person' && value.request === record.id);const rows = value?.decisions;+ if (!['spec-approve', 'spec-decline', 'spec-answer'].includes(intent.verb) || typeof args.ids !== 'string') return false;const ids = args.ids.split(/[\s,]+/u).filter(Boolean);return value?.agentId === 'person' && value.channel === 'view' && Array.isArray(rows) && rows.length === ids.length&& rows.every((row, index) => (row.kind === 'doctrine' ? 'doctrine:' : '') + row.id === ids[index]@@ -157,7 +181,7 @@ export function requestStageText(record, phase) {const text = phase === 'claim' ? 'Received a request from the paired view.': phase === 'refuse' ? 'Could not fulfil this request. Read its recorded refusal and next step.': 'Apply the person’s recorded row decision with pullboard spec apply, or decline this request with a reason. '- + record.move.verb + ': ' + record.move.args.ids;+ + record.move.verb + ': ' + (record.move.args.ids ?? record.move.args.row);return 'View request ' + record.id + ': ' + text;}@@ -167,7 +191,7 @@ function fulfilsStage(record, move, tag) {return move.operation === 'shout' && move.args.length === 1 && value?.from === 'person' && value.to === 'coordinator'&& value.text === requestStageText(record, tag.phase, tag.error) && !value.decision && value.answers == null && value.evidence == null&& Boolean(value.request) === (tag.phase === 'repo-request')- && (tag.phase !== 'repo-request' || ['spec-approve', 'spec-decline'].includes(record.move.verb))+ && (tag.phase !== 'repo-request' || ['spec-approve', 'spec-decline', 'spec-answer'].includes(record.move.verb))&& Object.keys(value).every(key => ['from', 'to', 'text', 'lanes', 'request', 'decision', 'answers', 'evidence'].includes(key));}@@ -196,7 +220,7 @@ export function requestMoveProblem(board, move, { checkExecutorLease = true } =const actor = relayMoveActor(move);if (!['coordinator', 'person'].includes(actor)) return new Refused('PERSON_REQUEST_RECEIPT', 'only the coordinator fulfils an authenticated person request');if (tag.phase === 'execute') {- const expected = { add: 'addItem', shout: 'shout', answer: 'answerDecision', hold: record.move.args.off ? 'releaseLane' : 'holdLane', 'spec-approve': 'recordRowDecisions', 'spec-decline': 'recordRowDecisions', 'sentinel-approve': 'decideSentinel', 'sentinel-decline': 'decideSentinel' }[record.move.verb];+ const expected = { add: 'addItem', shout: 'shout', answer: 'answerDecision', hold: record.move.args.off ? 'releaseLane' : 'holdLane', 'spec-approve': 'recordRowDecisions', 'spec-decline': 'recordRowDecisions', 'spec-answer': 'recordRowDecisions', fact: 'appendFact', 'sentinel-approve': 'decideSentinel', 'sentinel-decline': 'decideSentinel', 'land-waive': 'recordLandingWaiver', signing: 'setPersonSigning' }[record.move.verb];if (move.operation !== expected || !fulfilsIntent(record, move)) return new Refused('PERSON_REQUEST_RECEIPT', 'the ordinary move does not fulfil this request; execute its original CLI intent');}if (move.engine >= 6 && ['claim', 'repo-request', 'refuse'].includes(tag.phase) && !fulfilsStage(record, move, tag)) return new Refused('PERSON_REQUEST_RECEIPT', 'publish only the exact stage for this authenticated phone request');@@ -233,7 +257,7 @@ export function recordRequestMove(board, move, outcome, sequence, at) {} else if (tag.phase === 'execute') {record.result = outcome.result;record.resultSequence = sequence;- if (!['spec-approve', 'spec-decline'].includes(record.move.verb)) record.status = 'done';+ if (!['spec-approve', 'spec-decline', 'spec-answer'].includes(record.move.verb)) record.status = 'done';} else if (tag.phase === 'repo-request') {record.coordinatorRequest = outcome.result;}diff --git a/src/relay-sender.js b/src/relay-sender.jsindex 867b2784..0827afc4 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -10,7 +10,7 @@ export function relayMoveActor(move) {if (move.operation === 'addItem') return args[0]?.by ?? null;if (move.operation === 'shout') return args[0]?.from ?? null;if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(move.operation)) return args[0]?.agentId ?? null;- if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove'].includes(move.operation)) return args[0]?.agentId ?? null;+ if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove', 'setPersonSigning', 'proposePersonMove'].includes(move.operation)) return args[0]?.agentId ?? null;if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';if (move.operation === 'release') return args[1] ?? null;if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'recordSpecApprovalBaseline', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'recordLandingTestDefect', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;@@ -29,7 +29,19 @@ export function validRelaySender(sender) {(sender.lineage === undefined || typeof sender.lineage === 'string' && sender.lineage.length > 0 && sender.lineage.length <= 64) &&(sender.login === undefined || typeof sender.login === 'string' && /^[A-Za-z0-9-]{1,39}$/u.test(sender.login)) &&(sender.approver === undefined || typeof sender.approver === 'boolean') &&- (sender.engine === undefined || Number.isSafeInteger(sender.engine) && sender.engine > 0));+ (sender.engine === undefined || Number.isSafeInteger(sender.engine) && sender.engine > 0) &&+ (sender.presence === undefined || sender.kind === 'person' && validPresence(sender.presence)));+}++/**+ * The relay's passkey stamp on a person request: the board, the request id and intent digest it was granted for,+ * the passkey, when, and the relay's signature over them [E22].+ */+export function validPresence(value) {+ return Boolean(value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).sort().join() === 'at,board,credential,digest,request,signature' &&+ typeof value.request === 'string' && /^[A-Za-z0-9_-]{1,80}$/u.test(value.request) && typeof value.credential === 'string' &&+ /^[A-Za-z0-9_-]{1,1400}$/u.test(value.credential) && Number.isSafeInteger(value.at) && value.at > 0 &&+ /^[0-9a-f]{32}$/u.test(value.board ?? '') && /^[0-9a-f]{64}$/u.test(value.digest ?? '') && /^[A-Za-z0-9_-]{86}$/u.test(value.signature ?? ''));}/**@@ -37,8 +49,8 @@ export function validRelaySender(sender) {* person fact or request, or any move whose actor is the person. On a board that names approvers, only an approver's* session makes one [E4].*/-function personAuthority(move) {- return personFact(move) || ['recordRowDecisions', 'decideSentinel'].includes(move?.operation) || move?.operation === 'answerDecision' && Boolean(move.args?.[1]?.asPerson) ||+export function personAuthority(move) {+ return personFact(move) || ['holdLane', 'releaseLane'].includes(move?.operation) && Boolean(move.args?.[1]?.asPerson) || ['recordRowDecisions', 'decideSentinel'].includes(move?.operation) || move?.operation === 'answerDecision' && Boolean(move.args?.[1]?.asPerson) ||move?.operation === 'shout' && Boolean(move.args?.[0]?.request) || relayMoveActor(move) === 'person';}diff --git a/src/sentinel-command.js b/src/sentinel-command.jsindex f3f9a56f..216094cf 100644--- a/src/sentinel-command.js+++ b/src/sentinel-command.js@@ -1,5 +1,6 @@/** CLI proposal and exact person decisions for board-owned watches [A6,D3]. */import { PERSON } from './board.js';+import { requireSignedPerson } from './person-signing-cli.js';import { requirePersonChannel } from './person.js';import { Refused } from './refused.js';import { sentinels } from './sentinels.js';@@ -22,7 +23,6 @@ export async function sentinelCommand({ ctx, words, values, withBoard, whoAmI, oif (extra.length || !['propose', 'approve', 'decline'].includes(verb) || !name) {throw new Refused('USAGE', 'use pullboard sentinel propose <name> --check "<command>" --every 10m --owner <seat or lane>, sentinel approve <name>, sentinel decline <name> --reason "<why>", or pullboard sentinels');}- if (verb !== 'propose') requirePersonChannel(ctx.io.personChannel);return withBoard(ctx, async board => {const me = whoAmI(ctx, board);let row;@@ -37,6 +37,9 @@ export async function sentinelCommand({ ctx, words, values, withBoard, whoAmI, oif (!current) throw new Refused('STALE_SENTINEL', 'read the current proposals with pullboard sentinels');const digest = values.digest ?? current.digest;if (digest !== current.digest) throw new Refused('STALE_SENTINEL', 'this proposal changed after it was shown; refresh the pending watch and decide its current command, directory and schedule');+ const confirmed = await requireSignedPerson(ctx, board, me, { verb: `sentinel-${verb}`, args: { name, digest, ...(verb === 'decline' ? { reason: String(values.reason ?? '') } : {}) } });+ if (confirmed !== null) return confirmed;+ requirePersonChannel(ctx.io.personChannel);row = await ordered(ctx, board, 'decideSentinel', [{ agentId: PERSON, channel: ctx.io.personChannel ?? 'terminal',name, digest, decision: verb, reason: (values.reason ?? '').trim() }]);}diff --git a/test/api.test.js b/test/api.test.jsindex a2d4008d..abb2a65e 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -1,7 +1,15 @@/** The public, versioned JSON surface of every pullboard command (A1). */import assert from 'node:assert/strict';import { randomUUID } from 'node:crypto';-import { runFixtureExecFile as execFileSync, startFixtureChild as spawn, runFixtureChild as spawnSync, reportFixtureChildFailure, runFixtureChild, runFixtureGit, safeFixtureDiagnostic } from './fixture-child.js';+import {+ runFixtureExecFile as execFileSync,+ startFixtureChild as spawn,+ runFixtureChild as spawnSync,+ reportFixtureChildFailure,+ runFixtureChild,+ runFixtureGit,+ safeFixtureDiagnostic,+} from './fixture-child.js';import { performance } from 'node:perf_hooks';import {appendFileSync,@@ -19,16 +27,46 @@ import { tmpdir } from 'node:os';import { DatabaseSync } from 'node:sqlite';import { once } from 'node:events';import { createServer } from 'node:http';-import { join, dirname, resolve, basename, delimiter } from 'node:path';-import { after, test } from 'node:test';-import { main, resultCommands } from '../src/cli.js';+import {+ join,+ dirname,+ resolve,+ basename,+ delimiter,+} from 'node:path';+import {+ after,+ test,+} from 'node:test';+import {+ main,+ resultCommands,+} from '../src/cli.js';import { createLocalApiHandler } from '../src/api.js';import { serveApi } from '../src/api.js';import * as apiExports from '../src/api.js';-import { addItem as addBoardItem, allShouts, EVENT_LOG_VERSION, closeBoard, events as boardEvents, openBoard, verdictsFor } from '../src/board.js';-import { presentationShout, relayPresentation } from '../src/relay-presentation.js';+import {+ addItem as addBoardItem,+ allShouts,+ EVENT_LOG_VERSION,+ closeBoard,+ events as boardEvents,+ openBoard,+ verdictsFor,+} from '../src/board.js';+import { SIGNED_EVENT_LOG_VERSION } from '../src/board.js';++// The newest event-log format this Pullboard reads: a board with signed person moves is format 2 [E22].+const READABLE_EVENT_LOG = Math.max(EVENT_LOG_VERSION, SIGNED_EVENT_LOG_VERSION);+import {+ presentationShout,+ relayPresentation,+} from '../src/relay-presentation.js';import { JSON_SHAPES } from '../src/json.js';-import { projectState, serveView } from '../src/serve.js';+import {+ projectState,+ serveView,+} from '../src/serve.js';import { registerProject } from '../src/projects.js';import { SSH_SHELL_MARKERS } from '../src/person.js';import {@@ -231,13 +269,13 @@ test('[A5] board opens upgrade older event logs and refuse future event logs befconst file = join(box.repo, '.git', 'pullboard', 'board.sqlite');assert.equal(readEventLogVersion(file), String(EVENT_LOG_VERSION));- const future = EVENT_LOG_VERSION + 1;+ const future = READABLE_EVENT_LOG + 1;setEventLogVersion(file, future);const refused = box.run(box.repo, 'status', '--json');assert.equal(refused.status, 1, refused.stderr);const refusal = JSON.parse(refused.stdout).error;assert.equal(refusal.code, 'EVENT_LOG_VERSION');- assert.match(refusal.message, new RegExp(`event log version ${future}.*version ${EVENT_LOG_VERSION}`));+ assert.match(refusal.message, new RegExp(`event log version ${future}.*version ${READABLE_EVENT_LOG}`));assert.match(refusal.next, /upgrade pullboard/i);assert.equal(readEventLogVersion(file), String(future), 'a future-format refusal leaves the stored version untouched');@@ -570,7 +608,10 @@ test('[A5, A6] a future-schema worktree cannot migrate the shared board; main cawriteFileSync(guardedSource, unguardedText);const mutationProbe = join(unguarded, '.schema-mutation-probe.mjs');writeFileSync(mutationProbe, `- import { openBoard, closeBoard } from './src/board.js';+ import {+ openBoard,+ closeBoard,+} from './src/board.js';const board = openBoard(process.env.PULLBOARD_FIXTURE_BOARD, undefined, { isMain: false });closeBoard(board);`);@@ -1233,7 +1274,7 @@ test('[A5,A6] doctor diagnoses future event logs read-only and accepts the curreassert.deepEqual(JSON.parse(current.stdout).problems, [], 'the current event-log version is healthy');assert.deepEqual(readFileSync(file), beforeCurrent, 'doctor leaves a current board byte-for-byte unchanged');- setEventLogVersion(file, EVENT_LOG_VERSION + 1);+ setEventLogVersion(file, READABLE_EVENT_LOG + 1);const eventsDb = new DatabaseSync(file);let events;try { events = eventsDb.prepare('SELECT COUNT(*) AS count FROM event').get().count; }@@ -1246,10 +1287,10 @@ test('[A5,A6] doctor diagnoses future event logs read-only and accepts the curreconst problems = JSON.parse(refused.stdout).problems;const problem = problems.find((entry) => entry.code === 'EVENT_LOG_VERSION');assert.ok(problem, refused.stdout);- assert.match(problem.message, new RegExp(`event log version ${EVENT_LOG_VERSION + 1}.*version ${EVENT_LOG_VERSION}`));+ assert.match(problem.message, new RegExp(`event log version ${READABLE_EVENT_LOG + 1}.*version ${READABLE_EVENT_LOG}`));assert.match(problem.next, /upgrade pullboard/i);assert.deepEqual(readFileSync(file), futureBytes, 'the read-only diagnosis preserves the complete board file');- assert.equal(readEventLogVersion(file), String(EVENT_LOG_VERSION + 1), 'doctor does not silently upgrade the marker');+ assert.equal(readEventLogVersion(file), String(READABLE_EVENT_LOG + 1), 'doctor does not silently upgrade the marker');});test('[A5] view export preserves the typed future-version refusal without creating output', () => {@@ -1257,7 +1298,7 @@ test('[A5] view export preserves the typed future-version refusal without creaticonst added = json(box, box.repo, 'add', ['app', 'Export version fixture', '--specs', 'G1']);const file = join(box.repo, '.git', 'pullboard', 'board.sqlite');assert.ok(added.item.item_id);- setEventLogVersion(file, EVENT_LOG_VERSION + 1);+ setEventLogVersion(file, READABLE_EVENT_LOG + 1);const eventsDb = new DatabaseSync(file);let events;try { events = eventsDb.prepare('SELECT COUNT(*) AS count FROM event').get().count; }@@ -1272,11 +1313,11 @@ test('[A5] view export preserves the typed future-version refusal without creatiassert.equal(refused.stderr, '', 'view export returns a JSON refusal');const error = JSON.parse(refused.stdout).error;assert.equal(error.code, 'EVENT_LOG_VERSION', refused.stdout);- assert.match(error.message, new RegExp(`event log version ${EVENT_LOG_VERSION + 1}.*version ${EVENT_LOG_VERSION}`));+ assert.match(error.message, new RegExp(`event log version ${READABLE_EVENT_LOG + 1}.*version ${READABLE_EVENT_LOG}`));assert.match(error.next, /upgrade pullboard/i);assert.equal(existsSync(output), false, 'refused export creates no output directory or files');assert.deepEqual(readFileSync(file), before, 'refused export preserves every board byte');- assert.equal(readEventLogVersion(file), String(EVENT_LOG_VERSION + 1));+ assert.equal(readEventLogVersion(file), String(READABLE_EVENT_LOG + 1));});test('one move recomputes only the items it touched [A2,N26]', async (t) => {diff --git a/test/exchange.test.js b/test/exchange.test.jsindex 4f102365..40957c8c 100644--- a/test/exchange.test.js+++ b/test/exchange.test.js@@ -3,13 +3,28 @@*/import { submitFixture } from './board-submit-fixture.js';import assert from 'node:assert/strict';-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';-import { runFixtureChild, runFixtureGit } from './fixture-child.js';+import {+ mkdtempSync,+ mkdirSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import {+ runFixtureChild,+ runFixtureGit,+} from './fixture-child.js';import { tmpdir } from 'node:os';-import { join, resolve } from 'node:path';+import {+ join,+ resolve,+} from 'node:path';import { test } from 'node:test';import * as store from '../src/board.js';-import { exportBoard, importBoard } from '../src/exchange.js';+import {+ exportBoard,+ importBoard,+} from '../src/exchange.js';+import { SIGNED_EVENT_LOG_VERSION } from '../src/board.js';const SHA = 'a'.repeat(40);const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');@@ -98,10 +113,10 @@ test('[A5] imported event logs refuse future formats and upgrade older formats',const before = exportBoard(target);const future = structuredClone(exportBoard(source));const futureVersion = future.tables.board_meta.find((row) => row.meta_key === 'event_log_version');- futureVersion.meta_value = String(store.EVENT_LOG_VERSION + 1);+ futureVersion.meta_value = String(SIGNED_EVENT_LOG_VERSION + 1); // Format 2 is a signed board's, which this Pullboard reads [E22].assert.throws(() => importBoard(target, future), (error) => {assert.equal(error.code, 'EVENT_LOG_VERSION');- assert.match(error.message, new RegExp(`version ${store.EVENT_LOG_VERSION + 1}.*version ${store.EVENT_LOG_VERSION}`));+ assert.match(error.message, new RegExp(`version ${SIGNED_EVENT_LOG_VERSION + 1}.*version ${SIGNED_EVENT_LOG_VERSION}`));assert.match(error.message, /upgrade pullboard/i);return true;});diff --git a/test/machine.test.js b/test/machine.test.jsindex 8ff76525..7625c21d 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -6,7 +6,15 @@*/import { submitFixture } from './board-submit-fixture.js';import assert from 'node:assert/strict';-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import {+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { pathToFileURL } from 'node:url';@@ -16,8 +24,22 @@ import * as store from '../src/board.js';import { HELP } from '../src/cli.js';import { loadConfig } from '../src/config.js';import { Refused } from '../src/refused.js';-import { BLANKS, IN_STATE, MACHINE, effectiveGuards, lifecycleHelp, lifecycleMarkdown, machineProblems, storeTriggers } from '../src/machine.js';-import { runFixtureExecFile as execFileSync, runFixtureChild as spawnSync, runFixtureChild, runFixtureGit } from './fixture-child.js';+import {+ BLANKS,+ IN_STATE,+ MACHINE,+ effectiveGuards,+ lifecycleHelp,+ lifecycleMarkdown,+ machineProblems,+ storeTriggers,+} from '../src/machine.js';+import {+ runFixtureExecFile as execFileSync,+ runFixtureChild as spawnSync,+ runFixtureChild,+ runFixtureGit,+} from './fixture-child.js';/*** Refusals that are not about an item's lifecycle, so no move declares them: command input, caller@@ -82,6 +104,8 @@ const NOT_MOVES = {CHECKOUT_SESSION: 'the checkout-local session binding is readable before any item move',CHECKOUT_BUSY: 'a hook gives up waiting for a checkout another command holds, before any item move',UNMERGED_SCHEMA: 'shared-board schema compatibility checked before a command opens the database',+ PERSON_SIGNED: 'a person-only move on a board that signs person moves needs a passkey; no item move is person-only',+ PERSON_SIGNING_CORRUPT: 'the signing policy record is read before ordering any move; it is no item lifecycle rule',};/**diff --git a/test/person-first-pin-fixture.js b/test/person-first-pin-fixture.jsnew file mode 100644index 00000000..7e8722f3--- /dev/null+++ b/test/person-first-pin-fixture.js@@ -0,0 +1,44 @@+/** Initial unpaired authority insertion uses only an owned private board, never shared SQLite [E22,B26,H16]. */+import assert from 'node:assert/strict';+import {+ createHash,+ generateKeyPairSync,+ randomUUID,+ sign,+} from 'node:crypto';+import {+ mkdtempSync,+ rmSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import * as store from '../src/board.js';+import { presenceAttestation } from '../src/person-presence.js';++/** A local first-row insertion cannot supply the missing person/relay trust anchor on an unpaired signed board. */+export function firstUnpairedAuthorityInsertion(t) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-person-first-pin-'));+ const board = store.openBoard(join(directory, 'board.sqlite'));+ t.after(() => { store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); });+ const boardId = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value;+ store.setPersonSigning(board, { agentId: 'coordinator', signed: true });+ assert.equal(board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='person_authority_local'").get(), undefined,+ 'the board has never pinned an authority or paired a phone');+ assert.equal(board.db.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name LIKE 'person_authority_%'").all().length, 0,+ 'no legitimate first-pin triggers exist; this control never drops or alters a trigger');+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');+ const request = randomUUID();+ const intent = { version: 1, type: 'person-request', id: request, move: { verb: 'signing', args: { signed: 'off' } } };+ const presence = { board: boardId, request, digest: createHash('sha256').update(JSON.stringify(intent)).digest('hex'),+ credential: 'local-forged-credential', at: Date.now() };+ presence.signature = sign(null, presenceAttestation(presence), privateKey).toString('base64url');+ // The forged off is exact and correctly signed by an unrelated local key; it is not a relay/person attestation.+ board.db.prepare('INSERT INTO event(event_at,event_by,event_kind,item_id,event_detail) VALUES (?,?,?,?,?)')+ .run(new Date().toISOString(), 'person', 'person_signing', null, JSON.stringify({ signed: false, request, presence, intent }));+ assert.equal(store.personSigning(board).signed, true, 'without an authenticated authority the forged off is ignored');+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)').run('person_authority_local', JSON.stringify({+ origin: 'https://unrelated-fixture.invalid', publicKey: publicKey.export({ format: 'der', type: 'spki' }).toString('base64url'),+ }));+ assert.equal(store.personSigning(board).signed, true,+ 'an initial raw local authority row cannot turn signing off on an unpaired board');+}diff --git a/test/person-passkey-browser.test.js b/test/person-passkey-browser.test.jsnew file mode 100644index 00000000..a2e02649--- /dev/null+++ b/test/person-passkey-browser.test.js@@ -0,0 +1,58 @@+/** @pullboard-test-loads relay/browser-passkeys.js relay/browser-client.js relay/passkeys.js src/person-signing.js */+/** A real browser passkey confirms a person move a terminal started, with the person present, once [E22,H16]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { createE2eHelpers } from './e2e-helpers.js';+import { test } from 'node:test';+import {+ findChromeExecutable,+ relayWorkBudgetMs,+ startChrome,+} from './relay-browser-fixture.js';+import { relayClientFixture } from './relay-client-fixture.js';++test('a passkey on the paired browser confirms a terminal-started person move once [E22,H16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed', timeout: relayWorkBudgetMs(20),+}, async (t) => { // budget: hang ceiling for real CLI runs, Chrome and relay calls; not a speed target.+ // WebAuthn needs a domain for its RP id, so this relay is reached as localhost, not 127.0.0.1.+ const box = await relayClientFixture(t, { host: 'localhost' });+ assert.equal((await box.cli('add', box.lane, 'PASSKEY_BROWSER_READY')).code, 0);+ const ask = (await box.cli('shout', 'person', 'PASSKEY_BROWSER_DECISION', '--decision')).document.id;+ await box.link();+ assert.equal((await box.cli('settings', 'person.signed', 'on')).code, 0);+ const helpers = createE2eHelpers();+ const terminal = helpers.launch({ ...box, env: { ...box.env, SSH_CONNECTION: '127.0.0.1 40000 127.0.0.1 22' } },+ box.root, process.execPath, [join(import.meta.dirname, '..', 'bin', 'pullboard.js'), 'answer', String(ask), 'Confirmed in the browser', '--as', 'person', '--json']);+ t.after(async () => { if (terminal.exitCode === null && terminal.signalCode === null) terminal.kill('SIGTERM'); await terminal.closed; });+ await helpers.waitFor(() => { assert.equal(terminal.exitCode, null, terminal.stderrText); return terminal.stderrText.includes('this terminal is waiting'); },+ 'the original SSH terminal waits for a passkey', relayWorkBudgetMs(5));++ const chrome = await startChrome();+ t.after(() => chrome.close());+ // A platform authenticator that reports the person present, as Touch ID does after a touch.+ await chrome.send('WebAuthn.enable', {});+ await chrome.send('WebAuthn.addVirtualAuthenticator', { options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true,+ hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } });+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ await chrome.send('Network.setCookie', { name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax' });+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes('PASSKEY_BROWSER_READY')");++ await chrome.waitFor("!!document.querySelector('#person-passkey-add')", relayWorkBudgetMs(), 'the page offers to add a passkey');+ await chrome.evaluate("document.querySelector('#person-passkey-add').click()");+ await chrome.waitFor("!!document.querySelector('[id^=person-confirm-]')", relayWorkBudgetMs(), 'the terminal-started move waits on the page');+ assert.match(await chrome.evaluate("document.querySelector('#person-passkeys').textContent"), /Answer decision #\d+: Confirmed in the browser/u);+ await chrome.evaluate("document.querySelector('[id^=person-confirm-]').click()");+ await chrome.waitFor("!document.querySelector('[id^=person-confirm-]')", relayWorkBudgetMs(), 'one confirmation sends the move');++ const outcome = await terminal.closed;+ assert.equal(outcome.code, 0, terminal.stderrText);+ const db = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'), { readOnly: true });+ let answers;+ try { answers = db.prepare('SELECT * FROM shout WHERE shout_answers=?').all(ask); }+ finally { db.close(); }+ // No second CLI invocation runs between starting the terminal and observing its committed answer.+ assert.deepEqual(answers.map((row) => [row.shout_from, row.shout_text]), [['person', 'Confirmed in the browser']]);+});diff --git a/test/person-passkey-fixture.js b/test/person-passkey-fixture.jsnew file mode 100644index 00000000..dbdecaa0--- /dev/null+++ b/test/person-passkey-fixture.js@@ -0,0 +1,96 @@+/** A software passkey that answers WebAuthn exactly as a phone or browser authenticator does [E22,H16]. */+import {+ createHash,+ generateKeyPairSync,+ randomBytes,+ sign,+} from 'node:crypto';+import {+ proposePersonMove,+ setPersonSigning,+} from '../src/person-signing.js';+import { validatePersonRequest } from '../src/person-request.js';+import { receivePersonRequest } from '../src/relay-requests.js';++/** SHA-256 bytes of a value. */+function sha256(value) { return createHash('sha256').update(value).digest(); }++/** Encode one CBOR head: a major type and its unsigned argument. */+function head(major, value) {+ if (value < 24) return Buffer.from([(major << 5) | value]);+ if (value < 256) return Buffer.from([(major << 5) | 24, value]);+ const bytes = Buffer.alloc(3); bytes[0] = (major << 5) | 25; bytes.writeUInt16BE(value, 1); return bytes;+}++/** Encode the small CBOR subset a COSE public key uses: integers, byte strings and one map. */+function cbor(value) {+ if (Buffer.isBuffer(value)) return Buffer.concat([head(2, value.length), value]);+ if (Number.isInteger(value)) return value >= 0 ? head(0, value) : head(1, -1 - value);+ const entries = [...value.entries()];+ return Buffer.concat([head(5, entries.length), ...entries.flatMap(([key, item]) => [cbor(key), cbor(item)])]);+}++/**+ * Make one ES256 passkey for an origin. `create` answers registration and `get` answers an assertion; each returns+ * the base64url fields a browser's PublicKeyCredential exposes. `presence: false` models an authenticator answering+ * with no user present, which is what software acting on the person's behalf could produce at best.+ */+export function softwarePasskey(origin) {+ const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });+ const raw = randomBytes(16);+ const id = raw.toString('base64url');+ const rpId = new URL(origin).hostname;+ let counter = 0;+ /** Authenticator data: the RP id hash, flags, a rising signature counter and any attested credential. */+ function authenticatorData(flags, attested = Buffer.alloc(0)) {+ const count = Buffer.alloc(4); count.writeUInt32BE(++counter);+ return Buffer.concat([sha256(rpId), Buffer.from([flags]), count, attested]);+ }+ /** The client data a browser builds for a ceremony. */+ function clientData(type, challenge) {+ return Buffer.from(JSON.stringify({ type, challenge, origin, crossOrigin: false }));+ }+ return {+ id,+ /** Register: attested credential data carries the COSE key, with user presence set. */+ create(challenge) {+ const jwk = publicKey.export({ format: 'jwk' });+ const cose = cbor(new Map([[1, 2], [3, -7], [-1, 1], [-2, Buffer.from(jwk.x, 'base64url')], [-3, Buffer.from(jwk.y, 'base64url')]]));+ const length = Buffer.alloc(2); length.writeUInt16BE(raw.length);+ const data = authenticatorData(0x41, Buffer.concat([Buffer.alloc(16), length, raw, cose]));+ return { id, clientDataJSON: clientData('webauthn.create', challenge).toString('base64url'), authenticatorData: data.toString('base64url') };+ },+ /** Assert over a challenge; user presence is set unless this models an absent person. */+ get(challenge, { presence = true, origin: claimed } = {}) {+ const data = authenticatorData(presence ? 0x05 : 0x00);+ const client = claimed ? Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin: claimed })) : clientData('webauthn.get', challenge);+ const signature = sign('sha256', Buffer.concat([data, sha256(client)]), privateKey);+ return { credential: id, clientDataJSON: client.toString('base64url'), authenticatorData: data.toString('base64url'), signature: signature.toString('base64url') };+ },+ };+}++/** The WebAuthn challenge for a person grant: SHA-256 of the grant, so the grant itself never reaches an authenticator. */+export function grantChallenge(grant) {+ return sha256(grant).toString('base64url');+}++/**+ * Record each signed-person-move event on a board the way the engine does: signing on, a terminal's proposal, and+ * the person's passkey-stamped request turning it off. The stamp's signature is a placeholder: replay reads stamps+ * as the relay attested them, and only a board with a pinned relay key checks the signature.+ *+ * @param {any} board+ * @param {string} agentId - the agent turning signing on and proposing+ */+export function recordSigningEvents(board, agentId) {+ setPersonSigning(board, { agentId, signed: true });+ const document = validatePersonRequest({ version: 1, type: 'person-request', id: 'signing-off-example', move: { verb: 'signing', args: { signed: 'off' } } });+ proposePersonMove(board, { agentId, request: document });+ const boardId = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value;+ const cursor = Number(board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='relay_applied_sequence'").get()?.meta_value ?? 0);+ const presence = { board: boardId, request: document.id, digest: createHash('sha256').update(JSON.stringify(document)).digest('hex'),+ credential: 'fixture-passkey', at: 1, signature: 'A'.repeat(86) };+ receivePersonRequest(board, document, { sequence: cursor + 1, at: new Date().toISOString(), sender: { kind: 'person', userId: 'fixture-person', presence } });+ setPersonSigning(board, { agentId: 'person', signed: false, request: document.id });+}diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex f76cf77f..0a48bb19 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -1,14 +1,34 @@-import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';+import {+ AGENT_SHELL_MARKERS,+ SSH_SHELL_MARKERS,+} from '../src/person.js';/** Private real CLI, auth and relay fixture; credentials never enter assertion messages [H1,H7,H18]. */import assert from 'node:assert/strict';import { createHash } from 'node:crypto';-import { startFixtureChild as spawn, reportFixtureChildFailure, runFixtureChild } from './fixture-child.js';+import {+ startFixtureChild as spawn,+ reportFixtureChildFailure,+ runFixtureChild,+} from './fixture-child.js';import { performance } from 'node:perf_hooks';import { createServer } from 'node:http';import { Transform } from 'node:stream';import { once } from 'node:events';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';-import { delimiter, join, resolve } from 'node:path';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import {+ delimiter,+ join,+ resolve,+} from 'node:path';import { tmpdir } from 'node:os';import { pathToFileURL } from 'node:url';import { createAuthHandler } from '../relay/auth-http.js';@@ -16,7 +36,10 @@ import { createRelayAuth } from '../relay/auth.js';import { createRelayHandler } from '../relay/service.js';import { createGitHubClient } from '../relay/github.js';import { githubFixture } from './relay-fixture.js';-import { relayWorkBudgetMs, MAX_SNAPSHOT_ATTEMPTS } from './relay-budget.js';+import {+ relayWorkBudgetMs,+ MAX_SNAPSHOT_ATTEMPTS,+} from './relay-budget.js';const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');const MAX_OBSERVED_SNAPSHOT_UPLOADS = MAX_SNAPSHOT_ATTEMPTS;@@ -140,7 +163,7 @@ export { childResult as relayFixtureChild };* fixture once used, a loaded machine kept the test process busy enough that browser replies queued past their* deadlines (#955, #979). A case that needs a faster poll passes pollMs by name and says why.*/-export async function relayClientFixture(t, { cliChildren, coordinatorModel, accountStorageBytes, pollMs = 200 } = {}) {+export async function relayClientFixture(t, { cliChildren, coordinatorModel, accountStorageBytes, pollMs = 200, host = '127.0.0.1' } = {}) {const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-cleanup-')));const root = join(scratch, 'repo');const home = join(scratch, 'home');@@ -483,7 +506,8 @@ globalThis.fetch = function tracedFetch(input, init) {server.listen(0, '127.0.0.1');await once(server, 'listening');const relayPort = server.address().port;- const origin = 'http://127.0.0.1:' + relayPort;+ // A browser passkey needs a domain for its RP id, so a passkey case names the relay by `localhost` [E22].+ const origin = 'http://' + host + ':' + relayPort;auth = createRelayAuth({ database: authDatabase, github: createGitHubClient({ ...provider.config, callbackURL: origin + '/auth/github/callback' }) });signIn = createAuthHandler({ auth, publicOrigin: origin });api = createRelayHandler({ directory: join(scratch, 'relay'), auth, publicOrigin: origin, pollMs, maintenanceMs: 0, accountStorageBytes, now: () => Date.now() + timeOffsetMs });diff --git a/test/relay-credential.test.js b/test/relay-credential.test.jsindex 3ed5d009..a952d20c 100644--- a/test/relay-credential.test.js+++ b/test/relay-credential.test.js@@ -1,11 +1,17 @@/** Real transport proves credential selection follows every public operation class [H2,H9,H16]. */import assert from 'node:assert/strict';-import { readFileSync, writeFileSync } from 'node:fs';+import {+ readFileSync,+ writeFileSync,+} from 'node:fs';import { createServer } from 'node:http';import { test } from 'node:test';import { ENGINE_OPERATIONS } from '../src/engine.js';import { ENGINE_VERSION } from '../src/machine.js';-import { decodeBoardKey, unseal } from '../src/seal.js';+import {+ decodeBoardKey,+ unseal,+} from '../src/seal.js';import { relayClientFixture } from './relay-client-fixture.js';import { syntheticFlakeObservation } from './flake-observation-fixture.js';@@ -33,6 +39,8 @@ test('every current operation selects its native actor credential without a secoif (operation === 'recordJobRun') args = [{ agentId: actor, name: 'credential-job' }];if (operation === 'takeCoordinator') args = [{ agentId: actor, machine: 'credential-machine' }];if (operation === 'landingLeaseMove') args = [{ agentId: actor, action: 'renew', token: 'credential-lease', branch: 'main', pid: 1, generation: 0 }];+ if (operation === 'setPersonSigning') args = [{ agentId: actor, signed: true }];+ if (operation === 'proposePersonMove') args = [{ agentId: actor, request: { version: 1, type: 'person-request', id: 'credential-proposal', move: { verb: 'shout', args: { text: 'credential proposal fixture' } } } }];if (operation === 'proposeSentinel') args = [{ agentId: actor,row: { name: 'credential-watch', check: 'true', every: 'hourly', owner: actor } }];if (['beginSentinelRun', 'finishSentinelRun'].includes(operation)) {diff --git a/test/team.test.js b/test/team.test.jsindex d1077c78..8b9007d4 100644--- a/test/team.test.js+++ b/test/team.test.js@@ -1,31 +1,90 @@-/** @pullboard-test-loads src/board.js src/engine.js src/exchange.js */+/** @pullboard-test-loads src/board.js src/engine.js src/exchange.js src/person-signing.js relay/passkeys.js *//** Two independent Git/SQLite replicas derive verdict freshness without rewriting proof [E8]. */import assert from 'node:assert/strict';import childProcess from 'node:child_process';import { syncBuiltinESMExports } from 'node:module';-import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, cpSync, readdirSync, lstatSync, renameSync, symlinkSync } from 'node:fs';-import { randomBytes, randomUUID } from 'node:crypto';-import { join, resolve } from 'node:path';+import {+ existsSync,+ mkdtempSync,+ mkdirSync,+ readFileSync,+ writeFileSync,+ rmSync,+ cpSync,+ readdirSync,+ lstatSync,+ renameSync,+ symlinkSync,+} from 'node:fs';+import {+ createHash,+ randomBytes,+ randomUUID,+} from 'node:crypto';+import {+ join,+ resolve,+} from 'node:path';import { pathToFileURL } from 'node:url';-import { after, test } from 'node:test';+import {+ after,+ test,+} from 'node:test';import * as store from '../src/board.js';-import { exportBoard, importBoard } from '../src/exchange.js';-import { applyEngineMove, prepareEngineMove } from '../src/engine.js';-import { relayClientFixture as sessionRelay, relayFixtureChild as sessionChild, relayClientFixture, relayFixtureChild } from './relay-client-fixture.js';-import { runFixtureGit as sessionGit, runFixtureGit } from './fixture-child.js';+import {+ exportBoard,+ importBoard,+} from '../src/exchange.js';+import {+ applyEngineMove,+ prepareEngineMove,+} from '../src/engine.js';+import {+ relayClientFixture as sessionRelay,+ relayFixtureChild as sessionChild,+ relayClientFixture,+ relayFixtureChild,+} from './relay-client-fixture.js';+import {+ runFixtureChild,+ runFixtureGit as sessionGit,+ runFixtureGit,+} from './fixture-child.js';+import {+ grantChallenge,+ softwarePasskey,+} from './person-passkey-fixture.js';+import { firstUnpairedAuthorityInsertion } from './person-first-pin-fixture.js';+import { refuseNamedSigners } from '../src/person-signing-cli.js';import { createE2eHelpers } from './e2e-helpers.js';-import { serveApi } from '../src/api.js';+import {+ executeMove,+ serveApi,+} from '../src/api.js';import { main } from '../src/cli.js';import { fetchFresh } from './http-fixture.js';-import { relaySnapshot, presentationDigest } from '../src/relay-presentation.js';+import {+ relaySnapshot,+ presentationDigest,+} from '../src/relay-presentation.js';import { snapshotState } from '../relay/browser-model.js';import { unpackRelease } from './release-archive.js';-import { decodeBoardKey, seal } from '../src/seal.js';+import {+ decodeBoardKey,+ seal,+} from '../src/seal.js';import { ENGINE_VERSION as PEOPLE_VERSION } from '../src/machine.js';import { relayWorkBudgetMs } from './relay-budget.js';-import { hostname, tmpdir } from 'node:os';-import { assertMatchingLandingHost, assertNoCulpritTrunkHold } from './landing-environment-fixture.js';+import {+ hostname,+ tmpdir,+} from 'node:os';+import {+ assertMatchingLandingHost,+ assertNoCulpritTrunkHold,+} from './landing-environment-fixture.js';import { landingQueueCase } from './landing-queue-fixture.js';+import { DatabaseSync } from 'node:sqlite';const CLI = join(import.meta.dirname, '..', 'bin', 'pullboard.js');@@ -872,3 +931,263 @@ test('a landing lease renewal or waiter poll writes no board event [Q1,Q2,Q3]',assert.equal(state.holder, null);assert.equal(state.line.length, 1, 'suppressing polling events does not discard the waiting command');});++/** Send one sealed person request with its passkey presence, returning the relay's answer. */+async function passkeyRequest(box, session, document, presence) {+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const head = await relayCall(box, session, 'GET', '/api/v2/boards/' + link.board + '/state');+ const events = await relayCall(box, session, 'GET', `/api/v1/boards/${link.board}/events?after=${head.document.state.sequence}`);+ const sequence = Math.max(head.document.state.sequence, ...(events.document.events ?? []).map((event) => event.event_id)) + 1;+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(document)), { boardId: link.board, kind: 'request', sequence })).toString('base64url');+ return relayCall(box, session, 'POST', `/api/v1/boards/${link.board}/requests`, { sequence, sealed, ...(presence ? { presence } : {}) });+}++/** True when no regular file under a directory holds a person session or a person grant. */+function holdsNoPersonCredential(directory) {+ return filesUnder(directory).every((file) => !/(?:ps_|pg_)[A-Za-z0-9_-]{43}/u.test(readFileSync(file).toString('latin1')));+}++test('person-only moves are signed [E22,B26,H16]', { timeout: relayWorkBudgetMs(60) }, async (t) => { // budget: hang ceiling for real CLI runs and relay calls; not a speed target.+ const box = await relayClientFixture(t);+ /** Run the real CLI in the main checkout with a chosen environment. */+ const cli = (env, ...args) => relayFixtureChild(box.root, env, [CLI, ...args, '--json']);+ // S10a: an agent that cleared AI_AGENT and CLAUDECODE has exactly the person's shell markers.+ const cleared = { ...box.env };+ const marked = { ...box.env, AI_AGENT: '1', CLAUDECODE: '1' };++ // Off, the default: person moves work as today, and status says once that they are not signed.+ const text = runFixtureChild(process.execPath, [CLI, 'status'], { cwd: box.root, env: box.env, encoding: 'utf8' });+ assert.equal(text.status, 0);+ assert.equal(text.stdout.split('\n').filter((line) => /person moves are not signed/u.test(line)).length, 1, 'status says it in one line');+ assert.equal((await box.cli('status')).document.person.signed, false);+ 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.+ 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;++ // 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;+ for (const words of [['answer', String(ask), 'S10a cleared markers', '--as', 'person'], ['spec', 'approve', 'E1'], ['spec', 'approve', 'doctrine:D1'],+ ['spec', 'decline', 'E1', '--reason', 'no'], ['land', '--waive', 'test/x.test.js', '--until', '2099-01-01', '--reason', 'flaky'], ['settings', 'person.signed', 'off']]) {+ const refused = await cli(cleared, ...words);+ assert.equal(refused.code, 1, words.join(' '));+ assert.equal(refused.document.error.code, 'PERSON_SIGNED', `${words.join(' ')}: ${JSON.stringify(refused.document)}`);+ assert.match(refused.document.error.next, /relay on --all/u, 'unpaired: the next step pairs a phone or browser');+ assert.match(refused.document.error.next, /passkey/u);+ }+ assert.equal(box.calls.length, calls, 'refused locally, before any network call or wait');+ assert.equal((await cli(marked, 'answer', String(ask), 'marked agent', '--as', 'person')).document.error.code, 'PERSON_SIGNED', 'an agent shell is refused too');+ const remote = await cli({ ...cleared, SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22' }, 'answer', String(ask), 'from SSH', '--as', 'person');+ assert.equal(remote.document.error.code, 'PERSON_SIGNED', 'over SSH the same passkey step applies');++ // No local file edit turns it off: not the project config, not machine settings.+ const config = join(box.root, 'pullboard.json');+ writeFileSync(config, JSON.stringify({ ...JSON.parse(readFileSync(config, 'utf8')), person: { signed: false } }, null, 2) + '\n');+ mkdirSync(box.env.PULLBOARD_MACHINE_HOME, { recursive: true });+ writeFileSync(join(box.env.PULLBOARD_MACHINE_HOME, 'settings.json'), JSON.stringify({ person: { signed: false } }) + '\n');+ assert.equal((await cli(cleared, 'answer', String(ask), 'after edits', '--as', 'person')).document.error.code, 'PERSON_SIGNED', 'edits leave it on');+ assert.equal((await box.cli('status')).document.person.signed, true);++ // S10b: whatever the OS user can read, an agent can read, so the local view's channel is refused too.+ const viewed = await executeMove(box.root, { verb: 'answer', item: ask, args: { as: 'person', text: 'through the view secret' } }, main);+ 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);+ 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']);+ t.after(async () => { if (terminal.exitCode === null && terminal.signalCode === null) terminal.kill('SIGTERM'); await terminal.closed; });+ /** Observe fixture SQLite directly; no second command may execute the waiting action. */+ const nativeRows = (sql, ...args) => {+ const db = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'), { readOnly: true });+ try { return db.prepare(sql).all(...args); } finally { db.close(); }+ };+ /** Read durable request receipts without running status, export or another command. */+ const nativeRequests = () => Object.fromEntries(JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?',+ 'relay_person_requests')[0]?.meta_value ?? '[]').filter(record => !record.duplicateOf).map(record => [record.id, record]));+ await helpers.waitFor(() => {+ assert.equal(terminal.exitCode, null, terminal.stderrText);+ return terminal.stderrText.includes(box.origin) && terminal.stderrText.includes('this terminal is waiting');+ }, 'the original SSH terminal asks for one passkey confirmation', relayWorkBudgetMs(5));+ const proposals = JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0].meta_value);+ const proposal = proposals.at(-1);+ assert.deepEqual(proposal.move, { verb: 'answer', item: ask, args: { as: 'person', text: 'Signed on the passkey' } }, 'the exact move waits for the passkey');++ // The person registers a passkey with user presence; agents and machines cannot ask for a grant.+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const phone = (await box.phoneSession()).token;+ const passkey = softwarePasskey(box.origin);+ const challenge = await relayCall(box, phone, 'POST', '/api/v1/passkeys/challenge', {});+ assert.equal(challenge.status, 200, JSON.stringify(challenge.document));+ const registered = await relayCall(box, phone, 'POST', '/api/v1/passkeys', { challenge: challenge.document.challenge, ...passkey.create(challenge.document.challenge) });+ assert.equal(registered.status, 200, JSON.stringify(registered.document));+ const document = { version: 1, type: 'person-request', id: proposal.id, move: proposal.move };+ const machineGrant = await relayCall(box, link.token, 'POST', `/api/v1/boards/${link.board}/person-grants`, { request: proposal.id, digest: 'a'.repeat(64) });+ assert.equal(machineGrant.document.error?.code, 'HUMAN_REQUIRED', 'the machine credential, which agents share, gets no grant');+ /** Ask the relay for a fresh single-use grant for this request and the digest of its exact intent. */+ const grantFor = async (document) => {+ const digest = createHash('sha256').update(JSON.stringify(document)).digest('hex');+ const issued = await relayCall(box, phone, 'POST', `/api/v1/boards/${link.board}/person-grants`, { request: document.id, digest });+ assert.equal(issued.status, 200, JSON.stringify(issued.document));+ assert.deepEqual(issued.document.credentials, [passkey.id]);+ return issued.document.grant;+ };++ // Without user presence, or with no assertion at all, nothing acts as the person.+ const absent = await passkeyRequest(box, phone, document, { grant: await grantFor(document), ...passkey.get(grantChallenge('not-this-grant')) });+ assert.equal(absent.document.error?.code, 'PASSKEY_ASSERTION', 'an assertion over another challenge is refused');+ const grant = await grantFor(document);+ const noPresence = await passkeyRequest(box, phone, document, { grant, ...passkey.get(grantChallenge(grant), { presence: false }) });+ assert.equal(noPresence.document.error?.code, 'PASSKEY_PRESENCE', 'an authenticator answer with no user present is refused');+ const elsewhere = await passkeyRequest(box, phone, document, { grant, ...passkey.get(grantChallenge(grant), { origin: 'http://elsewhere.localhost' }) });+ assert.equal(elsewhere.document.error?.code, 'PASSKEY_ASSERTION', 'an answer made for another site is refused');+ const forgedSignature = { grant, ...passkey.get(grantChallenge(grant)), signature: passkey.get(grantChallenge('other bytes')).signature };+ assert.equal((await passkeyRequest(box, phone, document, forgedSignature)).document.error?.code, 'PASSKEY_ASSERTION', 'a signature over other bytes is refused');+ const unsigned = { version: 1, type: 'person-request', id: randomUUID(), move: proposal.move };+ assert.equal((await passkeyRequest(box, phone, unsigned)).status, 200, 'the relay stores a session request without a passkey');+ await helpers.waitFor(() => nativeRequests()[unsigned.id]?.status === 'refused', 'the waiting terminal refuses unsigned intent', relayWorkBudgetMs(5));+ let received = nativeRequests();+ assert.equal(received[unsigned.id].status, 'refused');+ assert.equal(received[unsigned.id].error.code, 'PERSON_SIGNED', 'without a passkey the native board refuses it');++ // One confirmation on the passkey carries out the exact move, once.+ const presence = { grant, ...passkey.get(grantChallenge(grant)) };+ const signed = await passkeyRequest(box, phone, document, presence);+ assert.equal(signed.status, 200, JSON.stringify(signed.document));+ const terminalResult = await terminal.closed;+ assert.equal(terminalResult.code, 0, terminal.stderrText);+ assert.equal(JSON.parse(terminal.stdoutText).request, proposal.id, 'the original terminal reports its exact request');+ received = nativeRequests();+ assert.equal(received[proposal.id].status, 'done', JSON.stringify(received[proposal.id]));+ const answers = nativeRows('SELECT * FROM shout WHERE shout_answers=?', ask);+ assert.deepEqual(answers.map((row) => [row.shout_from, row.shout_text]), [['person', 'Signed on the passkey']]);+ const replay = await passkeyRequest(box, phone, { ...document, id: randomUUID() }, presence);+ assert.equal(replay.document.error?.code, 'PHONE_APPROVAL_USED', 'the grant is single-use');+ assert.ok(holdsNoPersonCredential(box.root) && holdsNoPersonCredential(box.env.HOME), 'the grant was never stored');++ // A hand edit to the board file cannot forge a passkey request, turn signing off or swap the relay key.+ const raw = new DatabaseSync(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ try {+ /** One board metadata value, read straight from the file. */+ const meta = (key) => raw.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key)?.meta_value;+ assert.equal(meta('event_log_version'), '2', 'a Pullboard from before signed moves refuses this board');+ assert.throws(() => raw.prepare("UPDATE board_meta SET meta_value='{}' WHERE meta_key='person_authority_local'").run(), /PERSON_AUTHORITY/u, 'the pinned relay key stays');+ assert.throws(() => raw.prepare("INSERT OR REPLACE INTO board_meta(meta_key,meta_value) VALUES ('person_authority_local','{}')").run(), /PERSON_AUTHORITY/u);+ assert.throws(() => raw.prepare("DELETE FROM event WHERE event_kind='person_signing'").run(), /APPEND_ONLY/u, 'the signing history stays');+ const records = JSON.parse(meta('relay_person_requests'));+ const genuine = records.find((record) => record.id === proposal.id);+ const sender = JSON.parse(genuine.received).sender;+ // A genuine stamp copied into a hand-written off names the digest of another request.+ raw.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?,?,?,?,?)').run(new Date().toISOString(), 'person', 'person_signing', null,+ JSON.stringify({ signed: false, request: proposal.id, presence: sender.presence, intent: { version: 1, type: 'person-request', id: proposal.id, move: { verb: 'signing', args: { signed: 'off' } } } }));+ // The same stamp on a rewritten request: the same id, another answer, waiting to run again.+ const forged = structuredClone(document);+ forged.move.args.text = 'A forged second answer';+ const { result, resultSequence, executor, executorUntil, ...rest } = genuine;+ const rewritten = { ...rest, move: forged.move, encoded: JSON.stringify(forged), received: JSON.stringify({ document: forged, sender }), status: 'waiting' };+ raw.prepare('UPDATE board_meta SET meta_value=? WHERE meta_key=?').run(JSON.stringify(records.map((record) => record.id === genuine.id ? rewritten : record)), 'relay_person_requests');+ } finally { raw.close(); }+ assert.equal((await box.cli('status')).document.person.signed, true, 'the hand-written off turns nothing off');+ const waitingAgain = helpers.launch({ ...box, env: cleared }, box.root, process.execPath,+ [CLI, 'answer', String(ask), 'still signed', '--as', 'person', '--json']);+ try {+ await helpers.waitFor(() => { assert.equal(waitingAgain.exitCode, null, waitingAgain.stderrText); return waitingAgain.stderrText.includes('this terminal is waiting'); },+ 'a cleared-marker terminal still waits for a new confirmation', relayWorkBudgetMs(5));+ assert.equal(nativeRows('SELECT * FROM shout WHERE shout_answers=?', ask).length, 1, 'waiting creates no second person answer');+ } finally { if (waitingAgain.exitCode === null && waitingAgain.signalCode === null) waitingAgain.kill('SIGTERM'); await waitingAgain.closed; }+ assert.equal((await box.cli('export')).document.tables.shout.filter((row) => row.shout_answers === ask).length, 1, 'the rewritten request never runs as the person');++ // A signed row decision binds the exact rows the person saw; a row naming SSH signers is refused by name.+ 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`));+ 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]) {+ const rowGrant = await grantFor(request);+ assert.equal((await passkeyRequest(box, phone, request, { grant: rowGrant, ...passkey.get(grantChallenge(rowGrant)) })).status, 200);+ }+ received = await receivedRequests(box);+ assert.equal(received[blind.id].error?.code, 'STALE_ROW_DECISION', 'a decision that does not name the rows shown is refused');+ 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');+ 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. */+ async function confirmTerminal(argv, expectedVerb) {+ const beforeIds = new Set(JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0]?.meta_value ?? '[]').map(entry => entry.id));+ const child = helpers.launch({ ...box, env: { ...cleared, SSH_CONNECTION: '127.0.0.1 40000 127.0.0.1 22' } },+ box.root, process.execPath, [CLI, ...argv, '--json']);+ try {+ const proposal = await helpers.waitFor(() => {+ assert.equal(child.exitCode, null, child.stderrText);+ if (!child.stderrText.includes('this terminal is waiting')) return null;+ return JSON.parse(nativeRows('SELECT meta_value FROM board_meta WHERE meta_key=?', 'person_proposals')[0]?.meta_value ?? '[]').find(entry => !beforeIds.has(entry.id));+ }, 'the exact new terminal proposal', relayWorkBudgetMs(5));+ assert.equal(proposal.move.verb, expectedVerb);+ const request = { version: 1, type: 'person-request', id: proposal.id, move: proposal.move,+ ...(proposal.rows ? { rows: proposal.rows } : {}) };+ const actionGrant = await grantFor(request);+ assert.equal((await passkeyRequest(box, phone, request, { grant: actionGrant, ...passkey.get(grantChallenge(actionGrant)) })).status, 200);+ const outcome = await child.closed;+ assert.equal(outcome.code, 0, child.stderrText);+ const result = JSON.parse(child.stdoutText);+ assert.equal(result.request, proposal.id);+ assert.ok(['done', 'waiting'].includes(nativeRequests()[proposal.id].status));+ return result;+ } finally {+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');+ await child.closed;+ }+ }+ // 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 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');+ const held = await confirmTerminal(['hold', box.lane, '--as', 'person', '--reason', 'Wait for the exact reviewed rule'], 'hold');+ assert.equal(held.held, true);+ assert.equal(nativeRows('SELECT hold_reason,hold_by FROM hold WHERE hold_lane=?', box.lane)[0].hold_by, 'person');+ const unheld = await confirmTerminal(['hold', box.lane, '--as', 'person', '--off'], 'hold');+ assert.equal(unheld.held, false);+ assert.equal(nativeRows('SELECT * FROM hold WHERE hold_lane=?', box.lane).length, 0);+ for (const name of ['signed-watch-approved', 'signed-watch-declined']) {+ assert.equal((await box.cli('sentinel', 'propose', name, '--check', 'true', '--every', 'hourly', '--owner', 'coordinator')).code, 0);+ }+ const watch = await confirmTerminal(['sentinel', 'approve', 'signed-watch-approved'], 'sentinel-approve');+ assert.equal(watch.sentinel.status, 'approved');+ const declinedWatch = await confirmTerminal(['sentinel', 'decline', 'signed-watch-declined', '--reason', 'Do not run this exact watch'], 'sentinel-decline');+ assert.equal(declinedWatch.sentinel.status, 'declined');+ const question = 'Which store holds the data: SQLite. Choices: SQLite, Postgres.';+ writeFileSync(join(box.root, 'SPEC.md'), readFileSync(join(box.root, 'SPEC.md'), 'utf8')+ + `\n- G2 [pending, must] ${question} | gate: review\n- G3 [draft, must] A terminal-approved row. | gate: review\n- G4 [draft, must] A terminal-declined row. | gate: review\n`);+ const answeredRow = await confirmTerminal(['spec', 'answer', 'G2', 'Postgres'], 'spec-answer');+ assert.equal(answeredRow.decisions[0].id, 'G2');+ assert.match(answeredRow.decisions[0].text, /data: Postgres/u);+ const approvedRow = await confirmTerminal(['spec', 'approve', 'G3'], 'spec-approve');+ assert.equal(approvedRow.decisions[0].decision, 'approve');+ const declinedRow = await confirmTerminal(['spec', 'decline', 'G4', '--reason', 'Do not approve this row'], 'spec-decline');+ assert.equal(declinedRow.decisions[0].decision, 'decline');+ const waiver = await confirmTerminal(['land', '--waive', 'gate:lint', '--until', '2099-01-01', '--reason', 'An explicit bounded fixture exception'], 'land-waive');+ assert.equal(waiver.waiver.test, 'gate:lint');++ // Only the passkey turns signing off; unlinking offline keeps it on.+ const switchedOff = await confirmTerminal(['settings', 'person.signed', 'off'], 'signing');+ assert.equal(switchedOff.person.signed, false);+ assert.equal((await box.cli('status')).document.person.signed, false, 'the passkey turned signing off');+ assert.equal((await cli(marked, 'settings', 'person.signed', 'on')).code, 0);+ await box.stopRelay();+ await cli(cleared, 'relay', 'off');+ assert.equal(existsSync(box.linkFile), false, 'unlinking works offline with no tap');+ assert.equal((await box.cli('status')).document.person.signed, true, 'unlinking never turns signing off');+});++/** 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);