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(relay): restore environment key fallback [H15,H17]
Corey Olsond5b83b076c05
diff --git a/src/relay-key.js b/src/relay-key.jsindex b32ed80c..6c4add4b 100644--- a/src/relay-key.js+++ b/src/relay-key.js@@ -63,7 +63,7 @@ export function storeBoardKey(boardId, key) {return 'file';}-/** Read a board key only from this device's private file or operating-system keychain. */+/** Read a board key from device storage or a canonical local environment secret for unpaired agents. */export function readBoardKey(boardId) {const id = identity(boardId);const file = keyFile(id);@@ -80,7 +80,8 @@ export function readBoardKey(boardId) {const found = spawnSync(service, args, { encoding: 'utf8', timeout: 10000 });if (found.status === 0) return decodeBoardKey(found.stdout.trim());}- throw new Refused('RELAY_KEY_MISSING', 'the board key is missing on this device; pair this device again, or run pullboard relay off then relay on to upload a new sealed snapshot');+ if (process.env.PULLBOARD_RELAY_KEY !== undefined) return decodeBoardKey(process.env.PULLBOARD_RELAY_KEY);+ throw new Refused('RELAY_KEY_MISSING', 'the board key is missing on this device; set PULLBOARD_RELAY_KEY from your local secret store, pair this device again, or run pullboard relay off then relay on to upload a new sealed snapshot');}/** Remove the device key after a successful unlink, leaving all local board records untouched. */diff --git a/test/pairing.test.js b/test/pairing.test.jsindex 2f7912be..36d8e132 100644--- a/test/pairing.test.js+++ b/test/pairing.test.js@@ -1,11 +1,13 @@/** One-time pairing keeps its secret off the relay and rejects replay or expiry [H15,H17]. */import assert from 'node:assert/strict';+import { randomBytes, webcrypto } from 'node:crypto';import { createServer } from 'node:http';import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';import { createPairingCode, openPairingBundle, parsePairingCode, sealPairingBundle } from '../src/pairing.js';+import { decodeBoardKey } from '../src/seal.js';import { createPairingStore } from '../relay/pairing-store.js';import { createPairingHandler } from '../relay/pairing-http.js';import { createRelayHandler } from '../relay/service.js';@@ -13,6 +15,7 @@ import { Refused } from '../src/refused.js';import { relayClientFixture } from './relay-client-fixture.js';const BOARD = '0123456789abcdef0123456789abcdef';+const OTHER_BOARD = 'fedcba9876543210fedcba9876543210';/** Serve only the pairing adapter on a private loopback port for actual HTTP boundary checks. */async function servePairing(t, authorize, pairings = createPairingStore()) {@@ -43,6 +46,28 @@ function bundle(overrides = {}) {};}+/** Make a valid encrypted package for another board to exercise the receiver's identity guard. */+async function sealedOtherBoardPackage(code) {+ const { locator, secret } = parsePairingCode(code);+ const value = bundle({ board: OTHER_BOARD, snapshot: { version: 1, tables: {+ board_meta: [{ meta_key: 'board_id', meta_value: OTHER_BOARD }], event: [{ event_id: 14 }],+ } } });+ const key = await webcrypto.subtle.importKey('raw', secret, 'AES-GCM', false, ['encrypt']);+ const iv = randomBytes(12);+ const aad = new TextEncoder().encode(JSON.stringify(['pullboard-pairing', 1, locator]));+ const plaintext = new TextEncoder().encode(JSON.stringify(value));+ const ciphertext = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad, tagLength: 128 }, key, plaintext);+ return Buffer.concat([iv, Buffer.from(ciphertext)]).toString('base64url');+}++/** Read relay-owned files only; local device homes intentionally retain their own keys. */+function relayFiles(directory) {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const path = join(directory, entry.name);+ return entry.isDirectory() ? relayFiles(path) : [readFileSync(path)];+ });+}+test('[H15,H17] client seals board key and native snapshot under a one-time code the relay cannot read', async () => {const issued = createPairingCode(BOARD);assert.match(issued.locator, /^[A-Za-z0-9_-]{22}$/);@@ -70,6 +95,13 @@ test('[H15,H17] client seals board key and native snapshot under a one-time codeawait assert.rejects(openPairingBundle(issued.code, tampered), { code: 'PAIR_CODE_INVALID' });const wrong = createPairingCode(BOARD);await assert.rejects(openPairingBundle(wrong.code, sealed), { code: 'PAIR_CODE_INVALID' });+ const wrongBoardBundle = bundle({ board: OTHER_BOARD, snapshot: { version: 1, tables: {+ board_meta: [{ meta_key: 'board_id', meta_value: OTHER_BOARD }], event: [{ event_id: 14 }],+ } } });+ await assert.rejects(sealPairingBundle(issued.code, wrongBoardBundle), { code: 'PAIR_PACKAGE' },+ 'the linked client will not seal a snapshot for a different board');+ await assert.rejects(openPairingBundle(issued.code, await sealedOtherBoardPackage(issued.code)), { code: 'PAIR_PACKAGE' },+ 'the joining client rejects a valid encrypted package for a different board');});test('[H15,H17] package validation excludes sender credentials and validates relay and board identity', async () => {@@ -119,6 +151,18 @@ test('[H15,H17] relay pairing envelopes expire after ten minutes and are consumeassert.equal(store.size(), 0, 'expired and used tombstones are eventually pruned');});+test('[H15,H17] a pairing code cannot be consumed as another board', () => {+ const store = createPairingStore();+ const issued = createPairingCode(BOARD);+ const opaque = 'A'.repeat(60);+ store.publish(BOARD, issued.locator, opaque);++ assert.throws(() => store.consume(OTHER_BOARD, issued.locator), { code: 'PAIR_CODE_INVALID' },+ 'the relay record is bound to the board that published the code');+ assert.deepEqual(store.consume(BOARD, issued.locator), { sealed: opaque },+ 'a mismatched-board attempt does not spend the original code');+});+test('[H15,H17] relay refuses malformed, duplicate and over-capacity pairing envelopes', () => {const store = createPairingStore({ maxCodes: 1 });const first = createPairingCode(BOARD);@@ -249,3 +293,37 @@ test('[H15,H17] production CLI pairs a real second clone and reads the same boarassert.deepEqual(paired.exported, box.before, 'the second clone imports the same native rows and counters');assert.ok(!box.calls.some((call) => call.path.includes(printed.document.code)), 'the code secret never appears in a relay request path');});++test('[H15,H17] a paired clone synchronizes without a key file from PULLBOARD_RELAY_KEY', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ const printed = await box.cli('relay', 'pair');+ const paired = await box.otherDeviceJoin(printed.document.code);+ const beforeSyncCalls = box.calls.length;+ const synchronized = await paired.syncWithEnvironmentKey('export');+ assert.equal(synchronized.code, 0, 'the paired clone reads the relay using its local environment key');+ assert.equal(paired.keyFileExists(), false, 'the synchronization ran with no stored key file');+ assert.ok(box.calls.slice(beforeSyncCalls).some(({ method, path }) => method === 'GET' && /\/events\?after=/.test(path)),+ 'the clone fetched linked relay state with no stored key file');+ assert.deepEqual(synchronized.document, paired.exported, 'sync reads the paired board without changing its native rows');++ const encodedKey = readFileSync(box.keyFile, 'utf8').trim();+ const keyBytes = decodeBoardKey(encodedKey);+ const secretText = printed.document.code.split('.')[2];+ const secretBytes = parsePairingCode(printed.document.code).secret;+ const wireBytes = Buffer.concat(box.transit.flatMap(({ request, response }) => [request, response]));+ const relayDiskBytes = Buffer.concat([...relayFiles(box.relayDirectory), readFileSync(box.authDatabase)]);+ const output = JSON.stringify(synchronized.document);+ for (const [label, value] of [+ ['raw board key bytes', keyBytes],+ ['encoded board key', Buffer.from(encodedKey)],+ ['raw pairing secret bytes', Buffer.from(secretBytes)],+ ['encoded pairing secret', Buffer.from(secretText)],+ ]) {+ assert.equal(wireBytes.includes(value), false, `relay HTTP bodies contain no ${label}`);+ assert.equal(relayDiskBytes.includes(value), false, `relay-owned files contain no ${label}`);+ }+ assert.equal(box.calls.some(({ path }) => path.includes(secretText)), false, 'the pairing secret never appears in a relay URL');+ assert.equal(output.includes(encodedKey), false, 'the environment key is not echoed in the clone command result');+ assert.equal(output.includes(secretText), false, 'the pairing secret is not echoed in the clone command result');+});diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 44167bc0..0e1cde43 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -2,6 +2,7 @@import assert from 'node:assert/strict';import { spawn, spawnSync } from 'node:child_process';import { createServer } from 'node:http';+import { Transform } from 'node:stream';import { once } from 'node:events';import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { delimiter, join, resolve } from 'node:path';@@ -56,21 +57,43 @@ export async function relayClientFixture(t) {};const provider = await githubFixture(t);provider.state.deviceAuthorized = true;- const auth = createRelayAuth({ database: join(scratch, 'auth.sqlite'), github: createGitHubClient(provider.config) });+ const authDatabase = join(scratch, 'auth.sqlite');+ const auth = createRelayAuth({ database: authDatabase, github: createGitHubClient(provider.config) });let time = Date.now();let override = null;let signIn;let api;const calls = [];+ const transit = [];const server = createServer(async (req, res) => {calls.push({ method: req.method, path: req.url });+ const requestChunks = [];+ const responseChunks = [];+ const request = new Transform({+ transform(chunk, _encoding, callback) {+ requestChunks.push(Buffer.from(chunk));+ callback(null, chunk);+ },+ });+ Object.assign(request, { method: req.method, url: req.url, headers: req.headers });+ req.pipe(request);+ /** Capture a response chunk for boolean-only transport audits without changing the response. */+ function captureResponse(chunk) {+ if (chunk !== undefined && chunk !== null && typeof chunk !== 'function') responseChunks.push(Buffer.from(chunk));+ }+ const write = res.write.bind(res);+ res.write = (chunk, ...args) => { captureResponse(chunk); return write(chunk, ...args); };+ const end = res.end.bind(res);+ res.end = (chunk, ...args) => { captureResponse(chunk); return end(chunk, ...args); };+ res.once('finish', () => transit.push({ method: req.method, path: req.url,+ request: Buffer.concat(requestChunks), response: Buffer.concat(responseChunks) }));if (override && req.method === 'DELETE') {res.writeHead(override.status, { 'content-type': 'application/json' });res.end(JSON.stringify({ version: override.version ?? 1, error: { code: override.code, message: 'fixture refusal' } }));return;}- if (await signIn(req, res)) return;- await api(req, res);+ if (await signIn(request, res)) return;+ await api(request, res);});server.listen(0, '127.0.0.1');await once(server, 'listening');@@ -137,14 +160,27 @@ export async function relayClientFixture(t) {if (joined.code !== 0) throw new Error('real clone did not join the one-use pairing code');const exported = await run('export');if (exported.code !== 0) throw new Error('paired clone could not read its restored board');- return { joined: document, exported: exported.document };+ const link = JSON.parse(readFileSync(join(otherRoot, '.git', 'pullboard', 'relay.json'), 'utf8'));+ const otherKeyFile = join(otherEnv.PULLBOARD_HOME, 'relay-keys', link.board + '.key');+ const environmentKey = readFileSync(otherKeyFile, 'utf8').trim();+ /** Run a real linked-clone command with only the environment key, after removing its key file. */+ async function syncWithEnvironmentKey(...args) {+ rmSync(otherKeyFile, { force: true });+ assert.equal(existsSync(otherKeyFile), false, 'the paired clone has no stored board-key file');+ const envKey = { ...otherEnv, PULLBOARD_RELAY_KEY: environmentKey };+ return childResult(otherRoot, envKey, [CLI, ...args, '--json']);+ }+ return { joined: document, exported: exported.document, syncWithEnvironmentKey,+ /** Check that the paired clone still has no persisted board-key file. */+ keyFileExists() { return existsSync(otherKeyFile); } };}/** Run multiple production commands in one process, emitting only safe counters. */async function script(source) {return childResult(root, env, ['--input-type=module', '-e', source]);}return {- root, env, lane, before, linkFile, keyFile, calls, cli, link, otherDeviceOff, otherDeviceJoin, script,+ root, env, lane, before, linkFile, keyFile, calls, transit, relayDirectory: join(scratch, 'relay'), authDatabase,+ cli, link, otherDeviceOff, otherDeviceJoin, script,advance(days) { time = Date.now() + days * 86400000; },overrideDelete(value) { override = value; },mainURL: new URL('../src/cli.js', import.meta.url).href,diff --git a/test/relay-key.test.js b/test/relay-key.test.jsindex aed20958..ff265842 100644--- a/test/relay-key.test.js+++ b/test/relay-key.test.js@@ -6,7 +6,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, stimport { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';-import { generateBoardKey, seal, unseal } from '../src/seal.js';+import { decodeBoardKey, encodeBoardKey, generateBoardKey, seal, unseal } from '../src/seal.js';import { forgetBoardKey, readBoardKey, storeBoardKey } from '../src/relay-key.js';/**@@ -23,9 +23,10 @@ function privateFallback(t) {mkdirSync(noCommands, { mode: 0o700 });chmodSync(home, 0o700);chmodSync(noCommands, 0o700);- const prior = Object.fromEntries(['HOME', 'PULLBOARD_HOME', 'PATH'].map((name) => [name, process.env[name]]));+ const prior = Object.fromEntries(['HOME', 'PULLBOARD_HOME', 'PULLBOARD_RELAY_KEY', 'PATH'].map((name) => [name, process.env[name]]));process.env.HOME = home;process.env.PULLBOARD_HOME = pullboardHome;+ delete process.env.PULLBOARD_RELAY_KEY;process.env.PATH = noCommands;t.after(() => {for (const [name, value] of Object.entries(prior)) {@@ -87,3 +88,23 @@ test('fallback refuses missing or wrong board identities, invalid/corrupt keys,assert.equal(existsSync(corrupt), false, 'forget removes the local key file');assert.throws(() => readBoardKey(boardId), { code: 'RELAY_KEY_MISSING' });});++test('PULLBOARD_RELAY_KEY is a canonical device-only fallback when no stored key exists [H1,H15,H17]', async (t) => {+ const box = privateFallback(t);+ const boardId = 'd'.repeat(32);+ const raw = await generateBoardKey();+ const encoded = encodeBoardKey(raw);++ process.env.PULLBOARD_RELAY_KEY = encoded;+ assert.deepEqual(readBoardKey(boardId), raw, 'the local environment key opens the same board key');+ assert.equal(existsSync(join(box.keyDirectory, `${boardId}.key`)), false, 'reading the environment fallback does not persist another copy');+ assert.deepEqual(decodeBoardKey(process.env.PULLBOARD_RELAY_KEY), raw, 'the accepted representation is canonical unpadded base64url');++ process.env.PULLBOARD_RELAY_KEY = `${encoded}=`;+ let refusal;+ assert.throws(() => readBoardKey(boardId), (error) => {+ refusal = error;+ return error.code === 'SEAL_KEY';+ }, 'padding aliases are refused instead of silently normalized');+ assert.equal(refusal.message.includes(encoded), false, 'a malformed environment secret is never echoed in the refusal');+});