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: close relay sign-in cancellation races [H5,N26]
Corey Olson580d6cbaf606
diff --git a/relay/auth-http.js b/relay/auth-http.jsindex b6986514..4bcf5d00 100644--- a/relay/auth-http.js+++ b/relay/auth-http.js@@ -36,7 +36,7 @@ export function createAuthHandler({ auth, publicOrigin }) {try { origin = new URL(publicOrigin); } catch { throw new Refused('RELAY_CONFIG', 'configure the relay public origin'); }if (origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash || (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname)))) throw new Refused('RELAY_CONFIG', 'use an HTTPS public origin, or a loopback HTTP origin for local tests');const secure = origin.protocol === 'https:' ? '; Secure' : '';- const routes = new Set(['GET /auth/github/start', 'GET /auth/github/callback', 'POST /auth/device/start', 'POST /auth/device/poll', 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'POST /auth/machines', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);+ const routes = new Set(['GET /auth/github/start', 'GET /auth/github/callback', 'POST /auth/device/start', 'POST /auth/device/poll', 'POST /auth/device/cancel', 'GET /auth/session', 'GET /auth/boards', 'POST /auth/boards/link', 'POST /auth/machines', 'GET /auth/tokens', 'POST /auth/tokens', 'POST /auth/tokens/revoke']);/** Resolve a bearer or cookie credential; cookie writes require an exact trusted Origin. */function token(req, write = false) {@@ -73,6 +73,9 @@ export function createAuthHandler({ auth, publicOrigin }) {} else if (route === 'POST /auth/device/poll') {const input = await body(req);json(res, 200, await auth.pollDevice(input.ticket));+ } else if (route === 'POST /auth/device/cancel') {+ const input = await body(req);+ json(res, 200, await auth.cancelDevice(input.ticket));} else if (route === 'GET /auth/session') {json(res, 200, { session: await auth.authenticate(token(req), { ...(url.searchParams.has('board') ? { board: url.searchParams.get('board') } : {}) }) });} else if (route === 'GET /auth/boards') {diff --git a/relay/auth.js b/relay/auth.jsindex 529b6f54..c7ea1ae9 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -100,9 +100,10 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =}/** Learn the immutable GitHub identity, then drop the user access credential immediately. */- async function signedIn(result) {+ async function signedIn(result, { cancelled } = {}) {if (!result || result.pending) throw new Refused('OAUTH_STATE', 'complete GitHub sign-in before creating a relay session');const user = await github.user(result.accessToken);+ if (cancelled?.()) throw new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked');open();if (!user || !/^[1-9][0-9]*$/.test(String(user.id)) || typeof user.login !== 'string' || !/^[A-Za-z0-9-]+$/.test(user.login)) throw new Refused('GITHUB_AUTH', 'GitHub did not confirm your account; sign in again');db.prepare('INSERT INTO relay_users (id,login) VALUES (?,?) ON CONFLICT(id) DO UPDATE SET login=excluded.login').run(String(user.id), user.login);@@ -112,7 +113,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =/** Remove expired in-memory flow secrets and limit anonymous sign-in allocations. */function pruneFlows() {open();- for (const map of [webFlows, deviceFlows]) for (const [key, flow] of map) if (flow.expires <= now()) map.delete(key);+ for (const map of [webFlows, deviceFlows]) for (const [key, flow] of map) if (flow.expires <= now() && !flow.busy) map.delete(key);if (webFlows.size + deviceFlows.size >= 10_000) throw new Refused('SIGN_IN_BUSY', 'too many sign-ins are pending; retry shortly');}@@ -177,7 +178,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =const grant = await github.startDevice();pruneFlows();const ticket = random('pd_');- deviceFlows.set(hash(ticket), { deviceCode: grant.deviceCode, expires: now() + grant.expiresIn * 1000, interval: grant.interval, next: now() + grant.interval * 1000 });+ deviceFlows.set(hash(ticket), { deviceCode: grant.deviceCode, expires: now() + grant.expiresIn * 1000, interval: grant.interval, next: now() + grant.interval * 1000, cancelled: false, completed: false, terminalOutcome: null, sessionId: null, pollSettled: null });return { ticket, userCode: grant.userCode, verificationURL: grant.verificationURL, expiresIn: grant.expiresIn, interval: grant.interval };},/** Throttle device polling, honor slow-down, and consume a successful grant only once. */@@ -186,23 +187,72 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =if (typeof ticket !== 'string') throw new Refused('OAUTH_EXPIRED', 'start CLI sign-in again');const key = hash(ticket);const flow = deviceFlows.get(key);- if (!flow || flow.expires <= now()) { deviceFlows.delete(key); throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again'); }+ if (!flow || flow.cancelled || flow.completed) throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again');+ if (flow.expires <= now() && !flow.busy) { deviceFlows.delete(key); throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again'); }if (flow.busy || flow.next > now()) return { pending: true, retryAfter: Math.max(1, Math.ceil((flow.next - now()) / 1000)) };flow.next = now() + flow.interval * 1000;flow.busy = true;- let result;- try { result = await github.pollDevice(flow.deviceCode); }- catch (error) { if (['OAUTH_DENIED', 'OAUTH_EXPIRED'].includes(error.code)) deviceFlows.delete(key); throw error; }- finally { flow.busy = false; }- if (flow.expires <= now()) { deviceFlows.delete(key); throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again'); }- if (result.pending) {- if (result.slow) flow.interval += 5;- if (Number.isFinite(result.interval) && result.interval > flow.interval) flow.interval = result.interval;- flow.next = now() + flow.interval * 1000;- return { pending: true, retryAfter: flow.interval };+ let settle;+ flow.pollSettled = new Promise(resolve => { settle = resolve; });+ try {+ let result;+ try { result = await github.pollDevice(flow.deviceCode); }+ catch (error) {+ if (flow.cancelled) throw new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked');+ if (['OAUTH_DENIED', 'OAUTH_EXPIRED'].includes(error.code)) {+ // Keep only the ticket hash and terminal class until the original flow expiry. A+ // cancel racing the held HTTP response can then be acknowledged without retaining+ // the provider code or treating an unknown/restarted ticket as cleaned up.+ flow.deviceCode = null;+ flow.terminalOutcome = error.code;+ flow.completed = true;+ }+ throw error;+ }+ if (flow.cancelled) throw new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked');+ if (flow.expires <= now()) { deviceFlows.delete(key); throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again'); }+ if (result.pending) {+ if (result.slow) flow.interval += 5;+ if (Number.isFinite(result.interval) && result.interval > flow.interval) flow.interval = result.interval;+ flow.next = now() + flow.interval * 1000;+ return { pending: true, retryAfter: flow.interval };+ }+ const session = await signedIn(result, { cancelled: () => flow.cancelled });+ // `signedIn` awaits GitHub before issuing; this second check closes the remaining async+ // boundary. If cancellation raced the synchronous insert, revoke only this flow's row.+ flow.deviceCode = null;+ flow.sessionId = session.id;+ flow.completed = true;+ if (flow.cancelled || flow.expires <= now()) {+ db.prepare("UPDATE relay_credentials SET revoked=1 WHERE id=? AND kind='session'").run(flow.sessionId);+ throw flow.cancelled+ ? new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked')+ : new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again');+ }+ return session;+ } finally {+ flow.busy = false;+ flow.pollSettled = null;+ settle();}- deviceFlows.delete(key);- return signedIn(result);+ },+ /** Cancel one bearer-ticket flow and revoke only the session it minted, if any. */+ async cancelDevice(ticket) {+ open();+ if (typeof ticket !== 'string' || !/^pd_[A-Za-z0-9_-]{43}$/u.test(ticket)) return { cancelled: false };+ const key = hash(ticket);+ const flow = deviceFlows.get(key);+ if (!flow || (flow.expires <= now() && !flow.busy)) {+ if (flow && !flow.busy) deviceFlows.delete(key);+ return { cancelled: false };+ }+ flow.cancelled = true;+ const pollSettled = flow.pollSettled;+ if (pollSettled) await pollSettled;+ flow.deviceCode = null;+ if (flow.sessionId) db.prepare("UPDATE relay_credentials SET revoked=1 WHERE id=? AND kind='session'").run(flow.sessionId);+ flow.sessionId = null;+ return { cancelled: true };},/** Authenticate a human or a scoped agent; every board write asks GitHub again. */async authenticate(token, { board, write = false } = {}) {diff --git a/src/relay-setup.js b/src/relay-setup.jsindex f8905269..09d999e9 100644--- a/src/relay-setup.js+++ b/src/relay-setup.js@@ -7,7 +7,7 @@ import { requirePersonChannel } from './person.js';import { codeIsFromMain, repoInfo } from './git.js';import { listApiProjects } from './projects.js';import { acceptDeviceEnrollment, beginDeviceEnrollment, readRelayMachine, relayMachineOwner, updateRelayMachine } from './relay-machine.js';-import { deliverDeviceWraps, relayDeviceRequest, relayMachineSignIn, relayMachineContext, relayRevokeDevice, relayOn, relayStatus, originRepository } from './relay.js';+import { deliverDeviceWraps, relayDeviceRequest, relayMachineSignIn, relayMachineContext, relayRevokeDevice, relayOn, relayStatus, originRepository, revokeRelayPersonSession } from './relay.js';import { terminalQr } from './qr.js';import { Refused } from './refused.js';@@ -166,9 +166,20 @@ export async function relayOnAll(address, io, { signal } = {}) {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' };+ if (signal?.aborted) {+ await revokeRelayPersonSession(session, io);+ return { outcome: 'cancelled' };+ }+ try { await flushRevocations(session, io); }+ catch (error) {+ if (!signal?.aborted) throw error;+ await revokeRelayPersonSession(session, io);+ return { outcome: 'cancelled' };+ }+ if (signal?.aborted) {+ await revokeRelayPersonSession(session, io);+ 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 = []; });diff --git a/src/relay.js b/src/relay.jsindex bdb89314..851c0d73 100644--- a/src/relay.js+++ b/src/relay.js@@ -1192,26 +1192,53 @@ function waitForDevicePoll(seconds, signal) {});}+/** Cancel one device ticket without the already-aborted caller signal. */+async function cancelDeviceFlow(url, ticket, io) {+ let result;+ try { result = await request({ url }, '/auth/device/cancel', { method: 'POST', body: { ticket } }, io); }+ catch {+ throw new Refused('OAUTH_CLEANUP', 'the relay could not confirm cleanup of the cancelled sign-in; retry before linking boards');+ }+ if (result.cancelled !== true) throw new Refused('OAUTH_CLEANUP', 'the relay did not confirm cleanup of the cancelled sign-in; retry before linking boards');+}++/** Revoke only the fresh person session created by this explicit device sign-in. */+export async function revokeRelayPersonSession(session, io) {+ if (!session || typeof session.token !== 'string' || !/^ps_[A-Za-z0-9_-]{43}$/.test(session.token) || typeof session.id !== 'string') {+ throw new Refused('OAUTH_CLEANUP', 'the relay session could not be identified for cancellation cleanup');+ }+ const result = await request({ url: session.url, token: session.token }, '/auth/tokens/revoke', { method: 'POST', body: { id: session.id } }, io);+ if (result.id !== session.id || result.revoked !== true) throw new Refused('OAUTH_CLEANUP', 'the relay did not confirm cleanup of the cancelled sign-in; retry before linking boards');+}+/** 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: {}, 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 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 }, signal }, io);+ try {cancellationOutcome(signal);- wait = signed.retryAfter ?? flow.interval;- } while (signed.pending);- const token = signed.token;- if (!/^ps_[A-Za-z0-9_-]{43}$/.test(token)) throw new Refused('RELAY_RESPONSE', 'the relay did not issue a person session; sign in again');- return signed;+ 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 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 }, signal }, io);+ cancellationOutcome(signal);+ wait = signed.retryAfter ?? flow.interval;+ } while (signed.pending);+ const token = signed.token;+ if (!/^ps_[A-Za-z0-9_-]{43}$/.test(token)) throw new Refused('RELAY_RESPONSE', 'the relay did not issue a person session; sign in again');+ return signed;+ } catch (error) {+ if (signal?.aborted || error.code === 'OAUTH_CANCELLED') {+ await cancelDeviceFlow(url, flow.ticket, io);+ throw new Refused('OAUTH_CANCELLED', 'GitHub device sign-in was cancelled; no board was linked');+ }+ throw error;+ }}/** Explicitly sign in through the relay and persist a sealed initial snapshot before uploading it. */@@ -1338,12 +1365,16 @@ export async function relayMachineSignIn(address, io, { signal } = {}) {let signed;try { signed = await deviceSignIn(url, io, { signal }); }catch (error) {+ if (error.code === 'OAUTH_CLEANUP') throw 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 (signal?.aborted) {+ await revokeRelayPersonSession({ ...signed, url }, io);+ 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 9608499c..24480e6b 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -586,7 +586,7 @@ globalThis.fetch = function tracedFetch(input, init) {return childResult(root, env, ['--input-type=module', '-e', source]);}return {- transit, providerState: provider.state, providerCalls: provider.calls, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,+ transit, providerState: provider.state, providerCalls: provider.calls, relayDirectory: join(scratch, 'relay'), authDatabase, auth, 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() {diff --git a/test/relay-fixture.js b/test/relay-fixture.jsindex 3c06b468..6cb42388 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, deviceDeclined: false, deviceExpired: 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, beforeDevicePoll: null, beforeUser: null };const calls = [];const codes = new Map();const userTokens = new Set();@@ -77,6 +77,7 @@ export async function githubFixture(t) {assert.equal(form.get('client_secret'), null);assert.equal(form.get('grant_type'), 'urn:ietf:params:oauth:grant-type:device_code');assert.equal(form.get('device_code'), deviceCode);+ if (state.beforeDevicePoll) await state.beforeDevicePoll();if (state.slow) { state.slow = false; return reply(res, 200, { error: 'slow_down' }); }return reply(res, 200, state.deviceDeclined ? { error: 'access_denied' }: state.deviceExpired ? { error: 'expired_token' }@@ -90,6 +91,7 @@ export async function githubFixture(t) {}if (url.pathname === '/user') {if (state.redirect) { res.writeHead(302, { location: state.redirect }); return res.end(); }+ if (state.beforeUser) await state.beforeUser();return reply(res, isUser ? 200 : 401, { id: state.accountID, login: 'fixture-user' });}if (url.pathname === '/repos/fixture/repository/installation') return reply(res, isApp && state.installed ? 200 : 404, { id: 42 });diff --git a/test/relay.test.js b/test/relay.test.jsindex 697be7b1..dc9f6d43 100644--- a/test/relay.test.js+++ b/test/relay.test.js@@ -41,11 +41,35 @@ 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)})) {+ 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') {+ return new Response(JSON.stringify({ version: 1, error: { code: 'RELAY_ROUTE', message: 'fixture route is unavailable' } }),+ { status: 404, headers: { 'content-type': 'application/json' } });+ }+ const response = await originalFetch(input, init);+ if (url.pathname === '/auth/device/poll') {+ const body = await response.text();+ await new Promise(resolve => {+ controller.signal.addEventListener('abort', resolve, { once: true });+ setImmediate(() => controller.abort());+ });+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });+ }+ return response;+ };} 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));+ try {+ const result = await relayOnAll(${JSON.stringify(box.origin)}, output, { signal: controller.signal });+ process.stdout.write(JSON.stringify(result));+ } catch (error) {+ process.stdout.write(JSON.stringify({ errorCode: error.code ?? 'UNEXPECTED_ERROR' }));+ process.exitCode = 1;+ }`);}@@ -61,6 +85,20 @@ async function seedRevocation(box) {/** Snapshot only private local metadata that cancellation must leave byte-for-byte unchanged. */function fileSnapshot(path) { return existsSync(path) ? readFileSync(path) : null; }+/** Count live person-session ids without reading bearer hashes or token plaintext. */+function livePersonSessionIds(box) {+ const db = new DatabaseSync(box.authDatabase ?? box.database, { readOnly: true });+ try { return db.prepare("SELECT id FROM relay_credentials WHERE kind='session' AND revoked=0 AND expires>? ORDER BY id").all(Date.now()).map(row => row.id); }+ finally { db.close(); }+}++/** Revoke only test-created session rows after asserting a fail-closed cleanup refusal. */+function revokeFixtureSessions(box, ids) {+ const db = new DatabaseSync(box.authDatabase ?? box.database);+ try { for (const id of ids) db.prepare("UPDATE relay_credentials SET revoked=1 WHERE kind='session' AND id=?").run(id); }+ finally { db.close(); }+}+/** 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');@@ -109,6 +147,8 @@ test('linking every board stops cleanly when the sign-in is declined or cancellebox.overrideDelete({ status: 200 });assert.equal((await seedRevocation(box)).code, 0, 'a prior revocation is queued before setup begins');}+ const priorSession = scenario === 'cancelled-after-sign-in' ? await box.phoneSession() : null;+ const sessionsBefore = livePersonSessionIds(box);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') {@@ -128,6 +168,8 @@ test('linking every board stops cleanly when the sign-in is declined or cancelleassert.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');+ assert.deepEqual(livePersonSessionIds(box), sessionsBefore, 'a pre-link terminal outcome leaves no new live person session');+ if (priorSession) assert.equal((await box.auth.authenticate(priorSession.token)).id, priorSession.id, 'cancellation preserves the preexisting person session');if (scenario === 'cancelled-after-sign-in') {const prior = JSON.parse(before.get(machineFile).toString('utf8'));const after = JSON.parse(fileSnapshot(machineFile).toString('utf8'));@@ -153,6 +195,104 @@ test('linking every board stops cleanly when the sign-in is declined or cancelleassert.equal(box.providerCalls.some(call => call.path === '/login/oauth/access_token'), true, 'the real synthetic provider returns the terminal sign-in result');}});++ await t.test('cancellation revokes a session minted behind a held poll response', async (t) => {+ const box = await relayClientFixture(t);+ const second = await registerSecondProject(box);+ box.refuseBoardLinks(true);+ const priorSession = await box.phoneSession();+ const sessionsBefore = livePersonSessionIds(box);+ const before = [box.linkFile, second.linkFile, box.keyFile, second.keyFile].map(path => [path, fileSnapshot(path)]);+ const result = await runRelayOnAll(box, 'held-poll-response');+ assert.equal(result.code, 0, 'the held response is canceled through the ticket cleanup path');+ assert.equal(result.document.outcome, 'cancelled', 'the caller reports cancellation only after cleanup confirmation');+ assert.deepEqual(livePersonSessionIds(box), sessionsBefore, 'the just-minted session is revoked');+ assert.equal((await box.auth.authenticate(priorSession.token)).id, priorSession.id, 'cleanup does not revoke a preexisting session');+ assert.equal(box.transit.filter(record => record.method === 'POST' && record.path === '/auth/device/cancel').length, 1,+ 'the held device flow is canceled through its ticket');+ for (const [path, contents] of before) assert.deepEqual(fileSnapshot(path), contents, 'a canceled poll leaves board links and keys unchanged');+ });++ for (const terminal of ['denied', 'expired']) await t.test(`cancellation acknowledges a held ${terminal} poll response without changing sessions`, async (t) => {+ const box = await relayClientFixture(t);+ const second = await registerSecondProject(box);+ box.refuseBoardLinks(true);+ box.providerState.deviceDeclined = terminal === 'denied';+ box.providerState.deviceExpired = terminal === 'expired';+ const priorSession = await box.phoneSession();+ const providerCallsBeforeAttempt = box.providerCalls.length;+ const sessionsBefore = livePersonSessionIds(box);+ const before = [box.linkFile, second.linkFile, box.keyFile, second.keyFile].map(path => [path, fileSnapshot(path)]);+ const result = await runRelayOnAll(box, `held-poll-response-${terminal}`);+ assert.equal(result.code, 0, 'a known terminal provider result is cleanable while its response is held');+ assert.equal(result.document.outcome, 'cancelled', 'cancellation is confirmed for this known terminal flow');+ assert.deepEqual(livePersonSessionIds(box), sessionsBefore, 'terminal provider results mint no person session');+ assert.equal((await box.auth.authenticate(priorSession.token)).id, priorSession.id, 'terminal cleanup preserves the prior session');+ assert.equal(box.transit.filter(record => record.method === 'POST' && record.path === '/auth/device/cancel').length, 1,+ 'the terminal flow is acknowledged through its exact ticket');+ assert.equal(box.providerCalls.slice(providerCallsBeforeAttempt).some(call => call.path === '/user'), false,+ 'a terminal provider response never reaches identity lookup');+ assert.equal(box.transit.some(record => record.path === '/auth/boards/link' || record.path === '/auth/machines'), false,+ 'terminal cancellation never begins a board or machine write');+ for (const [path, contents] of before) assert.deepEqual(fileSnapshot(path), contents, 'terminal cancellation leaves board links and keys unchanged');+ });++ await t.test('cancellation during provider polling does not mint a person session', async (t) => {+ const box = await fixture(t);+ let markStarted;+ let release;+ const started = new Promise(resolve => { markStarted = resolve; });+ const held = new Promise(resolve => { release = resolve; });+ box.state.deviceAuthorized = true;+ box.state.beforeDevicePoll = async () => { box.state.beforeDevicePoll = null; markStarted(); await held; };+ const grant = await box.auth.beginDevice();+ box.advance(grant.interval * 1000);+ const before = livePersonSessionIds({ authDatabase: box.database });+ const poll = box.auth.pollDevice(grant.ticket);+ await started;+ const cancellation = box.auth.cancelDevice(grant.ticket);+ release();+ await assert.rejects(poll, { code: 'OAUTH_CANCELLED' }, 'the provider result is discarded after cancellation');+ assert.deepEqual(await cancellation, { cancelled: true }, 'ticket cancellation waits for the provider operation to settle');+ assert.deepEqual(livePersonSessionIds({ authDatabase: box.database }), before, 'the canceled provider result creates no session');+ });++ await t.test('cancellation during GitHub identity lookup does not mint a person session', async (t) => {+ const box = await fixture(t);+ let markStarted;+ let release;+ const started = new Promise(resolve => { markStarted = resolve; });+ const held = new Promise(resolve => { release = resolve; });+ box.state.deviceAuthorized = true;+ box.state.beforeUser = async () => { box.state.beforeUser = null; markStarted(); await held; };+ const grant = await box.auth.beginDevice();+ box.advance(grant.interval * 1000);+ const before = livePersonSessionIds({ authDatabase: box.database });+ const poll = box.auth.pollDevice(grant.ticket);+ await started;+ const cancellation = box.auth.cancelDevice(grant.ticket);+ release();+ await assert.rejects(poll, { code: 'OAUTH_CANCELLED' }, 'the identity result is discarded after cancellation');+ assert.deepEqual(await cancellation, { cancelled: true }, 'cancellation waits for identity lookup to settle');+ assert.deepEqual(livePersonSessionIds({ authDatabase: box.database }), before, 'the canceled identity result creates no session');+ });++ await t.test('a failed cancellation acknowledgement is not reported as success', async (t) => {+ const box = await relayClientFixture(t);+ box.refuseBoardLinks(true);+ const sessionsBefore = livePersonSessionIds(box);+ const result = await runRelayOnAll(box, 'held-poll-response-cancel-fails');+ assert.notEqual(result.code, 0, 'a failed cleanup acknowledgement fails the caller closed');+ assert.equal(result.document.errorCode, 'OAUTH_CLEANUP', 'cleanup failure is surfaced as a typed refusal');+ assert.equal(box.transit.some(record => record.method === 'POST' && record.path === '/auth/device/cancel'), false,+ 'the unavailable cancel endpoint receives no request at the fixture');+ const after = livePersonSessionIds(box);+ const leaked = after.filter(id => !sessionsBefore.includes(id));+ assert.equal(leaked.length, 1, 'the test confirms cleanup was not falsely reported when the endpoint was unavailable');+ assert.equal(box.transit.some(record => record.path === '/auth/boards/link' || record.path === '/auth/machines'), false,+ 'failed cancellation never begins a board or machine write');+ revokeFixtureSessions(box, leaked);+ });});test('browser state/cookie binding and one-use device ticket protect both sign-in flows [H8, H1]', async (t) => {