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): deliver signed enrollments per board [H15]
Corey Olsonc57b04104987
diff --git a/relay/person-enrollment-http.js b/relay/person-enrollment-http.jsindex 8f5dbd98..dcd8468d 100644--- a/relay/person-enrollment-http.js+++ b/relay/person-enrollment-http.js@@ -5,9 +5,17 @@ import { personEnrollmentBody } from '../src/person-enrollment.js';/** Deliver only within the authenticated account and its currently authorized boards. */export async function handlePersonEnrollment(req, res, { pathname, who, devices, authorizeBoard }) {+ if (pathname === '/api/v1/devices/person-enrollments' && req.method === 'GET') {+ if (who.kind !== 'machine') throw new Refused('HUMAN_REQUIRED', 'Discover enrollments with the linked board’s machine credential.');+ await authorizeBoard(req, who.board);+ apiJson(res, 200, { enrollments: devices.person.pending(who.user.id, who.board) });+ return true;+ }const route = /^\/api\/v1\/devices\/person-enrollments\/([A-Za-z0-9_-]{43})$/u.exec(pathname);if (!route) return false;- if (who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'Use an authenticated person session for account enrollment.');+ if (who.kind !== 'session' && !(who.kind === 'machine' && req.method === 'PUT')) {+ throw new Refused('HUMAN_REQUIRED', 'Use a person session for enrollment or the linked machine for its board’s completion.');+ }const account = who.user.id;const nonce = route[1];if (req.method === 'POST') {@@ -28,6 +36,9 @@ export async function handlePersonEnrollment(req, res, { pathname, who, devices,!/^[A-Za-z0-9_-]{1,6000}$/u.test(body.wrapped) || Buffer.from(body.wrapped, 'base64url').toString('base64url') !== body.wrapped) {throw new Refused('DEVICE_WRAP', 'Send only a versioned opaque wrap and its exact board binding.');}+ if (who.kind === 'machine' && who.board !== body.board) {+ throw new Refused('TOKEN_BOARD', 'Complete only the board bound to this machine credential.');+ }await authorizeBoard(req, body.board);apiJson(res, 200, devices.person.complete(account, nonce, body));} else throw new Refused('NO_ENDPOINT', 'Use the documented person-enrollment action.');diff --git a/relay/person-enrollment-store.js b/relay/person-enrollment-store.jsindex 2bac7073..afd27c0b 100644--- a/relay/person-enrollment-store.js+++ b/relay/person-enrollment-store.js@@ -18,7 +18,22 @@ export function createPersonEnrollmentStore({ database, now }) {if (!row.used && row.expires <= now()) throw new Refused('PERSON_ENROLL_EXPIRED', 'Create a fresh person-authenticated enrollment.');return row;}+ /** Preserve previously stored single-wrap results while new requests accumulate one result per board. */+ function results(row) {+ const value = row.wrapped ? JSON.parse(row.wrapped) : [];+ return Array.isArray(value) ? value : [value];+ }return {+ /** Discover only active requests granting this publisher’s board and still missing its result. */+ pending(account, board) {+ return db().prepare(`SELECT p.* FROM person_enrollment p+ WHERE p.account=? AND p.used=0 AND p.expires>?+ AND NOT EXISTS (SELECT 1 FROM device d WHERE d.account=p.account AND d.id=p.device AND d.revoked=1)+ AND EXISTS (SELECT 1 FROM json_each(p.payload,'$.grants') WHERE value=?)+ AND NOT EXISTS (SELECT 1 FROM json_each(CASE WHEN json_type(p.wrapped)='array' THEN p.wrapped ELSE '[]' END)+ WHERE json_extract(value,'$.board')=?) ORDER BY p.nonce LIMIT 50`)+ .all(account, now(), board, board).map(row => JSON.parse(row.payload));+ },/** Store only a signed public challenge; the native client still verifies its pinned root. */begin(account, value) {const body = personEnrollmentBody(value);@@ -49,23 +64,30 @@ export function createPersonEnrollmentStore({ database, now }) {/** Return opaque bytes only; successful delivery never changes the signed request. */read(account, nonce) {const row = entry(account, nonce);- return { enrollment: JSON.parse(row.payload), wraps: row.wrapped ? [JSON.parse(row.wrapped)] : [] };+ return { enrollment: JSON.parse(row.payload), wraps: results(row) };},- /** Atomically spend the nonce and publish one opaque wrap without reviving a revoked device. */+ /** Publish each signed grant once; only an identical active completion is an idempotent retry. */complete(account, nonce, value) {const opened = db();opened.exec('BEGIN IMMEDIATE');try {const row = entry(account, nonce);- if (row.used) throw new Refused('PERSON_ENROLL_REPLAY', 'This challenge was already consumed; use its existing opaque result.');+ if (row.expires <= now()) throw new Refused('PERSON_ENROLL_EXPIRED', 'Create a fresh person-authenticated enrollment.');const request = JSON.parse(row.payload);if (!request.grants.includes(value.board)) throw new Refused('PERSON_ENROLL_AUTH', 'Wrap only a board named in the authenticated person challenge.');const wrapped = { board: value.board, engine: value.engine, wrapped: value.wrapped };+ const completed = results(row), prior = completed.find(result => result.board === value.board);+ if (prior) {+ if (JSON.stringify(prior) !== JSON.stringify(wrapped)) throw new Refused('PERSON_ENROLL_REPLAY', 'Use the exact recorded result for this nonce and board.');+ opened.exec('COMMIT');+ return { recorded: true };+ }+ if (row.used) throw new Refused('PERSON_ENROLL_REPLAY', 'This challenge was already consumed; use its existing opaque result.');opened.prepare('INSERT INTO device(account,id) VALUES(?,?) ON CONFLICT(account,id) DO NOTHING').run(account, row.device);opened.prepare('INSERT INTO wrapped_key(account,device,board,engine,wrapped) VALUES(?,?,?,?,?) ON CONFLICT(account,device,board) DO UPDATE SET engine=excluded.engine,wrapped=excluded.wrapped').run(account, row.device, value.board, value.engine, value.wrapped);- opened.prepare('UPDATE person_enrollment SET used=1,wrapped=? WHERE account=? AND nonce=?')- .run(JSON.stringify(wrapped), account, nonce);+ opened.prepare('UPDATE person_enrollment SET used=?,wrapped=? WHERE account=? AND nonce=?')+ .run(completed.length + 1 === request.grants.length ? 1 : 0, JSON.stringify([...completed, wrapped]), account, nonce);opened.exec('COMMIT');return { recorded: true };} catch (error) { opened.exec('ROLLBACK'); throw error; }diff --git a/src/relay-machine.js b/src/relay-machine.jsindex e8df3d0f..79dc161c 100644--- a/src/relay-machine.js+++ b/src/relay-machine.js@@ -114,6 +114,21 @@ export function relayMachineOwner() {return owner ? { account: owner.account, url: owner.url } : null;}+/** Read a public root pinned through native person setup; relay replies never establish this trust. */+export function relayPersonRoot(owner) {+ const roots = readRelayMachine().personRoots ?? [];+ if (!Array.isArray(roots)) throw new Refused('RELAY_MACHINE_STORAGE', 'Restore the owner-only person-root metadata.');+ const matching = roots.filter(root => root?.account === owner.account && root.url === owner.url);+ if (!matching.length) return null;+ try {+ const root = matching[0];+ const origin = new URL(root.origin);+ if (matching.length !== 1 || origin.origin !== root.origin || !(origin.protocol === 'https:' ||+ origin.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname))) throw new Error('origin');+ return { account: root.account, url: root.url, origin: root.origin, publicKey: devicePublicKey(root.publicKey) };+ } catch { throw new Refused('RELAY_MACHINE_STORAGE', 'Restore one exact account, relay, browser origin and public person root.'); }+}+/** Serialize cross-process read-modify-write and atomically replace the private machine file. */export function updateRelayMachine(mutate) {const folder = directory();diff --git a/src/relay-person-enrollment.js b/src/relay-person-enrollment.jsnew file mode 100644index 00000000..b74aefde--- /dev/null+++ b/src/relay-person-enrollment.js@@ -0,0 +1,40 @@+/** Deliver root-authenticated enrollments without adding unrestricted legacy roster authority [H15]. */+import { authenticatePersonEnrollment } from './person-enrollment.js';+import { relayPersonRoot } from './relay-machine.js';+import { readBoardKey } from './relay-key.js';+import { wrapDeviceBoardKey } from './relay-device-keys.js';+import { ENGINE_VERSION } from './machine.js';+import { Refused } from './refused.js';++/** Verify the locally pinned root and current board before using its existing machine transport. */+export async function deliverPersonEnrollments(state, io, send) {+ const pin = relayPersonRoot(state);+ if (!pin) return;+ const path = '/api/v1/devices/person-enrollments';+ const pending = await send(state, path, { method: 'GET' }, io);+ if (!Array.isArray(pending.enrollments) || pending.enrollments.length > 50) {+ throw new Refused('RELAY_RESPONSE', 'Use the bounded account enrollment queue.');+ }+ for (const value of pending.enrollments) {+ try {+ // The signature authenticates its full grant manifest; this machine independently clamps it to its own board.+ const body = await authenticatePersonEnrollment(pin.publicKey, value, { account: state.account,+ origin: pin.origin, nonce: value?.nonce, grants: value?.grants, now: Date.now() });+ if (!body.grants.includes(state.board)) throw new Refused('PERSON_ENROLL_AUTH', 'Wrap only this machine credential’s board.');+ const status = await send(state, '/api/v1/devices/' + body.device, { method: 'GET' }, io);+ if (status.revoked === true) throw new Refused('PERSON_ENROLL_REVOKED', 'Use a non-revoked browser enrollment.');+ if (status.revoked !== false && status.revoked !== null) throw new Refused('RELAY_RESPONSE', 'Read the device’s current revocation state.');+ const wrapped = await wrapDeviceBoardKey(readBoardKey(state.board), body.publicKey,+ { board: state.board, device: body.device, engine: ENGINE_VERSION });+ if (JSON.stringify(relayPersonRoot(state)) !== JSON.stringify(pin)) {+ throw new Refused('PERSON_ENROLL_AUTH', 'The local person root changed; authenticate a fresh enrollment.');+ }+ await send(state, path + '/' + body.nonce, { method: 'PUT', body: { board: state.board,+ engine: ENGINE_VERSION, wrapped: Buffer.from(JSON.stringify(wrapped)).toString('base64url') } }, io);+ } catch (error) {+ // Untrusted public challenges must not block other valid enrollments or ordinary board synchronization.+ if (!['PERSON_ENROLL_AUTH', 'PERSON_ENROLL_EXPIRED', 'PERSON_ENROLL_REVOKED'].includes(error.code)) throw error;+ io.err?.(`pullboard: [${error.code}] ignored an invalid or revoked person enrollment; authenticate a fresh challenge`);+ }+ }+}diff --git a/src/relay.js b/src/relay.jsindex 23b1e2c1..65ddd84d 100644--- a/src/relay.js+++ b/src/relay.js@@ -5,6 +5,7 @@ import {} from './relay-snapshot-size.js';export { formatSnapshotLimit };import { beginCommandPhase } from './command-phase.js';+import { deliverPersonEnrollments } from './relay-person-enrollment.js';import { recordedMoveRefusal } from './recorded-move.js';import {publishExcludedBoards,@@ -1755,6 +1756,7 @@ export async function relayDeviceRequest(session, path, options, io) {export async function deliverDeviceWraps(root, io) {const state = loadLink(linkFile(root));if (!state || state.unlinking || !state.account) return;+ await deliverPersonEnrollments(state, io, request);const devices = readRelayMachine().devices.filter(device => device.account === state.account && device.url === state.url);if (!devices.length) return;const key = readBoardKey(state.board);diff --git a/test/person-enrollment-delivery.test.js b/test/person-enrollment-delivery.test.jsindex 5d1b16b1..5d1e9430 100644--- a/test/person-enrollment-delivery.test.js+++ b/test/person-enrollment-delivery.test.js@@ -4,8 +4,14 @@ import { createHash } from 'node:crypto';import { readFileSync } from 'node:fs';import { test } from 'node:test';import { relayClientFixture } from './relay-client-fixture.js';-import { createPersonRoot, signPersonEnrollment } from '../src/person-enrollment.js';-import { createDeviceKeys, unwrapDeviceBoardKey } from '../src/relay-device-keys.js';+import {+ createPersonRoot,+ signPersonEnrollment,+} from '../src/person-enrollment.js';+import {+ createDeviceKeys,+ unwrapDeviceBoardKey,+} from '../src/relay-device-keys.js';import { decodeBoardKey } from '../src/seal.js';import { ENGINE_VERSION } from '../src/machine.js';@@ -43,7 +49,7 @@ test('a native key holder verifies a pinned person root before delivering each gconst result = await box.script(`const { updateRelayMachine } = await import(${JSON.stringify(new URL('../src/relay-machine.js', import.meta.url).href)});updateRelayMachine(state => { state.personRoots = ${JSON.stringify(publicKey- ? [{ account: '7', url: box.origin, publicKey }] : [])}; });+ ? [{ account: '7', url: box.origin, origin: box.origin, publicKey }] : [])}; });process.stdout.write('{}');`);assert.equal(result.code, 0, 'only the private fixture public-root metadata is written');