@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,260 @@
1
+ /*
2
+ * Capture sidecar CS6: the one seam between install/update/uninstall and the machine. Every file, mode, owner, link and
3
+ * command goes through it, so the tests run the real install and update logic against an in-memory machine (fakeSys) and
4
+ * read back what it did: files with their modes and owners, links, and every command with its arguments.
5
+ */
6
+ import { spawn, spawnSync } from "node:child_process";
7
+ import { createHash } from "node:crypto";
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ export function realSys() {
12
+ return {
13
+ platform: process.platform,
14
+ nodePath: process.execPath,
15
+ nodeVersion: process.versions.node,
16
+ isPrivileged: () => {
17
+ if (process.platform === "win32")
18
+ return spawnSync("net", ["session"], { stdio: "ignore" }).status === 0;
19
+ return process.getuid?.() === 0;
20
+ },
21
+ exists: (file) => fs.existsSync(file),
22
+ isDirectory: (file) => {
23
+ try {
24
+ return fs.statSync(file).isDirectory();
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ },
30
+ readFile: (file) => fs.readFileSync(file, "utf8"),
31
+ readBytes: (file) => fs.readFileSync(file),
32
+ writeFile: (file, data, options) => {
33
+ fs.writeFileSync(file, data, { mode: options?.mode });
34
+ if (options?.mode !== undefined && process.platform !== "win32")
35
+ fs.chmodSync(file, options.mode);
36
+ },
37
+ mkdir: (dir, options) => {
38
+ fs.mkdirSync(dir, { recursive: true, mode: options?.mode });
39
+ if (options?.mode !== undefined && process.platform !== "win32")
40
+ fs.chmodSync(dir, options.mode);
41
+ },
42
+ chmod: (file, mode) => fs.chmodSync(file, mode),
43
+ chown: (file, user, group, options) => {
44
+ const result = spawnSync("chown", [...(options?.recursive ? ["-R"] : []), `${user}:${group}`, file], { encoding: "utf8" });
45
+ if (result.status !== 0)
46
+ throw new Error(`chown ${user}:${group} ${file}: ${result.stderr.trim()}`);
47
+ },
48
+ link: (target, linkPath) => fs.symlinkSync(target, linkPath, process.platform === "win32" ? "junction" : "dir"),
49
+ readLink: (linkPath) => {
50
+ try {
51
+ return fs.readlinkSync(linkPath);
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ },
57
+ rename: (from, to) => fs.renameSync(from, to),
58
+ remove: (file) => fs.rmSync(file, { recursive: true, force: true }),
59
+ list: (dir) => {
60
+ try {
61
+ return fs.readdirSync(dir);
62
+ }
63
+ catch {
64
+ return [];
65
+ }
66
+ },
67
+ exec: (command, args, options) => {
68
+ const result = spawnSync(command, args, {
69
+ encoding: "utf8", env: options?.env ? { ...process.env, ...options.env } : process.env, input: options?.input,
70
+ timeout: options?.timeoutMs ?? 10 * 60_000, cwd: options?.cwd, maxBuffer: 64 * 1024 * 1024,
71
+ });
72
+ return { status: result.status ?? (result.error ? 127 : 1), stdout: result.stdout ?? "", stderr: result.stderr ?? (result.error?.message ?? "") };
73
+ },
74
+ spawn: (command, args, options) => {
75
+ const child = spawn(command, args, { env: options?.env ? { ...process.env, ...options.env } : process.env, cwd: options?.cwd, stdio: "ignore" });
76
+ return { stop: () => void child.kill("SIGTERM") };
77
+ },
78
+ copyDir: (from, to) => fs.cpSync(from, to, { recursive: true, dereference: true }),
79
+ download: async (url, file) => {
80
+ const response = await fetch(url, { redirect: "follow" });
81
+ if (!response.ok || !response.body)
82
+ throw new Error(`Downloading ${url} answered ${response.status}.`);
83
+ fs.writeFileSync(file, Buffer.from(await response.arrayBuffer()));
84
+ },
85
+ fetch: (...args) => fetch(...args),
86
+ sha256: (file) => createHash("sha256").update(fs.readFileSync(file)).digest("hex"),
87
+ integrity: (file, algorithm = "sha512") => `${algorithm}-${createHash(algorithm).update(fs.readFileSync(file)).digest("base64")}`,
88
+ tempDir: (prefix) => fs.mkdtempSync(path.join(os.tmpdir(), prefix)),
89
+ now: () => Date.now(),
90
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
91
+ };
92
+ }
93
+ /** An in-memory machine. `onExec` answers commands (default: success with no output); `downloads` maps URLs to bytes. */
94
+ export function fakeSys(options = {}) {
95
+ const entries = new Map();
96
+ const execs = [];
97
+ const platform = options.platform ?? "linux";
98
+ const join = platform === "win32" ? path.win32 : path.posix;
99
+ const norm = (file) => join.normalize(file).replace(/[\\/]+$/, "") || join.sep;
100
+ let clock = Date.UTC(2026, 9, 15, 12, 0, 0);
101
+ const parentOf = (file) => join.dirname(norm(file));
102
+ const ensureParents = (file) => {
103
+ for (let dir = parentOf(file); dir && !entries.has(dir) && dir !== parentOf(dir); dir = parentOf(dir))
104
+ entries.set(dir, { dir: true, mode: 0o755 });
105
+ };
106
+ const resolve = (file) => {
107
+ let current = norm(file);
108
+ // Follow links in any prefix (current/browser/... through the current link).
109
+ for (let hops = 0; hops < 16; hops++) {
110
+ const parts = current.split(/[\\/]/);
111
+ let changed = false;
112
+ for (let at = 1; at <= parts.length; at++) {
113
+ const prefix = parts.slice(0, at).join(join.sep) || join.sep;
114
+ const entry = entries.get(prefix);
115
+ if (entry && "link" in entry) {
116
+ current = norm(join.join(join.isAbsolute(entry.link) ? entry.link : join.join(parentOf(prefix), entry.link), ...parts.slice(at)));
117
+ changed = true;
118
+ break;
119
+ }
120
+ }
121
+ if (!changed)
122
+ return current;
123
+ }
124
+ return current;
125
+ };
126
+ const file = (name) => {
127
+ const entry = entries.get(resolve(name));
128
+ if (!entry || "link" in entry || entry.dir)
129
+ throw Object.assign(new Error(`ENOENT: ${name}`), { code: "ENOENT" });
130
+ return entry;
131
+ };
132
+ const sys = {
133
+ platform,
134
+ nodePath: platform === "win32" ? "C:\\Program Files\\nodejs\\node.exe" : "/usr/bin/node",
135
+ nodeVersion: options.nodeVersion ?? "22.23.0",
136
+ entries,
137
+ execs,
138
+ put(name, data, mode = 0o644) {
139
+ ensureParents(name);
140
+ entries.set(norm(name), { data: Buffer.from(data), mode });
141
+ },
142
+ modeOf: (name) => {
143
+ const entry = entries.get(norm(name));
144
+ return entry && "mode" in entry ? entry.mode : undefined;
145
+ },
146
+ ownerOf: (name) => entries.get(norm(name))?.owner,
147
+ advance: (ms) => {
148
+ clock += ms;
149
+ },
150
+ isPrivileged: () => options.privileged ?? true,
151
+ exists: (name) => entries.has(resolve(name)),
152
+ isDirectory: (name) => {
153
+ const entry = entries.get(resolve(name));
154
+ return !!entry && "dir" in entry && entry.dir === true;
155
+ },
156
+ readFile: (name) => file(name).data.toString("utf8"),
157
+ readBytes: (name) => file(name).data,
158
+ writeFile: (name, data, writeOptions) => {
159
+ const target = resolve(name);
160
+ ensureParents(target);
161
+ const previous = entries.get(target);
162
+ entries.set(target, { data: Buffer.from(data), mode: writeOptions?.mode ?? (previous && "mode" in previous ? previous.mode : 0o644),
163
+ owner: previous?.owner });
164
+ },
165
+ mkdir: (dir, mkdirOptions) => {
166
+ const target = resolve(dir);
167
+ ensureParents(target);
168
+ const previous = entries.get(target);
169
+ entries.set(target, { dir: true, mode: mkdirOptions?.mode ?? (previous && "mode" in previous ? previous.mode : 0o755), owner: previous?.owner });
170
+ },
171
+ chmod: (name, mode) => {
172
+ const target = resolve(name);
173
+ const entry = entries.get(target);
174
+ if (!entry || "link" in entry)
175
+ throw new Error(`ENOENT: ${name}`);
176
+ entries.set(target, { ...entry, mode });
177
+ },
178
+ chown: (name, user, group, chownOptions) => {
179
+ const target = resolve(name);
180
+ const owner = `${user}:${group}`;
181
+ for (const [key, entry] of entries)
182
+ if (key === target || (chownOptions?.recursive && key.startsWith(target + join.sep)))
183
+ entries.set(key, { ...entry, owner });
184
+ },
185
+ link: (target, linkPath) => {
186
+ const at = norm(linkPath);
187
+ if (entries.has(at))
188
+ throw Object.assign(new Error(`EEXIST: ${linkPath}`), { code: "EEXIST" });
189
+ ensureParents(at);
190
+ entries.set(at, { link: target });
191
+ },
192
+ readLink: (linkPath) => {
193
+ const entry = entries.get(norm(linkPath));
194
+ return entry && "link" in entry ? entry.link : undefined;
195
+ },
196
+ rename: (from, to) => {
197
+ const source = norm(from);
198
+ const target = norm(to);
199
+ if (!entries.has(source))
200
+ throw Object.assign(new Error(`ENOENT: ${from}`), { code: "ENOENT" });
201
+ const moved = [...entries].filter(([key]) => key === source || key.startsWith(source + join.sep));
202
+ for (const [key] of [...entries])
203
+ if (key === target || key.startsWith(target + join.sep))
204
+ entries.delete(key);
205
+ for (const [key] of moved)
206
+ entries.delete(key);
207
+ for (const [key, entry] of moved)
208
+ entries.set(target + key.slice(source.length), entry);
209
+ },
210
+ remove: (name) => {
211
+ const target = norm(name);
212
+ for (const key of [...entries.keys()])
213
+ if (key === target || key.startsWith(target + join.sep))
214
+ entries.delete(key);
215
+ },
216
+ list: (dir) => {
217
+ const target = resolve(dir);
218
+ return [...entries.keys()].filter((key) => parentOf(key) === target && key !== target).map((key) => join.basename(key)).sort();
219
+ },
220
+ exec: (command, args, execOptions) => {
221
+ const exec = { command, args, env: execOptions?.env };
222
+ execs.push(exec);
223
+ const answer = options.onExec?.(exec) ?? {};
224
+ return { status: answer.status ?? 0, stdout: answer.stdout ?? "", stderr: answer.stderr ?? "" };
225
+ },
226
+ spawn: (command, args, execOptions) => {
227
+ execs.push({ command, args, env: execOptions?.env });
228
+ options.onExec?.({ command, args, env: execOptions?.env });
229
+ return { stop: () => void execs.push({ command: "stop", args: [command, ...args] }) };
230
+ },
231
+ copyDir: (from, to) => {
232
+ const source = resolve(from);
233
+ const target = norm(to);
234
+ for (const [key, entry] of [...entries])
235
+ if (key === source || key.startsWith(source + join.sep)) {
236
+ ensureParents(target + key.slice(source.length));
237
+ entries.set(target + key.slice(source.length), entry);
238
+ }
239
+ },
240
+ download: async (url, name) => {
241
+ const source = options.downloads?.[url];
242
+ if (!source)
243
+ throw new Error(`Downloading ${url} answered 404.`);
244
+ sys.put(name, typeof source === "function" ? source() : source);
245
+ },
246
+ fetch: options.fetch ?? (async () => new Response("{}", { status: 404 })),
247
+ sha256: (name) => createHash("sha256").update(file(name).data).digest("hex"),
248
+ integrity: (name, algorithm = "sha512") => `${algorithm}-${createHash(algorithm).update(file(name).data).digest("base64")}`,
249
+ tempDir: (prefix) => {
250
+ const dir = join.join(platform === "win32" ? "C:\\Temp" : "/tmp", `${prefix}${entries.size}`);
251
+ sys.mkdir(dir, { mode: 0o700 });
252
+ return dir;
253
+ },
254
+ now: () => clock,
255
+ sleep: async (ms) => {
256
+ clock += ms;
257
+ },
258
+ };
259
+ return sys;
260
+ }
@@ -0,0 +1,57 @@
1
+ import { type Layout } from "./layout.js";
2
+ /** A stop waits this long for the running jobs (each job's budget is 60 s) before systemd kills the worker. */
3
+ export declare const WORKER_STOP_TIMEOUT_S = 150;
4
+ export type UnitInput = {
5
+ layout: Layout;
6
+ nodePath: string;
7
+ /** Directories holding a Unix socket outside the hidden trees (amendment A7). */
8
+ inaccessiblePaths: readonly string[];
9
+ /** Whether the browser host unit is installed (the pairing allowed public-web). */
10
+ web: boolean;
11
+ };
12
+ /** Node needs to be visible inside the browser host unit; anything outside /usr is mapped read-only (CS5w finding). */
13
+ export declare function nodeReadOnlyPaths(nodePath: string): string[];
14
+ export declare function workerUnit(input: UnitInput): string;
15
+ export declare function browserHostUnit(input: UnitInput): string;
16
+ export declare function updaterUnit(input: UnitInput): string;
17
+ export declare function updaterTimer(): string;
18
+ export declare function linuxUnits(input: UnitInput): Record<string, string>;
19
+ export declare const SID: {
20
+ readonly localService: "S-1-5-19";
21
+ readonly system: "S-1-5-18";
22
+ readonly administrators: "S-1-5-32-544";
23
+ };
24
+ /** A Task Scheduler 1.2 task: at boot, restart on failure, no time limit; `sid` is the account it runs as. */
25
+ export declare function windowsTask(input: {
26
+ description: string;
27
+ sid: string;
28
+ command: string;
29
+ args: string;
30
+ daily?: boolean;
31
+ }): string;
32
+ export declare function windowsTasks(input: UnitInput): Record<string, string>;
33
+ /** Every remote address but loopback, as ranges: one block rule, no allow rule, so block-over-allow precedence cannot bite. */
34
+ export declare const WINDOWS_BLOCKED_REMOTE: readonly ["0.0.0.0-126.255.255.255", "128.0.0.0-255.255.255.255", "::", "::2-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
35
+ export declare const firewallRuleName: (version: string) => string;
36
+ /** The PowerShell that installs the outbound block rule for one browser executable (plan §8). */
37
+ export declare function firewallRuleScript(version: string, executable: string): string;
38
+ /** The PowerShell that reads the rule back: enabled, blocking, outbound, bound to exactly this program. One JSON line. */
39
+ export declare function firewallVerifyScript(version: string): string;
40
+ export declare function firewallRemoveScript(version: string): string;
41
+ /** Whether the rule read back is the one this version needs. */
42
+ export declare function firewallRuleHolds(answer: string, executable: string): {
43
+ ok: boolean;
44
+ detail: string;
45
+ };
46
+ /** icacls for the key file: inheritance off; the service account reads, Administrators and SYSTEM own (plan §5). */
47
+ export declare function keyFileAclArgs(keyFile: string): string[];
48
+ /** icacls for the data directory: inheritance off; Administrators and SYSTEM full, the service account modify, nobody else. */
49
+ export declare function dataDirAclArgs(dataDir: string): string[];
50
+ /** Whether `icacls <file>` output grants exactly the three accounts, none of it inherited. */
51
+ export declare function keyFileAclHolds(icaclsOutput: string, file?: string): {
52
+ ok: boolean;
53
+ detail: string;
54
+ };
55
+ /** The launcher `install` writes: the `parhelia-capture` command, always running the installed current version. */
56
+ export declare function launcherScript(layout: Layout, nodePath: string): string;
57
+ //# sourceMappingURL=units.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"units.d.ts","sourceRoot":"","sources":["../../src/install/units.ts"],"names":[],"mappings":"AAOA,OAAO,EAA6D,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAErG,+GAA+G;AAC/G,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAEzC,MAAM,MAAM,SAAS,GAAG;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,iBAAiB,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,mFAAmF;IACnF,GAAG,EAAE,OAAO,CAAC;CACd,CAAC;AAIF,uHAAuH;AACvH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAG5D;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAqCnD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CA4BxD;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAiBpD;AAED,wBAAgB,YAAY,IAAI,MAAM,CAcrC;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAOnE;AAID,eAAO,MAAM,GAAG;aAAK,YAAY,EAAE,UAAU;aAAE,MAAM,EAAE,UAAU;aAAE,cAAc,EAAE,cAAc;CAAW,CAAC;AAI7G,8GAA8G;AAC9G,wBAAgB,WAAW,CAAC,KAAK,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAqB/H;AAID,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAarE;AAED,+HAA+H;AAC/H,eAAO,MAAM,sBAAsB,YACjC,yBAAyB,EAAE,2BAA2B,EAAE,IAAI,EAAE,6CAA6C,CACnG,CAAC;AAEX,eAAO,MAAM,gBAAgB,YAAa,MAAM,WAA0C,CAAC;AAI3F,iGAAiG;AACjG,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAO9E;AAED,0HAA0H;AAC1H,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAQ5D;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,gEAAgE;AAChE,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG;IAAE,EAAE,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAarG;AAED,oHAAoH;AACpH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAExD;AAED,+HAA+H;AAC/H,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAExD;AAED,8FAA8F;AAC9F,wBAAgB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG;IAAE,EAAE,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAcpG;AAED,mHAAmH;AACnH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAIvE"}
@@ -0,0 +1,244 @@
1
+ /*
2
+ * Capture sidecar CS6 (plan §5, §8): the service definitions `install` writes. Linux: three systemd units and a timer (the worker,
3
+ * the isolated browser host, the privileged updater). Windows: three scheduled tasks (restart on failure, start at boot) and the
4
+ * outbound block rule bound to one browser executable. Pure text; `install` writes it, the tests read it.
5
+ */
6
+ import path from "node:path";
7
+ import { browserHostUnitProperties } from "../isolation.js";
8
+ import { BROWSER_USER, IPC_GROUP, PACKAGE_ENTRY, UNIT, WORKER_USER } from "./layout.js";
9
+ /** A stop waits this long for the running jobs (each job's budget is 60 s) before systemd kills the worker. */
10
+ export const WORKER_STOP_TIMEOUT_S = 150;
11
+ const entry = (layout) => path.posix.join(layout.currentLink, PACKAGE_ENTRY);
12
+ /** Node needs to be visible inside the browser host unit; anything outside /usr is mapped read-only (CS5w finding). */
13
+ export function nodeReadOnlyPaths(nodePath) {
14
+ const prefix = path.posix.dirname(path.posix.dirname(nodePath));
15
+ return prefix === "/usr" || prefix.startsWith("/usr/") ? [] : [prefix];
16
+ }
17
+ export function workerUnit(input) {
18
+ const { layout } = input;
19
+ return `# Written by parhelia-capture install. The worker: polls Parhelia outbound, runs the egress proxy, drives CMS page captures.
20
+ [Unit]
21
+ Description=Parhelia capture service (worker)
22
+ Wants=network-online.target
23
+ After=network-online.target
24
+
25
+ [Service]
26
+ Type=exec
27
+ User=${WORKER_USER}
28
+ Group=${IPC_GROUP}
29
+ ExecStart=${input.nodePath} ${entry(layout)} start --config ${layout.configFile}
30
+ Restart=always
31
+ RestartSec=5
32
+ # SIGTERM drains: no new job is claimed, the running ones finish (each within its 60 s budget).
33
+ KillSignal=SIGTERM
34
+ TimeoutStopSec=${WORKER_STOP_TIMEOUT_S}
35
+ RuntimeDirectory=parhelia-capture parhelia-capture/browser-host
36
+ RuntimeDirectoryMode=0750
37
+ StateDirectory=parhelia-capture
38
+ StateDirectoryMode=0750
39
+ UMask=0027
40
+ Environment=HOME=${layout.stateDir}
41
+ Environment=NODE_ENV=production
42
+ NoNewPrivileges=yes
43
+ ProtectSystem=strict
44
+ ProtectHome=yes
45
+ PrivateTmp=yes
46
+ PrivateDevices=yes
47
+ ProtectKernelTunables=yes
48
+ ProtectKernelModules=yes
49
+ ProtectControlGroups=yes
50
+
51
+ [Install]
52
+ WantedBy=multi-user.target
53
+ `;
54
+ }
55
+ export function browserHostUnit(input) {
56
+ const { layout } = input;
57
+ const isolation = browserHostUnitProperties({
58
+ socketDir: layout.socketDir,
59
+ readOnlyPaths: [layout.versionsDir, ...nodeReadOnlyPaths(input.nodePath)],
60
+ inaccessiblePaths: input.inaccessiblePaths,
61
+ user: BROWSER_USER,
62
+ environment: { HOME: "/tmp", NODE_ENV: "production" },
63
+ });
64
+ return `# Written by parhelia-capture install. The browser host: Chromium for public pages, without a network of its own (plan §8).
65
+ # It reaches the network only through the worker's egress sockets in ${layout.socketDir}.
66
+ [Unit]
67
+ Description=Parhelia capture service (isolated browser host)
68
+ BindsTo=${UNIT.worker}
69
+ After=${UNIT.worker}
70
+
71
+ [Service]
72
+ Type=exec
73
+ Group=${IPC_GROUP}
74
+ ExecStart=${input.nodePath} ${entry(layout)} browser-host --socket-dir ${layout.socketDir} --install-dir ${layout.currentLink}
75
+ Restart=always
76
+ RestartSec=5
77
+ UMask=0077
78
+ ${isolation.join("\n")}
79
+
80
+ [Install]
81
+ WantedBy=${UNIT.worker}
82
+ `;
83
+ }
84
+ export function updaterUnit(input) {
85
+ const { layout } = input;
86
+ return `# Written by parhelia-capture install. The privileged updater: installs the version the host names, side by side, and switches
87
+ # only after its hashes and self-test pass (plan CS-D14). It owns ${layout.versionsDir}; the service users only read it.
88
+ [Unit]
89
+ Description=Parhelia capture service (updater)
90
+ Wants=network-online.target
91
+ After=network-online.target
92
+
93
+ [Service]
94
+ Type=oneshot
95
+ ExecStart=${input.nodePath} ${entry(layout)} update --auto --config ${layout.configFile}
96
+ TimeoutStartSec=30min
97
+ UMask=0022
98
+ NoNewPrivileges=yes
99
+ PrivateTmp=yes
100
+ `;
101
+ }
102
+ export function updaterTimer() {
103
+ return `# Written by parhelia-capture install.
104
+ [Unit]
105
+ Description=Parhelia capture service (update check)
106
+
107
+ [Timer]
108
+ OnBootSec=10min
109
+ OnUnitActiveSec=6h
110
+ RandomizedDelaySec=30min
111
+ Persistent=true
112
+
113
+ [Install]
114
+ WantedBy=timers.target
115
+ `;
116
+ }
117
+ export function linuxUnits(input) {
118
+ return {
119
+ [UNIT.worker]: workerUnit(input),
120
+ ...(input.web ? { [UNIT.browserHost]: browserHostUnit(input) } : {}),
121
+ [UNIT.updater]: updaterUnit(input),
122
+ [UNIT.updaterTimer]: updaterTimer(),
123
+ };
124
+ }
125
+ // --- Windows -----------------------------------------------------------------------------------------------------------------
126
+ export const SID = { localService: "S-1-5-19", system: "S-1-5-18", administrators: "S-1-5-32-544" };
127
+ const xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
128
+ /** A Task Scheduler 1.2 task: at boot, restart on failure, no time limit; `sid` is the account it runs as. */
129
+ export function windowsTask(input) {
130
+ const triggers = input.daily
131
+ ? `<BootTrigger><Delay>PT10M</Delay></BootTrigger><CalendarTrigger><StartBoundary>2026-01-01T03:00:00</StartBoundary><RandomDelay>PT30M</RandomDelay><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger>`
132
+ : `<BootTrigger />`;
133
+ return `<?xml version="1.0" encoding="UTF-16"?>
134
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
135
+ <RegistrationInfo><Description>${xml(input.description)}</Description></RegistrationInfo>
136
+ <Triggers>${triggers}</Triggers>
137
+ <Principals><Principal id="Author"><UserId>${input.sid}</UserId><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
138
+ <Settings>
139
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
140
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
141
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
142
+ <ExecutionTimeLimit>${input.daily ? "PT1H" : "PT0S"}</ExecutionTimeLimit>
143
+ <RestartOnFailure><Interval>PT1M</Interval><Count>999</Count></RestartOnFailure>
144
+ <StartWhenAvailable>true</StartWhenAvailable>
145
+ <Enabled>true</Enabled>
146
+ </Settings>
147
+ <Actions Context="Author"><Exec><Command>${xml(input.command)}</Command><Arguments>${xml(input.args)}</Arguments></Exec></Actions>
148
+ </Task>
149
+ `;
150
+ }
151
+ const quoted = (value) => `"${value}"`;
152
+ export function windowsTasks(input) {
153
+ const { layout } = input;
154
+ const cli = quoted(path.win32.join(layout.currentLink, ...PACKAGE_ENTRY.split("/")));
155
+ return {
156
+ Worker: windowsTask({ description: "Parhelia capture service (worker)", sid: SID.localService, command: input.nodePath,
157
+ args: `${cli} start --config ${quoted(layout.configFile)}` }),
158
+ ...(input.web ? {
159
+ "Browser host": windowsTask({ description: "Parhelia capture service (browser host; outbound blocked by its firewall rule)", sid: SID.localService,
160
+ command: input.nodePath, args: `${cli} browser-host --socket-dir ${quoted(layout.socketDir)} --install-dir ${quoted(layout.currentLink)}` }),
161
+ } : {}),
162
+ Updater: windowsTask({ description: "Parhelia capture service (updater)", sid: SID.system, command: input.nodePath,
163
+ args: `${cli} update --auto --config ${quoted(layout.configFile)}`, daily: true }),
164
+ };
165
+ }
166
+ /** Every remote address but loopback, as ranges: one block rule, no allow rule, so block-over-allow precedence cannot bite. */
167
+ export const WINDOWS_BLOCKED_REMOTE = [
168
+ "0.0.0.0-126.255.255.255", "128.0.0.0-255.255.255.255", "::", "::2-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
169
+ ];
170
+ export const firewallRuleName = (version) => `Parhelia capture browser ${version}`;
171
+ const ps = (value) => `'${value.replace(/'/g, "''")}'`;
172
+ /** The PowerShell that installs the outbound block rule for one browser executable (plan §8). */
173
+ export function firewallRuleScript(version, executable) {
174
+ return [
175
+ `$ErrorActionPreference = 'Stop'`,
176
+ `Get-NetFirewallRule -DisplayName ${ps(firewallRuleName(version))} -ErrorAction SilentlyContinue | Remove-NetFirewallRule`,
177
+ `New-NetFirewallRule -DisplayName ${ps(firewallRuleName(version))} -Group 'Parhelia capture' -Direction Outbound -Action Block ` +
178
+ `-Profile Any -Program ${ps(executable)} -RemoteAddress ${WINDOWS_BLOCKED_REMOTE.map(ps).join(",")} | Out-Null`,
179
+ ].join("; ");
180
+ }
181
+ /** The PowerShell that reads the rule back: enabled, blocking, outbound, bound to exactly this program. One JSON line. */
182
+ export function firewallVerifyScript(version) {
183
+ return [
184
+ `$ErrorActionPreference = 'Stop'`,
185
+ `$rule = Get-NetFirewallRule -DisplayName ${ps(firewallRuleName(version))}`,
186
+ `$app = $rule | Get-NetFirewallApplicationFilter`,
187
+ `$address = $rule | Get-NetFirewallAddressFilter`,
188
+ `[pscustomobject]@{ enabled = "$($rule.Enabled)"; action = "$($rule.Action)"; direction = "$($rule.Direction)"; program = $app.Program; remote = @($address.RemoteAddress) } | ConvertTo-Json -Compress`,
189
+ ].join("; ");
190
+ }
191
+ export function firewallRemoveScript(version) {
192
+ return `Get-NetFirewallRule -DisplayName ${ps(firewallRuleName(version))} -ErrorAction SilentlyContinue | Remove-NetFirewallRule`;
193
+ }
194
+ /** Whether the rule read back is the one this version needs. */
195
+ export function firewallRuleHolds(answer, executable) {
196
+ try {
197
+ const rule = JSON.parse(answer);
198
+ const problems = [];
199
+ if (rule.enabled !== "True")
200
+ problems.push("not enabled");
201
+ if (rule.action !== "Block")
202
+ problems.push(`action ${rule.action}`);
203
+ if (rule.direction !== "Outbound")
204
+ problems.push(`direction ${rule.direction}`);
205
+ if ((rule.program ?? "").toLowerCase() !== executable.toLowerCase())
206
+ problems.push(`bound to ${rule.program ?? "no program"}`);
207
+ if (!(rule.remote ?? []).some((range) => range.startsWith("0.0.0.0-126")))
208
+ problems.push("does not cover remote IPv4");
209
+ return { ok: problems.length === 0, detail: problems.length === 0 ? "outbound blocked for this browser" : problems.join(", ") };
210
+ }
211
+ catch {
212
+ return { ok: false, detail: `unreadable answer: ${answer.slice(0, 200)}` };
213
+ }
214
+ }
215
+ /** icacls for the key file: inheritance off; the service account reads, Administrators and SYSTEM own (plan §5). */
216
+ export function keyFileAclArgs(keyFile) {
217
+ return [keyFile, "/inheritance:r", "/grant:r", `*${SID.localService}:R`, `*${SID.administrators}:F`, `*${SID.system}:F`];
218
+ }
219
+ /** icacls for the data directory: inheritance off; Administrators and SYSTEM full, the service account modify, nobody else. */
220
+ export function dataDirAclArgs(dataDir) {
221
+ return [dataDir, "/inheritance:r", "/grant:r", `*${SID.administrators}:(OI)(CI)F`, `*${SID.system}:(OI)(CI)F`, `*${SID.localService}:(OI)(CI)M`];
222
+ }
223
+ /** Whether `icacls <file>` output grants exactly the three accounts, none of it inherited. */
224
+ export function keyFileAclHolds(icaclsOutput, file) {
225
+ const entries = icaclsOutput.split(/\r?\n/)
226
+ .map((line) => (file && line.startsWith(file) ? line.slice(file.length) : line).trim())
227
+ .filter((line) => line.length > 0 && !/^Successfully processed/i.test(line))
228
+ // The first line still carries the path when it was not given: keep from the last token that names an account.
229
+ .map((line) => line.replace(/^.*?((?:NT AUTHORITY|BUILTIN|NT SERVICE|[^\s\\]+)\\[^:]+:\(|[^\s\\:]+:\()/, "$1"))
230
+ .filter((line) => line.includes(":("));
231
+ const names = entries.map((entry) => entry.slice(0, entry.indexOf(":(")).trim().toUpperCase());
232
+ const allowed = ["NT AUTHORITY\\LOCAL SERVICE", "BUILTIN\\ADMINISTRATORS", "NT AUTHORITY\\SYSTEM"];
233
+ const extra = names.filter((name) => !allowed.includes(name));
234
+ const inherited = entries.some((entry) => entry.includes("(I)"));
235
+ if (extra.length || inherited || names.length === 0)
236
+ return { ok: false, detail: `the key file's ACL also grants ${[...extra, ...(inherited ? ["inherited entries"] : [])].join(", ") || "nothing readable"}` };
237
+ return { ok: true, detail: "only the service account, Administrators and SYSTEM" };
238
+ }
239
+ /** The launcher `install` writes: the `parhelia-capture` command, always running the installed current version. */
240
+ export function launcherScript(layout, nodePath) {
241
+ if (layout.platform === "win32")
242
+ return `@echo off\r\nrem Written by parhelia-capture install: always the installed current version.\r\n"${nodePath}" "${path.win32.join(layout.currentLink, ...PACKAGE_ENTRY.split("/"))}" %*\r\n`;
243
+ return `#!/bin/sh\n# Written by parhelia-capture install: always the installed current version.\nexec ${nodePath} ${entry(layout)} "$@"\n`;
244
+ }
@@ -0,0 +1,66 @@
1
+ import type { InstalledConfig, Layout } from "./layout.js";
2
+ import type { Sys } from "./sys.js";
3
+ import { type SidecarManifest } from "./versions.js";
4
+ export type ManifestAnswer = {
5
+ updatePolicy: string;
6
+ release: boolean;
7
+ manifest: SidecarManifest;
8
+ capabilities?: string[];
9
+ };
10
+ export type WorkerStatus = {
11
+ version: string;
12
+ pid?: number;
13
+ startedUtc?: string;
14
+ lastPollUtc?: string;
15
+ lastPollOk?: boolean;
16
+ lastPollError?: string;
17
+ web?: {
18
+ ok: boolean;
19
+ code?: string;
20
+ reason?: string;
21
+ } | null;
22
+ };
23
+ export type UpdaterStatus = {
24
+ checkedUtc: string;
25
+ result: UpdateResult;
26
+ current?: string;
27
+ wanted?: string;
28
+ policy?: string;
29
+ problems: string[];
30
+ };
31
+ export type UpdateResult = "no-release" | "up-to-date" | "available" | "updated" | "refused" | "rolled-back" | "unreachable";
32
+ export type Firewall = {
33
+ install(version: string, executable: string): void;
34
+ verify(version: string, executable: string): {
35
+ ok: boolean;
36
+ detail: string;
37
+ };
38
+ remove(version: string): void;
39
+ };
40
+ export type UpdaterDeps = {
41
+ sys: Sys;
42
+ layout: Layout;
43
+ config: InstalledConfig;
44
+ fetchManifest(): Promise<ManifestAnswer>;
45
+ /** The new version's self-test, before the switch: a test capture, and the §8 checks when public-web is on. */
46
+ selfTest(versionDir: string, version: string): Promise<{
47
+ ok: boolean;
48
+ detail: string;
49
+ }>;
50
+ /** Stops the worker (and browser host) between jobs, and starts them again. */
51
+ services: {
52
+ stop(): void;
53
+ start(): void;
54
+ };
55
+ /** Windows: the browser's outbound rule (plan §8: installed and verified before the first launch of a new path). */
56
+ firewall?: Firewall;
57
+ healthTimeoutMs?: number;
58
+ log?: (line: string) => void;
59
+ };
60
+ export type UpdateOptions = {
61
+ auto: boolean;
62
+ fromTarball?: string;
63
+ };
64
+ export declare function runUpdate(deps: UpdaterDeps, options: UpdateOptions): Promise<UpdaterStatus>;
65
+ export declare function readJson<T>(sys: Sys, file: string): T | undefined;
66
+ //# sourceMappingURL=updater.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"updater.d.ts","sourceRoot":"","sources":["../../src/install/updater.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EACwF,KAAK,eAAe,EAClH,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,cAAc,GAAG;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,QAAQ,EAAE,eAAe,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE5H,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,GAAG,CAAC,EAAE;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CAC9D,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,YAAY,GAAG,YAAY,GAAG,WAAW,GAAG,SAAS,GAAG,SAAS,GAAG,aAAa,GAAG,aAAa,CAAC;AAE7H,MAAM,MAAM,QAAQ,GAAG;IACrB,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACnD,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7E,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,GAAG,EAAE,GAAG,CAAC;IACT,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,eAAe,CAAC;IACxB,aAAa,IAAI,OAAO,CAAC,cAAc,CAAC,CAAC;IACzC,+GAA+G;IAC/G,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxF,+EAA+E;IAC/E,QAAQ,EAAE;QAAE,IAAI,IAAI,IAAI,CAAC;QAAC,KAAK,IAAI,IAAI,CAAA;KAAE,CAAC;IAC1C,oHAAoH;IACpH,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEpE,wBAAsB,SAAS,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CA6EjG;AAkBD,wBAAgB,QAAQ,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAMjE"}