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
feat(relay): authorize GitHub sessions and board tokens [H8,H1]
Corey Olson06a4e1fae67d
diff --git a/relay/README.md b/relay/README.mdnew file mode 100644index 00000000..5ec16b81--- /dev/null+++ b/relay/README.md@@ -0,0 +1,65 @@+# Relay authentication++This module implements the GitHub App sign-in and authorization boundary for the+opt-in relay. It does not start a public server or change any repository.++Create the GitHub provider with `createGitHubClient` from `github.js`. Configuration+names are `clientId`, `clientSecret`, `privateKey` (RSA PEM), and `callbackURL`.+The callback ends in `/auth/github/callback`. The default GitHub URLs are used in+production; HTTPS overrides and loopback HTTP stand-ins are supported. Register+with `githubAppManifest(callbackURL)` and enable the App's device flow in GitHub's+settings. The manifest requests only repository Metadata read permission.++Create `createRelayAuth({ database, github })` from `auth.js` with a private SQLite+file, separate from board databases. Create `createAuthHandler({ auth,+publicOrigin })` from `auth-http.js` with the trusted externally visible HTTPS+origin. Mount it before the API handler: it returns `false` for unrelated routes.+The reverse proxy must preserve request `Origin` and cookies; the handler never+trusts a forwarded host to decide cookie-write authorization.++Browser sign-in begins at `GET /auth/github/start`. The callback checks both a+one-use state and an HttpOnly browser-binding cookie, exchanges with S256 PKCE,+and redirects to `/` with an HttpOnly, SameSite=Lax session cookie (Secure on+HTTPS). Codes and session tokens are not put in the final browser URL.++A CLI posts `{}` to `/auth/device/start`, directs its person to the returned+`verificationURL` with `userCode`, then posts `{ticket}` to `/auth/device/poll`.+Pending responses carry `retryAfter` seconds. Polling is throttled and honors+GitHub's slow-down response. Successful polling returns a relay session once.+Response bodies carrying credentials have `Cache-Control: no-store`.++The handler also offers `/auth/session`, `/auth/boards`, `/auth/boards/link`,+`/auth/tokens`, and `/auth/tokens/revoke`. JSON responses have `version: 1`;+refusals have `error: {code, message, next}`. A bearer credential works for CLI+requests. Cookie-authorized writes must carry the exact configured Origin.++The API layer must call `auth.authenticate(token, {board, write})` before serving+board data or applying a board move. `write: true` always checks GitHub. For an+agent credential, use the returned `agent`, never an agent supplied in a request+body. A credential for one board is refused on another before any board lookup.+Use `auth.boardsFor(token)` for visibility, and `auth.linkBoard(token, board,+repository)` to link only a repository the person can read. `auth.issueToken`+requires a human session and returns a random, expiring credential scoped to one+board/agent. `auth.revoke(token, id)` revokes one owned credential.++GitHub user credentials are used only to obtain the account's immutable id and+login at sign-in, then discarded. Permission checks use an App-signed JWT to+obtain a repository-scoped installation token asking only for Metadata read.+These App tokens stay in RAM. Private repositories require an App installation+and a permission response for the same immutable user id. Public repositories+are readable without a private installation. Repository ids are pinned so a+replacement repository cannot inherit a board link.++SQLite stores account/repository identities and SHA-256 hashes of relay-issued+credentials, never their plaintext. Sessions expire in seven days by default;+board tokens in one day (configurable up to thirty days). Revocation persists+across restart. Sessions survive restart without GitHub user credentials; pending+web/device flows are held only in RAM and must be restarted after a restart.+Read permission checks are cached for less than ten minutes. Writes check again+every time and a denied write invalidates the read cache. Provider failures refuse+the current operation. Revocation or expiry during an awaited check also refuses+it. Call `auth.close()` when the relay shuts down.++`test/relay-github.test.js`, `test/relay.test.js`, and `test/relay-http.test.js` use+real loopback HTTP, generated RSA keys, and private SQLite files. No live GitHub+credentials, repositories, or board databases are needed.diff --git a/relay/auth-http.js b/relay/auth-http.jsnew file mode 100644index 00000000..66b7df16--- /dev/null+++ b/relay/auth-http.js@@ -0,0 +1,100 @@+/** Embeddable web/device sign-in routes for the opt-in relay [H8, H1]. */+import { Refused } from '../src/refused.js';++/** Read one named cookie; duplicate bindings are refused instead of choosing an ambiguous value. */+function cookie(req, name) {+ const matches = (req.headers.cookie || '').split(';').map(part => part.trim()).filter(part => part.startsWith(name + '='));+ if (matches.length > 1) throw new Refused('AUTH_REQUIRED', 'clear duplicate relay cookies and sign in again');+ return matches[0]?.slice(name.length + 1);+}++/** Parse a bounded JSON object, never surfacing request contents in refusals. */+async function body(req) {+ if ((req.headers['content-type'] || '').split(';')[0] !== 'application/json') throw new Refused('BAD_REQUEST', 'send an application/json object');+ const chunks = [];+ let size = 0;+ for await (const chunk of req) {+ size += chunk.length;+ if (size > 16_384) throw new Refused('BAD_REQUEST', 'send a JSON object smaller than 16 KiB');+ chunks.push(chunk);+ }+ let value;+ try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new Refused('BAD_REQUEST', 'send a valid JSON object'); }+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Refused('BAD_REQUEST', 'send a JSON object');+ return value;+}++/** Emit a versioned response with credentials protected from caches. */+function json(res, status, data) {+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });+ res.end(JSON.stringify({ version: 1, ...data }));+}++/** 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/tokens', 'POST /auth/tokens/revoke']);++ /** Resolve a bearer or cookie credential; cookie writes require an exact trusted Origin. */+ function token(req, write = false) {+ const authorization = req.headers.authorization;+ if (authorization) {+ const match = /^Bearer ((?:ps_|pa_)[A-Za-z0-9_-]{43})$/.exec(authorization);+ if (!match) throw new Refused('AUTH_REQUIRED', 'send a current relay bearer credential');+ return match[1];+ }+ const session = cookie(req, 'pb_session');+ if (write && req.headers.origin !== origin.origin) throw new Refused('BAD_ORIGIN', 'send cookie-authorized writes from the relay origin');+ return session;+ }++ /** Handle only auth routes and return false so the relay's API handler can serve other paths. */+ return async function handleAuth(req, res) {+ const url = new URL(req.url, origin);+ const route = req.method + ' ' + url.pathname;+ if (!routes.has(route)) return false;+ try {+ if (route === 'GET /auth/github/start') {+ const flow = auth.beginWeb();+ res.writeHead(302, { location: flow.authorizationURL, 'Cache-Control': 'no-store', 'Set-Cookie': 'pb_oauth_binding=' + flow.binding + '; Path=/auth/github; HttpOnly; SameSite=Lax; Max-Age=600' + secure });+ res.end();+ } else if (route === 'GET /auth/github/callback') {+ if (url.searchParams.has('error')) throw new Refused('OAUTH_DENIED', 'GitHub sign-in was declined; start again to sign in');+ const signed = await auth.finishWeb(url.searchParams.get('state'), url.searchParams.get('code'), cookie(req, 'pb_oauth_binding'));+ 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());+ } 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/session') {+ json(res, 200, { session: await auth.authenticate(token(req)) });+ } else if (route === 'GET /auth/boards') {+ json(res, 200, { boards: await auth.boardsFor(token(req)) });+ } else if (route === 'POST /auth/boards/link') {+ const bearer = token(req, true);+ const input = await body(req);+ json(res, 200, { board: await auth.linkBoard(bearer, input.board, input.repository) });+ } else if (route === 'POST /auth/tokens') {+ const bearer = token(req, true);+ const input = await body(req);+ json(res, 201, await auth.issueToken(bearer, input));+ } else {+ const bearer = token(req, true);+ const input = await body(req);+ json(res, 200, auth.revoke(bearer, input.id));+ }+ } 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 === 'AUTH_REQUIRED' ? 401 : ['NO_REPO_ACCESS', 'TOKEN_BOARD', 'TOKEN_NOT_OWNED', 'HUMAN_REQUIRED', 'BAD_ORIGIN'].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.jsnew file mode 100644index 00000000..df9a719e--- /dev/null+++ b/relay/auth.js@@ -0,0 +1,227 @@+/** Hash-only relay sessions and board credentials, authorized by current GitHub metadata [H8, H1]. */+import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';+import { chmodSync, mkdirSync } from 'node:fs';+import { dirname } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { Refused } from '../src/refused.js';+import { repositoryName } from './github.js';++export const ACCESS_WINDOW_MS = 10 * 60_000;+const MAX_TTL = 30 * 24 * 3600_000;++/** Hash credentials before any database lookup or persistence. */+function hash(value) { return createHash('sha256').update(value).digest('hex'); }++/** Generate an unpredictable relay credential, distinct from GitHub credentials. */+function random(prefix) { return prefix + randomBytes(32).toString('base64url'); }++/** Require a bounded explicit identifier without reflecting its input in errors. */+function identifier(value, code) {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(value) || value === '.' || value === '..') throw new Refused(code, 'use an identifier of 1 to 128 letters, digits, dots, underscores or hyphens');+ return value;+}++/** Compare two hashes without a variable-time comparison of a browser flow binding. */+function sameHash(left, right) {+ return typeof left === 'string' && typeof right === 'string' && left.length === right.length && timingSafeEqual(Buffer.from(left), Buffer.from(right));+}++/**+ * Persist only relay credential hashes and account/repository identities. User OAuth credentials+ * live solely in the sign-in call; App credentials belong to the injected provider's RAM cache.+ */+export function createRelayAuth({ database, github, now = Date.now, sessionTTL = 7 * 24 * 3600_000, tokenTTL = 24 * 3600_000 }) {+ if (typeof database !== 'string' || !database || !github) throw new Refused('RELAY_CONFIG', 'configure an auth database and GitHub App provider');+ for (const ttl of [sessionTTL, tokenTTL]) if (!Number.isSafeInteger(ttl) || ttl <= 0 || ttl > MAX_TTL) throw new Refused('RELAY_CONFIG', 'set credential expiry between one millisecond and thirty days');+ if (database !== ':memory:') mkdirSync(dirname(database), { recursive: true, mode: 0o700 });+ const db = new DatabaseSync(database);+ if (database !== ':memory:') chmodSync(database, 0o600);+ db.exec(`PRAGMA foreign_keys=ON;+ CREATE TABLE IF NOT EXISTS relay_users (id TEXT PRIMARY KEY, login TEXT NOT NULL);+ CREATE TABLE IF NOT EXISTS relay_boards (id TEXT PRIMARY KEY, repository TEXT NOT NULL, repository_id TEXT NOT NULL);+ CREATE TABLE IF NOT EXISTS relay_credentials (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, kind TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES relay_users(id), board TEXT REFERENCES relay_boards(id), agent TEXT, expires INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);+ `);+ const permissions = new Map();+ const webFlows = new Map();+ const deviceFlows = new Map();+ let closed = false;++ /** Refuse operation after closing instead of surfacing a raw SQLite error. */+ function open() { if (closed) throw new Refused('RELAY_CLOSED', 'start the relay before signing in or using a credential'); }++ /** Resolve a current credential and latest account login without storing its plaintext. */+ function credential(token) {+ open();+ if (typeof token !== 'string' || !/^(ps_|pa_)[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');+ return row;+ }++ /** Mint one independently expiring/revocable credential and persist only its hash. */+ function issue(user, kind, board, agent, ttl) {+ open();+ const token = random(kind === 'session' ? 'ps_' : 'pa_');+ const id = randomUUID();+ const expires = now() + ttl;+ db.prepare('INSERT INTO relay_credentials (id,hash,kind,user_id,board,agent,expires) VALUES (?,?,?,?,?,?,?)').run(id, hash(token), kind, user.id, board ?? null, agent ?? null, expires);+ return { token, id, expires };+ }++ /** Learn the immutable GitHub identity, then drop the user access credential immediately. */+ async function signedIn(result) {+ if (!result || result.pending) throw new Refused('OAUTH_STATE', 'complete GitHub sign-in before creating a relay session');+ const user = await github.user(result.accessToken);+ open();+ if (!user || !/^[1-9][0-9]*$/.test(String(user.id)) || typeof user.login !== 'string' || !/^[A-Za-z0-9-]+$/.test(user.login)) throw new Refused('GITHUB_AUTH', 'GitHub did not confirm your account; sign in again');+ db.prepare('INSERT INTO relay_users (id,login) VALUES (?,?) ON CONFLICT(id) DO UPDATE SET login=excluded.login').run(String(user.id), user.login);+ return { ...issue({ id: String(user.id) }, 'session', null, null, sessionTTL), user: { id: String(user.id), login: user.login } };+ }++ /** 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);+ if (webFlows.size + deviceFlows.size >= 10_000) throw new Refused('SIGN_IN_BUSY', 'too many sign-ins are pending; retry shortly');+ }++ /** Require GitHub-confirmed access, with a ten-minute read cache and a fresh check for writes. */+ async function access(row, board, write) {+ const linked = db.prepare('SELECT * FROM relay_boards WHERE id=?').get(board);+ if (!linked) throw new Refused('BOARD_NOT_LINKED', 'link this board to a readable GitHub repository before using it');+ const key = row.user_id + ':' + board;+ const prior = permissions.get(key);+ const started = now();+ if (!write && prior && started >= prior.checked && started - prior.checked < ACCESS_WINDOW_MS) {+ if (!prior.allowed) throw new Refused('NO_REPO_ACCESS', 'GitHub cannot confirm your repository access; ask for access and retry');+ return linked;+ }+ try {+ const repo = await github.access({ id: row.user_id, login: row.login }, linked.repository);+ if (String(repo.id) !== linked.repository_id) throw new Refused('NO_REPO_ACCESS', 'the linked repository identity changed; ask the coordinator to link the correct board');+ if (!permissions.has(key) || permissions.get(key).checked <= started) permissions.set(key, { checked: started, allowed: true });+ return linked;+ } catch (error) {+ if (error.code === 'NO_REPO_ACCESS' && (!permissions.has(key) || permissions.get(key).checked <= started)) permissions.set(key, { checked: started, allowed: false });+ throw error;+ }+ }++ const auth = {+ /** Start a browser authorization with a distinct CSRF cookie binding and PKCE verifier. */+ beginWeb() {+ pruneFlows();+ const state = random('');+ const binding = random('');+ const verifier = random('');+ webFlows.set(hash(state), { binding: hash(binding), verifier, expires: now() + 10 * 60_000 });+ return { authorizationURL: github.authorizeURL(state, createHash('sha256').update(verifier).digest('base64url')), binding };+ },+ /** Consume a matching browser grant once; neither verifier nor GitHub token enters SQLite. */+ async finishWeb(state, code, binding) {+ open();+ if (typeof state !== 'string' || typeof binding !== 'string') throw new Refused('OAUTH_STATE', 'start sign-in again in this browser');+ const key = hash(state);+ const flow = webFlows.get(key);+ if (!flow || flow.expires <= now() || !sameHash(flow.binding, hash(binding))) throw new Refused('OAUTH_STATE', 'the sign-in state expired or does not match this browser; start again');+ webFlows.delete(key);+ return signedIn(await github.exchangeCode(code, flow.verifier));+ },+ /** Give the CLI a relay ticket; the GitHub device credential remains in RAM. */+ async beginDevice() {+ pruneFlows();+ 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 };+ },+ /** Throttle device polling, honor slow-down, and consume a successful grant only once. */+ async pollDevice(ticket) {+ open();+ 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.busy || flow.next > now()) return { pending: true, retryAfter: Math.max(1, Math.ceil((flow.next - now()) / 1000)) };+ flow.next = now() + flow.interval * 1000;+ flow.busy = true;+ let result;+ try { result = await github.pollDevice(flow.deviceCode); }+ catch (error) { if (['OAUTH_DENIED', 'OAUTH_EXPIRED'].includes(error.code)) deviceFlows.delete(key); throw error; }+ finally { flow.busy = false; }+ if (flow.expires <= now()) { deviceFlows.delete(key); throw new Refused('OAUTH_EXPIRED', 'CLI sign-in expired; start again'); }+ if (result.pending) {+ if (result.slow) flow.interval += 5;+ if (Number.isFinite(result.interval) && result.interval > flow.interval) flow.interval = result.interval;+ flow.next = now() + flow.interval * 1000;+ return { pending: true, retryAfter: flow.interval };+ }+ deviceFlows.delete(key);+ return signedIn(result);+ },+ /** Authenticate a human or a scoped agent; every board write asks GitHub again. */+ async authenticate(token, { board, write = false } = {}) {+ const row = credential(token);+ if (row.kind === 'board' && board !== row.board) throw new Refused('TOKEN_BOARD', 'use this token only on its named board; obtain another token for another board');+ if (board !== undefined) {+ identifier(board, 'BAD_BOARD');+ await access(row, board, write);+ credential(token); // A revocation or expiry during the awaited provider call must take effect.+ }+ return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, agent: row.agent } : {}), expires: row.expires };+ },+ /** Accept a link only from a signed-in human with current repository read access. */+ async linkBoard(token, board, repository) {+ identifier(board, 'BAD_BOARD');+ repositoryName(repository);+ const row = credential(token);+ if (row.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to link a board');+ const repo = await github.access({ id: row.user_id, login: row.login }, repository);+ credential(token);+ open();+ const existing = db.prepare('SELECT * FROM relay_boards WHERE id=?').get(board);+ if (existing && existing.repository_id !== String(repo.id)) throw new Refused('BOARD_LINK_CONFLICT', 'use a new board identifier for a different repository');+ db.prepare('INSERT INTO relay_boards (id,repository,repository_id) VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET repository=excluded.repository').run(board, repo.name, String(repo.id));+ permissions.delete(row.user_id + ':' + board);+ return { id: board, repository: repo.name, repositoryID: String(repo.id) };+ },+ /** List only linked boards the current credential and GitHub account may read. */+ async boardsFor(token) {+ const row = credential(token);+ const boards = row.kind === 'board' ? db.prepare('SELECT * FROM relay_boards WHERE id=?').all(row.board) : db.prepare('SELECT * FROM relay_boards ORDER BY id').all();+ const visible = [];+ for (const board of boards) {+ try { await auth.authenticate(token, { board: board.id }); visible.push({ id: board.id, repository: board.repository }); }+ catch (error) { if (error.code !== 'NO_REPO_ACCESS') throw error; }+ }+ return visible;+ },+ /** Mint an agent credential scoped to a single readable board and immutable human identity. */+ async issueToken(token, { board, agent, expiresIn = tokenTTL }) {+ identifier(board, 'BAD_BOARD');+ identifier(agent, 'BAD_AGENT');+ if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0 || expiresIn > MAX_TTL) throw new Refused('BAD_EXPIRY', 'choose a token expiry between one millisecond and thirty days');+ const principal = await auth.authenticate(token, { board, write: true });+ if (principal.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'sign in as a person to issue a board token');+ credential(token);+ return { ...issue(principal.user, 'board', board, agent, expiresIn), board, agent };+ },+ /** Revoke one owned credential; this never revokes an unrelated session or board token. */+ revoke(token, id) {+ const row = credential(token);+ if (typeof id !== 'string') throw new Refused('TOKEN_NOT_OWNED', 'name one of your relay credentials to revoke');+ const target = db.prepare('SELECT id,user_id FROM relay_credentials WHERE id=?').get(id);+ if (!target || target.user_id !== row.user_id || (row.kind !== 'session' && row.id !== id)) throw new Refused('TOKEN_NOT_OWNED', 'revoke only your own credential; sign in as its owner');+ db.prepare('UPDATE relay_credentials SET revoked=1 WHERE id=?').run(id);+ return { id, revoked: true };+ },+ /** Close persistent state and drop pending in-memory grants. */+ close() {+ if (closed) return;+ closed = true;+ webFlows.clear(); deviceFlows.clear(); permissions.clear(); db.close();+ },+ };+ return auth;+}diff --git a/relay/github.js b/relay/github.jsnew file mode 100644index 00000000..597d7a80--- /dev/null+++ b/relay/github.js@@ -0,0 +1,223 @@+/** GitHub App user authorization and read-only repository checks for the relay (H8, H1). */+import { createPrivateKey, sign } from 'node:crypto';+import { Refused } from '../src/refused.js';++export const GITHUB_API_VERSION = '2026-03-10';++/** Require an HTTPS endpoint, allowing only loopback HTTP for a stand-in provider in tests. */+function endpoint(value) {+ let url;+ try { url = new URL(value); } catch { throw new Refused('GITHUB_CONFIG', 'set a valid GitHub endpoint URL'); }+ const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);+ if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(loopback && url.protocol === 'http:'))) {+ throw new Refused('GITHUB_CONFIG', 'use HTTPS for GitHub endpoints; only a loopback test provider may use HTTP');+ }+ return url;+}++/** Keep repository names as two path components, never an arbitrary provider URL. */+export function repositoryName(value) {+ if (typeof value !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value) || (value.split('/').includes('.') || value.split('/').includes('..'))) {+ throw new Refused('BAD_REPOSITORY', 'name a GitHub repository as owner/name');+ }+ return value;+}++/** Registration asks only for metadata; user access tokens intersect the App's and user's access. */+export function githubAppManifest(callbackURL) {+ const callback = endpoint(callbackURL);+ return {+ name: 'Pullboard',+ url: 'https://pullboard.dev',+ callback_urls: [callback.href],+ hook_attributes: { url: new URL('/auth/github/events', callback).href, active: false },+ public: true,+ default_permissions: { metadata: 'read' },+ default_events: [],+ request_oauth_on_install: true,+ };+}++/** Classify provider errors without retaining or repeating its response body or credentials. */+function tokenResult(data) {+ if (['authorization_pending', 'slow_down'].includes(data.error)) {+ return { pending: true, slow: data.error === 'slow_down', interval: Number(data.interval) || undefined };+ }+ if (data.error === 'access_denied') throw new Refused('OAUTH_DENIED', 'GitHub sign-in was declined; start sign-in again if you want to continue');+ if (['expired_token', 'token_expired', 'incorrect_device_code', 'bad_verification_code'].includes(data.error)) {+ throw new Refused('OAUTH_EXPIRED', 'GitHub sign-in expired or its code is invalid; start sign-in again');+ }+ if (data.error) throw new Refused('GITHUB_AUTH', 'GitHub could not complete sign-in; check the App configuration and start again');+ if (typeof data.access_token !== 'string' || !data.access_token.startsWith('ghu_') || (typeof data.token_type !== 'string' || data.token_type.toLowerCase() !== 'bearer') || (data.scope && data.scope !== '')) {+ throw new Refused('GITHUB_AUTH', 'sign in through a GitHub App with metadata read permission; OAuth App scopes are not supported');+ }+ const expiresIn = data.expires_in === undefined ? 28_800 : Number(data.expires_in);+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) throw new Refused('OAUTH_EXPIRED', 'the GitHub credential is expired; start sign-in again');+ return { accessToken: data.access_token, expiresIn };+}++/**+ * Use GitHub's App web/device flows, without requesting OAuth scopes or following credentials to+ * another origin. The injected loopback provider exercises the real HTTP protocol in tests.+ */+export function createGitHubClient({ clientId, clientSecret, callbackURL, oauthBase = 'https://github.com', apiBase = 'https://api.github.com', timeoutMs = 10_000, privateKey, now = Date.now }) {+ if (typeof clientId !== 'string' || !clientId || typeof clientSecret !== 'string' || !clientSecret) {+ throw new Refused('GITHUB_CONFIG', 'configure the GitHub App client id and secret before starting sign-in');+ }+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000) throw new Refused('GITHUB_CONFIG', 'set a GitHub request timeout between 1 and 60000 milliseconds');+ const oauth = endpoint(oauthBase);+ const api = endpoint(apiBase);+ const callback = endpoint(callbackURL);++ const installationTokens = new Map();+ let key;+ if (privateKey) {+ try { key = createPrivateKey(privateKey); } catch { throw new Refused('GITHUB_CONFIG', 'configure a valid GitHub App RSA private key'); }+ if (key.asymmetricKeyType !== 'rsa') throw new Refused('GITHUB_CONFIG', 'configure a GitHub App RSA private key');+ }++ /** Sign a short-lived App JWT; the deployment key never enters persistent auth state. */+ function appJWT() {+ if (!key) throw new Refused('GITHUB_CONFIG', 'configure the GitHub App private key to check repository access');+ const issued = Math.floor(now() / 1000);+ const head = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url');+ const claims = Buffer.from(JSON.stringify({ iat: issued - 60, exp: issued + 540, iss: clientId })).toString('base64url');+ const unsigned = head + '.' + claims;+ return unsigned + '.' + sign('RSA-SHA256', Buffer.from(unsigned), key).toString('base64url');+ }++ /** Bound requests and same-origin redirects; never surface provider bodies in errors. */+ async function request(base, path, { form, token, json } = {}) {+ let url = new URL(path, base);+ const headers = { 'User-Agent': 'pullboard-relay', Accept: form ? 'application/json' : 'application/vnd.github+json', 'X-GitHub-Api-Version': GITHUB_API_VERSION };+ if (token) headers.Authorization = `Bearer ${token}`;+ if (form) headers['Content-Type'] = 'application/x-www-form-urlencoded';+ if (json) headers['Content-Type'] = 'application/json';+ const body = form ? new URLSearchParams(form).toString() : json ? JSON.stringify(json) : undefined;+ const signal = AbortSignal.timeout(timeoutMs);+ for (let redirects = 0; redirects < 4; redirects += 1) {+ let response;+ try { response = await fetch(url, { method: form || json ? 'POST' : 'GET', headers, body, redirect: 'manual', signal }); }+ catch { throw new Refused('GITHUB_UNAVAILABLE', 'GitHub is unavailable; retry when it answers'); }+ if (response.status >= 300 && response.status < 400) {+ const location = response.headers.get('location');+ await response.body?.cancel();+ let next;+ try { next = new URL(location, url); } catch { /* Refuse malformed redirect targets below. */ }+ if (form || json || !location || !next || next.origin !== base.origin || next.username || next.password) {+ throw new Refused('GITHUB_UNAVAILABLE', 'GitHub returned an unsafe redirect; retry or check the configured endpoint');+ }+ url = next;+ continue;+ }+ if ([401, 403, 404].includes(response.status)) {+ await response.body?.cancel();+ throw new Refused('NO_REPO_ACCESS', 'GitHub cannot confirm access with this sign-in; sign in again or ask for repository access');+ }+ if (!response.ok) {+ await response.body?.cancel();+ throw new Refused('GITHUB_UNAVAILABLE', 'GitHub is unavailable or rate limited; retry when it answers');+ }+ let data;+ try {+ const chunks = [];+ let size = 0;+ for await (const chunk of response.body) {+ size += chunk.byteLength;+ if (size > 65_536) throw new Error('response limit');+ chunks.push(chunk);+ }+ data = JSON.parse(Buffer.concat(chunks).toString('utf8'));+ } catch { throw new Refused('GITHUB_UNAVAILABLE', 'GitHub returned an invalid response; retry when it answers'); }+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Refused('GITHUB_UNAVAILABLE', 'GitHub returned an invalid response; retry when it answers');+ return data;+ }+ throw new Refused('GITHUB_UNAVAILABLE', 'GitHub redirected too many times; retry or check the configured endpoint');+ }++ return {+ /** Send the browser through an App authorization with CSRF state and an S256 PKCE challenge. */+ authorizeURL(state, challenge) {+ if (typeof state !== 'string' || !state || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) throw new Refused('OAUTH_STATE', 'start a new browser sign-in');+ const url = new URL('/login/oauth/authorize', oauth);+ url.search = new URLSearchParams({ client_id: clientId, redirect_uri: callback.href, state, code_challenge: challenge, code_challenge_method: 'S256' }).toString();+ return url.href;+ },+ /** Exchange a one-use browser code; the service owns state validation and verifier secrecy. */+ async exchangeCode(code, verifier) {+ if (typeof code !== 'string' || !code || typeof verifier !== 'string' || !verifier) throw new Refused('OAUTH_STATE', 'start a new browser sign-in');+ return tokenResult(await request(oauth, '/login/oauth/access_token', { form: { client_id: clientId, client_secret: clientSecret, redirect_uri: callback.href, code, code_verifier: verifier } }));+ },+ /** Request a device authorization without broad OAuth scopes or a CLI-held App secret. */+ async startDevice() {+ const data = await request(oauth, '/login/device/code', { form: { client_id: clientId } });+ if (typeof data.device_code !== 'string' || !data.device_code || typeof data.user_code !== 'string' || !data.user_code || !Number.isFinite(Number(data.expires_in)) || Number(data.expires_in) <= 0 || !Number.isFinite(Number(data.interval)) || Number(data.interval) <= 0) {+ throw new Refused('GITHUB_AUTH', 'GitHub returned an invalid device flow; start sign-in again');+ }+ let verification;+ try { verification = new URL(data.verification_uri); } catch { /* Refuse absent or malformed URLs below. */ }+ if (!verification || verification.origin !== oauth.origin || verification.username || verification.password) throw new Refused('GITHUB_AUTH', 'GitHub returned an unexpected verification address; start sign-in again');+ return { deviceCode: data.device_code, userCode: data.user_code, verificationURL: verification.href, expiresIn: Number(data.expires_in), interval: Number(data.interval) };+ },+ /** Poll only when the auth service permits it; GitHub's pending/slow-down results stay typed. */+ async pollDevice(deviceCode) {+ return tokenResult(await request(oauth, '/login/oauth/access_token', { form: { client_id: clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' } }));+ },+ /** Confirm the current user's immutable identity before minting a relay session. */+ async user(token) {+ const data = await request(api, '/user', { token });+ if (!Number.isSafeInteger(data.id) || data.id <= 0 || typeof data.login !== 'string' || !data.login) throw new Refused('GITHUB_AUTH', 'GitHub did not confirm an account; start sign-in again');+ return { id: String(data.id), login: data.login };+ },+ /** Check current account access with App metadata, discarding every sign-in credential. */+ async access(user, name) {+ const path = '/repos/' + repositoryName(name).split('/').map(encodeURIComponent).join('/');+ let installation;+ try { installation = await request(api, path + '/installation', { token: appJWT() }); }+ catch (error) {+ if (error.code !== 'NO_REPO_ACCESS') throw error;+ const publicRepo = await request(api, path);+ if (publicRepo.private !== false || !Number.isSafeInteger(publicRepo.id) || publicRepo.id <= 0) {+ throw new Refused('NO_REPO_ACCESS', 'install the GitHub App on this repository and ask for repository access');+ }+ return { id: String(publicRepo.id), name: repositoryName(publicRepo.full_name) };+ }+ if (!Number.isSafeInteger(installation.id) || installation.id <= 0) throw new Refused('NO_REPO_ACCESS', 'GitHub did not confirm an App installation; install the App on this repository');+ const cacheKey = String(installation.id) + ':' + name.toLowerCase();+ let credential = installationTokens.get(cacheKey);+ if (!credential || credential.expires <= now() + 60_000) {+ const minted = await request(api, '/app/installations/' + installation.id + '/access_tokens', {+ token: appJWT(), json: { repositories: [name.split('/')[1]], permissions: { metadata: 'read' } },+ });+ const expires = Date.parse(minted.expires_at);+ if (typeof minted.token !== 'string' || !minted.token.startsWith('ghs_') || !Number.isFinite(expires) || expires <= now()) {+ throw new Refused('GITHUB_AUTH', 'GitHub did not issue a current App token; check the App installation');+ }+ credential = { token: minted.token, expires };+ installationTokens.set(cacheKey, credential);+ }+ try {+ const repo = await request(api, path, { token: credential.token });+ if (!Number.isSafeInteger(repo.id) || repo.id <= 0 || typeof repo.private !== 'boolean') throw new Refused('NO_REPO_ACCESS', 'GitHub did not confirm repository metadata; check the App installation');+ if (repo.private) {+ if (!user || !/^[A-Za-z0-9-]+$/.test(user.login)) throw new Refused('NO_REPO_ACCESS', 'sign in again to confirm your GitHub account');+ const permission = await request(api, path + '/collaborators/' + encodeURIComponent(user.login) + '/permission', { token: credential.token });+ if (String(permission.user?.id) !== String(user.id) || !['read', 'triage', 'write', 'maintain', 'admin'].includes(permission.permission)) {+ throw new Refused('NO_REPO_ACCESS', 'your GitHub account cannot read this repository; ask for access or sign in again');+ }+ }+ return { id: String(repo.id), name: repositoryName(repo.full_name) };+ } catch (error) {+ if (error.code === 'NO_REPO_ACCESS') installationTokens.delete(cacheKey);+ throw error;+ }+ },+ /** A successful metadata read proves both App and user access; pin the immutable repo id. */+ async repository(token, name) {+ const [owner, repo] = repositoryName(name).split('/');+ const data = await request(api, `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`, { token });+ if (!Number.isSafeInteger(data.id) || data.id <= 0 || typeof data.full_name !== 'string') throw new Refused('NO_REPO_ACCESS', 'GitHub did not confirm this repository; ask for access or check its name');+ return { id: String(data.id), name: repositoryName(data.full_name) };+ },+ };+}diff --git a/test/relay-fixture.js b/test/relay-fixture.jsnew file mode 100644index 00000000..6cccb90c--- /dev/null+++ b/test/relay-fixture.js@@ -0,0 +1,115 @@+/** Real loopback GitHub protocol stand-in; all credentials and keys are generated in memory [H8, H1]. */+import assert from 'node:assert/strict';+import { createHash, generateKeyPairSync, randomBytes, verify } from 'node:crypto';+import { createServer } from 'node:http';+import { once } from 'node:events';++/** Start a provider with real signed JWT verification and one-use browser/device grants. */+export async function githubFixture(t) {+ const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });+ const state = { access: true, public: false, installed: true, repositoryID: 100, accountID: 7, permissionAccountID: 7, deviceAuthorized: false, slow: false, redirect: null };+ const calls = [];+ const codes = new Map();+ const userTokens = new Set();+ const installationTokens = new Set();+ const deviceCode = randomBytes(24).toString('base64url');+ const clientSecret = randomBytes(24).toString('base64url');+ let origin;++ /** Return JSON without recording provider credentials in fixture diagnostics. */+ function reply(res, status, value) {+ res.writeHead(status, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(value));+ }++ /** Verify App identity cryptographically, rather than accepting an arbitrary bearer string. */+ function appToken(token) {+ try {+ const [header, payload, signature] = token.split('.');+ const claims = JSON.parse(Buffer.from(payload, 'base64url'));+ return JSON.parse(Buffer.from(header, 'base64url')).alg === 'RS256' && claims.iss === 'fixture-app' && claims.exp > Date.now() / 1000 && claims.exp - claims.iat <= 600 && verify('RSA-SHA256', Buffer.from(header + '.' + payload), publicKey, Buffer.from(signature, 'base64url'));+ } catch { return false; }+ }++ /** Issue synthetic user credentials; only in-memory Sets ever retain their plaintext. */+ function userCredential() {+ const token = 'ghu_' + randomBytes(32).toString('base64url');+ userTokens.add(token);+ return { access_token: token, token_type: 'bearer', scope: '', expires_in: 3600 };+ }++ /** Implement the actual OAuth and metadata HTTP endpoints used by the relay. */+ async function handle(req, res) {+ const url = new URL(req.url, origin);+ const bearer = (req.headers.authorization || '').replace(/^Bearer /, '');+ const isApp = appToken(bearer);+ const isInstallation = installationTokens.has(bearer);+ const isUser = userTokens.has(bearer);+ let raw = '';+ for await (const chunk of req) raw += chunk;+ const form = new URLSearchParams(raw);+ calls.push({ method: req.method, path: url.pathname, user: isUser, app: isApp, installation: isInstallation, apiVersion: req.headers['x-github-api-version'], formKeys: [...form.keys()] });+ if (url.pathname === '/login/oauth/authorize') {+ assert.equal(url.searchParams.get('scope'), null);+ assert.equal(url.searchParams.get('client_id'), 'fixture-app');+ assert.equal(url.searchParams.get('code_challenge_method'), 'S256');+ const code = randomBytes(24).toString('base64url');+ codes.set(code, url.searchParams.get('code_challenge'));+ const callback = new URL(url.searchParams.get('redirect_uri'));+ callback.searchParams.set('code', code);+ callback.searchParams.set('state', url.searchParams.get('state'));+ res.writeHead(303, { location: callback.href });+ return res.end();+ }+ if (url.pathname === '/login/device/code') {+ assert.deepEqual([...form.keys()], ['client_id']);+ return reply(res, 200, { device_code: deviceCode, user_code: 'TEST-ONLY', verification_uri: origin + '/login/device', expires_in: 900, interval: 1 });+ }+ if (url.pathname === '/login/device') {+ state.deviceAuthorized = true;+ res.writeHead(200, { 'Content-Type': 'text/html' });+ return res.end('<p>Test account authorized.</p>');+ }+ if (url.pathname === '/login/oauth/access_token') {+ assert.equal(form.get('scope'), null);+ assert.equal(form.get('client_id'), 'fixture-app');+ if (form.has('device_code')) {+ assert.equal(form.get('client_secret'), null);+ assert.equal(form.get('grant_type'), 'urn:ietf:params:oauth:grant-type:device_code');+ assert.equal(form.get('device_code'), deviceCode);+ if (state.slow) { state.slow = false; return reply(res, 200, { error: 'slow_down' }); }+ return reply(res, 200, state.deviceAuthorized ? userCredential() : { error: 'authorization_pending' });+ }+ assert.ok(form.get('client_secret') === clientSecret, 'browser exchange uses configured App secret');+ const challenge = codes.get(form.get('code'));+ codes.delete(form.get('code'));+ const proof = createHash('sha256').update(form.get('code_verifier') || '').digest('base64url');+ return reply(res, 200, challenge && proof === challenge ? userCredential() : { error: 'bad_verification_code' });+ }+ if (url.pathname === '/user') {+ if (state.redirect) { res.writeHead(302, { location: state.redirect }); return res.end(); }+ return reply(res, isUser ? 200 : 401, { id: state.accountID, login: 'fixture-user' });+ }+ if (url.pathname === '/repos/fixture/repository/installation') return reply(res, isApp && state.installed ? 200 : 404, { id: 42 });+ if (url.pathname === '/app/installations/42/access_tokens') {+ assert.ok(isApp, 'installation request has a valid RSA App JWT');+ assert.deepEqual(JSON.parse(raw), { repositories: ['repository'], permissions: { metadata: 'read' } });+ const token = 'ghs_' + randomBytes(32).toString('base64url');+ installationTokens.add(token);+ return reply(res, 201, { token, expires_at: new Date(Date.now() + 3600_000).toISOString() });+ }+ if (url.pathname === '/repos/fixture/repository') return reply(res, isInstallation || state.public ? 200 : 404, { id: state.repositoryID, full_name: 'fixture/repository', private: !state.public });+ if (url.pathname === '/repos/fixture/repository/collaborators/fixture-user/permission') {+ if (state.beforePermission) await state.beforePermission();+ return reply(res, isInstallation ? 200 : 403, { permission: state.access ? 'read' : 'none', user: { id: state.permissionAccountID } });+ }+ return reply(res, 404, { message: 'not available' });+ }++ const server = createServer(handle);+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ origin = 'http://127.0.0.1:' + server.address().port;+ t.after(() => { server.closeAllConnections(); server.close(); });+ return { state, calls, origin, userTokens, installationTokens, config: { clientId: 'fixture-app', clientSecret, privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }), oauthBase: origin, apiBase: origin, callbackURL: origin + '/callback' } };+}diff --git a/test/relay-github.test.js b/test/relay-github.test.jsnew file mode 100644index 00000000..e580446c--- /dev/null+++ b/test/relay-github.test.js@@ -0,0 +1,73 @@+/** GitHub App authorization and metadata-only access against real loopback HTTP [H8, H1]. */+import assert from 'node:assert/strict';+import { createHash, randomBytes } from 'node:crypto';+import { createServer } from 'node:http';+import { once } from 'node:events';+import { test } from 'node:test';+import { createGitHubClient, githubAppManifest, repositoryName, GITHUB_API_VERSION } from '../relay/github.js';+import { githubFixture } from './relay-fixture.js';++test('App browser grant uses state and PKCE and is one-use [H8, H1]', async (t) => {+ const fixture = await githubFixture(t);+ const client = createGitHubClient(fixture.config);+ const verifier = randomBytes(32).toString('base64url');+ const state = randomBytes(32).toString('base64url');+ const authorize = new URL(client.authorizeURL(state, createHash('sha256').update(verifier).digest('base64url')));+ assert.equal(authorize.searchParams.get('state'), state);+ const response = await fetch(authorize, { redirect: 'manual' });+ const callback = new URL(response.headers.get('location'));+ assert.equal(callback.searchParams.get('state'), state);+ const result = await client.exchangeCode(callback.searchParams.get('code'), verifier);+ assert.deepEqual(await client.user(result.accessToken), { id: '7', login: 'fixture-user' });+ await assert.rejects(client.exchangeCode(callback.searchParams.get('code'), verifier), { code: 'OAUTH_EXPIRED' });+ assert.ok(fixture.calls.filter(call => call.path !== '/login/oauth/authorize').every(call => call.apiVersion === GITHUB_API_VERSION));+});++test('device grant polls pending and slow-down without CLI-held secret [H8, H1]', async (t) => {+ const fixture = await githubFixture(t);+ const client = createGitHubClient(fixture.config);+ const grant = await client.startDevice();+ assert.equal((await client.pollDevice(grant.deviceCode)).pending, true);+ fixture.state.slow = true;+ assert.equal((await client.pollDevice(grant.deviceCode)).slow, true);+ await fetch(grant.verificationURL);+ const signed = await client.pollDevice(grant.deviceCode);+ assert.equal((await client.user(signed.accessToken)).id, '7');+ const polls = fixture.calls.filter(call => call.path === '/login/oauth/access_token');+ assert.ok(polls.every(call => !call.formKeys.includes('client_secret') && !call.formKeys.includes('scope')));+});++test('App metadata checks current private access and immutable account identity [H8, H1]', async (t) => {+ const fixture = await githubFixture(t);+ const client = createGitHubClient(fixture.config);+ const user = { id: '7', login: 'fixture-user' };+ assert.deepEqual(await client.access(user, 'fixture/repository'), { id: '100', name: 'fixture/repository' });+ fixture.state.access = false;+ await assert.rejects(client.access(user, 'fixture/repository'), { code: 'NO_REPO_ACCESS' });+ fixture.state.access = true;+ fixture.state.permissionAccountID = 8;+ await assert.rejects(client.access(user, 'fixture/repository'), { code: 'NO_REPO_ACCESS' });+ fixture.state.installed = false;+ await assert.rejects(client.access(user, 'fixture/repository'), { code: 'NO_REPO_ACCESS' });+ fixture.state.public = true;+ assert.equal((await client.access(user, 'fixture/repository')).id, '100');+ assert.ok(fixture.calls.filter(call => call.path.endsWith('/permission')).every(call => call.installation && !call.user));+ assert.deepEqual(githubAppManifest(fixture.config.callbackURL).default_permissions, { metadata: 'read' });+ assert.throws(() => repositoryName('owner/../other'), { code: 'BAD_REPOSITORY' });+});++test('GitHub credentials never follow a redirect to a different origin [H8, H1]', async (t) => {+ const fixture = await githubFixture(t);+ let foreignRequests = 0;+ const foreign = createServer((req, res) => { foreignRequests += 1; res.end('{}'); });+ foreign.listen(0, '127.0.0.1');+ await once(foreign, 'listening');+ t.after(() => { foreign.closeAllConnections(); foreign.close(); });+ fixture.state.redirect = 'http://127.0.0.1:' + foreign.address().port + '/capture';+ const client = createGitHubClient(fixture.config);+ const grant = await client.startDevice();+ fixture.state.deviceAuthorized = true;+ const signed = await client.pollDevice(grant.deviceCode);+ await assert.rejects(client.user(signed.accessToken), { code: 'GITHUB_UNAVAILABLE' });+ assert.equal(foreignRequests, 0);+});diff --git a/test/relay-http.test.js b/test/relay-http.test.jsnew file mode 100644index 00000000..010b191d--- /dev/null+++ b/test/relay-http.test.js@@ -0,0 +1,110 @@+/** Actual browser/device HTTP contracts, cookie isolation and mutation CSRF protection [H8, H1]. */+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import { once } from 'node:events';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { createGitHubClient } from '../relay/github.js';+import { createRelayAuth } from '../relay/auth.js';+import { createAuthHandler } from '../relay/auth-http.js';+import { githubFixture } from './relay-fixture.js';++/** Start the real auth HTTP handler on loopback with a private SQLite auth store. */+async function relay(t) {+ const provider = await githubFixture(t);+ const root = mkdtempSync(join(tmpdir(), 'pullboard-relay-http-'));+ let handler;+ const server = createServer(async (req, res) => {+ if (await handler(req, res)) return;+ res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<title>Relay test</title><p>Signed in.</p>');+ });+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ const origin = 'http://127.0.0.1:' + server.address().port;+ const github = createGitHubClient({ ...provider.config, callbackURL: origin + '/auth/github/callback' });+ let time = Date.now();+ const auth = createRelayAuth({ database: join(root, 'auth.sqlite'), github, now: () => time });+ handler = createAuthHandler({ auth, publicOrigin: origin });+ t.after(() => { server.closeAllConnections(); server.close(); auth.close(); rmSync(root, { recursive: true, force: true }); });+ return { ...provider, origin, auth, advance(ms) { time += ms; } };+}++/** Follow the real browser redirects while keeping flow cookies out of request URLs. */+async function browserLogin(box) {+ const start = await fetch(box.origin + '/auth/github/start', { redirect: 'manual' });+ const binding = start.headers.getSetCookie()[0].split(';')[0];+ assert.match(start.headers.getSetCookie()[0], /HttpOnly; SameSite=Lax/);+ const grant = await fetch(start.headers.get('location'), { redirect: 'manual' });+ const callbackURL = grant.headers.get('location');+ const callback = await fetch(callbackURL, { redirect: 'manual', headers: { cookie: binding } });+ assert.equal(callback.status, 303);+ assert.equal(callback.headers.get('location'), '/');+ assert.equal(callback.headers.get('cache-control'), 'no-store');+ const cookie = callback.headers.getSetCookie().find(value => value.startsWith('pb_session='));+ assert.match(cookie, /HttpOnly; SameSite=Lax/);+ return { cookie: cookie.split(';')[0], callbackURL, binding };+}++test('web redirects create HttpOnly sessions; replay and cross-origin cookie writes are refused [H8, H1]', async (t) => {+ const box = await relay(t);+ const signed = await browserLogin(box);+ const session = await fetch(box.origin + '/auth/session', { headers: { cookie: signed.cookie } });+ const principal = await session.json();+ assert.equal(principal.version, 1);+ assert.equal(principal.session.user.id, '7');+ assert.equal(principal.session.token, undefined);+ const replay = await fetch(signed.callbackURL, { redirect: 'manual', headers: { cookie: signed.binding } });+ assert.equal((await replay.json()).error.code, 'OAUTH_STATE');+ const input = { board: 'alpha', repository: 'fixture/repository' };+ const denied = await fetch(box.origin + '/auth/boards/link', { method: 'POST', headers: { cookie: signed.cookie, origin: 'https://foreign.invalid', 'Content-Type': 'application/json' }, body: JSON.stringify(input) });+ assert.equal(denied.status, 403);+ assert.equal((await denied.json()).error.code, 'BAD_ORIGIN');+ const linked = await fetch(box.origin + '/auth/boards/link', { method: 'POST', headers: { cookie: signed.cookie, origin: box.origin, 'Content-Type': 'application/json' }, body: JSON.stringify(input) });+ assert.equal(linked.status, 200);+ assert.equal((await linked.json()).board.id, 'alpha');+});++test('CLI device HTTP flow returns a one-time session and individually revocable board token [H8, H1]', async (t) => {+ const box = await relay(t);+ const start = await fetch(box.origin + '/auth/device/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });+ const grant = await start.json();+ assert.equal(grant.version, 1);+ assert.equal(grant.deviceCode, undefined);+ await fetch(grant.verificationURL);+ box.advance(grant.interval * 1000);+ const poll = await fetch(box.origin + '/auth/device/poll', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ticket: grant.ticket }) });+ const signed = await poll.json();+ assert.equal(signed.user.id, '7');+ assert.equal(poll.headers.get('cache-control'), 'no-store');+ const headers = { authorization: 'Bearer ' + signed.token, 'Content-Type': 'application/json' };+ const link = await fetch(box.origin + '/auth/boards/link', { method: 'POST', headers, body: JSON.stringify({ board: 'alpha', repository: 'fixture/repository' }) });+ assert.equal(link.status, 200);+ const issue = await fetch(box.origin + '/auth/tokens', { method: 'POST', headers, body: JSON.stringify({ board: 'alpha', agent: 'worker' }) });+ assert.equal(issue.status, 201);+ const scoped = await issue.json();+ const boards = await fetch(box.origin + '/auth/boards', { headers: { authorization: 'Bearer ' + scoped.token } });+ assert.equal((await boards.json()).boards.length, 1);+ const revoke = await fetch(box.origin + '/auth/tokens/revoke', { method: 'POST', headers, body: JSON.stringify({ id: scoped.id }) });+ assert.equal((await revoke.json()).revoked, true);+ const revoked = await fetch(box.origin + '/auth/boards', { headers: { authorization: 'Bearer ' + scoped.token } });+ assert.equal(revoked.status, 401);+ assert.equal((await revoked.json()).error.code, 'AUTH_REQUIRED');+});++test('HTTP errors are versioned and bounded; production cookies are Secure [H8, H1]', async (t) => {+ const box = await relay(t);+ const malformed = await fetch(box.origin + '/auth/device/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '[' });+ const error = await malformed.json();+ assert.equal(error.version, 1);+ assert.deepEqual(Object.keys(error.error).sort(), ['code', 'message', 'next']);+ assert.equal(error.error.code, 'BAD_REQUEST');+ const tooLarge = await fetch(box.origin + '/auth/device/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ padding: 'x'.repeat(17_000) }) });+ assert.equal((await tooLarge.json()).error.code, 'BAD_REQUEST');+ let captured;+ const secureHandler = createAuthHandler({ auth: box.auth, publicOrigin: 'https://relay.example.invalid' });+ await secureHandler({ method: 'GET', url: '/auth/github/start', headers: {} }, { writeHead(status, headers) { captured = headers; }, end() {} });+ assert.match(captured['Set-Cookie'], /; Secure$/);+ assert.throws(() => createAuthHandler({ auth: box.auth, publicOrigin: 'http://relay.example.invalid' }), { code: 'RELAY_CONFIG' });+});diff --git a/test/relay.test.js b/test/relay.test.jsnew file mode 100644index 00000000..a44230c0--- /dev/null+++ b/test/relay.test.js@@ -0,0 +1,163 @@+/** Relay identity, expiry, permission freshness and scoped credential isolation [H8, H1]. */+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { createGitHubClient } from '../relay/github.js';+import { createRelayAuth, ACCESS_WINDOW_MS } from '../relay/auth.js';+import { githubFixture } from './relay-fixture.js';++/** Use real private SQLite and an actual HTTP provider with a controllable expiry clock. */+async function fixture(t, options = {}) {+ const provider = await githubFixture(t);+ const root = mkdtempSync(join(tmpdir(), 'pullboard-relay-auth-'));+ const database = join(root, 'auth.sqlite');+ let time = Date.now();+ const clock = () => time;+ const github = createGitHubClient(provider.config);+ const config = { database, github, now: clock, ...options };+ const auth = createRelayAuth(config);+ t.after(() => { auth.close(); rmSync(root, { recursive: true, force: true }); });+ return { ...provider, providerConfig: provider.config, auth, database, config, advance(ms) { time += ms; } };+}++/** Complete a real stand-in device grant, advancing only the injected relay expiry clock. */+async function login(box) {+ const grant = await box.auth.beginDevice();+ box.state.deviceAuthorized = true;+ box.advance(grant.interval * 1000);+ return box.auth.pollDevice(grant.ticket);+}++test('browser state/cookie binding and one-use device ticket protect both sign-in flows [H8, H1]', async (t) => {+ const box = await fixture(t);+ const web = box.auth.beginWeb();+ const authorized = await fetch(web.authorizationURL, { redirect: 'manual' });+ const callback = new URL(authorized.headers.get('location'));+ const state = callback.searchParams.get('state');+ const code = callback.searchParams.get('code');+ await assert.rejects(box.auth.finishWeb(state, code, 'wrong-browser'), { code: 'OAUTH_STATE' });+ const signed = await box.auth.finishWeb(state, code, web.binding);+ assert.equal((await box.auth.authenticate(signed.token)).user.id, '7');+ await assert.rejects(box.auth.finishWeb(state, code, web.binding), { code: 'OAUTH_STATE' });+ const grant = await box.auth.beginDevice();+ assert.equal(grant.deviceCode, undefined);+ const polls = box.calls.filter(call => call.path === '/login/oauth/access_token').length;+ assert.equal((await box.auth.pollDevice(grant.ticket)).pending, true);+ assert.equal(box.calls.filter(call => call.path === '/login/oauth/access_token').length, polls);+ box.advance(1000);+ box.state.slow = true;+ assert.equal((await box.auth.pollDevice(grant.ticket)).retryAfter, 6);+ box.advance(6000);+ box.state.deviceAuthorized = true;+ const cli = await box.auth.pollDevice(grant.ticket);+ assert.equal((await box.auth.authenticate(cli.token)).user.id, '7');+ await assert.rejects(box.auth.pollDevice(grant.ticket), { code: 'OAUTH_EXPIRED' });+});++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);+ box.state.access = false;+ await assert.rejects(box.auth.linkBoard(signed.token, 'alpha', 'fixture/repository'), { code: 'NO_REPO_ACCESS' });+ assert.deepEqual(await box.auth.boardsFor(signed.token), []);+ box.state.access = true;+ await box.auth.linkBoard(signed.token, 'alpha', 'fixture/repository');+ await box.auth.linkBoard(signed.token, 'beta', 'fixture/repository');+ const agent = await box.auth.issueToken(signed.token, { board: 'alpha', agent: 'worker-1' });+ assert.equal((await box.auth.authenticate(agent.token, { board: 'alpha', write: true })).agent, 'worker-1');+ const before = box.calls.length;+ await assert.rejects(box.auth.authenticate(agent.token, { board: 'beta', write: true }), { code: 'TOKEN_BOARD' });+ assert.equal(box.calls.length, before, 'cross-board credentials are rejected before a provider check');+ assert.deepEqual((await box.auth.boardsFor(agent.token)).map(board => board.id), ['alpha']);+ await assert.rejects(box.auth.linkBoard(agent.token, 'gamma', 'fixture/repository'), { code: 'HUMAN_REQUIRED' });+});++test('lost GitHub read access takes effect at ten minutes and before every board write [H8, H1]', async (t) => {+ const box = await fixture(t);+ const signed = await login(box);+ await box.auth.linkBoard(signed.token, 'alpha', 'fixture/repository');+ await box.auth.authenticate(signed.token, { board: 'alpha' });+ box.state.access = false;+ box.advance(ACCESS_WINDOW_MS - 1);+ assert.equal((await box.auth.boardsFor(signed.token)).length, 1, 'cached reads last less than ten minutes');+ box.advance(1);+ assert.deepEqual(await box.auth.boardsFor(signed.token), []);+ box.state.access = true;+ await box.auth.authenticate(signed.token, { board: 'alpha', write: true });+ box.state.access = false;+ await assert.rejects(box.auth.authenticate(signed.token, { board: 'alpha', write: true }), { code: 'NO_REPO_ACCESS' });+ assert.deepEqual(await box.auth.boardsFor(signed.token), [], 'a denied write invalidates an earlier allowed read');+});++test('credentials are hash-only, expire, revoke individually and survive relay restart [H8, H1]', async (t) => {+ const box = await fixture(t, { sessionTTL: 30_000 });+ const signed = await login(box);+ await box.auth.linkBoard(signed.token, 'alpha', 'fixture/repository');+ const first = await box.auth.issueToken(signed.token, { board: 'alpha', agent: 'one', expiresIn: 10_000 });+ const second = await box.auth.issueToken(signed.token, { board: 'alpha', agent: 'two', expiresIn: 20_000 });+ assert.notEqual(first.token, second.token);+ box.auth.revoke(signed.token, first.id);+ await assert.rejects(box.auth.authenticate(first.token, { board: 'alpha' }), { code: 'AUTH_REQUIRED' });+ assert.equal((await box.auth.authenticate(second.token, { board: 'alpha' })).agent, 'two');+ const persisted = readFileSync(box.database);+ for (const secret of [signed.token, first.token, second.token, box.providerConfig.privateKey, box.providerConfig.clientSecret, ...box.userTokens, ...box.installationTokens].filter(Boolean)) {+ assert.ok(!persisted.includes(Buffer.from(secret)), 'plaintext credential is absent from real SQLite bytes');+ }+ box.auth.close();+ const userCalls = box.calls.filter(call => call.path === '/user').length;+ const restarted = createRelayAuth({ ...box.config, github: createGitHubClient(box.providerConfig) });+ t.after(() => restarted.close());+ assert.equal((await restarted.authenticate(signed.token, { board: 'alpha', write: true })).user.id, '7');+ assert.equal(box.calls.filter(call => call.path === '/user').length, userCalls, 'restart requires no new sign-in or user credential');+ await assert.rejects(restarted.authenticate(first.token, { board: 'alpha' }), { code: 'AUTH_REQUIRED' });+ box.advance(20_000);+ await assert.rejects(restarted.authenticate(second.token, { board: 'alpha' }), { code: 'AUTH_REQUIRED' });+ box.advance(10_000);+ await assert.rejects(restarted.authenticate(signed.token), { code: 'AUTH_REQUIRED' });+});++test('revoking during an awaited GitHub write check refuses the pending write [H8, H1]', async (t) => {+ const box = await fixture(t);+ const signed = await login(box);+ await box.auth.linkBoard(signed.token, 'alpha', 'fixture/repository');+ let release;+ let entered;+ const held = new Promise(resolve => { release = resolve; });+ const started = new Promise(resolve => { entered = resolve; });+ box.state.beforePermission = async () => { entered(); await held; };+ const pending = box.auth.authenticate(signed.token, { board: 'alpha', write: true });+ await started;+ box.auth.revoke(signed.token, signed.id);+ release();+ await assert.rejects(pending, { code: 'AUTH_REQUIRED' });+});++test('a deleted and recreated repository cannot inherit the linked board [H8, H1]', async (t) => {+ const box = await fixture(t);+ const signed = await login(box);+ await box.auth.linkBoard(signed.token, 'alpha', 'fixture/repository');+ box.state.repositoryID = 200;+ await assert.rejects(box.auth.authenticate(signed.token, { board: 'alpha', write: true }), { code: 'NO_REPO_ACCESS' });+ await assert.rejects(box.auth.linkBoard(signed.token, 'alpha', 'fixture/repository'), { code: 'BOARD_LINK_CONFLICT' });+});++test('expired browser/device grants cannot create sessions and concurrent polls consume only once [H8, H1]', async (t) => {+ const box = await fixture(t);+ const web = box.auth.beginWeb();+ const response = await fetch(web.authorizationURL, { redirect: 'manual' });+ const callback = new URL(response.headers.get('location'));+ box.advance(10 * 60_000);+ await assert.rejects(box.auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), web.binding), { code: 'OAUTH_STATE' });+ const expired = await box.auth.beginDevice();+ box.advance(expired.expiresIn * 1000);+ await assert.rejects(box.auth.pollDevice(expired.ticket), { code: 'OAUTH_EXPIRED' });+ const grant = await box.auth.beginDevice();+ box.state.deviceAuthorized = true;+ box.advance(grant.interval * 1000);+ const results = await Promise.all([box.auth.pollDevice(grant.ticket), box.auth.pollDevice(grant.ticket)]);+ assert.equal(results.filter(result => result.token).length, 1);+ assert.equal(results.filter(result => result.pending).length, 1);+ await assert.rejects(box.auth.pollDevice(grant.ticket), { code: 'OAUTH_EXPIRED' });+});