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.

chore(merge): integrate accepted ssh relay sign-in [H5,P6]

Corey Olsonc8dd8a205248
diff --cc relay/auth-http.js
index ffaf5fff,4bcf5d00..1b0e6cb2
--- a/relay/auth-http.js
+++ b/relay/auth-http.js
@@@ -65,9 -36,7 +65,9 @@@ export function createAuthHandler({ aut
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',
- 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']);
++ 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/device/confirm', 'POST /auth/device/confirmation/open', 'POST /auth/device/confirmation/status', 'POST /auth/device/confirmation',
+ '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) {
@@@ -109,26 -73,9 +109,29 @@@
} 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/device/confirm') {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer',
+ 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY',
+ 'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'" });
+ res.end(deviceConfirmationPage());
+ } else if (route === 'POST /auth/device/confirmation/open') {
+ if (req.headers.origin !== origin.origin) throw new Refused('BAD_ORIGIN', 'open a device confirmation from the relay origin');
+ const input = await body(req);
+ const flow = auth.openDeviceConfirmation(input.ticket);
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
+ 'Set-Cookie': 'pb_device_confirmation=' + flow.binding + '; Path=/auth/device; HttpOnly; SameSite=Strict; Max-Age=' + flow.cookieMaxAge + secure });
+ res.end(JSON.stringify({ version: 1, opened: true }));
+ } else if (route === 'POST /auth/device/confirmation/status') {
+ if (req.headers.origin !== origin.origin) throw new Refused('BAD_ORIGIN', 'read a device confirmation from the relay origin');
+ const input = await body(req);
+ json(res, 200, auth.deviceConfirmationStatus(input.ticket, cookie(req, 'pb_device_confirmation')));
+ } else if (route === 'POST /auth/device/confirmation') {
+ if (req.headers.origin !== origin.origin) throw new Refused('BAD_ORIGIN', 'send cookie-authorized confirmation from the relay origin');
+ const input = await body(req);
+ json(res, 200, await auth.confirmDevice(input.ticket, cookie(req, 'pb_device_confirmation'), input.decision));
} 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 --cc relay/auth.js
index bb71d742,b1b71897..1a1ba65d
--- a/relay/auth.js
+++ b/relay/auth.js
@@@ -60,7 -60,8 +60,9 @@@ export function createRelayAuth({ datab
const permissions = new Map();
const webFlows = new Map();
const deviceFlows = new Map();
+ const deviceConfirmations = new Map();
+ // A hashed ticket may revoke only its minted session, retained until that session expires.
+ const deviceSessionReceipts = new Map();
let closed = false;
let locked = false;
@@@ -123,41 -115,12 +126,43 @@@
/** Remove expired in-memory flow secrets and limit anonymous sign-in allocations. */
function pruneFlows() {
open();
- for (const [key, flow] of deviceFlows) if (deviceFlowExpiry(flow) <= now()) {
- for (const map of [webFlows, deviceFlows]) for (const [key, flow] of map) if (flow.expires <= now() && !flow.busy) map.delete(key);
++ for (const [key, flow] of deviceFlows) if (deviceFlowExpiry(flow) <= now() && !flow.busy) {
+ if (!flow.confirmed) discardDeviceSession(flow);
+ deviceFlows.delete(key);
+ if (flow.confirmationTicket) deviceConfirmations.delete(hash(flow.confirmationTicket));
+ }
+ for (const map of [webFlows, deviceConfirmations]) for (const [key, flow] of map) if (flow.expires <= now()) map.delete(key);
- if (webFlows.size + deviceFlows.size >= 10_000) throw new Refused('SIGN_IN_BUSY', 'too many sign-ins are pending; retry shortly');
+ for (const [key, receipt] of deviceSessionReceipts) if (receipt.expires <= now()) deviceSessionReceipts.delete(key);
+ const activeTickets = new Set([...deviceFlows.keys(), ...deviceSessionReceipts.keys()]);
+ if (new Set([...webFlows.keys(), ...activeTickets]).size >= 10_000) throw new Refused('SIGN_IN_BUSY', 'too many sign-ins are pending; retry shortly');
}
+ /** Look up a live pending browser confirmation without accepting the CLI polling ticket. */
+ function confirmation(ticket) {
+ open();
+ if (typeof ticket !== 'string') throw new Refused('OAUTH_EXPIRED', 'the relay confirmation expired; run pullboard relay on again');
+ const key = hash(ticket);
+ const flow = deviceConfirmations.get(key);
- if (!flow || flow.expires <= now()) {
++ if (!flow || flow.cancelled || flow.expires <= now()) {
+ deviceConfirmations.delete(key);
+ if (flow) {
+ if (!flow.confirmed) {
+ deviceFlows.delete(flow.deviceTicketHash);
+ discardDeviceSession(flow);
+ }
+ }
+ throw new Refused('OAUTH_EXPIRED', 'the relay confirmation expired; run pullboard relay on again');
+ }
+ return { key, flow };
+ }
+
+ /** Validate the browser-only cookie binding before reading or changing a pending confirmation. */
+ function confirmationBinding(flow, binding) {
+ if (!flow.confirmationBinding || !sameHash(flow.confirmationBinding, hash(binding ?? ''))) {
+ throw new Refused('OAUTH_STATE', 'open the relay confirmation link in this browser again');
+ }
+ }
+
/** Hide public boards below triage, and refuse actions below write without hiding readable private boards. */
function authorize(permission, linked, write) {
if (!permission.allowed) {
@@@ -235,14 -182,8 +240,15 @@@
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, cancelled: false, completed: false, terminalOutcome: null, sessionId: null, pollSettled: null });
- return { ticket, userCode: grant.userCode, verificationURL: grant.verificationURL, expiresIn: grant.expiresIn, interval: grant.interval };
+ const grantExpires = now() + grant.expiresIn * 1000;
+ const deviceTicketHash = hash(ticket);
+ const flow = { deviceCode: grant.deviceCode, deviceTicketHash, grantExpires, expires: grantExpires, interval: grant.interval, next: now() + grant.interval * 1000,
++ cancelled: false, completed: false, terminalOutcome: null, sessionId: null, pollSettled: null,
+ ...(pendingIntent ? { intent: pendingIntent, confirmationTicket: random('pc_') } : {}) };
+ deviceFlows.set(deviceTicketHash, flow);
+ if (flow.confirmationTicket) deviceConfirmations.set(hash(flow.confirmationTicket), flow);
+ return { ticket, ...(flow.confirmationTicket ? { confirmationTicket: flow.confirmationTicket } : {}), 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. */
async pollDevice(ticket) {
@@@ -250,111 -191,91 +256,169 @@@
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 || deviceFlowExpiry(flow) <= now()) {
+ 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 (deviceFlowExpiry(flow) <= now() && !flow.busy) {
+ deviceFlows.delete(key);
+ if (flow?.confirmationTicket) deviceConfirmations.delete(hash(flow.confirmationTicket));
+ if (flow && !flow.confirmed) discardDeviceSession(flow);
+ throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again');
+ }
+ if (flow.intent) {
+ if (flow.declined) {
+ discardDeviceSession(flow);
+ deviceFlows.delete(key);
+ deviceConfirmations.delete(hash(flow.confirmationTicket));
+ throw new Refused('OAUTH_DENIED', 'the person declined to link this board; run pullboard relay on again to start a new sign-in');
+ }
+ if (flow.confirmed) {
+ deviceFlows.delete(key);
+ deviceConfirmations.delete(hash(flow.confirmationTicket));
+ return { ...flow.session, linkConfirmed: true, linkedBoard: flow.intent.board };
+ }
+ if (flow.session) return { pending: true, pendingConfirmation: true, confirmationExpiresIn: Math.max(1, Math.ceil((flow.expires - now()) / 1000)), retryAfter: flow.interval };
+ }
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;
+ 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)) {
- deviceFlows.delete(key);
- if (flow.confirmationTicket) deviceConfirmations.delete(hash(flow.confirmationTicket));
- // 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.
++ // Retain the ticket hash until expiry so a racing cancellation can confirm cleanup.
+ 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 (flow.expires <= now()) {
+ deviceFlows.delete(key);
+ if (flow.confirmationTicket) deviceConfirmations.delete(hash(flow.confirmationTicket));
+ if (!flow.confirmed) discardDeviceSession(flow);
+ throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again');
+ }
+ if (flow.declined) {
+ deviceFlows.delete(key);
+ if (flow.confirmationTicket) deviceConfirmations.delete(hash(flow.confirmationTicket));
+ throw new Refused('OAUTH_DENIED', 'the person declined to link this board; run pullboard relay on again to start a new sign-in');
+ }
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.sessionExpires = session.expires;
- flow.completed = true;
++ flow.completed = !flow.intent;
+ deviceSessionReceipts.set(key, { sessionId: session.id, expires: session.expires, revoked: false });
+ if (flow.cancelled || flow.expires <= now()) {
+ db.prepare("UPDATE relay_credentials SET revoked=1 WHERE id=? AND kind='session'").run(flow.sessionId);
+ deviceSessionReceipts.get(key).revoked = true;
+ 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');
+ }
+ if (flow.intent) {
- flow.session = await signedIn(result);
++ flow.session = session;
+ if (flow.declined || flow.expires <= now()) {
+ discardDeviceSession(flow);
+ deviceFlows.delete(key);
+ deviceConfirmations.delete(hash(flow.confirmationTicket));
+ throw new Refused(flow.declined ? 'OAUTH_DENIED' : 'OAUTH_EXPIRED', 'the person confirmation ended before sign-in completed; run pullboard relay on again');
+ }
+ flow.expires = now() + 10 * 60_000;
+ return { pending: true, pendingConfirmation: true, confirmationExpiresIn: 600, retryAfter: flow.interval };
+ }
- deviceFlows.delete(key);
- return signedIn(result);
+ return session;
} finally {
flow.busy = false;
+ flow.pollSettled = null;
+ settle();
+ }
+ },
+ /** 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);
+ let flow = deviceFlows.get(key);
+ let receipt = deviceSessionReceipts.get(key);
+ if (flow && flow.expires <= now() && !flow.busy) {
+ deviceFlows.delete(key);
+ flow = null;
+ }
+ if (receipt && receipt.expires <= now()) {
+ deviceSessionReceipts.delete(key);
+ receipt = null;
+ }
+ if (!flow && !receipt) return { cancelled: false };
+ if (flow) {
+ flow.cancelled = true;
+ const pollSettled = flow.pollSettled;
+ if (pollSettled) await pollSettled;
+ flow.deviceCode = null;
+ receipt = deviceSessionReceipts.get(key) ?? receipt;
+ }
+ const sessionId = receipt?.sessionId ?? flow?.sessionId;
+ const sessionExpires = receipt?.expires ?? flow?.sessionExpires;
+ if (sessionId && !Number.isSafeInteger(sessionExpires)) throw new Refused('OAUTH_CLEANUP', 'the relay cannot confirm cleanup for this sign-in; retry or sign in again');
+ if (sessionId && !receipt?.revoked) {
+ db.prepare("UPDATE relay_credentials SET revoked=1 WHERE id=? AND kind='session' AND expires=?").run(sessionId, sessionExpires);
+ if (receipt) receipt.revoked = true;
+ }
- if (flow) flow.sessionId = null;
++ if (flow) {
++ discardDeviceSession(flow);
++ flow.sessionId = null;
++ if (flow.confirmationTicket) deviceConfirmations.delete(hash(flow.confirmationTicket));
+ }
+ return { cancelled: true };
},
+ /** Start a cookie-bound browser visit for the separate one-use board confirmation nonce. */
+ openDeviceConfirmation(ticket) {
+ const { flow } = confirmation(ticket);
+ const binding = random('');
+ flow.confirmationBinding = hash(binding);
+ return { binding, cookieMaxAge: Math.max(1, Math.ceil((flow.grantExpires - now()) / 1000) + 600) };
+ },
+ /** Read only the immutable board intent and whether the matching device grant is ready. */
+ deviceConfirmationStatus(ticket, binding) {
+ const { flow } = confirmation(ticket);
+ confirmationBinding(flow, binding);
+ return { ready: Boolean(flow.session), confirmed: Boolean(flow.confirmed), declined: Boolean(flow.declined),
+ ...(flow.session ? { account: flow.session.user.login } : {}), intent: flow.intent };
+ },
+ /** Confirm or decline the exact board intent; only approval links it and releases the session to the CLI. */
+ async confirmDevice(ticket, binding, decision) {
+ const { flow } = confirmation(ticket);
+ confirmationBinding(flow, binding);
+ if (decision === 'decline') {
+ if (flow.confirmed) throw new Refused('OAUTH_STATE', 'this board link was already confirmed');
+ if (flow.confirming) throw new Refused('OAUTH_PENDING', 'the board link is being confirmed; wait for the relay page');
+ flow.declined = true;
+ discardDeviceSession(flow);
+ return { declined: true };
+ }
+ if (decision !== 'confirm') throw new Refused('BAD_REQUEST', 'choose confirm or decline on the relay page');
+ if (!flow.session) throw new Refused('OAUTH_PENDING', 'finish GitHub sign-in before confirming this board link');
+ if (!flow.confirmed) {
+ if (flow.confirming) throw new Refused('OAUTH_PENDING', 'the board link is being confirmed; wait for the relay page');
+ flow.confirming = true;
+ try {
+ await auth.linkBoard(flow.session.token, flow.intent.board, flow.intent.repository, flow.expires);
+ flow.confirmed = true;
+ flow.deliveryExpires = now() + 10 * 60_000;
+ } finally { flow.confirming = false; }
+ }
+ return { confirmed: true, board: flow.intent.board };
+ },
/** Authenticate a human or a scoped agent; every board write asks GitHub again. */
async authenticate(token, { board, write = false } = {}) {
const row = credential(token);
@@@ -520,7 -440,7 +584,7 @@@
close() {
if (closed) return;
closed = true;
- webFlows.clear(); deviceFlows.clear(); deviceConfirmations.clear(); permissions.clear(); db.close();
- webFlows.clear(); deviceFlows.clear(); permissions.clear(); db.close();
++ webFlows.clear(); deviceFlows.clear(); deviceConfirmations.clear(); deviceSessionReceipts.clear(); permissions.clear(); db.close();
},
};
return auth;
diff --cc src/relay.js
index d81638a0,851c0d73..bc46454f
--- a/src/relay.js
+++ b/src/relay.js
@@@ -144,8 -143,8 +144,8 @@@ 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 supplied = io?.ignoreRelayEnvironmentToken ? undefined : 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');
const token = readToken ?? state.token;
@@@ -798,7 -801,7 +802,7 @@@ async function actorTransport(root, fil
if (!state.token?.startsWith('pm_')) throw new Refused('HUMAN_REQUIRED', 'run pullboard relay on --all to authorize this board’s machine credential');
return state;
}
-- const supplied = process.env.PULLBOARD_RELAY_TOKEN;
++ const supplied = io?.ignoreRelayEnvironmentToken ? undefined : process.env.PULLBOARD_RELAY_TOKEN;
if (supplied !== undefined) {
if (!/^pa_[A-Za-z0-9_-]{43}$/.test(supplied)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token, without including it in command arguments');
const transport = { ...state, token: supplied, agent: actor };
@@@ -1168,31 -1171,74 +1172,82 @@@ export async function relayRecover(root
/** 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, intent) {
+ /** 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();
+ });
+ }
+
+ /** 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 } = {}) {
++async function deviceSignIn(url, io, { signal, intent } = {}) {
+ cancellationOutcome(signal);
const client = { url };
- const flow = await request(client, '/auth/device/start', { method: 'POST', body: intent ? { intent } : {} }, io);
- io.stderr.write(intent
- ? `Sign in with GitHub for board ${intent.boardName} from ${intent.host}: open ${flow.verificationURL} and enter ${flow.userCode}. After sign-in, confirm the link in your browser: ${flow.confirmationURL}\n`
- : `Sign in with GitHub: open ${flow.verificationURL} and enter ${flow.userCode}\n`);
- if (intent && typeof flow.confirmationURL !== 'string') throw new Refused('RELAY_RESPONSE', 'the relay did not provide a board confirmation page; sign in again');
- let expires = Date.now() + flow.expiresIn * 1000;
- let confirmationPending = false;
- let signed;
- let wait = flow.interval;
- do {
- await new Promise((resolve) => setTimeout(resolve, Math.max(1, wait) * 1000));
- if (!confirmationPending && 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);
- if (signed.pendingConfirmation && Number.isSafeInteger(signed.confirmationExpiresIn)) {
- confirmationPending = true;
- expires = Date.now() + signed.confirmationExpiresIn * 1000;
- const flow = await request(client, '/auth/device/start', { method: 'POST', body: {}, signal }, io);
++ const flow = await request(client, '/auth/device/start', { method: 'POST', body: intent ? { intent } : {}, signal }, io);
+ try {
+ cancellationOutcome(signal);
- io.stderr.write(`Sign in with GitHub: open ${flow.verificationURL} and enter ${flow.userCode}\n`);
- const expires = Date.now() + flow.expiresIn * 1000;
++ io.stderr.write(intent
++ ? `Sign in with GitHub for board ${intent.boardName} from ${intent.host}: open ${flow.verificationURL} and enter ${flow.userCode}. After sign-in, confirm the link in your browser: ${flow.confirmationURL}\n`
++ : `Sign in with GitHub: open ${flow.verificationURL} and enter ${flow.userCode}\n`);
++ if (intent && typeof flow.confirmationURL !== 'string') throw new Refused('RELAY_RESPONSE', 'the relay did not provide a board confirmation page; sign in again');
++ let expires = Date.now() + flow.expiresIn * 1000;
++ let confirmationPending = false;
+ 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');
++ if (!confirmationPending && 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);
++ if (signed.pendingConfirmation && Number.isSafeInteger(signed.confirmationExpiresIn)) {
++ confirmationPending = true;
++ expires = Date.now() + signed.confirmationExpiresIn * 1000;
++ }
+ 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');
}
- 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;
+ throw error;
+ }
}
/** Explicitly sign in through the relay and persist a sealed initial snapshot before uploading it. */
@@@ -1215,10 -1255,8 +1270,10 @@@ export async function relayOn(root, add
const url = relayOrigin(address || state?.url || DEFAULT_RELAY);
if (state && (state.url !== url || state.repository !== repository)) throw new Refused('RELAY_LINKED', 'this board is linked to another relay or repository; run relay off before changing its link');
const key = state ? readBoardKey(state.board) : await generateBoardKey();
- const signed = credential ?? session ?? await deviceSignIn(url, io);
- if (session && session.url !== url) throw new Refused('RELAY_SESSION', 'Sign in again to this relay with pullboard relay on --all.');
+ const intent = remoteShell ? { board: state?.board ?? localRecords(root, store.boardId), repository,
+ host: hostname(), boardName: basename(root) } : undefined;
- const signed = remoteShell ? await deviceSignIn(url, io, intent) : reusableCredential ?? reusableSession ?? await deviceSignIn(url, io);
++ const signed = remoteShell ? await deviceSignIn(url, io, { intent }) : reusableCredential ?? reusableSession ?? await deviceSignIn(url, io);
+ if (reusableSession && reusableSession.url !== url) throw new Refused('RELAY_SESSION', 'Sign in again to this relay with pullboard relay on --all.');
if (!state) {
const snapshot = localRecords(root, (board) => {
startRelayEpoch(board);
diff --cc test/relay-client-fixture.js
index a28c1bff,24480e6b..367bdc45
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@@ -676,8 -586,8 +683,8 @@@ globalThis.fetch = function tracedFetch
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, auth, otherDeviceJoin,
- root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,
+ root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, startCli, waitForResponse, holdNextConfirmationStatus, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,
/** Assert the test consumed every declared child budget, with no hidden CLI calls. */
assertCliChildrenComplete() {
if (cliChildren) assert.equal(cliChildIndex, cliChildren.length, 'every planned private CLI child ran exactly once');
diff --cc test/relay.test.js
index d39a368b,2f3a83b3..97c8b885
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@@ -1,12 -1,11 +1,11 @@@
/** 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 { tmpdir } from 'node:os';
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { dirname, join, resolve } from 'node:path';
++import { hostname, tmpdir } from 'node:os';
+import { basename, dirname, join, resolve } from 'node:path';
import { test } from 'node:test';
import { DatabaseSync } from 'node:sqlite';
- import { hostname } from 'node:os';
import { ENGINE_VERSION } from '../src/machine.js';
import { createGitHubClient } from '../relay/github.js';
import { createRelayAuth, ACCESS_WINDOW_MS } from '../relay/auth.js';
@@@ -17,52 -16,169 +16,215 @@@ import { serveView } from '../src/serve
import { fetchFresh } from './http-fixture.js';
import { fetchPrintedViewLink } from './view-link-fixture.js';
+const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');
+
+/** Open the relay confirmation page and retain only its browser cookie and one-use ticket. */
+async function openRelayConfirmation(box, confirmationURL) {
+ const url = new URL(confirmationURL);
+ const ticket = decodeURIComponent(url.hash.slice(1));
+ assert.ok(ticket, 'confirmation nonce is carried in the browser fragment');
+ const page = await fetch(new URL('/auth/device/confirm', url.origin));
+ assert.equal(page.status, 200, 'relay serves the person confirmation page');
+ assert.equal(page.headers.get('referrer-policy'), 'no-referrer');
+ const html = await page.text();
+ assert.match(html, /textContent="Link "|textContent = "Link "/u, 'the page inserts board and host labels as text');
+ const wrongOrigin = await fetch(box.origin + '/auth/device/confirmation/open', {
+ method: 'POST', headers: { origin: 'https://foreign.invalid', 'content-type': 'application/json' }, body: JSON.stringify({ ticket }),
+ });
+ assert.equal(wrongOrigin.status, 403, 'a foreign page cannot open the browser confirmation');
+ const opened = await fetch(box.origin + '/auth/device/confirmation/open', {
+ method: 'POST', headers: { origin: box.origin, 'content-type': 'application/json' }, body: JSON.stringify({ ticket }),
+ });
+ assert.equal(opened.status, 200, 'the confirmation page receives a cookie-bound browser session');
+ const cookie = opened.headers.get('set-cookie')?.split(';', 1)[0];
+ assert.match(cookie ?? '', /^pb_device_confirmation=/u);
+ const cookieMaxAge = Number(/(?:^|;\s*)Max-Age=(\d+)/u.exec(opened.headers.get('set-cookie') ?? '')?.[1]);
+ /** Read confirmation status with same-origin browser credentials and no URL capability. */
+ async function status() {
+ const response = await fetch(box.origin + '/auth/device/confirmation/status', {
+ method: 'POST', headers: { origin: box.origin, cookie, 'content-type': 'application/json' }, body: JSON.stringify({ ticket }),
+ });
+ return { response, document: await response.json() };
+ }
+ /** Submit one explicit person decision through the browser-cookie and exact-Origin boundary. */
+ async function decide(decision, origin = box.origin) {
+ return fetch(box.origin + '/auth/device/confirmation', {
+ method: 'POST', headers: { origin, cookie, 'content-type': 'application/json' }, body: JSON.stringify({ ticket, decision }),
+ });
+ }
+ return { ticket, cookie, cookieMaxAge, html, status, decide };
+}
+
+/** Count linked boards through a separate read-only SQLite connection. */
+function linkedBoardCount(database) {
+ const db = new DatabaseSync(database, { readOnly: true });
+ try { return db.prepare('SELECT COUNT(*) AS count FROM relay_boards').get().count; }
+ finally { db.close(); }
+}
+
+ 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;
+ 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 (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/')) {
+ setImmediate(() => controller.abort());
+ await new Promise(resolve => controller.signal.addEventListener('abort', resolve, { once: true }));
+ }
+ return originalFetch(input, init);
+ };
+ } else if (['held-poll-response', 'held-poll-response-cancel-fails',
+ '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' && 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' } });
+ }
+ 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 (mode === 'already-aborted') controller.abort();
+ const output = { personChannel: 'view', cwd: process.cwd(),
+ 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, 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;
+ }
+ `);
+ }
+
+ /** 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; }
+
+ /** 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');
+ 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);