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(view): exchange the view key for a session cookie [N39,N26]
Corey Olson16da6402d728
diff --git a/src/serve.js b/src/serve.jsindex 8977099d..d1e2129e 100644--- a/src/serve.js+++ b/src/serve.js@@ -5,7 +5,7 @@* real CLI in the project, so every rule and refusal applies exactly as at a terminal.** It listens on the loopback address only and answers nothing without its own Host, and no board without the- * session's secret, so another site in the browser cannot reach it. Besides its own page, it answers one other origin,+ * session's secret or its HttpOnly session cookie, so another site in the browser cannot reach it. Besides its own page, it answers one other origin,* the hosted page at https://app.pullboard.dev, which gets the secret by a round trip that only ever returns there.* Idle reads open no outbound connection (P5); an explicit person sign-in reuses the existing relay linking flow.*/@@ -440,6 +440,41 @@ function sandboxListenStep(env = process.env) {return `allow local network in your agent tool's sandbox settings, ${terminal}`;}+/**+ * The one value a request's Cookie header gives the named cookie, or null when it gives none, names+ * it without a value, or gives it twice: another server on this host can set a cookie of the same+ * name, so a second copy makes both untrustworthy. It reads the view's cookie exactly as the local+ * API does (src/api.js), so the page and its API never disagree about who holds the session.+ *+ * @param {unknown} header+ * @param {string} name+ * @returns {string | null}+ */+function requestCookie(header, name) {+ if (typeof header !== 'string') return null;+ let found = null;+ for (const part of header.split(';')) {+ const separator = part.indexOf('=');+ if (separator < 0) {+ if (part.trim() === name) return null;+ continue;+ }+ if (part.slice(0, separator).trim() !== name) continue;+ if (found !== null) return null;+ found = part.slice(separator + 1).trim();+ }+ return found;+}++/**+ * Whether a credential a request offers is the expected one, compared in constant time.+ *+ * @param {Buffer} given+ * @param {Buffer} expected+ * @returns {boolean}+ */+const credentialMatches = (given, expected) => given.length === expected.length && timingSafeEqual(given, expected);+/*** Serve the view until stopped, optionally giving its API access to only one registered project.*@@ -448,6 +483,12 @@ function sandboxListenStep(env = process.env) {*/export async function serveView({ port = 0, secret = randomBytes(18).toString('base64url'), projectRoot } = {}) {const key = Buffer.from(secret);+ const cookieName = `pullboard_view_${randomBytes(9).toString('hex')}`;+ const session = randomBytes(18).toString('base64url');+ const sessionKey = Buffer.from(session);+ /** Only same-origin browser requests may authenticate by this session cookie. */+ const cookieMatches = (req) => credentialMatches(Buffer.from(requestCookie(req.headers.cookie, cookieName) ?? ''), sessionKey)+ && (req.headers['sec-fetch-site'] === undefined || req.headers['sec-fetch-site'] === 'same-origin');let bound = 0;// The API reads projectState and codeAt from this module. Load its factory after our exports// initialize, and use the real CLI entry point without adding a second move implementation.@@ -457,14 +498,15 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('bconst signIns = new Set();const signInLifetime = new AbortController();const apiHandler = createLocalApiHandler({ secret, getPort: () => bound, runCommand: main, stateDetail: 'summary',- allowedOrigins: [HOSTED_ORIGIN], ...(projectRoot === undefined ? {} : { scope: { projectRoot } }) });- const reply = (res, code, type, body) => {+ allowedOrigins: [HOSTED_ORIGIN], sessionCookie: { name: cookieName, value: session }, ...(projectRoot === undefined ? {} : { scope: { projectRoot } }) });+ const reply = (res, code, type, body, headers = {}) => {res.writeHead(code, {'content-type': type,'cache-control': 'no-store','referrer-policy': 'no-referrer','x-content-type-options': 'nosniff','content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",+ ...headers,});res.end(body);};@@ -526,7 +568,7 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('b/** Forget only roots that the same current registry snapshot cannot open as boards. */async function forgetUnreadableRequest(req, res, url) {const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? ''));- if (given.length !== key.length || !timingSafeEqual(given, key) || url.search || req.headers.authorization !== undefined) {+ if ((!credentialMatches(given, key) && !cookieMatches(req)) || url.search || req.headers.authorization !== undefined) {return json(res, 403, refusalDocument(new Refused('VIEW_SIGN_IN_AUTH', 'open this view and send its session key in the x-pullboard-key header only')));}if (req.method !== 'POST') return json(res, 405, refusalDocument(new Refused('BAD_REQUEST', 'use a confirmed JSON POST to forget unreadable boards')));@@ -547,7 +589,7 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('b/** Run only the existing person-channel adapter, with per-view intent ownership and header authentication. */async function sharingRequest(req, res, url) {const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? ''));- if (given.length !== key.length || !timingSafeEqual(given, key) || url.search || req.headers.authorization !== undefined) {+ if ((!credentialMatches(given, key) && !cookieMatches(req)) || url.search || req.headers.authorization !== undefined) {return json(res, 403, refusalDocument(new Refused('VIEW_SIGN_IN_AUTH', 'open the view link and send its session key in the x-pullboard-key header only')));}try {@@ -632,8 +674,10 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('bif (projectRoot === undefined && url.pathname === '/api/v1/projects/forget-unreadable') return forgetUnreadableRequest(req, res, url);return apiHandler(req, res);}+ if (hosted) return json(res, 403, { error: 'open the printed view link for local pages; the hosted page uses the API' });const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? url.searchParams.get('k') ?? ''));- if (given.length !== key.length || !timingSafeEqual(given, key)) {+ const validKey = credentialMatches(given, key);+ if (!validKey && !cookieMatches(req)) {const destination = req.headers['sec-fetch-dest'];const browserPage = req.method === 'GET' && url.pathname === '/' && !url.searchParams.has('k') && req.headers['x-pullboard-key'] === undefined&& /(?:^|,)\s*text\/html(?:\s*;|\s*,|\s*$)/iu.test(String(req.headers.accept ?? ''))@@ -641,9 +685,16 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('bif (browserPage) return reply(res, 401, 'text/html; charset=utf-8', '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Open your board</title><h1>Open your board</h1><p>The board opens at <a href="' + HOSTED_ORIGIN + '">app.pullboard.dev</a>.</p></html>');return json(res, 403, { error: 'this view needs its own address and secret: open the link pullboard view printed' });}+ if (req.method === 'GET' && url.searchParams.has('k')) {+ url.searchParams.delete('k');+ return reply(res, 303, 'text/plain; charset=utf-8', '', {+ location: `http://${req.headers.host}${url.pathname}${url.search}`,+ ...(validKey ? { 'set-cookie': `${cookieName}=${session}; Path=/; HttpOnly; SameSite=Strict` } : {}),+ });+ }try {// The board, and the Roadmap at its own address (N38), are the one page.- if (req.method === 'GET' && (url.pathname === '/' || /^\/(?:[^/]+\/)?(?:home|items|shouts|spec|doctrine|activity|roadmap|settings)(?:\/[^/]+)?$/.test(url.pathname))) return reply(res, 200, 'text/html; charset=utf-8', cockpitPage(secret, { paths: true }));+ if (req.method === 'GET' && (url.pathname === '/' || /^\/(?:[^/]+\/)?(?:home|items|shouts|spec|doctrine|activity|roadmap|settings)(?:\/[^/]+)?$/.test(url.pathname))) return reply(res, 200, 'text/html; charset=utf-8', cockpitPage('', { paths: true, apiHeaders: {}, stylesheet: '/view.css' }));if (req.method === 'GET' && url.pathname === '/view.css') return reply(res, 200, 'text/css; charset=utf-8', VIEW_CSS);return json(res, 404, { error: 'no such page' });} catch (error) {diff --git a/test/cockpit/auth.test.js b/test/cockpit/auth.test.jsnew file mode 100644index 00000000..29f52f55--- /dev/null+++ b/test/cockpit/auth.test.js@@ -0,0 +1,169 @@+/**+ * The view's secret leaves the address bar (N39, N26): the printed link's key is traded for a+ * session cookie, and every later request is authorized by that cookie, over real HTTP.+ */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { request } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { serveView } from '../../src/serve.js';++/**+ * Send one GET to a running view on a connection of its own, following no redirect, so the test sees+ * each answer the browser would; `host` replaces the Host header to stand in for another site.+ *+ * @param {number} port+ * @param {string} path+ * @param {Record<string, string>} [headers]+ * @returns {Promise<{ status: number, headers: import('node:http').IncomingHttpHeaders, body: string }>}+ */+function get(port, path, headers = {}) {+ return new Promise((done, fail) => {+ const outbound = request({ host: '127.0.0.1', port, path, agent: false, headers: { connection: 'close', ...headers } }, (response) => {+ let body = '';+ response.setEncoding('utf8');+ response.on('data', (chunk) => { body += chunk; });+ response.on('end', () => done({ status: response.statusCode ?? 0, headers: response.headers, body }));+ });+ outbound.once('error', fail);+ outbound.setTimeout(10_000, () => outbound.destroy(new Error(`GET ${path.split('?')[0]} timed out`)));+ outbound.end();+ });+}++/**+ * Open a printed link's address, check it trades the key for one session cookie and lands on the same+ * address without the key, and return that cookie's name=value pair and where it landed.+ *+ * @param {number} port+ * @param {string} path+ * @param {string} key+ * @returns {Promise<{ pair: string, landed: URL }>}+ */+async function exchange(port, path, key) {+ const opened = await get(port, path);+ assert.equal(opened.status, 303, `${path.split('?')[0]}: the link with the key redirects`);+ const landed = new URL(opened.headers.location ?? '', `http://127.0.0.1:${port}`);+ assert.equal(landed.origin, `http://127.0.0.1:${port}`, 'the redirect stays on this view');+ assert.equal(landed.searchParams.has('k'), false, 'the redirect drops the key from the address');+ assert.ok(!landed.href.includes(key), 'the key appears nowhere in the new address');+ const cookies = opened.headers['set-cookie'] ?? [];+ assert.equal(cookies.length, 1, 'the exchange sets one cookie');+ const [pair, ...attributes] = cookies[0].split(';').map((part) => part.trim());+ const named = attributes.map((attribute) => attribute.toLowerCase());+ assert.ok(named.includes('httponly'), 'the cookie is HttpOnly, so no script on the page can read it');+ assert.ok(named.includes('samesite=strict'), 'the cookie is SameSite=Strict, so another site cannot send it');+ assert.ok(named.includes('path=/'), 'the cookie covers the whole view');+ assert.ok(!named.some((attribute) => attribute.startsWith('domain=')), 'the cookie is host-only');+ const [name, value] = [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)];+ assert.match(name, /^pullboard_view_[0-9a-f]{16,}$/u, "the cookie's name is the view's, with a session part");+ assert.ok(value.length >= 16, 'the cookie has a value');+ assert.ok(!value.includes(key) && !key.includes(value), 'the cookie is a session value, never the key itself');+ return { pair, landed };+}++test('[N39,N26] the view key becomes a cookie', async (t) => {+ const home = mkdtempSync(join(tmpdir(), 'pullboard-view-auth-'));+ const before = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = home;+ t.after(() => {+ if (before === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = before;+ rmSync(home, { recursive: true, force: true });+ });+ const open = new Set();+ /** Start a view session and close it after the test unless the test closes it first. */+ const start = async (port) => {+ const served = await serveView({ port });+ open.add(served);+ return { ...served, close: async () => { if (open.delete(served)) await served.close(); } };+ };+ t.after(() => Promise.all([...open].map((served) => served.close())));+ const view = await start(0);+ const link = new URL(view.url);+ const key = link.searchParams.get('k') ?? '';+ const { port } = view;+ assert.ok(key, 'the printed link carries the key');++ // Opening the printed link trades the key for the cookie and lands on the same address without it.+ const { pair, landed } = await exchange(port, link.pathname + link.search, key);+ assert.equal(landed.pathname + landed.search, '/', 'the printed link lands on the clean board address');+ const routed = await exchange(port, `/roadmap?q=launch&k=${encodeURIComponent(key)}`, key);+ assert.equal(routed.landed.pathname + routed.landed.search, '/roadmap?q=launch', 'any address keeps its path and other parameters');+ assert.equal(routed.pair, pair, 'one session, one cookie');++ // The clean address works with the cookie alone: the page, its stylesheet and its API.+ const page = await get(port, '/', { cookie: pair });+ assert.equal(page.status, 200, 'the clean address serves the page with the cookie alone');+ assert.match(String(page.headers['content-type']), /^text\/html/);+ assert.ok(!page.body.includes(key), 'the page itself holds no key');+ assert.match(page.body, /<link rel="stylesheet" href="\/view\.css">/, 'the page links its stylesheet without the key');+ assert.equal((await get(port, '/roadmap?q=launch', { cookie: pair })).status, 200, 'a routed clean address works too');+ assert.equal((await get(port, '/view.css', { cookie: `theme=dark; ${pair}` })).status, 200, 'the stylesheet loads by the cookie among others');+ const boards = await get(port, '/api/v1/boards', { cookie: pair });+ assert.equal(boards.status, 200, 'the page API accepts the cookie');+ assert.equal(JSON.parse(boards.body).version, 1);++ // Neither cookie nor key is refused, as is a cookie with the wrong value or name, or a doubled one.+ for (const headers of [{}, { cookie: `${pair.split('=')[0]}=not-this-session` }, { cookie: `${pair}; ${pair}` }, { cookie: `${pair}x` }, { cookie: `pullboard_view_${port}=${pair.split('=')[1]}` }]) {+ const label = JSON.stringify(Object.keys(headers).length ? 'a wrong cookie' : 'nothing');+ assert.equal((await get(port, '/', headers)).status, 403, `the page refuses ${label}`);+ assert.equal((await get(port, '/view.css', headers)).status, 403, `the stylesheet refuses ${label}`);+ assert.equal((await get(port, '/api/v1/boards', headers)).status, 401, `the API refuses ${label}`);+ }+ assert.equal((await get(port, '/?k=not-the-key')).status, 403, 'a wrong key in the address is refused');+ assert.equal((await get(port, '/?k=not-the-key')).headers['set-cookie'], undefined, 'and gets no cookie');++ // A foreign Host or Origin is refused even with the cookie, and a foreign Host gets no cookie for the key.+ const foreignHost = { host: `pullboard.example:${port}` };+ assert.equal((await get(port, '/', { ...foreignHost, cookie: pair })).status, 403, 'the page refuses another Host, cookie or not');+ assert.equal((await get(port, '/api/v1/boards', { ...foreignHost, cookie: pair })).status, 401, 'the API refuses another Host, cookie or not');+ const rebound = await get(port, link.pathname + link.search, foreignHost);+ assert.equal(rebound.status, 403, 'a rebound name cannot open the printed link');+ assert.equal(rebound.headers['set-cookie'], undefined, 'and gets no cookie from it');+ const foreignOrigin = { origin: 'http://pullboard.example', cookie: pair };+ assert.equal((await get(port, '/', foreignOrigin)).status, 403, 'the page refuses another Origin, cookie or not');+ assert.equal((await get(port, '/api/v1/boards', foreignOrigin)).status, 403, 'the API refuses another Origin, cookie or not');++ for (const path of ['/', '/api/v1/boards', '/api/v1/view-link']) {+ assert.equal((await get(port, path, { cookie: pair, 'sec-fetch-site': 'same-site' })).status >= 400, true, 'a same-site foreign-port request cannot borrow the cookie');+ assert.equal((await get(port, path, { cookie: pair, origin: 'https://app.pullboard.dev' })).status >= 400, true, 'the hosted origin still needs its explicit key header');+ }+ assert.equal((await get(port, '/api/v1/view-link', { cookie: pair })).status, 200, 'the local invitation uses the cookie too');++ // The key is not single-use: the printed link opens again, and scripts still send it as a header.+ const again = await exchange(port, link.pathname + link.search, key);+ assert.equal((await get(port, '/', { cookie: again.pair })).status, 200, 'opening the printed link again still works');+ assert.equal((await get(port, '/', { 'x-pullboard-key': key })).status, 200, 'the key header still opens the page for scripts');+ assert.equal((await get(port, '/api/v1/boards', { 'x-pullboard-key': key })).status, 200, 'and the API');++ // A second view on another port shares the browser's cookie jar for 127.0.0.1, and refuses the first's cookie.+ const second = await start(0);+ assert.notEqual(second.port, port);+ const secondLink = new URL(second.url);+ const own = await exchange(second.port, secondLink.pathname + secondLink.search, secondLink.searchParams.get('k') ?? '');+ assert.notEqual(own.pair.split('=')[0], pair.split('=')[0], 'each view session names its own cookie');+ assert.notEqual(own.pair.split('=')[1], pair.split('=')[1], 'and gives it its own value');+ const borrowed = `${own.pair.split('=')[0]}=${pair.split('=')[1]}`;+ for (const cookie of [pair, borrowed]) {+ assert.equal((await get(second.port, '/', { cookie })).status, 403, "another view's page refuses this view's cookie");+ assert.equal((await get(second.port, '/api/v1/boards', { cookie })).status, 401, "another view's API refuses this view's cookie");+ }+ assert.equal((await get(port, '/', { cookie: own.pair })).status, 403, "and this view refuses the other's");+ assert.equal((await get(port, '/', { cookie: `${own.pair}; ${pair}` })).status, 200, 'both cookies in one jar still open each view');+ assert.equal((await get(second.port, '/', { cookie: `${own.pair}; ${pair}` })).status, 200);++ // A later session on the same port gets a new cookie name and value, and refuses the old session's cookie.+ await view.close();+ const later = await start(port);+ assert.equal(later.port, port, 'the later session serves from the same port');+ const laterLink = new URL(later.url);+ const renewed = await exchange(port, laterLink.pathname + laterLink.search, laterLink.searchParams.get('k') ?? '');+ assert.notEqual(renewed.pair.split('=')[0], pair.split('=')[0], 'two sessions on one port name their cookies differently');+ assert.notEqual(renewed.pair.split('=')[1], pair.split('=')[1], 'and give them different values');+ assert.equal((await get(port, '/', { cookie: pair })).status, 403, "the later session's page refuses the earlier session's cookie");+ assert.equal((await get(port, '/api/v1/boards', { cookie: pair })).status, 401, "and so does its API");+ assert.equal((await get(port, '/', { cookie: `${pair}; ${renewed.pair}` })).status, 200, 'its own cookie opens it beside the stale one');+});