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): keep board keys in owner-only files [H15,H17]

Corey Olson1c141de856ae
diff --git a/src/relay-key.js b/src/relay-key.js
index b32ed80c..ab6cd78b 100644
--- a/src/relay-key.js
+++ b/src/relay-key.js
@@ -13,7 +13,7 @@ function identity(boardId) {
return boardId;
}
-/** Locate the private fallback without putting a board key in a repository. */
+/** Locate the owner-only key under the machine pullboard home, outside repositories. */
function keyFile(boardId) {
return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'relay-keys', identity(boardId) + '.key');
}
@@ -30,26 +30,8 @@ function keychain() {
return null;
}
-/** Save a generated key in the keychain, or atomically in an owner-only fallback file. */
-export function storeBoardKey(boardId, key) {
- const id = identity(boardId);
- const encoded = encodeBoardKey(key);
- const service = keychain();
- if (service) {
- // security's interactive mode receives the key through a pipe, never process arguments.
- const saved = spawnSync(service, service === 'security' ? ['-i']
- : ['store', '--label=Pullboard board key', 'application', 'pullboard', 'board', id], {
- encoding: 'utf8', timeout: 10000,
- input: service === 'security' ? `add-generic-password -U -a ${id} -s pullboard.board-key -w ${encoded}\n` : encoded,
- });
- if (saved.status !== 0) throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay on again');
- // Interactive security may exit successfully after a failed command; check the stored value.
- if (service === 'security') {
- const found = spawnSync(service, ['find-generic-password', '-a', id, '-s', 'pullboard.board-key', '-w'], { encoding: 'utf8', timeout: 10000 });
- if (found.status !== 0 || found.stdout.trim() !== encoded) throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay on again');
- }
- return 'keychain';
- }
+/** Persist a device key atomically in a private file, independent of keychain availability. */
+function writeKeyFile(id, encoded) {
const file = keyFile(id);
const directory = join(file, '..');
mkdirSync(directory, { recursive: true, mode: 0o700 });
@@ -60,9 +42,25 @@ export function storeBoardKey(boardId, key) {
writeFileSync(temporary, encoded + '\n', { mode: 0o600, flag: 'wx' });
renameSync(temporary, file);
} finally { rmSync(temporary, { force: true }); }
+ return file;
+}
+
+/** Save a generated key in its owner-only device file, even when a keychain is available. */
+export function storeBoardKey(boardId, key) {
+ const id = identity(boardId);
+ writeKeyFile(id, encodeBoardKey(key));
return 'file';
}
+/** 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. */
export function readBoardKey(boardId) {
const id = identity(boardId);
@@ -72,13 +70,22 @@ export function readBoardKey(boardId) {
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());
}
+ 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');
}
@@ -86,8 +93,10 @@ export function readBoardKey(boardId) {
/** Remove the device key after a successful unlink, leaving all local board records untouched. */
export function forgetBoardKey(boardId, storage) {
const id = identity(boardId);
- const service = keychain();
- if (!service && storage === 'keychain') throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay off again to finish forgetting its key');
+ const file = keyFile(id);
+ const hasFile = existsSync(file);
+ const service = hasFile ? null : keychain();
+ if (!hasFile && !service && storage === 'keychain') throw new Refused('RELAY_KEYCHAIN', 'unlock the system keychain and run pullboard relay off again to finish forgetting its key');
if (service) {
const removed = spawnSync(service, service === 'security'
? ['delete-generic-password', '-a', id, '-s', 'pullboard.board-key']
@@ -95,5 +104,5 @@ export function forgetBoardKey(boardId, storage) {
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 and run pullboard relay off again to finish forgetting its key');
}
- rmSync(keyFile(id), { force: true });
+ rmSync(file, { force: true });
}
diff --git a/src/relay.js b/src/relay.js
index 853fa7a3..615920e8 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -145,13 +145,13 @@ function behind(root, state) {
return localRecords(root, (board) => board.db.prepare('SELECT COUNT(*) AS count FROM event WHERE event_id > ?').get(state.cursor).count);
}
-/** Expose pairing information while keeping the human relay credential out of output. */
-function summary(root, state) {
+/** Expose key-free link status; only an explicit link operation includes its pairing carrier. */
+function summary(root, state, { pairing = false } = {}) {
if (!state) return { linked: false, board: '', url: '', link: '', sequence: 0, behind: 0 };
if (state.unlinking) return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, cleanup: true };
- const key = encodeBoardKey(readBoardKey(state.board));
+ const fragment = pairing ? '&key=' + encodeBoardKey(readBoardKey(state.board)) : '';
return { linked: true, board: state.board, url: state.url,
- link: 'https://app.pullboard.dev/#board=' + state.board + '&key=' + key,
+ link: 'https://app.pullboard.dev/#board=' + state.board + fragment,
sequence: state.sequence, behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)) };
}
@@ -601,9 +601,9 @@ export async function relayOn(root, address, io) {
}
await ensureOrdered(root, file, state, io);
await catchUp(root, file, state, io);
- result = summary(root, state);
+ result = summary(root, state, { pairing: true });
}
- catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}; pending records are queued for the next command`); result = summary(root, state); }
+ catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}; pending records are queued for the next command`); result = summary(root, state, { pairing: true }); }
io.say(terminalQr(result.link));
return result;
});
diff --git a/test/relay-key-file.test.js b/test/relay-key-file.test.js
new file mode 100644
index 00000000..a44548e8
--- /dev/null
+++ b/test/relay-key-file.test.js
@@ -0,0 +1,106 @@
+/** Owner-only relay key files and legacy keychain migration [H15,H17]. */
+import assert from 'node:assert/strict';
+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');
+ 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.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');
+ 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');
+});