Files
pipelines/app/tool/capture/browser.mjs
T
alan 18807b8ac2 Clipboard on http: copy and paste work without the Clipboard API
Over plain http on a tailnet address the page is not a secure context and
navigator.clipboard is undefined, so the web engine refused every copy.
ClipboardReportingMessenger now answers clipboard calls through the
browser's legacy clipboard when the API is missing (web only, conditional
import): copy uses execCommand('copy') with a one-shot copy-event listener
(no focus or selection change); a paste key's Clipboard.getData takes the
browser's own paste event, the key reported not-handled so the browser
still fires it. A Paste button/menu says to use Ctrl+V or the https address.
Secure pages keep the engine path. Capture kit: --insecure and clipboard=.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:06:58 +00:00

123 lines
5.8 KiB
JavaScript

// Headless Chrome over the DevTools protocol: launch a private instance (fresh
// profile, remote debugging on an OS-assigned port) or attach to a running one
// via `--cdp http://127.0.0.1:<port>`. Either way the kit works in its own page
// target, and close() removes everything it created.
import { spawn } from 'node:child_process';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
const CALL_TIMEOUT_MS = 30000;
const DEFAULT_CHROME ='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
async function launch(chromePath, gpu, args = []) {
const profile = await mkdtemp(join(tmpdir(), 'pipelines-capture-chrome-'));
const chrome = spawn(chromePath, [
'--headless=new', '--no-first-run', '--no-default-browser-check',
// Without a GPU CanvasKit rasterises on the CPU; `gpu` keeps WebGL (Metal
// through ANGLE on a Mac) for benches that measure raster time.
// Linux keeps the GPU through ANGLE on Vulkan.
...(gpu ? [process.platform === 'darwin' ? '--use-angle=metal' : '--use-angle=vulkan',
...(process.platform === 'darwin' ? [] : ['--enable-features=Vulkan']),
'--enable-gpu-rasterization', '--ignore-gpu-blocklist'] : ['--disable-gpu']),
'--hide-scrollbars', '--mute-audio', ...args,
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '';
chrome.stderr.on('data', (d) => { stderr += d; });
const exited = new Promise((done) => chrome.once('exit', done));
const cleanup = async () => {
if (chrome.exitCode === null && chrome.signalCode === null) {
chrome.kill('SIGTERM');
const timedOut = await Promise.race([exited.then(() => false), delay(3000, true)]);
if (timedOut) { chrome.kill('SIGKILL'); await exited; }
}
await rm(profile, { recursive: true, force: true }).catch(() => {});
};
for (let i = 0; i < 150; i++) {
const ws = stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1];
if (ws) return { ws, cleanup };
if (chrome.exitCode !== null) break;
await delay(100);
}
await cleanup();
throw new Error(`Chrome did not start (${chromePath}): ${stderr.slice(-800)}`);
}
async function attach(cdp) {
const version = await (await fetch(new URL('/json/version', cdp))).json();
return { ws: version.webSocketDebuggerUrl, cleanup: async () => {} };
}
/**
* Opens a page target. Returns `{ send, on, close }`: `send(method, params)`
* talks to the page session; `on(method, fn)` subscribes to its events and
* returns the unsubscribe function; `newPage()` opens a scratch page.
*/
export async function openBrowser({ cdp, gpu = false, args = [], chromePath = process.env.CHROME_PATH ?? DEFAULT_CHROME } = {}) {
const { ws: endpoint, cleanup } = cdp ? await attach(cdp) : await launch(chromePath, gpu, args);
const ws = new WebSocket(endpoint);
try {
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = () => fail(new Error(`Cannot open ${endpoint}`)); });
} catch (error) { await cleanup(); throw error; }
let nextId = 0;
const pending = new Map();
const listeners = new Map();
let sessionId;
ws.onmessage = (event) => {
const m = JSON.parse(event.data);
if (m.id && pending.has(m.id)) {
const { ok, fail, method } = pending.get(m.id);
pending.delete(m.id);
return m.error ? fail(new Error(`${method}: ${m.error.message}`)) : ok(m.result ?? {});
}
if (m.method && m.sessionId === sessionId) for (const fn of listeners.get(m.method) ?? []) fn(m.params);
};
// Every call is bounded: an unresponsive page (for example a navigation to a
// server that never answers) fails the step instead of hanging the kit.
const raw = (method, params = {}, session) => new Promise((ok, fail) => {
const id = ++nextId;
const timer = setTimeout(() => {
pending.delete(id);
fail(new Error(`${method}: no reply within ${CALL_TIMEOUT_MS} ms`));
}, CALL_TIMEOUT_MS);
const settle = (fn) => (value) => { clearTimeout(timer); fn(value); };
pending.set(id, { ok: settle(ok), fail: settle(fail), method });
ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }));
});
let targetId;
try {
({ targetId } = await raw('Target.createTarget', { url: 'about:blank' }));
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
} catch (error) { ws.close(); await cleanup(); throw error; }
return {
send: (method, params) => raw(method, params, sessionId),
/** A browser-level call (no page session), e.g. `Browser.grantPermissions`. */
sendBrowser: (method, params) => raw(method, params),
on: (method, fn) => {
listeners.set(method, [...(listeners.get(method) ?? []), fn]);
return () => listeners.set(method, listeners.get(method).filter((f) => f !== fn));
},
/** Every open page target (tabs a link opened included): `{ url, type }`. */
targets: async () => (await raw('Target.getTargets')).targetInfos
.filter((t) => t.type === 'page').map((t) => ({ url: t.url, type: t.type })),
newPage: async () => {
const page = await raw('Target.createTarget', { url: 'about:blank' });
const { sessionId: sid } = await raw('Target.attachToTarget', { targetId: page.targetId, flatten: true });
return {
send: (method, params) => raw(method, params, sid),
targetId: page.targetId,
close: () => raw('Target.closeTarget', { targetId: page.targetId }).catch(() => {}),
};
},
/** Brings the kit's own page to the front again (after a scratch page). */
front: () => raw('Target.activateTarget', { targetId }),
close: async () => {
await raw('Target.closeTarget', { targetId }).catch(() => {});
ws.close();
await cleanup();
},
};
}