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(view): link every local board in one sign-in [H5,N26]
Corey Olsonb5fa593f2cbc
diff --git a/src/cockpit.js b/src/cockpit.jsindex d23247c3..56edfc8d 100644--- a/src/cockpit.js+++ b/src/cockpit.js@@ -115,6 +115,12 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ</section><p class="empty" id="project-loading" role="status" hidden>Loading project…</p>${hostedMarkup('http://127.0.0.1:4890')}+ <p class="side-hint" id="share-note" hidden>See these boards from any device: link them to pullboard.dev <button class="ghost" id="share-start" type="button">Sign in with GitHub</button></p>+ <section class="card-panel" id="share-panel" aria-label="Link these boards" hidden>+ <p id="share-status" role="status" aria-live="polite"></p>+ <button class="ghost" id="share-pair" type="button" hidden>Pair a device</button>+ <button class="ghost" id="share-close" type="button">Cancel sign-in</button>+ </section><section class="card-panel snapshot-controls" id="snapshot-controls" ${snapshot ? '' : 'hidden'} aria-label="Snapshot replay"><span>Read-only snapshot</span><button class="ghost" id="replay-play" type="button">Play from first event</button>@@ -1000,11 +1006,11 @@ async function api(path, body) {}/** Use one JSON request primitive, capturing its local route and session before awaiting a reply. */-async function jsonRequest(path, body, base, headers, cache) {+async function jsonRequest(path, body, base, headers, cache, format = 'json') {const session = localSession;path = base + path;const res = await fetch(path, { method: body ? 'POST' : 'GET', headers: { ...headers, ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined, cache });- const json = await res.json();+ const json = format === 'html' && res.ok ? await res.text() : await res.json();if (session && session === localSession && base === session.origin) {if (res.status === 401 || res.status === 403) localExpired();else if (res.ok && !localConfirmed) { localConfirmed = true; tabValue(LOCAL_TRIPS, null); }@@ -1012,11 +1018,131 @@ async function jsonRequest(path, body, base, headers, cache) {if (!res.ok) {const refusal = json.error;const message = refusal && typeof refusal === 'object' ? '[' + refusal.code + '] ' + refusal.message : refusal || res.status;- throw new Error(message);+ const error = new Error(message);+ if (refusal && typeof refusal === 'object') error.code = refusal.code;+ throw error;}return json;}+/** Read only this machine's authenticated view, including when its page is hosted elsewhere. */+function sharingApi(body) {+ return jsonRequest('/api/v1/view-link', body, hosted.local ? localReadBase : connection.base,+ hosted.local ? localReadHeaders : connection.headers);+}++let sharingReady = null;+let sharingTask = Promise.resolve();+let sharing = { state: 'idle', intentId: null, popup: null, timer: null, closing: false, boards: [] };++/** Show the opt-in once after a real local read; quiet boards do not acquire another polling loop. */+async function sharingInvitation() {+ if (!$('share-note') || snapshot || (hosted.local ? !localSession : pageReadOnly || configuredTransportModule)) return;+ try { $('share-note').hidden = !(await sharingApi()).available; }+ catch { $('share-note').hidden = true; }+}++/** Render names and reasons as text, without exposing machine paths or private sign-in material. */+function sharingProgress(status) {+ sharing.state = status.state;+ sharing.boards = status.boards || [];+ const linked = sharing.boards.filter(board => board.outcome === 'linked');+ if (linked.length) $('share-note').hidden = true;+ const lines = sharing.boards.map(board => board.outcome === 'linked' ? 'Linked ' + board.name + '.'+ : 'Did not link ' + board.name + ': ' + board.reason);+ if (status.error) lines.push(status.error.message);+ else if (['cancelled', 'declined', 'expired'].includes(status.state)) lines.push('No boards were linked. You can sign in again whenever you want.');+ else if (status.state === 'pairing') lines.push('Your boards are linked. Pair a device to open them there, or close this step; the links stay in place.');+ else if (status.state === 'pairing-stopped') lines.push('Phone pairing stopped. Your boards remain linked.');+ else if (status.state === 'linking') lines.push('Linking every registered board…');+ else if (status.state === 'done' && !linked.length && !lines.length) lines.push('No boards were linked.');+ if (lines.length) $('share-status').textContent = lines.join('\\n');+ $('share-pair').hidden = status.state !== 'pairing';+ $('share-close').textContent = linked.length ? 'Close' : 'Cancel sign-in';+ if (status.state !== 'waiting') { sharing.popup?.close(); sharing.popup = null; }+}++/** Stop the one operation and await core cleanup; a linking batch is never described as rolled back. */+async function closeSharing() {+ clearTimeout(sharing.timer);+ sharing.closing = true;+ if (!sharing.intentId) return;+ try {+ const status = await sharingApi({ action: 'cancel', intentId: sharing.intentId });+ sharingProgress(status);+ sharing.popup?.close(); sharing.popup = null;+ $('share-start').disabled = false;+ sharingReady = sharingInvitation();+ } catch (error) {+ $('share-status').textContent = error.message;+ if (error.code === 'VIEW_SIGN_IN_LINKING') {+ sharing.closing = false;+ sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);+ } else { sharing.popup?.close(); sharing.popup = null; $('share-start').disabled = false; }+ }+}++/** Poll public progress only while the person has an active sign-in or pairing step. */+async function pollSharing() {+ if (sharing.closing) return;+ if (sharing.state === 'waiting' && sharing.popup?.closed) { sharingTask = closeSharing(); return sharingTask; }+ try {+ const status = await sharingApi({ action: 'status', intentId: sharing.intentId });+ sharingProgress(status);+ if (['waiting', 'linking', 'pairing'].includes(status.state)) sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);+ else { $('share-start').disabled = false; sharingReady = sharingInvitation(); }+ } catch (error) {+ $('share-status').textContent = error.message;+ $('share-start').disabled = false;+ }+}++/** Begin one existing all-board sign-in; open its browser window in the native click before awaiting the server. */+async function beginSharing(popup) {+ sharing = { state: 'waiting', intentId: null, popup, timer: null, closing: false, boards: [] };+ $('share-panel').hidden = false;+ $('share-start').disabled = true;+ $('share-status').textContent = 'Starting GitHub sign-in…';+ try {+ const instructions = await sharingApi({ action: 'start' });+ sharing.intentId = instructions.intentId;+ if (sharing.closing || popup?.closed) return await closeSharing();+ $('share-status').textContent = 'Enter ' + instructions.userCode + ' in the GitHub window. Closing this sign-in before linking leaves every board local.';+ popup.location.replace(instructions.verificationURL);+ sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);+ } catch (error) {+ popup?.close();+ $('share-status').textContent = error.message;+ $('share-start').disabled = false;+ }+}++/** Open only core's transient device navigation in a separately authenticated HTML response, never a JSON URL. */+async function pairSharing(popup) {+ const base = hosted.local ? localReadBase : connection.base;+ const headers = hosted.local ? localReadHeaders : connection.headers;+ try {+ const html = await jsonRequest('/api/v1/view-link', { action: 'pairing', intentId: sharing.intentId }, base, headers, undefined, 'html');+ const destination = new DOMParser().parseFromString(html, 'text/html').querySelector('a')?.getAttribute('href');+ if (!destination) throw new Error('Phone pairing is no longer waiting. Read the sign-in status and start again if needed.');+ popup.location.replace(destination);+ } catch (error) { popup?.close(); $('share-status').textContent = error.message; }+}++$('share-start')?.addEventListener('click', () => {+ const popup = window.open('about:blank', '_blank');+ if (!popup) { $('share-panel').hidden = false; $('share-status').textContent = 'Allow this view to open the GitHub sign-in window, then try again.'; return; }+ popup.opener = null;+ sharingTask = beginSharing(popup);+});+$('share-close')?.addEventListener('click', () => { sharingTask = closeSharing(); });+$('share-pair')?.addEventListener('click', () => {+ const popup = window.open('about:blank', '_blank');+ if (!popup) { $('share-status').textContent = 'Allow this view to open the device-pairing window, then try again.'; return; }+ popup.opener = null;+ sharingTask = pairSharing(popup);+});+let relayEngine = null;/** The account's linked boards: a same-origin read that declares the relay's engine, as every relay request does. */async function linkedList() {@@ -1497,6 +1623,7 @@ async function refresh(fresh = null) {}if (!snapshot) follow();$('live').textContent = snapshot ? 'read-only snapshot' : liveLine();+ sharingReady ??= sharingInvitation();}// The local view follows the shown boards' events instead of a timer (#545): it reads the board once, waits on itsdiff --git a/src/serve.js b/src/serve.jsindex 91fb7a77..583c9abb 100644--- a/src/serve.js+++ b/src/serve.js@@ -7,7 +7,7 @@* 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).+ * Idle reads open no outbound connection (P5); an explicit person sign-in reuses the existing relay linking flow.*/import { spawnSync } from 'node:child_process';import {@@ -58,6 +58,8 @@ import {} from './projects.js';import { fetchLocal } from './local-fetch.js';import { Refused } from './refused.js';+import { refusalDocument } from './json.js';+import { relayLinkAvailability } from './relay.js';import { personNeeds } from './needs.js';import { projectRowDecisions } from './row-decisions.js';import { loadSpec } from './spec.js';@@ -445,6 +447,9 @@ 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 { startViewSignIn, viewSignInStatus, viewSignInPairingNavigation, cancelViewSignIn } = await import('./relay-setup.js');+ const 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) => {@@ -463,6 +468,66 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('bres.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>');};+ /** The invitation is a local read: it neither signs in nor opens a relay connection. */+ function sharingAvailable() {+ if (projectRoot !== undefined) return false;+ const projects = listApiProjects();+ return projects.length > 0 && projects.every(project => {+ const state = relayLinkAvailability(project.root);+ return !state.linked && !state.unlinking;+ });+ }++ /** Read one bounded JSON object; no arbitrary CLI words or relay address enter this route. */+ async function sharingBody(req) {+ if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/iu.test(String(req.headers['content-type'] ?? ''))) {+ throw new Refused('VIEW_SIGN_IN_JSON', 'send a JSON object to this view');+ }+ let length = 0;+ const chunks = [];+ for await (const chunk of req) {+ length += chunk.length;+ if (length <= 4096) chunks.push(chunk);+ }+ if (length > 4096) throw new Refused('VIEW_SIGN_IN_JSON', 'send only the sign-in action and its intent id');+ let body;+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { /* Refuse below. */ }+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Refused('VIEW_SIGN_IN_JSON', 'send a JSON object to this view');+ return body;+ }++ /** 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) {+ 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 {+ if (req.method === 'GET') return json(res, 200, { version: 1, available: sharingAvailable() });+ if (req.method !== 'POST') return json(res, 405, refusalDocument(new Refused('VIEW_SIGN_IN_METHOD', 'use GET for the invitation or a JSON POST for sign-in')));+ if (projectRoot !== undefined) throw new Refused('VIEW_SIGN_IN_SCOPE', 'open the full machine view to link every registered board');+ const body = await sharingBody(req);+ if (body.action === 'start' && Object.keys(body).length === 1) {+ const instructions = await startViewSignIn({ signal: signInLifetime.signal });+ signIns.add(instructions.intentId);+ return json(res, 200, { version: 1, ...instructions });+ }+ if (!['status', 'cancel', 'pairing'].includes(body.action) || Object.keys(body).some(name => !['action', 'intentId'].includes(name))+ || !signIns.has(body.intentId)) throw new Refused('VIEW_SIGN_IN_UNKNOWN', 'start sign-in in this view before reading or stopping it');+ if (body.action === 'pairing') {+ const destination = viewSignInPairingNavigation(body.intentId).url.replace(/[&<>"']/gu, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]);+ return reply(res, 200, 'text/html; charset=utf-8', '<!doctype html><meta charset="utf-8"><a href="' + destination + '">Continue device pairing</a>');+ }+ const status = body.action === 'cancel' ? await cancelViewSignIn(body.intentId) : viewSignInStatus(body.intentId);+ // Names and reasons are public progress; machine paths remain on this computer.+ const boards = status.boards.map(({ root, ...board }) => board);+ return json(res, 200, { version: 1, ...status, boards });+ } catch (error) {+ const refusal = error instanceof Refused ? error : new Refused('VIEW_SIGN_IN_FAILED', 'sign-in could not finish; check this view and try again');+ return json(res, 400, refusalDocument(refusal));+ }+ }+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.@@ -476,7 +541,7 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('b// API refuses another Host in its own words.const isOwnHost = req.headers.host === `${LOOPBACK}:${bound}` || req.headers.host === `localhost:${bound}`;if (!isOwnHost) {- if (url.pathname.startsWith('/api/') && req.method !== 'OPTIONS') return apiHandler(req, res);+ if (url.pathname.startsWith('/api/') && url.pathname !== '/api/v1/view-link' && 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.@@ -515,6 +580,7 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('bif (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' });}+ if (url.pathname === '/api/v1/view-link') return sharingRequest(req, res, url);return apiHandler(req, res);}const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? url.searchParams.get('k') ?? ''));@@ -552,7 +618,17 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('bready({url: `http://${LOOPBACK}:${bound}/?k=${secret}`,port: bound,- close: () => new Promise((closed) => { apiHandler.close(); server.close(() => closed()); server.closeIdleConnections(); }),+ close: async () => {+ signInLifetime.abort();+ await Promise.all([...signIns].map(async intentId => {+ // An in-flight linking batch cannot be rolled back. Wait until core can cleanly stop its pairing stage.+ try {+ while (viewSignInStatus(intentId).state === 'linking') await new Promise(done => setTimeout(done, 100));+ await cancelViewSignIn(intentId);+ } catch (error) { if (!(error instanceof Refused) || error.code !== 'VIEW_SIGN_IN_UNKNOWN') throw error; }+ }));+ await new Promise((closed) => { apiHandler.close(); server.close(() => closed()); server.closeIdleConnections(); });+ },});});};diff --git a/test/cockpit/relay.test.js b/test/cockpit/relay.test.jsindex 07919e13..2199cd0c 100644--- a/test/cockpit/relay.test.js+++ b/test/cockpit/relay.test.js@@ -1,7 +1,7 @@/** Cockpit relay checks, using the shared real-board fixtures [N26]. */import assert from 'node:assert/strict';import { execFileSync, spawnSync } from 'node:child_process';-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { createServer, request } from 'node:http';import { tmpdir } from 'node:os';import { delimiter, join, relative, resolve, sep } from 'node:path';@@ -2088,3 +2088,183 @@ test('the star line shows once to a signed-in person and stays dismissed [N26]',await star.close().finally(() => rmSync(profile, { recursive: true, force: true }));}});+++test('the view links every board on this machine in one sign-in [H5,N26]', {+ timeout: relayWorkBudgetMs() * 12,+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async (t) => {+ for (const mode of ['linked', 'declined', 'closed', 'partial']) {+ await t.test(mode, async (scenario) => {+ const box = await relayClientFixture(scenario);+ box.providerState.deviceAuthorized = false;+ const module = (name) => new URL('../../src/' + name, import.meta.url).href;+ const fixtureModule = new URL('../fixture-child.js', import.meta.url).href;+ const prepared = await box.script(`+import assert from 'node:assert/strict';+import { mkdirSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { main } from ${JSON.stringify(module('cli.js'))};+import { updateRelayMachine } from ${JSON.stringify(module('relay-machine.js'))};+import { runFixtureGit } from ${JSON.stringify(fixtureModule)};+const other = join(dirname(${JSON.stringify(box.root)}), 'second-view-board');+mkdirSync(other);+for (const args of [['init','-q','-b','main'], ['-c','commit.gpgsign=false','commit','--allow-empty','-q','-m','chore: private view board']])+ runFixtureGit(args, {cwd:other,env:process.env});+if (${JSON.stringify(mode)} !== 'partial') runFixtureGit(['remote','add','origin','[email protected]:fixture/repository.git'], {cwd:other,env:process.env});+assert.equal(await main(['init','--json'], {cwd:other,stdin:process.stdin,stdout:{isTTY:false,write(){}},stderr:{write(){}}}),0);+updateRelayMachine(state => { state.owner = {account:'7',url:${JSON.stringify(box.origin)}}; });+process.stdout.write(JSON.stringify({other}));+`);+ assert.equal(prepared.code, 0, 'two private boards are registered through the real CLI');+ const links = [box.root, prepared.document.other].map(root => join(root, '.git/pullboard/relay.json'));+ assert.deepEqual(links.map(existsSync), [false, false]);+ let releasePoll;+ const held = new Promise(done => { releasePoll = done; });+ box.providerState.beforeDevicePoll = () => held;+ if (mode === 'declined') box.providerState.deviceDeclined = true;+ const local = await startView({dir:box.root,env:{...box.env,SSH_CONNECTION:'127.0.0.1 1 127.0.0.1 2'}}, {signal:scenario.signal});+ const chrome = await stableChrome(await startChrome());+ let cleaned = false;+ /** Close only resources owned by this scenario once, before its private relay is removed. */+ const cleanup = async () => { if (cleaned) return; cleaned = true; releasePoll?.(); await chrome.close(); await local.stop(); };+ scenario.after(cleanup);+ try {+ await chrome.navigate(local.link.href);+ await chrome.waitFor("!document.body.classList.contains('loading') && data?.projects?.length === 2");+ await chrome.stable("typeof sharingReady === 'undefined' ? null : sharingReady");+ assert.equal(await chrome.stable("document.querySelector('#share-note')?.hidden === false"), true,+ 'the real local view offers one quiet invitation before any board is linked');+ assert.equal(await chrome.stable("document.querySelector('#share-note')?.textContent.includes('See these boards from any device: link them to pullboard.dev')"), true);+ const starts = box.providerCalls.filter(call => call.path === '/login/device/code').length;+ await press(chrome, "document.querySelector('#share-start')");+ // The real GitHub popup hides this tab; foreground the owned view before measuring its progress.+ await chrome.send('Page.bringToFront');+ await chrome.stable('sharingTask');+ assert.equal(box.providerCalls.filter(call => call.path === '/login/device/code').length - starts, 1,+ 'one native person click starts exactly one real device sign-in for every board');+ assert.equal(await chrome.stable("document.querySelector('#share-status')?.textContent.includes('TEST-ONLY')"), true,+ 'the view displays the public GitHub code');+ if (mode === 'closed') {+ const targets = await chrome.send('Target.getTargets');+ const popup = targets.targetInfos.find(target => target.type === 'page' && target.url.endsWith('/login/device'));+ assert.ok(popup, 'the person sign-in opened in an actual browser page');+ await chrome.send('Target.closeTarget', {targetId:popup.targetId});+ await chrome.waitFor('sharing.closing === true');+ let closedState = null;+ const closed = chrome.stable('sharingTask.then(() => sharing.state)').then(state => { closedState = state; });+ const deadline = Date.now() + relayWorkBudgetMs();+ while (!box.calls.some(call => call.path === '/auth/device/cancel') && closedState === null) {+ assert.ok(Date.now() < deadline, 'closing the sign-in reaches its real cancellation request or a terminal result');+ await new Promise(done => setTimeout(done, 25));+ }+ if (closedState !== null) assert.equal(closedState, 'cancelled', 'closing waits for confirmed core cancellation');+ releasePoll();+ await closed;+ assert.equal(closedState, 'cancelled', 'closing finishes the actual core cancellation');+ } else releasePoll();+ if (mode === 'declined' || mode === 'closed') {+ await chrome.waitFor("sharing.state === 'declined' || sharing.state === 'cancelled'", relayWorkBudgetMs());+ assert.match(await chrome.stable("document.querySelector('#share-status').textContent"), /No boards were linked/u);+ assert.deepEqual(links.map(existsSync), [false, false], 'declining or closing the real sign-in links neither board');+ assert.equal(await chrome.stable("document.querySelector('#share-note').hidden"), false);+ } else {+ await chrome.waitFor("sharing.state === 'pairing' || sharing.state === 'done'", relayWorkBudgetMs() * 2);+ assert.deepEqual(links.map(existsSync), mode === 'linked' ? [true,true] : [true,false],+ 'the existing core flow links each authorized registered board');+ const text = await chrome.stable("document.querySelector('#share-status').textContent");+ assert.match(text, /Linked repo/u);+ if (mode === 'linked') assert.match(text, /Linked second-view-board/u);+ else assert.match(text, /Did not link second-view-board: .+/u, 'a refused board is named with its actual reason');+ assert.equal(await chrome.stable("document.querySelector('#share-note').hidden"), true, 'the invitation disappears after linking');+ await press(chrome, "document.querySelector('#share-close')");+ await chrome.stable('sharingTask');+ assert.deepEqual(links.map(existsSync), mode === 'linked' ? [true,true] : [true,false], 'stopping phone pairing preserves completed board links');+ }+ assert.equal(box.providerCalls.filter(call => call.path === '/login/device/code').length - starts, 1, 'no second board sign-in or retry occurred');+ assert.doesNotMatch(await chrome.stable("document.querySelector('#share-status').textContent"), /(?:ps_|pd_|pg_|pm_)[A-Za-z0-9_-]{20,}/u,+ 'the progress panel never exposes person, ticket or machine credentials');+ } finally { await cleanup(); }+ });+ }+});+++test('view sign-in keeps its key and intents inside the authenticated machine view [H5,N26]', { timeout: relayWorkBudgetMs() * 3 }, async (t) => {+ const box = await relayClientFixture(t);+ box.providerState.deviceAuthorized = false;+ const serveModule = new URL('../../src/serve.js', import.meta.url).href;+ const machineModule = new URL('../../src/relay-machine.js', import.meta.url).href;+ const result = await box.script(`+import { request } from 'node:http';+import { serveView, HOSTED_ORIGIN } from ${JSON.stringify(serveModule)};+import { updateRelayMachine } from ${JSON.stringify(machineModule)};+updateRelayMachine(state => { state.owner = {account:'7',url:${JSON.stringify(box.origin)}}; });+const observations = [];+/** Return only safe HTTP observations; the outer native test makes every assertion itself. */+function observe(actual, expected, why) { observations.push({actual,expected,why}); }+const key = 'private-view-sign-in-fixture';+const view = await serveView({secret:key});+const other = await serveView({secret:key});+const scoped = await serveView({secret:key,projectRoot:${JSON.stringify(box.root)}});+/** Send one real HTTP request with explicit Host, origin and header fields. */+function call(server, {method='GET', headers={}, body, query=''}={}) {+ const address = new URL('/api/v1/view-link'+query, server.url);+ return new Promise((resolve,reject) => {+ const req = request(address, {method,headers}, res => {+ const chunks=[];+ res.on('data', chunk => chunks.push(chunk));+ res.on('end', () => resolve({status:res.statusCode,headers:res.headers,body:JSON.parse(Buffer.concat(chunks).toString())}));+ });+ req.on('error',reject);+ req.end(body);+ });+}+const auth = {'x-pullboard-key':key};+const json = {...auth,'content-type':'application/json'};+try {+ for (const options of [{}, {query:'?k='+key}, {headers:auth,query:'?intentId=anything'},+ {headers:{...auth,origin:'https://foreign.invalid'}}, {headers:{...auth,host:'foreign.invalid'}}]) {+ observe((await call(view,options)).status,403,'a sign-in route needs its own Host/origin and a header-only key');+ }+ const invitation = await call(view,{headers:auth});+ observe(invitation.status,200);+ observe(invitation.body,{version:1,available:true},'the idle invitation exposes no board paths or credentials');+ const hosted = await call(view,{headers:{...auth,origin:HOSTED_ORIGIN}});+ observe(hosted.status,200,'the trusted hosted page can use the same local person channel');+ observe(hosted.headers['access-control-allow-origin'],HOSTED_ORIGIN);+ for (const [body,type] of [['action=start','text/plain'], ['[]','application/json'],+ ['{','application/json'], [JSON.stringify({action:'run'}),'application/json'],+ [JSON.stringify({action:'start',relayUrl:'https://foreign.invalid'}),'application/json'],+ [JSON.stringify({action:'status',intentId:'not-owned'}),'application/json'],+ [JSON.stringify({action:'start',padding:'x'.repeat(5000)}),'application/json']]) {+ observe((await call(view,{method:'POST',headers:{...auth,'content-type':type},body})).status,400,'only one bounded known JSON action is admitted');+ }+ observe((await call(view,{method:'PUT',headers:json,body:'{}'})).status,405);+ observe((await call(scoped,{headers:auth})).body,{version:1,available:false});+ const scope = await call(scoped,{method:'POST',headers:json,body:JSON.stringify({action:'start'})});+ observe(scope.status,400,'a one-project view cannot authorize every board on the machine');+ observe(scope.body.error.code,'VIEW_SIGN_IN_SCOPE');+ const started = await call(view,{method:'POST',headers:json,body:JSON.stringify({action:'start'})});+ observe(started.status,200);+ observe(Object.keys(started.body).sort(),['expiresAt','intentId','userCode','verificationURL','version']);+ const intentId = started.body.intentId;+ const foreign = await call(other,{method:'POST',headers:json,body:JSON.stringify({action:'status',intentId})});+ observe(foreign.status,400,'another view cannot read an operation it did not start');+ observe(foreign.body.error?.code,'VIEW_SIGN_IN_UNKNOWN');+ const status = await call(view,{method:'POST',headers:json,body:JSON.stringify({action:'status',intentId})});+ observe(status.body.state,'waiting');+ observe(status.body.boards,[]);+ observe(/(?:ps_|pd_|pg_|pm_)[A-Za-z0-9_-]{20,}/u.test(JSON.stringify(status.body)),false,'public status contains no person, ticket or machine credential');+ const cancelled = await call(view,{method:'POST',headers:json,body:JSON.stringify({action:'cancel',intentId})});+ observe(cancelled.body.state,'cancelled');+ observe(cancelled.body.boards,[]);+ process.stdout.write(JSON.stringify({observations}));+} finally { await scoped.close(); await other.close(); await view.close(); }+`);+ assert.equal(result.code,0,'the private real-HTTP view boundary script completes');+ assert.ok(result.document.observations.length >= 20, 'the private script returned every boundary observation');+ for (const {actual,expected,why} of result.document.observations) assert.deepEqual(actual,expected,why);+ assert.equal(box.providerCalls.filter(call => call.path === '/login/device/code').length,1,+ 'all refused requests and idle reads performed no sign-in; only the authenticated start did');+});