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): authenticate person-bound account enrollment [H15]
Corey Olson9596048d7a53
diff --git a/relay/device-http.js b/relay/device-http.jsindex 1c597003..aee7bdac 100644--- a/relay/device-http.js+++ b/relay/device-http.js@@ -3,6 +3,7 @@ import { apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js'import { Refused } from '../src/refused.js';import { devicePublicKey } from '../src/relay-device-keys.js';import { approvalContext } from '../src/relay-approval.js';+import { handlePersonEnrollment } from './person-enrollment-http.js';/** Require exact bounded action fields, excluding secrets and unrecognized relay metadata. */function exact(value, fields) {@@ -22,6 +23,7 @@ export function createDeviceHandler({ authenticate, authorizeBoard, boardsFor, dif (url.search) throw new Refused('BAD_REQUEST', 'Keep device action fields out of URL queries.');const who = await authenticate(req, !['GET', 'HEAD'].includes(req.method));const account = who.user.id;+ if (await handlePersonEnrollment(req, res, { pathname: url.pathname, who, devices, authorizeBoard })) return true;if (url.pathname === '/api/v1/devices/approvals' && req.method === 'POST') {if (who.kind !== 'machine') throw new Refused('HUMAN_REQUIRED', 'request this approval with the linked board’s machine credential');await authorizeBoard(req, who.board);diff --git a/relay/device-store.js b/relay/device-store.jsindex 90af8e52..e6be3089 100644--- a/relay/device-store.js+++ b/relay/device-store.js@@ -4,6 +4,7 @@ import { join } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { Refused } from '../src/refused.js';import { approvalContext } from '../src/relay-approval.js';+import { createPersonEnrollmentStore } from './person-enrollment-store.js';/** Keep device revocations durable so an in-flight native wrap cannot recreate deleted grants. */export function createDeviceStore({ directory, now = Date.now }) {@@ -56,6 +57,7 @@ export function createDeviceStore({ directory, now = Date.now }) {return row ? { context: JSON.parse(row.context), sealed: row.sealed, state: row.state, response: row.response } : null;}return {+ person: createPersonEnrollmentStore({ database, now }),/** Bind the public session id that actually uploaded enrollment, never its bearer credential. */bindSession(principal, device, { enrollment = false } = {}) {if (principal.kind !== 'session') return;diff --git a/relay/person-enrollment-http.js b/relay/person-enrollment-http.jsnew file mode 100644index 00000000..8f5dbd98--- /dev/null+++ b/relay/person-enrollment-http.js@@ -0,0 +1,35 @@+/** Isolated transport for person-signed enrollment; legacy pairing routes keep their meaning [H15]. */+import { apiJson, readApiBody } from '../src/api-http.js';+import { Refused } from '../src/refused.js';+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 }) {+ 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.');+ const account = who.user.id;+ const nonce = route[1];+ if (req.method === 'POST') {+ const value = await readApiBody(req, { maxBytes: 8192 });+ const body = personEnrollmentBody(value);+ if (body.account !== account) throw new Refused('PERSON_ENROLL_ACCOUNT', 'Sign in to the challenge’s exact account.');+ if (body.nonce !== nonce) throw new Refused('PERSON_ENROLL_AUTH', 'Use the exact signed nonce in the enrollment address.');+ for (const board of body.grants) await authorizeBoard(req, board);+ apiJson(res, 200, devices.person.begin(account, value));+ } else if (req.method === 'GET') {+ const result = devices.person.read(account, nonce);+ for (const board of result.enrollment.grants) await authorizeBoard(req, board);+ apiJson(res, 200, result);+ } else if (req.method === 'PUT') {+ const body = await readApiBody(req, { maxBytes: 8192 });+ if (!body || Object.keys(body).sort().join(',') !== 'board,engine,wrapped' || !/^[0-9a-f]{32}$/u.test(body.board ?? '') ||+ !Number.isSafeInteger(body.engine) || body.engine < 1 || typeof body.wrapped !== 'string' ||+ !/^[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.');+ }+ 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.');+ return true;+}diff --git a/relay/person-enrollment-store.js b/relay/person-enrollment-store.jsnew file mode 100644index 00000000..90bc0725--- /dev/null+++ b/relay/person-enrollment-store.js@@ -0,0 +1,79 @@+/** Carry opaque person enrollment traffic without becoming its cryptographic trust root [H15]. */+import { Refused } from '../src/refused.js';+import { personEnrollmentBody } from '../src/person-enrollment.js';++/** Use the device store's private SQLite connection and durable revocation tombstones. */+export function createPersonEnrollmentStore({ database, now }) {+ /** Keep spent nonces permanently spent; expiry never makes an old request reusable. */+ function db() {+ const opened = database();+ opened.exec(`CREATE TABLE IF NOT EXISTS person_enrollment (+ account TEXT NOT NULL, nonce TEXT NOT NULL, device TEXT NOT NULL, expires INTEGER NOT NULL,+ payload TEXT NOT NULL, used INTEGER NOT NULL DEFAULT 0, wrapped TEXT,+ PRIMARY KEY(account,nonce));`);+ return opened;+ }+ /** Hide other accounts and reject revocation or an expired pending challenge. */+ function entry(account, nonce) {+ const row = db().prepare('SELECT * FROM person_enrollment WHERE account=? AND nonce=?').get(account, nonce);+ if (!row) throw new Refused('PERSON_ENROLL_MISSING', 'Use this account’s own person-authenticated enrollment.');+ if (db().prepare('SELECT revoked FROM device WHERE account=? AND id=?').get(account, row.device)?.revoked) {+ throw new Refused('PERSON_ENROLL_REVOKED', 'This device was revoked; authenticate a different device.');+ }+ if (!row.used && row.expires <= now()) throw new Refused('PERSON_ENROLL_EXPIRED', 'Create a fresh person-authenticated enrollment.');+ return row;+ }+ return {+ /** Store only a signed public challenge; the native client still verifies its pinned root. */+ begin(account, value) {+ const body = personEnrollmentBody(value);+ if (body.account !== account) throw new Refused('PERSON_ENROLL_ACCOUNT', 'Sign in to the challenge’s exact account.');+ if (typeof value.signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/u.test(value.signature) ||+ Buffer.from(value.signature, 'base64url').toString('base64url') !== value.signature) {+ throw new Refused('PERSON_ENROLL_AUTH', 'Send a canonical person-root signature with the public challenge.');+ }+ const opened = db();+ if (opened.prepare('SELECT 1 FROM person_enrollment WHERE account=? AND nonce=?').get(account, body.nonce)) {+ throw new Refused('PERSON_ENROLL_REPLAY', 'Use a fresh one-time person challenge.');+ }+ if (body.expires <= now() || body.expires > now() + 600_000) throw new Refused('PERSON_ENROLL_EXPIRED', 'Create a fresh challenge valid for at most ten minutes.');+ if (opened.prepare('SELECT revoked FROM device WHERE account=? AND id=?').get(account, body.device)?.revoked) {+ throw new Refused('PERSON_ENROLL_REVOKED', 'This device was revoked; authenticate a different device.');+ }+ try {+ opened.prepare('INSERT INTO person_enrollment(account,nonce,device,expires,payload) VALUES(?,?,?,?,?)')+ .run(account, body.nonce, body.device, body.expires, JSON.stringify({ ...body, signature: value.signature }));+ } catch (error) {+ if (opened.prepare('SELECT 1 FROM person_enrollment WHERE account=? AND nonce=?').get(account, body.nonce)) {+ throw new Refused('PERSON_ENROLL_REPLAY', 'Use a fresh one-time person challenge.');+ }+ throw error;+ }+ return { recorded: true };+ },+ /** 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)] : [] };+ },+ /** Atomically spend the nonce and publish one opaque wrap without reviving a revoked device. */+ 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.');+ 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 };+ 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.exec('COMMIT');+ return { recorded: true };+ } catch (error) { opened.exec('ROLLBACK'); throw error; }+ },+ };+}diff --git a/src/next-steps.js b/src/next-steps.jsindex 00d741ad..916f739f 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -257,6 +257,13 @@ export const NEXT_STEPS = Object.freeze({DEVICE_ENDPOINT: 'upgrade Pullboard on this machine and the phone, then retry',DEVICE_ENROLLMENT: 'make a fresh pairing link: pullboard relay on --all',DEVICE_ENROLL_AUTH: 'make a fresh pairing link: pullboard relay on --all',+ PERSON_ENROLL_AUTH: 'authenticate a fresh enrollment with the locally trusted person credential',+ PERSON_ENROLL_EXPIRED: 'create a fresh person-authenticated challenge valid for at most ten minutes',+ PERSON_ENROLL_REVOKED: 'authenticate a different non-revoked device with the person credential',+ PERSON_ENROLL_ACCOUNT: 'sign in to the exact account named in the person challenge',+ PERSON_ENROLL_MISSING: 'use this account’s own person-authenticated enrollment',+ PERSON_ENROLL_REPLAY: 'create a fresh one-time person challenge; do not reuse the consumed nonce',+ PERSON_ENVELOPE_AUTH: 'use the original independently retained person material and exact account envelope context',DEVICE_EXISTS: 'make a fresh pairing link: pullboard relay on --all',DEVICE_FORMAT: 'make a fresh pairing link: pullboard relay on --all',DEVICE_ID: 'list paired devices with pullboard relay devices and name one of them',diff --git a/src/person-enrollment.js b/src/person-enrollment.jsnew file mode 100644index 00000000..9cd7a3d3--- /dev/null+++ b/src/person-enrollment.js@@ -0,0 +1,115 @@+/** Verify client-held person roots without trusting relay identity assertions [H15]. */+import { Refused } from './refused.js';+import { devicePublicKey } from './relay-device-keys.js';++const encoder = new TextEncoder();++/** Encode protocol bytes canonically in browsers and Node. */+function encode(bytes) { return btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, ''); }++/** Refuse noncanonical or incorrectly sized transport bytes. */+function decode(value, length) {+ try {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/u.test(value)) throw new Error();+ const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), c => c.charCodeAt(0));+ if (bytes.length !== length || encode(bytes) !== value) throw new Error();+ return bytes;+ } catch { throw new Refused('PERSON_ENROLL_AUTH', 'Use a fresh person-authenticated enrollment with canonical public fields.'); }+}++/** Accept stable numeric account identifiers rather than mutable login names. */+function account(value) { return typeof value === 'string' && /^[1-9][0-9]{0,19}$/u.test(value); }++/** Normalize only the signed fields, never a relay-provided trust root or private key. */+export function personEnrollmentBody(value) {+ try {+ if (!value || Object.keys(value).some(k => !['v', 'account', 'device', 'publicKey', 'origin', 'nonce', 'expires', 'grants', 'signature'].includes(k)) ||+ value.v !== 1 || !account(value.account) || !/^device-[0-9a-f]{32}$/u.test(value.device ?? '') ||+ !Number.isSafeInteger(value.expires) || value.expires <= 0 || !Array.isArray(value.grants) ||+ value.grants.length < 1 || value.grants.length > 32 || value.grants.some(b => !/^[0-9a-f]{32}$/u.test(b)) ||+ new Set(value.grants).size !== value.grants.length) throw new Error();+ const origin = new URL(value.origin);+ if (origin.origin !== value.origin || origin.username || origin.password ||+ !(origin.protocol === 'https:' || origin.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname))) throw new Error();+ decode(value.nonce, 32);+ return { v: 1, account: value.account, device: value.device, publicKey: devicePublicKey(value.publicKey),+ origin: value.origin, nonce: value.nonce, expires: value.expires, grants: [...value.grants] };+ } catch { throw new Refused('PERSON_ENROLL_AUTH', 'Use a fresh person-authenticated enrollment with the exact account, device and grants.'); }+}++/** Domain-separate signatures from pairing, key wraps and other account actions. */+function signedBytes(body) { return encoder.encode(JSON.stringify(['pullboard-person-enrollment', body])); }++/** Generate the independent person root; credential unlock and recovery UI are separate work. */+export async function createPersonRoot() {+ const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']);+ return { privateKey: pair.privateKey, publicKey: devicePublicKey(await crypto.subtle.exportKey('jwk', pair.publicKey)) };+}++/** Sign only with an already unlocked client-held root, never a relay session token. */+export async function signPersonEnrollment(privateKey, value) {+ const body = personEnrollmentBody(value);+ const signature = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, signedBytes(body));+ return { ...body, signature: encode(new Uint8Array(signature)) };+}++/** Authenticate against a caller-pinned root and trusted current context before wrapping. */+export async function authenticatePersonEnrollment(trustedRoot, value, expected) {+ const body = personEnrollmentBody(value);+ if (expected?.revoked) throw new Refused('PERSON_ENROLL_REVOKED', 'Use a non-revoked person enrollment.');+ if (!Number.isSafeInteger(expected?.now) || body.expires <= expected.now || body.expires > expected.now + 600_000) {+ throw new Refused('PERSON_ENROLL_EXPIRED', 'Create a fresh person-authenticated challenge valid for at most ten minutes.');+ }+ try {+ if (body.account !== expected.account || body.origin !== expected.origin || body.nonce !== expected.nonce ||+ JSON.stringify(body.grants) !== JSON.stringify(expected.grants)) throw new Error();+ const key = await crypto.subtle.importKey('jwk', devicePublicKey(trustedRoot), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);+ if (!await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, decode(value.signature, 64), signedBytes(body))) throw new Error();+ await crypto.subtle.importKey('jwk', body.publicKey, { name: 'ECDH', namedCurve: 'P-256' }, false, []);+ return body;+ } catch { throw new Refused('PERSON_ENROLL_AUTH', 'The person signature or trusted enrollment context changed; authenticate a fresh challenge.'); }+}++/** Require an exact versioned account-vault binding; historical contexts never silently migrate. */+function envelopeContext(value) {+ if (!value || Object.keys(value).sort().join(',') !== 'account,keyId,revision' || !account(value.account) ||+ typeof value.keyId !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(value.keyId) || !Number.isSafeInteger(value.revision) || value.revision < 1) {+ throw new Refused('PERSON_ENVELOPE_AUTH', 'Use the exact account, key id and positive vault revision.');+ }+ return { account: value.account, keyId: value.keyId, revision: value.revision };+}++/** Derive a purpose-specific vault key from independently retained 256-bit person material. */+async function envelopeKey(secret, salt, context, usage) {+ if (!(secret instanceof Uint8Array) || secret.length !== 32) throw new Error('256-bit person material required');+ const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);+ return await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt,+ info: encoder.encode(JSON.stringify(['pullboard-person-vault-key', context])) }, material,+ { name: 'AES-GCM', length: 256 }, false, [usage]);+}++/** Seal a 32-byte vault key; this format supplies no browser credential or lost-key recovery. */+export async function sealAccountEnvelope(secret, vaultKey, value) {+ const context = envelopeContext(value);+ try {+ if (!(vaultKey instanceof Uint8Array) || vaultKey.length !== 32) throw new Error();+ const salt = crypto.getRandomValues(new Uint8Array(32));+ const nonce = crypto.getRandomValues(new Uint8Array(12));+ const key = await envelopeKey(secret, salt, context, 'encrypt');+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce,+ additionalData: encoder.encode(JSON.stringify(['pullboard-account-envelope', 1, context])) }, key, vaultKey);+ return { v: 1, ...context, salt: encode(salt), nonce: encode(nonce), ciphertext: encode(new Uint8Array(ciphertext)) };+ } catch { throw new Refused('PERSON_ENVELOPE_AUTH', 'Seal the vault key with independently retained 256-bit person material.'); }+}++/** Open only with independently retained material and the caller's exact expected context. */+export async function openAccountEnvelope(secret, envelope, expected) {+ const context = envelopeContext(expected);+ try {+ if (!envelope || Object.keys(envelope).sort().join(',') !== 'account,ciphertext,keyId,nonce,revision,salt,v' ||+ envelope.v !== 1 || envelope.account !== context.account || envelope.keyId !== context.keyId || envelope.revision !== context.revision) throw new Error();+ const key = await envelopeKey(secret, decode(envelope.salt, 32), context, 'decrypt');+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: decode(envelope.nonce, 12),+ additionalData: encoder.encode(JSON.stringify(['pullboard-account-envelope', 1, context])) }, key, decode(envelope.ciphertext, 48)));+ } catch { throw new Refused('PERSON_ENVELOPE_AUTH', 'The account envelope or recovery material does not match; use the original person-held material.'); }+}