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): preserve links on pairing cancel [H5,N26]

Corey Olson6666d7645273
diff --git a/src/relay-setup.js b/src/relay-setup.js
index 09d999e9..0e1a2681 100644
--- a/src/relay-setup.js
+++ b/src/relay-setup.js
@@ -121,46 +121,100 @@ async function linkProjects(session, io) {
return { linked, failed };
}
-/** Publish a one-use public locator and wait in this command; no service or unattended daemon is added. */
-async function pairFirstDevice(session, board, linked, io) {
+/** Wait for the next pairing poll or an abort without leaving an abort listener behind. */
+function waitForPairingPoll(signal) {
+ return new Promise(resolve => {
+ if (signal?.aborted) { resolve(); return; }
+ const finish = () => {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', finish);
+ resolve();
+ };
+ const timer = setTimeout(finish, 500);
+ signal?.addEventListener('abort', finish, { once: true });
+ });
+}
+
+/** Publish a one-use locator and wait in this command; cancellation never undoes linked boards. */
+async function pairFirstDevice(session, board, linked, io, { signal, onPairingURL } = {}) {
+ if (signal?.aborted) {
+ io.say('Boards linked; phone pairing cancelled. Run pullboard relay on --all for a fresh code.');
+ return { paired: false, interrupted: false, pairingOutcome: 'cancelled', pairingCleanup: 'not-published' };
+ }
const pending = beginDeviceEnrollment(board, session);
const path = '/api/v1/devices/enrollments/' + pending.locator;
- await relayDeviceRequest(session, path, { method: 'POST', body: {} }, io);
const link = session.url + '/#device=' + pending.locator + '.' + pending.secret;
- io.say('Pair your phone once: ' + link);
- try { io.say(terminalQr(link)); }
- catch (error) { if (error.code !== 'PAIR_LINK_LONG') throw error; io.say('Open the pairing link above.'); }
let interrupted = false;
- /** End foreground pairing without discarding successful board links or saving a partial device. */
+ let pairingOutcome = 'expired';
+ let pairingCleanup = 'not-published';
+ let locatorMayExist = false;
+ let deviceId;
+ /** Stop foreground polling without discarding successful board links or saving a partial device. */
const stop = () => { interrupted = true; };
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
try {
- while (!interrupted && Date.now() < pending.expires) {
- const result = await relayDeviceRequest(session, path, {}, io);
- if (interrupted) break;
+ locatorMayExist = true;
+ try { await relayDeviceRequest(session, path, { method: 'POST', body: {}, signal }, io); }
+ catch (error) {
+ if (signal?.aborted && error.code === 'OAUTH_CANCELLED') pairingOutcome = 'cancelled';
+ else throw error;
+ }
+ if (signal?.aborted || interrupted) pairingOutcome = 'cancelled';
+ else if (onPairingURL) onPairingURL({ url: link, expires: pending.expires });
+ else {
+ io.say('Pair your phone once: ' + link);
+ try { io.say(terminalQr(link)); }
+ catch (error) { if (error.code !== 'PAIR_LINK_LONG') throw error; io.say('Open the pairing link above.'); }
+ }
+ while (!signal?.aborted && !interrupted && Date.now() < pending.expires) {
+ let result;
+ try { result = await relayDeviceRequest(session, path, { signal }, io); }
+ catch (error) {
+ if (signal?.aborted && error.code === 'OAUTH_CANCELLED') { pairingOutcome = 'cancelled'; break; }
+ throw error;
+ }
+ if (signal?.aborted || interrupted) { pairingOutcome = 'cancelled'; break; }
if (result.enrollment) {
+ // Cancellation may prevent acceptance only before its asynchronous authentication starts.
+ if (signal?.aborted) { pairingOutcome = 'cancelled'; break; }
const device = await acceptDeviceEnrollment(result.enrollment);
await relayDeviceRequest(session, '/api/v1/devices/' + device.deviceId, { method: 'POST', body: {} }, io);
await relayDeviceRequest(session, path, { method: 'DELETE' }, io);
+ locatorMayExist = false;
+ pairingCleanup = 'confirmed';
for (const project of linked) await deliverDeviceWraps(project.root, io);
io.say('Phone paired; current and future linked boards will appear here.');
- return { paired: true, deviceId: device.deviceId };
+ deviceId = device.deviceId;
+ pairingOutcome = 'paired';
+ break;
}
- await new Promise(resolve => { setTimeout(resolve, 500); });
+ await waitForPairingPoll(signal);
}
- io.say('Boards linked; phone pairing stopped. Run pullboard relay on --all for a fresh code.');
- return { paired: false, interrupted };
+ if (pairingOutcome !== 'paired' && (signal?.aborted || interrupted)) pairingOutcome = 'cancelled';
} finally {
process.off('SIGINT', stop); process.off('SIGTERM', stop);
- updateRelayMachine(state => { if (state.pending?.locator === pending.locator) state.pending = null; });
- // Best-effort remove the public locator. Its relay lifetime remains ten minutes on an outage.
- try { await relayDeviceRequest(session, path, { method: 'DELETE' }, io); } catch { /* Never undo completed links after a pairing timeout. */ }
+ try { updateRelayMachine(state => { if (state.pending?.locator === pending.locator) state.pending = null; }); }
+ finally {
+ if (locatorMayExist) {
+ // Cleanup is independent of the caller's aborted signal; never claim deletion if unconfirmed.
+ try {
+ await relayDeviceRequest(session, path, { method: 'DELETE' }, io);
+ pairingCleanup = 'confirmed';
+ } catch { pairingCleanup = 'unconfirmed'; }
+ }
+ }
}
+ if (pairingOutcome === 'paired') return { paired: true, deviceId, pairingOutcome, pairingCleanup };
+ io.say((onPairingURL
+ ? `Boards linked; phone pairing ${pairingOutcome}. Run pullboard relay on --all for a fresh code.`
+ : 'Boards linked; phone pairing stopped. Run pullboard relay on --all for a fresh code.')
+ + (pairingCleanup === 'unconfirmed' ? ' The relay may retain this request until it expires.' : ''));
+ return { paired: false, interrupted: interrupted || Boolean(signal?.aborted), pairingOutcome, pairingCleanup };
}
/** Explicit foreground sign-in repairs links; only board machine credentials survive this command. */
-export async function relayOnAll(address, io, { signal } = {}) {
+export async function relayOnAll(address, io, { signal, onPairingURL } = {}) {
requirePersonChannel(io.personChannel);
// A cancelled or declined sign-in must not migrate machine state or scrub existing board links.
const owner = relayMachineOwner();
@@ -186,6 +240,6 @@ export async function relayOnAll(address, io, { signal } = {}) {
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 }
- : await pairFirstDevice(session, result.linked[0].board, result.linked, io);
+ : await pairFirstDevice(session, result.linked[0].board, result.linked, io, { signal, onPairingURL });
return { ...result, ...pairing, autoLink: true };
}
diff --git a/test/relay.test.js b/test/relay.test.js
index cf19aee3..2f3a83b3 100644
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@ -18,21 +18,76 @@ 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;
+const relayDeviceKeysURL = new URL('../src/relay-device-keys.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)};
+ import { readRelayMachine } from ${JSON.stringify(relayMachineURL)};
+ import { createDeviceKeys, signDeviceEnrollment } from ${JSON.stringify(relayDeviceKeysURL)};
const controller = new AbortController();
const originalFetch = globalThis.fetch;
- if (${JSON.stringify(signalMode)} === 'during-poll') {
+ const mode = ${JSON.stringify(signalMode)};
+ const pairingCallbacks = [];
+ const messages = [];
+ let enrollmentUploaded = false;
+ if (['pairing-cancel', 'pairing-cancel-delete-fails', 'pairing-complete', 'pairing-abort-during-acceptance'].includes(mode)) {
+ globalThis.fetch = async (input, init) => {
+ const url = new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url);
+ const method = init?.method ?? input?.method ?? 'GET';
+ if (mode === 'pairing-cancel-delete-fails' && url.pathname.startsWith('/api/v1/devices/enrollments/') && method === 'DELETE') {
+ return new Response(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture cleanup was not acknowledged' } }),
+ { status: 503, headers: { 'content-type': 'application/json' } });
+ }
+ if (url.pathname.startsWith('/api/v1/devices/enrollments/') && method === 'GET' && controller.signal.aborted) {
+ return new Response(JSON.stringify({ version: 1, error: { code: 'DEVICE_PAIR_EXPIRED', message: 'fixture stopped an ignored pairing cancellation' } }),
+ { status: 410, headers: { 'content-type': 'application/json' } });
+ }
+ const response = await originalFetch(input, init);
+ if (url.pathname.startsWith('/api/v1/devices/enrollments/') && method === 'GET') {
+ if (mode.startsWith('pairing-cancel')) setImmediate(() => controller.abort());
+ if (!mode.startsWith('pairing-cancel') && !enrollmentUploaded && !(await response.clone().json()).enrollment) {
+ const callback = pairingCallbacks[0];
+ const pairingUrl = callback?.url ?? messages.find(value => value.startsWith('Pair your phone once: '))?.slice('Pair your phone once: '.length);
+ if (!pairingUrl) throw new Error('fixture could not find the in-memory pairing link');
+ const fragment = new URL(pairingUrl).hash.slice('#device='.length);
+ const [locator, secret] = fragment.split('.');
+ const headers = new Headers(init?.headers ?? input?.headers);
+ const authorization = headers.get('authorization');
+ const engine = headers.get('x-pullboard-engine');
+ const identityResponse = await originalFetch(new URL('/api/v1/devices/session', url.origin), {
+ headers: { authorization, 'x-pullboard-engine': engine },
+ });
+ const { account } = await identityResponse.json();
+ const keys = await createDeviceKeys();
+ const enrollment = await signDeviceEnrollment(secret, {
+ v: 1, account, locator, deviceId: keys.deviceId, publicKey: keys.publicKey,
+ label: 'fixture phone', createdAt: new Date().toISOString(),
+ });
+ const enrolled = await originalFetch(url.href, {
+ method: 'PUT', headers: { authorization, 'x-pullboard-engine': engine, 'content-type': 'application/json' },
+ body: JSON.stringify(enrollment),
+ });
+ if (!enrolled.ok) throw new Error('fixture device enrollment was refused');
+ enrollmentUploaded = true;
+ if (mode === 'pairing-abort-during-acceptance') {
+ const subtle = globalThis.crypto.subtle;
+ const verify = subtle.verify.bind(subtle);
+ subtle.verify = async (...args) => { controller.abort(); subtle.verify = verify; return verify(...args); };
+ }
+ }
+ }
+ return response;
+ };
+ } else if (mode === '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') {
+ } else if (mode === '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/')) {
@@ -42,10 +97,10 @@ async function runRelayOnAll(box, signalMode) {
return originalFetch(input, init);
};
} else if (['held-poll-response', 'held-poll-response-cancel-fails',
- 'held-poll-response-denied', 'held-poll-response-expired'].includes(${JSON.stringify(signalMode)})) {
+ 'held-poll-response-denied', 'held-poll-response-expired'].includes(mode)) {
globalThis.fetch = async (input, init) => {
const url = new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url);
- if (url.pathname === '/auth/device/cancel' && ${JSON.stringify(signalMode)} === 'held-poll-response-cancel-fails') {
+ if (url.pathname === '/auth/device/cancel' && mode === 'held-poll-response-cancel-fails') {
return new Response(JSON.stringify({ version: 1, error: { code: 'RELAY_ROUTE', message: 'fixture route is unavailable' } }),
{ status: 404, headers: { 'content-type': 'application/json' } });
}
@@ -60,12 +115,23 @@ async function runRelayOnAll(box, signalMode) {
}
return response;
};
- } else if (${JSON.stringify(signalMode)} === 'already-aborted') controller.abort();
+ } else if (mode === 'already-aborted') controller.abort();
const output = { personChannel: 'view', cwd: process.cwd(),
- stderr: { write() {} }, say() {}, err() {} };
+ stderr: { write() {} }, say(value) { messages.push(String(value)); }, err(value) { messages.push(String(value)); } };
try {
- const result = await relayOnAll(${JSON.stringify(box.origin)}, output, { signal: controller.signal });
- process.stdout.write(JSON.stringify(result));
+ const result = await relayOnAll(${JSON.stringify(box.origin)}, output, {
+ signal: controller.signal, onPairingURL(value) { pairingCallbacks.push(value); },
+ });
+ const machine = readRelayMachine();
+ process.stdout.write(JSON.stringify({ ...result,
+ pairingCallbackCount: pairingCallbacks.length,
+ pairingCallbackHasCode: Boolean(pairingCallbacks[0]?.url.includes('#device=')),
+ pairingCallbackExpires: Number.isSafeInteger(pairingCallbacks[0]?.expires),
+ pairingUrlPrinted: messages.some(value => value.includes('#device=')),
+ pairingCleanupWarningShown: messages.some(value => value.includes('may retain this request')),
+ signalAborted: controller.signal.aborted,
+ enrollmentUploaded, pendingCleared: machine.pending === null, deviceCount: machine.devices.length,
+ }));
} catch (error) {
process.stdout.write(JSON.stringify({ errorCode: error.code ?? 'UNEXPECTED_ERROR' }));
process.exitCode = 1;
@@ -344,6 +410,64 @@ test('linking every board stops cleanly when the sign-in is declined or cancelle
});
});
+test('a cancel during pairing keeps the links and stops pairing cleanly [H5,N26]', async (t) => {
+ await t.test('cancellation before the first link remains a no-link outcome', async (t) => {
+ const box = await relayClientFixture(t);
+ await registerSecondProject(box);
+ const result = await runRelayOnAll(box, 'already-aborted');
+ assert.equal(result.code, 0);
+ assert.equal(result.document.outcome, 'cancelled');
+ assert.deepEqual(result.document.linked ?? [], []);
+ assert.equal(box.transit.some(record => record.path === '/auth/boards/link'), false, 'no board-link request starts');
+ assert.equal(result.document.pairingCallbackCount, 0, 'no pairing URL is announced');
+ });
+
+ for (const mode of ['pairing-cancel', 'pairing-cancel-delete-fails']) await t.test(mode, async (t) => {
+ const box = await relayClientFixture(t);
+ await registerSecondProject(box);
+ const result = await runRelayOnAll(box, mode);
+ assert.equal(result.code, 0, 'pairing cancellation is a named successful setup outcome');
+ assert.equal(result.document.pairingOutcome, 'cancelled');
+ assert.equal(result.document.paired, false);
+ assert.equal(result.document.linked.length, 2, 'the completed board links remain in the result');
+ assert.deepEqual(result.document.failed, []);
+ assert.equal(result.document.pendingCleared, true, 'the local pending enrollment is removed');
+ assert.equal(result.document.deviceCount, 0, 'cancellation before acceptance records no device');
+ assert.equal(result.document.pairingCallbackCount, 1, 'the optional pairing callback receives the pairing address');
+ assert.equal(result.document.pairingCallbackHasCode, true);
+ assert.equal(result.document.pairingCallbackExpires, true);
+ assert.equal(result.document.pairingUrlPrinted, false, 'the callback replaces CLI URL/QR output');
+ assert.equal(result.document.signalAborted, true);
+ if (mode === 'pairing-cancel') {
+ assert.equal(result.document.pairingCleanup, 'confirmed');
+ assert.equal(box.transit.filter(record => record.method === 'DELETE' && /\/api\/v1\/devices\/enrollments\//u.test(record.path)).length, 1);
+ } else {
+ assert.equal(result.document.pairingCleanup, 'unconfirmed', 'a refused DELETE is not reported as cleanup success');
+ assert.equal(result.document.pairingCleanupWarningShown, true);
+ }
+ });
+
+ for (const mode of ['pairing-complete', 'pairing-abort-during-acceptance']) await t.test(mode, async (t) => {
+ const box = await relayClientFixture(t);
+ await registerSecondProject(box);
+ const result = await runRelayOnAll(box, mode);
+ assert.equal(result.code, 0, 'the real loopback enrollment completes');
+ assert.equal(result.document.pairingCallbackCount, 1, 'the optional pairing callback receives the pairing address');
+ assert.equal(result.document.pairingUrlPrinted, false, 'the callback replaces CLI URL/QR output');
+ assert.equal(result.document.pairingOutcome, 'paired');
+ assert.equal(result.document.paired, true);
+ assert.equal(result.document.linked.length, 2);
+ assert.deepEqual(result.document.failed, []);
+ assert.equal(result.document.pairingCallbackHasCode, true);
+ assert.equal(result.document.enrollmentUploaded, true);
+ assert.equal(result.document.pendingCleared, true);
+ assert.equal(result.document.deviceCount, 1);
+ assert.equal(box.transit.filter(record => record.method === 'PUT' && /\/api\/v1\/devices\/device-[0-9a-f]{32}\/boards\//u.test(record.path)).length, 2,
+ 'the enrolled device receives wraps for every linked board');
+ assert.equal(result.document.signalAborted, mode === 'pairing-abort-during-acceptance');
+ });
+});
+
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();