Skip to content

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.

feat(view): pullboard.dev opens the boards on this machine [N26,A2]

Corey Olson04c88008d9e9
diff --git a/src/cockpit.js b/src/cockpit.js
index 994cbf91..5b07bb90 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -36,12 +36,16 @@ function lifecycle() {
* The Roadmap tab has its own address (N38): /roadmap on a host that serves the page there too,
* which `paths` declares, and a #roadmap fragment anywhere else, such as a snapshot hosted under a
* folder, where a path the host does not serve would leave a reload with nothing.
+ * The hosted page at https://app.pullboard.dev passes hostedLocal (N26, #513): on the machine that runs pullboard
+ * view, the page reads that view straight, writable, and the relay transport is never loaded; on any other device it
+ * is the relay page as before when relaySession says the request has a relay session, and otherwise it says why it
+ * cannot read a board here and links signIn.
*
* @param {string} [key] - The session's secret.
- * @param {{snapshot?: boolean, readOnly?: boolean, requests?: boolean, transportModule?: string|null, apiBase?: string, apiHeaders?: Record<string, string>, stylesheet?: string, paths?: boolean}} [options] - Served connection and assets, optional person requests over a read-only transport, host routes, or a static page with event replay.
+ * @param {{snapshot?: boolean, readOnly?: boolean, requests?: boolean, transportModule?: string|null, apiBase?: string, apiHeaders?: Record<string, string>, stylesheet?: string, paths?: boolean, hostedLocal?: boolean, relaySession?: boolean, signIn?: string|null}} [options] - Served connection and assets, optional person requests over a read-only transport, host routes, a static page with event replay, or the hosted page that reads this machine's view first.
* @returns {string}
*/
-export function cockpitPage(key = '', { snapshot = false, readOnly = false, requests = false, transportModule = null, apiBase = '', apiHeaders = { 'x-pullboard-key': key }, stylesheet = null, paths = false } = {}) {
+export function cockpitPage(key = '', { snapshot = false, readOnly = false, requests = false, transportModule = null, apiBase = '', apiHeaders = { 'x-pullboard-key': key }, stylesheet = null, paths = false, hostedLocal = false, relaySession = false, signIn = null } = {}) {
// Derive the current CLI inventory for every served, relay or exported page.
const COMMAND_SOURCE = 'pullboard (?:' + commandPhrases().join('|') + ')(?![\\w-])(?: (?:--?[\\w-]+|\\d+|#\\d+|"[^"\\n]*"|[A-Z][A-Z0-9_]*|[\\w-]*[\\/.:@][^\\s"]*|[a-z]+-\\d+)(?![\\w-]))*';
@@ -49,6 +53,8 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
const connection = JSON.stringify(transportModule ? { base: '', headers: {} } : { base: apiBase.replace(/\/$/, ''), headers: apiHeaders }).replace(/</g, '\\u003c');
const moduleOption = JSON.stringify(transportModule).replace(/</g, '\\u003c');
const requestMode = Boolean(readOnly && requests && !snapshot && transportModule);
+ if (signIn !== null && (typeof signIn !== 'string' || !signIn.startsWith('/') || signIn.startsWith('//'))) throw new TypeError('signIn must be a path on the hosting site, or null');
+ const hostedOptions = JSON.stringify({ local: Boolean(hostedLocal) && !snapshot, relaySession: Boolean(relaySession), signIn }).replace(/</g, '\\u003c');
const css = stylesheet ?? (snapshot ? 'view.css' : transportModule ? '/view.css' : '/view.css?k=' + encodeURIComponent(key));
const cssAttribute = css.replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]);
return `<!doctype html>
@@ -87,6 +93,10 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
<div class="top-find"><input id="q" type="search" placeholder="Search" aria-label="Search items, Spec, Doctrine and shouts" autocomplete="off"><div class="find-results" id="find-results" role="listbox" aria-label="Search results" hidden></div></div>
</header>
<main>
+ <section class="card-panel" id="local-note" role="status" hidden>
+ <p id="local-note-text"></p>
+ <p id="local-note-links" hidden><a id="local-note-view" href="http://127.0.0.1:4890/local/view">Open the local view</a> <a id="local-note-sign-in" hidden>Sign in to see linked boards</a> <button class="ghost" id="local-note-retry" type="button">Try again</button></p>
+ </section>
<section class="card-panel first">
<h2>No boards yet</h2>
<p>Run <code>pullboard init</code> in a git repo, or ask an agent to. Its board shows up here by itself.</p>
@@ -166,12 +176,61 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
<div class="console" id="console" title="Click to close" hidden></div>
<script>
const snapshot = ${JSON.stringify(snapshot)};
-const readOnly = ${JSON.stringify(readOnly)};
-const requests = ${JSON.stringify(requestMode)};
-const transportModule = ${moduleOption};
+let readOnly = ${JSON.stringify(readOnly)};
+let requests = ${JSON.stringify(requestMode)};
+let transportModule = ${moduleOption};
const connection = ${connection};
let transport = null;
let transportLoadError = null;
+// The hosted page (N26, #513): at https://app.pullboard.dev, on the machine that runs pullboard view, the page reads
+// that view straight instead of the relay. The view hands it the session's secret by a round trip that ends back here
+// with the secret in the address's fragment, which no request carries; the page takes it out of the address before
+// anything else reads the address, and keeps it for this tab only. Every request then sends it in x-pullboard-key.
+const hosted = ${hostedOptions};
+const LOCAL_VIEW = 'http://127.0.0.1:4890';
+const LOCAL_TAB = 'pullboard.local.session';
+const LOCAL_TRIPS = 'pullboard.local.trips';
+let localSession = null;
+let localProblem = null;
+let localConfirmed = false;
+/** Read, keep or forget a value for this tab only; a browser that refuses keeps nothing, and the page goes on. */
+function tabValue(name, value) {
+ try {
+ if (value === undefined) return sessionStorage.getItem(name);
+ if (value === null) sessionStorage.removeItem(name);
+ else sessionStorage.setItem(name, value);
+ } catch { return null; }
+ return value;
+}
+/** Whether a value is a local session this page may use: version 1, a loopback origin with its port, and a secret. */
+function validLocalSession(value) {
+ if (!value || value.version !== 1 || typeof value.key !== 'string' || !/^[\\x21-\\x7e]{1,256}$/.test(value.key) || typeof value.origin !== 'string') return false;
+ try {
+ const address = new URL(value.origin);
+ return address.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(address.hostname) && address.port !== '' && address.origin === value.origin;
+ } catch { return false; }
+}
+// A relay pairing link carries its own fragment; that load stays the relay's, as before.
+const relayPairing = hosted.local && ['board', 'key', 'device'].some((name) => new URLSearchParams(location.hash.slice(1)).has(name));
+if (hosted.local && !relayPairing) {
+ const fragment = new URLSearchParams(location.hash.slice(1));
+ const returned = fragment.get('pullboard-local');
+ if (returned !== null) {
+ fragment.delete('pullboard-local');
+ const rest = fragment.toString();
+ let removed = true;
+ try { history.replaceState(history.state, '', location.pathname + location.search + (rest ? '#' + rest : '')); }
+ catch { removed = false; }
+ let returnedSession = null;
+ try { returnedSession = JSON.parse(returned); } catch { /* refused below */ }
+ if (!removed) localProblem = 'This browser kept the connection secret in the address, so this page will not use it. Close this tab, then open the local view.';
+ else if (validLocalSession(returnedSession)) localSession = { version: 1, origin: returnedSession.origin, key: returnedSession.key };
+ else localProblem = 'The local view sent back a connection this page cannot read. Try again, or open the local view.';
+ } else {
+ try { const kept = JSON.parse(tabValue(LOCAL_TAB) ?? 'null'); if (validLocalSession(kept)) localSession = kept; } catch { /* nothing kept for this tab */ }
+ }
+ tabValue(LOCAL_TAB, localSession ? JSON.stringify(localSession) : null);
+}
const snapshotReplay = { final: null, events: [], index: 0, playing: false, timer: null };
const keep = (name, value) => { name = snapshot ? 'snapshot.' + name : name; try { if (value === undefined) return localStorage.getItem(name); localStorage.setItem(name, value); } catch { return null; } return value; };
// Whether the host serves this page at /roadmap as well as at /, so the Roadmap's address is a path;
@@ -214,6 +273,83 @@ let deferredClickRender = false;
const addressedShouts = new Map();
const $ = (id) => document.getElementById(id);
+/** Say in one line what the page is doing about this machine's view, or why it cannot read it, with the ways on. */
+function localNote(text, ways = false) {
+ $('local-note').hidden = !text;
+ $('local-note-text').textContent = text || '';
+ $('local-note-links').hidden = !ways;
+ $('local-note-view').href = (localSession?.origin || LOCAL_VIEW) + '/local/view';
+ $('local-note-sign-in').hidden = !hosted.signIn || hosted.relaySession;
+ if (hosted.signIn) $('local-note-sign-in').href = hosted.signIn;
+}
+
+/** Send this tab on the round trip to the local view, which sends it straight back here; two tries in a row at most. */
+function localTrip(base) {
+ const trips = Number(tabValue(LOCAL_TRIPS) || 0);
+ if (trips >= 2) {
+ tabValue(LOCAL_TRIPS, null);
+ localNote('The local view did not give this page a session it accepts. Open the local view, or try again.', true);
+ return false;
+ }
+ tabValue(LOCAL_TRIPS, String(trips + 1));
+ location.assign(base + '/local/connect');
+ return true;
+}
+
+/** The local view refused this tab's secret, as after a restart with a new one: go round again for it, unasked. */
+function localExpired() {
+ const base = localSession.origin;
+ localSession = null;
+ localConfirmed = false;
+ tabValue(LOCAL_TAB, null);
+ localTrip(base);
+}
+
+/**
+ * Reach this machine's view: say first why the browser may ask about local network access, then read the view's
+ * public protocol, which holds no secret and no board, and take the session the round trip brought back. It is
+ * 'local' when the page now reads the local view, 'away' when the browser is on the round trip, and 'unreachable'
+ * when the page cannot read it, with what it knows of why on the page.
+ */
+async function connectLocal() {
+ const base = localSession?.origin || LOCAL_VIEW;
+ let permission = null;
+ for (const name of ['loopback-network', 'local-network-access']) {
+ try { permission = (await navigator.permissions.query({ name })).state; break; } catch { /* this browser has no such permission */ }
+ }
+ if (permission === 'denied') {
+ localNote('This browser has refused this page access to apps on this device, so it cannot read the board running here. Allow it in the site settings for app.pullboard.dev, or open the local view.', true);
+ return 'unreachable';
+ }
+ if (permission !== 'granted') {
+ localNote('Your browser may ask to let this page reach apps on this device: allow it, and the page reads the board pullboard view runs here, which never leaves this machine.');
+ // The line is on screen before the request that can raise the browser's prompt.
+ await new Promise((painted) => requestAnimationFrame(() => requestAnimationFrame(painted)));
+ }
+ let reply;
+ try { reply = await fetch(base + '/local/protocol', { signal: AbortSignal.timeout(3000), credentials: 'omit', redirect: 'error' }); }
+ catch {
+ localNote('This page cannot reach a local view: pullboard view may not be running, this browser may have refused it access to this device, or the installed Pullboard may be older than this page. Start pullboard view and try again, or open the link it printed.', true);
+ return 'unreachable';
+ }
+ let protocol = null;
+ try { protocol = await reply.json(); } catch { /* not this protocol */ }
+ if (!reply.ok || protocol?.version !== 1 || protocol?.apiVersion !== 1 || protocol?.hostedOrigin !== location.origin) {
+ localNote('The installed Pullboard does not match this page. Open the link pullboard view printed, or update Pullboard.', true);
+ return 'unreachable';
+ }
+ if (!localSession) return localTrip(base) ? 'away' : 'unreachable';
+ connection.base = localSession.origin;
+ connection.headers = { 'x-pullboard-key': localSession.key };
+ readOnly = false;
+ requests = false;
+ transportModule = null;
+ transport = null;
+ document.body.classList.remove('read-only', 'requests');
+ localNote(null);
+ return 'local';
+}
+
/** Mark primary pointer targets whose click would be lost if a refresh replaces them. */
function holdClickPointer(event) {
if (!event.isPrimary || event.button !== 0 || !(event.target instanceof Element && event.target.closest('#pipeline .pipeline-item, #spec-detail [data-row-decision="decline"], #spec-decline-submit'))) return;
@@ -761,6 +897,10 @@ async function api(path, body) {
path = snapshot ? path.split('?')[0].slice(1) + '.json' : connection.base + path;
const res = await fetch(path, { method: body ? 'POST' : 'GET', headers: snapshot ? {} : { ...connection.headers, ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined });
const json = await res.json();
+ if (localSession && connection.base === localSession.origin && !snapshot) {
+ if (res.status === 401 || res.status === 403) localExpired();
+ else if (res.ok && !localConfirmed) { localConfirmed = true; tabValue(LOCAL_TRIPS, null); }
+ }
if (!res.ok) {
const refusal = json.error;
const message = refusal && typeof refusal === 'object' ? '[' + refusal.code + '] ' + refusal.message : refusal || res.status;
@@ -2785,8 +2925,22 @@ if (snapshot) {
if (snapshotReplay.playing) { clearTimeout(snapshotReplay.timer); snapshotReplay.timer = setTimeout(advanceReplay, 1000 / Number($('replay-speed').value)); }
});
}
+if (hosted.local) $('local-note-retry').addEventListener('click', () => {
+ localProblem = null;
+ tabValue(LOCAL_TRIPS, null);
+ connectLocal().then((local) => local === 'local' ? refresh() : null).catch((error) => localNote(error.message, true));
+});
/** Load an explicitly configured transport before the first read; its updates refresh this page. */
async function startPage() {
+ // The hosted page reads this machine's view when it can. When it cannot, it is the relay page as before, for a
+ // person signed in to the relay; anyone else sees why, and the ways on.
+ if (hosted.local && !relayPairing) {
+ let local = 'unreachable';
+ if (localProblem) localNote(localProblem, true);
+ else local = await connectLocal();
+ if (local === 'away') return;
+ if (local === 'unreachable' && !hosted.relaySession) return;
+ }
if (transportModule) {
try {
const module = await import(transportModule);
diff --git a/src/serve.js b/src/serve.js
index eab348b0..d6abfed8 100644
--- a/src/serve.js
+++ b/src/serve.js
@@ -4,8 +4,10 @@
* refreshing itself. Reads and actions use the shared local API v1 handler (A3); actions run the
* 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 the session's secret and its
- * own Host, so another site in the browser cannot reach it. It opens no outbound connection (P5).
+ * 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,
+ * the hosted page at https://app.pullboard.dev, which gets the secret by a round trip that only ever returns there.
+ * It opens no outbound connection (P5).
*/
import { spawnSync } from 'node:child_process';
import { randomBytes, timingSafeEqual } from 'node:crypto';
@@ -30,6 +32,13 @@ import { loadSpec } from './spec.js';
/** The page's styles (N26), read once: the page links them, so it needs no inline style. */
const VIEW_CSS = readFileSync(new URL('./view.css', import.meta.url), 'utf8');
export const LOOPBACK = '127.0.0.1';
+/**
+ * The hosted page's origin (N26, A2): the one origin besides the view's own page that may call the view, and the only
+ * place the view's round trip ever sends its secret.
+ */
+export const HOSTED_ORIGIN = 'https://app.pullboard.dev';
+/** The request headers the hosted page may send across origins: the secret, a JSON body's type, and a stream's cursor. */
+const HOSTED_HEADERS = ['x-pullboard-key', 'content-type', 'last-event-id'];
/**
* Replace only board-recorded filesystem fields in exported API documents. Event details are
@@ -352,7 +361,7 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('b
// initialize, and use the real CLI entry point without adding a second move implementation.
const { createLocalApiHandler } = await import('./api.js');
const { main } = await import('./cli.js');
- const apiHandler = createLocalApiHandler({ secret, getPort: () => bound, runCommand: main });
+ const apiHandler = createLocalApiHandler({ secret, getPort: () => bound, runCommand: main, allowedOrigins: [HOSTED_ORIGIN] });
const reply = (res, code, type, body) => {
res.writeHead(code, {
'content-type': type,
@@ -364,6 +373,11 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('b
res.end(body);
};
const json = (res, code, value) => reply(res, code, 'application/json; charset=utf-8', JSON.stringify(value));
+ // A page that only sends the browser on, and only when it is the top page: framed, it never runs and never shows.
+ const onward = (res, destination) => {
+ res.setHeader('x-frame-options', 'DENY');
+ return reply(res, 200, 'text/html; charset=utf-8', '<!doctype html><meta charset="utf-8"><title>Opening Pullboard</title><script>if (window.top === window.self) location.replace(' + JSON.stringify(destination).replace(/</g, '\\u003c') + ');</script>');
+ };
const server = createServer(async (req, res) => {
// A request line no URL parser accepts cannot carry the secret, so it gets the same 403, and it
// must not be able to stop the server.
@@ -373,10 +387,53 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('b
} catch {
return json(res, 403, { error: 'this view needs its own address and secret: open the link pullboard view printed' });
}
- if (url.pathname.startsWith('/api/')) return apiHandler(req, res);
- const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? url.searchParams.get('k') ?? ''));
+ // Only the view's own address reaches it: a site that points a name of its own at 127.0.0.1 sends that name. The
+ // API refuses another Host in its own words.
const isOwnHost = req.headers.host === `${LOOPBACK}:${bound}` || req.headers.host === `localhost:${bound}`;
- if (!isOwnHost || given.length !== key.length || !timingSafeEqual(given, key)) return json(res, 403, { error: 'this view needs its own address and secret: open the link pullboard view printed' });
+ if (!isOwnHost) {
+ if (url.pathname.startsWith('/api/') && req.method !== 'OPTIONS') return apiHandler(req, res);
+ return json(res, 403, { error: 'this view answers only at 127.0.0.1 or localhost on its own port: open the link pullboard view printed' });
+ }
+ // A browser names the page a request comes from; the view answers its own page and the hosted one, nothing else.
+ const origin = req.headers.origin;
+ const hosted = origin === HOSTED_ORIGIN;
+ if (origin !== undefined && !hosted && origin !== `http://${LOOPBACK}:${bound}` && origin !== `http://localhost:${bound}`) {
+ return json(res, 403, { error: 'this view answers its own page and https://app.pullboard.dev only' });
+ }
+ res.setHeader('vary', 'Origin');
+ if (hosted) res.setHeader('access-control-allow-origin', HOSTED_ORIGIN);
+ if (req.method === 'OPTIONS') {
+ const asked = String(req.headers['access-control-request-headers'] ?? '').toLowerCase().split(',').map((name) => name.trim()).filter(Boolean);
+ const route = url.pathname.startsWith('/api/') || url.pathname === '/local/protocol';
+ if (!hosted || !route || !['GET', 'POST'].includes(req.headers['access-control-request-method']) || asked.some((name) => !HOSTED_HEADERS.includes(name))) {
+ return json(res, 403, { error: 'from https://app.pullboard.dev, ask for a GET or a JSON POST to /api/, sending only x-pullboard-key, content-type and last-event-id' });
+ }
+ res.setHeader('access-control-allow-methods', 'GET, POST');
+ res.setHeader('access-control-allow-headers', HOSTED_HEADERS.join(', '));
+ res.setHeader('access-control-allow-private-network', 'true');
+ res.setHeader('access-control-max-age', '600');
+ return reply(res, 204, 'text/plain; charset=utf-8', '');
+ }
+ // The round trip (N26): any page may send the browser here, and the secret goes back to the hosted page only, in
+ // the address's fragment, which no request carries. /local/view opens this view itself, as its printed link does.
+ // Each is a page of its own: a script's read or a frame gets nothing.
+ if (req.method === 'GET' && (url.pathname === '/local/connect' || url.pathname === '/local/view')) {
+ const destination = req.headers['sec-fetch-dest'];
+ if (origin !== undefined || (destination !== undefined && destination !== 'document')) return json(res, 403, { error: 'open this address as a page of its own, never from a script or inside a frame' });
+ if (url.pathname === '/local/view') return onward(res, `http://${LOOPBACK}:${bound}/?k=${secret}`);
+ return onward(res, HOSTED_ORIGIN + '/#' + new URLSearchParams({ 'pullboard-local': JSON.stringify({ version: 1, origin: `http://${LOOPBACK}:${bound}`, key: secret }) }));
+ }
+ // What the hosted page needs to know this view can take it: no secret, and no board data.
+ if (req.method === 'GET' && url.pathname === '/local/protocol') return json(res, 200, { version: 1, apiVersion: 1, hostedOrigin: HOSTED_ORIGIN, connect: '/local/connect', view: '/local/view' });
+ if (url.pathname.startsWith('/api/')) {
+ // The hosted page sends the secret in its header only, never in an address a history or a log could keep.
+ if (hosted && (url.searchParams.has('k') || req.headers.authorization !== undefined || req.headers['x-pullboard-key'] === undefined)) {
+ return json(res, 403, { error: 'from https://app.pullboard.dev, send the session secret in the x-pullboard-key header only' });
+ }
+ return apiHandler(req, res);
+ }
+ const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? url.searchParams.get('k') ?? ''));
+ if (given.length !== key.length || !timingSafeEqual(given, key)) return json(res, 403, { error: 'this view needs its own address and secret: open the link pullboard view printed' });
try {
// The board, and the Roadmap at its own address (N38), are the one page.
if (req.method === 'GET' && (url.pathname === '/' || /^\/(?:[^/]+\/)?(?:items|shouts|spec|doctrine|activity|roadmap)(?:\/[^/]+)?$/.test(url.pathname))) return reply(res, 200, 'text/html; charset=utf-8', cockpitPage(secret, { paths: true }));
diff --git a/test/cockpit/local-origin.test.js b/test/cockpit/local-origin.test.js
new file mode 100644
index 00000000..58b3c33e
--- /dev/null
+++ b/test/cockpit/local-origin.test.js
@@ -0,0 +1,320 @@
+/** The hosted page reads this machine's view straight, and the view answers only its own page and that one [N26,A2]. */
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { createServer, request } from 'node:http';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { cockpitPage } from '../../src/cockpit.js';
+import { takeDefaultViewPort } from '../view-port-fixture.js';
+import { BIN, machine, project, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, styleOf } from './fixture.js';
+
+const HOSTED = 'https://app.pullboard.dev';
+const LOCAL = 'http://127.0.0.1:4890';
+
+/** Start the real view on a named port, as pullboard view does, and wait until it answers its printed link. */
+async function viewAt(box, port) {
+ const child = spawn(process.execPath, [BIN, 'view', '--no-open', '--port', String(port)], { cwd: box.dir, env: { ...box.env, PULLBOARD_VIEW_FOREGROUND: '1' } });
+ const stop = () => new Promise((done) => {
+ if (child.exitCode !== null || child.signalCode !== null) return done();
+ child.once('exit', done);
+ child.kill('SIGTERM');
+ });
+ try {
+ const link = await new Promise((found, fail) => {
+ let out = '';
+ child.stdout.on('data', (chunk) => {
+ out += chunk;
+ const match = /Pullboard view: (http:\/\/127\.0\.0\.1:\d+\/\?k=\S+)/.exec(out);
+ if (match) found(new URL(match[1]));
+ });
+ child.once('exit', (code) => fail(new Error(`view exited ${code}: ${out}`)));
+ });
+ return { link, key: link.searchParams.get('k'), base: link.origin, stop };
+ } catch (error) {
+ await stop();
+ throw error;
+ }
+}
+
+/** One plain HTTP request to the view, with exactly these headers, following nothing. */
+function call(view, path, { method = 'GET', headers = {}, body = '' } = {}) {
+ return new Promise((done, fail) => {
+ const outgoing = request(new URL(path, view.base), { method, headers, agent: false }, (res) => {
+ const chunks = [];
+ res.on('data', (chunk) => chunks.push(chunk));
+ res.on('end', () => done({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks).toString('utf8') }));
+ });
+ outgoing.on('error', fail);
+ outgoing.end(body);
+ });
+}
+
+/** Where a round-trip page sends the browser: the one address its script replaces the page with. */
+function onwardOf(page) {
+ const literal = /location\.replace\(("(?:\\.|[^"\\])*")\)/.exec(page)?.[1];
+ assert.ok(literal, 'the page sends the browser to one address');
+ return new URL(JSON.parse(literal));
+}
+
+/**
+ * Stand in for the hosted page at its real origin: Chrome answers every request for https://app.pullboard.dev with the
+ * cockpit the relay would serve there and the view's styles, and nothing else is touched, so the requests to the
+ * local view meet Chrome's own cross-origin rules.
+ */
+async function hostedStandIn(chrome, pages, styles) {
+ const failures = [];
+ const tasks = [];
+ const listener = ({ data }) => {
+ const message = JSON.parse(String(data));
+ if (message.method !== 'Fetch.requestPaused') return;
+ tasks.push((async () => {
+ const { requestId, resourceType, request: asked } = message.params;
+ const document = resourceType === 'Document';
+ const page = new URL(asked.url).search === '?relay' ? pages.relay : pages.anonymous;
+ await chrome.send('Fetch.fulfillRequest', {
+ requestId, responseCode: 200,
+ responseHeaders: [
+ { name: 'Content-Type', value: document ? 'text/html; charset=utf-8' : 'text/css; charset=utf-8' },
+ { name: 'Cache-Control', value: 'no-store' },
+ // The connections #533's relay page allows: its own origin and the local view's default address.
+ ...(document ? [{ name: 'Content-Security-Policy', value: `connect-src 'self' ${LOCAL} http://localhost:4890; frame-ancestors 'none'` }] : []),
+ ],
+ body: Buffer.from(document ? page : styles).toString('base64'),
+ });
+ })().catch((error) => failures.push(error.message)));
+ };
+ chrome.socket.addEventListener('message', listener);
+ await chrome.send('Fetch.enable', { patterns: [{ urlPattern: HOSTED + '/*', requestStage: 'Request' }] });
+ return async () => {
+ chrome.socket.removeEventListener('message', listener);
+ try { await Promise.all(tasks); } finally { await chrome.send('Fetch.disable'); }
+ assert.deepEqual(failures, [], 'the stand-in hosted page was served');
+ };
+}
+
+test('a pullboard.dev page reads the local board [N26,A2]', { timeout: 120_000 }, async () => { // budget: hang ceiling for the default-port lease, two real round trips in Chrome and a view restart.
+ const executable = chromeExecutable();
+ assert.ok(executable, 'the hosted page check needs real Chrome');
+ const box = machine();
+ const board = project(box, 'hosted-local');
+ box.run(board.repo, 'add', 'web', 'A board that stays on this machine', '--specs', 'G1');
+ const lease = await takeDefaultViewPort(box.dir, { agent: 'local-origin-' + process.pid });
+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-local-origin-'));
+ let view, chrome, stopStandIn;
+ try {
+ view = await viewAt(box, 4890);
+ chrome = await openSnapshotChrome(executable, 'about:blank', profile);
+ // Each fetch the hosted page makes, with what the page showed and where its address stood as it made it.
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => {
+ if (location.origin !== ${JSON.stringify(HOSTED)}) return;
+ const nativeFetch = window.fetch.bind(window);
+ const log = window.__localFetches = [];
+ window.fetch = (input, init) => {
+ const note = document.getElementById('local-note');
+ log.push({ url: String(typeof input === 'string' ? input : input.url), address: location.href, note: note ? !note.hidden : false, text: document.getElementById('local-note-text')?.textContent ?? '' });
+ return nativeFetch(input, init);
+ };
+ })()` });
+ const relayPage = (relaySession) => cockpitPage('', { readOnly: true, requests: true, transportModule: '/relay/client.js', apiHeaders: {}, stylesheet: '/view.css', hostedLocal: true, relaySession, signIn: '/auth/github/start' });
+ stopStandIn = await hostedStandIn(chrome, { anonymous: relayPage(false), relay: relayPage(true) }, await styleOf(view));
+ const trips = () => chrome.requests.filter((entry) => entry.url === LOCAL + '/local/connect').length;
+ const relayModule = () => chrome.requests.filter((entry) => entry.url === HOSTED + '/relay/client.js').length;
+ /** Wait until the page has asked for the relay module this many times in all. */
+ const relayAsked = async (times) => {
+ for (const deadline = Date.now() + 10_000; relayModule() < times && Date.now() < deadline;) await new Promise((later) => setTimeout(later, 50)); // budget: hang ceiling for the relay module request.
+ assert.equal(relayModule(), times, 'the page loads the relay module');
+ };
+ const localFetches = 'JSON.stringify((window.__localFetches || []).filter((entry) => entry.url.startsWith(' + JSON.stringify(LOCAL) + ')))';
+
+ // With nothing on this machine's port, the page says why and links the local view; a person with no relay session
+ // gets the sign-in link and the relay module is never loaded, while one with a session gets the relay page. The
+ // browser has not been allowed to reach this device yet, so the page says why it may ask before it first asks.
+ await view.stop();
+ await chrome.send('Page.navigate', { url: HOSTED + '/' });
+ await chrome.waitFor("location.search === '' && /cannot reach a local view/.test(document.querySelector('#local-note-text')?.textContent)", 20_000); // budget: hang ceiling for one refused loopback request.
+ const asked = JSON.parse(await chrome.stable(localFetches));
+ assert.equal(asked[0]?.url, LOCAL + '/local/protocol', 'the page first reads the local view\'s public protocol');
+ assert.ok(asked[0].note && /may ask to let this page reach apps on this device/.test(asked[0].text), `the line saying why the browser may ask is on screen before that request: ${JSON.stringify(asked[0])}`);
+ const away = JSON.parse(await chrome.stable("JSON.stringify({ links: !document.querySelector('#local-note-links').hidden, view: document.querySelector('#local-note-view').href, signIn: document.querySelector('#local-note-sign-in').hidden ? null : document.querySelector('#local-note-sign-in').getAttribute('href') })"));
+ assert.deepEqual(away, { links: true, view: LOCAL + '/local/view', signIn: '/auth/github/start' }, 'an unreachable view is named, with the local view and sign-in linked');
+ assert.equal(relayModule(), 0, 'without a relay session the relay module is never loaded');
+ await chrome.send('Page.navigate', { url: HOSTED + '/?relay' });
+ await chrome.waitFor("location.search === '?relay' && !document.querySelector('#local-note-links').hidden", 20_000); // budget: hang ceiling for one refused loopback request.
+ // A browser that has since refused this page the access is named as the reason, as it is the one the page knows.
+ const second = JSON.parse(await chrome.stable(`(async () => JSON.stringify({ text: document.querySelector('#local-note-text').textContent, permission: await navigator.permissions.query({ name: 'loopback-network' }).then((p) => p.state, () => null) }))()`));
+ assert.match(second.text, second.permission === 'denied' ? /has refused this page access to apps on this device/ : /cannot reach a local view/, `the page names what it knows: ${JSON.stringify(second)}`);
+ await relayAsked(1);
+ assert.equal(await chrome.stable("document.querySelector('#local-note-sign-in').hidden"), true, 'a person with a relay session is not asked to sign in');
+ // A relay pairing link stays the relay's: the page does not look for this machine on that load.
+ await chrome.send('Page.navigate', { url: HOSTED + '/#board=b1&key=k1' });
+ await relayAsked(2);
+ assert.deepEqual(JSON.parse(await chrome.stable(localFetches)), [], 'a pairing load makes no request to the local view');
+ // A person who allowed this page to reach this device. One grant refuses every permission it does not name, and
+ // the names differ between Chrome versions, so the widest set this Chrome knows is granted at once.
+ for (const permissions of [['loopbackNetwork', 'localNetwork', 'localNetworkAccess'], ['localNetworkAccess']]) {
+ try { await chrome.send('Browser.grantPermissions', { origin: HOSTED, permissions }); break; } catch { /* a name this Chrome does not have */ }
+ }
+ // A view that speaks another protocol is named as not matching this page.
+ const other = createServer((req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': HOSTED });
+ res.end(JSON.stringify({ version: 2, apiVersion: 2, hostedOrigin: HOSTED }));
+ });
+ await new Promise((ready) => other.listen(4890, '127.0.0.1', ready));
+ try {
+ await chrome.send('Page.navigate', { url: HOSTED + '/?other' });
+ await chrome.waitFor("location.search === '?other' && /does not match this page/.test(document.querySelector('#local-note-text')?.textContent)", 20_000); // budget: hang ceiling for one loopback request.
+ } finally { await new Promise((closed) => { other.close(closed); other.closeAllConnections(); }); }
+ assert.equal(trips(), 0, 'no round trip starts toward a view the page cannot use');
+
+ view = await viewAt(box, 4890);
+ await chrome.send('Page.navigate', { url: HOSTED + '/' });
+ await chrome.waitFor("location.origin === 'https://app.pullboard.dev' && document.querySelector('#chain')?.textContent.includes('A board that stays on this machine')", 30_000); // budget: hang ceiling for the discovery, one top-level round trip and the first board read.
+ const shown = JSON.parse(await chrome.stable(`JSON.stringify({ address: location.href, base: connection.base, readOnly, transportModule, kept: sessionStorage.getItem('pullboard.local.session'), lasting: Object.keys(localStorage).map((name) => localStorage.getItem(name)).join(' '), log: window.__localFetches })`));
+ assert.ok(!shown.address.includes('pullboard-local') && !shown.address.includes(view.key), 'the secret is gone from the address bar');
+ assert.equal(shown.base, LOCAL, 'the page reads the local view at its default address');
+ assert.equal(shown.readOnly, false, 'the local board is not read-only');
+ assert.equal(shown.transportModule, null, 'the relay transport is never loaded');
+ assert.deepEqual(JSON.parse(shown.kept), { version: 1, origin: LOCAL, key: view.key }, 'the session is kept for this tab');
+ assert.ok(!shown.lasting.includes(view.key), 'nothing lasting holds the secret');
+ const local = shown.log.filter((entry) => entry.url.startsWith(LOCAL));
+ assert.equal(local[0]?.url, LOCAL + '/local/protocol', 'the page first reads the local view\'s public protocol');
+ assert.ok(local.every((entry) => !entry.address.includes('pullboard-local')), 'no request is made while the secret is in the address');
+ assert.ok(local.some((entry) => entry.url.startsWith(LOCAL + '/api/')), 'the page reads the board through the view\'s API');
+ assert.equal(trips(), 1, 'the page itself started one top-level round trip');
+ const api = chrome.requests.filter((entry) => entry.url.startsWith(LOCAL + '/api/') && entry.method !== 'OPTIONS');
+ assert.ok(api.length > 0 && api.every((entry) => Object.entries(entry.headers).some(([name, value]) => name.toLowerCase() === 'x-pullboard-key' && value === view.key)), 'every API request carries the secret in x-pullboard-key');
+ assert.ok(chrome.requests.every((entry) => !new URL(entry.url).search.includes(view.key)), 'no request carries the secret in its query');
+
+ // The view restarts with a new secret: the page goes round again by itself.
+ const before = view.key;
+ await view.stop();
+ view = await viewAt(box, 4890);
+ assert.notEqual(view.key, before, 'the restarted view has a new secret');
+ await chrome.waitFor(`connection.headers['x-pullboard-key'] === ${JSON.stringify(view.key)} && document.querySelector('#chain')?.textContent.includes('A board that stays on this machine')`, 45_000); // budget: hang ceiling for the next refresh to meet the refusal, a second round trip and a read.
+ assert.equal(trips(), 2, 'the page repeated the round trip without the person');
+ assert.ok(!(await chrome.stable('location.href')).includes(view.key), 'the new secret is gone from the address bar too');
+ assert.ok(chrome.requests.every((entry) => !new URL(entry.url).search.includes(view.key) && !new URL(entry.url).search.includes(before)), 'neither secret ever rode in a query');
+ assert.deepEqual(chrome.exceptions, [], 'Chrome reports no uncaught exceptions');
+ } finally {
+ try { if (stopStandIn) await stopStandIn(); }
+ finally {
+ try { if (chrome) await closeSnapshotChrome(chrome); }
+ finally {
+ try { if (view) await view.stop(); }
+ finally { rmSync(profile, { recursive: true, force: true }); await lease.release(); }
+ }
+ }
+ }
+});
+
+test('a foreign origin or wrong Host is refused by the local view [N26,A2]', { timeout: 60_000 }, async () => { // budget: hang ceiling for one real view and a few local requests.
+ const box = machine();
+ project(box, 'local-origin-refusals');
+ const view = await startView(box);
+ try {
+ const port = view.link.port;
+ const key = { 'x-pullboard-key': view.key };
+ // Another site, even holding the secret, gets a plain refusal and no permission to read it.
+ for (const path of ['/api/v1/boards', '/local/protocol', '/local/connect', '/?k=' + view.key]) {
+ const foreign = await call(view, path, { headers: { ...key, origin: 'https://foreign.example' } });
+ assert.equal(foreign.status, 403, `a foreign origin is refused at ${path.replace(view.key, '<key>')}`);
+ assert.equal(foreign.headers['access-control-allow-origin'], undefined, 'and is not allowed to read the answer');
+ assert.equal(JSON.parse(foreign.body).error, 'this view answers its own page and https://app.pullboard.dev only');
+ assert.ok(!foreign.body.includes(view.key));
+ }
+ const foreignWrite = await call(view, '/api/v1/boards', { method: 'POST', headers: { ...key, origin: 'https://foreign.example', 'content-type': 'application/json' }, body: '{}' });
+ assert.equal(foreignWrite.status, 403, 'a foreign origin cannot write');
+ const foreignPreflight = await call(view, '/api/v1/boards', { method: 'OPTIONS', headers: { origin: 'https://foreign.example', 'access-control-request-method': 'GET', 'access-control-request-headers': 'x-pullboard-key' } });
+ assert.equal(foreignPreflight.status, 403, 'a foreign preflight is refused');
+ assert.equal(foreignPreflight.headers['access-control-allow-private-network'], undefined);
+ // A name of another site pointed at 127.0.0.1, as DNS rebinding sends it, reaches nothing.
+ for (const path of ['/local/protocol', '/local/connect', '/?k=' + view.key]) {
+ const rebound = await call(view, path, { headers: { ...key, host: 'foreign.example:' + port } });
+ assert.equal(rebound.status, 403, `a wrong Host is refused at ${path.replace(view.key, '<key>')}`);
+ assert.ok(!rebound.body.includes(view.key));
+ }
+ const reboundApi = await call(view, '/api/v1/boards', { headers: { ...key, host: 'foreign.example:' + port } });
+ assert.equal(reboundApi.status, 401, 'the API refuses a wrong Host in its own words');
+ assert.equal(JSON.parse(reboundApi.body).error.code, 'AUTH_REQUIRED');
+ // The hosted page itself is refused without the secret in its header.
+ const bare = await call(view, '/api/v1/boards', { headers: { origin: HOSTED } });
+ assert.equal(bare.status, 403, 'the allowed origin without the secret is refused');
+ assert.ok(!bare.body.includes(view.key));
+ const queried = await call(view, '/api/v1/boards?k=' + view.key, { headers: { origin: HOSTED } });
+ assert.equal(queried.status, 403, 'the allowed origin may not send the secret in a query');
+ const bearer = await call(view, '/api/v1/boards', { headers: { origin: HOSTED, authorization: 'Bearer ' + view.key } });
+ assert.equal(bearer.status, 403, 'nor in another header');
+ const wrongKey = await call(view, '/api/v1/boards', { headers: { origin: HOSTED, 'x-pullboard-key': 'not-' + view.key } });
+ assert.equal(wrongKey.status, 401, 'nor with a wrong secret');
+ // With its header, the hosted page reads and writes, writes only as JSON.
+ const preflight = await call(view, '/api/v1/boards', { method: 'OPTIONS', headers: { origin: HOSTED, 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type,x-pullboard-key', 'access-control-request-private-network': 'true' } });
+ assert.equal(preflight.status, 204, 'the hosted page\'s preflight is answered');
+ assert.equal(preflight.headers['access-control-allow-origin'], HOSTED);
+ assert.equal(preflight.headers['access-control-allow-private-network'], 'true');
+ assert.match(preflight.headers['access-control-allow-headers'], /x-pullboard-key/);
+ assert.match(preflight.headers.vary, /Origin/);
+ const widened = await call(view, '/api/v1/boards', { method: 'OPTIONS', headers: { origin: HOSTED, 'access-control-request-method': 'GET', 'access-control-request-headers': 'authorization' } });
+ assert.equal(widened.status, 403, 'a preflight for any other header is refused');
+ const read = await call(view, '/api/v1/boards', { headers: { ...key, origin: HOSTED } });
+ assert.equal(read.status, 200, 'the hosted page reads with its header');
+ assert.equal(read.headers['access-control-allow-origin'], HOSTED);
+ const id = JSON.parse(read.body).boards[0].id;
+ const shout = JSON.stringify({ verb: 'shout', args: { to: 'all', text: 'from the hosted page' } });
+ const plain = await call(view, `/api/v1/boards/${id}/moves`, { method: 'POST', headers: { ...key, origin: HOSTED, 'content-type': 'text/plain' }, body: shout });
+ assert.equal(plain.status, 400, 'a write that is not JSON is refused, as a form could send it');
+ const moved = await call(view, `/api/v1/boards/${id}/moves`, { method: 'POST', headers: { ...key, origin: HOSTED, 'content-type': 'application/json' }, body: shout });
+ assert.equal(moved.status, 200, `the hosted page writes as JSON: ${moved.body}`);
+ // The view's own page and its printed link are as before.
+ const own = await call(view, '/api/v1/boards', { headers: { ...key, origin: view.base } });
+ assert.equal(own.status, 200, 'the view\'s own page still reads');
+ assert.equal(own.headers['access-control-allow-origin'], undefined, 'and needs no cross-origin permission');
+ assert.equal((await call(view, view.link.pathname + view.link.search)).status, 200, 'the printed link still opens the board');
+ } finally {
+ await view.stop();
+ }
+});
+
+test('the local view hands its secret only to the hosted page [N26,A2]', { timeout: 60_000 }, async () => { // budget: hang ceiling for one real view and a few local requests.
+ const box = machine();
+ project(box, 'local-origin-handoff');
+ const view = await startView(box);
+ try {
+ const trip = await call(view, '/local/connect', { headers: { 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate' } });
+ assert.equal(trip.status, 200, 'any page may start the round trip with a top-level visit, without the secret');
+ assert.equal(trip.headers['x-frame-options'], 'DENY', 'the round-trip page refuses to be framed');
+ assert.match(trip.headers['content-security-policy'], /frame-ancestors 'none'/);
+ assert.equal(trip.headers['referrer-policy'], 'no-referrer');
+ assert.equal(trip.headers['cache-control'], 'no-store');
+ assert.match(trip.body, /if \(window\.top === window\.self\)/, 'a framed copy never runs its redirect');
+ const onward = onwardOf(trip.body);
+ assert.equal(onward.origin, HOSTED, 'the secret goes back to https://app.pullboard.dev only');
+ assert.equal(onward.pathname, '/');
+ assert.equal(onward.search, '', 'never in a query');
+ assert.deepEqual(JSON.parse(new URLSearchParams(onward.hash.slice(1)).get('pullboard-local')), { version: 1, origin: view.base, key: view.key }, 'only in the fragment');
+ const elsewhere = onwardOf((await call(view, '/local/connect?return=' + encodeURIComponent('https://foreign.example/'))).body);
+ assert.equal(elsewhere.origin, HOSTED, 'no address a page names can turn the round trip elsewhere');
+ // A script's read, a frame and another site's name get nothing.
+ for (const [why, headers] of [
+ ['a script on the hosted page', { origin: HOSTED, 'sec-fetch-dest': 'empty' }],
+ ['a script on another site', { origin: 'https://foreign.example' }],
+ ['a frame', { 'sec-fetch-dest': 'iframe' }],
+ ['a script tag', { 'sec-fetch-dest': 'script' }],
+ ['another site\'s name for this address', { host: 'foreign.example:' + view.link.port }],
+ ]) {
+ const refused = await call(view, '/local/connect', { headers });
+ assert.equal(refused.status, 403, `${why} is refused`);
+ assert.ok(!refused.body.includes(view.key), `${why} gets no secret`);
+ }
+ const protocol = await call(view, '/local/protocol', { headers: { origin: HOSTED } });
+ assert.equal(protocol.status, 200, 'the hosted page can read what this view speaks');
+ assert.equal(protocol.headers['access-control-allow-origin'], HOSTED);
+ assert.deepEqual(JSON.parse(protocol.body), { version: 1, apiVersion: 1, hostedOrigin: HOSTED, connect: '/local/connect', view: '/local/view' }, 'and nothing else: no secret and no board');
+ const opened = onwardOf((await call(view, '/local/view')).body);
+ assert.equal(opened.origin, view.base, 'the local view link opens this view itself');
+ assert.equal(opened.searchParams.get('k'), view.key, 'as the link pullboard view printed does');
+ } finally {
+ await view.stop();
+ }
+});