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(relay): confirm SSH board links in browser [P6,H5]
Corey Olson7346cbc99e94
diff --git a/relay/auth-http.js b/relay/auth-http.jsindex b6986514..d40af8c6 100644--- a/relay/auth-http.js+++ b/relay/auth-http.js@@ -30,13 +30,43 @@ function json(res, status, data) {res.end(JSON.stringify({ version: 1, ...data }));}+/** Render a fixed confirmation shell; all board and host text comes from textContent after fetch. */+function deviceConfirmationPage() {+ return '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' ++ '<title>Confirm board link · Pullboard</title><main><h1>Confirm board link</h1><p id="status">Checking this sign-in…</p>' ++ '<p id="intent"></p><button id="confirm" hidden>Confirm link</button> <button id="decline" hidden>Decline</button></main>' ++ '<script>let ticket=decodeURIComponent(location.hash.slice(1));history.replaceState(null,"",location.pathname);const status=document.querySelector("#status");' ++ 'const intent=document.querySelector("#intent");const confirmButton=document.querySelector("#confirm");const declineButton=document.querySelector("#decline");' ++ '/** Bind this browser tab to the one-use ticket without putting it in a request URL. */ async function openConfirmation(){' ++ 'const response=await fetch("/auth/device/confirmation/open",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({ticket})});' ++ 'const value=await response.json();if(!response.ok)throw new Error(value.error?.message||"This confirmation expired.");}' ++ '/** Read the current grant without exposing a session credential to the page. */ async function refresh(){try{' ++ 'const response=await fetch("/auth/device/confirmation/status",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({ticket})});' ++ 'const value=await response.json();if(!response.ok)throw new Error(value.error?.message||"This confirmation expired.");' ++ 'if(value.declined){status.textContent="You declined this board link. Nothing was linked.";return;}' ++ 'if(value.confirmed){status.textContent="The board is linked. You can return to the terminal.";return;}' ++ 'if(!value.ready){status.textContent="Finish GitHub sign-in in the other tab, then this page will ask you to confirm.";return;}' ++ 'status.textContent="Signed in as @"+value.account+". Confirm only if this is the board and machine you intended.";' ++ 'intent.textContent="Link "+value.intent.boardName+" from "+value.intent.host+"?";confirmButton.hidden=false;declineButton.hidden=false;' ++ '}catch(error){status.textContent=error.message;confirmButton.hidden=true;declineButton.hidden=true;}}' ++ '/** Send an exact-origin, cookie-bound confirmation decision. */ async function decide(decision){confirmButton.disabled=true;declineButton.disabled=true;try{' ++ 'const response=await fetch("/auth/device/confirmation",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},' ++ 'body:JSON.stringify({ticket,decision})});const value=await response.json();if(!response.ok)throw new Error(value.error?.message||"The relay could not confirm this link.");' ++ 'status.textContent=value.confirmed?"The board is linked. You can return to the terminal.":"You declined this board link. Nothing was linked.";' ++ 'confirmButton.hidden=true;declineButton.hidden=true;}catch(error){status.textContent=error.message;confirmButton.disabled=false;declineButton.disabled=false;}}' ++ 'confirmButton.onclick=()=>decide("confirm");declineButton.onclick=()=>decide("decline");' ++ 'void openConfirmation().then(refresh).catch(error=>{status.textContent=error.message;});setInterval(()=>{if(confirmButton.hidden)void refresh();},2000);</script></html>';+}+/** Use a configured public origin, never a client-controlled Host or proxy header. */export function createAuthHandler({ auth, publicOrigin }) {let origin;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',+ '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) {@@ -68,11 +98,36 @@ export function createAuthHandler({ auth, publicOrigin }) {res.writeHead(303, { location: '/', 'Cache-Control': 'no-store', 'Set-Cookie': ['pb_session=' + signed.token + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + Math.max(0, Math.floor((signed.expires - Date.now()) / 1000)) + secure, 'pb_oauth_binding=; Path=/auth/github; HttpOnly; SameSite=Lax; Max-Age=0' + secure] });res.end();} else if (route === 'POST /auth/device/start') {- await body(req);- json(res, 200, await auth.beginDevice());+ const input = await body(req);+ const grant = await auth.beginDevice(input);+ if (grant.confirmationTicket) {+ grant.confirmationURL = new URL('/auth/device/confirm#' + encodeURIComponent(grant.confirmationTicket), origin).href;+ delete grant.confirmationTicket;+ }+ json(res, 200, grant);} else if (route === 'POST /auth/device/poll') {const input = await body(req);json(res, 200, await auth.pollDevice(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 --git a/relay/auth.js b/relay/auth.jsindex 529b6f54..12cdf32a 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -60,6 +60,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =const permissions = new Map();const webFlows = new Map();const deviceFlows = new Map();+ const deviceConfirmations = new Map();let closed = false;let locked = false;@@ -79,6 +80,16 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =finally { locked = false; }}+ /** Revoke a server-held device session when its person declined or abandoned confirmation. */+ function discardDeviceSession(flow) {+ if (!flow.session?.id) return;+ lifecycle(() => db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=? AND kind=?').run(flow.session.id, 'session'));+ flow.session = null;+ }++ /** Keep a confirmed device session retrievable only for its bounded CLI delivery window. */+ function deviceFlowExpiry(flow) { return flow.confirmed ? flow.deliveryExpires : flow.expires; }+/** Resolve a current credential and latest account login without storing its plaintext. */function credential(token) {open();@@ -112,10 +123,41 @@ 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 [key, flow] of deviceFlows) if (deviceFlowExpiry(flow) <= now()) {+ 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');}+ /** 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()) {+ 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) {@@ -172,13 +214,35 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =return signedIn(await github.exchangeCode(code, flow.verifier));},/** Give the CLI a relay ticket; the GitHub device credential remains in RAM. */- async beginDevice() {+ async beginDevice({ intent } = {}) {pruneFlows();+ if (intent !== undefined && (!intent || typeof intent !== 'object' || Array.isArray(intent))) {+ throw new Refused('BAD_REQUEST', 'start a relay sign-in with a valid board confirmation');+ }+ let pendingIntent;+ if (intent !== undefined) {+ if (Object.keys(intent).sort().join(',') !== 'board,boardName,host,repository') {+ throw new Refused('BAD_REQUEST', 'start a relay sign-in with exactly one board confirmation');+ }+ identifier(intent.board, 'BAD_BOARD');+ const repository = repositoryName(intent.repository);+ if (typeof intent.host !== 'string' || !intent.host || intent.host.length > 255 || /[\u0000-\u001f\u007f]/u.test(intent.host) ||+ typeof intent.boardName !== 'string' || !intent.boardName.trim() || intent.boardName.length > 200 || /[\u0000-\u001f\u007f]/u.test(intent.boardName)) {+ throw new Refused('BAD_REQUEST', 'start a relay sign-in with a valid board name and machine host');+ }+ pendingIntent = Object.freeze({ board: intent.board, repository, host: intent.host, boardName: intent.boardName });+ }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 });- 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,+ ...(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) {@@ -186,24 +250,108 @@ 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 || deviceFlowExpiry(flow) <= now()) {+ 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;try { result = await github.pollDevice(flow.deviceCode); }- catch (error) { if (['OAUTH_DENIED', 'OAUTH_EXPIRED'].includes(error.code)) deviceFlows.delete(key); throw error; }+ catch (error) {+ if (['OAUTH_DENIED', 'OAUTH_EXPIRED'].includes(error.code)) {+ deviceFlows.delete(key);+ if (flow.confirmationTicket) deviceConfirmations.delete(hash(flow.confirmationTicket));+ }+ 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 (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 };}+ if (flow.intent) {+ flow.session = await signedIn(result);+ 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);},+ /** 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);@@ -219,7 +367,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, ...(row.kind === 'machine' ? { machine: row.agent } : { agent: row.agent }) } : {}), ...(repository ? { permission: repository.permission, public: repository.public } : {}), expires: row.expires };},/** Accept a link only from a signed-in human with current repository write access. */- async linkBoard(token, board, repository) {+ async linkBoard(token, board, repository, deadline = Infinity) {identifier(board, 'BAD_BOARD');repositoryName(repository);const row = credential(token);@@ -227,6 +375,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =const repo = await github.access({ id: row.user_id, login: row.login }, repository);authorize({ allowed: true, hidden: false, role: repo.permission, public: repo.public }, {}, true);credential(token);+ if (deadline <= now()) throw new Refused('OAUTH_EXPIRED', 'the relay confirmation expired before the board link was made; run pullboard relay on again');open();lifecycle(() => {if (db.prepare('SELECT 1 FROM relay_cleanup WHERE board=?').get(board)) throw new Refused('RELAY_CLEANUP', 'finish pending board cleanup before linking again');@@ -368,7 +517,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =close() {if (closed) return;closed = true;- webFlows.clear(); deviceFlows.clear(); permissions.clear(); db.close();+ webFlows.clear(); deviceFlows.clear(); deviceConfirmations.clear(); permissions.clear(); db.close();},};return auth;diff --git a/src/cli.js b/src/cli.jsindex ca4f7c0e..2508daa8 100644--- a/src/cli.js+++ b/src/cli.js@@ -3291,8 +3291,9 @@ async function runMain(argv, streams) {if (parsed) {try {const [command, verb] = parsed.positionals;+ const remoteRelayOn = command === 'relay' && verb === 'on' && !parsed.values.all;if (!parsed.values.help && !parsed.values.version &&- (parsed.values.as === 'person' && command !== 'decisions' || command === 'relay' && ['on', 'join', 'revoke'].includes(verb))) requirePersonChannel(io.personChannel);+ (parsed.values.as === 'person' && command !== 'decisions' || command === 'relay' && ['on', 'join', 'revoke'].includes(verb) && !remoteRelayOn)) requirePersonChannel(io.personChannel);checkoutSession = await bindCheckoutSession(io, parsed.positionals, parsed.values);if (checkoutSession?.lease) CHECKOUT_LEASES.set(io, checkoutSession.lease);} catch (error) {diff --git a/src/person.js b/src/person.jsindex e6ddc8ff..ed4f033c 100644--- a/src/person.js+++ b/src/person.js@@ -35,3 +35,14 @@ export function requirePersonChannel(channel = 'terminal', environment = process}return channel;}++/** Permit only relay-on's SSH device flow for a person; agent terminals stay refused. */+export function requireRelayOnChannel(channel = 'terminal', environment = process.env) {+ if (!['terminal', 'view'].includes(channel)) {+ throw new Refused('B26_PERSON_CHANNEL', 'person actions use the terminal or the view; run pullboard view, the person’s channel');+ }+ if (channel === 'terminal' && AGENT_SHELL_MARKERS.some((name) => Boolean(environment[name]))) {+ throw new Refused('B26_PERSON_CHANNEL', 'this terminal belongs to an agent; run pullboard view, the person’s channel, and let the person act there');+ }+ return channel;+}diff --git a/src/relay.js b/src/relay.jsindex 78ed272b..d81638a0 100644--- a/src/relay.js+++ b/src/relay.js@@ -1,7 +1,8 @@/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H5,H16,H17,P5]. */import { createHash, randomUUID } from 'node:crypto';import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';-import { dirname, join } from 'node:path';+import { hostname } from 'node:os';+import { basename, dirname, join } from 'node:path';import { gunzipSync, gzipSync } from 'node:zlib';import * as store from './board.js';import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';@@ -18,7 +19,7 @@ import { relaySenderProblem } from './relay-sender.js';import { readRelayMachine, removeRecordedDevice, updateRelayMachine, wrapForRecordedDevice } from './relay-machine.js';import { receivePersonRequest, requestMoveProblem } from './relay-requests.js';import { nativePhoneAction, phoneProposal, publishPhoneApproval, warnPhoneApproval } from './relay-phone.js';-import { requirePersonChannel } from './person.js';+import { requirePersonChannel, requireRelayOnChannel } from './person.js';import { listApiProjects } from './projects.js';export const DEFAULT_RELAY = 'https://app.pullboard.dev';@@ -144,7 +145,7 @@ function notices(document, io) {/** The sole outbound transport in the CLI: explicit sign-in or a saved, opted-in board link. */async function request(state, path, { method = 'GET', body, allowMissing = false, initialBaseline = false } = {}, io) {- 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;@@ -1168,17 +1169,25 @@ export async function relayRecover(root, skip, io) {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) {+async function deviceSignIn(url, io, intent) {const client = { url };- const flow = await request(client, '/auth/device/start', { method: 'POST', body: {} }, io);- io.stderr.write(`Sign in with GitHub: open ${flow.verificationURL} and enter ${flow.userCode}\n`);- const expires = Date.now() + flow.expiresIn * 1000;+ 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 (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 } }, io);+ 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;@@ -1188,7 +1197,13 @@ async function deviceSignIn(url, io) {/** Explicitly sign in through the relay and persist a sealed initial snapshot before uploading it. */export async function relayOn(root, address, io, { session, credential, quiet = false, strict = false } = {}) {- if (!credential) requirePersonChannel(io.personChannel);+ const remoteShell = io.personChannel !== 'view' && Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY);+ const reusableSession = remoteShell ? undefined : session;+ const reusableCredential = remoteShell ? undefined : credential;+ if (remoteShell) {+ requireRelayOnChannel(io.personChannel);+ io.ignoreRelayEnvironmentToken = true;+ } else if (!reusableCredential) requirePersonChannel(io.personChannel);readRelayMachine();for (const project of listApiProjects()) { try { loadLink(linkFile(project.root)); } catch { /* Report this command's own link below. */ } }const repository = originRepository(root);@@ -1200,8 +1215,10 @@ export async function relayOn(root, address, io, { session, credential, quiet =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);+ 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);@@ -1220,12 +1237,13 @@ export async function relayOn(root, address, io, { session, credential, quiet =// Persist the exact sealed snapshot and a recoverable link intent before making the remote link.saveLink(file, state);if (state.linkPending) {- if (!credential) await request({ ...state, token: signed.token }, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository } }, io);+ if (signed.linkConfirmed && signed.linkedBoard !== state.board) throw new Refused('RELAY_RESPONSE', 'the relay confirmed a different board; sign in again');+ if (!reusableCredential && !signed.linkConfirmed) await request({ ...state, token: signed.token }, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository } }, io);delete state.linkPending;saveLink(file, state);}const machine = updateRelayMachine(settings => settings.machine);- const issued = credential ?? await request({ ...state, token: signed.token }, '/auth/machines', { method: 'POST', body: { board: state.board, machine } }, io);+ const issued = reusableCredential ?? await request({ ...state, token: signed.token }, '/auth/machines', { method: 'POST', body: { board: state.board, machine } }, io);if (!/^pm_[A-Za-z0-9_-]{43}$/u.test(issued.token ?? '') || issued.board !== state.board || issued.machine !== machine) throw new Refused('RELAY_RESPONSE', 'the relay did not issue this board’s machine credential; sign in again');// Cached agent credentials belong to the account that minted them.if (state.account !== account) delete state.agentTokens;diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 40f2aea0..de5c2d74 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -218,9 +218,27 @@ globalThis.fetch = function tracedFetch(input, init) {let beforeMove;const calls = [];const transit = [];+ const responseWaiters = [];const moveAcks = [];const privateKeys = new Set();let keyLeaked = false;+ /** Wait until a named relay request has fully returned to its caller. */+ function waitForResponse(path) {+ const prior = transit.find(entry => entry.path.split('?')[0] === path);+ if (prior) return Promise.resolve(prior);+ return new Promise(resolveResponse => responseWaiters.push({ path, resolve: resolveResponse }));+ }+ /** Record one completed private HTTP exchange and wake matching deterministic fixture waiters. */+ function recordResponse(entry) {+ transit.push(entry);+ for (let index = responseWaiters.length - 1; index >= 0; index -= 1) {+ const waiter = responseWaiters[index];+ if (entry.path.split('?')[0] === waiter.path) {+ responseWaiters.splice(index, 1);+ waiter.resolve(entry);+ }+ }+ }const server = createServer(async (req, res) => {const snapshotWrite = req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '');if (snapshotWrite) snapshotWriteCount += 1;@@ -285,7 +303,7 @@ globalThis.fetch = function tracedFetch(input, init) {}return end(chunk, ...args);};- res.once('finish', () => transit.push({ method: req.method, path: req.url,+ res.once('finish', () => recordResponse({ method: req.method, path: req.url,request: Buffer.concat(requestChunks), response: Buffer.concat(responseChunks) }));calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '', engine: req.headers['x-pullboard-engine'],browser: String(req.headers.cookie ?? '').includes('pb_session=') });@@ -482,6 +500,48 @@ globalThis.fetch = function tracedFetch(input, init) {cliChildDeadlineMs(snapshotUploads);return runCliChild(args, snapshotUploads, true);}+ /** Start the production CLI with live output so a browser confirmation can interleave with SSH sign-in. */+ function startCli(args, extraEnv = {}) {+ const child = spawn(process.execPath, [CLI, ...args, '--json'], { cwd: root, env: { ...env, ...extraEnv }, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ let stderr = '';+ const deadlineMs = cliChildDeadlineMs(DEFAULT_SNAPSHOT_UPLOADS);+ /** Stop a private CLI process that exceeds the fixture's upload-derived ceiling. */+ function stopOverdueChild() { child.kill('SIGKILL'); }+ const watchdog = setTimeout(stopOverdueChild, deadlineMs);+ watchdog.unref?.();+ /** Retain streamed standard output for the final machine-readable result. */+ function captureStdout(part) { stdout += part; }+ /** Retain streamed standard error so the browser can follow the printed confirmation URL. */+ function captureStderr(part) { stderr += part; }+ child.stdout.setEncoding('utf8').on('data', captureStdout);+ child.stderr.setEncoding('utf8').on('data', captureStderr);+ /** Preserve a single terminal result for both output waiters and fixture cleanup. */+ let resolveClosed;+ const closed = new Promise(resolve => { resolveClosed = resolve; });+ /** Capture child exit without losing stdout or stderr already delivered to this fixture. */+ function onClose(code, signal) {+ clearTimeout(watchdog);+ resolveClosed({ code, signal, stdout, stderr });+ }+ child.once('close', onClose);+ /** Reject prompt waits when the child closes before the expected text appears. */+ function failClosed() { throw new Error('private CLI closed before its expected prompt'); }+ /** Wait for a specific streamed prompt, or fail when the child exits before printing it. */+ async function waitForOutput(marker) {+ while (!stderr.includes(marker)) {+ if (child.exitCode !== null || child.signalCode !== null) throw new Error('private CLI exited before its expected prompt');+ await Promise.race([once(child.stderr, 'data'), closed.then(failClosed)]);+ }+ return stderr;+ }+ t.after(async () => {+ if (child.exitCode !== null || child.signalCode !== null) return;+ child.kill('SIGKILL');+ await closed;+ });+ return { child, closed, deadlineMs, waitForOutput, get stdout() { return stdout; }, get stderr() { return stderr; } };+ }assert.equal(runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: root, env, encoding: 'utf8' }).status, 0);writeFileSync(join(root, 'README.md'), 'private relay fixture project\n', { mode: 0o600 });assert.equal(runFixtureChild('git', ['add', 'README.md'], { cwd: root, env, encoding: 'utf8' }).status, 0);@@ -580,7 +640,7 @@ globalThis.fetch = function tracedFetch(input, init) {}return {transit, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,- root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,+ root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, startCli, waitForResponse, 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 --git a/test/relay.test.js b/test/relay.test.jsindex 0074cb59..181ce15a 100644--- a/test/relay.test.js+++ b/test/relay.test.js@@ -3,9 +3,10 @@ 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 { dirname, join, resolve } from 'node:path';+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';@@ -16,6 +17,52 @@ import { serveView } from '../src/serve.js';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(); }+}+/** Use real private SQLite and an actual HTTP provider with a controllable expiry clock. */async function fixture(t, options = {}) {const provider = await githubFixture(t);@@ -64,6 +111,111 @@ test('browser state/cookie binding and one-use device ticket protect both sign-iawait assert.rejects(box.auth.pollDevice(grant.ticket), { code: 'OAUTH_EXPIRED' });});+test('relay on from an SSH shell links only after the person confirms in the browser [P6, H5, H8, B26]', async (t) => {+ const box = await relayClientFixture(t);+ const ssh = { SSH_CONNECTION: '192.0.2.10 12345 192.0.2.20 22', PULLBOARD_RELAY_TOKEN: 'pa_' + 'x'.repeat(43) };+ const running = box.startCli(['relay', 'on', '--url', box.origin], ssh);+ const marker = 'After sign-in, confirm the link in your browser: ';+ const output = await running.waitForOutput(marker);+ const startResponse = await box.waitForResponse('/auth/device/start');+ const deviceGrant = JSON.parse(startResponse.response.toString());+ const line = output.split('\n').find(value => value.includes(marker));+ const confirmationURL = line?.slice(line.indexOf(marker) + marker.length).trim();+ assert.ok(confirmationURL, 'SSH sign-in prints the separate browser confirmation address');+ await box.waitForResponse('/auth/device/poll');+ const browser = await openRelayConfirmation(box, confirmationURL);+ assert.ok(browser.cookieMaxAge > 600 && browser.cookieMaxAge <= deviceGrant.expiresIn + 600,+ 'an early browser visit remains bound through the remaining device grant and ten-minute confirmation window');+ const status = await browser.status();+ assert.equal(status.response.status, 200);+ assert.equal(status.document.ready, true, 'the relay holds the GitHub session until the device grant is complete');+ assert.equal(status.document.intent.boardName, basename(box.root));+ assert.equal(status.document.intent.host, hostname());+ assert.equal(JSON.stringify(status.document).includes('token'), false, 'the browser status does not expose a relay credential');+ assert.equal(linkedBoardCount(box.authDatabase), 0, 'no board is linked before the person confirms');+ const foreignDecision = await browser.decide('confirm', 'https://foreign.invalid');+ assert.equal(foreignDecision.status, 403, 'a foreign origin cannot confirm even with the browser cookie');+ assert.equal(linkedBoardCount(box.authDatabase), 0, 'a refused cross-origin decision creates no link');+ const confirmed = await browser.decide('confirm');+ assert.equal(confirmed.status, 200, 'the exact-origin browser action confirms the displayed intent');+ assert.equal(linkedBoardCount(box.authDatabase), 1, 'the relay links only after affirmative confirmation');+ const completed = await running.closed;+ assert.equal(completed.signal, null);+ assert.equal(completed.code, 0, 'SSH relay on receives the person session only after confirmation');+ assert.equal(JSON.parse(completed.stdout).linked, true);++ const declineBox = await relayClientFixture(t);+ const declinedRun = declineBox.startCli(['relay', 'on', '--url', declineBox.origin], { SSH_TTY: '/dev/pts/8' });+ const declinedOutput = await declinedRun.waitForOutput(marker);+ const declinedLine = declinedOutput.split('\n').find(value => value.includes(marker));+ const declinedURL = declinedLine?.slice(declinedLine.indexOf(marker) + marker.length).trim();+ assert.ok(declinedURL);+ await declineBox.waitForResponse('/auth/device/poll');+ const declinedBrowser = await openRelayConfirmation(declineBox, declinedURL);+ assert.equal((await declinedBrowser.status()).document.ready, true);+ assert.equal((await declinedBrowser.decide('decline')).status, 200);+ const declined = await declinedRun.closed;+ assert.equal(declined.code, 1, 'the CLI reports a person decline');+ assert.equal(JSON.parse(declined.stdout).error.code, 'OAUTH_DENIED');+ assert.equal(linkedBoardCount(declineBox.authDatabase), 0, 'declining leaves the board unlinked');++ const startsBeforeRefusals = box.calls.filter(call => call.path === '/auth/device/start').length;+ const agent = spawnSync(process.execPath, [CLI, 'relay', 'on', '--url', box.origin, '--json'], {+ cwd: box.root, env: { ...box.env, SSH_CONNECTION: ssh.SSH_CONNECTION, AI_AGENT: '1' }, encoding: 'utf8',+ });+ assert.equal(agent.status, 1);+ assert.equal(JSON.parse(agent.stdout).error.code, 'B26_PERSON_CHANNEL', 'an agent-marked SSH shell still cannot link');+ const personAnswer = spawnSync(process.execPath, [CLI, 'answer', '1', 'yes', '--as', 'person', '--json'], {+ cwd: box.root, env: { ...box.env, SSH_CONNECTION: ssh.SSH_CONNECTION }, encoding: 'utf8',+ });+ assert.equal(personAnswer.status, 1);+ assert.equal(JSON.parse(personAnswer.stdout).error.code, 'B26_PERSON_CHANNEL', 'other person-only SSH actions remain refused');+ assert.equal(box.calls.filter(call => call.path === '/auth/device/start').length, startsBeforeRefusals,+ 'refused shell actions never start another browser grant');+});++test('an unanswered device board confirmation expires after ten minutes [H8]', async (t) => {+ const box = await fixture(t);+ const intent = { board: 'ssh-board', boardName: 'fixture-board', host: 'fixture-host', repository: 'fixture/repository' };+ const flow = await box.auth.beginDevice({ intent });+ box.state.deviceAuthorized = true;+ box.advance(flow.interval * 1000);+ const pending = await box.auth.pollDevice(flow.ticket);+ assert.equal(pending.pendingConfirmation, true);+ assert.equal('token' in pending, false, 'the CLI ticket does not return the held person session');+ const browser = box.auth.openDeviceConfirmation(flow.confirmationTicket);+ const status = box.auth.deviceConfirmationStatus(flow.confirmationTicket, browser.binding);+ assert.equal(status.ready, true);+ assert.equal('token' in status, false, 'browser status contains no relay credential');+ box.advance(10 * 60_000);+ await assert.rejects(box.auth.pollDevice(flow.ticket), { code: 'OAUTH_EXPIRED' });+ assert.equal(linkedBoardCount(box.database), 0, 'an unanswered intent never links a board');+ const db = new DatabaseSync(box.database);+ try {+ assert.equal(db.prepare("SELECT COUNT(*) AS count FROM relay_credentials WHERE kind='session' AND revoked=1").get().count, 1,+ 'the server-held session is revoked after the confirmation deadline');+ } finally { db.close(); }+});++test('a confirmation approved before its deadline can reach the SSH CLI just after ten minutes [P6, H5]', async (t) => {+ const box = await fixture(t);+ const intent = { board: 'ssh-board', boardName: 'fixture-board', host: 'fixture-host', repository: 'fixture/repository' };+ const flow = await box.auth.beginDevice({ intent });+ const browser = box.auth.openDeviceConfirmation(flow.confirmationTicket);+ box.state.deviceAuthorized = true;+ box.advance(flow.interval * 1000);+ const pending = await box.auth.pollDevice(flow.ticket);+ assert.equal(pending.pendingConfirmation, true);+ box.advance(599_000);+ const approved = await box.auth.confirmDevice(flow.confirmationTicket, browser.binding, 'confirm');+ assert.equal(approved.confirmed, true, 'the person approved before the original confirmation deadline');+ box.advance(2_000);+ const delivered = await box.auth.pollDevice(flow.ticket);+ assert.equal(delivered.linkConfirmed, true, 'the valid approval remains retrievable after its decision deadline');+ assert.equal(delivered.linkedBoard, intent.board);+ assert.match(delivered.token, /^ps_[A-Za-z0-9_-]{43}$/u);+});+test('unreadable links are refused; agent tokens belong to exactly one board [H8, H1]', async (t) => {const box = await fixture(t);const signed = await login(box);