@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserHostProtocol.d.ts","sourceRoot":"","sources":["../src/browserHostProtocol.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,eAAO,MAAM,UAAU,cAAc,CAAC;AACtC,eAAO,MAAM,qBAAqB,QAAuC,CAAC;AAC1E,eAAO,MAAM,iBAAiB,QAAmB,CAAC;AAElD,MAAM,MAAM,YAAY,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC;AAE3E,MAAM,MAAM,gBAAgB,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,IAAI,CAAC,EA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AAC,SAAS,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,WAEvE,MAAM,GAAG,MAAM,UAoB/B"}
@@ -0,0 +1,29 @@
1
+ export const JOB_SOCKET = "jobs.sock";
2
+ export const EGRESS_SOCKET_PATTERN = /^egress-[A-Za-z0-9_-]{1,80}\.sock$/;
3
+ export const MAX_MESSAGE_BYTES = 48 * 1024 * 1024;
4
+ /** Splits a stream into JSON lines (bounded: a line past the limit ends the connection). */
5
+ export function lineReader(onMessage, onOverflow) {
6
+ let buffer = "";
7
+ return (chunk) => {
8
+ buffer += chunk.toString();
9
+ if (buffer.length > MAX_MESSAGE_BYTES) {
10
+ buffer = "";
11
+ onOverflow();
12
+ return;
13
+ }
14
+ let newline;
15
+ while ((newline = buffer.indexOf("\n")) >= 0) {
16
+ const line = buffer.slice(0, newline);
17
+ buffer = buffer.slice(newline + 1);
18
+ if (!line.trim())
19
+ continue;
20
+ try {
21
+ onMessage(JSON.parse(line));
22
+ }
23
+ catch {
24
+ onOverflow();
25
+ return;
26
+ }
27
+ }
28
+ };
29
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,239 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * Capture sidecar CS4-CS6: the command line.
4
+ * install / uninstall / status / update the service on this machine (CS6: units or tasks, the updater, the hashes)
5
+ * start the worker (an installed one reads --config; with --web the public-web profile)
6
+ * browser-host the isolated browser host (its unit starts it)
7
+ * doctor names what is wrong; --profile public-web proves the isolation; --quick is the
8
+ * updater's test capture of a staged version
9
+ * pair, unit-properties by hand: pair without installing, print the browser host unit's hardening
10
+ */
11
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { createRequire } from "node:module";
13
+ import { dirname, join } from "node:path";
14
+ import { hostname } from "node:os";
15
+ import { fileURLToPath } from "node:url";
16
+ import { BrowserHostLink } from "./browserHostLink.js";
17
+ import { runBrowserHost } from "./browserHost.js";
18
+ import { generalChecks, printChecks, quickCapture } from "./install/doctor.js";
19
+ import { install, statusLines, uninstall } from "./install/install.js";
20
+ import { layoutFor } from "./install/layout.js";
21
+ import { selfTest, services, windowsFirewall } from "./install/services.js";
22
+ import { realSys } from "./install/sys.js";
23
+ import { runUpdate } from "./install/updater.js";
24
+ import { browserOf, readRecord } from "./install/versions.js";
25
+ import { browserHostUnitProperties, ownAddresses, parheliaIsColocated, socketDirectoriesOutsideHiddenTrees } from "./isolation.js";
26
+ import { ParheliaClient, newWorkerKey } from "./parheliaClient.js";
27
+ import { SIDECAR_VERSION } from "./version.js";
28
+ import { resolveAll, verifyWebIsolation } from "./webIsolation.js";
29
+ import { defaultLaunch, startWorker, WEB_CAPABILITY } from "./worker.js";
30
+ const DEFAULT_SOCKET_DIR = "/run/parhelia-capture/browser-host";
31
+ const USAGE = `parhelia-capture ${SIDECAR_VERSION}
32
+
33
+ Install (root on Linux, Administrator on Windows; Node 22 or later):
34
+ npx @parhelia/capture install --origin <url> --pair <XXXXX-XXXXX-XXXXX-XXXXX> [--name <name>] [--no-web]
35
+ [--probe-url <url>] [--public-url <url>] [--registry <url>] [--browser-mirror <url>]
36
+ [--browser-path <chrome> | --from <tarball>] [--key-file <path>]
37
+ parhelia-capture status | doctor [--profile public-web] | update [--from <tarball>] | uninstall [--keep-key]
38
+
39
+ By hand:
40
+ parhelia-capture pair --origin <url> --code <code> --key-file <path> [--name <name>]
41
+ parhelia-capture start (--config <file> | --origin <url> (--key-file <path> | env PARHELIA_CAPTURE_KEY)) [--browser <chrome>]
42
+ [--web [--socket-dir <dir>] [--probe-url <url>] [--public-url <url>]]
43
+ parhelia-capture browser-host [--socket-dir <dir>] [--install-dir <dir> | --browser <chrome>]
44
+ parhelia-capture doctor --profile public-web (--config <file> | --origin <url> --key-file <path>) [--socket-dir <dir>]
45
+ parhelia-capture unit-properties [--socket-dir <dir>] [--read-only <path>]... [--user-unit]
46
+
47
+ --origin is the address this machine reaches Parhelia at (often an internal one). The socket directory defaults to ${DEFAULT_SOCKET_DIR}.`;
48
+ function option(args, name) {
49
+ const at = args.indexOf(name);
50
+ return at >= 0 ? args[at + 1] : undefined;
51
+ }
52
+ function options(args, name) {
53
+ return args.flatMap((value, at) => (value === name && args[at + 1] ? [args[at + 1]] : []));
54
+ }
55
+ function required(args, name) {
56
+ const value = option(args, name);
57
+ if (!value)
58
+ throw new Error(`${name} is required.\n\n${USAGE}`);
59
+ return value;
60
+ }
61
+ function readKey(args, config) {
62
+ const keyFile = option(args, "--key-file") ?? config?.keyFile;
63
+ const key = keyFile ? readFileSync(keyFile, "utf8").trim() : process.env.PARHELIA_CAPTURE_KEY?.trim();
64
+ if (!key)
65
+ throw new Error(`A worker key is required: --key-file, or the environment variable PARHELIA_CAPTURE_KEY.\n\n${USAGE}`);
66
+ return key;
67
+ }
68
+ function readConfig(args, fallback) {
69
+ const file = option(args, "--config") ?? fallback;
70
+ if (!file)
71
+ return undefined;
72
+ try {
73
+ return JSON.parse(readFileSync(file, "utf8"));
74
+ }
75
+ catch (error) {
76
+ if (option(args, "--config"))
77
+ throw new Error(`The configuration ${file} cannot be read: ${String(error)}`);
78
+ return undefined;
79
+ }
80
+ }
81
+ /** The running package and its playwright-core (a source build installs these as they are). */
82
+ function self() {
83
+ const require = createRequire(import.meta.url);
84
+ const playwrightDir = dirname(require.resolve("playwright-core/package.json"));
85
+ const browsers = JSON.parse(readFileSync(join(playwrightDir, "browsers.json"), "utf8"));
86
+ return {
87
+ packageDir: fileURLToPath(new URL("..", import.meta.url)), playwrightDir, version: SIDECAR_VERSION,
88
+ browserRevision: browsers.browsers.find((browser) => browser.name === "chromium-headless-shell")?.revision,
89
+ };
90
+ }
91
+ const log = (line) => console.log(JSON.stringify({ at: new Date().toISOString(), ...line }));
92
+ async function main(argv) {
93
+ const [command, ...args] = argv;
94
+ if (Number(process.versions.node.split(".")[0]) < 22)
95
+ throw new Error(`Node 22 or later is required (this is ${process.versions.node}).`);
96
+ const sys = realSys();
97
+ switch (command) {
98
+ case "install": {
99
+ const layout = layoutFor(process.platform);
100
+ const origin = required(args, "--origin");
101
+ const report = await install({
102
+ sys, layout, origin, pairCode: option(args, "--pair"), keyFile: option(args, "--key-file"), name: option(args, "--name") ?? hostname(),
103
+ web: args.includes("--no-web") ? false : undefined, probeUrl: option(args, "--probe-url"), publicUrl: option(args, "--public-url"),
104
+ registry: option(args, "--registry"), browserMirror: option(args, "--browser-mirror"), browserPath: option(args, "--browser-path"),
105
+ fromTarball: option(args, "--from"), self: self(), newKey: newWorkerKey,
106
+ pair: (at, code, key, name) => ParheliaClient.pair(at, code, key, name),
107
+ fetchManifest: (key) => new ParheliaClient({ origin, key, version: SIDECAR_VERSION }).manifest(),
108
+ scanSockets: () => socketDirectoriesOutsideHiddenTrees("/", [layout.socketDir]),
109
+ colocated: async () => parheliaIsColocated(await resolveAll(new URL(origin).hostname).catch(() => []), ownAddresses()),
110
+ firewall: process.platform === "win32" ? windowsFirewall(sys) : undefined,
111
+ log: (line) => console.log(line),
112
+ });
113
+ console.log(`Installed ${report.version} (${report.source === "release" ? "checked against Parhelia's hashes" : "source build, unchecked"}).`);
114
+ console.log(`Screenshots of public websites: ${report.web ? "on once the isolation self-test passes" : `off${report.webNote ? ` (${report.webNote})` : ""}`}.`);
115
+ console.log(report.polled ? "The worker polls Parhelia." : "The worker has not polled yet.");
116
+ for (const warning of report.warnings)
117
+ console.log(`Note: ${warning}`);
118
+ if (!report.polled)
119
+ process.exitCode = 1;
120
+ return;
121
+ }
122
+ case "uninstall":
123
+ uninstall({ sys, layout: layoutFor(process.platform), keepKey: args.includes("--keep-key"), log: (line) => console.log(line) });
124
+ console.log("The capture service is removed from this machine. Revoke its pairing under Settings › Capture service.");
125
+ return;
126
+ case "status":
127
+ for (const line of statusLines(sys, layoutFor(process.platform)))
128
+ console.log(line);
129
+ return;
130
+ case "update": {
131
+ const layout = layoutFor(process.platform);
132
+ const config = readConfig(args, layout.configFile);
133
+ if (!config)
134
+ throw new Error("The capture service is not installed here (no configuration).");
135
+ if (!sys.isPrivileged())
136
+ throw new Error("The updater owns the code: run it as root (Linux) or from an Administrator shell (Windows).");
137
+ const client = new ParheliaClient({ origin: config.origin, key: readKey(args, config), version: SIDECAR_VERSION });
138
+ const result = await runUpdate({
139
+ sys, layout, config, fetchManifest: () => client.manifest(), selfTest: selfTest(sys, layout, config),
140
+ services: services(sys, layout, config.web), firewall: process.platform === "win32" && config.web ? windowsFirewall(sys) : undefined,
141
+ log: (line) => console.log(line),
142
+ }, { auto: args.includes("--auto"), fromTarball: option(args, "--from") });
143
+ if (result.result === "refused" || result.result === "rolled-back" || result.result === "unreachable")
144
+ process.exitCode = 1;
145
+ return;
146
+ }
147
+ case "pair": {
148
+ const origin = required(args, "--origin");
149
+ const keyFile = required(args, "--key-file");
150
+ const key = newWorkerKey();
151
+ const worker = await ParheliaClient.pair(origin, required(args, "--code"), key, option(args, "--name") ?? hostname());
152
+ mkdirSync(dirname(keyFile), { recursive: true });
153
+ writeFileSync(keyFile, key + "\n", { mode: 0o600 });
154
+ chmodSync(keyFile, 0o600);
155
+ console.log(`Paired as '${worker.name}' (${worker.workerId}); may run: ${worker.capabilities.join(", ")}. Key written to ${keyFile}.`);
156
+ return;
157
+ }
158
+ case "start": {
159
+ const config = readConfig(args);
160
+ const record = config ? readRecord(sys, config.installDir) : undefined;
161
+ const layout = config ? layoutFor(process.platform) : undefined;
162
+ const browser = option(args, "--browser") ?? config?.browserPath ?? (config && layout ? browserOf(sys, layout, config.installDir) : undefined);
163
+ const web = config ? config.web : args.includes("--web");
164
+ const link = web ? await BrowserHostLink.listen(option(args, "--socket-dir") ?? config?.socketDir ?? DEFAULT_SOCKET_DIR, log, { groupAccess: config?.socketGroupAccess }) : undefined;
165
+ const worker = startWorker({
166
+ origin: config?.origin ?? required(args, "--origin"), key: readKey(args, config), version: SIDECAR_VERSION, launch: defaultLaunch(browser),
167
+ web: link ? { link, isolation: { probeUrl: option(args, "--probe-url") ?? config?.probeUrl, publicUrl: option(args, "--public-url") ?? config?.publicUrl } } : undefined,
168
+ install: config ? { record, statusFile: config.statusFile, updaterStatusFile: config.updaterStatusFile } : undefined,
169
+ });
170
+ const stop = () => void worker.stop();
171
+ process.once("SIGINT", stop);
172
+ process.once("SIGTERM", stop);
173
+ await worker.done;
174
+ await link?.close();
175
+ return;
176
+ }
177
+ case "browser-host": {
178
+ const stopping = new AbortController();
179
+ process.once("SIGINT", () => stopping.abort());
180
+ process.once("SIGTERM", () => stopping.abort());
181
+ const installDir = option(args, "--install-dir");
182
+ const browser = option(args, "--browser") ?? (installDir ? browserOf(sys, layoutFor(process.platform), installDir) : undefined);
183
+ await runBrowserHost({ socketDir: option(args, "--socket-dir") ?? DEFAULT_SOCKET_DIR, version: SIDECAR_VERSION,
184
+ launch: defaultLaunch(browser), signal: stopping.signal });
185
+ return;
186
+ }
187
+ case "doctor": {
188
+ if (args.includes("--quick")) {
189
+ const installDir = required(args, "--install-dir");
190
+ const check = await quickCapture(browserOf(sys, layoutFor(process.platform), installDir));
191
+ if (!printChecks([check]))
192
+ process.exitCode = 1;
193
+ return;
194
+ }
195
+ const layout = layoutFor(process.platform);
196
+ const config = readConfig(args, option(args, "--origin") ? undefined : layout.configFile);
197
+ if (option(args, "--profile") === WEB_CAPABILITY) {
198
+ const client = new ParheliaClient({ origin: config?.origin ?? required(args, "--origin"), key: readKey(args, config), version: SIDECAR_VERSION });
199
+ const link = await BrowserHostLink.listen(option(args, "--socket-dir") ?? config?.socketDir ?? DEFAULT_SOCKET_DIR, log, { groupAccess: config?.socketGroupAccess });
200
+ try {
201
+ console.log(`Waiting for the browser host on ${link.socketDir} …`);
202
+ const host = await link.waitForHost(30_000);
203
+ if (!host)
204
+ throw new Error(`No browser host connected within 30 s: start 'parhelia-capture browser-host --socket-dir ${link.socketDir}' in its unit.`);
205
+ const report = await verifyWebIsolation({ client, link, probeUrl: option(args, "--probe-url") ?? config?.probeUrl,
206
+ publicUrl: option(args, "--public-url") ?? config?.publicUrl });
207
+ printChecks(report.checks);
208
+ console.log(report.ok ? "The public-web profile can run here." : `${report.code}: ${report.reason}`);
209
+ if (!report.ok)
210
+ process.exitCode = 1;
211
+ }
212
+ finally {
213
+ await link.close();
214
+ }
215
+ return;
216
+ }
217
+ if (!config)
218
+ throw new Error(`The capture service is not installed here; pass --config, or run doctor --profile public-web by hand.\n\n${USAGE}`);
219
+ if (!printChecks(await generalChecks(sys, layout, config)))
220
+ process.exitCode = 1;
221
+ return;
222
+ }
223
+ case "unit-properties": {
224
+ const socketDir = option(args, "--socket-dir") ?? DEFAULT_SOCKET_DIR;
225
+ const properties = browserHostUnitProperties({ socketDir, readOnlyPaths: options(args, "--read-only"), userUnit: args.includes("--user-unit"),
226
+ inaccessiblePaths: socketDirectoriesOutsideHiddenTrees("/", [socketDir]) });
227
+ console.log(properties.join("\n"));
228
+ return;
229
+ }
230
+ default:
231
+ console.log(USAGE);
232
+ if (command && command !== "help" && command !== "--help")
233
+ process.exitCode = 2;
234
+ }
235
+ }
236
+ main(process.argv.slice(2)).catch((error) => {
237
+ console.error(error instanceof Error ? error.message : String(error));
238
+ process.exitCode = 1;
239
+ });
@@ -0,0 +1,38 @@
1
+ import type { Browser } from "playwright-core";
2
+ import { type EgressLogEntry } from "./egressProxy.js";
3
+ import type { CaptureJobOffer } from "./parheliaClient.js";
4
+ export declare const CONTROLLER_PATH = "/parhelia/capture/controller";
5
+ export declare const CONTROLLER_BINDING = "parheliaCapture";
6
+ export declare const CONTROLLER_EVENTS = "parheliaCaptureEvent";
7
+ export declare const RELAY_BINDING = "parheliaCaptureRelay";
8
+ export declare const RELAY_DELIVER = "parheliaCaptureDeliver";
9
+ export declare const CAPTURE_COOKIE = "parhelia-capture";
10
+ /** Stops animations, transitions and the caret before measurement (plan CS-D4 step 1); applied through re-validation. */
11
+ export declare const PRECONDITION_CSS = "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important;scroll-behavior:auto!important}";
12
+ export type JobOutcome = {
13
+ kind: "result";
14
+ result: unknown;
15
+ } | {
16
+ kind: "failed";
17
+ errorCode: string;
18
+ message: string;
19
+ } | {
20
+ kind: "cancelled";
21
+ };
22
+ export type CmsJobOptions = {
23
+ /** The origin the worker reached Parhelia at: job URLs are relative to it, and it is always on the job's allowlist. */
24
+ origin: string;
25
+ launch: (args: string[]) => Promise<Browser>;
26
+ /** The host's current bridge, fetched once per worker. */
27
+ bridgeScript: () => Promise<string>;
28
+ /** Aborted when the host names the attempt cancelled, or the worker stops. */
29
+ signal: AbortSignal;
30
+ log?: (line: Record<string, unknown>) => void;
31
+ egressLog?: (entry: EgressLogEntry) => void;
32
+ /** Test seam: the job's browser waits this long for its controller's answer at most (default: the deadline). */
33
+ now?: () => number;
34
+ };
35
+ /** The `host:port` of an origin as the egress proxy sees it on CONNECT or in an absolute request URL. */
36
+ export declare function hostPortOf(origin: string): string;
37
+ export declare function runCmsJob(offer: CaptureJobOffer, options: CmsJobOptions): Promise<JobOutcome>;
38
+ //# sourceMappingURL=cmsJob.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cmsJob.d.ts","sourceRoot":"","sources":["../src/cmsJob.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,OAAO,EAA+B,MAAM,iBAAiB,CAAC;AAC5E,OAAO,EAAqC,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAC1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,eAAO,MAAM,eAAe,iCAAiC,CAAC;AAC9D,eAAO,MAAM,kBAAkB,oBAAoB,CAAC;AACpD,eAAO,MAAM,iBAAiB,yBAAyB,CAAC;AACxD,eAAO,MAAM,aAAa,yBAAyB,CAAC;AACpD,eAAO,MAAM,aAAa,2BAA2B,CAAC;AACtD,eAAO,MAAM,cAAc,qBAAqB,CAAC;AAEjD,yHAAyH;AACzH,eAAO,MAAM,gBAAgB,8IACgH,CAAC;AAE9I,MAAM,MAAM,UAAU,GAClB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GACnC;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACtD;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC;AAE1B,MAAM,MAAM,aAAa,GAAG;IAC1B,uHAAuH;IACvH,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7C,0DAA0D;IAC1D,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IACpC,8EAA8E;IAC9E,MAAM,EAAE,WAAW,CAAC;IACpB,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;IAC9C,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;IAC5C,gHAAgH;IAChH,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB,CAAC;AAEF,yGAAyG;AACzG,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAIjD;AAED,wBAAsB,SAAS,CAAC,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,UAAU,CAAC,CAgCnG"}
package/dist/cmsJob.js ADDED
@@ -0,0 +1,218 @@
1
+ import { proxyLaunchArgs, startEgressProxy } from "./egressProxy.js";
2
+ export const CONTROLLER_PATH = "/parhelia/capture/controller";
3
+ export const CONTROLLER_BINDING = "parheliaCapture";
4
+ export const CONTROLLER_EVENTS = "parheliaCaptureEvent";
5
+ export const RELAY_BINDING = "parheliaCaptureRelay";
6
+ export const RELAY_DELIVER = "parheliaCaptureDeliver";
7
+ export const CAPTURE_COOKIE = "parhelia-capture";
8
+ /** Stops animations, transitions and the caret before measurement (plan CS-D4 step 1); applied through re-validation. */
9
+ export const PRECONDITION_CSS = "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important;scroll-behavior:auto!important}";
10
+ /** The `host:port` of an origin as the egress proxy sees it on CONNECT or in an absolute request URL. */
11
+ export function hostPortOf(origin) {
12
+ const url = new URL(origin);
13
+ const port = url.port || (url.protocol === "https:" ? "443" : "80");
14
+ return `${url.hostname.toLowerCase()}:${port}`;
15
+ }
16
+ export async function runCmsJob(offer, options) {
17
+ const log = options.log ?? (() => undefined);
18
+ const now = options.now ?? Date.now;
19
+ const origin = new URL(options.origin).origin;
20
+ const controllerUrl = origin + CONTROLLER_PATH;
21
+ if (!offer.previewUrl)
22
+ return { kind: "failed", errorCode: "capture-no-preview-url", message: "The job names no page to load." };
23
+ const targetUrl = new URL(offer.previewUrl, origin).toString();
24
+ const allow = [...new Set([hostPortOf(origin), ...offer.allowlist.map((entry) => entry.toLowerCase())])];
25
+ const proxy = await startEgressProxy({ allow, log: options.egressLog });
26
+ let browser;
27
+ try {
28
+ browser = await options.launch(proxyLaunchArgs(proxy.url));
29
+ const context = await browser.newContext({
30
+ viewport: { width: 1280, height: 900 },
31
+ deviceScaleFactor: 1,
32
+ // The host's bridge is injected by content on heads whose CSP would refuse it; the network is the proxy's to police.
33
+ bypassCSP: true,
34
+ serviceWorkers: "block",
35
+ acceptDownloads: false,
36
+ // CS0 amendment A4: without it a head's own bridge tag and media on a private Parhelia origin are blocked headless.
37
+ permissions: ["local-network-access"],
38
+ });
39
+ await addCaptureCookie(context, origin, offer);
40
+ return await drive(context, offer, { ...options, origin }, controllerUrl, targetUrl, log, now);
41
+ }
42
+ catch (error) {
43
+ if (options.signal.aborted)
44
+ return { kind: "cancelled" };
45
+ return { kind: "failed", errorCode: "capture-worker-failed", message: error instanceof Error ? error.message : String(error) };
46
+ }
47
+ finally {
48
+ await browser?.close().catch(() => undefined);
49
+ await proxy.close();
50
+ }
51
+ }
52
+ /** The capture cookie on the Parhelia origin only (plan CS-D7): HttpOnly, Secure per the origin's scheme, path `/`. */
53
+ async function addCaptureCookie(context, origin, offer) {
54
+ const url = new URL(origin);
55
+ await context.addCookies([
56
+ {
57
+ name: CAPTURE_COOKIE,
58
+ value: offer.cookie,
59
+ domain: url.hostname,
60
+ path: "/",
61
+ httpOnly: true,
62
+ secure: url.protocol === "https:",
63
+ sameSite: "Lax",
64
+ expires: Math.floor(offer.deadlineUnixMs / 1000),
65
+ },
66
+ ]);
67
+ }
68
+ async function drive(context, offer, options, controllerUrl, targetUrl, log, now) {
69
+ const controller = await context.newPage();
70
+ // The controller is the host's code: its errors are the worker's diagnostics (bounded; it logs no secrets).
71
+ controller.on("console", (message) => {
72
+ if (message.type() === "error")
73
+ log({ event: "controller-error", job: offer.jobId, text: message.text().slice(0, 500) });
74
+ });
75
+ const target = await context.newPage();
76
+ let active = true;
77
+ // Armed by the first measurement the controller asks for (plan CS-D3: a target main-frame navigation after measurement
78
+ // ends the attempt). Before it, a head may still settle its own URL (a client router's replaceState while hydrating).
79
+ let measured = false;
80
+ let loaded = false;
81
+ let settle;
82
+ const outcome = new Promise((resolve) => (settle = resolve));
83
+ const end = (value) => {
84
+ if (!active)
85
+ return;
86
+ active = false;
87
+ settle(value);
88
+ };
89
+ const refuse = (reason) => {
90
+ log({ event: "refused", job: offer.jobId, reason });
91
+ throw new Error("refused");
92
+ };
93
+ const isMainFrameOf = (page, frame) => frame === page.mainFrame();
94
+ const pageChanged = () => end({ kind: "failed", errorCode: "capture-page-changed", message: "The page navigated while it was captured; the capture was refused." });
95
+ /** A call into the target: a document destroyed under it after measurement is the navigation it is (it may beat `framenavigated`). */
96
+ const onTarget = async (work) => {
97
+ try {
98
+ return await work();
99
+ }
100
+ catch (error) {
101
+ if (measured && /context was destroyed|navigat/i.test(error instanceof Error ? error.message : String(error)))
102
+ pageChanged();
103
+ throw error;
104
+ }
105
+ };
106
+ await target.exposeBinding(RELAY_BINDING, (source, message) => {
107
+ if (source.page !== target || !isMainFrameOf(target, source.frame))
108
+ return void log({ event: "refused", reason: "relay from a child frame" });
109
+ if (!active)
110
+ return;
111
+ controller.evaluate(([name, m]) => window[name]?.(m), [CONTROLLER_EVENTS, message])
112
+ .catch(() => undefined);
113
+ });
114
+ await controller.exposeBinding(CONTROLLER_BINDING, async (source, name, args) => {
115
+ if (source.page !== controller || !isMainFrameOf(controller, source.frame))
116
+ refuse(`controller call '${name}' from a child frame`);
117
+ if (controller.url() !== controllerUrl)
118
+ refuse(`controller call '${name}' after the controller navigated`);
119
+ if (!active)
120
+ refuse(`controller call '${name}' after the attempt ended`);
121
+ switch (name) {
122
+ case "job":
123
+ return { jobId: offer.jobId, attemptId: offer.attemptId, dialogType: offer.dialogType, parameters: offer.parameters ?? null,
124
+ target: offer.target ?? null };
125
+ case "setViewport": {
126
+ const size = args;
127
+ const width = Math.round(Number(size?.width)), height = Math.round(Number(size?.height));
128
+ if (!(width >= 240 && width <= 3840 && height >= 240 && height <= 4320))
129
+ refuse("viewport out of range");
130
+ await target.setViewportSize({ width, height });
131
+ return true;
132
+ }
133
+ case "load":
134
+ if (loaded)
135
+ refuse("the target loads once");
136
+ loaded = true;
137
+ const response = await target.goto(targetUrl, { waitUntil: "domcontentloaded" });
138
+ // Diagnostics: what the head answered (the path only: a query may carry a one-time preview code) and the identity it states.
139
+ const refusals = [];
140
+ for (let hop = response?.request().redirectedFrom(); hop; hop = hop.redirectedFrom()) {
141
+ const refusal = (await hop.response())?.headers()["x-parhelia-capture-refusal"];
142
+ if (refusal)
143
+ refusals.push(refusal);
144
+ }
145
+ log({ event: "target-loaded", job: offer.jobId, status: response?.status() ?? null, path: new URL(target.url()).pathname,
146
+ ...(refusals.length ? { captureRefusals: refusals } : {}),
147
+ renderedCoordinate: await target.evaluate(() => document.querySelector("script[data-parhelia-rendered-coordinate]")?.textContent?.slice(0, 500) ?? null).catch(() => null) });
148
+ if (!(await target.evaluate(() => !!window.__PARHELIA_EDITING_BRIDGE_RUNTIME__))) {
149
+ // The head's own bridge bowed out at top level (an older bridge, a loader that skips top-level pages): the host's
150
+ // current bridge, by content.
151
+ await target.addScriptTag({ content: await options.bridgeScript() });
152
+ log({ event: "bridge-injected", job: offer.jobId });
153
+ }
154
+ return true;
155
+ case "relaySend":
156
+ if (args?.name === "captureDom")
157
+ measured = true;
158
+ await onTarget(() => target.evaluate(([deliver, m]) => window[deliver]?.(m), [RELAY_DELIVER, args]));
159
+ return true;
160
+ case "inject":
161
+ if (args === "precondition")
162
+ await onTarget(() => target.addStyleTag({ content: PRECONDITION_CSS }));
163
+ else if (args === "prescroll")
164
+ await onTarget(() => prescroll(target));
165
+ else
166
+ refuse("unknown injection");
167
+ return true;
168
+ case "screenshot": {
169
+ const request = args;
170
+ const png = await onTarget(() => target.screenshot({ clip: request.clip, fullPage: !!request.fullPage, scale: "css", caret: "initial",
171
+ animations: "allow", type: "png" }));
172
+ return "data:image/png;base64," + png.toString("base64");
173
+ }
174
+ case "complete":
175
+ end({ kind: "result", result: args?.result ?? null });
176
+ return true;
177
+ default:
178
+ return refuse(`unknown call '${name}'`);
179
+ }
180
+ });
181
+ controller.on("framenavigated", (frame) => {
182
+ if (frame === controller.mainFrame() && frame.url() !== controllerUrl && frame.url() !== "about:blank")
183
+ end({ kind: "failed", errorCode: "capture-controller-navigated", message: "The controller page navigated away; the attempt ended." });
184
+ });
185
+ target.on("framenavigated", (frame) => {
186
+ if (frame === target.mainFrame() && measured)
187
+ pageChanged();
188
+ });
189
+ options.signal.addEventListener("abort", () => end({ kind: "cancelled" }), { once: true });
190
+ const deadline = setTimeout(() => end({ kind: "failed", errorCode: "capture-deadline", message: "The capture ran out of time." }), Math.max(1, offer.deadlineUnixMs - now() - 1_000));
191
+ try {
192
+ const opened = await controller.goto(controllerUrl, { waitUntil: "domcontentloaded" });
193
+ if (!opened || opened.status() !== 200)
194
+ end({ kind: "failed", errorCode: "capture-controller-unavailable", message: `The controller page answered ${opened?.status() ?? "nothing"}.` });
195
+ return await outcome;
196
+ }
197
+ finally {
198
+ clearTimeout(deadline);
199
+ active = false;
200
+ }
201
+ }
202
+ /** One pass down the page for lazy images, then back to the top (plan CS-D4 step 1). */
203
+ async function prescroll(target) {
204
+ await target.evaluate(async () => {
205
+ const step = Math.max(200, window.innerHeight * 0.8);
206
+ for (let y = 0; y < document.documentElement.scrollHeight; y += step) {
207
+ window.scrollTo(0, y);
208
+ await new Promise((resolve) => setTimeout(resolve, 100));
209
+ }
210
+ const pending = [...document.images].filter((image) => !image.complete);
211
+ await Promise.race([
212
+ Promise.all(pending.map((image) => new Promise((resolve) => { image.onload = image.onerror = resolve; }))),
213
+ new Promise((resolve) => setTimeout(resolve, 3_000)),
214
+ ]);
215
+ window.scrollTo(0, 0);
216
+ await new Promise((resolve) => setTimeout(resolve, 100));
217
+ });
218
+ }
@@ -0,0 +1,59 @@
1
+ import net from "node:net";
2
+ /**
3
+ * The sidecar's own floor: private, loopback, link-local (metadata), shared, benchmark, documentation, multicast and reserved
4
+ * space, and NAT64. A job's `blockedRanges` (the host's one table, `SafeUrlPolicy.BlockedRanges`) add to it; nothing a job
5
+ * says takes a range out of it.
6
+ */
7
+ export declare const BASELINE_BLOCKED_RANGES: readonly string[];
8
+ /** A block list of CIDR ranges (IPv4-mapped IPv6 addresses are checked as their IPv4 address). Malformed entries throw. */
9
+ export declare function blockListOf(ranges: readonly string[]): net.BlockList;
10
+ /** Whether an address lies in the baseline's blocked space (or `extra`); anything that is not an IP address is blocked. */
11
+ export declare function isBlockedAddress(ip: string, extra?: net.BlockList): boolean;
12
+ export type EgressDecision = {
13
+ ok: boolean;
14
+ address?: string;
15
+ reason: string;
16
+ };
17
+ export type EgressLogEntry = {
18
+ kind: "http" | "connect";
19
+ host: string;
20
+ port: number;
21
+ } & EgressDecision;
22
+ export type EgressProxyOptions = {
23
+ /** `host:port` pairs (lower case) the job allows whatever they resolve to (a `cms` job; a public-web job has none). */
24
+ allow: readonly string[];
25
+ /** The job's blocked ranges (CIDR), on top of {@link BASELINE_BLOCKED_RANGES}. */
26
+ blockedRanges?: readonly string[];
27
+ /**
28
+ * Addresses refused whatever range they are in (a public-web job: every address of the Parhelia origin and of this
29
+ * machine, so a public Parhelia or a public address of the sidecar's own machine is no way in either).
30
+ */
31
+ denyAddresses?: readonly string[];
32
+ /** Listen on this Unix socket (the browser host's egress socket; created `0600`) instead of a loopback port. */
33
+ socketPath?: string;
34
+ /** The socket is `0660` (an installed sidecar shares it with the browser user through the ipc group). */
35
+ socketGroupAccess?: boolean;
36
+ /** Test seam: fixed answers for names. */
37
+ resolve?: (host: string) => Promise<string[]>;
38
+ /**
39
+ * Test seam: where the connection to a CHECKED address physically goes (the SSRF fixtures stand public addresses in for
40
+ * local servers). The decision is untouched: it is always made on the address the name resolved to.
41
+ */
42
+ connectTo?: (address: string, port: number) => {
43
+ host: string;
44
+ port: number;
45
+ };
46
+ log?: (entry: EgressLogEntry) => void;
47
+ };
48
+ export type EgressProxy = {
49
+ /** `http://127.0.0.1:<port>` for a loopback listener; the socket path for a Unix one. */
50
+ url: string;
51
+ close(): Promise<void>;
52
+ };
53
+ /** The one decision for a connection to `host:port`. */
54
+ export declare function decideEgress(host: string, port: number, options: EgressProxyOptions): Promise<EgressDecision>;
55
+ /** Starts a proxy for one job: on an ephemeral loopback port, or on the job's Unix socket. */
56
+ export declare function startEgressProxy(options: EgressProxyOptions): Promise<EgressProxy>;
57
+ /** Chromium's flags that send every connection, loopback included, through the proxy (CS0: proven by the spike). */
58
+ export declare function proxyLaunchArgs(proxyUrl: string): string[];
59
+ //# sourceMappingURL=egressProxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"egressProxy.d.ts","sourceRoot":"","sources":["../src/egressProxy.ts"],"names":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