Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(core): authorize key handover from signed board membership [H15,E17]
Corey Olson0d4de2175866
diff --git a/docs/formats.md b/docs/formats.mdindex 3ff92a4c..c1cf0cd9 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -427,6 +427,7 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `edit` | editor | `brief`, `route`, `criterion`, `check`, `unfrozen`, optional `after`, optional `pendingRefreeze`, engine-19 `reason`, `barCorrection` || `escalate` | builder | `from`, `to`, `note`, `attempt` || `attempt` | reporting agent | `n`, `seconds`, `result` |+| `board_members` | coordinator | `document` (exact version-1 body with board, repository, revision and complete members, approving login and SSH signature; native moves and checkpoints carry it sealed) || `fact` | author | `id`, `kind`, `text`, `ref`, `supersedes`, engine-20 `implies`, `decision`, `supersededBy`, engine-30 `cause`, `neverAgain`, `channel` || `claim` | builder | `leaseUntil`, `digest` || `renew` | builder | `leaseUntil`, `digest` |@@ -676,3 +677,7 @@ not a native move, parent identity, configuration or authority record. Missing/dreplays activity. Reads freeze an event high-water mark before observing Git; subsequent eventsand messages remain pending. News has a separate cursor so an ordinary poll cannot consume afuture session-start digest.++### Signed board membership++`setBoardMembers` records an exact next revision in `board_meta.board_members` and a `board_members` event. Its signed document is `{body:{v:1,board,repository,revision,members},by,signature}`; the SSH namespace is `pullboard-board-members` and the bytes are the JSON array `["pullboard-board-members",body,by]`. Repeating the identical document is idempotent. A new empty list removes all additional members. Native ordered transport and checkpoints seal this document with the board key. A key handover independently checks the approving login against committed `pullboard.json` approvers and its SSH signature against GitHub; stored or relay-provided identity flags alone never authorize a handover. Every requester also proves ownership of its own device key. The current native revision is authoritative; an old signature cannot roll back that state.diff --git a/docs/formats.test.js b/docs/formats.test.jsindex 0f01bac5..993cce86 100644--- a/docs/formats.test.js+++ b/docs/formats.test.js@@ -42,6 +42,8 @@ import {recordLandingFlake,recordHealthFindings,openBoard,+ boardId,+ setBoardMembers,passDecision,PERSON,recordAttempt,@@ -296,6 +298,8 @@ function engineLeafFixture(t, landedVersion, pendingLeaves) {function recordEventContract() {const board = openBoard(':memory:');const coordinator = ensureCoordinator(board, '/coordinator');+ // Synthetic format fixture; cryptographic authority is exercised by relay-membership.test.js.+ setBoardMembers(board, { agentId: coordinator, document: { body: { v: 1, board: boardId(board), repository: 'fixture/repository', revision: 1, members: ['bob'] }, by: 'alice', signature: '-----BEGIN SSH SIGNATURE-----\nsynthetic format fixture\n' } });const builder = register(board, { lane: 'docs', path: '/builder' });register(board, { lane: 'docs', path: '/builder', family: 'codex' });register(board, { lane: 'docs', path: '/builder', model: 'Fixture Model' });diff --git a/src/board-members-engine.js b/src/board-members-engine.jsnew file mode 100644index 00000000..5f1e9b9e--- /dev/null+++ b/src/board-members-engine.js@@ -0,0 +1,3 @@+/** Signed, sealed board membership and deterministic revision storage [E17,H16]. */+import { unassignedEngine } from './engine-next.js';+export const BOARD_MEMBERS_ENGINE = unassignedEngine();diff --git a/src/board-members.js b/src/board-members.jsnew file mode 100644index 00000000..d63a4e69--- /dev/null+++ b/src/board-members.js@@ -0,0 +1,61 @@+/** Signed membership travels inside the native sealed board state [E17,H16]. */+import { Refused } from './refused.js';+import { COORDINATOR } from './config.js';+import { atomic, logEvent } from './board-event-log.js';+import { ENGINE_VERSION } from './machine.js';+import { BOARD_MEMBERS_ENGINE } from './board-members-engine.js';++const LOGIN = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u;++/** Copy only the complete, exact signed format; unknown fields cannot acquire unsigned meaning. */+export function boardMembersDocument(value) {+ const exact = (object, keys) => object && typeof object === 'object' && !Array.isArray(object) &&+ Object.keys(object).sort().join(',') === [...keys].sort().join(',');+ const body = value?.body;+ if (!exact(value, ['body', 'by', 'signature']) || !exact(body, ['v', 'board', 'repository', 'revision', 'members']) ||+ body.v !== 1 || typeof body.board !== 'string' || !/^[a-f0-9]{32}$/u.test(body.board) ||+ typeof body.repository !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(body.repository) ||+ !Number.isSafeInteger(body.revision) || body.revision < 1 || !Array.isArray(body.members) || body.members.length > 100 ||+ body.members.some(login => typeof login !== 'string' || !LOGIN.test(login)) ||+ new Set(body.members.map(login => login.toLowerCase())).size !== body.members.length ||+ typeof value.by !== 'string' || !LOGIN.test(value.by) || typeof value.signature !== 'string' ||+ !value.signature.startsWith('-----BEGIN SSH SIGNATURE-----') || value.signature.length > 16384) {+ throw new Refused('BOARD_MEMBERS_INVALID', 'the board member list is not a complete signed v1 document; ask a committed approver to publish a new list');+ }+ return { body: { v: 1, board: body.board, repository: body.repository, revision: body.revision, members: [...body.members] },+ by: value.by, signature: value.signature };+}++/** Canonical bytes include every body field and the named signer, separated from device and identity proofs. */+export function boardMembersBytes(document) {+ const { body, by } = document;+ return JSON.stringify(['pullboard-board-members', { v: body.v, board: body.board, repository: body.repository,+ revision: body.revision, members: [...body.members] }, by]);+}++/** Read the current signed document, including an empty revocation list's revision. */+export function readBoardMembers(board) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('board_members');+ if (!row) return null;+ let value;+ try { value = JSON.parse(row.meta_value); } catch { throw new Refused('BOARD_MEMBERS_INVALID', 'the stored board member list is malformed; ask a committed approver to publish a new list'); }+ return boardMembersDocument(value);+}++/** Store an approver's signed list through its coordinator atomically; authorization is reverified at every key handover, never cached here. */+export function setBoardMembers(board, { agentId, document }) {+ if ((board.executionEngineVersion ?? ENGINE_VERSION) < BOARD_MEMBERS_ENGINE) throw new Refused('ENGINE_VERSION', 'update pullboard before recording board members');+ if (agentId !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'the coordinator records the approver-signed member list; publish it from the main checkout');+ const next = boardMembersDocument(document);+ return atomic(board, () => {+ const id = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('board_id')?.meta_value;+ if (next.body.board !== id) throw new Refused('BOARD_MEMBERS_INVALID', 'the signed member list names another board');+ const previous = readBoardMembers(board);+ if (previous && JSON.stringify(previous) === JSON.stringify(next)) return previous;+ if (next.body.revision !== (previous?.body.revision ?? 0) + 1) throw new Refused('BOARD_MEMBERS_REVISION', 'the board member list changed; read its current revision and sign a new list');+ 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('board_members', JSON.stringify(next));+ logEvent(board, agentId, 'board_members', null, { document: next });+ return next;+ });+}diff --git a/src/board.js b/src/board.jsindex 38819a37..9769f679 100644--- a/src/board.js+++ b/src/board.js@@ -1,3 +1,4 @@+export { readBoardMembers, setBoardMembers } from './board-members.js';import { requireFactKind } from './item-notes.js';import { activityNewsFlag } from './activity-news.js';import { migrateEventLogVersion } from './board-event-log-migrate.js';diff --git a/src/cli-main.js b/src/cli-main.jsindex 5d960fad..c8ccf302 100644--- a/src/cli-main.js+++ b/src/cli-main.js@@ -297,7 +297,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' || command === 'relay' && ['on', 'join', 'revoke', 'members'].includes(verb) && !remoteRelayOn)) {(await import('./person.js')).requirePersonChannel(io.personChannel);io.caller('person');}diff --git a/src/commands/relay.js b/src/commands/relay.jsindex f6c30fea..4c37408c 100644--- a/src/commands/relay.js+++ b/src/commands/relay.js@@ -11,6 +11,8 @@ import {Refused,} from '../refused.js';import * as relayOutput from '../relay-output.js';+import { prepareBoardMembers } from '../relay-membership.js';+import { githubKeys } from '../relay-handover.js';import {relayJoin,relayPair,@@ -29,6 +31,7 @@ import {import {relayOff,relayOn,+ relayMachineContext,relayRecover,relayRevoke,relayStatus,@@ -42,13 +45,30 @@ import {agentDisplayName,context,main,+ ordered,withBoard,+ whoAmI,} from '../cli.js';/** Run `pullboard relay` and return its exit code. */export async function run(io, { first, second, rest, values }) {if (['on', 'join'].includes(first) && gitSyncLinked(io.cwd)) throw new Refused('GIT_SYNC_LINKED', 'this board already shares moves through Git; it cannot start a second move order', 'keep using pullboard sync for this board');if (values['new-browser'] && first !== 'pair') throw new Refused('USAGE', 'pullboard relay pair --new-browser');+ if (first === 'members') {+ if (!second || second === 'clear' && rest.length || values.url || values.all || values.skip) throw new Refused('USAGE', 'pullboard relay members <login> [<login> ...], or pullboard relay members clear');+ requirePersonChannel(io.personChannel);+ const ctx = context(io);+ const state = relayMachineContext(ctx.info.root);+ if (!state || state.environment) throw new Refused('RELAY_NOT_LINKED', 'link this person’s computer before publishing board members');+ await withBoard(ctx, async board => {+ const revision = (store.readBoardMembers(board)?.body.revision ?? 0) + 1;+ const document = await prepareBoardMembers(ctx.info.root, state, second === 'clear' ? [] : [second, ...rest], { githubKeys, revision });+ await ordered(ctx, board, 'setBoardMembers', [{ agentId: whoAmI(ctx, board).id, document }]);+ io.result?.({ board: state.board, revision, members: document.body.members });+ io.say(`Board member list revision ${revision}: ${document.body.members.length ? document.body.members.join(', ') : 'no additional members'}.`);+ });+ return 0;+ }if (first === 'recover') {if (second || rest.length || !values.skip || values.url || values.all) throw new Refused('USAGE', 'pullboard relay recover --skip <exact blocked next sequence>');requirePersonChannel('terminal');diff --git a/src/help.js b/src/help.jsindex 95a987c9..c1072381 100644--- a/src/help.js+++ b/src/help.js@@ -57,6 +57,7 @@ Set uppullboard relay [status|on|off|pair|join <code>] [--url <address>] link, inspect or unlink this board's sealed relayon signs in through GitHub; the address defaults to https://app.pullboard.devpair prints a one-use machine code; join stores it in another clone+ pullboard relay members <login> [<login> ...] | clear publish an approver-signed membership listpullboard relay pair --new-browser sign in and pair one more browser; existing browsers stay pairedpullboard relay on --all [--url <address>] link every registered project after one sign-in; pair the phone oncekeep this command open until pairing finishes; later projects link on registrationdiff --git a/src/moves/setBoardMembers.js b/src/moves/setBoardMembers.jsnew file mode 100644index 00000000..1e96d10c--- /dev/null+++ b/src/moves/setBoardMembers.js@@ -0,0 +1,10 @@+/** Native signed membership routing [E17,H16]. */+import { BOARD_MEMBERS_ENGINE } from '../board-members-engine.js';+export default Object.freeze({ operation: 'setBoardMembers', engine: 1, itemIdFirstArgument: false,+ minimumEngine: () => BOARD_MEMBERS_ENGINE, actor: move => move.args[0]?.agentId ?? null,+ nextSteps: Object.freeze({+ COORDINATOR_ONLY: 'ask the coordinator to do it: pullboard shout coordinator "<what you need>"',+ BOARD_MEMBERS_INVALID: 'ask a committed approver to publish a complete signed board member list',+ BOARD_MEMBERS_REVISION: 'read the current member revision, then sign a new list',+ ENGINE_VERSION: 'upgrade Pullboard: npm install -g pullboard@latest',+ }) });diff --git a/src/next-step-defaults.js b/src/next-step-defaults.jsindex 47e70833..a933f4a1 100644--- a/src/next-step-defaults.js+++ b/src/next-step-defaults.js@@ -218,6 +218,7 @@ export const DEFAULT_NEXT_STEPS = Object.freeze({"BOARD_REPO_LINKED": "pull pullboard.json from main, which names the repository's board, then run pullboard relay on again to join it","GITHUB_UNAVAILABLE": "run any pullboard command again once GitHub answers; the new device keeps waiting","RELAY_JOIN_NOT_EMPTY": "keep this board, then run pullboard init and pullboard relay on in a fresh clone to join the team board",+ "RELAY_NOT_MEMBER": "ask a committed approver to publish the board member list with pullboard relay members <login>, then retry relay on","RELAY_KEY_VOUCH": "add the SSH key that signed this device to your GitHub account with gh ssh-key add, then run pullboard relay on again","RELAY_KEY_WAIT_EXPIRED": "run pullboard relay on again while a linked computer of this repository is online","RELAY_SSH_KEY": "make an SSH key with ssh-keygen -t ed25519, add it to GitHub with gh ssh-key add, then run pullboard relay on again",diff --git a/src/recorded-move.js b/src/recorded-move.jsindex 187175dd..a14686e8 100644--- a/src/recorded-move.js+++ b/src/recorded-move.js@@ -28,6 +28,7 @@ export function requestedCommandMove(command, operation) {refreeze: ['refreeze'], reopen: ['reopen'], escalate: ['escalate', 'shout'],next: ['claim', 'reserveReview', 'reserveNextReview'], run: ['claim', 'release', 'submit', 'reserveReview', 'reserveNextReview', 'verify', 'escalate', 'shout'],init: ['register'], join: ['register'], worktree: ['register'], takeover: ['takeCoordinator'],+ relay: ['setBoardMembers'],shout: ['shout'], answer: ['answerDecision'], pass: ['passDecision'], fact: ['appendFact'],hold: ['holdLane', 'releaseLane', 'holdItem', 'releaseItemHold'],bar: ['setBarReady', 'signBar'], settings: ['setLineSetting', 'setPersonSigning'], check: ['acceptCheck'],diff --git a/src/relay-handover.js b/src/relay-handover.jsindex d59aa3e1..69bba283 100644--- a/src/relay-handover.js+++ b/src/relay-handover.js@@ -1,17 +1,4 @@/** A member's new device gets its board key from an online member device, vouched by an SSH key on GitHub [E17]. */-import { spawnSync } from 'node:child_process';-import {- existsSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from 'node:fs';-import {- homedir,- tmpdir,-} from 'node:os';-import { join } from 'node:path';import {createDeviceKeys,unwrapDeviceBoardKey,@@ -19,6 +6,10 @@ import {} from './relay-device-keys.js';import { ENGINE_VERSION } from './machine.js';import { Refused } from './refused.js';+import { signSshVouch, verifySshVouch } from './relay-ssh-proof.js';+import { authorizeMember } from './relay-membership.js';+import { readBoardMembers } from './board-members.js';+import { localRecords } from './relay.js';const NAMESPACE = 'pullboard-device-key';const TEN_MINUTES = 10 * 60_000;@@ -27,58 +18,6 @@ const POLL_MS = 1000;/** The exact bytes an SSH key signs: the statement, domain-separated from every other signature. */export function statementBytes(statement) { return JSON.stringify([NAMESPACE, statement]); }-/** Run ssh-keygen in a private scratch folder, refusing plainly when OpenSSH is not installed. */-function sshKeygen(args, input) {- const result = spawnSync('ssh-keygen', args, { input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 30_000 });- if (result.error?.code === 'ENOENT') throw new Refused('RELAY_SSH_KEYGEN', 'ssh-keygen is not installed; install OpenSSH, then run pullboard relay on again');- return result;-}--/** Work with files in a fresh owner-only folder that is always removed. */-function scratch(work) {- const folder = mkdtempSync(join(tmpdir(), 'pullboard-vouch-'));- try { return work(folder); } finally { rmSync(folder, { recursive: true, force: true }); }-}--/** The SSH key that vouches for this device: PULLBOARD_SSH_KEY, or the usual key files under ~/.ssh. */-function signingKey(environment = process.env) {- if (environment.PULLBOARD_SSH_KEY) return environment.PULLBOARD_SSH_KEY;- const found = ['id_ed25519', 'id_ecdsa', 'id_rsa'].map(name => join(homedir(), '.ssh', name)).find(existsSync);- if (!found) throw new Refused('RELAY_SSH_KEY', 'no SSH key here vouches for this device; add one to your GitHub account with ssh-keygen -t ed25519 and gh ssh-key add, or set PULLBOARD_SSH_KEY to its path');- return found;-}--/**- * Sign the statement with the person's SSH key. With an agent running, the public half lets ssh-agent sign for a key- * with a passphrase; otherwise ssh-keygen reads the private key file itself.- */-function sshSign(bytes) {- const key = signingKey();- return scratch(folder => {- const file = join(folder, 'statement');- writeFileSync(file, bytes, { mode: 0o600 });- const tries = process.env.SSH_AUTH_SOCK && existsSync(key + '.pub') ? [key + '.pub', key] : [key];- let failure = '';- for (const signer of tries) {- const result = sshKeygen(['-Y', 'sign', '-q', '-n', NAMESPACE, '-f', signer, file]);- if (result.status === 0 && existsSync(file + '.sig')) return readFileSync(file + '.sig', 'utf8');- failure = String(result.stderr ?? '').trim().split('\n')[0];- }- throw new Refused('RELAY_SSH_SIGN', `ssh-keygen could not sign with ${key}${failure ? ' (' + failure + ')' : ''}; load the key with ssh-add, or set PULLBOARD_SSH_KEY to a key on your GitHub account`);- });-}--/** Whether one of the login's GitHub SSH keys made this signature over this exact statement. */-async function vouched(statement, signature, login, githubKeys) {- const keys = await githubKeys(login);- if (!keys.length) return false;- return scratch(folder => {- writeFileSync(join(folder, 'allowed'), keys.map(key => `${login} namespaces="${NAMESPACE}" ${key}`).join('\n') + '\n', { mode: 0o600 });- writeFileSync(join(folder, 'statement.sig'), signature, { mode: 0o600 });- return sshKeygen(['-Y', 'verify', '-f', join(folder, 'allowed'), '-I', login, '-n', NAMESPACE, '-s', join(folder, 'statement.sig')], statementBytes(statement)).status === 0;- });-}-/** Wait between polls without keeping a finished command alive. */function pause(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }@@ -94,7 +33,7 @@ export async function requestBoardKey(link, login, send, io) {const statement = { v: 1, board: link.board, repository: link.repository, device: keys.deviceId, publicKey: keys.publicKey,login, engine: ENGINE_VERSION, expires: Date.now() + TEN_MINUTES - 30_000 };const path = '/api/v1/boards/' + link.board + '/key-requests';- const posted = await send(link, path, { method: 'POST', body: { statement, signature: sshSign(statementBytes(statement)) } }, io);+ const posted = await send(link, path, { method: 'POST', body: { statement, signature: signSshVouch(statementBytes(statement), NAMESPACE) } }, io);let said = false;while (Date.now() < statement.expires) {const answer = await send(link, path + '/' + posted.id, {}, io);@@ -118,19 +57,20 @@ export async function requestBoardKey(link, login, send, io) {* person's GitHub SSH keys signed, and refuse the rest by name. GitHub being unreachable leaves a request waiting.* `send` is the relay transport and `githubKeys` reads a login's public SSH keys from GitHub.*/-export async function handOverBoardKeys(state, key, { send, githubKeys }, io) {+export async function handOverBoardKeys(state, key, { send, githubKeys, root, document = null, identity = null }, io) {const path = '/api/v1/boards/' + state.board + '/key-requests';const { requests } = await send(state, path, {}, io);for (const entry of Array.isArray(requests) ? requests : []) {const statement = entry.statement;let body;try {- if (statement?.board !== state.board || statement.repository.toLowerCase() !== String(state.repository).toLowerCase() || statement.login !== entry.login || !(statement.expires > Date.now())) {+ if (statement?.board !== state.board || typeof statement.repository !== 'string' || statement.repository.toLowerCase() !== String(state.repository).toLowerCase() || statement.login !== entry.login || !(statement.expires > Date.now())) {throw new Refused('RELAY_KEY_VOUCH', 'the key request names another board, repository or person; run pullboard relay on again in the clone');}- if (!await vouched(statement, entry.signature, entry.login, githubKeys)) {+ if (!await verifySshVouch(statementBytes(statement), entry.signature, entry.login, githubKeys, NAMESPACE)) {throw new Refused('RELAY_KEY_VOUCH', `no SSH key on ${entry.login}'s GitHub account signed this device key; add the key that signed it to GitHub with gh ssh-key add, then run pullboard relay on again`);}+ await authorizeMember(root, state, document, entry.login, { githubKeys, identity });const wrapped = await wrapDeviceBoardKey(key, statement.publicKey, { board: state.board, device: statement.device, engine: statement.engine });body = { wrapped: Buffer.from(JSON.stringify(wrapped)).toString('base64url') };} catch (error) {@@ -144,7 +84,7 @@ export async function handOverBoardKeys(state, key, { send, githubKeys }, io) {}/** The public SSH keys on a GitHub account, read from GitHub itself so the relay cannot add one. */-async function githubKeys(login) {+export async function githubKeys(login) {const base = new URL(process.env.PULLBOARD_GITHUB_API || 'https://api.github.com');if (base.protocol !== 'https:' && !(base.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname))) {throw new Refused('GITHUB_UNAVAILABLE', 'PULLBOARD_GITHUB_API must be an HTTPS address, or loopback HTTP for tests');@@ -160,8 +100,17 @@ async function githubKeys(login) {}/** Hand this board's key to member devices that asked; a failure here never fails the command that noticed [E17]. */-export async function handOverKeys(state, key, send, io) {+export async function handOverKeys(root, state, key, send, io) {delete io.keyRequestsWaiting;- try { await handOverBoardKeys(state, key, { send, githubKeys }, io); }- catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: a new device's key request waits: ${error.message}`); }+ try {+ // This proof is made with this device's local SSH key, never accepted from a relay response.+ let identity = null;+ if (typeof state.login === 'string' && state.login) {+ const body = { v: 1, board: state.board, repository: state.repository, login: state.login };+ try { identity = { body, signature: signSshVouch(JSON.stringify(['pullboard-person-identity', body]), 'pullboard-person-identity') }; }+ catch (error) { if (!(error instanceof Refused)) throw error; }+ }+ const document = localRecords(root, readBoardMembers);+ await handOverBoardKeys(state, key, { send, githubKeys, root, document, identity }, io);+ } catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: a new device's key request waits: ${error.message}`); }}diff --git a/src/relay-membership.js b/src/relay-membership.jsnew file mode 100644index 00000000..27455121--- /dev/null+++ b/src/relay-membership.js@@ -0,0 +1,57 @@+/** Membership authority comes from committed policy or exact local SSH proofs, never a relay assertion [E17]. */+import { mainPolicy } from './trusted-policy.js';+import { Refused } from './refused.js';+import { boardMembersBytes, boardMembersDocument } from './board-members.js';+import { signSshVouch, verifySshVouch } from './relay-ssh-proof.js';++const NAMESPACE = 'pullboard-board-members';+const sameLogin = (a, b) => typeof a === 'string' && typeof b === 'string' && a.toLowerCase() === b.toLowerCase();+const sameRepository = sameLogin;++/** Read only the approvers from the accepted committed policy. */+function approvers(root) {+ const list = mainPolicy(root).config.approvers;+ return Array.isArray(list) ? list : [];+}++/** Prepare the exact next revision with the local key, then independently prove its committed approver ownership. */+export async function prepareBoardMembers(root, state, logins, { githubKeys, revision, signingKey } = {}) {+ const by = state.login;+ if (!approvers(root).some(login => sameLogin(login, by))) {+ throw new Refused('NOT_APPROVER', `${by ?? 'this person'} is not a committed approver; ask an approver named in pullboard.json to publish board members`);+ }+ if (logins != null && !Array.isArray(logins)) throw new Refused('BOARD_MEMBERS_INVALID', 'board members must be a list of GitHub logins');+ const members = logins == null ? [] : [...logins];+ const unsigned = { body: { v: 1, board: state.board, repository: state.repository, revision, members }, by };+ // Validate before signing, without accepting or retaining a mutable caller container.+ const checked = boardMembersDocument({ ...unsigned, signature: '-----BEGIN SSH SIGNATURE-----\nvalidation\n' });+ const bytes = boardMembersBytes(checked);+ const signature = signSshVouch(bytes, NAMESPACE, signingKey);+ if (!await verifySshVouch(bytes, signature, by, githubKeys, NAMESPACE)) {+ throw new Refused('RELAY_KEY_VOUCH', `the signing key is not a current GitHub SSH key of committed approver ${by}; select that person's SSH key`);+ }+ return boardMembersDocument({ ...checked, signature });+}++/** Authorize a requester using only current committed policy or independently verified exact signed documents. */+export async function authorizeMember(root, state, document, login, { githubKeys, identity } = {}) {+ if (typeof login !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u.test(login)) {+ throw new Refused('RELAY_NOT_MEMBER', 'the key requester has no valid GitHub login');+ }+ const owners = approvers(root);+ if (owners.some(owner => sameLogin(owner, login))) return true;+ const body = identity?.body;+ if (body && Object.keys(identity).sort().join(',') === 'body,signature' &&+ Object.keys(body).sort().join(',') === 'board,login,repository,v' && body.v === 1 &&+ body.board === state.board && sameRepository(body.repository, state.repository) && sameLogin(body.login, login)) {+ const bytes = JSON.stringify(['pullboard-person-identity', { v: 1, board: body.board, repository: body.repository, login: body.login }]);+ if (await verifySshVouch(bytes, identity.signature, login, githubKeys, 'pullboard-person-identity')) return true;+ }+ if (document) {+ const checked = boardMembersDocument(document);+ if (checked.body.board === state.board && sameRepository(checked.body.repository, state.repository) &&+ owners.some(owner => sameLogin(owner, checked.by)) && checked.body.members.some(member => sameLogin(member, login)) &&+ await verifySshVouch(boardMembersBytes(checked), checked.signature, checked.by, githubKeys, NAMESPACE)) return true;+ }+ throw new Refused('RELAY_NOT_MEMBER', `${login} is not a trusted member of this board; a committed approver must publish a signed board member list naming ${login}`);+}diff --git a/src/relay-ssh-proof.js b/src/relay-ssh-proof.jsnew file mode 100644index 00000000..1ac391d4--- /dev/null+++ b/src/relay-ssh-proof.js@@ -0,0 +1,69 @@+/** Local SSH proofs checked against direct GitHub keys [E17]. */+import { spawnSync } from 'node:child_process';+import {+ existsSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import {+ homedir,+ tmpdir,+} from 'node:os';+import { join } from 'node:path';+import { Refused } from './refused.js';++/** Run ssh-keygen in a private scratch folder, refusing plainly when OpenSSH is not installed. */+function sshKeygen(args, input) {+ const result = spawnSync('ssh-keygen', args, { input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 30_000 });+ if (result.error?.code === 'ENOENT') throw new Refused('RELAY_SSH_KEYGEN', 'ssh-keygen is not installed; install OpenSSH, then run pullboard relay on again');+ return result;+}++/** Work with files in a fresh owner-only folder that is always removed. */+function scratch(work) {+ const folder = mkdtempSync(join(tmpdir(), 'pullboard-vouch-'));+ try { return work(folder); } finally { rmSync(folder, { recursive: true, force: true }); }+}++/** The SSH key that vouches for this device: PULLBOARD_SSH_KEY, or the usual key files under ~/.ssh. */+function signingKey(environment = process.env) {+ if (environment.PULLBOARD_SSH_KEY) return environment.PULLBOARD_SSH_KEY;+ const found = ['id_ed25519', 'id_ecdsa', 'id_rsa'].map(name => join(homedir(), '.ssh', name)).find(existsSync);+ if (!found) throw new Refused('RELAY_SSH_KEY', 'no SSH key here vouches for this device; add one to your GitHub account with ssh-keygen -t ed25519 and gh ssh-key add, or set PULLBOARD_SSH_KEY to its path');+ return found;+}++/**+ * Sign the statement with the person's SSH key. With an agent running, the public half lets ssh-agent sign for a key+ * with a passphrase; otherwise ssh-keygen reads the private key file itself.+ */+export function signSshVouch(bytes, namespace, requestedKey) {+ const key = requestedKey ?? signingKey();+ return scratch(folder => {+ const file = join(folder, 'statement');+ writeFileSync(file, bytes, { mode: 0o600 });+ const tries = process.env.SSH_AUTH_SOCK && existsSync(key + '.pub') ? [key + '.pub', key] : [key];+ let failure = '';+ for (const signer of tries) {+ const result = sshKeygen(['-Y', 'sign', '-q', '-n', namespace, '-f', signer, file]);+ if (result.status === 0 && existsSync(file + '.sig')) return readFileSync(file + '.sig', 'utf8');+ failure = String(result.stderr ?? '').trim().split('\n')[0];+ }+ throw new Refused('RELAY_SSH_SIGN', `ssh-keygen could not sign with ${key}${failure ? ' (' + failure + ')' : ''}; load the key with ssh-add, or set PULLBOARD_SSH_KEY to a key on your GitHub account`);+ });+}++/** Whether one of the login's GitHub SSH keys made this signature over this exact statement. */+export async function verifySshVouch(bytes, signature, login, githubKeys, namespace) {+ if (!/^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/u.test(login) || typeof signature !== 'string' || signature.length > 16384 || !/^[a-z0-9-]+$/u.test(namespace)) return false;+ const keys = (await githubKeys(login)).filter(key => typeof key === 'string' && /^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) [A-Za-z0-9+/=]+$/u.test(key));+ if (!keys.length) return false;+ return scratch(folder => {+ writeFileSync(join(folder, 'allowed'), keys.map(key => `${login} namespaces="${namespace}" ${key}`).join('\n') + '\n', { mode: 0o600 });+ writeFileSync(join(folder, 'statement.sig'), signature, { mode: 0o600 });+ return sshKeygen(['-Y', 'verify', '-f', join(folder, 'allowed'), '-I', login, '-n', namespace, '-s', join(folder, 'statement.sig')], bytes).status === 0;+ });+}+diff --git a/src/relay.js b/src/relay.jsindex 75171d46..a28d404d 100644--- a/src/relay.js+++ b/src/relay.js@@ -1260,7 +1260,7 @@ export async function syncRelay(root, io) {if (checkpointInBackground()) { if (state.checkpoint) scheduleCheckpoint(root, file); else requestCheckpointCheck(root, file); }else if (state.checkpoint || state.presentationDigest !== presentationDigest(relayPresentation(root))) await publishCheckpoint(root, file, state, io);await deliverDeviceWraps(root, io);- if (io.keyRequestsWaiting && !state.environment) await (await import('./relay-handover.js')).handOverKeys(state, readBoardKey(state.board), request, io); // an agent token never hands over a key+ if (io.keyRequestsWaiting && !state.environment) await (await import('./relay-handover.js')).handOverKeys(root, state, readBoardKey(state.board), request, io); // an agent token never hands over a keyreturn summary(root, state);}catch (error) {diff --git a/test/move-registry-baseline.json b/test/move-registry-baseline.jsonindex 77602445..45224d31 100644--- a/test/move-registry-baseline.json+++ b/test/move-registry-baseline.json@@ -62,7 +62,8 @@"recordJobRun","takeCoordinator","landingLeaseMove",- "recordPublishFinding"+ "recordPublishFinding",+ "setBoardMembers"],"itemIdFirstArgument": ["signBar",@@ -631,6 +632,14 @@null,null,null+ ],+ "setBoardMembers": [+ null,+ "first",+ null,+ null,+ null,+ null]},"floorCases": [@@ -6952,7 +6961,10 @@"WRONG_BOARD": "open the repository registered to this board and confirm its identity with pullboard status","WRONG_LANE": "create a worktree in the required lane with pullboard worktree <lane> --model \"<model name>\", or take an item in your lane with pullboard next","EXCLUDED_REPOSITORY": "restore the GitHub origin of each excluded project, then run pullboard relay on --all",- "EXCLUDED_INVENTORY": "restore at most 256 excluded boards and their active paired devices, then run pullboard relay on --all"+ "EXCLUDED_INVENTORY": "restore at most 256 excluded boards and their active paired devices, then run pullboard relay on --all",+ "BOARD_MEMBERS_INVALID": "ask a committed approver to publish a complete signed board member list",+ "BOARD_MEMBERS_REVISION": "read the current member revision, then sign a new list",+ "RELAY_NOT_MEMBER": "ask a committed approver to publish the board member list with pullboard relay members <login>, then retry relay on"},"replay": {"initial": {@@ -7569,6 +7581,10 @@"EXCLUDED_INVENTORY"],"qualification": "#983 adds only these2 explicitfeature recovery entries; all557 accepted8ba/f0 entries,61ops,366actors,477floors and historicalreplay remain unchanged. These two strings are explicit newfeature contract, not a regenerated snapshot from candidate execution."+ },+ "feature342": {+ "newOperation": "setBoardMembers",+ "qualification": "Only this feature operation, its six actor outcomes and three new recovery strings are added explicitly. Existing operation order, historical floors and replay captures are not regenerated; pre-existing main golden differences remain separate."}},"historicalOperations": [diff --git a/test/relay-membership.test.js b/test/relay-membership.test.jsnew file mode 100644index 00000000..fdbd7690--- /dev/null+++ b/test/relay-membership.test.js@@ -0,0 +1,64 @@+/** Signed membership uses real Git policy, native replay and OpenSSH proofs [E17,H15,H16]. */+import assert from 'node:assert/strict';+import { after, test } from 'node:test';+import { randomBytes } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import * as store from '../src/board.js';+import { exportBoard, importBoard } from '../src/exchange.js';+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';+import { seal, unseal } from '../src/seal.js';+import { prepareBoardMembers, authorizeMember } from '../src/relay-membership.js';+import { runFixtureChild } from './fixture-child.js';+import { createE2eHelpers } from './e2e-helpers.js';++const helpers = createE2eHelpers();+after(helpers.cleanup);++test('an approver signed member list survives sealed native replay and revokes by revision [H15,H16,E17]', async t => {+ const box = helpers.project();+ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));+ const replica = store.openBoard(join(box.dir, 'replica.sqlite'));+ t.after(() => { store.closeBoard(replica); store.closeBoard(board); });+ const state = { board: store.boardId(board), repository: 'fixture/repository', login: 'alice' };+ const signingKey = join(box.dir, 'alice');+ assert.equal(runFixtureChild('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', signingKey], { encoding: 'utf8' }).status, 0);+ const publicKey = readFileSync(signingKey + '.pub', 'utf8').trim().split(' ').slice(0, 2).join(' ');+ const githubKeys = async login => login === 'alice' ? [publicKey] : [];+ const configFile = join(box.repo, 'pullboard.json');+ const config = JSON.parse(readFileSync(configFile, 'utf8'));+ await assert.rejects(prepareBoardMembers(box.repo, state, ['bob'], { githubKeys, revision: 1, signingKey }),+ error => error.code === 'NOT_APPROVER', 'no approvers cannot authorize a non-approver member');+ writeFileSync(configFile, JSON.stringify({ ...config, approvers: ['alice'] }, null, 2));+ box.git(box.repo, 'add', 'pullboard.json');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: declare the independent approver');+ const document = await prepareBoardMembers(box.repo, state, ['bob'], { githubKeys, revision: 1, signingKey });+ const before = exportBoard(board);+ const move = prepareEngineMove(board, 'setBoardMembers', [{ agentId: 'coordinator', document }]);+ applyEngineMove(board, move);+ const eventCount = board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n;+ store.setBoardMembers(board, { agentId: 'coordinator', document });+ assert.equal(board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n, eventCount, 'an identical retry emits no second event');+ const key = randomBytes(32);+ const binding = { boardId: state.board, sequence: 1, kind: 'move' };+ const sealed = await seal(key, Buffer.from(JSON.stringify(move)), binding);+ importBoard(replica, before);+ applyEngineMove(replica, JSON.parse(Buffer.from(await unseal(key, sealed, binding)).toString('utf8')));+ assert.deepEqual(store.readBoardMembers(replica), document, 'native encrypted transport preserves the exact signed list');+ assert.equal(await authorizeMember(box.repo, state, store.readBoardMembers(replica), 'bob', { githubKeys }), true);+ await assert.rejects(authorizeMember(box.repo, state, { ...document, body: { ...document.body, members: ['mallory'] } }, 'mallory', { githubKeys }),+ error => error.code === 'RELAY_NOT_MEMBER', 'a board-key holder cannot change approver-signed members');+ await assert.rejects(authorizeMember(box.repo, { ...state, board: 'f'.repeat(32) }, document, 'bob', { githubKeys }),+ error => error.code === 'RELAY_NOT_MEMBER', 'the same signature authorizes no other board');+ const revoked = await prepareBoardMembers(box.repo, state, [], { githubKeys, revision: 2, signingKey });+ applyEngineMove(board, prepareEngineMove(board, 'setBoardMembers', [{ agentId: 'coordinator', document: revoked }]));+ await assert.rejects(authorizeMember(box.repo, state, store.readBoardMembers(board), 'bob', { githubKeys }),+ error => error.code === 'RELAY_NOT_MEMBER', 'the current empty revision revokes an additional member');+ assert.throws(() => store.setBoardMembers(board, { agentId: 'coordinator', document }), error => error.code === 'BOARD_MEMBERS_REVISION');+ assert.throws(() => store.setBoardMembers(board, { agentId: 'person', document: revoked }), error => error.code === 'COORDINATOR_ONLY');+ writeFileSync(configFile, JSON.stringify({ ...config, approvers: ['carol'] }, null, 2));+ box.git(box.repo, 'add', 'pullboard.json');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: replace the independent approver');+ await assert.rejects(authorizeMember(box.repo, state, document, 'bob', { githubKeys }),+ error => error.code === 'RELAY_NOT_MEMBER', 'a removed approver cannot authorize even an otherwise valid historical list');+});diff --git a/test/team.test.js b/test/team.test.jsindex 5ed79078..39013f6e 100644--- a/test/team.test.js+++ b/test/team.test.js@@ -26,6 +26,7 @@ import { relayWorkBudgetMs } from './relay-budget.js';import { hostname, tmpdir } from 'node:os';import { createDeviceKeys, unwrapDeviceBoardKey } from '../src/relay-device-keys.js';import { handOverBoardKeys, statementBytes } from '../src/relay-handover.js';+import { signSshVouch } from '../src/relay-ssh-proof.js';import { assertMatchingLandingHost, assertNoCulpritTrunkHold } from './landing-environment-fixture.js';import { landingQueueCase } from './landing-queue-fixture.js';@@ -708,7 +709,7 @@ function memberDevice(t, box, name) {}test('a clone of a linked repo joins its board; a member device hands over the key [E1,E12,E17]', { timeout: relayWorkBudgetMs(20) }, async (t) => { // budget: hang ceiling for four devices' real CLI runs, ssh-keygen and relay calls; not a speed target.- const box = await teamBoard(t, null);+ const box = await teamBoard(t, ['alice']);// Each computer has OpenSSH's ssh-keygen, and reads SSH keys from the stand-in GitHub.const tools = join(box.root, '..', 'tools-bin');mkdirSync(tools, { mode: 0o700 });@@ -717,6 +718,11 @@ test('a clone of a linked repo joins its board; a member device hands over the kassert.ok(sshKeygen, 'the test machine has OpenSSH');symlinkSync(sshKeygen, join(tools, 'ssh-keygen'));Object.assign(box.env, { PATH: tools, PULLBOARD_GITHUB_API: box.providerOrigin });+ const aliceKey = join(box.root, '..', 'alice-handover-key');+ assert.equal(runFixtureChild('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', aliceKey], { encoding: 'utf8' }).status, 0);+ box.env.PULLBOARD_SSH_KEY = aliceKey;+ const alicePublic = readFileSync(aliceKey + '.pub', 'utf8').trim().split(' ').slice(0, 2).join(' ');+ box.providerState.sshKeys = { alice: [alicePublic] };const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));const config = join(box.root, 'pullboard.json');assert.equal(JSON.parse(readFileSync(config, 'utf8')).relay?.board, link.board, 'relay on writes the board’s id into pullboard.json');@@ -742,8 +748,12 @@ test('a clone of a linked repo joins its board; a member device hands over the kassert.equal(kept.document?.error?.code, 'RELAY_JOIN_NOT_EMPTY', `a clone with work of its own is not joined over it: ${JSON.stringify(kept.document?.error ?? null)}`);assert.equal(box.auth.linkedBoards().length, 1);+ const members = await box.cli('relay', 'members', 'bob');+ assert.equal(members.code, 0, `alice publishes a real signed member list: ${members.stderr}`);+ assert.deepEqual(members.document.members, ['bob']);+// E17: a device key signed by an SSH key that is not on bob's GitHub account gets no board key.- box.providerState.sshKeys = { bob: [] };+ box.providerState.sshKeys = { alice: [alicePublic], bob: [] };const stray = memberDevice(t, box, 'bob-stray');assert.equal((await stray.cli('init')).code, 0);stray.sshKey();@@ -757,7 +767,7 @@ test('a clone of a linked repo joins its board; a member device hands over the k// E17: bob's new device, its key on his GitHub account, joins once a member device is online.const fresh = memberDevice(t, box, 'bob-new');assert.equal((await fresh.cli('init')).code, 0);- box.providerState.sshKeys = { bob: [fresh.sshKey()] };+ box.providerState.sshKeys = { alice: [alicePublic], bob: [fresh.sshKey()] };const freshOn = fresh.start('relay', 'on', '--url', box.origin);assert.equal(await freshOn.said('no member device is online'), true, 'the new device says no member is online and waits');assert.equal((await box.cli('status')).code, 0, 'alice’s computer comes online and hands the key over');@@ -1006,7 +1016,8 @@ test('a landing lease renewal or waiter poll writes no board event [Q1,Q2,Q3]',test('a non-approver device without a signed member list receives no board key [H15,E17]', async t => {const folder = mkdtempSync(join(tmpdir(), 'pullboard-handover-membership-'));t.after(() => rmSync(folder, { recursive: true, force: true }));- const state = { board: '7'.repeat(32), repository: 'fixture/repository', login: 'alice' };+ const box = helpers.project();+ const state = { board: withBoard(box.repo, store.boardId), repository: 'fixture/repository', login: 'alice' };const boardKey = randomBytes(32);/** Make an actual SSH signature and device key, independent of what the malicious relay asserts. */async function request(login) {@@ -1020,15 +1031,18 @@ test('a non-approver device without a signed member list receives no board key [writeFileSync(input, statementBytes(statement), { mode: 0o600 });const signed = runFixtureChild('ssh-keygen', ['-Y', 'sign', '-q', '-n', 'pullboard-device-key', '-f', file, input], { encoding: 'utf8' });assert.equal(signed.status, 0, "the request is genuinely signed by that login's SSH key");- return { device, publicKey: readFileSync(file + '.pub', 'utf8').trim(),+ return { device, signingKey: file, publicKey: readFileSync(file + '.pub', 'utf8').trim().split(' ').slice(0, 2).join(' '),entry: { id: login, login, statement, signature: readFileSync(input + '.sig', 'utf8') } };}const outsider = await request('bob');const member = await request('alice');+ const body = { v: 1, board: state.board, repository: state.repository, login: 'alice' };+ const identity = { body, signature: signSshVouch(JSON.stringify(['pullboard-person-identity', body]), 'pullboard-person-identity', member.signingKey) };/** Present attacker-controlled relay entries while resolving SSH ownership directly for each account. */async function answer(person) {const deliveries = [];await handOverBoardKeys(state, boardKey, {+ root: box.repo, identity,async send(_state, _path, options) {if (options.method === 'PUT') { deliveries.push(options.body); return {}; }return { requests: [person.entry] };@@ -1043,7 +1057,7 @@ test('a non-approver device without a signed member list receives no board key [JSON.parse(Buffer.from(refused.wrapped, 'base64url').toString('utf8')),{ board: state.board, device: outsider.device.deviceId, engine: PEOPLE_VERSION }) : null;assert.equal(leaked !== null && Buffer.from(leaked).equals(boardKey), false, 'the outsider cannot decrypt the actual board key');- assert.equal(refused.refused?.code, 'RELAY_KEY_VOUCH', 'a valid outsider signature cannot establish trusted board membership');+ assert.equal(refused.refused?.code, 'RELAY_NOT_MEMBER', 'a valid outsider signature cannot establish trusted board membership');assert.equal(Object.hasOwn(refused, 'wrapped'), false, 'the relay receives no key ciphertext it could unwrap as the outsider');const allowed = await answer(member);assert.ok(allowed.wrapped, 'the linked person can still bootstrap their own independently vouched device');