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: cancel relay setup before board linking [H5,N26]
Corey Olsonc862a99663f9
diff --git a/src/cli.js b/src/cli.jsindex 1ec82219..36da6f11 100644--- a/src/cli.js+++ b/src/cli.js@@ -3209,8 +3209,21 @@ async function runCommand(argv, io) {}if (values.all) {if (first !== 'on' || second || rest.length) throw new Refused('USAGE', 'pullboard relay on --all [--url <address>]');- const result = await relayOnAll(values.url, io);- io.result?.(result); return result.failed.length ? 1 : 0;+ const controller = new AbortController();+ const cancelSignIn = () => controller.abort();+ process.once('SIGINT', cancelSignIn);+ process.once('SIGTERM', cancelSignIn);+ let result;+ try { result = await relayOnAll(values.url, io, { signal: controller.signal }); }+ finally { process.off('SIGINT', cancelSignIn); process.off('SIGTERM', cancelSignIn); }+ io.result?.(result);+ if (result.outcome) {+ io.say(result.outcome === 'declined' ? 'GitHub sign-in was declined; no boards were linked.'+ : result.outcome === 'expired' ? 'GitHub device sign-in expired; no boards were linked.'+ : 'GitHub device sign-in was cancelled; no boards were linked.');+ return 1;+ }+ return result.failed.length ? 1 : 0;}if (['tokens', 'revoke'].includes(first)) {if (rest.length || values.url || (first === 'tokens' && second) || (first === 'revoke' && !second)) {diff --git a/src/relay-machine.js b/src/relay-machine.jsindex a98f3a31..29d22ac7 100644--- a/src/relay-machine.js+++ b/src/relay-machine.js@@ -91,6 +91,13 @@ export function readRelayMachine() {return state;}+/** Read only the saved person endpoint without migrating or scrubbing credentials. */+export function relayMachineOwner() {+ const state = readState();+ const owner = state.owner ?? (state.session ? { account: state.session.account, url: state.session.url } : null);+ return owner ? { account: owner.account, url: owner.url } : null;+}+/** 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-setup.js b/src/relay-setup.jsindex 2e46a24c..f8905269 100644--- a/src/relay-setup.js+++ b/src/relay-setup.js@@ -6,7 +6,7 @@ import { openApproval, restoreLinkReply } from './relay-approval.js';import { requirePersonChannel } from './person.js';import { codeIsFromMain, repoInfo } from './git.js';import { listApiProjects } from './projects.js';-import { acceptDeviceEnrollment, beginDeviceEnrollment, readRelayMachine, updateRelayMachine } from './relay-machine.js';+import { acceptDeviceEnrollment, beginDeviceEnrollment, readRelayMachine, relayMachineOwner, updateRelayMachine } from './relay-machine.js';import { deliverDeviceWraps, relayDeviceRequest, relayMachineSignIn, relayMachineContext, relayRevokeDevice, relayOn, relayStatus, originRepository } from './relay.js';import { terminalQr } from './qr.js';import { Refused } from './refused.js';@@ -160,14 +160,18 @@ async function pairFirstDevice(session, board, linked, io) {}/** Explicit foreground sign-in repairs links; only board machine credentials survive this command. */-export async function relayOnAll(address, io) {+export async function relayOnAll(address, io, { signal } = {}) {requirePersonChannel(io.personChannel);- const prior = readRelayMachine();- // Scrub every registered legacy link before asking for or using fresh person authority.- for (const project of listApiProjects()) { try { relayMachineContext(project.root); } catch { /* linkProjects reports invalid projects. */ } }- const session = await relayMachineSignIn(address || prior.owner?.url, io);- updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = []; });+ // A cancelled or declined sign-in must not migrate machine state or scrub existing board links.+ const owner = relayMachineOwner();+ const session = await relayMachineSignIn(address || owner?.url, io, { signal });+ if (session.outcome) return session;+ if (signal?.aborted) return { outcome: 'cancelled' };await flushRevocations(session, io);+ if (signal?.aborted) return { outcome: 'cancelled' };+ // From this synchronous commit point onward the first board-link attempt is underway; later+ // cancellation must not claim that already-started link writes were rolled back.+ updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = []; });const result = await linkProjects(session, io);const devices = readRelayMachine().devices.filter(device => device.account === session.account && device.url === session.url);const pairing = devices.length || !result.linked.length ? { paired: devices.length > 0 }diff --git a/src/relay.js b/src/relay.jsindex 78ed272b..bdb89314 100644--- a/src/relay.js+++ b/src/relay.js@@ -143,7 +143,7 @@ function notices(document, io) {}/** The sole outbound transport in the CLI: explicit sign-in or a saved, opted-in board link. */-async function request(state, path, { method = 'GET', body, allowMissing = false, initialBaseline = false } = {}, io) {+async function request(state, path, { method = 'GET', body, allowMissing = false, initialBaseline = false, signal } = {}, io) {const supplied = process.env.PULLBOARD_RELAY_TOKEN;const readToken = method === 'GET' && path.startsWith('/api/v1/boards/') ? supplied : undefined;if (readToken !== undefined && !/^pa_[A-Za-z0-9_-]{43}$/.test(readToken)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token without including it in command arguments');@@ -151,14 +151,18 @@ async function request(state, path, { method = 'GET', body, allowMissing = falselet response;try {response = await fetch(relayOrigin(state.url) + path, {- method, redirect: 'error', signal: AbortSignal.timeout(10000),+ method, redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000),headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(initialBaseline ? { 'if-none-match': '*' } : {}) },...(body === undefined ? {} : { body: JSON.stringify(body) }),});- } catch { throw new Refused('RELAY_UNAVAILABLE', `the relay ${state.url} did not answer; read the local board offline, then retry this move when the relay is reachable`); }+ } catch {+ if (signal?.aborted) throw new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked');+ throw new Refused('RELAY_UNAVAILABLE', `the relay ${state.url} did not answer; read the local board offline, then retry this move when the relay is reachable`);+ }let document;try { document = await response.json(); }catch {+ if (signal?.aborted) throw new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked');const error = new Refused('RELAY_RESPONSE', 'the relay returned an invalid response; retry with the configured relay address');error.httpStatus = response.status;throw error;@@ -1167,18 +1171,42 @@ export async function relayRecover(root, skip, io) {/** Read the local link and lag without opening a network connection or revealing its relay token. */export function relayStatus(root) { return summary(root, loadLink(linkFile(root))); }-/** Renew a person session through the relay without changing this device's board key or cursors. */-async function deviceSignIn(url, io) {+/** Throw a named refusal when the caller has cancelled the in-progress device sign-in. */+function cancellationOutcome(signal) {+ if (signal?.aborted) throw new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked');+}++/** Wait for one bounded device-flow poll interval and wake promptly on caller cancellation. */+function waitForDevicePoll(seconds, signal) {+ cancellationOutcome(signal);+ return new Promise((resolve, reject) => {+ const finish = (error) => {+ clearTimeout(timer);+ signal?.removeEventListener('abort', cancel);+ if (error) reject(error); else resolve();+ };+ const cancel = () => finish(new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked'));+ const timer = setTimeout(() => finish(), Math.max(1, seconds) * 1000);+ signal?.addEventListener('abort', cancel, { once: true });+ if (signal?.aborted) cancel();+ });+}++/** Sign in with the caller's cancellation signal; no board credential is persisted here. */+async function deviceSignIn(url, io, { signal } = {}) {+ cancellationOutcome(signal);const client = { url };- const flow = await request(client, '/auth/device/start', { method: 'POST', body: {} }, io);+ const flow = await request(client, '/auth/device/start', { method: 'POST', body: {}, signal }, io);+ cancellationOutcome(signal);io.stderr.write(`Sign in with GitHub: open ${flow.verificationURL} and enter ${flow.userCode}\n`);const expires = Date.now() + flow.expiresIn * 1000;let signed;let wait = flow.interval;do {- await new Promise((resolve) => setTimeout(resolve, Math.max(1, wait) * 1000));+ await waitForDevicePoll(wait, signal);if (Date.now() >= expires) throw new Refused('OAUTH_EXPIRED', 'GitHub device sign-in expired; run pullboard relay on again');- signed = await request(client, '/auth/device/poll', { method: 'POST', body: { ticket: flow.ticket } }, io);+ signed = await request(client, '/auth/device/poll', { method: 'POST', body: { ticket: flow.ticket }, signal }, io);+ cancellationOutcome(signal);wait = signed.retryAfter ?? flow.interval;} while (signed.pending);const token = signed.token;@@ -1304,10 +1332,18 @@ export async function relayRequestDevice(root) {}/** Sign in once for machine setup; the saved account is the provider-authenticated identity. */-export async function relayMachineSignIn(address, io) {+export async function relayMachineSignIn(address, io, { signal } = {}) {requirePersonChannel(io.personChannel);const url = relayOrigin(address || DEFAULT_RELAY);- const signed = await deviceSignIn(url, io);+ let signed;+ try { signed = await deviceSignIn(url, io, { signal }); }+ catch (error) {+ if (signal?.aborted || error.code === 'OAUTH_CANCELLED') return { outcome: 'cancelled' };+ if (error.code === 'OAUTH_DENIED') return { outcome: 'declined' };+ if (error.code === 'OAUTH_EXPIRED') return { outcome: 'expired' };+ throw error;+ }+ if (signal?.aborted) return { outcome: 'cancelled' };if (typeof signed.user?.id !== 'string') throw new Refused('RELAY_RESPONSE', 'Sign in again to receive an authenticated account identity.');return { token: signed.token, id: signed.id, account: signed.user.id, url };}diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 40f2aea0..9608499c 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -211,6 +211,7 @@ globalThis.fetch = function tracedFetch(input, init) {let rejectedStateReads = null;let beforeSnapshotWrite = null;let refuseRequestWrites = false;+ let refuseBoardLinks = false;let refuseNextAcceptedApprovalCompletionResponse = false;let signIn;let api;@@ -329,6 +330,12 @@ globalThis.fetch = function tracedFetch(input, init) {res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture request outage' } }));return;}+ if (refuseBoardLinks && req.method === 'POST' && req.url === '/auth/boards/link') {+ req.resume();+ res.writeHead(503, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ version: 1, error: { code: 'FIXTURE_LINK_REFUSED', message: 'fixture link sentinel' } }));+ return;+ }if (refuseSnapshotWrites && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {res.writeHead(503, { 'content-type': 'application/json' });res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture snapshot outage' } }));@@ -579,7 +586,7 @@ globalThis.fetch = function tracedFetch(input, init) {return childResult(root, env, ['--input-type=module', '-e', source]);}return {- transit, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,+ transit, providerState: provider.state, providerCalls: provider.calls, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,/** Assert the test consumed every declared child budget, with no hidden CLI calls. */assertCliChildrenComplete() {@@ -626,6 +633,8 @@ globalThis.fetch = function tracedFetch(input, init) {/** Return how many state reads reached the private relay. */stateReadStarted() { return stateReadStarted; },refuseRequestWrites(value) { refuseRequestWrites = value; },+ /** Fail a surprise first-link request promptly so cancellation regressions cannot reach phone pairing. */+ refuseBoardLinks(value) { refuseBoardLinks = value; },/** Return HTTP 403 only after the real relay has stored one sealed approval completion. */refuseNextAcceptedApprovalCompletionResponse() { refuseNextAcceptedApprovalCompletionResponse = true; },mainURL: new URL('../src/cli.js', import.meta.url).href,diff --git a/test/relay-fixture.js b/test/relay-fixture.jsindex c994654d..3c06b468 100644--- a/test/relay-fixture.js+++ b/test/relay-fixture.js@@ -7,7 +7,7 @@ import { once } from 'node:events';/** Start a provider with real signed JWT verification and one-use browser/device grants. */export async function githubFixture(t) {const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });- const state = { access: true, permission: 'write', public: false, installed: true, repositoryID: 100, accountID: 7, permissionAccountID: 7, deviceAuthorized: false, slow: false, redirect: null };+ const state = { access: true, permission: 'write', public: false, installed: true, repositoryID: 100, accountID: 7, permissionAccountID: 7, deviceAuthorized: false, deviceDeclined: false, deviceExpired: false, slow: false, redirect: null };const calls = [];const codes = new Map();const userTokens = new Set();@@ -78,7 +78,9 @@ export async function githubFixture(t) {assert.equal(form.get('grant_type'), 'urn:ietf:params:oauth:grant-type:device_code');assert.equal(form.get('device_code'), deviceCode);if (state.slow) { state.slow = false; return reply(res, 200, { error: 'slow_down' }); }- return reply(res, 200, state.deviceAuthorized ? userCredential() : { error: 'authorization_pending' });+ return reply(res, 200, state.deviceDeclined ? { error: 'access_denied' }+ : state.deviceExpired ? { error: 'expired_token' }+ : state.deviceAuthorized ? userCredential() : { error: 'authorization_pending' });}assert.ok(form.get('client_secret') === clientSecret, 'browser exchange uses configured App secret');const challenge = codes.get(form.get('code'));diff --git a/test/relay.test.js b/test/relay.test.jsindex 0074cb59..697be7b1 100644--- a/test/relay.test.js+++ b/test/relay.test.js@@ -1,7 +1,7 @@/** Relay identity, expiry, permission freshness and scoped credential isolation [H8, H1]. */import assert from 'node:assert/strict';import { runFixtureChild as spawnSync } from './fixture-child.js';-import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';import { test } from 'node:test';@@ -16,6 +16,65 @@ import { serveView } from '../src/serve.js';import { fetchFresh } from './http-fixture.js';import { fetchPrintedViewLink } from './view-link-fixture.js';+const relaySetupURL = new URL('../src/relay-setup.js', import.meta.url).href;+const relayMachineURL = new URL('../src/relay-machine.js', import.meta.url).href;++/** Call the shared setup flow with a private caller signal and credential-free output streams. */+async function runRelayOnAll(box, signalMode) {+ return box.script(`+ import { relayOnAll } from ${JSON.stringify(relaySetupURL)};+ const controller = new AbortController();+ const originalFetch = globalThis.fetch;+ if (${JSON.stringify(signalMode)} === 'during-poll') {+ globalThis.fetch = async (input, init) => {+ const response = await originalFetch(input, init);+ const url = new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url);+ if (url.pathname === '/auth/device/start') setImmediate(() => controller.abort());+ return response;+ };+ } else if (${JSON.stringify(signalMode)} === 'during-flush') {+ globalThis.fetch = async (input, init) => {+ const url = new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url);+ if (init?.method === 'DELETE' && url.pathname.startsWith('/api/v1/devices/')) {+ setImmediate(() => controller.abort());+ await new Promise(resolve => controller.signal.addEventListener('abort', resolve, { once: true }));+ }+ return originalFetch(input, init);+ };+ } else if (${JSON.stringify(signalMode)} === 'already-aborted') controller.abort();+ const output = { personChannel: 'view', cwd: process.cwd(),+ stderr: { write() {} }, say() {}, err() {} };+ const result = await relayOnAll(${JSON.stringify(box.origin)}, output, { signal: controller.signal });+ process.stdout.write(JSON.stringify(result));+ `);+}++/** Seed one prior cleanup obligation so cancellation can be observed after auth and during flush. */+async function seedRevocation(box) {+ return box.script(`+ import { updateRelayMachine } from ${JSON.stringify(relayMachineURL)};+ updateRelayMachine(state => { state.revocations = [{ deviceId: 'device-00000000000000000000000000000000', account: '7', url: ${JSON.stringify(box.origin)} }]; });+ process.stdout.write(JSON.stringify({ seeded: true }));+ `);+}++/** Snapshot only private local metadata that cancellation must leave byte-for-byte unchanged. */+function fileSnapshot(path) { return existsSync(path) ? readFileSync(path) : null; }++/** Register a second synthetic local project without linking it to the private relay. */+async function registerSecondProject(box) {+ const root = join(dirname(box.root), 'cancel-second-project');+ mkdirSync(root);+ for (const args of [['init', '-q', '-b', 'main'], ['-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-q', '-m', 'fixture base'],+ ['remote', 'add', 'origin', '[email protected]:fixture/repository.git']]) {+ assert.equal(spawnSync('git', args, { cwd: root, env: box.env, encoding: 'utf8', timeout: 15_000 }).status, 0);+ }+ assert.equal((await box.cliAt(root, 'init')).code, 0, 'the second fixture project is registered on this machine');+ const exported = await box.cliAt(root, 'export');+ const id = exported.document.tables.board_meta.find(row => row.meta_key === 'board_id').meta_value;+ return { linkFile: join(root, '.git', 'pullboard', 'relay.json'), keyFile: join(box.env.PULLBOARD_HOME, 'relay-keys', id + '.key') };+}+/** Use real private SQLite and an actual HTTP provider with a controllable expiry clock. */async function fixture(t, options = {}) {const provider = await githubFixture(t);@@ -38,6 +97,64 @@ async function login(box) {return box.auth.pollDevice(grant.ticket);}+test('linking every board stops cleanly when the sign-in is declined or cancelled [H5,N26]', async (t) => {+ for (const scenario of ['already-cancelled', 'declined', 'expired', 'cancelled-during-sign-in', 'cancelled-after-sign-in']) await t.test(scenario, async (t) => {+ const box = await relayClientFixture(t);+ const second = await registerSecondProject(box);+ box.refuseBoardLinks(true);+ box.providerState.deviceAuthorized = scenario !== 'cancelled-during-sign-in';+ box.providerState.deviceDeclined = scenario === 'declined';+ box.providerState.deviceExpired = scenario === 'expired';+ if (scenario === 'cancelled-after-sign-in') {+ box.overrideDelete({ status: 200 });+ assert.equal((await seedRevocation(box)).code, 0, 'a prior revocation is queued before setup begins');+ }+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine', 'state.json');+ const before = new Map([box.linkFile, second.linkFile, box.keyFile, second.keyFile, machineFile].map(path => [path, fileSnapshot(path)]));+ if (scenario === 'cancelled-during-sign-in') {+ // A broken caller that ignores abort sees a provider denial at its first poll instead of hanging.+ setTimeout(() => { box.providerState.deviceDeclined = true; }, 100);+ }+ const mode = scenario === 'already-cancelled' ? 'already-aborted'+ : scenario === 'cancelled-during-sign-in' ? 'during-poll'+ : scenario === 'cancelled-after-sign-in' ? 'during-flush' : 'none';+ const result = await runRelayOnAll(box, mode);+ assert.equal(result.code, 0, 'the private setup caller returns a structured terminal outcome');+ const expected = scenario === 'declined' ? 'declined' : scenario === 'expired' ? 'expired' : 'cancelled';+ assert.equal(result.document.outcome, expected, 'sign-in termination has a named outcome');+ assert.deepEqual(result.document.linked ?? [], [], 'no board is linked after an interrupted sign-in');+ assert.deepEqual(result.document.failed ?? [], [], 'cancellation is not reported as a per-board failure');+ assert.deepEqual(fileSnapshot(box.linkFile), before.get(box.linkFile), 'cancelled sign-in leaves the board link file unchanged');+ assert.deepEqual(fileSnapshot(second.linkFile), before.get(second.linkFile), 'cancellation leaves the second registered board unlinked');+ assert.deepEqual(fileSnapshot(box.keyFile), before.get(box.keyFile), 'cancelled sign-in leaves the board key unchanged');+ assert.deepEqual(fileSnapshot(second.keyFile), before.get(second.keyFile), 'cancellation leaves the second board key unstored');+ if (scenario === 'cancelled-after-sign-in') {+ const prior = JSON.parse(before.get(machineFile).toString('utf8'));+ const after = JSON.parse(fileSnapshot(machineFile).toString('utf8'));+ assert.equal(after.autoLink, prior.autoLink, 'cancellation before the first link does not enable auto-linking');+ assert.deepEqual(after.owner, prior.owner, 'cancellation before the first link does not change the saved owner');+ assert.deepEqual(after.approvals, prior.approvals, 'cancellation before the first link preserves pending approvals');+ assert.deepEqual(after.revocations, [], 'the already-queued revocation is flushed as its existing cleanup obligation');+ } else {+ assert.deepEqual(fileSnapshot(machineFile), before.get(machineFile), 'decline or cancellation during sign-in does not mutate machine metadata');+ }+ assert.equal(box.transit.some(record => /\/auth\/boards\/link$|\/auth\/machines$|^\/api\/v1\/boards\//u.test(record.path)), false,+ 'no board or machine credential request begins before sign-in is committed');+ if (scenario === 'already-cancelled') {+ assert.equal(box.transit.some(record => record.path === '/auth/device/start'), false,+ 'an already-aborted signal prevents the device flow from starting');+ assert.equal(box.providerCalls.some(call => call.path === '/login/oauth/access_token'), false,+ 'an already-aborted signal makes no provider request');+ }+ if (scenario === 'cancelled-during-sign-in') {+ assert.equal(box.transit.some(record => record.path === '/auth/device/start'), true, 'the caller cancels an active device sign-in');+ }+ if (scenario === 'declined' || scenario === 'expired') {+ assert.equal(box.providerCalls.some(call => call.path === '/login/oauth/access_token'), true, 'the real synthetic provider returns the terminal sign-in result');+ }+ });+});+test('browser state/cookie binding and one-use device ticket protect both sign-in flows [H8, H1]', async (t) => {const box = await fixture(t);const web = box.auth.beginWeb();