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(api): accept the view session cookie [A2,N39]
Corey Olson97ce1414c5d9
diff --git a/src/api.js b/src/api.jsindex 15d8dd01..2f8311bc 100644--- a/src/api.js+++ b/src/api.js@@ -723,14 +723,43 @@ async function createRequest(root, body, isMain) {}, isMain);}+/** Return one unambiguous value for a named request cookie, or null when absent or duplicated. */+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;+}++/** Compare two credential buffers without exposing their contents or comparing equal-length values ordinarily. */+function credentialMatches(candidate, expected) {+ return candidate.length === expected.length && timingSafeEqual(candidate, expected);+}+/** Share the local router with the person's view and other local transports; the standalone API explicitly denies person authority. */-export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, isMain, allowedOrigins = [], onStateBuild, personChannel = 'view', stateDetail = 'full' } = {}) {+export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, isMain, allowedOrigins = [], onStateBuild, personChannel = 'view', stateDetail = 'full', sessionCookie } = {}) {if (typeof getPort !== 'function') throw new TypeError('createLocalApiHandler needs a bound-port getter');if (typeof runCommand !== 'function') throw new TypeError('createLocalApiHandler needs the actual CLI entry point as runCommand');// A page that still reads each item's detail from the state keeps full items until it opts in.if (!['full', 'summary'].includes(stateDetail)) throw new TypeError('createLocalApiHandler stateDetail is full or summary');+ if (sessionCookie !== undefined && (!sessionCookie || typeof sessionCookie.name !== 'string'+ || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(sessionCookie.name)+ || typeof sessionCookie.value !== 'string' || !/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/u.test(sessionCookie.value))) {+ throw new TypeError('createLocalApiHandler sessionCookie needs a cookie name and value');+ }const codeIsMain = codeIsFromMain() && isMain !== false;const key = Buffer.from(secret);+ const cookieName = sessionCookie?.name;+ const cookieKey = sessionCookie === undefined ? null : Buffer.from(sessionCookie.value);const permittedOrigins = new Set(allowedOrigins);const stateCache = new Map();// The fingerprints of the summary states each board's clients were sent, least recently sent@@ -838,7 +867,11 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? (authorization.startsWith('Bearer ') ? authorization.slice(7) : url.searchParams.get('k') ?? '')));const bound = getPort();const ownHost = req.headers.host === ADDRESS + ':' + bound || req.headers.host === 'localhost:' + bound;- if (!ownHost || given.length !== key.length || !timingSafeEqual(given, key)) throw new Refused('AUTH_REQUIRED', 'this API needs its session secret and own host; use the address pullboard serve printed');+ const validKey = credentialMatches(given, key);+ const cookieValue = cookieKey ? requestCookie(req.headers.cookie, cookieName) : null;+ const givenCookie = Buffer.from(cookieValue ?? '');+ const validCookie = cookieKey !== null && cookieValue !== null && credentialMatches(givenCookie, cookieKey);+ if (!ownHost || (!validKey && !validCookie)) throw new Refused('AUTH_REQUIRED', 'this API needs its session secret and own host; use the address pullboard serve printed');if (req.headers.origin && req.headers.origin !== 'http://' + req.headers.host && !permittedOrigins.has(req.headers.origin)) throw new Refused('API_ORIGIN', 'use the API from its own origin');return { local: true };},diff --git a/test/api-http.test.js b/test/api-http.test.jsindex 149c856a..51d6dd28 100644--- a/test/api-http.test.js+++ b/test/api-http.test.js@@ -1150,6 +1150,90 @@ test('[A2, N26] one event stream serves many boards', async (t) => {assert.match(repeated.document.error.message, new RegExp(box.id));});+test('[A2,N39] the local API accepts the view session cookie', async (t) => {+ const box = fixture(t);+ const secret = randomUUID();+ const sessionCookie = {+ name: `pullboard_view_${randomUUID().replaceAll('-', '')}`,+ value: randomUUID(),+ };+ let bound;+ const handler = createLocalApiHandler({+ secret,+ getPort: () => bound,+ runCommand: main,+ projects: () => [{ root: box.root, name: 'Cookie fixture' }],+ personChannel: 'api',+ sessionCookie,+ });+ const server = createServer(handler);+ await new Promise((ready, fail) => {+ server.once('error', fail);+ server.listen(0, '127.0.0.1', () => { bound = server.address().port; ready(); });+ });+ t.after(() => new Promise((closed) => server.close(closed)));+ const origin = `http://127.0.0.1:${bound}`;+ const cookie = `${sessionCookie.name}=${sessionCookie.value}`;+ /** Send one real HTTP request to the private API handler. */+ const request = (path, headers = {}, init = {}) => fetchFresh(origin + path, {+ ...init,+ headers: { ...headers, ...(init.body === undefined ? {} : { 'content-type': 'application/json' }) },+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),+ });+ /** Decode the handler's versioned refusal and check its authentication result. */+ async function refused(response, status, code = 'AUTH_REQUIRED') {+ assert.equal(response.status, status);+ const document = await response.json();+ assert.equal(document.version, 1);+ assert.equal(document.error.code, code);+ }++ const cookieListing = await request('/api/v1/boards', { cookie });+ assert.equal(cookieListing.status, 200, 'the current view cookie authenticates the actual local API');+ const listing = await cookieListing.json();+ assert.equal(listing.version, 1);+ const board = listing.boards.find((entry) => resolve(entry.root) === resolve(box.root));+ assert.ok(board, 'the private Git fixture is listed through cookie authentication');+ const state = await request(`/api/v1/boards/${board.id}/state`, { cookie });+ assert.equal(state.status, 200, 'cookie-authenticated state reads the fixture SQLite board');++ await refused(await request('/api/v1/boards'), 401, 'AUTH_REQUIRED');+ await refused(await request('/api/v1/boards', { cookie: `${sessionCookie.name}=wrong-cookie-value` }), 401, 'AUTH_REQUIRED');+ await refused(await request('/api/v1/boards', { cookie: `${sessionCookie.name}=expired-session-value` }), 401, 'AUTH_REQUIRED');+ await refused(await request('/api/v1/boards', { cookie: `${cookie}; ${cookie}` }), 401, 'AUTH_REQUIRED');+ await refused(await request('/api/v1/boards', { cookie: `${sessionCookie.name}=wrong-cookie-value; ${cookie}` }), 401, 'AUTH_REQUIRED');+ await refused(await request('/api/v1/boards', { cookie: `${sessionCookie.name}; ${cookie}` }), 401, 'AUTH_REQUIRED');+ const staleName = `${sessionCookie.name}_old`;+ await refused(await request('/api/v1/boards', { cookie: `${staleName}=${sessionCookie.value}` }), 401, 'AUTH_REQUIRED');++ const foreignHost = await new Promise((done, reject) => {+ const outbound = httpRequest(origin + '/api/v1/boards', { headers: { host: 'foreign.invalid', cookie } }, (response) => {+ let text = '';+ response.on('data', (chunk) => { text += chunk; });+ response.on('end', () => done({ status: response.statusCode, document: JSON.parse(text) }));+ });+ outbound.once('error', reject);+ outbound.end();+ });+ assert.equal(foreignHost.status, 401, 'a valid cookie cannot cross the API host boundary');+ assert.equal(foreignHost.document.error.code, 'AUTH_REQUIRED');+ await refused(await request('/api/v1/boards', { cookie, origin: 'https://foreign.invalid' }), 403, 'API_ORIGIN');++ const keyHeader = await request('/api/v1/boards', { 'x-pullboard-key': secret });+ assert.equal(keyHeader.status, 200, 'the existing key header remains valid');+ const bearer = await request('/api/v1/boards', { authorization: `Bearer ${secret}` });+ assert.equal(bearer.status, 200, 'the existing Bearer key remains valid');+ const queryKey = await request(`/api/v1/boards?k=${encodeURIComponent(secret)}`);+ assert.equal(queryKey.status, 200, 'the existing query key remains valid');+ const badCookieWithKey = await request('/api/v1/boards', { cookie: `${sessionCookie.name}=wrong-cookie-value`, 'x-pullboard-key': secret });+ assert.equal(badCookieWithKey.status, 200, 'a bad cookie does not override a valid key');++ const personMove = await request(`/api/v1/boards/${board.id}/moves`, { cookie }, {+ method: 'POST', body: { verb: 'next', args: { as: 'person' } },+ });+ await refused(personMove, 400, 'B26_PERSON_CHANNEL');+});+test('[A2] local auth, origin, unknown board and malformed calls refuse without moving', async (t) => {const box = await httpBox(t);const unauthenticated = await fetchFresh(box.origin + '/api/v1/boards');