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): refuse revoked sessions before credential use [H5,E16]
Corey Olson44b80db8afff
diff --git a/docs/api.md b/docs/api.mdindex 71d30c70..054f5406 100644--- a/docs/api.md+++ b/docs/api.md@@ -198,7 +198,7 @@ Only the coordinator sets or edits an item's `--check`. `pullboard check [id]` p`relay on --all [--url <address>]` returns `{version, linked: [{project, root, board}], failed: [{project, root, reason}], paired, autoLink: true}`. Its status is nonzero when a project failed; successful links remain available. With no paired phone, the command prints one tappable pairing link and QR, then waits in the foreground up to ten minutes. Interruption or expiration leaves completed links intact and exits zero when no link failed. Every explicit invocation signs in afresh; no person session is retained on the Mac. Later project registrations publish one sealed phone-link proposal and keep working locally until its single approval tap. `doctor` and `resume` name the waiting project and its expiry; expiration requires an explicit fresh sign-in rather than silently asking again. `relay off` excludes that project from automatic linking; explicit `relay on` clears the exclusion.-`relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation never asks the target device to approve its own removal. Another paired phone can approve it with a short-lived, single-use, RAM-only grant for that exact target. With no other paired approver or no linked publishing board, the person completes a fresh GitHub device-code sign-in on the computer instead. The authenticated account and relay origin must match the saved enrollment; the fresh session stays in memory and is revoked after the action. Agent terminals are refused before any sign-in or network request. A failed or interrupted approval or sign-in needs an explicit retry. Revocation stops future wrapping and refuses the removed browser’s enrolled session with `DEVICE_REVOKED` (HTTP 403), including snapshot and event reads. Its next connected page clears the locally held board keys, private device key and board request cache and shows that it was removed; reload retains the refusal. The relay stores only public session ids tied to the enrollment, never an extra bearer credential. A fresh GitHub sign-in remains eligible for recovery; it does not resurrect the revoked device. An offline copy cannot be remotely erased and board key rotation remains separate (#346).+`relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation never asks the target device to approve its own removal. Another paired phone can approve it with a short-lived, single-use, RAM-only grant for that exact target. With no other paired approver or no linked publishing board, the person completes a fresh GitHub device-code sign-in on the computer instead. The authenticated account and relay origin must match the saved enrollment; the fresh session stays in memory and is revoked after the action. Agent terminals are refused before any sign-in or network request. A failed or interrupted approval or sign-in needs an explicit retry. Revocation stops future wrapping and refuses the removed browser’s enrolled session with `DEVICE_REVOKED` (HTTP 403), including snapshot/event reads and auth-session, board-list and token-list reads. That same principal boundary refuses its machine or agent credential issuance, so the removed session cannot mint another reader. The public board-free shell still loads to clear local browser data; it grants no person actions. Its next connected page clears the locally held board keys, private device key and board request cache and shows that it was removed; reload retains the refusal. The relay stores only public session ids tied to the enrollment, never an extra bearer credential. A fresh GitHub sign-in remains eligible for recovery; it does not resurrect the revoked device. An offline copy cannot be remotely erased and board key rotation remains separate (#346).Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Enrollment, device listing and direct revocation require a person session. A board-scoped machine credential can PUT only its own board wrap to an already enrolled device. Cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.diff --git a/relay/auth-http.js b/relay/auth-http.jsindex 1b0e6cb2..758e8960 100644--- a/relay/auth-http.js+++ b/relay/auth-http.js@@ -157,7 +157,7 @@ export function createAuthHandler({ auth, publicOrigin }) {} catch (error) {const code = error instanceof Refused ? error.code : 'INTERNAL_ERROR';const message = error instanceof Refused ? error.message.replace(/^\[[^\]]+\] /, '') : 'the relay could not complete this request; retry or contact its coordinator';- const status = code === 'BOARD_NOT_LINKED' ? 404 : code === 'AUTH_REQUIRED' ? 401 : ['NO_REPO_ACCESS', 'TOKEN_BOARD', 'TOKEN_NOT_OWNED', 'HUMAN_REQUIRED', 'BAD_ORIGIN', 'WRITE_REQUIRED'].includes(code) ? 403 : code === 'GITHUB_UNAVAILABLE' ? 503 : code === 'INTERNAL_ERROR' ? 500 : 400;+ const status = code === 'BOARD_NOT_LINKED' ? 404 : code === 'AUTH_REQUIRED' ? 401 : ['DEVICE_REVOKED', 'NO_REPO_ACCESS', 'TOKEN_BOARD', 'TOKEN_NOT_OWNED', 'HUMAN_REQUIRED', 'BAD_ORIGIN', 'WRITE_REQUIRED'].includes(code) ? 403 : code === 'GITHUB_UNAVAILABLE' ? 503 : code === 'INTERNAL_ERROR' ? 500 : 400;json(res, status, { error: { code, message, next: message } });}return true;diff --git a/relay/auth.js b/relay/auth.jsindex 1a1ba65d..3f390699 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -63,6 +63,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =const deviceConfirmations = new Map();// A hashed ticket may revoke only its minted session, retained until that session expires.const deviceSessionReceipts = new Map();+ const sessionGuards = new Set();let closed = false;let locked = false;@@ -98,6 +99,9 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =if (typeof token !== 'string' || !/^(ps_|pa_|pm_)[A-Za-z0-9_-]{43}$/.test(token)) throw new Refused('AUTH_REQUIRED', 'sign in to the relay or supply a current board token');const row = db.prepare('SELECT c.*, u.login FROM relay_credentials c JOIN relay_users u ON u.id=c.user_id WHERE c.hash=?').get(hash(token));if (!row || row.revoked || row.expires <= now()) throw new Refused('AUTH_REQUIRED', 'this credential is expired or revoked; sign in or obtain a new board token');+ if (row.kind === 'session') {+ for (const guard of sessionGuards) guard({ id: row.id, kind: row.kind, user: { id: row.user_id }, expires: row.expires });+ }return row;}@@ -486,6 +490,13 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =pendingCleanup() { open(); return db.prepare('SELECT board FROM relay_cleanup ORDER BY board').all().map((row) => row.board); },/** Remove an unlink intent only after its journal, sidecars and managed backups are gone. */finishCleanup(board) { identifier(board, 'BAD_BOARD'); lifecycle(() => db.prepare('DELETE FROM relay_cleanup WHERE board=?').run(board)); },+ /** Register a synchronous device-session boundary shared by every credential use, including auth routes. */+ addSessionGuard(guard) {+ open();+ if (typeof guard !== 'function') throw new Refused('RELAY_CONFIG', 'configure a synchronous session guard before serving relay authentication');+ sessionGuards.add(guard);+ return () => sessionGuards.delete(guard);+ },/** List only linked boards the current credential and GitHub account may read. */async boardsFor(token) {const row = credential(token);@@ -584,7 +595,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =close() {if (closed) return;closed = true;- webFlows.clear(); deviceFlows.clear(); deviceConfirmations.clear(); deviceSessionReceipts.clear(); permissions.clear(); db.close();+ webFlows.clear(); deviceFlows.clear(); deviceConfirmations.clear(); deviceSessionReceipts.clear(); sessionGuards.clear(); permissions.clear(); db.close();},};return auth;diff --git a/relay/browser-page.js b/relay/browser-page.jsindex 0847cfbe..a74395a6 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -55,16 +55,19 @@ export function createRelayBrowserHandler({ authenticate }) {}if (path !== '/') return false;let relaySession = false;+ let removedSession = false;try {const who = await authenticate(req);if (who.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'Sign in as a person to open the relay view.');relaySession = true;} catch (error) {- if (!(error instanceof Refused) || !['AUTH_REQUIRED', 'HUMAN_REQUIRED'].includes(error.code)) throw error;+ if (!(error instanceof Refused) || !['AUTH_REQUIRED', 'HUMAN_REQUIRED', 'DEVICE_REVOKED'].includes(error.code)) throw error;+ removedSession = error.code === 'DEVICE_REVOKED';}- const notice = relaySession ? '<p>Pairing this browser…</p>'+ // The public, board-free shell must still load so its client can erase a removed browser's local keys.+ const notice = removedSession ? '<p>This browser was removed from the board.</p>' : relaySession ? '<p>Pairing this browser…</p>': '<p>Connecting to this machine. Sign in to see your linked boards.</p><a href="/auth/github/start">Sign in with GitHub</a>';- const page = cockpitPage('', { readOnly: true, requests: relaySession, transportModule: relaySession ? '/relay/client.js' : '/relay/sign-in.js', apiHeaders: {}, stylesheet: '/view.css', hostedLocal: true, relaySession, signIn: '/auth/github/start' })+ const page = cockpitPage('', { readOnly: true, requests: relaySession, transportModule: relaySession || removedSession ? '/relay/client.js' : '/relay/sign-in.js', apiHeaders: {}, stylesheet: '/view.css', hostedLocal: true, relaySession: relaySession || removedSession, signIn: '/auth/github/start' }).replace('<link rel="icon" href="data:,">', '<link rel="icon" href="/icons/pullboard.svg" type="image/svg+xml">\n<link rel="manifest" href="/manifest.webmanifest">\n<link rel="apple-touch-icon" href="/icons/pullboard-192.png">\n<meta name="theme-color" content="#f6faf7">').replace('<main>', '<main><section class="card-panel" id="relay-notice" role="status">' + notice + '</section>');const scripts = [...page.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(match => createHash('sha256').update(match[1]).digest('base64'));diff --git a/relay/service.js b/relay/service.jsindex b768ea30..ffa08679 100644--- a/relay/service.js+++ b/relay/service.js@@ -107,6 +107,8 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin}const deviceStore = createDeviceStore({ directory: root, now });+ // Auth handlers share this same auth object, so revoked sessions cannot mint a new reader elsewhere.+ const releaseSessionGuard = auth.addSessionGuard?.(principal => deviceStore.authorizeSession(principal));const deviceHandler = createDeviceHandler({authenticate: async (req, write) => deviceStore.authorizeSession(await auth.authenticate(credential(req, origin, write))),authorizeBoard: (req, id) => authorizedRequest(req, id, true),@@ -266,7 +268,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginhandle.maintenance = maintain;handle.backup = retention.backup;handle.maintenanceStatus = () => ({ error: maintenanceError });- handle.close = () => { clearInterval(timer); common.close(); deviceStore.close(); };+ handle.close = () => { clearInterval(timer); common.close(); releaseSessionGuard?.(); deviceStore.close(); };return handle;}diff --git a/test/relay-browser.test.js b/test/relay-browser.test.jsindex 48c4373a..c731dd05 100644--- a/test/relay-browser.test.js+++ b/test/relay-browser.test.js@@ -563,20 +563,23 @@ async function enrolledBrowser(box, t) {return { chrome, device: state.devices[0].deviceId };}-/** Revoke the enrolled browser with the real CLI and one actual phone approval tap. */-async function revokeBrowser(box, chrome, device) {- const before = box.transit.length;- const revoke = box.startCli(['relay', 'revoke', device]);- const posted = await browserDeviceTransition(() => box.transit.slice(before).find(record =>- record.method === 'POST' && record.path === '/api/v1/devices/approvals'), 'the native revocation requests phone approval');- const context = JSON.parse(posted.request.toString('utf8')).context;- assert.equal(context.target, device);- assert.equal(context.action, 'revoke-device');- await chrome.waitFor(`document.querySelector('#phone-approve-${context.id}') !== null`);- await chrome.evaluate(`document.querySelector('#phone-approve-${context.id}').click()`);- const result = await revoke.closed;- assert.equal(result.code, 0, 'one actual phone tap completes native revocation');- assert.equal(JSON.parse(result.stdout).revoked, true);+/** Revoke the only enrolled browser through main's fresh provider sign-in, without its own approval. */+async function revokeBrowser(box, _chrome, device) {+ const before = box.calls.length;+ const authorized = box.providerState.deviceAuthorized;+ box.providerState.deviceAuthorized = false;+ try {+ const revoke = box.startCli(['relay', 'revoke', device]);+ await revoke.waitForOutput('Sign in with GitHub: open ');+ assert.ok(box.calls.slice(before).some(record => record.path === '/auth/device/start'),+ 'the only phone is removed through a fresh provider sign-in');+ assert.equal(box.calls.slice(before).some(record => record.path === '/api/v1/devices/approvals'), false,+ 'the target browser never approves its own removal');+ box.providerState.deviceAuthorized = true;+ const result = await revoke.closed;+ assert.equal(result.code, 0, 'a genuine fresh sign-in completes native revocation');+ assert.equal(JSON.parse(result.stdout).revoked, true);+ } finally { box.providerState.deviceAuthorized = authorized; }}test('a revoked device read is refused as revoked [H5,E16]', {@@ -651,3 +654,87 @@ test('revocation clears an already open browser and its cached board request staassert.equal(await chrome.evaluate("document.querySelector('#phone-approvals') === null"), true, 'removed browser releases its approval panel and polling loop');assert.equal(await chrome.evaluate("document.querySelector('#relay-removed a')?.getAttribute('href')"), '/auth/github/start');});++/** Independently probe real public auth delegation after a genuinely enrolled browser is revoked. */+test('reviewer: a revoked bound session cannot regain ciphertext through auth machine minting [H5,E16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const {chrome, device} = await enrolledBrowser(box, t);+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const oldSession = await box.phoneSession();+ const retainedKey = await chrome.evaluate(`JSON.parse(localStorage.getItem('pullboard.relay.keys.v1'))[${JSON.stringify(link.board)}]`);+ assert.equal(typeof retainedKey, 'string', 'the genuinely enrolled browser already received this board key');+ const endpoint = box.origin + '/api/v1/boards/' + link.board + '/state';+ const oldHeaders = {authorization:'Bearer '+oldSession.token,'x-pullboard-engine':String(ENGINE_VERSION)};+ assert.equal((await fetch(endpoint,{headers:oldHeaders})).status,200,'the bound session has original read access');+ await revokeBrowser(box, chrome, device);+ const refused = await fetch(endpoint,{headers:oldHeaders});+ assert.equal(refused.status,403,'the direct bound-session read is refused');+ assert.equal((await refused.json()).error.code,'DEVICE_REVOKED','revocation is real, not an expired or foreign session');+ // A genuinely fresh unbound GitHub sign-in must remain eligible for lost-phone recovery (#755).+ const start = await fetch(box.origin+'/auth/github/start',{redirect:'manual'});+ const binding=start.headers.getSetCookie().find(value=>value.startsWith('pb_oauth_binding=')).split(';')[0];+ const approved=await fetch(start.headers.get('location'),{redirect:'manual'});+ const callback=await fetch(approved.headers.get('location'),{redirect:'manual',headers:{cookie:binding}});+ assert.equal(callback.status,303,'a fresh independent OAuth sign-in completes');+ const fresh=callback.headers.getSetCookie().find(value=>value.startsWith('pb_session=')).split(';')[0].slice('pb_session='.length);+ assert.notEqual(fresh,oldSession.token,'the positive control really uses a different fresh session');+ const freshRead=await fetch(endpoint,{headers:{authorization:'Bearer '+fresh,'x-pullboard-engine':String(ENGINE_VERSION)}});+ assert.equal(freshRead.status,200,'fresh unbound person recovery remains eligible');+ const minted=await fetch(box.origin+'/auth/machines',{method:'POST',headers:{...oldHeaders,'content-type':'application/json'},body:JSON.stringify({board:link.board,machine:'revoked-browser-redelegation'})});+ const document=await minted.json();+ let delegatedStatus=null,decryptedOriginal=false;+ if(minted.status===201){+ assert.match(document.token,/^pm_[A-Za-z0-9_-]{43}$/u,'the actual auth endpoint issued a machine delegate');+ const delegated=await fetch(endpoint,{headers:{authorization:'Bearer '+document.token,'x-pullboard-engine':String(ENGINE_VERSION)}});+ delegatedStatus=delegated.status;+ if(delegated.status===200){+ const {state}=await delegated.json();+ assert.equal(typeof state.sealed,'string','the relay served actual ciphertext, not merely a board name');+ const plain=await unseal(decodeBoardKey(retainedKey),Buffer.from(state.sealed,'base64url'),{boardId:link.board,kind:'snapshot',sequence:state.sequence});+ const snapshot=snapshotDocument(plain);+ decryptedOriginal=JSON.stringify(snapshot).includes('private cleanup fixture item');+ assert.equal(decryptedOriginal,true,'the previously received browser key decrypts the regained board');+ }+ }+ t.diagnostic(JSON.stringify({oldBoundRead:refused.status,freshUnboundRead:freshRead.status,machineMint:minted.status,delegatedRead:delegatedStatus,decryptedOriginal}));+ assert.equal(minted.status,403,'a revoked bound browser session must not mint a fresh machine credential that bypasses its revoked read');+ assert.equal(document.error?.code,'DEVICE_REVOKED');+});+/** The revoked session cannot exchange its refusal for another credential through the auth router. */+test('a revoked browser cannot mint or list relay credentials [H5,E16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const { chrome, device } = await enrolledBrowser(box, t);+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const session = await box.phoneSession();+ const old = { authorization: 'Bearer ' + session.token };+ const paths = ['/auth/session', '/auth/boards', '/auth/tokens?board=' + link.board];+ for (const path of paths) {+ const response = await fetch(box.origin + path, { headers: old });+ assert.equal(response.status, 200, 'the active enrolled session can read ' + path);+ await response.body?.cancel();+ }+ await revokeBrowser(box, chrome, device);+ await box.restartRelay();+ for (const headers of [old, { cookie: 'pb_session=' + session.token, origin: box.origin }]) {+ for (const path of paths) {+ const response = await fetch(box.origin + path, { headers });+ assert.equal(response.status, 403, 'the revoked session cannot read ' + path);+ assert.equal((await response.json()).error.code, 'DEVICE_REVOKED');+ }+ for (const [path, input] of [+ ['/auth/tokens', { board: link.board, agent: 'revoked-auth-route-probe' }],+ ['/auth/machines', { board: link.board, machine: 'revoked-auth-route-probe' }],+ ]) {+ const response = await fetch(box.origin + path, { method: 'POST',+ headers: { ...headers, 'content-type': 'application/json' }, body: JSON.stringify(input) });+ const document = await response.json();+ assert.equal(response.status, 403, 'the revoked session cannot mint through ' + path);+ assert.equal(document.error?.code, 'DEVICE_REVOKED');+ assert.equal(Object.hasOwn(document, 'token'), false, 'a refusal contains no delegated credential');+ }+ }+});