@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.
- package/README.md +83 -2
- package/dist/browserHost.d.ts +19 -0
- package/dist/browserHost.d.ts.map +1 -0
- package/dist/browserHost.js +247 -0
- package/dist/browserHostLink.d.ts +50 -0
- package/dist/browserHostLink.d.ts.map +1 -0
- package/dist/browserHostLink.js +193 -0
- package/dist/browserHostProtocol.d.ts +61 -0
- package/dist/browserHostProtocol.d.ts.map +1 -0
- package/dist/browserHostProtocol.js +29 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +239 -0
- package/dist/cmsJob.d.ts +38 -0
- package/dist/cmsJob.d.ts.map +1 -0
- package/dist/cmsJob.js +218 -0
- package/dist/egressProxy.d.ts +59 -0
- package/dist/egressProxy.d.ts.map +1 -0
- package/dist/egressProxy.js +205 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/install/doctor.d.ts +31 -0
- package/dist/install/doctor.d.ts.map +1 -0
- package/dist/install/doctor.js +189 -0
- package/dist/install/install.d.ts +72 -0
- package/dist/install/install.d.ts.map +1 -0
- package/dist/install/install.js +267 -0
- package/dist/install/layout.d.ts +81 -0
- package/dist/install/layout.d.ts.map +1 -0
- package/dist/install/layout.js +77 -0
- package/dist/install/services.d.ts +16 -0
- package/dist/install/services.d.ts.map +1 -0
- package/dist/install/services.js +94 -0
- package/dist/install/sys.d.ts +91 -0
- package/dist/install/sys.d.ts.map +1 -0
- package/dist/install/sys.js +260 -0
- package/dist/install/units.d.ts +57 -0
- package/dist/install/units.d.ts.map +1 -0
- package/dist/install/units.js +244 -0
- package/dist/install/updater.d.ts +66 -0
- package/dist/install/updater.d.ts.map +1 -0
- package/dist/install/updater.js +111 -0
- package/dist/install/versions.d.ts +61 -0
- package/dist/install/versions.d.ts.map +1 -0
- package/dist/install/versions.js +204 -0
- package/dist/isolation.d.ts +76 -0
- package/dist/isolation.d.ts.map +1 -0
- package/dist/isolation.js +163 -0
- package/dist/parheliaClient.d.ts +97 -0
- package/dist/parheliaClient.d.ts.map +1 -0
- package/dist/parheliaClient.js +111 -0
- package/dist/version.d.ts +13 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +36 -0
- package/dist/webIsolation.d.ts +24 -0
- package/dist/webIsolation.d.ts.map +1 -0
- package/dist/webIsolation.js +112 -0
- package/dist/webJob.d.ts +56 -0
- package/dist/webJob.d.ts.map +1 -0
- package/dist/webJob.js +177 -0
- package/dist/worker.d.ts +53 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +213 -0
- package/package.json +28 -4
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
2
|
+
export declare const WORKER_KEY_PREFIX = "pcs1_";
|
|
3
|
+
export type CaptureJobTarget = {
|
|
4
|
+
store: string;
|
|
5
|
+
itemId: string;
|
|
6
|
+
nativeId?: string;
|
|
7
|
+
language: string;
|
|
8
|
+
version: number;
|
|
9
|
+
site?: string;
|
|
10
|
+
};
|
|
11
|
+
export type CaptureJobOffer = {
|
|
12
|
+
jobId: string;
|
|
13
|
+
attemptId: string;
|
|
14
|
+
kind: string;
|
|
15
|
+
dialogType: string;
|
|
16
|
+
parameters?: Record<string, unknown> | null;
|
|
17
|
+
target?: CaptureJobTarget | null;
|
|
18
|
+
previewUrl?: string | null;
|
|
19
|
+
renderContext?: unknown;
|
|
20
|
+
allowlist: string[];
|
|
21
|
+
/** A public-web job: the host's blocked ranges (CIDR), on top of the sidecar's own floor. */
|
|
22
|
+
blockedRanges?: string[] | null;
|
|
23
|
+
deadlineUnixMs: number;
|
|
24
|
+
cookie: string;
|
|
25
|
+
};
|
|
26
|
+
export type CapturePollAnswer = {
|
|
27
|
+
protocolVersion: number;
|
|
28
|
+
jobs: CaptureJobOffer[];
|
|
29
|
+
cancelledAttempts: string[];
|
|
30
|
+
/** CS6: the version the host names (absent for a source build). */
|
|
31
|
+
wantedVersion?: string;
|
|
32
|
+
/** CS6: below it this worker turns public-web off by itself. */
|
|
33
|
+
securityMinimum?: string;
|
|
34
|
+
browserMaxAgeDays?: number;
|
|
35
|
+
/** CS6: why the host serves no public-web job of this worker. */
|
|
36
|
+
webRefusal?: string;
|
|
37
|
+
};
|
|
38
|
+
/** CS6: what a poll reports about the install (the host shows it under Settings › Capture service). */
|
|
39
|
+
export type CaptureWorkerReport = {
|
|
40
|
+
browserRevision?: string;
|
|
41
|
+
browserReleasedUtc?: string;
|
|
42
|
+
problems: string[];
|
|
43
|
+
webOffReason?: string;
|
|
44
|
+
};
|
|
45
|
+
/** CS7: the code of an answer that came from in front of Parhelia (a sign-in, an SSO proxy), never from Parhelia itself. */
|
|
46
|
+
export declare const SSO_FRONT_CODE = "capture-origin-fronted";
|
|
47
|
+
/** The named reason when an answer came from in front of Parhelia, or undefined when it is Parhelia's own. */
|
|
48
|
+
export declare function frontOf(status: number, contentType: string, json: {
|
|
49
|
+
error?: string;
|
|
50
|
+
} | undefined): string | undefined;
|
|
51
|
+
export declare class ParheliaRefusedError extends Error {
|
|
52
|
+
readonly status: number;
|
|
53
|
+
readonly code: string | undefined;
|
|
54
|
+
constructor(status: number, code: string | undefined, message: string);
|
|
55
|
+
}
|
|
56
|
+
export declare function newWorkerKey(): string;
|
|
57
|
+
/** The key's SHA-256, base64url: all a pairing sends (the key itself never leaves this machine but as the bearer). */
|
|
58
|
+
export declare function workerKeyHash(key: string): string;
|
|
59
|
+
export type ParheliaClientOptions = {
|
|
60
|
+
/** The origin the worker reaches Parhelia at (often an internal one). */
|
|
61
|
+
origin: string;
|
|
62
|
+
key: string;
|
|
63
|
+
version: string;
|
|
64
|
+
fetch?: typeof fetch;
|
|
65
|
+
};
|
|
66
|
+
export declare class ParheliaClient {
|
|
67
|
+
readonly origin: string;
|
|
68
|
+
private readonly key;
|
|
69
|
+
private readonly version;
|
|
70
|
+
private readonly fetchImpl;
|
|
71
|
+
constructor(options: ParheliaClientOptions);
|
|
72
|
+
poll(capabilities: string[], waitMs: number, signal?: AbortSignal, report?: CaptureWorkerReport): Promise<CapturePollAnswer>;
|
|
73
|
+
/** CS6: the version this host names, its hashes, and this worker's update policy (the updater asks with the worker key). */
|
|
74
|
+
manifest(): Promise<import("./install/updater.js").ManifestAnswer>;
|
|
75
|
+
complete(jobId: string, attemptId: string, result: unknown, error?: string): Promise<{
|
|
76
|
+
status: string;
|
|
77
|
+
}>;
|
|
78
|
+
/** The host's current bridge, by content (injected where the head's own bridge did not start at top level). */
|
|
79
|
+
bridge(): Promise<string>;
|
|
80
|
+
/**
|
|
81
|
+
* Opens an egress probe (plan §8 verification step 1): the host keeps a one-time token and answers its nonce to whoever
|
|
82
|
+
* presents it once. The worker's own read is the positive control; a probe for the restricted browser is a second one.
|
|
83
|
+
*/
|
|
84
|
+
openProbe(): Promise<{
|
|
85
|
+
url: string;
|
|
86
|
+
nonce: string;
|
|
87
|
+
}>;
|
|
88
|
+
/** Exchanges a one-time pairing code for this key (the server stores only the key's hash). */
|
|
89
|
+
static pair(origin: string, code: string, key: string, name: string, fetchImpl?: typeof fetch): Promise<{
|
|
90
|
+
workerId: string;
|
|
91
|
+
name: string;
|
|
92
|
+
capabilities: string[];
|
|
93
|
+
}>;
|
|
94
|
+
private post;
|
|
95
|
+
private static read;
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=parheliaClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parheliaClient.d.ts","sourceRoot":"","sources":["../src/parheliaClient.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAClC,eAAO,MAAM,iBAAiB,UAAU,CAAC;AAEzC,MAAM,MAAM,gBAAgB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EA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AAC,CAEjE;IAED,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAEvG;IAED,+GAA+G;IACzG,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,CAE9B;IAED;;;OAGG;IACG,SAAS,IAAI,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAGzD;IAED,8FAA8F;IAC9F,OAAa,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,GAAE,OAAO,KAAa;kBAOjE,MAAM;cAAQ,MAAM;sBAAgB,MAAM,EAAE;OACpF;YAEa,IAAI;mBAWG,IAAI;CAiB1B"}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Capture sidecar CS4: the worker's line to Parhelia (plan CS-D8, "authenticate independently"): outbound only, the worker
|
|
3
|
+
* key as a bearer, never a cookie. The capture cookie a poll answer carries goes into the job's browser context only.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
export const PROTOCOL_VERSION = 1;
|
|
7
|
+
export const WORKER_KEY_PREFIX = "pcs1_";
|
|
8
|
+
/** CS7: the code of an answer that came from in front of Parhelia (a sign-in, an SSO proxy), never from Parhelia itself. */
|
|
9
|
+
export const SSO_FRONT_CODE = "capture-origin-fronted";
|
|
10
|
+
/** The named reason when an answer came from in front of Parhelia, or undefined when it is Parhelia's own. */
|
|
11
|
+
export function frontOf(status, contentType, json) {
|
|
12
|
+
const advice = "use the address this machine reaches Parhelia at directly (its internal origin, not the public one behind the sign-in) as --origin.";
|
|
13
|
+
if (status >= 300 && status < 400)
|
|
14
|
+
return `Parhelia's address answered a redirect: a sign-in (SSO) sits in front of it; ${advice}`;
|
|
15
|
+
if (/text\/html/i.test(contentType) && !json)
|
|
16
|
+
return `Parhelia's address answered a web page, not the capture protocol: a sign-in (SSO) or another site sits in front of it; ${advice}`;
|
|
17
|
+
if ((status === 401 || status === 403 || status === 407) && !json?.error?.startsWith("capture-"))
|
|
18
|
+
return `Parhelia's address answered ${status} from something in front of Parhelia (an SSO proxy), not from Parhelia; ${advice}`;
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
export class ParheliaRefusedError extends Error {
|
|
22
|
+
status;
|
|
23
|
+
code;
|
|
24
|
+
constructor(status, code, message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.status = status;
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.name = "ParheliaRefusedError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export function newWorkerKey() {
|
|
32
|
+
return WORKER_KEY_PREFIX + randomBytes(32).toString("base64url");
|
|
33
|
+
}
|
|
34
|
+
/** The key's SHA-256, base64url: all a pairing sends (the key itself never leaves this machine but as the bearer). */
|
|
35
|
+
export function workerKeyHash(key) {
|
|
36
|
+
return createHash("sha256").update(key.trim(), "utf8").digest("base64url");
|
|
37
|
+
}
|
|
38
|
+
export class ParheliaClient {
|
|
39
|
+
origin;
|
|
40
|
+
key;
|
|
41
|
+
version;
|
|
42
|
+
fetchImpl;
|
|
43
|
+
constructor(options) {
|
|
44
|
+
this.origin = new URL(options.origin).origin;
|
|
45
|
+
this.key = options.key.trim();
|
|
46
|
+
this.version = options.version;
|
|
47
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
48
|
+
}
|
|
49
|
+
poll(capabilities, waitMs, signal, report) {
|
|
50
|
+
return this.post("/parhelia/capture/worker/poll", { protocolVersion: PROTOCOL_VERSION, version: this.version, capabilities, waitMs, ...(report ? { report } : {}) }, signal);
|
|
51
|
+
}
|
|
52
|
+
/** CS6: the version this host names, its hashes, and this worker's update policy (the updater asks with the worker key). */
|
|
53
|
+
manifest() {
|
|
54
|
+
return this.post("/parhelia/capture/worker/manifest", {});
|
|
55
|
+
}
|
|
56
|
+
complete(jobId, attemptId, result, error) {
|
|
57
|
+
return this.post("/parhelia/capture/worker/complete", { jobId, attemptId, result: result ?? null, error: error ?? null });
|
|
58
|
+
}
|
|
59
|
+
/** The host's current bridge, by content (injected where the head's own bridge did not start at top level). */
|
|
60
|
+
async bridge() {
|
|
61
|
+
return (await this.post("/parhelia/capture/worker/bridge", {})).script;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Opens an egress probe (plan §8 verification step 1): the host keeps a one-time token and answers its nonce to whoever
|
|
65
|
+
* presents it once. The worker's own read is the positive control; a probe for the restricted browser is a second one.
|
|
66
|
+
*/
|
|
67
|
+
async openProbe() {
|
|
68
|
+
const probe = await this.post("/parhelia/capture/worker/egress-probe", {});
|
|
69
|
+
return { url: new URL(probe.path, this.origin).toString(), nonce: probe.nonce };
|
|
70
|
+
}
|
|
71
|
+
/** Exchanges a one-time pairing code for this key (the server stores only the key's hash). */
|
|
72
|
+
static async pair(origin, code, key, name, fetchImpl = fetch) {
|
|
73
|
+
const response = await fetchImpl(new URL("/parhelia/capture/pair", origin), {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers: { "content-type": "application/json" },
|
|
76
|
+
body: JSON.stringify({ code, keyHash: workerKeyHash(key), name }),
|
|
77
|
+
redirect: "manual",
|
|
78
|
+
});
|
|
79
|
+
return ParheliaClient.read(response);
|
|
80
|
+
}
|
|
81
|
+
async post(path, body, signal) {
|
|
82
|
+
const response = await this.fetchImpl(new URL(path, this.origin), {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${this.key}` },
|
|
85
|
+
body: JSON.stringify(body),
|
|
86
|
+
redirect: "manual",
|
|
87
|
+
signal,
|
|
88
|
+
});
|
|
89
|
+
return ParheliaClient.read(response);
|
|
90
|
+
}
|
|
91
|
+
static async read(response) {
|
|
92
|
+
const text = await response.text();
|
|
93
|
+
let json;
|
|
94
|
+
try {
|
|
95
|
+
json = text ? JSON.parse(text) : undefined;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
json = undefined;
|
|
99
|
+
}
|
|
100
|
+
// Parhelia's own answers are JSON naming a capture code. A redirect, an HTML page, or a refusal without Parhelia's JSON
|
|
101
|
+
// comes from something in front of it (an SSO proxy such as Pangolin answers a bare 401 "Unauthorized"): CS7.
|
|
102
|
+
const front = frontOf(response.status, response.headers.get("content-type") ?? "", json);
|
|
103
|
+
if (front)
|
|
104
|
+
throw new ParheliaRefusedError(response.status, SSO_FRONT_CODE, front);
|
|
105
|
+
if (!response.ok)
|
|
106
|
+
throw new ParheliaRefusedError(response.status, json?.error, json?.message ?? `Parhelia answered ${response.status}`);
|
|
107
|
+
if (json === undefined)
|
|
108
|
+
throw new ParheliaRefusedError(response.status, undefined, "Parhelia answered something that is not JSON.");
|
|
109
|
+
return json;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const SIDECAR_VERSION: string;
|
|
2
|
+
type Parsed = {
|
|
3
|
+
major: number;
|
|
4
|
+
minor: number;
|
|
5
|
+
patch: number;
|
|
6
|
+
pre?: string;
|
|
7
|
+
};
|
|
8
|
+
/** `major.minor.patch[-pre]`; anything else (a source build's "dev") is not a release version. */
|
|
9
|
+
export declare function parseVersion(text: string | undefined | null): Parsed | undefined;
|
|
10
|
+
/** Like the host's CaptureSidecarVersion: a pre-release sorts before its release; an unparsable version sorts below everything. */
|
|
11
|
+
export declare function compareVersions(a: string | undefined | null, b: string | undefined | null): number;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=version.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAYA,eAAO,MAAM,eAAe,QAAS,CAAC;AAEtC,KAAK,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5E,kGAAkG;AAClG,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,SAAS,CAIhF;AAED,mIAAmI;AACnI,wBAAgB,eAAe,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,EAAE,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CASlG"}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** The sidecar's version as its package states it (the release pipeline writes it; a source checkout says "dev"). */
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
function read() {
|
|
4
|
+
try {
|
|
5
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
6
|
+
return pkg.version && !pkg.version.startsWith("#{") ? pkg.version : "dev";
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return "dev";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export const SIDECAR_VERSION = read();
|
|
13
|
+
/** `major.minor.patch[-pre]`; anything else (a source build's "dev") is not a release version. */
|
|
14
|
+
export function parseVersion(text) {
|
|
15
|
+
const match = (text ?? "").trim().replace(/^v/, "").replace(/\+.*$/, "").match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);
|
|
16
|
+
if (!match)
|
|
17
|
+
return undefined;
|
|
18
|
+
return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), pre: match[4] };
|
|
19
|
+
}
|
|
20
|
+
/** Like the host's CaptureSidecarVersion: a pre-release sorts before its release; an unparsable version sorts below everything. */
|
|
21
|
+
export function compareVersions(a, b) {
|
|
22
|
+
const left = parseVersion(a);
|
|
23
|
+
const right = parseVersion(b);
|
|
24
|
+
if (!left || !right)
|
|
25
|
+
return !left && !right ? 0 : !left ? -1 : 1;
|
|
26
|
+
for (const key of ["major", "minor", "patch"])
|
|
27
|
+
if (left[key] !== right[key])
|
|
28
|
+
return left[key] < right[key] ? -1 : 1;
|
|
29
|
+
if (left.pre === right.pre)
|
|
30
|
+
return 0;
|
|
31
|
+
if (left.pre === undefined)
|
|
32
|
+
return 1;
|
|
33
|
+
if (right.pre === undefined)
|
|
34
|
+
return -1;
|
|
35
|
+
return left.pre < right.pre ? -1 : 1;
|
|
36
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { BrowserHostLink } from "./browserHostLink.js";
|
|
2
|
+
import type { EgressLogEntry } from "./egressProxy.js";
|
|
3
|
+
import { type IsolationReport } from "./isolation.js";
|
|
4
|
+
import type { ParheliaClient } from "./parheliaClient.js";
|
|
5
|
+
export type WebIsolationOptions = {
|
|
6
|
+
client: Pick<ParheliaClient, "origin" | "openProbe">;
|
|
7
|
+
link: BrowserHostLink;
|
|
8
|
+
platform?: string;
|
|
9
|
+
/** A probe on another host when Parhelia runs on this machine (its answer, read by the worker, is the marker). */
|
|
10
|
+
probeUrl?: string;
|
|
11
|
+
/** A public page the browser must load through the proxy (step 7); omitted: not checked. */
|
|
12
|
+
publicUrl?: string;
|
|
13
|
+
/** The blocked ranges the proxy applies in the layer-2 checks (the host's table when known). */
|
|
14
|
+
blockedRanges?: readonly string[];
|
|
15
|
+
resolve?: (host: string) => Promise<string[]>;
|
|
16
|
+
ownAddresses?: () => string[];
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
egressLog?: (entry: EgressLogEntry) => void;
|
|
19
|
+
};
|
|
20
|
+
export declare function resolveAll(host: string, resolve?: (host: string) => Promise<string[]>): Promise<string[]>;
|
|
21
|
+
/** The addresses a public-web job's proxy refuses whatever range they are in: Parhelia's and this machine's own. */
|
|
22
|
+
export declare function webDenyAddresses(origin: string, options?: Pick<WebIsolationOptions, "resolve" | "ownAddresses">): Promise<string[]>;
|
|
23
|
+
export declare function verifyWebIsolation(options: WebIsolationOptions): Promise<IsolationReport>;
|
|
24
|
+
//# sourceMappingURL=webIsolation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webIsolation.d.ts","sourceRoot":"","sources":["../src/webIsolation.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,eAAe,EAAgB,MAAM,sBAAsB,CAAC;AAE1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAEmB,KAAK,eAAe,EAC7C,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D,MAAM,MAAM,mBAAmB,GAAG;IAChC,MAAM,EAAE,IAAI,CAAC,cAAc,EAAE,QAAQ,GAAG,WAAW,CAAC,CAAC;IACrD,IAAI,EAAE,eAAe,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kHAAkH;IAClH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4FAA4F;IAC5F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gGAAgG;IAChG,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC9C,YAAY,CAAC,EAAE,MAAM,MAAM,EAAE,CAAC;IAC9B,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;CAC7C,CAAC;AAEF,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAK/G;AAED,oHAAoH;AACpH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,GAAG,cAAc,CAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAG7I;AAED,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,eAAe,CAAC,CA0D/F"}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Capture sidecar CS5w (plan §8 "Verification that proves enforcement"): the self-test that gates `public-web`. Positive
|
|
3
|
+
* control first (the unrestricted worker fetches a remote nonce and a loopback nonce), then the actual browser in its
|
|
4
|
+
* restricted host with the proxy switched off must fetch neither, the host's view must hold no foreign socket and no D-Bus,
|
|
5
|
+
* and with the proxy on Parhelia's own address is refused while a public page (when named) loads.
|
|
6
|
+
*/
|
|
7
|
+
import dns from "node:dns/promises";
|
|
8
|
+
import http from "node:http";
|
|
9
|
+
import net from "node:net";
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
import { judgeIsolation, ownAddresses, parheliaIsColocated, webPreconditionRefusal, } from "./isolation.js";
|
|
12
|
+
export async function resolveAll(host, resolve) {
|
|
13
|
+
const bare = host.replace(/^\[|\]$/g, "");
|
|
14
|
+
if (net.isIP(bare))
|
|
15
|
+
return [bare];
|
|
16
|
+
if (resolve)
|
|
17
|
+
return resolve(bare);
|
|
18
|
+
return (await dns.lookup(bare, { all: true })).map((entry) => entry.address);
|
|
19
|
+
}
|
|
20
|
+
/** The addresses a public-web job's proxy refuses whatever range they are in: Parhelia's and this machine's own. */
|
|
21
|
+
export async function webDenyAddresses(origin, options = {}) {
|
|
22
|
+
const parhelia = await resolveAll(new URL(origin).hostname, options.resolve).catch(() => []);
|
|
23
|
+
return [...new Set([...parhelia, ...(options.ownAddresses ?? ownAddresses)()])];
|
|
24
|
+
}
|
|
25
|
+
export async function verifyWebIsolation(options) {
|
|
26
|
+
const platform = options.platform ?? process.platform;
|
|
27
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
28
|
+
const parheliaAddresses = await resolveAll(new URL(options.client.origin).hostname, options.resolve).catch(() => []);
|
|
29
|
+
const colocated = parheliaIsColocated(parheliaAddresses, (options.ownAddresses ?? ownAddresses)());
|
|
30
|
+
const refusal = webPreconditionRefusal({ platform, colocated, probeUrl: options.probeUrl });
|
|
31
|
+
if (refusal)
|
|
32
|
+
return { ok: false, code: refusal.code, reason: refusal.message, checks: [] };
|
|
33
|
+
if (!options.link.host)
|
|
34
|
+
return { ok: false, code: "capture-web-no-browser-host", reason: "No browser host is connected to this worker.", checks: [] };
|
|
35
|
+
const policy = {
|
|
36
|
+
blockedRanges: options.blockedRanges ?? [],
|
|
37
|
+
denyAddresses: await webDenyAddresses(options.client.origin, options),
|
|
38
|
+
resolve: options.resolve,
|
|
39
|
+
};
|
|
40
|
+
const local = await startNonceServer();
|
|
41
|
+
try {
|
|
42
|
+
// 1. The remote probe, with its positive control: another host (Parhelia when it is elsewhere, else --probe-url).
|
|
43
|
+
let remote;
|
|
44
|
+
let browserRemoteUrl;
|
|
45
|
+
let parheliaThroughProxy;
|
|
46
|
+
if (options.probeUrl) {
|
|
47
|
+
const control = await read(fetchImpl, options.probeUrl);
|
|
48
|
+
const marker = control.text?.trim().slice(0, 200) ?? "";
|
|
49
|
+
remote = { url: options.probeUrl, marker, controlOk: control.ok && marker.length >= 8,
|
|
50
|
+
controlDetail: control.error ?? (marker.length < 8 ? "its answer is too short to serve as a marker" : undefined) };
|
|
51
|
+
browserRemoteUrl = options.probeUrl;
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
const control = await options.client.openProbe();
|
|
55
|
+
const answer = await read(fetchImpl, control.url);
|
|
56
|
+
remote = { url: control.url, marker: control.nonce, controlOk: !!answer.text?.includes(control.nonce), controlDetail: answer.error };
|
|
57
|
+
const forBrowser = await options.client.openProbe();
|
|
58
|
+
browserRemoteUrl = forBrowser.url;
|
|
59
|
+
remote = { ...remote, marker: forBrowser.nonce, url: forBrowser.url };
|
|
60
|
+
}
|
|
61
|
+
// Layer 2: Parhelia's own address through the proxy (a fresh token; its nonce must not come back).
|
|
62
|
+
if (!options.probeUrl || !colocated) {
|
|
63
|
+
const throughProxy = await options.client.openProbe().catch(() => undefined);
|
|
64
|
+
if (throughProxy)
|
|
65
|
+
parheliaThroughProxy = { url: throughProxy.url, marker: throughProxy.nonce };
|
|
66
|
+
}
|
|
67
|
+
// 2-3. The local probe and its control.
|
|
68
|
+
const localControl = await read(fetchImpl, local.url);
|
|
69
|
+
const localEvidence = { url: local.url, marker: local.nonce, controlOk: !!localControl.text?.includes(local.nonce), controlDetail: localControl.error };
|
|
70
|
+
const probes = [
|
|
71
|
+
{ name: "remote-direct", url: browserRemoteUrl, proxied: false },
|
|
72
|
+
{ name: "local-direct", url: local.url, proxied: false },
|
|
73
|
+
];
|
|
74
|
+
if (parheliaThroughProxy)
|
|
75
|
+
probes.push({ name: "parhelia-proxied", url: parheliaThroughProxy.url, proxied: true });
|
|
76
|
+
if (options.publicUrl)
|
|
77
|
+
probes.push({ name: "public-proxied", url: options.publicUrl, proxied: true });
|
|
78
|
+
// 4-7. The actual browser in its restricted host.
|
|
79
|
+
const observations = await options.link.selfTest(probes, policy, 90_000, options.egressLog);
|
|
80
|
+
return judgeIsolation({ platform, remote, local: localEvidence, parheliaThroughProxy, publicUrl: options.publicUrl, observations,
|
|
81
|
+
socketDir: options.link.socketDir });
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
return { ok: false, code: "capture-web-isolation-unproven", reason: `The isolation self-test did not complete: ${error instanceof Error ? error.message : String(error)}`, checks: [] };
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
await local.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function read(fetchImpl, url) {
|
|
91
|
+
try {
|
|
92
|
+
const response = await fetchImpl(url, { redirect: "manual", signal: AbortSignal.timeout(8_000) });
|
|
93
|
+
return { ok: response.ok, text: (await response.text()).slice(0, 4_000) };
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** A loopback endpoint answering a per-run nonce (step 2). Listens on every loopback the machine has for IPv4. */
|
|
100
|
+
async function startNonceServer() {
|
|
101
|
+
const nonce = randomBytes(18).toString("base64url");
|
|
102
|
+
const server = http.createServer((_request, response) => {
|
|
103
|
+
response.writeHead(200, { "content-type": "text/plain" });
|
|
104
|
+
response.end(nonce);
|
|
105
|
+
});
|
|
106
|
+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
107
|
+
return {
|
|
108
|
+
url: `http://127.0.0.1:${server.address().port}/`,
|
|
109
|
+
nonce,
|
|
110
|
+
close: () => new Promise((resolve) => server.close(() => resolve())),
|
|
111
|
+
};
|
|
112
|
+
}
|
package/dist/webJob.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Browser } from "playwright-core";
|
|
2
|
+
export declare const MAX_IMAGE_HEIGHT = 7680;
|
|
3
|
+
export declare const PNG_SIZE_FALLBACK_THRESHOLD = 2500000;
|
|
4
|
+
export declare const JPEG_QUALITY = 0.9;
|
|
5
|
+
/** The parameters the host sends (CaptureUrlScreenshotFunction), re-checked here: the worker trusts no job blindly. */
|
|
6
|
+
export type WebJobParameters = {
|
|
7
|
+
url: string;
|
|
8
|
+
scope?: "viewport" | "page";
|
|
9
|
+
viewportWidth?: number;
|
|
10
|
+
viewportHeight?: number;
|
|
11
|
+
maxImageWidth?: number;
|
|
12
|
+
};
|
|
13
|
+
export type WebCaptureResult = {
|
|
14
|
+
success: true;
|
|
15
|
+
scope: "viewport" | "page";
|
|
16
|
+
image: {
|
|
17
|
+
dataUrl: string;
|
|
18
|
+
fileName: string;
|
|
19
|
+
contentType: string;
|
|
20
|
+
fileSize: number;
|
|
21
|
+
};
|
|
22
|
+
imageWidth: number;
|
|
23
|
+
imageHeight: number;
|
|
24
|
+
finalUrl: string;
|
|
25
|
+
httpStatus: number | null;
|
|
26
|
+
truncated: boolean;
|
|
27
|
+
};
|
|
28
|
+
export type WebJobOutcome = {
|
|
29
|
+
kind: "result";
|
|
30
|
+
result: WebCaptureResult;
|
|
31
|
+
} | {
|
|
32
|
+
kind: "failed";
|
|
33
|
+
errorCode: string;
|
|
34
|
+
message: string;
|
|
35
|
+
} | {
|
|
36
|
+
kind: "cancelled";
|
|
37
|
+
};
|
|
38
|
+
export type WebJobOptions = {
|
|
39
|
+
/** Launches the job's browser with these flags (the proxy's; the sandbox is the launcher's to keep on). */
|
|
40
|
+
launch: (args: string[]) => Promise<Browser>;
|
|
41
|
+
/** The flags that send every connection through the job's egress proxy. */
|
|
42
|
+
proxyArgs: string[];
|
|
43
|
+
deadlineUnixMs: number;
|
|
44
|
+
signal: AbortSignal;
|
|
45
|
+
now?: () => number;
|
|
46
|
+
};
|
|
47
|
+
/** The job's parameters as this sidecar will run them, or the reason it will not. */
|
|
48
|
+
export declare function normalizeWebParameters(raw: unknown): {
|
|
49
|
+
ok: true;
|
|
50
|
+
value: Required<WebJobParameters>;
|
|
51
|
+
} | {
|
|
52
|
+
ok: false;
|
|
53
|
+
message: string;
|
|
54
|
+
};
|
|
55
|
+
export declare function runWebJob(rawParameters: unknown, options: WebJobOptions): Promise<WebJobOutcome>;
|
|
56
|
+
//# sourceMappingURL=webJob.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webJob.d.ts","sourceRoot":"","sources":["../src/webJob.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,OAAO,EAAwB,MAAM,iBAAiB,CAAC;AAGrE,eAAO,MAAM,gBAAgB,OAAO,CAAC;AACrC,eAAO,MAAM,2BAA2B,UAAY,CAAC;AACrD,eAAO,M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AM,MAAM,CAAC;CACpB,CAAC;AAKF,qFAAqF;AACrF,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,OAAO,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAoBrI;AAED,wBAAsB,SAAS,CAAC,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CA6CtG"}
|
package/dist/webJob.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { PRECONDITION_CSS } from "./cmsJob.js";
|
|
2
|
+
export const MAX_IMAGE_HEIGHT = 7680;
|
|
3
|
+
export const PNG_SIZE_FALLBACK_THRESHOLD = 2_500_000;
|
|
4
|
+
export const JPEG_QUALITY = 0.9;
|
|
5
|
+
const NETWORK_QUIET_MS = 5_000;
|
|
6
|
+
const NAVIGATION_TIMEOUT_MS = 30_000;
|
|
7
|
+
const LAZY_SCROLL_MS = 3_000;
|
|
8
|
+
const clamp = (value, fallback, min, max) => typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback;
|
|
9
|
+
/** The job's parameters as this sidecar will run them, or the reason it will not. */
|
|
10
|
+
export function normalizeWebParameters(raw) {
|
|
11
|
+
const parameters = (raw ?? {});
|
|
12
|
+
let url;
|
|
13
|
+
try {
|
|
14
|
+
url = new URL(String(parameters.url ?? ""));
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return { ok: false, message: "The job names no valid URL." };
|
|
18
|
+
}
|
|
19
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
20
|
+
return { ok: false, message: "Only http and https pages are captured." };
|
|
21
|
+
if (url.username || url.password)
|
|
22
|
+
return { ok: false, message: "A URL with user information is refused." };
|
|
23
|
+
return {
|
|
24
|
+
ok: true,
|
|
25
|
+
value: {
|
|
26
|
+
url: url.toString(),
|
|
27
|
+
scope: parameters.scope === "page" ? "page" : "viewport",
|
|
28
|
+
viewportWidth: clamp(parameters.viewportWidth, 1280, 240, 3840),
|
|
29
|
+
viewportHeight: clamp(parameters.viewportHeight, 900, 240, 4320),
|
|
30
|
+
maxImageWidth: clamp(parameters.maxImageWidth, 1280, 64, 3840),
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export async function runWebJob(rawParameters, options) {
|
|
35
|
+
const now = options.now ?? Date.now;
|
|
36
|
+
const normalized = normalizeWebParameters(rawParameters);
|
|
37
|
+
if (!normalized.ok)
|
|
38
|
+
return { kind: "failed", errorCode: "capture-url-invalid", message: normalized.message };
|
|
39
|
+
const parameters = normalized.value;
|
|
40
|
+
let browser;
|
|
41
|
+
const abort = () => void browser?.close().catch(() => undefined);
|
|
42
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
43
|
+
try {
|
|
44
|
+
if (options.signal.aborted)
|
|
45
|
+
return { kind: "cancelled" };
|
|
46
|
+
browser = await options.launch(options.proxyArgs);
|
|
47
|
+
const context = await browser.newContext({
|
|
48
|
+
viewport: { width: parameters.viewportWidth, height: parameters.viewportHeight },
|
|
49
|
+
deviceScaleFactor: 1,
|
|
50
|
+
serviceWorkers: "block",
|
|
51
|
+
acceptDownloads: false,
|
|
52
|
+
javaScriptEnabled: true,
|
|
53
|
+
// No Parhelia cookie, no storage state, no permission: a public page gets a stranger's browser.
|
|
54
|
+
});
|
|
55
|
+
const remaining = () => options.deadlineUnixMs - now() - 3_000;
|
|
56
|
+
const page = await context.newPage();
|
|
57
|
+
const captured = await capture(page, parameters, remaining);
|
|
58
|
+
if (options.signal.aborted)
|
|
59
|
+
return { kind: "cancelled" };
|
|
60
|
+
if (captured.kind !== "png")
|
|
61
|
+
return captured;
|
|
62
|
+
const processed = await postProcess(browser, captured.png, parameters.maxImageWidth, parameters.scope);
|
|
63
|
+
return {
|
|
64
|
+
kind: "result",
|
|
65
|
+
result: {
|
|
66
|
+
success: true,
|
|
67
|
+
scope: parameters.scope,
|
|
68
|
+
image: processed.image,
|
|
69
|
+
imageWidth: processed.width,
|
|
70
|
+
imageHeight: processed.height,
|
|
71
|
+
finalUrl: captured.finalUrl,
|
|
72
|
+
httpStatus: captured.httpStatus,
|
|
73
|
+
truncated: captured.truncated,
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (options.signal.aborted)
|
|
79
|
+
return { kind: "cancelled" };
|
|
80
|
+
return { kind: "failed", errorCode: "capture-worker-failed", message: firstLine(error) };
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
options.signal.removeEventListener("abort", abort);
|
|
84
|
+
await browser?.close().catch(() => undefined);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** A navigation the egress proxy refused shows as one of these (CONNECT refused; a plain-HTTP refusal is its 403 + header). */
|
|
88
|
+
const PROXY_REFUSALS = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED|ERR_HTTP_RESPONSE_CODE_FAILURE/;
|
|
89
|
+
async function capture(page, parameters, remaining) {
|
|
90
|
+
let response;
|
|
91
|
+
try {
|
|
92
|
+
response = await page.goto(parameters.url, { waitUntil: "load", timeout: Math.max(1_000, Math.min(NAVIGATION_TIMEOUT_MS, remaining())) });
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
const message = firstLine(error);
|
|
96
|
+
if (PROXY_REFUSALS.test(message))
|
|
97
|
+
return { kind: "failed", errorCode: "capture-egress-refused", message: "The capture service refused to connect: the address is not public." };
|
|
98
|
+
return { kind: "failed", errorCode: "capture-url-unreachable", message: `The page did not load: ${message}` };
|
|
99
|
+
}
|
|
100
|
+
if (response?.headers()["x-capture-egress"])
|
|
101
|
+
return { kind: "failed", errorCode: "capture-egress-refused", message: "The capture service refused to connect: the address is not public." };
|
|
102
|
+
await page.waitForLoadState("networkidle", { timeout: Math.max(0, Math.min(NETWORK_QUIET_MS, remaining())) }).catch(() => undefined);
|
|
103
|
+
await page.addStyleTag({ content: PRECONDITION_CSS }).catch(() => undefined);
|
|
104
|
+
const scale = Math.min(1, parameters.maxImageWidth / parameters.viewportWidth);
|
|
105
|
+
const heightCap = Math.floor(MAX_IMAGE_HEIGHT / scale);
|
|
106
|
+
let truncated = false;
|
|
107
|
+
let png;
|
|
108
|
+
if (parameters.scope === "page") {
|
|
109
|
+
const height = await page.evaluate(() => Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0));
|
|
110
|
+
await scrollForLazyContent(page, Math.min(height, heightCap), parameters.viewportHeight, remaining);
|
|
111
|
+
const settled = await page.evaluate(() => Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0));
|
|
112
|
+
truncated = settled > heightCap;
|
|
113
|
+
png = truncated
|
|
114
|
+
? await page.screenshot({ type: "png", fullPage: true, clip: { x: 0, y: 0, width: parameters.viewportWidth, height: heightCap },
|
|
115
|
+
animations: "allow", caret: "initial", scale: "css", timeout: Math.max(1_000, remaining()) })
|
|
116
|
+
: await page.screenshot({ type: "png", fullPage: true, animations: "allow", caret: "initial", scale: "css", timeout: Math.max(1_000, remaining()) });
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
png = await page.screenshot({ type: "png", animations: "allow", caret: "initial", scale: "css", timeout: Math.max(1_000, remaining()) });
|
|
120
|
+
}
|
|
121
|
+
return { kind: "png", png, finalUrl: page.url(), httpStatus: response?.status() ?? null, truncated };
|
|
122
|
+
}
|
|
123
|
+
/** One bounded pass down the page so lazy images load, then back to the top. */
|
|
124
|
+
async function scrollForLazyContent(page, height, step, remaining) {
|
|
125
|
+
const until = Date.now() + Math.min(LAZY_SCROLL_MS, Math.max(0, remaining() - 5_000));
|
|
126
|
+
for (let y = step; y < height && Date.now() < until; y += step) {
|
|
127
|
+
await page.evaluate((top) => window.scrollTo(0, top), y).catch(() => undefined);
|
|
128
|
+
await page.waitForTimeout(100);
|
|
129
|
+
}
|
|
130
|
+
await page.evaluate(() => window.scrollTo(0, 0)).catch(() => undefined);
|
|
131
|
+
await page.waitForLoadState("networkidle", { timeout: Math.max(0, Math.min(2_000, remaining())) }).catch(() => undefined);
|
|
132
|
+
}
|
|
133
|
+
/** Downscale and encode in an offline about:blank page of the same browser (no network, no page of the site). */
|
|
134
|
+
async function postProcess(browser, png, maxWidth, scope) {
|
|
135
|
+
let context;
|
|
136
|
+
try {
|
|
137
|
+
context = await browser.newContext({ offline: true, javaScriptEnabled: true, serviceWorkers: "block" });
|
|
138
|
+
const page = await context.newPage();
|
|
139
|
+
const encoded = await page.evaluate(async ({ source, maxWidth, threshold, quality }) => {
|
|
140
|
+
const image = new Image();
|
|
141
|
+
image.src = source;
|
|
142
|
+
await image.decode();
|
|
143
|
+
const scale = Math.min(1, maxWidth / image.naturalWidth);
|
|
144
|
+
const canvas = document.createElement("canvas");
|
|
145
|
+
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale));
|
|
146
|
+
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale));
|
|
147
|
+
const drawing = canvas.getContext("2d");
|
|
148
|
+
if (!drawing)
|
|
149
|
+
throw new Error("No 2D canvas for the post-processing.");
|
|
150
|
+
drawing.imageSmoothingQuality = "high";
|
|
151
|
+
drawing.drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
152
|
+
const blobOf = (type, q) => new Promise((resolve, reject) => canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("Encoding failed."))), type, q));
|
|
153
|
+
let blob = await blobOf("image/png");
|
|
154
|
+
if (blob.size > threshold)
|
|
155
|
+
blob = await blobOf("image/jpeg", quality);
|
|
156
|
+
const dataUrl = await new Promise((resolve, reject) => {
|
|
157
|
+
const reader = new FileReader();
|
|
158
|
+
reader.onload = () => resolve(String(reader.result));
|
|
159
|
+
reader.onerror = () => reject(new Error("Reading the image failed."));
|
|
160
|
+
reader.readAsDataURL(blob);
|
|
161
|
+
});
|
|
162
|
+
return { dataUrl, contentType: blob.type, fileSize: blob.size, width: canvas.width, height: canvas.height };
|
|
163
|
+
}, { source: `data:image/png;base64,${png.toString("base64")}`, maxWidth, threshold: PNG_SIZE_FALLBACK_THRESHOLD, quality: JPEG_QUALITY });
|
|
164
|
+
const extension = encoded.contentType === "image/jpeg" ? "jpg" : "png";
|
|
165
|
+
return {
|
|
166
|
+
image: { dataUrl: encoded.dataUrl, fileName: `web-${scope}-screenshot.${extension}`, contentType: encoded.contentType, fileSize: encoded.fileSize },
|
|
167
|
+
width: encoded.width,
|
|
168
|
+
height: encoded.height,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
await context?.close().catch(() => undefined);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function firstLine(error) {
|
|
176
|
+
return (error instanceof Error ? error.message : String(error)).split("\n")[0].slice(0, 300);
|
|
177
|
+
}
|