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.

feat: expose cancellable view sign-in [H5,N26]

Corey Olson2cf885e76f56
diff --git a/src/relay-setup.js b/src/relay-setup.js
index 0e1a2681..b3ed0108 100644
--- a/src/relay-setup.js
+++ b/src/relay-setup.js
@@ -1,5 +1,6 @@
/** Set up a machine once, enroll its phone in the foreground and link later registrations [H5,H17]. */
import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
import * as store from './board.js';
import { phoneProposal, publishPhoneApproval, warnPhoneApproval } from './relay-phone.js';
import { openApproval, restoreLinkReply } from './relay-approval.js';
@@ -102,7 +103,7 @@ export async function revokeRelayDevice(deviceId, io) {
}
/** Link every non-excluded registry entry, collecting project-specific partial failures. */
-async function linkProjects(session, io) {
+async function linkProjects(session, io, { onBoardOutcome } = {}) {
const machine = readRelayMachine();
const linked = [];
const failed = [];
@@ -111,10 +112,12 @@ async function linkProjects(session, io) {
try {
const result = await relayOn(project.root, session.url, io, { session, quiet: true, strict: true });
linked.push({ project: project.name, root: project.root, board: result.board });
+ onBoardOutcome?.({ root: project.root, name: project.name, outcome: 'linked', reason: '' });
io.say(`linked: ${project.name}`);
} catch (error) {
const reason = error instanceof Refused ? error.message : 'Restore this registered project and retry.';
failed.push({ project: project.name, root: project.root, reason });
+ onBoardOutcome?.({ root: project.root, name: project.name, outcome: 'failed', reason });
io.err(`not linked: ${project.name}; ${reason}`);
}
}
@@ -214,11 +217,11 @@ async function pairFirstDevice(session, board, linked, io, { signal, onPairingUR
}
/** Explicit foreground sign-in repairs links; only board machine credentials survive this command. */
-export async function relayOnAll(address, io, { signal, onPairingURL } = {}) {
+export async function relayOnAll(address, io, { signal, onPairingURL, onSignIn, onLinking, onBoardOutcome } = {}) {
requirePersonChannel(io.personChannel);
// 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 });
+ const session = await relayMachineSignIn(address || owner?.url, io, { signal, onSignIn });
if (session.outcome) return session;
if (signal?.aborted) {
await revokeRelayPersonSession(session, io);
@@ -236,10 +239,160 @@ export async function relayOnAll(address, io, { signal, onPairingURL } = {}) {
}
// 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.
+ onLinking?.();
updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = []; });
- const result = await linkProjects(session, io);
+ const result = await linkProjects(session, io, { onBoardOutcome });
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, { signal, onPairingURL });
return { ...result, ...pairing, autoLink: true };
}
+
+// These operations belong to this view process. No ticket, person session, or pairing URL is
+// serialized into the machine record or returned as part of an operation's public status.
+const viewSignIns = new Map();
+const VIEW_INTENT_LIMIT = 32;
+const VIEW_RESULT_LIFETIME_MS = 10 * 60_000;
+const VIEW_TERMINAL_STATES = new Set(['done', 'declined', 'expired', 'cancelled', 'pairing-stopped']);
+
+/** Forget finished operations after a bounded retention period without disturbing live cleanup. */
+function pruneViewSignIns() {
+ const now = Date.now();
+ for (const [id, operation] of viewSignIns) {
+ if (operation.finishedAt && now - operation.finishedAt >= VIEW_RESULT_LIFETIME_MS) viewSignIns.delete(id);
+ }
+ while (viewSignIns.size >= VIEW_INTENT_LIMIT) {
+ const finished = [...viewSignIns].find(([, operation]) => operation.finishedAt);
+ if (!finished) break;
+ viewSignIns.delete(finished[0]);
+ }
+}
+
+/** Read a process-local operation without accepting an arbitrary relay ticket or person credential. */
+function viewSignInIntent(intentId) {
+ pruneViewSignIns();
+ const operation = typeof intentId === 'string' && viewSignIns.get(intentId);
+ if (!operation) throw new Refused('VIEW_SIGN_IN_UNKNOWN', 'this view sign-in is no longer available; start sign-in again');
+ return operation;
+}
+
+/** Return only public outcomes, never the private controller, ticket, or pairing capability. */
+function viewSignInPublic(operation) {
+ return {
+ state: operation.state,
+ boards: operation.boards.map(board => ({ ...board })),
+ ...(operation.error ? { error: { ...operation.error } } : {}),
+ ...(operation.pairingCleanup ? { pairingCleanup: operation.pairingCleanup } : {}),
+ };
+}
+
+/** Keep upstream diagnostics useful without reflecting a bearer accidentally included in an error. */
+function viewSignInReason(message) {
+ return String(message).replace(/\b(?:ps_|pa_|pm_|pd_|pg_|ghu_|ghs_)[A-Za-z0-9_-]{20,}\b/gu, '[redacted credential]');
+}
+
+/** Validate the provider's public device instructions before the view opens a browser address. */
+function viewDeviceInstructions(flow) {
+ let verification;
+ let relay;
+ try { verification = new URL(flow.verificationURL); relay = new URL(flow.relayUrl); } catch { /* Refuse below. */ }
+ const loopback = hostname => ['127.0.0.1', 'localhost', '[::1]'].includes(hostname);
+ if (!verification || !relay || verification.username || verification.password || verification.hash
+ || !((verification.protocol === 'https:' && verification.hostname === 'github.com'
+ && verification.port === '' && verification.pathname === '/login/device' && !verification.search)
+ || (verification.protocol === 'http:' && loopback(verification.hostname)
+ && relay.protocol === 'http:' && loopback(relay.hostname) && verification.pathname === '/login/device' && !verification.search))
+ || typeof flow.userCode !== 'string' || !/^[\x21-\x7e]{1,128}$/u.test(flow.userCode)
+ || !Number.isSafeInteger(flow.expiresAt) || flow.expiresAt <= Date.now()) {
+ throw new Refused('VIEW_SIGN_IN_RESPONSE', 'the relay returned invalid sign-in instructions; check its address and start again');
+ }
+ return { verificationURL: verification.href, userCode: flow.userCode, expiresAt: flow.expiresAt };
+}
+
+/** Start the existing device flow in RAM; the view receives only its public link, code and id. */
+export async function startViewSignIn({ relayUrl, signal } = {}) {
+ if (signal?.aborted) throw new Refused('OAUTH_CANCELLED', 'sign-in was cancelled before it started; no board was linked');
+ pruneViewSignIns();
+ if ([...viewSignIns.values()].some(operation => !operation.finishedAt)) {
+ throw new Refused('VIEW_SIGN_IN_BUSY', 'this view is already signing in; finish or cancel that sign-in first');
+ }
+ const intentId = randomUUID();
+ const operation = { state: 'waiting', boards: [], controller: new AbortController(), pairing: null, finishedAt: null };
+ const abortStarting = () => operation.controller.abort();
+ signal?.addEventListener('abort', abortStarting, { once: true });
+ viewSignIns.set(intentId, operation);
+ let resolveReady;
+ let rejectReady;
+ let published = false;
+ const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
+ // The established linking path still owns authorization and pairing. Its terminal IO is a
+ // sink; progress enters this operation only through typed callbacks, never parsed text.
+ const io = { personChannel: 'view', say() {}, err() {}, stderr: { write() {} } };
+ operation.finished = Promise.resolve().then(() => relayOnAll(relayUrl, io, {
+ signal: operation.controller.signal,
+ onSignIn(flow) {
+ let instructions;
+ try { instructions = viewDeviceInstructions(flow); }
+ catch (error) { operation.controller.abort(); rejectReady(error); throw error; }
+ published = true;
+ resolveReady({ intentId, ...instructions });
+ },
+ onLinking() { operation.state = 'linking'; },
+ onBoardOutcome(board) {
+ operation.boards = operation.boards.filter(prior => prior.root !== board.root);
+ operation.boards.push({ ...board, reason: viewSignInReason(board.reason) });
+ },
+ onPairingURL(pairing) { operation.state = 'pairing'; operation.pairing = { ...pairing }; },
+ })).then(result => {
+ operation.state = result.outcome ?? (result.pairingOutcome && result.pairingOutcome !== 'paired' ? 'pairing-stopped' : 'done');
+ if (result.pairingCleanup) operation.pairingCleanup = result.pairingCleanup;
+ if (result.pairingCleanup === 'unconfirmed') operation.error = { code: 'VIEW_PAIRING_CLEANUP',
+ message: 'boards remain linked; the relay could not confirm phone-pairing cleanup and may retain the request until it expires' };
+ if (!published) rejectReady(new Refused(result.outcome === 'cancelled' ? 'OAUTH_CANCELLED' : 'VIEW_SIGN_IN_STOPPED',
+ 'sign-in stopped before instructions were available; no board was linked'));
+ }, error => {
+ operation.state = 'done';
+ operation.error = { code: error instanceof Refused ? error.code : 'VIEW_SIGN_IN_FAILED',
+ message: error instanceof Refused ? viewSignInReason(error.message) : 'sign-in could not finish; check the relay and try again' };
+ if (!published) rejectReady(error);
+ }).finally(() => {
+ operation.pairing = null;
+ operation.finishedAt = Date.now();
+ });
+ try { return await ready; }
+ catch (error) {
+ // A rejected instruction response must not hide a later failure to cancel its real ticket.
+ await operation.finished;
+ if (operation.error?.code === 'OAUTH_CLEANUP') throw new Refused(operation.error.code, operation.error.message);
+ throw error;
+ } finally { signal?.removeEventListener('abort', abortStarting); }
+}
+
+/** Poll only public operation progress; core, not the browser, polls the private relay ticket. */
+export function viewSignInStatus(intentId) {
+ return viewSignInPublic(viewSignInIntent(intentId));
+}
+
+/** Give the authenticated view server a transient pairing redirect, never a JSON status field. */
+export function viewSignInPairingNavigation(intentId) {
+ const operation = viewSignInIntent(intentId);
+ if (operation.controller.signal.aborted || operation.state !== 'pairing' || !operation.pairing || operation.pairing.expires <= Date.now()) {
+ throw new Refused('VIEW_PAIRING_NOT_READY', 'phone pairing is not waiting; read this sign-in’s current status');
+ }
+ return { ...operation.pairing };
+}
+
+/** Cancel and await actual cleanup, preserving linked boards if linking already began. */
+export async function cancelViewSignIn(intentId) {
+ const operation = viewSignInIntent(intentId);
+ if (operation.state === 'linking') {
+ throw new Refused('VIEW_SIGN_IN_LINKING', 'board linking has started and will finish as one batch; stop phone pairing when it begins');
+ }
+ if (!VIEW_TERMINAL_STATES.has(operation.state)) {
+ // Stop publishing the capability synchronously; remote deletion may still be pending.
+ operation.pairing = null;
+ operation.controller.abort();
+ }
+ await operation.finished;
+ return viewSignInPublic(operation);
+}
diff --git a/src/relay.js b/src/relay.js
index 851c0d73..86de93a6 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -571,6 +571,12 @@ async function flushMirror(root, file, state, io) {
/** A saved link is the opt-in boundary; unlinked callers neither read keys nor contact the relay. */
export function relayLinked(root) { return Boolean(loadLink(linkFile(root))); }
+/** Read validated View eligibility without decoding snapshots, opening a board or contacting the relay. */
+export function relayLinkAvailability(root) {
+ const state = loadLink(linkFile(root));
+ return { linked: Boolean(state && !state.unlinking), unlinking: Boolean(state?.unlinking) };
+}
+
/** Authenticate and decode one opaque relay record on this device alone. */
async function decoded(key, record, state, kind, sequence) {
const bytes = Buffer.from(record.sealed, 'base64url');
@@ -1212,7 +1218,7 @@ export async function revokeRelayPersonSession(session, io) {
}
/** Sign in with the caller's cancellation signal; no board credential is persisted here. */
-async function deviceSignIn(url, io, { signal } = {}) {
+async function deviceSignIn(url, io, { signal, onSignIn } = {}) {
cancellationOutcome(signal);
const client = { url };
const flow = await request(client, '/auth/device/start', { method: 'POST', body: {}, signal }, io);
@@ -1220,6 +1226,8 @@ async function deviceSignIn(url, io, { signal } = {}) {
cancellationOutcome(signal);
io.stderr.write(`Sign in with GitHub: open ${flow.verificationURL} and enter ${flow.userCode}\n`);
const expires = Date.now() + flow.expiresIn * 1000;
+ // The view receives only the public device instructions. The ticket stays in this stack.
+ onSignIn?.({ verificationURL: flow.verificationURL, userCode: flow.userCode, expiresAt: expires, relayUrl: url });
let signed;
let wait = flow.interval;
do {
@@ -1359,11 +1367,11 @@ 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, { signal } = {}) {
+export async function relayMachineSignIn(address, io, { signal, onSignIn } = {}) {
requirePersonChannel(io.personChannel);
const url = relayOrigin(address || DEFAULT_RELAY);
let signed;
- try { signed = await deviceSignIn(url, io, { signal }); }
+ try { signed = await deviceSignIn(url, io, { signal, onSignIn }); }
catch (error) {
if (error.code === 'OAUTH_CLEANUP') throw error;
if (signal?.aborted || error.code === 'OAUTH_CANCELLED') return { outcome: 'cancelled' };
diff --git a/test/relay-setup.test.js b/test/relay-setup.test.js
new file mode 100644
index 00000000..58c83673
--- /dev/null
+++ b/test/relay-setup.test.js
@@ -0,0 +1,224 @@
+/** The view uses the actual device authorization and all-board linking path without a terminal [H5,N26]. */
+import assert from 'node:assert/strict';
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { test } from 'node:test';
+import * as setup from '../src/relay-setup.js';
+import { relayClientFixture } from './relay-client-fixture.js';
+
+/** Run the public view adapter in a process whose complete home, registry and boards are private. */
+async function viewScenario(box, mode) {
+ const setupModule = pathToFileURL(resolve(import.meta.dirname, '../src/relay-setup.js')).href;
+ const relayModule = pathToFileURL(resolve(import.meta.dirname, '../src/relay.js')).href;
+ const cliModule = pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href;
+ const fixtureModule = pathToFileURL(resolve(import.meta.dirname, 'fixture-child.js')).href;
+ return box.script(`
+import assert from 'node:assert/strict';
+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import * as setup from ${JSON.stringify(setupModule)};
+import { relayLinkAvailability } from ${JSON.stringify(relayModule)};
+import { main } from ${JSON.stringify(cliModule)};
+import { runFixtureGit } from ${JSON.stringify(fixtureModule)};
+const root = ${JSON.stringify(box.root)};
+const relayUrl = ${JSON.stringify(box.origin)};
+const mode = ${JSON.stringify(mode)};
+const shouldLink = ['linked','pairing-cleanup-refused'].includes(mode);
+const other = join(dirname(root), 'second-view-board');
+mkdirSync(other);
+for (const args of [['init','-q','-b','main'], ['-c','commit.gpgsign=false','commit','--allow-empty','-q','-m','chore: private view board'],
+ ['remote','add','origin','[email protected]:fixture/repository.git']]) runFixtureGit(args, {cwd:other,env:process.env});
+const quiet = {cwd:other,stdin:process.stdin,stdout:{isTTY:false,write(){}},stderr:{write(){}}};
+assert.equal(await main(['init','--json'], quiet), 0, 'the second board is registered through the production CLI');
+const links = [root,other].map(repo => join(repo,'.git','pullboard','relay.json'));
+for (const repo of [root,other]) assert.deepEqual(relayLinkAvailability(repo),{linked:false,unlinking:false});
+let intentId;
+let linkingCancelRefused = false;
+let releasePairingDelete;
+let pairingDeleteStarted = false;
+let holdPairingDelete = mode === 'linked';
+let releaseDeviceCancel;
+let deviceCancelStarted = false;
+let holdDeviceCancel = true;
+let corruptInstructions = ['invalid-url','cleanup-refused'].includes(mode);
+const originalFetch = globalThis.fetch;
+const starting = new AbortController();
+globalThis.fetch = async (input, options) => {
+ const address = new URL(input instanceof Request ? input.url : input);
+ if (mode === 'abort-start' && address.pathname === '/auth/device/start') {
+ starting.abort();
+ throw new DOMException('private start aborted', 'AbortError');
+ }
+ if (shouldLink && address.pathname === '/auth/boards/link' && !linkingCancelRefused) {
+ assert.equal(setup.viewSignInStatus(intentId).state, 'linking');
+ await assert.rejects(setup.cancelViewSignIn(intentId), {code:'VIEW_SIGN_IN_LINKING'});
+ linkingCancelRefused = true;
+ }
+ if (holdPairingDelete && options?.method === 'DELETE' && address.pathname.startsWith('/api/v1/devices/enrollments/')) {
+ pairingDeleteStarted = true;
+ await new Promise(resolve => { releasePairingDelete = resolve; });
+ }
+ if (corruptInstructions && address.pathname === '/auth/device/start') {
+ const response = await originalFetch(input,options);
+ const body = await response.json();
+ body.verificationURL = 'https://example.invalid/login/device';
+ return new Response(JSON.stringify(body),{status:response.status,headers:response.headers});
+ }
+ if (corruptInstructions && holdDeviceCancel && address.pathname === '/auth/device/cancel') {
+ deviceCancelStarted = true;
+ await new Promise(resolve => { releaseDeviceCancel = resolve; });
+ if (mode === 'cleanup-refused') return new Response(JSON.stringify({version:1,cancelled:false}),{status:200});
+ }
+ if (mode === 'pairing-cleanup-refused' && options?.method === 'DELETE'
+ && address.pathname.startsWith('/api/v1/devices/enrollments/')) {
+ return new Response(JSON.stringify({version:1,error:{code:'UNAVAILABLE',message:'private cleanup unavailable'}}),{status:503});
+ }
+ return originalFetch(input,options);
+};
+/** Await a state transition; this is a hang ceiling, never a performance assertion. */
+async function until(read) {
+ const deadline = Date.now()+20000;
+ do {
+ const found = read();
+ if (found) return found;
+ await new Promise(done => setTimeout(done,25));
+ } while (Date.now()<deadline);
+ assert.fail('the private view operation did not reach its expected state');
+}
+/** Scan private fixture files in bounded chunks; no session or device ticket belongs on disk. */
+function containsPersonMaterial(directory) {
+ for (const entry of readdirSync(directory,{withFileTypes:true})) {
+ const path = join(directory,entry.name);
+ if (entry.isDirectory()) { if (containsPersonMaterial(path)) return true; continue; }
+ if (!entry.isFile()) continue;
+ const fd = openSync(path,'r');
+ const chunk = Buffer.alloc(65536);
+ let tail = '';
+ try {
+ let length;
+ while ((length=readSync(fd,chunk,0,chunk.length,null))) {
+ const text = tail+chunk.subarray(0,length).toString('latin1');
+ if (/(?:ps_|pd_|pg_)[A-Za-z0-9_-]{43}/u.test(text)) return true;
+ tail = text.slice(-96);
+ }
+ } finally { closeSync(fd); }
+ }
+ return false;
+}
+try {
+ if (corruptInstructions) {
+ let settled = false;
+ const pending = setup.startViewSignIn({relayUrl}).then(
+ () => { settled = true; assert.fail('foreign provider instructions must be refused'); },
+ error => { settled = true; return error; });
+ try {
+ await until(() => deviceCancelStarted);
+ assert.equal(settled,false,'the error must wait for real ticket cleanup');
+ assert.equal(links.some(existsSync),false);
+ } finally { holdDeviceCancel = false; releaseDeviceCancel?.(); }
+ const error = await pending;
+ assert.equal(error.code,mode === 'cleanup-refused' ? 'OAUTH_CLEANUP' : 'VIEW_SIGN_IN_RESPONSE');
+ corruptInstructions = false;
+ const recovery = await setup.startViewSignIn({relayUrl});
+ intentId = recovery.intentId;
+ const cancelled = await setup.cancelViewSignIn(intentId);
+ assert.equal(cancelled.state,'cancelled','finished failed startup does not leave a busy view');
+ assert.equal(links.some(existsSync),false);
+ assert.equal(containsPersonMaterial(dirname(root)),false);
+ process.stdout.write(JSON.stringify({state:error.code,linked:0,storedPersonMaterial:false}));
+ } else if (mode === 'abort-start') {
+ await assert.rejects(setup.startViewSignIn({relayUrl,signal:starting.signal}), {code:'OAUTH_CANCELLED'});
+ assert.equal(links.some(existsSync),false,'a cancelled start does not link a board');
+ assert.equal(containsPersonMaterial(dirname(root)),false,'no private session or ticket is saved');
+ process.stdout.write(JSON.stringify({state:'cancelled',linked:0,storedPersonMaterial:false}));
+ } else {
+ const instructions = await setup.startViewSignIn({relayUrl});
+ intentId = instructions.intentId;
+ assert.deepEqual(Object.keys(instructions).sort(),['expiresAt','intentId','userCode','verificationURL']);
+ assert.equal(new URL(instructions.verificationURL).pathname,'/login/device');
+ assert.equal(instructions.userCode,'TEST-ONLY');
+ assert.equal(setup.viewSignInStatus(intentId).state,'waiting');
+ await assert.rejects(setup.startViewSignIn({relayUrl}),{code:'VIEW_SIGN_IN_BUSY'});
+ let final;
+ if (mode === 'cancel') {
+ final = await setup.cancelViewSignIn(intentId);
+ assert.equal(final.state,'cancelled');
+ } else if (shouldLink) {
+ const pairing = await until(() => setup.viewSignInStatus(intentId).state === 'pairing');
+ assert.equal(pairing,true);
+ const publicStatus = setup.viewSignInStatus(intentId);
+ assert.equal(publicStatus.boards.length,2);
+ assert.ok(publicStatus.boards.every(board => board.outcome === 'linked'));
+ assert.ok(!JSON.stringify(publicStatus).includes('#device='),'public status never contains the pairing capability');
+ assert.ok(!/(?:ps_|pd_|pg_)[A-Za-z0-9_-]{43}/u.test(JSON.stringify(publicStatus)));
+ const navigation = setup.viewSignInPairingNavigation(intentId);
+ assert.equal(new URL(navigation.url).origin,relayUrl);
+ assert.ok(new URL(navigation.url).hash.startsWith('#device='),'only the trusted view redirect accessor returns pairing navigation');
+ assert.equal(linkingCancelRefused,true,'linking finishes as one batch despite a cancel request');
+ const cancellation = setup.cancelViewSignIn(intentId);
+ try {
+ if (mode === 'linked') {
+ await until(() => pairingDeleteStarted);
+ assert.equal(setup.viewSignInStatus(intentId).state,'pairing','cleanup has not completed yet');
+ assert.throws(() => setup.viewSignInPairingNavigation(intentId),{code:'VIEW_PAIRING_NOT_READY'},
+ 'navigation is revoked while the real enrollment deletion is still pending');
+ }
+ } finally { releasePairingDelete?.(); }
+ final = await cancellation;
+ assert.equal(final.state,'pairing-stopped');
+ assert.equal(final.pairingCleanup,mode === 'linked' ? 'confirmed' : 'unconfirmed');
+ if (mode === 'pairing-cleanup-refused') assert.equal(final.error.code,'VIEW_PAIRING_CLEANUP',
+ 'unconfirmed remote deletion remains visible to the user');
+ assert.equal(final.boards.filter(board => board.outcome === 'linked').length,2);
+ for (const repo of [root,other]) assert.deepEqual(relayLinkAvailability(repo),{linked:true,unlinking:false});
+ const saved = readFileSync(links[0],'utf8');
+ try {
+ writeFileSync(links[0],JSON.stringify({...JSON.parse(saved),unlinking:true}));
+ assert.deepEqual(relayLinkAvailability(root),{linked:false,unlinking:true},
+ 'the lightweight read preserves pending unlink cleanup eligibility');
+ } finally { writeFileSync(links[0],saved); }
+ assert.throws(() => setup.viewSignInPairingNavigation(intentId),{code:'VIEW_PAIRING_NOT_READY'});
+ } else {
+ final = await until(() => {
+ const status=setup.viewSignInStatus(intentId);
+ return ['declined','expired','done'].includes(status.state) ? status : null;
+ });
+ assert.equal(final.state,mode);
+ }
+ const linked = links.filter(existsSync).length;
+ assert.equal(linked,shouldLink ? 2 : 0,'only confirmed sign-in may link boards');
+ assert.equal(containsPersonMaterial(dirname(root)),false,'neither the person session nor the relay ticket is written to any fixture file');
+ process.stdout.write(JSON.stringify({state:final.state,linked,storedPersonMaterial:false}));
+ }
+} finally {
+ holdPairingDelete = false;
+ releasePairingDelete?.();
+ holdDeviceCancel = false;
+ releaseDeviceCancel?.();
+ if (intentId) await setup.cancelViewSignIn(intentId);
+ globalThis.fetch = originalFetch;
+}
+`);
+}
+
+test("the view's sign-in links every board without a terminal or a stored session [H5,N26]", async (t) => {
+ assert.equal(typeof setup.startViewSignIn, 'function', 'core exposes a view sign-in adapter');
+ assert.equal(typeof setup.viewSignInStatus, 'function');
+ assert.equal(typeof setup.cancelViewSignIn, 'function');
+ for (const mode of ['linked', 'cancel', 'declined', 'expired', 'abort-start', 'invalid-url', 'cleanup-refused', 'pairing-cleanup-refused']) {
+ await t.test(mode, async (t) => {
+ const box = await relayClientFixture(t);
+ box.providerState.deviceAuthorized = ['linked','pairing-cleanup-refused'].includes(mode);
+ box.providerState.deviceDeclined = mode === 'declined';
+ box.providerState.deviceExpired = mode === 'expired';
+ const before = box.providerCalls.filter(call => call.path === '/login/device/code').length;
+ const result = await viewScenario(box, mode);
+ assert.equal(result.code, 0, result.failure ?? 'the private view scenario failed');
+ const outcome = result.document;
+ assert.equal(outcome.linked, ['linked','pairing-cleanup-refused'].includes(mode) ? 2 : 0);
+ assert.equal(outcome.storedPersonMaterial, false);
+ const after = box.providerCalls.filter(call => call.path === '/login/device/code').length;
+ assert.equal(after - before, mode === 'abort-start' ? 0 : ['invalid-url','cleanup-refused'].includes(mode) ? 2 : 1, 'one device sign-in serves each attempt, including explicit recovery after invalid instructions');
+ });
+ }
+});