@parhelia/capture 0.0.0-stage → 0.4.12893

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +83 -2
  2. package/dist/browserHost.d.ts +19 -0
  3. package/dist/browserHost.d.ts.map +1 -0
  4. package/dist/browserHost.js +247 -0
  5. package/dist/browserHostLink.d.ts +50 -0
  6. package/dist/browserHostLink.d.ts.map +1 -0
  7. package/dist/browserHostLink.js +193 -0
  8. package/dist/browserHostProtocol.d.ts +61 -0
  9. package/dist/browserHostProtocol.d.ts.map +1 -0
  10. package/dist/browserHostProtocol.js +29 -0
  11. package/dist/cli.d.ts +3 -0
  12. package/dist/cli.d.ts.map +1 -0
  13. package/dist/cli.js +239 -0
  14. package/dist/cmsJob.d.ts +38 -0
  15. package/dist/cmsJob.d.ts.map +1 -0
  16. package/dist/cmsJob.js +218 -0
  17. package/dist/egressProxy.d.ts +59 -0
  18. package/dist/egressProxy.d.ts.map +1 -0
  19. package/dist/egressProxy.js +205 -0
  20. package/dist/index.d.ts +11 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +10 -0
  23. package/dist/install/doctor.d.ts +31 -0
  24. package/dist/install/doctor.d.ts.map +1 -0
  25. package/dist/install/doctor.js +189 -0
  26. package/dist/install/install.d.ts +72 -0
  27. package/dist/install/install.d.ts.map +1 -0
  28. package/dist/install/install.js +267 -0
  29. package/dist/install/layout.d.ts +81 -0
  30. package/dist/install/layout.d.ts.map +1 -0
  31. package/dist/install/layout.js +77 -0
  32. package/dist/install/services.d.ts +16 -0
  33. package/dist/install/services.d.ts.map +1 -0
  34. package/dist/install/services.js +94 -0
  35. package/dist/install/sys.d.ts +91 -0
  36. package/dist/install/sys.d.ts.map +1 -0
  37. package/dist/install/sys.js +260 -0
  38. package/dist/install/units.d.ts +57 -0
  39. package/dist/install/units.d.ts.map +1 -0
  40. package/dist/install/units.js +244 -0
  41. package/dist/install/updater.d.ts +66 -0
  42. package/dist/install/updater.d.ts.map +1 -0
  43. package/dist/install/updater.js +111 -0
  44. package/dist/install/versions.d.ts +61 -0
  45. package/dist/install/versions.d.ts.map +1 -0
  46. package/dist/install/versions.js +204 -0
  47. package/dist/isolation.d.ts +76 -0
  48. package/dist/isolation.d.ts.map +1 -0
  49. package/dist/isolation.js +163 -0
  50. package/dist/parheliaClient.d.ts +97 -0
  51. package/dist/parheliaClient.d.ts.map +1 -0
  52. package/dist/parheliaClient.js +111 -0
  53. package/dist/version.d.ts +13 -0
  54. package/dist/version.d.ts.map +1 -0
  55. package/dist/version.js +36 -0
  56. package/dist/webIsolation.d.ts +24 -0
  57. package/dist/webIsolation.d.ts.map +1 -0
  58. package/dist/webIsolation.js +112 -0
  59. package/dist/webJob.d.ts +56 -0
  60. package/dist/webJob.d.ts.map +1 -0
  61. package/dist/webJob.js +177 -0
  62. package/dist/worker.d.ts +53 -0
  63. package/dist/worker.d.ts.map +1 -0
  64. package/dist/worker.js +213 -0
  65. package/package.json +28 -4
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @parhelia/capture
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Parhelia's capture sidecar: real Chromium screenshots and DOM captures of CMS pages for agents, without an editor open in
4
+ anyone's browser. It long-polls Parhelia outbound (no inbound port), renders each page top-level in its own sandboxed
5
+ browser behind an egress proxy, and drives it with the controller page the Parhelia host serves. The capture logic ships
6
+ with the host; the sidecar carries none, so it needs no upgrade when Parhelia does.
7
+
8
+ Node 22 or later. Plan: `docs/capture-sidecar-plan.md`.
9
+
10
+ ## Install (Settings › Capture service › Add)
11
+
12
+ Prerequisites: Node 22 or later with npm; root (sudo) on Linux with systemd, an Administrator PowerShell on Windows; outbound
13
+ HTTPS to Parhelia and the rendering hosts. An administrator clicks **Add** under **Settings › Capture service**, which shows the
14
+ Node bootstrap line for the OS and a paste-ready command with a one-time pairing code:
15
+
16
+ ```bash
17
+ sudo npx --yes @parhelia/capture install --origin https://parhelia.internal.example --pair XXXXX-XXXXX-XXXXX-XXXXX
18
+ ```
19
+
20
+ `--origin` is the address this machine reaches Parhelia at. The key is generated on this machine; Parhelia stores only its
21
+ SHA-256. Pipeline-provisioned hosts skip the code: the host's connection string `parhelia.capture`
22
+ (`key=pcs1_…;capabilities=cms,public-web;update=notify`) names a key, and `install --key-file <file>` uses it.
23
+
24
+ What `install` sets up on Linux: the users `parhelia-capture` (the worker) and `parhelia-capture-browser` (the browser host,
25
+ whose only group is `parhelia-capture-ipc`); the code under `/opt/parhelia-capture/versions/<version>` with the `current`
26
+ link, root-owned and read-only to both; the key `/etc/parhelia-capture/worker.key` (0600, the worker's); Chromium's libraries
27
+ and an emoji font on apt systems; the units `parhelia-capture-worker`, `parhelia-capture-browser-host` (no network of its
28
+ own, see below) and `parhelia-capture-updater` with its timer; and the command `/usr/local/sbin/parhelia-capture`. On Windows:
29
+ the code under `%ProgramFiles%\Parhelia Capture`, the data and key under `%ProgramData%\Parhelia Capture` with inheritance
30
+ off, the browser's outbound firewall rule, and three scheduled tasks.
31
+
32
+ ```bash
33
+ parhelia-capture status # versions, services, last poll, public websites, the updater's last run
34
+ parhelia-capture doctor # names what is wrong (Node, origin, SSO, key, permissions, sandbox, proxy or CA)
35
+ parhelia-capture update # an update now (also for "Notify only" workers); --from <tarball> for air-gapped ones
36
+ parhelia-capture uninstall # removes everything; revoke the worker under Settings › Capture service
37
+ ```
38
+
39
+ ## Updates
40
+
41
+ The Parhelia host names the sidecar version it wants, with the tarball's integrity hash, each browser archive's SHA-256 and a
42
+ security minimum (written by the release pipeline, `frontend/scripts/write-capture-manifest.mjs`). The privileged updater
43
+ installs nothing whose hash the host did not name; it installs the new version beside the current one, runs its self-test
44
+ (a test capture, and the isolation proof when public websites are on), stops the worker between jobs, switches `current`,
45
+ and waits for the new version's first poll, else it rolls back. Each worker's policy in Settings is **Automatic** (the
46
+ default) or **Notify only**. Below the security minimum, or with a browser past its age, screenshots of public websites stay
47
+ off by themselves; CMS captures continue.
48
+
49
+ ## What each job gets
50
+
51
+ - A browser of its own (the sidecar's Chromium build, sandbox on) whose every connection goes through the job's egress
52
+ proxy: the Parhelia origin, the page's head and the host's media origins, plus public addresses; private, loopback,
53
+ link-local and metadata addresses are refused at the point of connection (each redirect hop included).
54
+ - One cookie: the job-bound capture cookie from the poll answer, on the Parhelia origin. No login, no editor session.
55
+ - The host's controller page and the target page; every call between them is authorized by the worker (the job's own
56
+ pages, their main frames, the attempt still active).
57
+
58
+ ## Screenshots of public websites (`public-web`)
59
+
60
+ The agent tool `capture-url-screenshot` takes screenshots of public pages. Such a page is untrusted and the sidecar usually
61
+ sits inside the network, so the browser for it runs in a separate **browser host** process that has no network of its own:
62
+ on Linux a systemd unit with `PrivateNetwork=yes` and an empty view of every directory sockets live in, apart from its own
63
+ socket directory. Every connection it makes goes through a Unix socket to the worker's egress proxy. That proxy resolves
64
+ each name itself, refuses private, loopback, link-local and metadata addresses, the host's blocked ranges, and the addresses
65
+ of Parhelia and of this machine, and connects only to the address it checked. A public-web job gets no cookie.
66
+
67
+ ```bash
68
+ # the worker, offering public-web once the browser host is connected and its isolation is proven
69
+ npx @parhelia/capture start --origin https://parhelia.internal.example --key-file /etc/parhelia-capture/worker.key --web
70
+ # the browser host, inside its hardened unit (print the unit's properties with `unit-properties`)
71
+ npx @parhelia/capture browser-host --socket-dir /run/parhelia-capture/browser-host
72
+ # the isolation self-test on its own
73
+ npx @parhelia/capture doctor --profile public-web --origin https://parhelia.internal.example --key-file /etc/parhelia-capture/worker.key
74
+ ```
75
+
76
+ The worker offers `public-web` only after the self-test passes, and repeats it when the browser host reconnects and once
77
+ an hour. The test first checks that the worker itself can fetch a nonce from Parhelia (another host) and one from its own
78
+ loopback. With the proxy switched off, the real browser must then reach neither. The browser host's view must hold no
79
+ socket but its own, D-Bus must be unreachable, and Chromium must run sandboxed. With the proxy on, Parhelia's address must
80
+ be refused. When Parhelia runs on the same machine, name a probe on another host with `--probe-url`. On Windows, a sidecar
81
+ on the machine that runs Parhelia refuses `public-web` by name, because loopback is not filtered there.
82
+
83
+ Local development: `npm run capture` (repository root) runs a worker from source against :5090 with a dev key;
84
+ `scripts/run-scenario.ps1 <scenario> -Capture` starts one with the scenario and gives the host the matching key.
@@ -0,0 +1,19 @@
1
+ import type { Browser } from "playwright-core";
2
+ export type BrowserHostOptions = {
3
+ socketDir: string;
4
+ version: string;
5
+ launch: (args: string[]) => Promise<Browser>;
6
+ log?: (line: Record<string, unknown>) => void;
7
+ /** Stops the host (and its reconnect loop). */
8
+ signal?: AbortSignal;
9
+ };
10
+ /** Connects to the worker and serves it until the signal ends it; reconnects when the worker restarts. */
11
+ export declare function runBrowserHost(options: BrowserHostOptions): Promise<void>;
12
+ /** A listener on this unit's private loopback that relays every connection to the worker's egress socket. */
13
+ export declare function startForwarder(egressSocket: string): Promise<{
14
+ url: string;
15
+ close(): Promise<void>;
16
+ }>;
17
+ /** Every Unix socket this process can see, outside its own socket directory (plan §8 step 5, amendment A7). */
18
+ export declare function visibleSockets(ownDir: string, root?: string): string[];
19
+ //# sourceMappingURL=browserHost.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserHost.d.ts","sourceRoot":"","sources":["../src/browserHost.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAQ/C,MAAM,MAAM,kBAAkB,GAAG;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7C,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;IAC9C,+CAA+C;IAC/C,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,CAAC;AAEF,0GAA0G;AAC1G,wBAAsB,cAAc,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAa/E;AA2DD,6GAA6G;AAC7G,wBAAsB,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAC,CA0B3G;AAkDD,+GAA+G;AAC/G,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,SAAM,GAAG,MAAM,EAAE,CAqBnE"}
@@ -0,0 +1,247 @@
1
+ /*
2
+ * Capture sidecar CS5w (plan §8): the browser host. Runs where it has no network of its own (Linux: a systemd unit with
3
+ * `PrivateNetwork=yes` and an empty view of everywhere sockets live; see isolation.ts), connects to the worker's job socket,
4
+ * and runs each public-web job in a fresh sandboxed Chromium whose proxy is a forwarder on this unit's private loopback that
5
+ * relays to the job's egress socket. It also answers the worker's self-test with what it observes from inside: the sockets
6
+ * it can see, whether D-Bus answers, whether its Chromium runs sandboxed, and what each probe URL returned.
7
+ */
8
+ import { readdirSync, readFileSync } from "node:fs";
9
+ import net from "node:net";
10
+ import { join } from "node:path";
11
+ import { proxyLaunchArgs } from "./egressProxy.js";
12
+ import { EGRESS_SOCKET_PATTERN, JOB_SOCKET, lineReader, } from "./browserHostProtocol.js";
13
+ import { runWebJob } from "./webJob.js";
14
+ /** Connects to the worker and serves it until the signal ends it; reconnects when the worker restarts. */
15
+ export async function runBrowserHost(options) {
16
+ const log = options.log ?? ((line) => console.log(JSON.stringify({ at: new Date().toISOString(), role: "browser-host", ...line })));
17
+ let backoff = 250;
18
+ while (!options.signal?.aborted) {
19
+ const ended = await serveOnce(options, log).catch((error) => {
20
+ log({ event: "link-failed", error: String(error) });
21
+ return false;
22
+ });
23
+ if (options.signal?.aborted)
24
+ break;
25
+ if (ended)
26
+ backoff = 250;
27
+ await new Promise((resolve) => setTimeout(resolve, backoff));
28
+ backoff = Math.min(backoff * 2, 5_000);
29
+ }
30
+ }
31
+ /** One connection to the worker; resolves when it closes (true when it had been established). */
32
+ function serveOnce(options, log) {
33
+ return new Promise((resolve, reject) => {
34
+ const socket = net.connect(join(options.socketDir, JOB_SOCKET));
35
+ const jobs = new Map();
36
+ let established = false;
37
+ const send = (message) => {
38
+ if (!socket.destroyed)
39
+ socket.write(JSON.stringify(message) + "\n");
40
+ };
41
+ const stop = () => socket.destroy();
42
+ options.signal?.addEventListener("abort", stop, { once: true });
43
+ socket.on("connect", () => {
44
+ established = true;
45
+ log({ event: "connected" });
46
+ send({ type: "hello", version: options.version, pid: process.pid, platform: process.platform });
47
+ });
48
+ socket.on("data", lineReader((raw) => {
49
+ const message = raw;
50
+ if (message.type === "web-job") {
51
+ const abort = new AbortController();
52
+ jobs.set(message.id, abort);
53
+ void runJob(message, options, abort.signal)
54
+ .then((outcome) => send({ type: "result", id: message.id, outcome }))
55
+ .finally(() => jobs.delete(message.id));
56
+ }
57
+ else if (message.type === "cancel") {
58
+ jobs.get(message.id)?.abort();
59
+ }
60
+ else if (message.type === "self-test") {
61
+ void selfTest(message, options)
62
+ .then((observations) => send({ type: "self-test-result", id: message.id, observations }))
63
+ .catch((error) => send({ type: "self-test-result", id: message.id, error: String(error) }));
64
+ }
65
+ }, () => socket.destroy()));
66
+ socket.on("error", (error) => {
67
+ if (!established)
68
+ reject(error);
69
+ });
70
+ socket.on("close", () => {
71
+ options.signal?.removeEventListener("abort", stop);
72
+ for (const job of jobs.values())
73
+ job.abort();
74
+ if (established)
75
+ log({ event: "disconnected" });
76
+ resolve(established);
77
+ });
78
+ });
79
+ }
80
+ async function runJob(message, options, signal) {
81
+ if (!EGRESS_SOCKET_PATTERN.test(message.egress))
82
+ return { kind: "failed", errorCode: "capture-worker-failed", message: "The job names no egress socket of this host." };
83
+ const forwarder = await startForwarder(join(options.socketDir, message.egress));
84
+ try {
85
+ return await runWebJob(message.parameters, {
86
+ launch: options.launch, proxyArgs: proxyLaunchArgs(forwarder.url), deadlineUnixMs: message.deadlineUnixMs, signal,
87
+ });
88
+ }
89
+ finally {
90
+ await forwarder.close();
91
+ }
92
+ }
93
+ /** A listener on this unit's private loopback that relays every connection to the worker's egress socket. */
94
+ export async function startForwarder(egressSocket) {
95
+ const connections = new Set();
96
+ const server = net.createServer((inbound) => {
97
+ const upstream = net.connect(egressSocket);
98
+ connections.add(inbound);
99
+ connections.add(upstream);
100
+ inbound.pipe(upstream).pipe(inbound);
101
+ const drop = () => {
102
+ inbound.destroy();
103
+ upstream.destroy();
104
+ connections.delete(inbound);
105
+ connections.delete(upstream);
106
+ };
107
+ upstream.on("error", drop);
108
+ inbound.on("error", drop);
109
+ inbound.on("close", drop);
110
+ upstream.on("close", drop);
111
+ });
112
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
113
+ return {
114
+ url: `http://127.0.0.1:${server.address().port}`,
115
+ close: () => new Promise((resolve) => {
116
+ for (const connection of connections)
117
+ connection.destroy();
118
+ server.close(() => resolve());
119
+ }),
120
+ };
121
+ }
122
+ async function selfTest(message, options) {
123
+ const observations = {
124
+ // The filesystem checks are Linux's (plan §8 step 5); Windows isolates by its firewall rule.
125
+ socketsVisible: process.platform === "linux" ? visibleSockets(options.socketDir) : [],
126
+ dbus: process.platform === "linux" ? await connectOutcome("/run/dbus/system_bus_socket") : "not applicable",
127
+ noSandboxFlag: null,
128
+ probes: [],
129
+ platform: process.platform,
130
+ };
131
+ const forwarder = message.egress && EGRESS_SOCKET_PATTERN.test(message.egress)
132
+ ? await startForwarder(join(options.socketDir, message.egress)) : undefined;
133
+ try {
134
+ for (const proxied of [false, true]) {
135
+ const probes = message.probes.filter((probe) => probe.proxied === proxied);
136
+ if (probes.length === 0)
137
+ continue;
138
+ if (proxied && !forwarder) {
139
+ observations.probes.push(...probes.map((probe) => ({ ...probe, error: "no egress socket for the proxied probes" })));
140
+ continue;
141
+ }
142
+ // Proxy off is the OS layer's test: the browser must reach nothing by itself.
143
+ const browser = await options.launch(proxied ? proxyLaunchArgs(forwarder.url) : ["--no-proxy-server"]);
144
+ try {
145
+ if (observations.noSandboxFlag !== true)
146
+ observations.noSandboxFlag = noSandboxFlagInProcesses();
147
+ for (const probe of probes)
148
+ observations.probes.push(await visit(browser, probe, message.deadlineUnixMs));
149
+ }
150
+ finally {
151
+ await browser.close().catch(() => undefined);
152
+ }
153
+ }
154
+ }
155
+ finally {
156
+ await forwarder?.close();
157
+ }
158
+ return observations;
159
+ }
160
+ async function visit(browser, probe, deadlineUnixMs) {
161
+ const context = await browser.newContext({ serviceWorkers: "block", acceptDownloads: false });
162
+ try {
163
+ const page = await context.newPage();
164
+ const response = await page.goto(probe.url, { timeout: Math.max(1_000, Math.min(8_000, deadlineUnixMs - Date.now())) });
165
+ const text = await page.evaluate(() => document.body?.innerText ?? "").catch(() => "");
166
+ return { ...probe, status: response?.status() ?? null, text: text.slice(0, 400) };
167
+ }
168
+ catch (error) {
169
+ return { ...probe, error: (error instanceof Error ? error.message : String(error)).split("\n")[0].slice(0, 200) };
170
+ }
171
+ finally {
172
+ await context.close().catch(() => undefined);
173
+ }
174
+ }
175
+ /** Every Unix socket this process can see, outside its own socket directory (plan §8 step 5, amendment A7). */
176
+ export function visibleSockets(ownDir, root = "/") {
177
+ const skip = new Set(["/proc", "/sys"]);
178
+ const own = ownDir.replace(/\/+$/, "");
179
+ const found = [];
180
+ const walk = (dir, depth) => {
181
+ if (depth > 14)
182
+ return;
183
+ let entries;
184
+ try {
185
+ entries = readdirSync(dir, { withFileTypes: true });
186
+ }
187
+ catch {
188
+ return;
189
+ }
190
+ for (const entry of entries) {
191
+ const path = (dir === "/" ? "" : dir) + "/" + entry.name;
192
+ if (skip.has(path) || path === own)
193
+ continue;
194
+ if (entry.isSocket())
195
+ found.push(path);
196
+ else if (entry.isDirectory() && !entry.isSymbolicLink())
197
+ walk(path, depth + 1);
198
+ }
199
+ };
200
+ walk(root, 0);
201
+ return found;
202
+ }
203
+ function connectOutcome(path) {
204
+ return new Promise((resolve) => {
205
+ const socket = net.connect(path);
206
+ socket.on("connect", () => {
207
+ socket.destroy();
208
+ resolve("CONNECTED");
209
+ });
210
+ socket.on("error", (error) => resolve(`refused: ${error.code ?? error.message}`));
211
+ });
212
+ }
213
+ function noSandboxFlagInProcesses() {
214
+ if (process.platform !== "linux")
215
+ return null;
216
+ try {
217
+ // Only this host's own descendants: other Chromium processes on the machine are not this host's to judge.
218
+ const parents = new Map();
219
+ for (const entry of readdirSync("/proc").filter((name) => /^\d+$/.test(name))) {
220
+ try {
221
+ const stat = readFileSync(`/proc/${entry}/stat`, "utf8");
222
+ parents.set(Number(entry), Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]));
223
+ }
224
+ catch {
225
+ // gone
226
+ }
227
+ }
228
+ const descends = (pid) => {
229
+ for (let at = parents.get(pid), hops = 0; at !== undefined && at > 1 && hops < 64; at = parents.get(at), hops++)
230
+ if (at === process.pid)
231
+ return true;
232
+ return false;
233
+ };
234
+ return [...parents.keys()].filter(descends).some((pid) => {
235
+ try {
236
+ const command = readFileSync(`/proc/${pid}/cmdline`, "utf8");
237
+ return /chrom/i.test(command) && command.includes("--no-sandbox");
238
+ }
239
+ catch {
240
+ return false;
241
+ }
242
+ });
243
+ }
244
+ catch {
245
+ return null;
246
+ }
247
+ }
@@ -0,0 +1,50 @@
1
+ import { type EgressLogEntry } from "./egressProxy.js";
2
+ import { type ProbeRequest, type SelfTestObservations } from "./browserHostProtocol.js";
3
+ import type { WebJobOutcome } from "./webJob.js";
4
+ export type EgressPolicy = {
5
+ blockedRanges: readonly string[];
6
+ denyAddresses: readonly string[];
7
+ resolve?: (host: string) => Promise<string[]>;
8
+ connectTo?: (address: string, port: number) => {
9
+ host: string;
10
+ port: number;
11
+ };
12
+ };
13
+ /** A Windows named-pipe prefix (`\\.\pipe\…`) rather than a directory. */
14
+ export declare const isPipePath: (path: string) => boolean;
15
+ export type BrowserHostInfo = {
16
+ version: string;
17
+ pid: number;
18
+ platform: string;
19
+ };
20
+ export declare class BrowserHostLink {
21
+ readonly socketDir: string;
22
+ private readonly server;
23
+ private readonly log;
24
+ readonly groupAccess: boolean;
25
+ private current?;
26
+ private readonly waiting;
27
+ private readonly connectListeners;
28
+ private constructor();
29
+ /**
30
+ * Listens on the job socket. Owner-only by default (`0700`/`0600`); with `groupAccess` (an installed sidecar: the browser host
31
+ * runs as its own user whose only group is the ipc group) the directory is `0750` and the sockets `0660`. On Windows the
32
+ * directory is a named-pipe prefix (`\\.\pipe\…`): nothing is created on disk.
33
+ */
34
+ static listen(socketDir: string, log?: (line: Record<string, unknown>) => void, options?: {
35
+ groupAccess?: boolean;
36
+ }): Promise<BrowserHostLink>;
37
+ get host(): BrowserHostInfo | undefined;
38
+ onConnect(listener: (info: BrowserHostInfo) => void): () => void;
39
+ /** Waits until a browser host has said hello (or the time is up). */
40
+ waitForHost(timeoutMs: number): Promise<BrowserHostInfo | undefined>;
41
+ private accept;
42
+ private send;
43
+ private withEgress;
44
+ /** Runs one public-web job in the browser host behind its own egress proxy; answers when it ends or its deadline passes. */
45
+ runWebJob(id: string, parameters: unknown, deadlineUnixMs: number, policy: EgressPolicy, signal: AbortSignal, egressLog?: (entry: EgressLogEntry) => void): Promise<WebJobOutcome>;
46
+ /** Asks the browser host what it sees from inside, and what each probe URL returns to its browser. */
47
+ selfTest(probes: ProbeRequest[], policy: EgressPolicy | undefined, timeoutMs?: number, egressLog?: (entry: EgressLogEntry) => void): Promise<SelfTestObservations>;
48
+ close(): Promise<void>;
49
+ }
50
+ //# sourceMappingURL=browserHostLink.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserHostLink.d.ts","sourceRoot":"","sources":["../src/browserHostLink.ts"],"names":[],"mappings":"AAUA,OAAO,EAAoB,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAEa,KAAK,YAAY,EAAE,KAAK,oBAAoB,EAC/D,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,MAAM,YAAY,GAAG;IAAE,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC7I,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAAC;AAElF,0EAA0E;AAC1E,eAAO,MAAM,UAAU,SAAU,MAAM,YAAqC,CAAC;AAE7E,MAAM,MAAM,eAAe,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjF,qBAAa,eAAe;IAMxB,QAAQ,CAAC,SAAS,EAAE,MAAM;IAC1B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,QAAQ,CAAC,WAAW,EAAE,OAAO;IAR/B,OAAO,CAAC,OAAO,CAAC,CAAiD;IACjE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqD;IAC7E,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA8C;IAE/E,OAAO,eAKH;IAEJ;;;;OAIG;IACH,OAAa,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,GAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAsB,EACnG,OAAO,GAAE;QAAE,WAAW,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,eAAe,CAAC,CAsBnE;IAED,IAAI,IAAI,IAAI,eAAe,GAAG,SAAS,CAEtC;IAED,SAAS,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,eAAe,KAAK,IAAI,GAAG,MAAM,IAAI,CAG/D;IAED,qEAAqE;IAC/D,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAazE;IAED,OAAO,CAAC,MAAM;IA0Bd,OAAO,CAAC,IAAI;YAOE,UAAU;IAgBxB,4HAA4H;IAC5H,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAC1G,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,CAyBrE;IAED,sGAAsG;IACtG,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,MAAM,EAAE,YAAY,GAAG,SAAS,EAAE,SAAS,SAAS,EACnF,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAoB5E;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAI3B;CACF"}
@@ -0,0 +1,193 @@
1
+ /*
2
+ * Capture sidecar CS5w (plan §8): the worker's end of the browser host. Owns the socket directory (`0700`) and the job socket
3
+ * (`0600`); for each public-web job it opens that job's egress proxy on its own socket in the directory, with the job's
4
+ * blocked ranges and this worker's deny list, and hands the job to the connected browser host. The newest connection is the
5
+ * browser host (a restarted host replaces its stale predecessor).
6
+ */
7
+ import { chmodSync, mkdirSync, rmSync } from "node:fs";
8
+ import net from "node:net";
9
+ import { join } from "node:path";
10
+ import { randomBytes } from "node:crypto";
11
+ import { startEgressProxy } from "./egressProxy.js";
12
+ import { JOB_SOCKET, lineReader, } from "./browserHostProtocol.js";
13
+ /** A Windows named-pipe prefix (`\\.\pipe\…`) rather than a directory. */
14
+ export const isPipePath = (path) => path.startsWith("\\\\.\\pipe\\");
15
+ export class BrowserHostLink {
16
+ socketDir;
17
+ server;
18
+ log;
19
+ groupAccess;
20
+ current;
21
+ waiting = new Map();
22
+ connectListeners = new Set();
23
+ constructor(socketDir, server, log, groupAccess) {
24
+ this.socketDir = socketDir;
25
+ this.server = server;
26
+ this.log = log;
27
+ this.groupAccess = groupAccess;
28
+ }
29
+ /**
30
+ * Listens on the job socket. Owner-only by default (`0700`/`0600`); with `groupAccess` (an installed sidecar: the browser host
31
+ * runs as its own user whose only group is the ipc group) the directory is `0750` and the sockets `0660`. On Windows the
32
+ * directory is a named-pipe prefix (`\\.\pipe\…`): nothing is created on disk.
33
+ */
34
+ static async listen(socketDir, log = () => undefined, options = {}) {
35
+ const groupAccess = options.groupAccess ?? false;
36
+ const pipe = isPipePath(socketDir);
37
+ if (!pipe) {
38
+ mkdirSync(socketDir, { recursive: true, mode: groupAccess ? 0o750 : 0o700 });
39
+ chmodSync(socketDir, groupAccess ? 0o750 : 0o700);
40
+ }
41
+ const path = join(socketDir, JOB_SOCKET);
42
+ if (!pipe)
43
+ rmSync(path, { force: true });
44
+ let link;
45
+ const server = net.createServer((socket) => link.accept(socket));
46
+ link = new BrowserHostLink(socketDir, server, log, groupAccess);
47
+ const previous = process.umask(groupAccess ? 0o117 : 0o177);
48
+ try {
49
+ await new Promise((resolve, reject) => {
50
+ server.once("error", reject);
51
+ server.listen(path, () => resolve());
52
+ });
53
+ }
54
+ finally {
55
+ process.umask(previous);
56
+ }
57
+ return link;
58
+ }
59
+ get host() {
60
+ return this.current?.info;
61
+ }
62
+ onConnect(listener) {
63
+ this.connectListeners.add(listener);
64
+ return () => this.connectListeners.delete(listener);
65
+ }
66
+ /** Waits until a browser host has said hello (or the time is up). */
67
+ async waitForHost(timeoutMs) {
68
+ if (this.host)
69
+ return this.host;
70
+ return new Promise((resolve) => {
71
+ const timer = setTimeout(() => {
72
+ off();
73
+ resolve(undefined);
74
+ }, timeoutMs);
75
+ const off = this.onConnect((info) => {
76
+ clearTimeout(timer);
77
+ off();
78
+ resolve(info);
79
+ });
80
+ });
81
+ }
82
+ accept(socket) {
83
+ const previous = this.current;
84
+ this.current = { socket };
85
+ previous?.socket.destroy();
86
+ socket.on("data", lineReader((raw) => {
87
+ const message = raw;
88
+ if (message.type === "hello") {
89
+ if (this.current?.socket !== socket)
90
+ return;
91
+ this.current.info = { version: message.version, pid: message.pid, platform: message.platform };
92
+ this.log({ event: "browser-host-connected", pid: message.pid, version: message.version });
93
+ for (const listener of [...this.connectListeners])
94
+ listener(this.current.info);
95
+ }
96
+ else if ("id" in message) {
97
+ this.waiting.get(message.id)?.(message);
98
+ }
99
+ }, () => socket.destroy()));
100
+ socket.on("error", () => socket.destroy());
101
+ socket.on("close", () => {
102
+ if (this.current?.socket === socket) {
103
+ this.current = undefined;
104
+ this.log({ event: "browser-host-disconnected" });
105
+ // Every job and self-test on this connection ends now, not at its deadline.
106
+ for (const [id, answer] of [...this.waiting])
107
+ answer({ type: "self-test-result", id, error: "the browser host disconnected" });
108
+ }
109
+ });
110
+ }
111
+ send(message) {
112
+ const socket = this.current?.info ? this.current.socket : undefined;
113
+ if (!socket || socket.destroyed)
114
+ return false;
115
+ socket.write(JSON.stringify(message) + "\n");
116
+ return true;
117
+ }
118
+ async withEgress(policy, log, use) {
119
+ if (!policy)
120
+ return use(undefined);
121
+ const name = `egress-${randomBytes(9).toString("base64url")}.sock`;
122
+ const proxy = await startEgressProxy({
123
+ allow: [], blockedRanges: policy.blockedRanges, denyAddresses: policy.denyAddresses, socketPath: join(this.socketDir, name),
124
+ socketGroupAccess: this.groupAccess,
125
+ resolve: policy.resolve, connectTo: policy.connectTo, log,
126
+ });
127
+ try {
128
+ return await use(name);
129
+ }
130
+ finally {
131
+ await proxy.close();
132
+ }
133
+ }
134
+ /** Runs one public-web job in the browser host behind its own egress proxy; answers when it ends or its deadline passes. */
135
+ runWebJob(id, parameters, deadlineUnixMs, policy, signal, egressLog) {
136
+ return this.withEgress(policy, egressLog, (egress) => new Promise((resolve) => {
137
+ const finish = (outcome) => {
138
+ clearTimeout(timer);
139
+ signal.removeEventListener("abort", cancel);
140
+ this.waiting.delete(id);
141
+ resolve(outcome);
142
+ };
143
+ const cancel = () => {
144
+ this.send({ type: "cancel", id });
145
+ finish({ kind: "cancelled" });
146
+ };
147
+ const timer = setTimeout(() => {
148
+ this.send({ type: "cancel", id });
149
+ finish({ kind: "failed", errorCode: "capture-worker-timeout", message: "The page was not captured within the job's time." });
150
+ }, Math.max(1_000, deadlineUnixMs - Date.now()));
151
+ this.waiting.set(id, (message) => {
152
+ if (message.type === "result")
153
+ finish(message.outcome);
154
+ else
155
+ finish({ kind: "failed", errorCode: "capture-worker-failed", message: "The browser host disconnected during the capture." });
156
+ });
157
+ if (signal.aborted)
158
+ return cancel();
159
+ signal.addEventListener("abort", cancel, { once: true });
160
+ if (!this.send({ type: "web-job", id, parameters, deadlineUnixMs, egress: egress }))
161
+ finish({ kind: "failed", errorCode: "capture-worker-failed", message: "No browser host is connected to this worker." });
162
+ }));
163
+ }
164
+ /** Asks the browser host what it sees from inside, and what each probe URL returns to its browser. */
165
+ selfTest(probes, policy, timeoutMs = 60_000, egressLog) {
166
+ const id = "self-test-" + randomBytes(6).toString("hex");
167
+ return this.withEgress(probes.some((probe) => probe.proxied) ? policy : undefined, egressLog, (egress) => new Promise((resolve, reject) => {
168
+ const timer = setTimeout(() => {
169
+ this.waiting.delete(id);
170
+ reject(new Error("The browser host did not answer the self-test in time."));
171
+ }, timeoutMs);
172
+ this.waiting.set(id, (message) => {
173
+ clearTimeout(timer);
174
+ this.waiting.delete(id);
175
+ if (message.type === "self-test-result" && message.observations)
176
+ resolve(message.observations);
177
+ else
178
+ reject(new Error(message.type === "self-test-result" ? message.error ?? "self-test failed" : "unexpected answer"));
179
+ });
180
+ if (!this.send({ type: "self-test", id, probes, egress, deadlineUnixMs: Date.now() + timeoutMs })) {
181
+ clearTimeout(timer);
182
+ this.waiting.delete(id);
183
+ reject(new Error("No browser host is connected to this worker."));
184
+ }
185
+ }));
186
+ }
187
+ async close() {
188
+ this.current?.socket.destroy();
189
+ await new Promise((resolve) => this.server.close(() => resolve()));
190
+ if (!isPipePath(this.socketDir))
191
+ rmSync(join(this.socketDir, JOB_SOCKET), { force: true });
192
+ }
193
+ }
@@ -0,0 +1,61 @@
1
+ import type { WebJobOutcome } from "./webJob.js";
2
+ export declare const JOB_SOCKET = "jobs.sock";
3
+ export declare const EGRESS_SOCKET_PATTERN: RegExp;
4
+ export declare const MAX_MESSAGE_BYTES: number;
5
+ export type ProbeRequest = {
6
+ name: string;
7
+ url: string;
8
+ proxied: boolean;
9
+ };
10
+ export type ProbeObservation = {
11
+ name: string;
12
+ url: string;
13
+ proxied: boolean;
14
+ status?: number | null;
15
+ text?: string;
16
+ error?: string;
17
+ };
18
+ export type SelfTestObservations = {
19
+ /** Unix sockets the browser host's filesystem view holds, outside its own socket directory. */
20
+ socketsVisible: string[];
21
+ /** The outcome of connect() to the system D-Bus socket ("refused: ENOENT", or "CONNECTED"). */
22
+ dbus: string;
23
+ /** Whether any Chromium process of this host carried `--no-sandbox` (Linux: read from /proc). */
24
+ noSandboxFlag: boolean | null;
25
+ probes: ProbeObservation[];
26
+ platform: string;
27
+ };
28
+ export type HostMessage = {
29
+ type: "hello";
30
+ version: string;
31
+ pid: number;
32
+ platform: string;
33
+ } | {
34
+ type: "result";
35
+ id: string;
36
+ outcome: WebJobOutcome;
37
+ } | {
38
+ type: "self-test-result";
39
+ id: string;
40
+ observations?: SelfTestObservations;
41
+ error?: string;
42
+ };
43
+ export type WorkerMessage = {
44
+ type: "web-job";
45
+ id: string;
46
+ parameters: unknown;
47
+ deadlineUnixMs: number;
48
+ egress: string;
49
+ } | {
50
+ type: "cancel";
51
+ id: string;
52
+ } | {
53
+ type: "self-test";
54
+ id: string;
55
+ probes: ProbeRequest[];
56
+ egress?: string;
57
+ deadlineUnixMs: number;
58
+ };
59
+ /** Splits a stream into JSON lines (bounded: a line past the limit ends the connection). */
60
+ export declare function lineReader(onMessage: (message: unknown) => void, onOverflow: () => void): (chunk: Buffer | string) => void;
61
+ //# sourceMappingURL=browserHostProtocol.d.ts.map