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(relay): install the phone page and retain pairing [H5,H15]

Corey Olson50ec03228f2d
diff --git a/relay/app.webmanifest b/relay/app.webmanifest
new file mode 100644
index 00000000..6b609745
--- /dev/null
+++ b/relay/app.webmanifest
@@ -0,0 +1,15 @@
+{
+ "id": "/",
+ "name": "Pullboard",
+ "short_name": "Pullboard",
+ "start_url": "/",
+ "scope": "/",
+ "display": "standalone",
+ "background_color": "#f6faf7",
+ "theme_color": "#f6faf7",
+ "icons": [
+ { "src": "/icons/pullboard-192.png", "sizes": "192x192", "type": "image/png" },
+ { "src": "/icons/pullboard-512.png", "sizes": "512x512", "type": "image/png" },
+ { "src": "/icons/pullboard.svg", "sizes": "any", "type": "image/svg+xml" }
+ ]
+}
diff --git a/relay/browser-client.js b/relay/browser-client.js
index aab8431e..9e016955 100644
--- a/relay/browser-client.js
+++ b/relay/browser-client.js
@@ -7,6 +7,7 @@ import { ENGINE_VERSION } from './engine.js';
import { Refused } from './refused.js';
import { enqueueStream, followStream } from './browser-stream.js';
import { noticeLines, rememberOwnedRequestId, storedOwnedRequestState } from './browser-notice.js';
+import { registerApp, requestPairingPersistence } from './install.js';
const KEYS = 'pullboard.relay.keys.v1';
const PENDING = 'pullboard.relay.pair.v1';
@@ -94,6 +95,7 @@ async function documentAt(path, onDenied, options = {}) {
/** Build the API adapter the existing cockpit consumes; no board key enters an HTTP request. */
export async function createTransport({ onUpdate = () => {} } = {}) {
+ void registerApp();
const savedKeys = stored(localStorage, KEYS, {});
const keys = savedKeys && typeof savedKeys === 'object' && !Array.isArray(savedKeys) ? savedKeys : {};
const paired = new Map();
@@ -103,6 +105,8 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
let failure = '';
let failureBoard = null;
let accessLost = false;
+ let persistenceRequest = null;
+ let persistenceWarning = false;
rememberPairing();
let pair = takePairing() ?? stored(sessionStorage, PENDING, null);
if (pair && (!BOARD.test(pair.board ?? '') || typeof pair.key !== 'string')) pair = null;
@@ -135,6 +139,20 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
paragraph.textContent = text;
element.append(paragraph);
}
+ if (persistenceWarning) {
+ const paragraph = document.createElement('p');
+ paragraph.id = 'pairing-storage-notice';
+ paragraph.textContent = 'This browser may remove your pairing. Add Pullboard to your Home Screen to help keep it.';
+ element.append(paragraph);
+ }
+ }
+
+ /** Ask once after pairing, retaining one refusal line through later board refreshes. */
+ function keepPairingStorage() {
+ persistenceRequest ??= requestPairingPersistence().then(kept => {
+ persistenceWarning = !kept;
+ notice();
+ });
}
/** Keep one missing-snapshot board visible as waiting without clearing other authorized boards. */
@@ -356,7 +374,10 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
paired.set(board.id, entry);
waitingBoards.delete(board.id);
keys[board.id] = encoded;
- try { localStorage.setItem(KEYS, JSON.stringify({ ...stored(localStorage, KEYS, {}), [board.id]: encoded })); } catch { failure = 'This browser cannot save pairing. Use the pairing link again on your next visit.'; failureBoard = null; }
+ try {
+ localStorage.setItem(KEYS, JSON.stringify({ ...stored(localStorage, KEYS, {}), [board.id]: encoded }));
+ keepPairingStorage();
+ } catch { failure = 'This browser cannot save pairing. Use the pairing link again on your next visit.'; failureBoard = null; }
if (pair?.board === board.id) {
pair = null;
try { sessionStorage.removeItem(PENDING); } catch { /* Device storage can be unavailable. */ }
@@ -488,12 +509,16 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
/** Pair a link opened in this already-loaded page as well as one opened on a fresh visit. */
async function pairingChanged() {
- try { rememberPairing(); pair = takePairing() ?? pair; await enrollPhone((path, options) => documentAt(path, denied, options)); await listing(); onUpdate(); }
+ try {
+ rememberPairing(); pair = takePairing() ?? pair;
+ if (await enrollPhone((path, options) => documentAt(path, denied, options))) keepPairingStorage();
+ await listing(); onUpdate();
+ }
catch { failure = 'The pairing link is invalid. Get a new link from a linked machine.'; failureBoard = null; notice(); }
}
addEventListener('hashchange', pairingChanged);
addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });
- await enrollPhone((path, options) => documentAt(path, denied, options));
+ if (await enrollPhone((path, options) => documentAt(path, denied, options))) keepPairingStorage();
await listing();
await installPhoneApprovals((path, options) => documentAt(path, denied, options), keys, async () => { await listing(); onUpdate(); });
return {
diff --git a/relay/browser-devices.js b/relay/browser-devices.js
index c30e5225..f894ff85 100644
--- a/relay/browser-devices.js
+++ b/relay/browser-devices.js
@@ -41,7 +41,7 @@ async function deviceStorage(value) {
} finally { db.close(); }
}
-/** Send a public authenticated enrollment while the private key and QR secret remain on the phone. */
+/** Send a public enrollment without exposing private material; return true once new pairing delivers keys. */
export async function enrollPhone(documentAt) {
rememberDevicePairing();
let pending;
@@ -68,7 +68,7 @@ export async function enrollPhone(documentAt) {
while (Date.now() < pending.expires) {
try {
const response = await documentAt('/api/v1/devices/' + device.deviceId + '/boards');
- if (response.wraps.length) return;
+ if (response.wraps.length) return true;
} catch (error) { if (error.code !== 'DEVICE_NOT_ENROLLED') throw error; }
await new Promise(resolve => setTimeout(resolve, 250));
}
diff --git a/relay/browser-install.js b/relay/browser-install.js
new file mode 100644
index 00000000..a1c9cb5f
--- /dev/null
+++ b/relay/browser-install.js
@@ -0,0 +1,15 @@
+/** Optional browser installation and durable pairing storage [H5,H15]. */
+
+/** Register only our same-origin worker; failure leaves the online page usable. */
+export async function registerApp(browser = globalThis.navigator) {
+ if (!browser?.serviceWorker?.register) return null;
+ try { return await browser.serviceWorker.register('/service-worker.js', { scope: '/' }); }
+ catch { return null; } // Installation is optional; the normal online transport remains available.
+}
+
+/** Ask to retain this origin's pairing after it is saved, without claiming a browser guarantee. */
+export async function requestPairingPersistence(browser = globalThis.navigator) {
+ if (!browser?.storage?.persist) return false;
+ try { return await browser.storage.persist() === true; }
+ catch { return false; } // Refused or unavailable storage gets the same safe, actionable notice.
+}
diff --git a/relay/browser-page.js b/relay/browser-page.js
index 1d5963e7..0847cfbe 100644
--- a/relay/browser-page.js
+++ b/relay/browser-page.js
@@ -8,15 +8,15 @@ import { Refused } from '../src/refused.js';
const STYLES = readFileSync(new URL('../src/view.css', import.meta.url), 'utf8');
/** Refuse relay startup locally while the public shell has no relay session; keep its sign-in link and never reload. */
-const SIGN_IN_TRANSPORT = '/** Preserve device-only pairing before sign-in without starting relay reads. */\nimport { rememberPairing } from "./client.js";\nexport function createTransport() {\n rememberPairing();\n throw new Error("Sign in with GitHub to open your linked boards.");\n}\n';
+const SIGN_IN_TRANSPORT = '/** Preserve device-only pairing before sign-in without starting relay reads. */\nimport { rememberPairing } from "./client.js";\nimport { registerApp } from "./install.js";\nexport function createTransport() {\n void registerApp();\n rememberPairing();\n throw new Error("Sign in with GitHub to open your linked boards.");\n}\n';
/** Serve a fixed asset with cache and browser isolation boundaries, never a filesystem-derived URL. */
function respond(res, type, content, scriptHashes = []) {
const hashes = scriptHashes.map(hash => "'sha256-" + hash + "'").join(' ');
res.writeHead(200, {
- 'content-type': type + '; charset=utf-8', 'cache-control': 'no-store',
+ 'content-type': type + (typeof content === 'string' ? '; charset=utf-8' : ''), 'cache-control': 'no-store',
'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer',
- 'content-security-policy': "default-src 'none'; script-src 'self' " + hashes + "; style-src 'self'; connect-src 'self' http://127.0.0.1:4890 http://localhost:4890; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
+ 'content-security-policy': "default-src 'none'; script-src 'self' " + hashes + "; style-src 'self'; connect-src 'self' http://127.0.0.1:4890 http://localhost:4890; img-src 'self' data:; manifest-src 'self'; worker-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
});
res.end(content);
}
@@ -25,6 +25,12 @@ function respond(res, type, content, scriptHashes = []) {
export function createRelayBrowserHandler({ authenticate }) {
const assets = new Map([
['/view.css', ['text/css', STYLES]],
+ ['/manifest.webmanifest', ['application/manifest+json', readFileSync(new URL('./app.webmanifest', import.meta.url), 'utf8')]],
+ ['/service-worker.js', ['text/javascript', readFileSync(new URL('./service-worker.js', import.meta.url), 'utf8')]],
+ ['/icons/pullboard.svg', ['image/svg+xml', readFileSync(new URL('./icons/pullboard.svg', import.meta.url), 'utf8')]],
+ ['/icons/pullboard-192.png', ['image/png', readFileSync(new URL('./icons/pullboard-192.png', import.meta.url))]],
+ ['/icons/pullboard-512.png', ['image/png', readFileSync(new URL('./icons/pullboard-512.png', import.meta.url))]],
+ ['/relay/install.js', ['text/javascript', readFileSync(new URL('./browser-install.js', import.meta.url), 'utf8')]],
['/relay/device-keys.js', ['text/javascript', readFileSync(new URL('../src/relay-device-keys.js', import.meta.url), 'utf8')]],
['/relay/relay-approval.js', ['text/javascript', readFileSync(new URL('../src/relay-approval.js', import.meta.url), 'utf8').replace("'./relay-device-keys.js'", "'./device-keys.js'")]],
['/relay/browser-devices.js', ['text/javascript', readFileSync(new URL('./browser-devices.js', import.meta.url), 'utf8')]],
@@ -59,6 +65,7 @@ export function createRelayBrowserHandler({ authenticate }) {
const notice = relaySession ? '<p>Pairing this browser…</p>'
: '<p>Connecting to this machine. Sign in to see your linked boards.</p><a href="/auth/github/start">Sign in with GitHub</a>';
const page = cockpitPage('', { readOnly: true, requests: relaySession, transportModule: relaySession ? '/relay/client.js' : '/relay/sign-in.js', apiHeaders: {}, stylesheet: '/view.css', hostedLocal: true, relaySession, signIn: '/auth/github/start' })
+ .replace('<link rel="icon" href="data:,">', '<link rel="icon" href="/icons/pullboard.svg" type="image/svg+xml">\n<link rel="manifest" href="/manifest.webmanifest">\n<link rel="apple-touch-icon" href="/icons/pullboard-192.png">\n<meta name="theme-color" content="#f6faf7">')
.replace('<main>', '<main><section class="card-panel" id="relay-notice" role="status">' + notice + '</section>');
const scripts = [...page.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(match => createHash('sha256').update(match[1]).digest('base64'));
respond(res, 'text/html', page, scripts);
diff --git a/relay/icons/pullboard-192.png b/relay/icons/pullboard-192.png
new file mode 100644
index 00000000..70172354
Binary files /dev/null and b/relay/icons/pullboard-192.png differ
diff --git a/relay/icons/pullboard-512.png b/relay/icons/pullboard-512.png
new file mode 100644
index 00000000..2380bc25
Binary files /dev/null and b/relay/icons/pullboard-512.png differ
diff --git a/relay/icons/pullboard.svg b/relay/icons/pullboard.svg
new file mode 100644
index 00000000..b62269cc
--- /dev/null
+++ b/relay/icons/pullboard.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><rect width="64" height="64" rx="12" fill="#f6faf7"/><g transform="translate(9.6 9.6) scale(.7)"><path fill="#121a17" d="M8 7h35a6 6 0 0 1 6 6v7H8a5 5 0 0 1-5-5v-3a5 5 0 0 1 5-5Z"/><rect width="56" height="14" x="3" y="25" fill="#08915f" rx="5"/><path fill="#121a17" d="M8 43h35a6 6 0 0 1 6 6v8H8a5 5 0 0 1-5-5v-4a5 5 0 0 1 5-5Z"/></g></svg>
diff --git a/relay/service-worker.js b/relay/service-worker.js
new file mode 100644
index 00000000..0ae5bc00
--- /dev/null
+++ b/relay/service-worker.js
@@ -0,0 +1,7 @@
+/** Installation only: board pages, keys and API responses are never cached here [H5,H15]. */
+self.addEventListener('install', event => {
+ event.waitUntil(self.skipWaiting());
+});
+self.addEventListener('activate', event => {
+ event.waitUntil(self.clients.claim());
+});
diff --git a/test/relay-installable.test.js b/test/relay-installable.test.js
new file mode 100644
index 00000000..e3b18332
--- /dev/null
+++ b/test/relay-installable.test.js
@@ -0,0 +1,114 @@
+/** Hosted installation and pairing-storage behavior use real HTTP and Chrome [H5,H15,C7]. */
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { test } from 'node:test';
+import { relayClientFixture } from './relay-client-fixture.js';
+import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';
+
+test('a paired phone page is installable and asks to keep its storage [H5,H15,C7]', async t => {
+ const box = await relayClientFixture(t);
+ const shell = await fetch(box.origin + '/', { signal: AbortSignal.timeout(relayWorkBudgetMs()) });
+ assert.equal(shell.status, 200);
+ const html = await shell.text();
+ const manifestLink = /<link\s+rel="manifest"\s+href="([^"]+)"/u.exec(html);
+ assert.ok(manifestLink, 'the actual hosted page advertises its web app manifest');
+ assert.equal(new URL(manifestLink[1], box.origin).origin, box.origin);
+ const policy = shell.headers.get('content-security-policy');
+ assert.match(policy, /default-src 'none'/u);
+ assert.match(policy, /manifest-src 'self'/u);
+ assert.match(policy, /worker-src 'self'/u);
+ assert.doesNotMatch(policy, /unsafe-inline|unsafe-eval/u);
+
+ const response = await fetch(new URL(manifestLink[1], box.origin));
+ assert.equal(response.status, 200);
+ assert.match(response.headers.get('content-type'), /application\/manifest\+json/u);
+ assert.equal(response.headers.get('cache-control'), 'no-store');
+ const manifest = await response.json();
+ assert.equal(manifest.name, 'Pullboard');
+ assert.equal(manifest.display, 'standalone');
+ assert.equal(new URL(manifest.start_url, box.origin).href, box.origin + '/');
+ assert.equal(new URL(manifest.scope, box.origin).href, box.origin + '/');
+ for (const size of [192, 512]) {
+ const icon = manifest.icons.find(value => value.sizes === `${size}x${size}` && value.type === 'image/png');
+ assert.ok(icon, `the manifest has a real ${size}px raster fallback`);
+ const address = new URL(icon.src, box.origin);
+ assert.equal(address.origin, box.origin);
+ const downloaded = await fetch(address);
+ assert.equal(downloaded.status, 200);
+ assert.match(downloaded.headers.get('content-type'), /image\/png/u);
+ const png = Buffer.from(await downloaded.arrayBuffer());
+ assert.equal(png.subarray(0, 8).toString('hex'), '89504e470d0a1a0a');
+ assert.equal(png.readUInt32BE(16), size);
+ assert.equal(png.readUInt32BE(20), size);
+ }
+ const worker = await fetch(box.origin + '/service-worker.js');
+ assert.equal(worker.status, 200);
+ assert.match(worker.headers.get('content-type'), /javascript/u);
+ assert.equal(worker.headers.get('cache-control'), 'no-store');
+ assert.equal((await fetch(box.origin + '/relay/not-a-public-asset.js')).status, 401,
+ 'an unlisted path still requires authentication');
+ const session = await box.phoneSession();
+ assert.equal((await fetch(box.origin + '/relay/not-a-public-asset.js', {
+ headers: { authorization: 'Bearer ' + session.token },
+ })).status, 404, 'even an authenticated caller cannot fetch arbitrary filesystem paths');
+
+ await t.test('persistence permission grants, refusals and unsupported browsers are handled [H5,H15]', async () => {
+ const { requestPairingPersistence } = await import('../relay/browser-install.js');
+ let calls = 0;
+ assert.equal(await requestPairingPersistence({ storage: { persist: async () => { calls += 1; return true; } } }), true);
+ assert.equal(calls, 1);
+ assert.equal(await requestPairingPersistence({ storage: { persist: async () => false } }), false);
+ assert.equal(await requestPairingPersistence({ storage: { persist: async () => { throw new Error('fixture denial'); } } }), false);
+ assert.equal(await requestPairingPersistence({}), false);
+ });
+
+ await t.test('real pairing requests storage once and the worker controls the page [H5,H15,C7]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+ }, async () => {
+ const title = 'INSTALLABLE_PAIRED_BOARD';
+ assert.equal((await box.cli('add', box.lane, title)).code, 0);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const encoded = readFileSync(box.keyFile, 'utf8').trim();
+ const chrome = await startChrome();
+ try {
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', {
+ source: `window.setInterval = () => 0;
+ window.pairingPersistenceCalls = 0;
+ Object.defineProperty(navigator.storage, 'persist', { value: async () => {
+ window.pairingPersistenceCalls += 1;
+ return location.search === '?granted';
+ } });`,
+ });
+ const cookie = await chrome.send('Network.setCookie', {
+ name: 'pb_session', value: session.token, url: box.origin, httpOnly: true, sameSite: 'Lax',
+ });
+ assert.equal(cookie.success, true, 'the private browser has a real person session');
+ await chrome.navigate(box.origin + '/');
+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes('pair this browser')");
+ assert.equal(await chrome.evaluate('window.pairingPersistenceCalls'), 0, 'an unpaired visit does not ask to retain pairing');
+ await chrome.waitFor('navigator.serviceWorker.controller !== null', undefined, 'the served worker controls the hosted page');
+ assert.equal(await chrome.evaluate('navigator.serviceWorker.controller.scriptURL'), box.origin + '/service-worker.js');
+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');
+ assert.equal(await chrome.evaluate('window.pairingPersistenceCalls'), 1,
+ 'successful pairing asks the browser to retain its storage');
+ const warning = await chrome.evaluate("document.querySelector('#pairing-storage-notice')?.textContent");
+ assert.equal(typeof warning, 'string', 'a refused persistence request is visible after pairing');
+ assert.match(warning, /Home Screen/u);
+ assert.doesNotMatch(warning, /\n/u, 'a refused storage request is explained in one line');
+ await chrome.evaluate("import('/relay/client.js').then(async module => { const transport = await module.createTransport(); await transport.request('/api/v1/boards'); })");
+ assert.equal(await chrome.evaluate("document.querySelectorAll('#pairing-storage-notice').length"), 1,
+ 'later board refreshes keep one warning');
+ assert.equal(await chrome.evaluate('window.pairingPersistenceCalls'), 2,
+ 'a second transport asks once for its retained pairing, not once per refresh');
+ await chrome.navigate(box.origin + '/?granted');
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');
+ assert.equal(await chrome.evaluate('window.pairingPersistenceCalls'), 1,
+ 'reopening a retained pairing requests persistence once');
+ assert.equal(await chrome.evaluate("document.querySelector('#pairing-storage-notice') === null"), true,
+ 'granted persistence needs no refusal message');
+ assert.deepEqual(await chrome.evaluate('caches.keys()'), [], 'the minimal worker stores no board pages or API responses');
+ } finally { await chrome.close(); }
+ });
+});