Skip to content

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.

fix(relay): reconcile file and environment keys [H15,H17]

Corey Olson3d3992bf8d36
diff --cc src/relay-key.js
index ab6cd78b,6c4add4b..4cb2cda0
--- a/src/relay-key.js
+++ b/src/relay-key.js
@@@ -52,42 -63,25 +52,47 @@@ export function storeBoardKey(boardId,
return 'file';
}
-/** Read a board key from device storage or a canonical local environment secret for unpaired agents. */
+/** Remove a legacy keychain value after its validated key has been copied to the private file. */
+function removeKeychainValue(service, id) {
+ const removed = spawnSync(service, service === 'security'
+ ? ['delete-generic-password', '-a', id, '-s', 'pullboard.board-key']
+ : ['clear', 'application', 'pullboard', 'board', id], { encoding: 'utf8', timeout: 10000 });
+ const absent = service === 'security' ? removed.status === 44 : removed.status === 1 && !removed.stderr;
+ if (removed.status !== 0 && !absent) throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain to finish moving this board key');
+}
+
- /** Read a board key only from this device's private file or operating-system keychain. */
++/** Read device storage first, migrating legacy keychain values before using an environment fallback. */
export function readBoardKey(boardId) {
const id = identity(boardId);
const file = keyFile(id);
if (existsSync(file)) {
const stat = lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_KEY_STORAGE', 'restore the board key as an owner-only regular file with mode 600');
-- return decodeBoardKey(readFileSync(file, 'utf8').trim());
++ const encoded = readFileSync(file, 'utf8').trim();
++ const key = decodeBoardKey(encoded);
++ if (process.env.PULLBOARD_RELAY_KEY !== undefined && process.env.PULLBOARD_RELAY_KEY !== encoded) {
++ throw new Refused('RELAY_KEY_FILE_ENV_MISMATCH', 'PULLBOARD_RELAY_KEY differs from this board key file; unset PULLBOARD_RELAY_KEY or set it to the key from this device file');
++ }
++ return key;
}
- if (process.env.PULLBOARD_RELAY_KEY) return decodeBoardKey(process.env.PULLBOARD_RELAY_KEY);
const service = keychain();
if (service) {
const args = service === 'security'
? ['find-generic-password', '-a', id, '-s', 'pullboard.board-key', '-w']
: ['lookup', 'application', 'pullboard', 'board', id];
const found = spawnSync(service, args, { encoding: 'utf8', timeout: 10000 });
- if (found.status === 0) return decodeBoardKey(found.stdout.trim());
+ if (found.status === 0) {
+ const encoded = found.stdout.trim();
+ const key = decodeBoardKey(encoded);
+ // Keep the legacy value until a verified private file exists; roll back if deletion fails.
+ const migrated = writeKeyFile(id, encoded);
+ try { removeKeychainValue(service, id); }
+ catch (error) { rmSync(migrated, { force: true }); throw error; }
+ return key;
+ }
}
- 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 --cc test/relay-key-file.test.js
index a44548e8,00000000..466a1de4
mode 100644,000000..100644
--- a/test/relay-key-file.test.js
+++ b/test/relay-key-file.test.js
@@@ -1,106 -1,0 +1,123 @@@
+/** Owner-only relay key files and legacy keychain migration [H15,H17]. */
+import assert from 'node:assert/strict';
++import { randomBytes } from 'node:crypto';
+import { chmodSync, existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { relayClientFixture } from './relay-client-fixture.js';
+
+/** Install an isolated `security` command without consulting the host keychain. */
+function securityStandIn(box) {
+ const store = join(box.env.PULLBOARD_HOME, 'legacy-keychain-entry');
+ const security = join(box.env.PATH, 'security');
+ const script = '#!' + process.execPath + '\n' + [
+ "const { existsSync, readFileSync, rmSync } = require('node:fs');",
+ 'const command = process.argv[2];',
+ "if (['list-keychains', 'search'].includes(command)) process.exit(0);",
+ "if (['find-generic-password', 'lookup'].includes(command)) {",
+ " if (process.env.SECURITY_MODE !== 'available') process.exit(1);",
+ " if (!existsSync(process.env.KEYCHAIN_STORE)) process.exit(command === 'lookup' ? 1 : 44);",
+ " process.stdout.write(readFileSync(process.env.KEYCHAIN_STORE));",
+ "} else if (['delete-generic-password', 'clear'].includes(command)) rmSync(process.env.KEYCHAIN_STORE, { force: true });",
+ 'else process.exit(1);',
+ ].join('\n');
+ for (const executable of [security, join(box.env.PATH, 'secret-tool')]) {
+ writeFileSync(executable, script, { mode: 0o700 });
+ chmodSync(executable, 0o700);
+ }
+ box.env.KEYCHAIN_STORE = store;
+ box.env.SECURITY_MODE = 'locked';
+ return store;
+}
+
+test('owner-only key file links and reads with a locked keychain, migrates once, and supports the environment key [H15,H17]', async (t) => {
+ const box = await relayClientFixture(t);
+ const legacyStore = securityStandIn(box);
+
+ const linked = await box.cli('relay', 'on', '--url', box.origin);
+ assert.equal(linked.code, 0,
+ 'relay on succeeds when the available security command reports a locked keychain');
+ assert.ok(existsSync(box.keyFile), 'relay on writes the board key under the private pullboard home');
+ assert.equal(statSync(join(box.env.PULLBOARD_HOME, 'relay-keys')).mode & 0o777, 0o700,
+ 'the key directory is owner-only');
+ assert.equal(statSync(box.keyFile).mode & 0o777, 0o600,
+ 'the key file is owner-readable and owner-writable only');
+ assert.equal((await box.cli('relay')).code, 0,
+ 'a subsequent linked read does not need to unlock the keychain');
+
+ const encoded = readFileSync(box.keyFile, 'utf8').trim();
+ assert.equal(linked.document.link.endsWith('&key=' + encoded), true, 'the intended pairing field carries the generated key');
+ const { link: pairingLink, ...publicLinkResult } = linked.document;
+ assert.equal(JSON.stringify(publicLinkResult).includes(encoded), false, 'the JSON result has no key outside its pairing field');
+ for (const args of [['status'], ['show', '1'], ['relay'], ['show', '999999']]) {
+ const result = await box.cli(...args);
+ assert.equal(result.code, args[1] === '999999' ? 1 : 0, 'ordinary reads or their typed refusal complete');
+ assert.equal(JSON.stringify(result.document).includes(encoded), false, 'ordinary status, show, relay and refusals never contain the board key');
+ }
+ const text = await box.script(`
+ import { main } from ${JSON.stringify(box.mainURL)};
+ import { readFileSync } from 'node:fs';
+ const key = readFileSync(${JSON.stringify(box.keyFile)}, 'utf8').trim();
+ let output = '', errors = '';
+ const streams = { cwd: ${JSON.stringify(box.root)},
+ stdout: { write: part => { output += part; } }, stderr: { write: part => { errors += part; } } };
+ const linkedCode = await main(['relay', 'on', '--url', ${JSON.stringify(box.origin)}], streams);
+ const carriers = output.split('\\n').filter(line => line.includes(key));
+ const pairingOnly = carriers.length === 1 && carriers[0].startsWith('https://app.pullboard.dev/#board=') && carriers[0].endsWith('&key=' + key);
+ output = '';
+ const statusCode = await main(['status'], streams);
+ const refusalCode = await main(['show', '999999'], streams);
+ console.log(JSON.stringify({ version: 1, linkedCode, statusCode, refusalCode, pairingOnly,
+ ordinaryLeak: output.includes(key), errorLeak: errors.includes(key) }));
+ `);
+ assert.equal(text.code, 0, 'the real text-output probe completes without printing its captured key');
+ assert.deepEqual(text.document, { version: 1, linkedCode: 0, statusCode: 0, refusalCode: 1,
+ pairingOnly: true, ordinaryLeak: false, errorLeak: false }, 'text output shows the key once in its pairing link and nowhere in ordinary output or errors');
++ box.env.PULLBOARD_RELAY_KEY = encoded;
++ assert.equal((await box.cli('status')).code, 0, 'matching file and environment keys remain usable');
++ const wrongEnvironmentKey = randomBytes(32).toString('base64url');
++ box.env.PULLBOARD_RELAY_KEY = wrongEnvironmentKey;
++ const callsBeforeMismatch = box.calls.length;
++ const mismatch = await box.cli('add', box.lane, 'Refused mismatched key move');
++ assert.equal(mismatch.code, 1, 'a move refuses conflicting device key sources');
++ assert.equal(mismatch.document.error.code, 'RELAY_KEY_FILE_ENV_MISMATCH');
++ assert.match(mismatch.document.error.message, /PULLBOARD_RELAY_KEY.*file.*unset/u);
++ for (const key of [encoded, wrongEnvironmentKey]) {
++ assert.equal(JSON.stringify(mismatch.document).includes(key), false, 'the mismatch never exposes either key');
++ }
++ assert.equal(box.calls.length, callsBeforeMismatch, 'a mismatched key never reaches the relay');
++ box.env.PULLBOARD_RELAY_KEY = encoded;
+ writeFileSync(legacyStore, encoded, { mode: 0o600 });
+ rmSync(box.keyFile);
+ box.env.SECURITY_MODE = 'available';
+ const legacyLink = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ legacyLink.keyStorage = 'keychain';
+ writeFileSync(box.linkFile, JSON.stringify(legacyLink), { mode: 0o600 });
+ assert.equal((await box.cli('relay')).code, 0,
+ 'an existing keychain key still opens the linked board');
++ assert.ok(existsSync(box.keyFile), 'legacy migration runs before the matching environment fallback');
+ assert.equal(readFileSync(box.keyFile, 'utf8').trim(), encoded,
+ 'the legacy keychain key is copied into the owner-only file');
+ assert.equal(existsSync(legacyStore), false, 'the old keychain copy is removed after migration');
++ delete box.env.PULLBOARD_RELAY_KEY;
+ box.env.SECURITY_MODE = 'locked';
+ assert.equal((await box.cli('relay')).code, 0,
+ 'reads continue after migration when the keychain is locked again');
+ assert.equal((await box.cli('relay', 'off')).code, 0,
+ 'unlink uses the migrated file even when legacy metadata still says keychain');
+ assert.equal(existsSync(box.keyFile), false, 'unlink forgets the migrated owner-only file');
+ assert.equal((await box.cli('relay', 'on', '--url', box.origin)).code, 0,
+ 'the board can link again while the keychain remains locked');
+
+ const envKey = readFileSync(box.keyFile, 'utf8').trim();
+ rmSync(box.keyFile);
+ box.env.PULLBOARD_RELAY_KEY = envKey;
+ assert.equal((await box.cli('relay')).code, 0,
+ 'PULLBOARD_RELAY_KEY opens the linked board without a key file');
+ const moves = box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length;
+ assert.equal((await box.cli('add', box.lane, 'Environment-only key move')).code, 0,
+ 'PULLBOARD_RELAY_KEY seals and sends a real move without a key file');
+ assert.ok(box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length > moves,
+ 'the environment-only command reaches the real relay move endpoint');
+ assert.equal(existsSync(box.keyFile), false, 'the environment key is not copied to a file');
+});
diff --cc test/relay-key.test.js
index aed20958,ff265842..3ac85b81
--- a/test/relay-key.test.js
+++ b/test/relay-key.test.js
@@@ -87,3 -88,23 +88,51 @@@ test('fallback refuses missing or wron
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');
+ });
++
++
++test('owner-only key file refuses mismatched environment keys without exposing either source [H15,H17]', async (t) => {
++ const box = privateFallback(t);
++ const boardId = 'e'.repeat(32);
++ const raw = await generateBoardKey();
++ storeBoardKey(boardId, raw);
++ const file = join(box.keyDirectory, `${boardId}.key`);
++ const before = readFileSync(file);
++ const encoded = encodeBoardKey(raw);
++ process.env.PULLBOARD_RELAY_KEY = encoded;
++ assert.deepEqual(readBoardKey(boardId), raw, 'matching device sources remain usable');
++ const wrong = encodeBoardKey(await generateBoardKey());
++ process.env.PULLBOARD_RELAY_KEY = wrong;
++ assert.throws(() => readBoardKey(boardId), error => {
++ assert.equal(error.code, 'RELAY_KEY_FILE_ENV_MISMATCH');
++ assert.match(error.message, /PULLBOARD_RELAY_KEY.*file.*unset/u);
++ for (const key of [encoded, wrong]) assert.equal(error.message.includes(key), false);
++ return true;
++ });
++ assert.deepEqual(readFileSync(file), before, 'refusal leaves the stored key unchanged');
++ process.env.PULLBOARD_RELAY_KEY = '';
++ assert.throws(() => readBoardKey(boardId), { code: 'RELAY_KEY_FILE_ENV_MISMATCH' }, 'an explicitly empty environment value also conflicts with the file');
++ rmSync(file);
++ assert.throws(() => readBoardKey(boardId), { code: 'SEAL_KEY' }, 'an explicitly empty fallback is validated rather than silently ignored');
++ delete process.env.PULLBOARD_RELAY_KEY;
++ assert.throws(() => readBoardKey(boardId), error => error.code === 'RELAY_KEY_MISSING' && /set PULLBOARD_RELAY_KEY from your local secret store/u.test(error.message), 'missing-key guidance from main remains intact');
++});