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(test): share Chrome startup and group cleanup [C7]

Corey Olsone23b53751815
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.js
new file mode 100644
index 00000000..68169df7
--- /dev/null
+++ b/test/chrome-fixture.js
@@ -0,0 +1,276 @@
+/** Shared isolated Chrome launcher with bounded startup and complete process-group cleanup [C7]. */
+import { spawn } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+const STARTUP_TIMEOUT_MS = 30_000;
+const COMMAND_TIMEOUT_MS = 15_000;
+const CLEANUP_TIMEOUT_MS = 5_000;
+const GROUP_POLL_MS = 20;
+const STDERR_LIMIT = 128 * 1024;
+
+/** Find an installed Chrome without making browser availability a product-test failure. */
+export function findChromeExecutable() {
+ return [process.env.PULLBOARD_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser']
+ .find((candidate) => candidate && existsSync(candidate));
+}
+
+/** Pause briefly while polling startup or process-group cleanup, without leaving a live timer behind. */
+function pause(ms) {
+ return new Promise((resolvePause) => setTimeout(resolvePause, ms));
+}
+
+/** Keep the most recent diagnostic bytes while continuously draining Chrome's stderr pipe. */
+function appendStderr(current, chunk) {
+ const next = current + chunk;
+ return next.length <= STDERR_LIMIT ? next : next.slice(-STDERR_LIMIT);
+}
+
+/** Report whether the detached process group still has any members. */
+function processGroupExists(pid) {
+ if (!pid) return false;
+ try { process.kill(-pid, 0); return true; }
+ catch (error) { return error?.code !== 'ESRCH'; }
+}
+
+/** Wait until a detached process group has no members, not merely until its leader exits. */
+async function waitForProcessGroupExit(pid, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ do {
+ if (!processGroupExists(pid)) return true;
+ if (Date.now() >= deadline) break;
+ await pause(Math.min(GROUP_POLL_MS, deadline - Date.now()));
+ } while (Date.now() <= deadline);
+ return !processGroupExists(pid);
+}
+
+/** Wait for the leader's close event with a finite bound after the whole group has exited. */
+async function waitForLeaderExit(stopped, timeoutMs) {
+ let timer;
+ const exited = await Promise.race([stopped.then(() => true), new Promise((resolveExit) => {
+ timer = setTimeout(() => resolveExit(false), timeoutMs);
+ })]);
+ clearTimeout(timer);
+ return exited;
+}
+
+/** Stop an owned detached process group and wait for every helper before its profile may be removed. */
+async function stopProcessGroup(child, stopped, timeoutMs = CLEANUP_TIMEOUT_MS) {
+ const pid = child?.pid;
+ if (!pid) {
+ if (!await waitForLeaderExit(stopped, timeoutMs)) throw new Error('Isolated Chrome did not close after cleanup.');
+ return;
+ }
+ if (processGroupExists(pid)) {
+ try { process.kill(-pid, 'SIGTERM'); } catch { /* The owned process group already exited. */ }
+ }
+ if (!await waitForProcessGroupExit(pid, timeoutMs)) {
+ try { process.kill(-pid, 'SIGKILL'); } catch { /* The owned process group already exited. */ }
+ if (!await waitForProcessGroupExit(pid, timeoutMs)) throw new Error('Isolated Chrome process group did not exit after cleanup.');
+ }
+ if (!await waitForLeaderExit(stopped, timeoutMs)) throw new Error('Isolated Chrome did not close after its process group exited.');
+}
+
+/** Launch an executable as a detached process group and retain its stderr and launch timing. */
+export function launchChromeProcess({ executable, args = [], env = process.env, cleanupTimeoutMs = CLEANUP_TIMEOUT_MS } = {}) {
+ if (!executable) throw new Error('Chrome was not found; install Chrome or set PULLBOARD_CHROME.');
+ const launchedAt = Date.now();
+ const child = spawn(executable, args, { detached: true, env, stdio: ['ignore', 'ignore', 'pipe'] });
+ let stderr = '';
+ let launchError = null;
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk) => { stderr = appendStderr(stderr, chunk); });
+ child.once('error', (error) => { launchError = error; });
+ const stopped = new Promise((resolveStopped) => child.once('close', resolveStopped));
+ let closePromise;
+ /** Stop this exact process group once; callers can inspect stderr and elapsed launch time. */
+ function close() {
+ closePromise ??= stopProcessGroup(child, stopped, cleanupTimeoutMs);
+ return closePromise;
+ }
+ return {
+ child,
+ stopped,
+ close,
+ get stderr() { return stderr; },
+ get launchError() { return launchError; },
+ get launchDurationMs() { return Date.now() - launchedAt; },
+ };
+}
+
+/** Start isolated Chrome and expose navigation and evaluation methods over its local DevTools port. */
+export async function startChrome({
+ url = 'about:blank',
+ executable = findChromeExecutable(),
+ profileDirectory,
+ startupTimeoutMs = STARTUP_TIMEOUT_MS,
+ commandTimeoutMs = COMMAND_TIMEOUT_MS,
+ cleanupTimeoutMs = CLEANUP_TIMEOUT_MS,
+ env = process.env,
+} = {}) {
+ if (!executable) throw new Error('Chrome was not found; install Chrome or set PULLBOARD_CHROME.');
+ const ownedProfile = !profileDirectory;
+ const profile = resolve(profileDirectory ?? mkdtempSync(join(tmpdir(), 'pullboard-chrome-')));
+ mkdirSync(profile, { recursive: true, mode: 0o700 });
+ chmodSync(profile, 0o700);
+ const args = ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
+ '--disable-background-networking', '--disable-sync', '--disable-extensions', '--no-proxy-server',
+ '--use-mock-keychain', '--password-store=basic', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'];
+ let launched;
+ let socket;
+ let id = 0;
+ const pending = new Map();
+ try {
+ launched = launchChromeProcess({ executable, args, env, cleanupTimeoutMs });
+ const deadline = Date.now() + startupTimeoutMs;
+ const port = await readDevToolsPort(profile, launched, deadline);
+ const target = await createPageTarget(port, deadline);
+ socket = await connectDevTools(target.webSocketDebuggerUrl, deadline);
+ const send = createSender(socket, pending, () => ++id, commandTimeoutMs);
+ const evaluate = createEvaluator(send);
+ let closed = false;
+ /** Navigate the existing isolated browser profile to a local or test-owned URL. */
+ async function navigate(nextUrl) {
+ await send('Page.navigate', { url: nextUrl });
+ }
+ /** Wait until a page expression becomes truthy before its command deadline. */
+ async function waitFor(expression, timeoutMs = commandTimeoutMs) {
+ const waitDeadline = Date.now() + timeoutMs;
+ while (Date.now() < waitDeadline) {
+ if (await evaluate(expression)) return;
+ await pause(50);
+ }
+ throw new Error('Browser condition did not arrive before its deadline.');
+ }
+ /** Close once; remove an owned profile only after the full Chrome process group is gone. */
+ async function close() {
+ if (closed) return;
+ closed = true;
+ try { socket.close(); } catch { /* The DevTools socket already closed. */ }
+ rejectPending(pending, 'Isolated Chrome closed before a command completed.');
+ await launched.close();
+ if (ownedProfile) rmSync(profile, { recursive: true, force: true });
+ }
+ await send('Page.enable');
+ await send('Runtime.enable');
+ await send('Page.navigate', { url });
+ const launchDurationMs = launched.launchDurationMs;
+ process.stderr.write(`Chrome ready in ${launchDurationMs}ms (${startupTimeoutMs}ms DevTools budget)\n`);
+ return {
+ profileDirectory: profile,
+ launchDurationMs,
+ get stderr() { return launched.stderr; },
+ navigate,
+ evaluate,
+ waitFor,
+ send,
+ close,
+ };
+ } catch (error) {
+ socket?.close();
+ rejectPending(pending, 'Isolated Chrome stopped before startup completed.');
+ const launchDurationMs = launched?.launchDurationMs ?? 0;
+ const stderr = launched?.stderr?.trimEnd();
+ let cleanupFailure = null;
+ try { await launched?.close(); }
+ catch (cleanupError) { cleanupFailure = cleanupError; }
+ if (!cleanupFailure && ownedProfile) rmSync(profile, { recursive: true, force: true });
+ const message = sanitizeStartupError(error);
+ const cleanup = cleanupFailure ? `\n${cleanupFailure.message}; profile retained until the process group exits` : '';
+ throw new Error(`${message.message} (elapsed ${launchDurationMs}ms; ${startupTimeoutMs}ms DevTools budget)${stderr ? `\nChrome stderr:\n${stderr}` : ''}${cleanup}`);
+ }
+}
+
+/** Read Chrome's ephemeral debugging port and stop waiting when its leader exits or deadline passes. */
+async function readDevToolsPort(profile, launched, deadline) {
+ while (Date.now() < deadline) {
+ try {
+ const port = Number(readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0]);
+ if (Number.isInteger(port) && port > 0 && port <= 65_535) return port;
+ } catch { /* Chrome has not published the local DevTools port yet. */ }
+ if (launched.launchError) throw new Error('Isolated Chrome could not start.');
+ if (launched.child.exitCode !== null || launched.child.signalCode !== null) throw new Error('Isolated Chrome exited during startup.');
+ await pause(50);
+ }
+ throw new Error('Isolated Chrome did not publish its DevTools port.');
+}
+
+/** Create one blank page target without exceeding the shared startup deadline. */
+async function createPageTarget(port, deadline) {
+ const remaining = Math.max(1, deadline - Date.now());
+ const response = await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, {
+ method: 'PUT', signal: AbortSignal.timeout(remaining),
+ });
+ if (!response.ok) throw new Error('Isolated Chrome did not create a page target.');
+ const target = await response.json();
+ if (typeof target.webSocketDebuggerUrl !== 'string') throw new Error('Isolated Chrome returned no page target.');
+ return target;
+}
+
+/** Open the local DevTools WebSocket without echoing its URL or response data. */
+async function connectDevTools(debuggerUrl, deadline) {
+ const socket = new WebSocket(debuggerUrl);
+ await new Promise((resolveOpen, rejectOpen) => {
+ const remaining = Math.max(1, deadline - Date.now());
+ const timer = setTimeout(() => rejectOpen(new Error('DevTools socket did not open.')), remaining);
+ socket.addEventListener('open', () => { clearTimeout(timer); resolveOpen(); }, { once: true });
+ socket.addEventListener('error', () => { clearTimeout(timer); rejectOpen(new Error('DevTools socket failed.')); }, { once: true });
+ });
+ return socket;
+}
+
+/** Create a CDP command sender that correlates responses and bounds every request. */
+function createSender(socket, pending, nextId, timeoutMs) {
+ /** Resolve or reject the request matching one CDP response without logging its payload. */
+ function onMessage(event) {
+ let message;
+ try { message = JSON.parse(String(event.data)); } catch { return; }
+ const waiter = pending.get(message.id);
+ if (!waiter) return;
+ pending.delete(message.id);
+ clearTimeout(waiter.timer);
+ if (message.error) waiter.reject(new Error(`DevTools command failed: ${waiter.method}.`));
+ else waiter.resolve(message.result);
+ }
+ socket.addEventListener('message', onMessage);
+ return (method, params = {}) => new Promise((resolveResult, rejectResult) => {
+ const requestId = nextId();
+ const timer = setTimeout(() => {
+ pending.delete(requestId);
+ rejectResult(new Error(`DevTools command timed out: ${method}.`));
+ }, timeoutMs);
+ pending.set(requestId, { resolve: resolveResult, reject: rejectResult, timer, method });
+ try { socket.send(JSON.stringify({ id: requestId, method, params })); }
+ catch {
+ clearTimeout(timer);
+ pending.delete(requestId);
+ rejectResult(new Error(`DevTools command could not be sent: ${method}.`));
+ }
+ });
+}
+
+/** Evaluate a page expression by value, without including page content in failures. */
+function createEvaluator(send) {
+ return async (expression) => {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+ if (result.exceptionDetails) throw new Error('Browser evaluation failed.');
+ return result.result?.value;
+ };
+}
+
+/** Reject outstanding CDP requests during close or startup failure without exposing payloads. */
+function rejectPending(pending, message) {
+ for (const waiter of pending.values()) {
+ clearTimeout(waiter.timer);
+ waiter.reject(new Error(message));
+ }
+ pending.clear();
+}
+
+/** Replace implementation-specific startup errors with safe diagnostic text. */
+function sanitizeStartupError(error) {
+ if (error instanceof Error && /Chrome|DevTools|page target/.test(error.message)) return error;
+ return new Error('Isolated Chrome could not start or connect to its local DevTools endpoint.');
+}
diff --git a/test/chrome-fixture.test.js b/test/chrome-fixture.test.js
new file mode 100644
index 00000000..6a5fbf02
--- /dev/null
+++ b/test/chrome-fixture.test.js
@@ -0,0 +1,110 @@
+/** The shared Chrome fixture bounds startup and removes profiles only after the owned process group exits [C7]. */
+import assert from 'node:assert/strict';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { launchChromeProcess, startChrome } from './chrome-fixture.js';
+
+/** Pause between checks while waiting for a fixture helper's readiness marker. */
+function pause(ms) {
+ return new Promise((resolvePause) => setTimeout(resolvePause, ms));
+}
+
+/** Wait a finite time for a private marker, reporting only its fixture path on timeout. */
+async function waitForFile(path, timeoutMs = 5_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (existsSync(path)) return;
+ await pause(20);
+ }
+ assert.fail(`stand-in Chrome did not create its readiness marker: ${path}`);
+}
+
+/** Create an executable stand-in that writes after its leader exits, keeping both in one process group. */
+function delayedHelperScripts(profile) {
+ const helperReady = join(profile, 'helper-ready');
+ const lateWrite = join(profile, 'helper-finished');
+ const helper = [
+ "const fs = require('node:fs');",
+ 'const [ready, late] = process.argv.slice(1);',
+ "process.on('SIGTERM', () => { setTimeout(() => { fs.writeFileSync(late, 'finished'); process.exit(0); }, 1500); });",
+ "fs.writeFileSync(ready, 'ready');",
+ 'setInterval(() => {}, 1000);',
+ ].join('\n');
+ const leader = [
+ "const { spawn } = require('node:child_process');",
+ "const fs = require('node:fs');",
+ 'const [profile, helperCode] = process.argv.slice(1);',
+ "process.on('SIGTERM', () => process.exit(0));",
+ "spawn(process.execPath, ['-e', helperCode, profile + '/helper-ready', profile + '/helper-finished'], { stdio: 'ignore' });",
+ "fs.writeFileSync(profile + '/leader-ready', 'ready');",
+ 'setInterval(() => {}, 1000);',
+ ].join('\n');
+ return { helperReady, lateWrite, leader, helper };
+}
+
+/** Prove close waits for a surviving process-group helper before a single profile removal. */
+test('removes the profile only after every Chrome process exits [C7]', async (t) => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-chrome-group-'));
+ const profile = join(directory, 'profile');
+ mkdirSync(profile, { mode: 0o700 });
+ let removed = false;
+ let chrome;
+ t.after(async () => {
+ try { await chrome?.close(); }
+ finally {
+ // A deliberately broken close must not leave the stand-in helper alive.
+ const pid = chrome?.child.pid;
+ if (pid) {
+ try { process.kill(-pid, 'SIGKILL'); } catch { /* The owned fixture group is already gone. */ }
+ const deadline = Date.now() + 5_000;
+ while (Date.now() < deadline) {
+ try { process.kill(-pid, 0); } catch (error) { if (error.code === 'ESRCH') break; }
+ await pause(20);
+ }
+ }
+ }
+ if (!removed) rmSync(profile, { recursive: true, force: true });
+ rmSync(directory, { recursive: true, force: true });
+ });
+
+ const scripts = delayedHelperScripts(profile);
+ chrome = launchChromeProcess({ executable: process.execPath, args: ['-e', scripts.leader, profile, scripts.helper] });
+ await waitForFile(scripts.helperReady);
+ const closedAt = Date.now();
+ await chrome.close();
+ assert.ok(Date.now() - closedAt >= 1_300, 'close waited while the helper kept writing after the leader exited');
+ assert.equal(readFileSync(scripts.lateWrite, 'utf8'), 'finished', 'the helper finished its delayed profile write');
+ assert.doesNotThrow(() => rmSync(profile, { recursive: true }), 'one profile removal succeeds after the group is empty');
+ removed = true;
+});
+
+/** Prove a missing DevTools port is a single diagnostic failure, with stderr and elapsed time. */
+test('a missing DevTools port fails once with stderr and elapsed launch time [C7]', async (t) => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-chrome-no-port-'));
+ const launches = join(directory, 'launches');
+ const wrapper = join(directory, 'chrome-no-port');
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ writeFileSync(wrapper, [
+ '#!/usr/bin/env node',
+ "const fs = require('node:fs');",
+ "fs.appendFileSync(process.env.CHROME_LAUNCHES, 'launch\\n');",
+ "process.stderr.write('NO_PORT_STAND_IN_STDERR\\n');",
+ "process.on('SIGTERM', () => process.exit(0));",
+ 'setInterval(() => {}, 1000);',
+ ].join('\n'));
+ chmodSync(wrapper, 0o700);
+
+ await assert.rejects(startChrome({
+ executable: wrapper,
+ env: { ...process.env, CHROME_LAUNCHES: launches },
+ }), (error) => {
+ assert.match(error.message, /did not publish its DevTools port/u);
+ assert.match(error.message, /elapsed \d+ms; 30000ms DevTools budget/u);
+ assert.ok(Number(/elapsed (\d+)ms/u.exec(error.message)[1]) >= 30_000, 'the stand-in exercised the actual default startup budget');
+ assert.match(error.message, /NO_PORT_STAND_IN_STDERR/u);
+ return true;
+ });
+ assert.equal(readFileSync(launches, 'utf8'), 'launch\n', 'the shared launcher never retries');
+});
diff --git a/test/relay-browser-fixture.js b/test/relay-browser-fixture.js
index c6184c69..36e82240 100644
--- a/test/relay-browser-fixture.js
+++ b/test/relay-browser-fixture.js
@@ -1,208 +1,2 @@
-/** Reusable real headless Chrome fixture for local relay browser tests. */
-import { spawn } from 'node:child_process';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join, resolve } from 'node:path';
-
-const STARTUP_TIMEOUT_MS = 10_000;
-const COMMAND_TIMEOUT_MS = 15_000;
-const CLEANUP_TIMEOUT_MS = 5_000;
-
-/** Find an installed Chrome without making browser availability a product-test failure. */
-export function findChromeExecutable() {
- return [process.env.PULLBOARD_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser']
- .find((candidate) => candidate && existsSync(candidate));
-}
-
-/** Pause briefly while polling Chrome startup, without leaving a live timer behind. */
-function pause(ms) {
- return new Promise((resolvePause) => setTimeout(resolvePause, ms));
-}
-
-/** Wait for the owned Chrome process to exit, bounding and clearing the timeout either way. */
-async function waitForExit(stopped, timeoutMs) {
- let timer;
- const exited = await Promise.race([stopped.then(() => true), new Promise((resolveExit) => {
- timer = setTimeout(() => resolveExit(false), timeoutMs);
- })]);
- clearTimeout(timer);
- return exited;
-}
-
-/** Stop only a Chrome process group created by this fixture. */
-async function stopOwnedChrome(child, stopped) {
- if (!child.pid || await waitForExit(stopped, 0)) return;
- try { process.kill(-child.pid, 'SIGTERM'); } catch { /* The owned browser already exited. */ }
- if (await waitForExit(stopped, CLEANUP_TIMEOUT_MS)) return;
- try { process.kill(-child.pid, 'SIGKILL'); } catch { /* The owned browser already exited. */ }
- if (!await waitForExit(stopped, CLEANUP_TIMEOUT_MS)) throw new Error('Isolated Chrome did not exit after cleanup.');
-}
-
-/** Start isolated Chrome and expose safe navigation and evaluation methods over CDP. */
-export async function startChrome({ url = 'about:blank', executable = findChromeExecutable(), profileDirectory } = {}) {
- if (!executable) throw new Error('Chrome was not found; install Chrome or set PULLBOARD_CHROME.');
- const ownedProfile = !profileDirectory;
- const profile = resolve(profileDirectory ?? mkdtempSync(join(tmpdir(), 'pullboard-relay-chrome-')));
- mkdirSync(profile, { recursive: true, mode: 0o700 });
- chmodSync(profile, 0o700);
- const args = ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
- '--disable-background-networking', '--disable-sync', '--disable-extensions', '--no-proxy-server',
- '--use-mock-keychain', '--password-store=basic', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'];
- let child;
- let stopped;
- let port;
- let socket;
- let id = 0;
- const pending = new Map();
- try {
- for (let attempt = 0; attempt < 2; attempt += 1) {
- if (attempt > 0) rmSync(join(profile, 'DevToolsActivePort'), { force: true });
- child = spawn(executable, args, { detached: true, stdio: ['ignore', 'ignore', 'ignore'] });
- stopped = new Promise((resolveStopped) => child.once('close', resolveStopped));
- let startupFailed = false;
- child.once('error', () => { startupFailed = true; });
- try {
- port = await readDevToolsPort(profile, child, () => startupFailed);
- break;
- } catch (error) {
- await stopOwnedChrome(child, stopped);
- if (attempt === 1) throw error;
- }
- }
- const target = await createPageTarget(port);
- socket = await connectDevTools(target.webSocketDebuggerUrl);
- const send = createSender(socket, pending, () => ++id);
- const evaluate = createEvaluator(send);
- let closed = false;
- /** Navigate the existing isolated browser profile to a local or test-owned URL. */
- async function navigate(nextUrl) {
- await send('Page.navigate', { url: nextUrl });
- }
- /** Wait until a page expression becomes truthy before its deadline. */
- async function waitFor(expression, timeoutMs = COMMAND_TIMEOUT_MS) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- if (await evaluate(expression)) return;
- await pause(50);
- }
- throw new Error('Browser condition did not arrive before its deadline.');
- }
- /** Close this browser once, stop only its process group, and remove owned profile data. */
- async function close() {
- if (closed) return;
- closed = true;
- try { socket.close(); } catch { /* The DevTools socket already closed. */ }
- rejectPending(pending, 'Isolated Chrome closed before a command completed.');
- try {
- await stopOwnedChrome(child, stopped);
- } finally {
- if (ownedProfile) rmSync(profile, { recursive: true, force: true });
- }
- }
- await send('Page.enable');
- await send('Runtime.enable');
- await send('Page.navigate', { url });
- return { profileDirectory: profile, navigate, evaluate, waitFor, send, close };
- } catch (error) {
- socket?.close();
- rejectPending(pending, 'Isolated Chrome stopped before startup completed.');
- try {
- if (child && stopped) await stopOwnedChrome(child, stopped);
- } finally {
- if (ownedProfile) rmSync(profile, { recursive: true, force: true });
- }
- throw sanitizeStartupError(error);
- }
-}
-
-/** Read Chrome's ephemeral debugging port and fail safely if the child exits early. */
-async function readDevToolsPort(profile, child, hasStartupFailed) {
- const deadline = Date.now() + STARTUP_TIMEOUT_MS;
- while (Date.now() < deadline) {
- try {
- const port = Number(readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0]);
- if (Number.isInteger(port) && port > 0 && port <= 65_535) return port;
- } catch { /* Chrome has not published the local DevTools port yet. */ }
- if (hasStartupFailed()) throw new Error('Isolated Chrome could not start.');
- if (child.exitCode !== null || child.signalCode !== null) throw new Error('Isolated Chrome exited during startup.');
- await pause(50);
- }
- throw new Error('Isolated Chrome did not publish its DevTools port.');
-}
-
-/** Create one blank page target without exposing browser URLs in diagnostics. */
-async function createPageTarget(port) {
- const response = await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, {
- method: 'PUT', signal: AbortSignal.timeout(STARTUP_TIMEOUT_MS),
- });
- if (!response.ok) throw new Error('Isolated Chrome did not create a page target.');
- const target = await response.json();
- if (typeof target.webSocketDebuggerUrl !== 'string') throw new Error('Isolated Chrome returned no page target.');
- return target;
-}
-
-/** Open the local DevTools WebSocket without echoing its URL or response data. */
-async function connectDevTools(debuggerUrl) {
- const socket = new WebSocket(debuggerUrl);
- await new Promise((resolveOpen, rejectOpen) => {
- const timer = setTimeout(() => rejectOpen(new Error('DevTools socket did not open.')), STARTUP_TIMEOUT_MS);
- socket.addEventListener('open', () => { clearTimeout(timer); resolveOpen(); }, { once: true });
- socket.addEventListener('error', () => { clearTimeout(timer); rejectOpen(new Error('DevTools socket failed.')); }, { once: true });
- });
- return socket;
-}
-
-/** Create a CDP command sender that correlates responses and bounds every request. */
-function createSender(socket, pending, nextId) {
- /** Resolve or reject the request matching one CDP response without logging its payload. */
- function onMessage(event) {
- let message;
- try { message = JSON.parse(String(event.data)); } catch { return; }
- const waiter = pending.get(message.id);
- if (!waiter) return;
- pending.delete(message.id);
- clearTimeout(waiter.timer);
- if (message.error) waiter.reject(new Error(`DevTools command failed: ${waiter.method}.`));
- else waiter.resolve(message.result);
- }
- socket.addEventListener('message', onMessage);
- return (method, params = {}) => new Promise((resolveResult, rejectResult) => {
- const requestId = nextId();
- const timer = setTimeout(() => {
- pending.delete(requestId);
- rejectResult(new Error(`DevTools command timed out: ${method}.`));
- }, COMMAND_TIMEOUT_MS);
- pending.set(requestId, { resolve: resolveResult, reject: rejectResult, timer, method });
- try { socket.send(JSON.stringify({ id: requestId, method, params })); }
- catch {
- clearTimeout(timer);
- pending.delete(requestId);
- rejectResult(new Error(`DevTools command could not be sent: ${method}.`));
- }
- });
-}
-
-/** Evaluate a page expression by value, without including page content in failures. */
-function createEvaluator(send) {
- return async (expression) => {
- const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
- if (result.exceptionDetails) throw new Error('Browser evaluation failed.');
- return result.result?.value;
- };
-}
-
-/** Reject outstanding CDP requests during close or startup failure without exposing payloads. */
-function rejectPending(pending, message) {
- for (const waiter of pending.values()) {
- clearTimeout(waiter.timer);
- waiter.reject(new Error(message));
- }
- pending.clear();
-}
-
-/** Replace implementation-specific startup errors with a diagnostic that cannot leak a URL. */
-function sanitizeStartupError(error) {
- if (error instanceof Error && /Chrome|DevTools|page target/.test(error.message)) return error;
- return new Error('Isolated Chrome could not start or connect to its local DevTools endpoint.');
-}
+/** Keep relay tests on the shared launcher while preserving their established local import path [C7]. */
+export { findChromeExecutable, startChrome } from './chrome-fixture.js';
diff --git a/test/relay-browser.test.js b/test/relay-browser.test.js
index ef29d4e1..6d7e8858 100644
--- a/test/relay-browser.test.js
+++ b/test/relay-browser.test.js
@@ -40,28 +40,20 @@ ${launch}
return { wrapper, counter };
}
-test('relay fixture relaunches once when Chrome does not publish a DevTools port [H5]', {
- skip: !findChromeExecutable() && 'Chrome is not installed',
-}, async t => {
+test('relay fixture fails once when Chrome exits during startup [C7]', async t => {
const directory = mkdtempSync(join(tmpdir(), 'pullboard-relay-relaunch-'));
- let chrome;
- t.after(async () => {
- await chrome?.close();
- rmSync(directory, { recursive: true, force: true });
- });
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
const { wrapper, counter } = writeLaunchWrapper(directory, { chrome: findChromeExecutable() });
- await assert.doesNotReject((async () => { chrome = await startChrome({ executable: wrapper }); })(),
- 'the fixture retries once after the first launch fails');
- assert.equal(await chrome.evaluate('1 + 1'), 2, 'the second real browser reaches its local DevTools endpoint');
- assert.equal(Number(readFileSync(counter, 'utf8')), 2, 'the wrapper launched once unsuccessfully and once successfully');
+ await assert.rejects(startChrome({ executable: wrapper }), /exited during startup/u);
+ assert.equal(Number(readFileSync(counter, 'utf8')), 1, 'the relay fixture never retries a failed Chrome launch');
});
-test('relay fixture keeps the startup refusal after its second failed launch [H5]', async t => {
+test('relay fixture reports its first failed launch [C7]', async t => {
const directory = mkdtempSync(join(tmpdir(), 'pullboard-relay-failure-'));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const { wrapper, counter } = writeLaunchWrapper(directory, { failEveryLaunch: true });
- await assert.rejects(startChrome({ executable: wrapper }), /Isolated Chrome exited during startup\./u);
- assert.equal(Number(readFileSync(counter, 'utf8')), 2, 'a second failure does not trigger a third launch');
+ await assert.rejects(startChrome({ executable: wrapper }), /exited during startup/u);
+ assert.equal(Number(readFileSync(counter, 'utf8')), 1, 'one startup failure means exactly one browser launch');
});
/** Reserve and release an ephemeral loopback port so the wrapper can publish an unavailable endpoint. */
@@ -76,7 +68,7 @@ async function unusedLoopbackPort() {
return port;
}
-test('relay fixture does not relaunch after Chrome publishes its DevTools port [H5]', async t => {
+test('relay fixture does not retry after Chrome publishes an unavailable DevTools port [C7]', async t => {
const directory = mkdtempSync(join(tmpdir(), 'pullboard-relay-target-'));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const { wrapper, counter } = writeLaunchWrapper(directory, { publishPort: await unusedLoopbackPort() });
diff --git a/test/seal.test.js b/test/seal.test.js
index eb3b0e5d..fc3818d7 100644
--- a/test/seal.test.js
+++ b/test/seal.test.js
@@ -1,13 +1,14 @@
/** Device-side sealing is the same bytes and WebCrypto code in Node and Chrome (H15, H17). */
import assert from 'node:assert/strict';
-import { spawn, spawnSync } from 'node:child_process';
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { test } from 'node:test';
import { decodeBoardKey, encodeBoardKey, generateBoardKey, seal, SEAL_VERSION, unseal } from '../src/seal.js';
+import { findChromeExecutable, startChrome } from './chrome-fixture.js';
const BOARD = '0123456789abcdef0123456789abcdef';
const TEXT = new TextEncoder().encode('A private board payload: \u03bb \ud83d\udd12');
@@ -169,50 +170,8 @@ test('sealing validates inputs and copies mutable buffers and binding before awa
assert.deepEqual(await decoding, TEXT);
});
-/** Find an installed browser, with an explicit override for other supported host layouts. */
-function chromeExecutable() {
- return [process.env.PULLBOARD_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser']
- .find((path) => path && existsSync(path));
-}
-
-/** Await a browser callback, then stop only our isolated process group, without exposing output. */
-async function chromeRun(executable, url, profile, resultReady) {
- // Use the temporary profile and mock keychain; the test must never reach a person's credentials.
- const child = spawn(executable, ['--headless', '--disable-gpu', '--user-data-dir=' + profile,
- '--no-first-run', '--no-default-browser-check', '--disable-background-networking',
- '--disable-sync', '--disable-extensions', '--no-proxy-server', '--use-mock-keychain',
- '--password-store=basic', url],
- { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
- child.stdout.resume();
- child.stderr.resume();
- let timer;
- const stopped = new Promise((resolve) => child.once('close', resolve));
- try {
- await Promise.race([resultReady, new Promise((resolve, reject) => {
- timer = setTimeout(() => reject(new Error('Isolated Chrome did not report within 30 seconds.')), 30_000);
- child.once('error', () => reject(new Error('Isolated Chrome could not start.')));
- child.once('close', () => reject(new Error('Isolated Chrome exited before its interoperability result.')));
- })]);
- } finally {
- clearTimeout(timer);
- if (child.pid) {
- try { process.kill(-child.pid, 'SIGTERM'); } catch { /* Our process group already exited. */ }
- }
- let cleanupTimer;
- const exited = await Promise.race([stopped.then(() => true), new Promise((resolve) => {
- cleanupTimer = setTimeout(() => resolve(false), 5000);
- })]);
- clearTimeout(cleanupTimer);
- if (!exited && child.pid) {
- try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Our process group already exited. */ }
- }
- await stopped;
- }
-}
-
test('headless Chrome loads the unchanged module and exchanges sealed bytes with Node [H15,H17]', { timeout: 60_000 }, async (t) => {
- const executable = chromeExecutable();
+ const executable = findChromeExecutable();
if (!executable) return t.skip('Install Chrome or set PULLBOARD_CHROME to run the browser interoperability proof.');
const key = await generateBoardKey();
const fixtures = [];
@@ -222,8 +181,6 @@ test('headless Chrome loads the unchanged module and exchanges sealed bytes with
}
let browserResult;
const requests = new Set();
- let reportReady;
- const resultReady = new Promise((resolve) => { reportReady = resolve; });
const html = '<!doctype html><body data-seal-result="pending"><script type="module">' +
'import {decodeBoardKey,seal,unseal} from "/seal.js";' +
'try {const f=await (await fetch("/fixture")).json();const key=decodeBoardKey(f.key);const replies=[];' +
@@ -248,18 +205,20 @@ test('headless Chrome loads the unchanged module and exchanges sealed bytes with
if (req.url === '/result' && req.method === 'POST') {
let body = '';
req.on('data', (part) => { body += part; });
- req.on('end', () => { try { browserResult = JSON.parse(body); } catch { browserResult = null; } res.end('{}'); reportReady(); });
+ req.on('end', () => { try { browserResult = JSON.parse(body); } catch { browserResult = null; } res.end('{}'); });
return;
}
res.writeHead(404); res.end();
});
const profile = mkdtempSync(join(tmpdir(), 'pullboard-seal-chrome-'));
+ let chrome;
try {
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
- await chromeRun(executable, 'http://127.0.0.1:' + server.address().port + '/', profile, resultReady);
- } catch {
- assert.fail('Chrome interoperability failed; requested fixture routes: ' + [...requests].sort().join(', '));
+ chrome = await startChrome({ executable, profileDirectory: profile, url: 'http://127.0.0.1:' + server.address().port + '/' });
+ await chrome.waitFor("document.body.dataset.sealResult === 'pass'", 30_000);
+ } catch (error) {
+ assert.fail(`Chrome interoperability failed; requested fixture routes: ${[...requests].sort().join(', ')}; ${error.message}`);
}
assert.equal(browserResult?.length, 3, 'Chrome must return all three sealed kinds');
for (let index = 0; index < fixtures.length; index++) {
@@ -267,6 +226,7 @@ test('headless Chrome loads the unchanged module and exchanges sealed bytes with
assert.deepEqual(await unseal(key, new Uint8Array(browserResult[index].blob), fixtures[index].binding), TEXT);
}
} finally {
+ await chrome?.close();
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
rmSync(profile, { recursive: true, force: true });