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(relay): a clone of a linked repo joins its board [E1,E12,E17]
Corey Olson4b451b03ffb7
diff --git a/docs/api.md b/docs/api.mdindex 7993d6d6..68163db5 100644--- a/docs/api.md+++ b/docs/api.md@@ -535,6 +535,8 @@ Every session on a paired machine reads the board: a terminal, SSH, an agent, aA CI or cloud session that cannot pair sets `PULLBOARD_RELAY_TOKEN` to one agent token, `PULLBOARD_RELAY_KEY` to the board key and, for a relay other than app.pullboard.dev, `PULLBOARD_RELAY_URL`. In a clone with no relay link, its first command asks the relay for the token's one board, reads that board's sealed snapshot with the key and writes the local board, plus a `relay.json` marked `environment` that names the token's agent and holds neither the token nor the key. Every later command reads and moves as that agent, on that one board; a token for any other board is refused (`TOKEN_BOARD`). A clone already linked to another board keeps its `relay.json`: the environment never overwrites it, reads, `relay status` among them, go on with a `RELAY_LINKED` notice, and moves are refused. A session with both `PULLBOARD_RELAY_TOKEN` and `PULLBOARD_RELAY_KEY` uses that key as given when no key file exists: it never reads a keychain for it or writes a key file.+A repository has one team board. `relay on` writes the linked board's id into the committed `pullboard.json` as `"relay": { "board": "<id>" }` and says to commit it. The relay refuses to link a second board for a repository with `BOARD_REPO_LINKED`, naming the board it has; only `relay on` after `relay off` replaces its own earlier board, by sending `replaces` with the link. In a clone whose `pullboard.json` names a board it is not linked to, `relay on` joins that board and never links another: the clone's own board must be fresh from `init` (`RELAY_JOIN_NOT_EMPTY` otherwise), the person signs in, and the board key comes from this machine's key file when another clone here already has it. Otherwise the new device signs a fresh device key with an SSH key on the person's GitHub account (`PULLBOARD_SSH_KEY`, or `~/.ssh/id_ed25519`, `id_ecdsa` or `id_rsa`, through ssh-agent when one runs) and posts `{statement: {v, board, repository, device, publicKey, login, engine, expires}, signature}` to `POST /api/v1/boards/<board>/key-requests`, a person session only. With no member device online it says so on stderr and waits up to ten minutes. A member computer learns of a waiting request from a `KEY_REQUESTS` warning on its ordinary event read, lists them with `GET /api/v1/boards/<board>/key-requests`, reads the person's public SSH keys from GitHub itself (`PULLBOARD_GITHUB_API`, by default `https://api.github.com`), checks the signature with `ssh-keygen -Y verify` under the `pullboard-device-key` namespace, and answers with `PUT /api/v1/boards/<board>/key-requests/<id>` carrying the key wrapped to that device key alone, or `{refused: {code, message}}`, such as `RELAY_KEY_VOUCH` when no GitHub key signed it. The requester reads the answer once from `GET /api/v1/boards/<board>/key-requests/<id>`, stores the key, gets its own machine credential and restores the relay's checkpoint as its board. Only a person session or a machine credential answers or lists requests; an agent token does neither, and the relay never sees a board key.+## Sealed person requestsThe authenticated relay page calls `cockpitPage` with `readOnly: true` and the separate `requests: true` capability. This enables only the person's literal intents through the sealing transport; generic API writes remain refused. Local read-only pages and exported snapshots omit this capability and refuse every action.diff --git a/relay/auth-http.js b/relay/auth-http.jsindex be18ef5d..e864a90f 100644--- a/relay/auth-http.js+++ b/relay/auth-http.js@@ -139,7 +139,7 @@ export function createAuthHandler({ auth, publicOrigin }) {} else if (route === 'POST /auth/boards/link') {const bearer = token(req, true);const input = await body(req);- json(res, 200, { board: await auth.linkBoard(bearer, input.board, input.repository) });+ json(res, 200, { board: await auth.linkBoard(bearer, input.board, input.repository, Infinity, input.replaces ?? null) });} else if (route === 'GET /auth/machines') {json(res, 200, { machines: await auth.listMachines(token(req), url.searchParams.get('board')) });} else if (route === 'POST /auth/machines') {diff --git a/relay/auth.js b/relay/auth.jsindex dd0eb746..952a5e52 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -499,10 +499,14 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =}return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, ...(row.kind === 'machine' ? { machine: row.agent } : { agent: row.agent }) } : {}), ...(row.root ? { root: true, ...(row.lineage ? { lineage: row.lineage } : {}) } : {}), ...(repository ? { permission: repository.permission, public: repository.public } : {}), expires: row.expires };},- /** Accept a link only from a signed-in human with current repository write access. */- async linkBoard(token, board, repository, deadline = Infinity) {+ /**+ * Accept a link only from a signed-in human with current repository write access. A repository has one team+ * board: a second board for it is refused, unless this link replaces the named board after relay off [E12].+ */+ async linkBoard(token, board, repository, deadline = Infinity, replaces = null) {identifier(board, 'BAD_BOARD');repositoryName(repository);+ if (replaces !== null && replaces !== undefined) identifier(replaces, 'BAD_BOARD');const row = credential(token);if (row.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to link a board');const repo = await github.access({ id: row.user_id, login: row.login }, repository);@@ -514,6 +518,9 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =if (db.prepare('SELECT 1 FROM relay_cleanup WHERE board=?').get(board)) throw new Refused('RELAY_CLEANUP', 'finish pending board cleanup before linking again');const existing = db.prepare('SELECT * FROM relay_boards WHERE id=?').get(board);if (existing && existing.repository_id !== String(repo.id)) throw new Refused('BOARD_LINK_CONFLICT', 'use a new board identifier for a different repository');+ const other = db.prepare('SELECT id FROM relay_boards WHERE repository_id=? AND id<>? ORDER BY linked_at DESC, id').all(String(repo.id), board)+ .find((row) => row.id !== replaces && !db.prepare('SELECT 1 FROM relay_cleanup WHERE board=?').get(row.id));+ if (other) throw new Refused('BOARD_REPO_LINKED', `${repo.name} already has board ${other.id}, and a repository has one team board; pull pullboard.json from main, which names that board, then run pullboard relay on again to join it`);db.prepare('INSERT INTO relay_boards (id,repository,repository_id,linked_at,storage_account) VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET repository=excluded.repository,storage_account=COALESCE(relay_boards.storage_account,excluded.storage_account)').run(board, repo.name, String(repo.id), now(), row.user_id);permissions.delete(row.user_id + ':' + board);});diff --git a/relay/key-request-http.js b/relay/key-request-http.jsnew file mode 100644index 00000000..08b298bf--- /dev/null+++ b/relay/key-request-http.js@@ -0,0 +1,44 @@+/** HTTP boundary for board-key requests between a member's devices [E17,H15]. */+import {+ apiJson,+ apiRefusal,+ apiStatus,+ readApiBody,+} from '../src/api-http.js';+import { Refused } from '../src/refused.js';++const ROUTE = /^\/api\/v1\/boards\/([0-9a-f]{32})\/key-requests(?:\/([A-Za-z0-9_-]{22}))?$/u;++/**+ * Route key requests after the relay's normal board authorization. Only a person's sign-in asks for a key, and+ * only a person's own machine answers, so an agent token can neither request nor hand over a board key.+ */+export function createKeyRequestHandler({ authenticate, requests }) {+ return async function handleKeyRequest(req, res) {+ let url;+ try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); } catch { return false; }+ const match = ROUTE.exec(url.pathname);+ if (!match) return false;+ try {+ const [, board, id] = match;+ if (!id && req.method === 'POST') {+ const who = await authenticate(req, board, true);+ if (who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'ask for a board key from your own sign-in: run pullboard relay on in the clone');+ apiJson(res, 201, requests.publish(board, await readApiBody(req, { maxBytes: 16_384 }), who));+ } else if (!id && req.method === 'GET') {+ const who = await authenticate(req, board, false);+ if (!['machine', 'session'].includes(who.kind)) throw new Refused('HUMAN_REQUIRED', 'only a member’s linked computer hands over a board key');+ apiJson(res, 200, { requests: requests.waiting(board) });+ } else if (id && req.method === 'PUT') {+ const who = await authenticate(req, board, true);+ if (!['machine', 'session'].includes(who.kind)) throw new Refused('HUMAN_REQUIRED', 'only a member’s linked computer hands over a board key');+ apiJson(res, 200, requests.answer(board, id, await readApiBody(req, { maxBytes: 16_384 })));+ } else if (id && req.method === 'GET') {+ apiJson(res, 200, requests.read(board, id, await authenticate(req, board, false)));+ } else throw new Refused('NO_ENDPOINT', 'use POST or GET on key-requests, and PUT or GET on one request');+ } catch (error) {+ apiJson(res, apiStatus(error), apiRefusal(error));+ }+ return true;+ };+}diff --git a/relay/key-request-store.js b/relay/key-request-store.jsnew file mode 100644index 00000000..a0aa48a5--- /dev/null+++ b/relay/key-request-store.js@@ -0,0 +1,100 @@+/** Short-lived board-key requests from a member's new device; the relay never sees a board key [E17,H15]. */+import { randomBytes } from 'node:crypto';+import { Refused } from '../src/refused.js';++const TEN_MINUTES = 10 * 60_000;+const MAX_REQUESTS = 1_000;+const MAX_PER_BOARD = 20;+const BOARD = /^[0-9a-f]{32}$/u;+const ID = /^[A-Za-z0-9_-]{22}$/u;+const DEVICE = /^device-[0-9a-f]{32}$/u;+const B64 = /^[A-Za-z0-9_-]{43}$/u;+const ARMOR = /^-----BEGIN SSH SIGNATURE-----\n[A-Za-z0-9+/=\n]{40,4000}\n-----END SSH SIGNATURE-----\n?$/u;++/**+ * Check the exact statement a new device signed: its board, repository, device key and the GitHub login the+ * relay authenticated. The relay checks shape and identity only; member devices check the SSH signature.+ */+export function keyRequestStatement(value) {+ const fields = ['v', 'board', 'repository', 'device', 'publicKey', 'login', 'engine', 'expires'];+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join() !== [...fields].sort().join()+ || value.v !== 1 || !BOARD.test(value.board ?? '') || typeof value.repository !== 'string' || !/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/u.test(value.repository)+ || !DEVICE.test(value.device ?? '') || typeof value.login !== 'string' || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u.test(value.login)+ || !Number.isSafeInteger(value.engine) || value.engine < 1 || !Number.isSafeInteger(value.expires) || value.expires < 1+ || !value.publicKey || typeof value.publicKey !== 'object' || Object.keys(value.publicKey).sort().join() !== 'crv,kty,x,y'+ || value.publicKey.kty !== 'EC' || value.publicKey.crv !== 'P-256' || !B64.test(value.publicKey.x ?? '') || !B64.test(value.publicKey.y ?? '')) {+ throw new Refused('KEY_REQUEST', 'send the exact signed device-key statement; run pullboard relay on again in the clone');+ }+ return { v: 1, board: value.board, repository: value.repository, device: value.device,+ publicKey: { kty: 'EC', crv: 'P-256', x: value.publicKey.x, y: value.publicKey.y }, login: value.login, engine: value.engine, expires: value.expires };+}++/** Accept only an armored OpenSSH signature of bounded size. */+function armored(value) {+ if (typeof value !== 'string' || !ARMOR.test(value)) throw new Refused('KEY_REQUEST', 'sign the device key with ssh-keygen -Y sign; run pullboard relay on again in the clone');+ return value;+}++/** Accept a member's wrap as opaque base64url text, or a member's named refusal. */+function answer(value) {+ if (value && Object.keys(value).join() === 'wrapped' && typeof value.wrapped === 'string' && /^[A-Za-z0-9_-]{40,4000}$/u.test(value.wrapped)) return { wrapped: value.wrapped };+ if (value && Object.keys(value).join() === 'refused' && value.refused && typeof value.refused.code === 'string' && /^[A-Z0-9_]{1,64}$/u.test(value.refused.code)+ && typeof value.refused.message === 'string' && value.refused.message.length <= 500) return { refused: { code: value.refused.code, message: value.refused.message } };+ throw new Refused('KEY_REQUEST', 'answer a key request with the wrapped key or a named refusal');+}++/** Keep each request for at most ten minutes in memory; a restart only makes the new device ask again. */+export function createKeyRequestStore({ now = Date.now } = {}) {+ const records = new Map();++ /** Drop expired requests before any read or write. */+ function prune(at) {+ for (const [id, record] of records) if (at >= record.statement.expires) records.delete(id);+ }++ return Object.freeze({+ /** Record a new device's signed statement for the person the relay authenticated. */+ publish(board, body, who) {+ const at = now();+ prune(at);+ if (!body || Object.keys(body).sort().join() !== 'signature,statement') throw new Refused('KEY_REQUEST', 'send only the signed statement and its SSH signature');+ const statement = keyRequestStatement(body.statement);+ const signature = armored(body.signature);+ if (statement.board !== board) throw new Refused('KEY_REQUEST', 'the statement names another board; run pullboard relay on again in the clone');+ if (statement.login !== who.user.login) throw new Refused('KEY_REQUEST_PERSON', 'sign the statement as the GitHub account you signed in with');+ if (statement.expires <= at || statement.expires > at + TEN_MINUTES) throw new Refused('KEY_REQUEST_EXPIRED', 'make a statement valid for at most ten minutes; run pullboard relay on again');+ if (records.size >= MAX_REQUESTS || [...records.values()].filter(record => record.board === board).length >= MAX_PER_BOARD) {+ throw new Refused('KEY_REQUEST_BUSY', 'too many devices are waiting for this board; retry once one is handed its key');+ }+ const id = randomBytes(16).toString('base64url').slice(0, 22);+ records.set(id, { id, board, statement, signature, userId: who.user.id, login: who.user.login });+ return { id, expiresIn: Math.floor((statement.expires - at) / 1000) };+ },+ /** List the requests still waiting on a board, for its member devices to check and answer. */+ waiting(board) {+ prune(now());+ return [...records.values()].filter(record => record.board === board && !record.answer)+ .map(({ id, statement, signature, login }) => ({ id, statement, signature, login }));+ },+ /** Count waiting requests, so a member's ordinary sync learns of them without another call. */+ count(board) { return this.waiting(board).length; },+ /** Take a member device's answer once; the first answer wins. */+ answer(board, id, body) {+ prune(now());+ const record = ID.test(id ?? '') ? records.get(id) : undefined;+ if (!record || record.board !== board) throw new Refused('KEY_REQUEST_UNKNOWN', 'this key request expired or was answered; the new device asks again');+ if (record.answer) throw new Refused('KEY_REQUEST_ANSWERED', 'another member device already answered this request');+ record.answer = answer(body);+ return { answered: id };+ },+ /** Return the answer to the person who asked, once, and forget the request. */+ read(board, id, who) {+ prune(now());+ const record = ID.test(id ?? '') ? records.get(id) : undefined;+ if (!record || record.board !== board || record.userId !== who.user.id) throw new Refused('KEY_REQUEST_UNKNOWN', 'this key request expired; run pullboard relay on again in the clone');+ if (!record.answer) return { state: 'waiting' };+ records.delete(id);+ return record.answer.wrapped ? { state: 'delivered', wrapped: record.answer.wrapped } : { state: 'refused', refused: record.answer.refused };+ },+ });+}diff --git a/relay/service.js b/relay/service.jsindex c4143ba6..f3a3d471 100644--- a/relay/service.js+++ b/relay/service.js@@ -11,6 +11,8 @@ import { createDeviceStore } from './device-store.js';import { createDeviceHandler } from './device-http.js';import { createPairingStore } from './pairing-store.js';import { createPairingHandler } from './pairing-http.js';+import { createKeyRequestStore } from './key-request-store.js';+import { createKeyRequestHandler } from './key-request-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';@@ -180,6 +182,8 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginauthenticate: (req, { board, write }) => authorizedRequest(req, board, write),pairings: pairingStore,});+ const keyRequestStore = createKeyRequestStore({ now });+ const keyRequests = createKeyRequestHandler({ authenticate: (req, id, write) => authorizedRequest(req, id, write), requests: keyRequestStore });/** Refuse an old or ambiguous client before the opaque journal can return or accept board records. */async function authorizedRequest(req, id, write = false) {const who = await authorized(credential(req, origin, write), id, write);@@ -335,7 +339,8 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginreturn journal.after(after).map(event);}, false, board.engineVersion),warning: (board) => retention.notice(board.id),- warnings: (board) => [quota?.notice(board.id)].filter(Boolean),+ // A waiting key request rides on the member's ordinary event read, so handing a key over costs no extra call [E17].+ warnings: (board) => [quota?.notice(board.id), keyRequestStore.count(board.id) ? { code: 'KEY_REQUESTS', count: keyRequestStore.count(board.id) } : null].filter(Boolean),move: append,request: async (board, body, who) => (await append(board, body, who, 'request')).body,}, { pollMs });@@ -345,6 +350,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginif (await pagesHandler(req, res)) return;if (await deviceHandler(req, res)) return;if (await pairing(req, res)) return;+ if (await keyRequests(req, res)) return;try {if (browser && await browser(req, res)) return;let url;diff --git a/src/config.js b/src/config.jsindex 93a4afcb..b45ca9ca 100644--- a/src/config.js+++ b/src/config.js@@ -194,7 +194,8 @@ export function configProblems(config) {|| Object.keys(config.rigor).some(key => key !== 'budget'))) problems.push('"rigor" has only the optional whole number "budget", the lines of non-test code one change may add; 400 by default');if (config.relay !== undefined && (!config.relay || typeof config.relay !== 'object' || Array.isArray(config.relay)|| config.relay.outbox !== undefined && typeof config.relay.outbox !== 'boolean'- || Object.keys(config.relay).some(key => key !== 'outbox'))) problems.push('"relay" has only the optional boolean "outbox", off by default');+ || config.relay.board !== undefined && (typeof config.relay.board !== 'string' || !/^[0-9a-f]{32}$/u.test(config.relay.board))+ || Object.keys(config.relay).some(key => !['outbox', 'board'].includes(key)))) problems.push('"relay" has only the optional boolean "outbox", off by default, and "board", the linked board id relay on writes');if (config.approvers !== undefined && (!Array.isArray(config.approvers) || config.approvers.length > 50 || new Set(config.approvers).size !== config.approvers.length|| config.approvers.some((login) => typeof login !== 'string' || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u.test(login)))) problems.push('"approvers" lists the GitHub logins who act as the person on a linked board, at most fifty; leave it out for today\'s behaviour');if (!['inside', 'beside'].includes(config.worktrees)) problems.push('"worktrees" is "inside" or "beside"');diff --git a/src/relay-board-config.js b/src/relay-board-config.jsnew file mode 100644index 00000000..dbd10c64--- /dev/null+++ b/src/relay-board-config.js@@ -0,0 +1,41 @@+/** pullboard.json names the repository's linked board, so every clone finds it [E12]. */+import { isDeepStrictEqual } from 'node:util';+import {+ existsSync,+ readFileSync,+ writeFileSync,+} from 'node:fs';+import { join } from 'node:path';+import {+ CONFIG_FILE,+ loadConfig,+} from './config.js';++/** The board id this checkout's pullboard.json names, or null. */+export function namedBoard(root) {+ if (!existsSync(join(root, CONFIG_FILE))) return null;+ return loadConfig(root).relay?.board ?? null;+}++/**+ * Write the linked board's id into pullboard.json as "relay": { "board": ... }. The edit is textual, so the person's+ * layout survives; if the text is laid out in a way the edit cannot follow, the file is written out plainly instead.+ */+export function writeNamedBoard(root, board) {+ const file = join(root, CONFIG_FILE);+ if (!existsSync(file)) return false;+ const text = readFileSync(file, 'utf8');+ const value = JSON.parse(text);+ if (value.relay?.board === board) return false;+ const expected = { ...value, relay: { ...(value.relay ?? {}), board } };+ const entry = `"board": ${JSON.stringify(board)}`;+ const edited = value.relay === undefined+ ? text.replace(/^\{(\s*)/u, (_, gap) => `{${gap || '\n '}"relay": { ${entry} },${gap || '\n '}`)+ : value.relay.board === undefined+ ? text.replace(/("relay"\s*:\s*\{)(\s*)/u, (_, open, gap) => `${open}${gap || ' '}${entry}${Object.keys(value.relay).length ? ',' : ''}${gap || ' '}`)+ : text.replace(/("relay"\s*:\s*\{[^{}]*"board"\s*:\s*)"[0-9a-f]{32}"/u, (_, head) => head + JSON.stringify(board));+ let parsed;+ try { parsed = JSON.parse(edited); } catch { parsed = undefined; }+ writeFileSync(file, isDeepStrictEqual(parsed, expected) ? edited : JSON.stringify(expected, null, 2) + '\n');+ return true;+}diff --git a/src/relay-handover.js b/src/relay-handover.jsnew file mode 100644index 00000000..0d76cd26--- /dev/null+++ b/src/relay-handover.js@@ -0,0 +1,159 @@+/** 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,+ wrapDeviceBoardKey,+} from './relay-device-keys.js';+import { ENGINE_VERSION } from './machine.js';+import { Refused } from './refused.js';++const NAMESPACE = 'pullboard-device-key';+const TEN_MINUTES = 10 * 60_000;+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`);+ });+}++/** The public SSH keys on a GitHub account, read from GitHub itself so the relay cannot add one. */+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');+ }+ let keys;+ try {+ const response = await fetch(new URL('users/' + encodeURIComponent(login) + '/keys', base.href.endsWith('/') ? base : base.href + '/'),+ { headers: { accept: 'application/vnd.github+json' }, redirect: 'error', signal: AbortSignal.timeout(10_000) }); // budget: one GitHub read, the same ceiling as a relay request.+ if (!response.ok) throw new Error(String(response.status));+ keys = await response.json();+ } catch { throw new Refused('GITHUB_UNAVAILABLE', `could not read ${login}'s SSH keys from GitHub; the key request waits for the next command`); }+ return (Array.isArray(keys) ? keys : []).map(entry => entry?.key).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));+}++/** Whether one of the login's GitHub SSH keys made this signature over this exact statement. */+async function vouched(statement, signature, login) {+ 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)); }++/**+ * Ask the repository's board for its key from this new device: sign a fresh device key with the person's SSH key, then+ * wait until a member device hands the key over, wrapped to that device key alone. `link` carries the relay url and+ * the person's own sign-in token; `send` is the relay transport.+ *+ * @returns {Promise<Uint8Array>} the board key+ */+export async function requestBoardKey(link, login, send, io) {+ const keys = await createDeviceKeys();+ 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);+ let said = false;+ while (Date.now() < statement.expires) {+ const answer = await send(link, path + '/' + posted.id, {}, io);+ if (answer.state === 'delivered') {+ return unwrapDeviceBoardKey(keys.privateKey, JSON.parse(Buffer.from(answer.wrapped, 'base64url').toString('utf8')),+ { board: link.board, device: keys.deviceId, engine: ENGINE_VERSION });+ }+ if (answer.state === 'refused') throw new Refused(answer.refused.code, answer.refused.message.replace(/^\[[A-Z0-9_]+\] /u, ''));+ if (!said) {+ said = true;+ // A live wait line, like the sign-in prompt: it reaches the terminal even when the result is JSON.+ (io.stderr ?? process.stderr).write(`pullboard: no member device is online to hand over the key for board ${link.board.slice(0, 8)}; waiting. Any pullboard command on a linked computer of this repository hands it over. Ctrl-C stops; run pullboard relay on again later.\n`);+ }+ await pause(POLL_MS);+ }+ throw new Refused('RELAY_KEY_WAIT_EXPIRED', 'no member device handed over the board key within ten minutes; run pullboard relay on again while a linked computer of this repository is online');+}++/**+ * On a member device, answer every waiting key request for this board: wrap the key to a device key that one of the+ * person's GitHub SSH keys signed, and refuse the rest by name. GitHub being unreachable leaves a request waiting.+ */+export async function handOverBoardKeys(state, key, send, 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 !== state.repository || 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)) {+ 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`);+ }+ 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) {+ if (!(error instanceof Refused)) throw error;+ if (error.code === 'GITHUB_UNAVAILABLE') { io.err('pullboard: ' + error.message); continue; }+ body = { refused: { code: error.code, message: error.message } };+ }+ await send(state, path + '/' + entry.id, { method: 'PUT', body }, io);+ io.err(body.wrapped ? `pullboard: handed this board's key to a new device of ${entry.login}` : `pullboard: refused a new device of ${entry.login}: ${body.refused.message}`);+ }+}diff --git a/src/relay-join.js b/src/relay-join.jsnew file mode 100644index 00000000..344368f8--- /dev/null+++ b/src/relay-join.js@@ -0,0 +1,83 @@+/** relay on in a clone joins the board its pullboard.json names, and never links a second one [E12,E17]. */+import { hostname } from 'node:os';+import { join } from 'node:path';+import * as store from './board.js';+import {+ importBoard,+ isInitialBoard,+} from './exchange.js';+import { appliedSequence } from './engine.js';+import {+ codeIsFromMain,+ repoInfo,+} from './git.js';+import {+ forgetBoardKey,+ readBoardKey,+ storeBoardKey,+} from './relay-key.js';+import { requestBoardKey } from './relay-handover.js';+import { updateRelayMachine } from './relay-machine.js';+import { listApiProjects } from './projects.js';+import { Refused } from './refused.js';+import {+ localRecords,+ relayPersonCoordinator,+ relayStatus,+ request,+ restoreCheckpoint,+ saveLink,+ syncRelay,+} from './relay.js';++const TOKEN = /^pm_[A-Za-z0-9_-]{43}$/u;++/** Refuse a clone whose board already holds work before asking anyone for a key: joining would hide it. */+function requireFreshBoard(root, board) {+ const local = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });+ try {+ if (!isInitialBoard(local)) {+ throw new Refused('RELAY_JOIN_NOT_EMPTY', `pullboard.json names board ${board.slice(0, 8)}, but this clone's own board already holds work`,+ 'keep this board, and run pullboard init then pullboard relay on in a fresh clone to join the team board');+ }+ } finally { store.closeBoard(local); }+}++/** This device's copy of the board key: already here for another clone on this machine, or handed over by a member. */+async function boardKey(link, login, io) {+ try { return { key: readBoardKey(link.board), stored: false }; } catch (error) { if (error.code !== 'RELAY_KEY_MISSING') throw error; }+ const key = Buffer.from(await requestBoardKey(link, login, request, io));+ return { key, stored: storeBoardKey(link.board, key) };+}++/**+ * Join the named board: the person signs in, a member device hands over the key, the relay issues this machine its own+ * credential, and the relay's checkpoint becomes this clone's board, as a pairing would bring it.+ */+export async function joinNamedBoard(root, file, { board, url, repository, signIn }, io) {+ requireFreshBoard(root, board);+ const signed = await signIn();+ const login = signed.login ?? signed.user?.login;+ const account = signed.account ?? signed.user?.id;+ const { key, stored } = await boardKey({ url, board, repository, token: signed.token }, login, io);+ try {+ const machine = updateRelayMachine(settings => settings.machine);+ const issued = await request({ url, board, token: signed.token }, '/auth/machines', { method: 'POST', body: { board, machine, host: hostname() } }, io);+ if (!TOKEN.test(issued.token ?? '') || issued.board !== board || issued.machine !== machine) throw new Refused('RELAY_RESPONSE', 'the relay did not issue this board’s machine credential; sign in again');+ const state = { version: 1, mode: 'ordered', board, url, repository, token: issued.token, tokenId: issued.id, machine, account,+ ...(typeof login === 'string' && login ? { login } : {}), keyStorage: stored || 'file', sequence: 0, cursor: 0, baselineAccepted: true };+ await restoreCheckpoint(root, state, io, key, (local, native) => importBoard(local, native));+ state.sequence = localRecords(root, appliedSequence);+ state.cursor = localRecords(root, (local) => local.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id);+ saveLink(file, state);+ } catch (error) {+ if (stored) { try { forgetBoardKey(board, stored); } catch { /* The original refusal is the useful next step. */ } }+ throw error;+ }+ await relayPersonCoordinator(root, signed.token, io);+ await syncRelay(root, io);+ const name = listApiProjects().find(project => project.root === repoInfo(root).root)?.name ?? repository;+ const result = { ...relayStatus(root), notice: `Joined ${name}: this clone works on board ${board.slice(0, 8)}, the one pullboard.json names.` };+ io.err(result.notice);+ return result;+}diff --git a/src/relay.js b/src/relay.jsindex e60cf365..41ed912d 100644--- a/src/relay.js+++ b/src/relay.js@@ -71,6 +71,11 @@ import {withSeatName,} from './relay-seats.js';import { syncApprovers } from './relay-approvers.js';+import {+ namedBoard,+ writeNamedBoard,+} from './relay-board-config.js';+import { handOverBoardKeys } from './relay-handover.js';import { ENGINE_VERSION } from './machine.js';import {presentationDigest,@@ -967,6 +972,7 @@ async function catchUp(root, file, state, io) {if (localRecords(root, appliedSequence) <= after) throw new Refused('RELAY_RESPONSE', 'the relay checkpoint did not advance the missing prefix; fetch a consistent newer snapshot');return catchUp(root, file, state, io);}+ if ([remote.warning, ...(remote.warnings ?? [])].some((warning) => warning?.code === 'KEY_REQUESTS')) KEY_REQUESTS_SEEN.add(io);if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string')) {throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid ordered prefix; fetch a consistent relay snapshot');}@@ -1257,6 +1263,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 (KEY_REQUESTS_SEEN.has(io) && !state.environment) await handOverKeys(state, io); // an agent token never hands over a keyreturn summary(root, state);}catch (error) {@@ -1277,6 +1284,16 @@ export async function syncRelay(root, io) {}, io);}+/** Commands whose event read named a new device waiting for this board's key. */+const KEY_REQUESTS_SEEN = new WeakSet();++/** Hand this board's key to member devices that asked; a failure here never fails the command that noticed [E17]. */+async function handOverKeys(state, io) {+ KEY_REQUESTS_SEEN.delete(io);+ try { await handOverBoardKeys(state, readBoardKey(state.board), request, io); }+ catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: a new device's key request waits: ${error.message}`); }+}+/** Return token-management context without opening a board-key pairing link or exposing any credential. */function tokenContext(state) {return { linked: true, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, recovery: recoverySummary(state) };@@ -1575,6 +1592,14 @@ export async function relayOn(root, address, io, { session, credential, quiet =for (const project of listApiProjects()) { try { loadLink(linkFile(project.root)); } catch { /* Report this command's own link below. */ } }const repository = originRepository(root);const file = linkFile(root);+ // A clone whose pullboard.json names another board joins that board instead of linking a second one [E12].+ const named = loadLink(file) ? null : namedBoard(repoInfo(root).root);+ const relinking = relayRelink(root);+ if (named && named !== localRecords(root, store.boardId) && relinking?.previous !== named && relinking?.next !== named) {+ const url = relayOrigin(address || DEFAULT_RELAY);+ const { joinNamedBoard } = await import('./relay-join.js');+ return joinNamedBoard(root, file, { board: named, url, repository, signIn: () => deviceSignIn(url, io) }, io);+ }return locked(file, async () => {let state = loadLink(file);if (state) requireUnconflictedBaseline(state);@@ -1601,7 +1626,7 @@ export async function relayOn(root, address, io, { session, credential, quiet =cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, baselineCursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0,baselineAccepted: false, linkPending: true };state.snapshot = { sequence: 0, sealed: await sealedRecord(key, snapshot.document, state, 'snapshot', 0) };- if (relink) state.previousBoardNotice = relink.previous;+ if (relink) { state.previousBoardNotice = relink.previous; state.replaces = relink.previous; }}const account = signed.account ?? signed.user?.id;// Persist the exact sealed snapshot and a recoverable link intent before making the remote link.@@ -1609,10 +1634,19 @@ export async function relayOn(root, address, io, { session, credential, quiet =if (relink) finishRelink(root);if (state.linkPending) {if (signed.linkConfirmed && signed.linkedBoard !== state.board) throw new Refused('RELAY_RESPONSE', 'the relay confirmed a different board; sign in again');- if (!reusableCredential && !signed.linkConfirmed) await request({ ...state, token: signed.token }, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository } }, io);+ try {+ if (!reusableCredential && !signed.linkConfirmed) await request({ ...state, token: signed.token }, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository, ...(state.replaces ? { replaces: state.replaces } : {}) } }, io);+ } catch (error) {+ // The repository's board is another one: forget this never-linked intent, so relay on can join that board [E12].+ if (error.code === 'BOARD_REPO_LINKED') { rmSync(file, { force: true }); try { forgetBoardKey(state.board, state.keyStorage); } catch { /* The refusal names the next step. */ } }+ throw error;+ }delete state.linkPending;+ delete state.replaces;saveLink(file, state);}+ // Every clone of the repository finds its board in the committed pullboard.json [E12].+ if (writeNamedBoard(repoInfo(root).root, state.board)) io.err(`pullboard: pullboard.json now names board ${state.board.slice(0, 8)}; commit it so every clone of this repository joins this board`);const machine = updateRelayMachine(settings => settings.machine);const issued = reusableCredential ?? await request({ ...state, token: signed.token }, '/auth/machines', { method: 'POST', body: { board: state.board, machine } }, io);if (!/^pm_[A-Za-z0-9_-]{43}$/u.test(issued.token ?? '') || issued.board !== state.board || issued.machine !== machine) throw new Refused('RELAY_RESPONSE', 'the relay did not issue this board’s machine credential; sign in again');diff --git a/src/settings-inventory.js b/src/settings-inventory.jsindex 8cc0ec9a..168a22f4 100644--- a/src/settings-inventory.js+++ b/src/settings-inventory.js@@ -35,7 +35,7 @@ const MACHINE_DEFAULTS = {};const OPTIONAL_REPO_DEFAULTS = {project: null, name: null, 'checks.provesNothing': 'warn', 'verify.unrelatedTrunkMoves': false, 'verify.composeAtAdmission': false,- 'flakes.rerun': false, 'flakes.quarantine': false, 'rigor.budget': 400, 'relay.outbox': false,+ 'flakes.rerun': false, 'flakes.quarantine': false, 'rigor.budget': 400, 'relay.outbox': false, 'relay.board': null,submitGate: null, submitDeferAbove: null, landingShards: 1, 'landing.publish': null, 'landing.environment': null, positiveControl: null, affectedTests: null,'health.sentinel': true, 'testConcurrency.browser': 2, approvers: null,};diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 7852b8d5..04b9707b 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -753,7 +753,10 @@ globalThis.fetch = function tracedFetch(input, init) {const run = (...args) => childResult(nextRoot, nextEnv, [CLI, ...args, '--json']);assert.equal(runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: nextRoot, env: nextEnv, encoding: 'utf8' }).status, 0);assert.equal((await run('init')).code, 0);- assert.equal(runFixtureChild('git', ['remote', 'add', 'origin', '[email protected]:fixture/repository.git'], { cwd: nextRoot, env: nextEnv, encoding: 'utf8' }).status, 0);+ // Its own repository: the relay links one team board per repository [E12].+ const repository = 'repository-' + (provider.state.repositories.length + 1);+ provider.state.repositories.push(repository);+ assert.equal(runFixtureChild('git', ['remote', 'add', 'origin', `[email protected]:fixture/${repository}.git`], { cwd: nextRoot, env: nextEnv, encoding: 'utf8' }).status, 0);assert.equal((await run('add', lane, title)).code, 0);assert.equal((await run('relay', 'on', '--url', origin)).code, 0);const state = JSON.parse(readFileSync(join(nextRoot, '.git', 'pullboard', 'relay.json'), 'utf8'));@@ -766,7 +769,7 @@ globalThis.fetch = function tracedFetch(input, init) {return childResult(root, env, ['--input-type=module', '-e', source]);}return {- transit, providerState: provider.state, providerCalls: provider.calls, relayDirectory: join(scratch, 'relay'), authDatabase, auth, otherDeviceJoin,+ transit, providerState: provider.state, providerCalls: provider.calls, providerOrigin: provider.origin, relayDirectory: join(scratch, 'relay'), authDatabase, auth, otherDeviceJoin,root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, startCli, waitForResponse, holdNextConfirmationStatus, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,/** Assert the test consumed every declared child budget, with no hidden CLI calls. */assertCliChildrenComplete() {diff --git a/test/relay-fixture.js b/test/relay-fixture.jsindex 9af90176..fa17a6e4 100644--- a/test/relay-fixture.js+++ b/test/relay-fixture.js@@ -97,6 +97,9 @@ export async function githubFixture(t) {const login = userTokens.get(bearer) ?? 'fixture-user';return reply(res, isUser ? 200 : 401, { id: state.people?.[login]?.id ?? state.accountID, login });}+ // The public SSH keys on an account, as GitHub lists them; state.sshKeys maps a login to its key lines [E17].+ const keysOf = /^\/users\/([^/]+)\/keys$/u.exec(url.pathname)?.[1];+ if (keysOf) return reply(res, 200, (state.sshKeys?.[decodeURIComponent(keysOf)] ?? []).map((key, index) => ({ id: index + 1, key })));const repositoryPath = url.pathname.match(/^\/repos\/fixture\/([^/]+)(?:\/(.*))?$/u);const repositoryName = repositoryPath?.[1];const allowedRepository = state.repositories.includes(repositoryName);diff --git a/test/team.test.js b/test/team.test.jsindex 3a2516ce..2ff532e9 100644--- a/test/team.test.js+++ b/test/team.test.js@@ -663,6 +663,115 @@ test('a board that names no approvers takes person moves as before [E4]', { timeassert.notEqual((await receivedRequests(box))[fromBob].status, 'refused', 'any writer’s session answers as the person, as today');});+/** Another computer of a person: its own HOME, ~/.ssh and a fresh clone of the fixture repository. */+function memberDevice(t, box, name) {+ const home = join(box.root, '..', name + '-home');+ const root = join(box.root, '..', name + '-clone');+ mkdirSync(join(home, '.ssh'), { recursive: true, mode: 0o700 });+ runFixtureGit(['clone', '-q', box.root, root], { cwd: box.root, env: box.env });+ runFixtureGit(['remote', 'set-url', 'origin', '[email protected]:fixture/repository.git'], { cwd: root, env: box.env });+ const env = { ...box.env, HOME: home, PULLBOARD_HOME: join(home, '.pullboard'), PULLBOARD_MACHINE_HOME: join(home, 'machine') };+ delete env.PULLBOARD_MODEL;+ const device = { root, env, home, cli: (...args) => relayFixtureChild(root, env, [CLI, ...args, '--json']) };+ /** Generate this device's SSH key, as ssh-keygen -t ed25519 does, and return its public line. */+ device.sshKey = () => {+ const made = childProcess.spawnSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', name, '-f', join(home, '.ssh', 'id_ed25519')], { env, encoding: 'utf8' });+ assert.equal(made.status, 0, `ssh-keygen makes the device's key: ${made.stderr}`);+ return readFileSync(join(home, '.ssh', 'id_ed25519.pub'), 'utf8').trim().split(' ').slice(0, 2).join(' ');+ };+ /** Start a command that waits, and resolve said(text) once its stderr carries text. */+ device.start = (...args) => {+ const child = childProcess.spawn(process.execPath, [CLI, ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ let stderr = '';+ const waiting = [];+ child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });+ child.stderr.setEncoding('utf8').on('data', (part) => { stderr += part; for (const waiter of [...waiting]) waiter(); });+ const closed = new Promise((resolve) => child.once('close', (code) => {+ let document;+ try { document = JSON.parse(stdout); } catch { document = null; }+ for (const waiter of [...waiting]) waiter();+ resolve({ code, stderr, document });+ }));+ t.after(() => child.kill('SIGKILL'));+ /** Resolve once stderr carries the text, or the command has closed. */+ const said = (text) => new Promise((resolve) => {+ const check = () => { if (stderr.includes(text) || child.exitCode !== null) { waiting.splice(waiting.indexOf(check), 1); resolve(stderr.includes(text)); } };+ waiting.push(check);+ check();+ });+ return { closed, said };+ };+ return device;+}++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);+ // 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 });+ for (const name of readdirSync(box.env.PATH)) symlinkSync(join(box.env.PATH, name), join(tools, name));+ const sshKeygen = childProcess.spawnSync('sh', ['-c', 'command -v ssh-keygen'], { encoding: 'utf8' }).stdout.trim();+ assert.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 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');+ assert.equal((await box.cli('add', box.lane, 'Health endpoint')).code, 0);++ // S5: a clone made before pullboard.json named the board links no second board for the repository.+ const early = memberDevice(t, box, 'bob-early');+ assert.equal((await early.cli('init')).code, 0);+ assert.equal((await early.cli('add', box.lane, 'Health endpoint')).code, 0);+ box.providerState.signer = 'bob';+ const split = await early.cli('relay', 'on', '--url', box.origin);+ assert.equal(split.document?.error?.code, 'BOARD_REPO_LINKED', `the relay refuses a second board for the repository: ${JSON.stringify(split.document?.error ?? null)}`);+ assert.match(split.document.error.message + ' ' + split.document.error.next, new RegExp(link.board + '[\\s\\S]*pullboard.json'), 'the refusal names the board and where a clone finds it');+ assert.equal(box.auth.linkedBoards().length, 1, 'the relay holds one board for the repository');+ assert.equal(existsSync(join(early.root, '.git', 'pullboard', 'relay.json')), false, 'the refused clone keeps no half-made link');++ // Once pullboard.json names the board, that clone keeps its own work rather than hide it under the team board.+ runFixtureGit(['add', 'pullboard.json'], { cwd: box.root, env: box.env });+ runFixtureGit(['-c', 'core.hooksPath=/dev/null', 'commit', '-q', '-m', 'chore: name the relay board'], { cwd: box.root, env: box.env });+ rmSync(join(early.root, 'pullboard.json')); // the clone's own init wrote it before the repository carried one+ runFixtureGit(['pull', '-q', '--no-rebase', box.root, 'HEAD'], { cwd: early.root, env: early.env });+ const kept = await early.cli('relay', 'on', '--url', box.origin);+ assert.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);++ // 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: [] };+ const stray = memberDevice(t, box, 'bob-stray');+ assert.equal((await stray.cli('init')).code, 0);+ stray.sshKey();+ const strayOn = stray.start('relay', 'on', '--url', box.origin);+ assert.equal(await strayOn.said('no member device is online'), true, 'with no member online the new device says so and waits');+ assert.equal((await box.cli('status')).code, 0, 'alice’s computer comes online');+ const refused = await strayOn.closed;+ assert.equal(refused.document?.error?.code, 'RELAY_KEY_VOUCH', `the member device refuses a key no GitHub SSH key vouches for: ${refused.stderr}`);+ assert.equal(existsSync(join(stray.env.PULLBOARD_HOME, 'relay-keys', link.board + '.key')), false, 'the stray device holds no board key');++ // 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()] };+ 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');+ const joined = await freshOn.closed;+ box.providerState.signer = 'alice';+ assert.equal(joined.code, 0, `relay on in the clone joins the board: ${joined.stderr}`);+ assert.equal(JSON.parse(readFileSync(join(fresh.root, '.git', 'pullboard', 'relay.json'), 'utf8')).board, link.board, 'the clone works on the board pullboard.json names');+ assert.equal(box.auth.linkedBoards().length, 1, 'joining never links another board');+ const listed = await fresh.cli('list', '--all');+ assert.ok(listed.document.items.some((item) => (item.title ?? item.item_title) === 'Health endpoint'), 'the joined clone reads the team board');+ assert.equal((await fresh.cli('takeover')).code, 0, 'bob’s main checkout takes the one coordinator [E19]');+ const freshAdd = await fresh.cli('add', box.lane, 'From bob’s new computer');+ assert.equal(freshAdd.code, 0, `the joined clone moves on the team board: ${JSON.stringify(freshAdd.document?.error ?? null)}`);+ assert.equal((await box.cli('takeover')).code, 0, 'alice’s main checkout takes the coordinator back');+ assert.ok((await box.cli('export')).document.tables.item.some((item) => item.item_title === 'From bob’s new computer'), 'one board, one order: alice reads bob’s move');+});/** Every file under a directory, so a test can prove no secret was written anywhere in it. */function filesUnder(directory) {