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.

fix(view): harden configured transport [N26,H5]

Corey Olson8167cf2608f6
diff --git a/src/cockpit.js b/src/cockpit.js
index c4d247de..6b8eaca5 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -34,12 +34,14 @@ function lifecycle() {
* folder, where a path the host does not serve would leave a reload with nothing.
*
* @param {string} [key] - The session's secret.
- * @param {{snapshot?: boolean, apiBase?: string, apiHeaders?: Record<string, string>, stylesheet?: string, paths?: boolean}} [options] - Served API connection and assets, whether the host also serves the page at /roadmap, or a static, read-only page with event replay.
+ * @param {{snapshot?: boolean, readOnly?: boolean, transportModule?: string|null, apiBase?: string, apiHeaders?: Record<string, string>, stylesheet?: string, paths?: boolean}} [options] - Served API connection and assets, whether the host also serves the page at /roadmap, or a static, read-only page with event replay.
* @returns {string}
*/
-export function cockpitPage(key = '', { snapshot = false, apiBase = '', apiHeaders = { 'x-pullboard-key': key }, stylesheet = null, paths = false } = {}) {
- const connection = JSON.stringify({ base: apiBase.replace(/\/$/, ''), headers: apiHeaders }).replace(/</g, '\\u003c');
- const css = stylesheet ?? (snapshot ? 'view.css' : '/view.css?k=' + encodeURIComponent(key));
+export function cockpitPage(key = '', { snapshot = false, readOnly = false, transportModule = null, apiBase = '', apiHeaders = { 'x-pullboard-key': key }, stylesheet = null, paths = false } = {}) {
+ if (transportModule !== null && (typeof transportModule !== 'string' || !transportModule.trim())) throw new TypeError('transportModule must be a non-empty module URL or null');
+ const connection = JSON.stringify(transportModule ? { base: '', headers: {} } : { base: apiBase.replace(/\/$/, ''), headers: apiHeaders }).replace(/</g, '\\u003c');
+ const moduleOption = JSON.stringify(transportModule).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>
<html lang="en">
@@ -50,7 +52,7 @@ export function cockpitPage(key = '', { snapshot = false, apiBase = '', apiHeade
<link rel="stylesheet" href="${cssAttribute}">
<link rel="icon" href="data:,">
</head>
-<body class="loading${snapshot ? ' snapshot' : ''}">
+<body class="loading${snapshot ? ' snapshot' : ''}${readOnly ? ' read-only' : ''}">
<div class="shell">
<aside class="side" id="side" aria-label="Projects">
<div class="side-top">
@@ -143,7 +145,10 @@ export function cockpitPage(key = '', { snapshot = false, apiBase = '', apiHeade
<div class="console" id="console" title="Click to close" hidden></div>
<script>
const snapshot = ${JSON.stringify(snapshot)};
+const readOnly = ${JSON.stringify(readOnly)};
+const transportModule = ${moduleOption};
const connection = ${connection};
+let transport = 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;
@@ -444,7 +449,8 @@ function flowSvg(p) {
/** Read or move through API v1, retaining the rule and repair guidance in a refusal. */
async function api(path, body) {
- if (snapshot && body) throw new Error('This is a read-only snapshot.');
+ if (body && (snapshot || readOnly)) throw new Error(snapshot ? 'This is a read-only snapshot.' : 'This is a read-only view.');
+ if (transport) return transport.request(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();
@@ -1188,7 +1194,7 @@ function moveMessage(move, result) {
/** Run a public API move beside its action and let only the latest one own the console and timer. */
async function act(command, args, anchor) {
const out = $('console');
- if (snapshot) { out.hidden = false; out.className = 'console no'; out.textContent = 'This is a read-only snapshot.'; return false; }
+ if (snapshot || readOnly) { out.hidden = false; out.className = 'console no'; out.textContent = snapshot ? 'This is a read-only snapshot.' : 'This is a read-only view.'; return false; }
if (anchor) {
const target = anchor.matches('form')
? anchor.querySelector('.actions') || anchor.querySelector('[type="submit"]') || anchor
@@ -1329,7 +1335,17 @@ if (snapshot) {
if (snapshotReplay.playing) { clearTimeout(snapshotReplay.timer); snapshotReplay.timer = setTimeout(advanceReplay, 1000 / Number($('replay-speed').value)); }
});
}
-refresh().catch((error) => { document.body.classList.remove('loading'); $('live').textContent = 'cannot reach the view: ' + error.message; });
+/** Load an explicitly configured transport before the first read; its updates refresh this page. */
+async function startPage() {
+ if (transportModule) {
+ const module = await import(transportModule);
+ if (typeof module.createTransport !== 'function') throw new Error('The browser transport must export createTransport({ onUpdate }).');
+ transport = await module.createTransport({ onUpdate: () => transport ? refresh().catch((error) => { $('live').textContent = 'offline: ' + error.message; }) : Promise.resolve() });
+ if (!transport || typeof transport.request !== 'function') throw new Error('The browser transport must provide request(path, body).');
+ }
+ await refresh();
+}
+startPage().catch((error) => { document.body.classList.remove('loading'); $('live').textContent = 'cannot reach the view: ' + error.message; });
if (!snapshot) setInterval(() => { if (!document.hidden) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, 3000);
setInterval(tickAges, 60000);
</script>
diff --git a/src/view.css b/src/view.css
index 45b3dbc6..f434b7ac 100644
--- a/src/view.css
+++ b/src/view.css
@@ -303,6 +303,7 @@ code.inline { padding: 0 3px; border-radius: 3px; background: color-mix(in srgb,
.snapshot-controls label { display: flex; align-items: center; gap: 6px; }
.snapshot-controls output { color: var(--ink-muted); font: 12px/1.5 var(--mono); }
.snapshot #new-item, .snapshot form, .snapshot [data-new], .snapshot [data-release], .snapshot [data-shout], .snapshot [data-go^="decide:"] { display: none !important; }
+.read-only #new-item, .read-only form, .read-only [data-new], .read-only [data-release], .read-only [data-shout], .read-only [data-go^="decide:"] { display: none !important; }
/* Every action keeps a usable touch target at either viewport, including inline controls. */
button, input, select, textarea, [data-item], [data-row] { min-height: 44px; }
diff --git a/test/cockpit.test.js b/test/cockpit.test.js
index 1195bb41..6d80c55c 100644
--- a/test/cockpit.test.js
+++ b/test/cockpit.test.js
@@ -2633,6 +2633,117 @@ test('served connection reaches an authenticated API on another origin and path
}
});
+test('read-only pages use a local browser transport and refresh on its updates [N26,N27]', { timeout: 90_000 }, async (t) => {
+ const executable = chromeExecutable();
+ if (!executable) return t.skip('Install Chrome or set PULLBOARD_CHROME to run the browser transport proof.');
+
+ const box = machine();
+ const app = project(box, 'read only transport');
+ box.run(app.repo, 'add', 'web', 'Read-only fixture item', '--specs', 'G1', '--criterion', 'keeps action controls in the DOM');
+ box.run(app.repo, 'shout', 'person', 'Should the read-only fixture ship?', '--decision');
+ box.run(app.repo, 'hold', 'web', '--reason', 'read-only fixture hold');
+ const live = await startView(box);
+ const pageKey = 'page-relay-secret';
+ const headerKey = 'header-relay-secret';
+ const page = cockpitPage(pageKey, {
+ readOnly: true,
+ transportModule: '/transport.js',
+ apiBase: 'https://private.invalid/board?secret=api-base-secret',
+ apiHeaders: { 'x-pullboard-key': headerKey },
+ stylesheet: '/view.css',
+ });
+ for (const secret of [pageKey, headerKey, 'api-base-secret']) assert.equal(page.includes(secret), false, 'custom transport page options do not expose API credentials');
+ assert.throws(() => cockpitPage('', { transportModule: '' }), /transportModule/);
+
+ const forwarded = [];
+ const moduleSource = `export async function createTransport({ onUpdate }) {
+ window.__transportCalls = [];
+ window.__transportUpdate = onUpdate;
+ return { async request(path, body) {
+ window.__transportCalls.push({ path, body: body ?? null });
+ const response = await fetch('/fixture' + path, { method: body ? 'POST' : 'GET', headers: body ? { 'content-type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined });
+ const document = await response.json();
+ if (!response.ok) throw new Error(document.error?.message || String(response.status));
+ return document;
+ } };
+ }`;
+ const server = createServer((request, response) => {
+ const url = new URL(request.url, 'http://127.0.0.1');
+ if (url.pathname === '/' || url.pathname === '/missing') {
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ response.end(page);
+ return;
+ }
+ if (url.pathname === '/transport.js') {
+ response.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' });
+ response.end(moduleSource);
+ return;
+ }
+ if (url.pathname === '/view.css') {
+ response.writeHead(200, { 'content-type': 'text/css; charset=utf-8' });
+ response.end(readFileSync(new URL('../src/view.css', import.meta.url), 'utf8'));
+ return;
+ }
+ if (!url.pathname.startsWith('/fixture/')) {
+ response.writeHead(404).end();
+ return;
+ }
+ const target = url.pathname.slice('/fixture'.length) + url.search;
+ const headers = { 'x-pullboard-key': live.key };
+ if (request.method !== 'GET') {
+ forwarded.push(request.method);
+ response.writeHead(405, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'fixture transport accepts reads only' }));
+ return;
+ }
+ forwarded.push(request.method);
+ fetch(live.base + target, { headers }).then(async (reply) => {
+ response.writeHead(reply.status, { 'content-type': 'application/json' });
+ response.end(await reply.text());
+ }).catch((error) => {
+ response.writeHead(502, { 'content-type': 'application/json' });
+ response.end(JSON.stringify({ error: String(error.message || error) }));
+ });
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-transport-chrome-'));
+ scratch.push(profile);
+ let chrome;
+ try {
+ chrome = await openSnapshotChrome(executable, `http://127.0.0.1:${address.port}/`, profile);
+ await chrome.waitFor("typeof data === 'object' && document.body?.classList.contains('read-only') && !!data?.project && typeof window.__transportUpdate === 'function'");
+ const calls = JSON.parse(await chrome.evaluate('JSON.stringify(window.__transportCalls)'));
+ assert.ok(calls.some((call) => call.path === '/api/v1/boards'));
+ assert.ok(calls.some((call) => call.path.startsWith('/api/v1/boards/') && call.path.endsWith('/state')));
+ assert.match(await chrome.evaluate("document.querySelector('#live').textContent"), /^live · /, 'read-only transport keeps the page live');
+ const actionSelectors = ['#new-item', '#add-form', '#shout-form', '#hold-form', '[data-release]', '[data-shout]', '[data-new]', '[data-go^="decide:"]'];
+ const actionMatches = JSON.parse(await chrome.evaluate(`JSON.stringify(${JSON.stringify(actionSelectors)}.map((selector) => ({ selector, count: document.querySelectorAll(selector).length, visible: [...document.querySelectorAll(selector)].some((node) => !node.hidden && getComputedStyle(node).display !== 'none') })))`));
+ assert.ok(actionMatches.every((entry) => entry.count > 0), 'the seeded item, decision and hold exercise every action selector');
+ assert.deepEqual(actionMatches.filter((entry) => entry.visible).map((entry) => entry.selector), [], 'read-only mode hides every match for every action control');
+
+ const refusedAction = JSON.parse(await chrome.evaluate(`(async () => JSON.stringify({ result: await act('shout', { to: 'all', text: 'blocked' }), message: document.querySelector('#console').textContent }))()`));
+ assert.equal(refusedAction.result, false);
+ assert.match(refusedAction.message, /read-only/i);
+ const refusedApi = await chrome.evaluate(`(async () => { try { await api('/api/v1/boards/demo/moves', { verb: 'shout' }); return 'unexpected success'; } catch (error) { return error.message; } })()`);
+ assert.match(refusedApi, /read-only/i, 'direct API mutation calls are refused before transport');
+ assert.ok(forwarded.every((method) => method === 'GET'), 'read-only action attempts send no write through the transport');
+
+ await chrome.evaluate(`window.__samePage = true; Object.defineProperty(document, 'hidden', { configurable: true, get: () => true })`);
+ box.run(app.repo, 'add', 'web', 'Transport refresh item', '--specs', 'G1', '--criterion', 'appears after a transport update');
+ await chrome.evaluate('window.__transportUpdate()');
+ assert.equal(await chrome.evaluate("data?.project?.items.some((item) => item.title === 'Transport refresh item') && window.__samePage === true"), true, 'onUpdate refreshes state in the same page without relying on the poll');
+ assert.ok(forwarded.every((method) => method === 'GET'), 'transport update refreshed through reads only');
+
+ } finally {
+ if (chrome) {
+ chrome.socket.close();
+ await stopOwnedChrome(chrome.child, chrome.stopped);
+ }
+ await live.stop();
+ await new Promise((resolve) => server.close(resolve));
+ }
+});
+
test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N26,N27]', { timeout: 120_000 }, async (t) => {
const executable = chromeExecutable();
if (!executable) return t.skip('Install Chrome or set PULLBOARD_CHROME for viewport checks.');