camoucore 0.1.2

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.
@@ -0,0 +1,310 @@
1
+ /**
2
+ * A minimal virtual display implementation for Linux.
3
+ *
4
+ * TypeScript twin of python/src/camoucore/virtdisplay.py.
5
+ */
6
+ import { execFileSync, spawn } from "node:child_process";
7
+ import * as fs from "node:fs";
8
+ import { CannotExecuteXvfb, CannotFindXvfb, VirtualDisplayNotSupported, } from "./exceptions.js";
9
+ import { OS_NAME } from "./host.js";
10
+ /**
11
+ * Safe timeout for Xvfb writing the display num; prevents an infinite hang. A
12
+ * cold first Xvfb on a fresh host took 0.6-8.4 s to report, so 10 s failed
13
+ * launches that would have succeeded.
14
+ */
15
+ const DISPLAYFD_READ_TIMEOUT_MS = 30_000;
16
+ /**
17
+ * Xvfb's screen for headless="virtual" comes from the engine (Product.engine)
18
+ * until the launcher fits it to the identity. <LAUNCHER>_VIRTUAL_DISPLAY_SIZE=
19
+ * "<width>x<height>[x<depth>]" fixes the size instead, and the identity's
20
+ * screen is then kept within it.
21
+ */
22
+ export const SCREEN_KEY = "VIRTUAL_DISPLAY_SIZE";
23
+ /**
24
+ * The Composite extension stays disabled (Xvfb's `-extension COMPOSITE`);
25
+ * setting <LAUNCHER>_VIRTUAL_DISPLAY_COMPOSITE to 1 enables it.
26
+ */
27
+ export const COMPOSITE_KEY = "VIRTUAL_DISPLAY_COMPOSITE";
28
+ /** Screen geometry for Xvfb's -screen argument. */
29
+ function resolveScreen(product) {
30
+ const value = (product.getenv(SCREEN_KEY) ?? "").trim();
31
+ if (!value)
32
+ return product.engine.virtualScreen;
33
+ const parts = value.toLowerCase().split("x");
34
+ const valid = (parts.length === 2 || parts.length === 3) &&
35
+ parts.every((p) => /^\d+$/.test(p) && Number.parseInt(p, 10) > 0);
36
+ if (!valid) {
37
+ throw new VirtualDisplayNotSupported(`${product.envVar(SCREEN_KEY)} must look like '1920x1080' or '1920x1080x24', got '${value}'`);
38
+ }
39
+ if (parts.length === 2)
40
+ parts.push("24");
41
+ return parts.join("x");
42
+ }
43
+ export class VirtualDisplay {
44
+ product;
45
+ debug;
46
+ screen;
47
+ /** A size the caller chose; fit() leaves it alone. */
48
+ fixed;
49
+ composite;
50
+ proc = null;
51
+ _display = null;
52
+ /** What get() calls the server in its errors. */
53
+ serverName = "Xvfb";
54
+ constructor(product, debug = false, screen, composite) {
55
+ this.product = product;
56
+ this.debug = debug;
57
+ this.fixed = Boolean(screen || (product.getenv(SCREEN_KEY) ?? "").trim());
58
+ this.screen = screen || resolveScreen(product);
59
+ this.composite =
60
+ composite ??
61
+ ["1", "true"].includes((product.getenv(COMPOSITE_KEY) ?? "0").trim());
62
+ }
63
+ /** The display's width and height in pixels. */
64
+ get size() {
65
+ const [width, height] = this.screen.toLowerCase().split("x");
66
+ return [Number.parseInt(width, 10), Number.parseInt(height, 10)];
67
+ }
68
+ /**
69
+ * Size a display that is not yet started to `width` x `height` pixels,
70
+ * unless its size was fixed.
71
+ */
72
+ fit(width, height) {
73
+ if (this.fixed || this.proc !== null)
74
+ return;
75
+ const depth = this.screen.toLowerCase().split("x")[2];
76
+ this.screen = `${width}x${height}x${depth}`;
77
+ }
78
+ get xvfbArgs() {
79
+ return [
80
+ "-screen",
81
+ "0",
82
+ this.screen,
83
+ "-ac",
84
+ "-nolisten",
85
+ "tcp",
86
+ "-extension",
87
+ "RENDER",
88
+ "+extension",
89
+ "GLX",
90
+ this.composite ? "+extension" : "-extension",
91
+ "COMPOSITE",
92
+ "-extension",
93
+ "XVideo",
94
+ "-extension",
95
+ "XVideo-MotionCompensation",
96
+ "-extension",
97
+ "XINERAMA",
98
+ "-fp",
99
+ "built-ins",
100
+ "-nocursor",
101
+ "-br",
102
+ ];
103
+ }
104
+ get xvfbPath() {
105
+ let resolved;
106
+ try {
107
+ resolved = execFileSync("which", ["Xvfb"], {
108
+ encoding: "utf-8",
109
+ stdio: ["ignore", "pipe", "ignore"],
110
+ }).trim();
111
+ }
112
+ catch {
113
+ throw new CannotFindXvfb("Please install Xvfb to use headless mode.");
114
+ }
115
+ if (!resolved) {
116
+ throw new CannotFindXvfb("Please install Xvfb to use headless mode.");
117
+ }
118
+ try {
119
+ fs.accessSync(resolved, fs.constants.X_OK);
120
+ }
121
+ catch {
122
+ throw new CannotExecuteXvfb(`I do not have permission to execute Xvfb: ${resolved}`);
123
+ }
124
+ return resolved;
125
+ }
126
+ get setprivPath() {
127
+ try {
128
+ return execFileSync("which", ["setpriv"], {
129
+ encoding: "utf-8",
130
+ stdio: ["ignore", "pipe", "ignore"],
131
+ }).trim();
132
+ }
133
+ catch {
134
+ throw new CannotFindXvfb("Please install util-linux (for setpriv) to use headless mode.");
135
+ }
136
+ }
137
+ /** The error get() raises when the server fails. */
138
+ error(message) {
139
+ return new CannotExecuteXvfb(message);
140
+ }
141
+ /**
142
+ * What execs the server. setpriv's parent-death signal stops Xvfb when this
143
+ * process dies without reaching kill(), even by SIGKILL; SIGTERM lets Xvfb
144
+ * remove its own lock and socket. See xvfb-dies-with-its-launcher in
145
+ * ci/tribal-rules.yml.
146
+ */
147
+ wrapper() {
148
+ return [this.setprivPath, "--pdeathsig", "TERM"];
149
+ }
150
+ /** The server's argv, less -displayfd, which get() adds. */
151
+ command() {
152
+ return [this.xvfbPath, ...this.xvfbArgs];
153
+ }
154
+ serverEnv() {
155
+ return {
156
+ ...process.env,
157
+ // Force Mesa software GLX; we don't use the GPU anyway.
158
+ __GLX_VENDOR_LIBRARY_NAME: "mesa",
159
+ LIBGL_ALWAYS_SOFTWARE: "1",
160
+ };
161
+ }
162
+ /** Called once the server has reported its display. */
163
+ async ready() { }
164
+ /**
165
+ * Spawn the server (if it isn't already running) and return its ":N" display.
166
+ *
167
+ * Uses `-displayfd` so the server itself picks a free display number
168
+ * atomically and reports it back, avoiding userspace races. Python's
169
+ * `pass_fds` keeps the fd at its parent number; Node's `stdio` array
170
+ * renumbers extra pipes from 3 upward, so we hand the server fd 3 and read
171
+ * the pipe at index 3.
172
+ */
173
+ async get() {
174
+ VirtualDisplay.assertLinux();
175
+ if (this.proc === null) {
176
+ const [program, ...args] = this.command();
177
+ const cmd = [...this.wrapper(), program, "-displayfd", "3", ...args];
178
+ if (this.debug) {
179
+ console.log("Starting virtual display:", cmd.join(" "));
180
+ }
181
+ this.proc = spawn(cmd[0], cmd.slice(1), {
182
+ stdio: [
183
+ "ignore",
184
+ this.debug ? "inherit" : "ignore",
185
+ this.debug ? "inherit" : "ignore",
186
+ "pipe",
187
+ ],
188
+ detached: true,
189
+ env: this.serverEnv(),
190
+ });
191
+ // A spawn that fails after spawn() returns (EACCES, ENOEXEC, a noexec
192
+ // mount) is an 'error' event on the child; with no listener Node
193
+ // treats it as uncaught and exits. readDisplayNumber() turns it into
194
+ // this.error(); this keeps any later one from killing the process.
195
+ this.proc.on("error", () => { });
196
+ const displayFd = this.proc.stdio[3];
197
+ if (!displayFd) {
198
+ this.kill();
199
+ throw this.error(`Could not open ${this.serverName}'s -displayfd pipe`);
200
+ }
201
+ const raw = await this.readDisplayNumber(displayFd);
202
+ const parsed = Number.parseInt(raw.trim(), 10);
203
+ if (Number.isNaN(parsed)) {
204
+ this.kill();
205
+ throw this.error(`${this.serverName} wrote non-integer display: '${raw}'`);
206
+ }
207
+ this._display = parsed;
208
+ await this.ready();
209
+ }
210
+ else if (this.debug) {
211
+ console.log(`Using virtual display: ${this._display}`);
212
+ }
213
+ return `:${this._display}`;
214
+ }
215
+ readDisplayNumber(stream) {
216
+ return new Promise((resolve, reject) => {
217
+ let buf = "";
218
+ let settled = false;
219
+ const finish = (fn) => {
220
+ if (settled)
221
+ return;
222
+ settled = true;
223
+ clearTimeout(timer);
224
+ stream.removeAllListeners("data");
225
+ stream.removeAllListeners("end");
226
+ stream.removeAllListeners("error");
227
+ stream.on("error", () => { }); // a late pipe error is not fatal
228
+ proc?.removeListener("error", onSpawnError);
229
+ fn();
230
+ };
231
+ const proc = this.proc;
232
+ const onSpawnError = (error) => finish(() => {
233
+ this.kill();
234
+ reject(this.error(`Could not start ${this.serverName}: ${error}`));
235
+ });
236
+ proc?.once("error", onSpawnError);
237
+ const timer = setTimeout(() => {
238
+ finish(() => {
239
+ this.kill();
240
+ reject(this.error(`${this.serverName} did not report a display within ${DISPLAYFD_READ_TIMEOUT_MS}ms`));
241
+ });
242
+ }, DISPLAYFD_READ_TIMEOUT_MS);
243
+ stream.on("data", (chunk) => {
244
+ buf += chunk.toString();
245
+ if (buf.includes("\n")) {
246
+ finish(() => resolve(buf));
247
+ }
248
+ });
249
+ stream.on("end", () => {
250
+ finish(() => {
251
+ if (buf.includes("\n")) {
252
+ resolve(buf);
253
+ return;
254
+ }
255
+ const exit = this.proc?.exitCode;
256
+ this.kill();
257
+ reject(this.error(`${this.serverName} did not report a display (got '${buf}', exit=${exit})`));
258
+ });
259
+ });
260
+ stream.on("error", (error) => {
261
+ finish(() => {
262
+ this.kill();
263
+ reject(this.error(`Failed to read ${this.serverName}'s display: ${error}`));
264
+ });
265
+ });
266
+ });
267
+ }
268
+ /**
269
+ * Stop Xvfb if it is running, and remove its lock and socket either way: a
270
+ * killed Xvfb leaves its socket behind, and every stranded one pushes
271
+ * -displayfd's next display number higher.
272
+ */
273
+ kill() {
274
+ if (!this.proc)
275
+ return;
276
+ if (this.proc.exitCode === null && this.proc.signalCode === null) {
277
+ if (this.debug) {
278
+ console.log("Terminating virtual display:", this._display);
279
+ }
280
+ try {
281
+ this.proc.kill("SIGKILL");
282
+ }
283
+ catch {
284
+ // Already gone.
285
+ }
286
+ }
287
+ else if (this.debug) {
288
+ console.log("Virtual display already exited:", this._display);
289
+ }
290
+ for (const stale of [
291
+ `/tmp/.X${this._display}-lock`,
292
+ `/tmp/.X11-unix/X${this._display}`,
293
+ ]) {
294
+ try {
295
+ fs.unlinkSync(stale);
296
+ }
297
+ catch {
298
+ // Missing is the normal case; anything else (a permission error
299
+ // from a number another user has since claimed) must not take
300
+ // down a teardown path.
301
+ }
302
+ }
303
+ this.proc = null;
304
+ }
305
+ static assertLinux() {
306
+ if (OS_NAME !== "lin") {
307
+ throw new VirtualDisplayNotSupported("Virtual display is only supported on Linux.");
308
+ }
309
+ }
310
+ }
@@ -0,0 +1,32 @@
1
+ /** camoucore's warnings.yml, loaded once. */
2
+ export declare function loadWarnings(): Record<string, string>;
3
+ export interface RecordedWarning {
4
+ category: string;
5
+ message: string;
6
+ }
7
+ /**
8
+ * Emit a warning. While a `recordWarnings()` block is active the warning is
9
+ * captured instead of printed, as Python's catch_warnings(record=True) does.
10
+ */
11
+ export declare function warn(message: string, category?: string): void;
12
+ /**
13
+ * Run `fn`, capturing every warning it emits (sync or async) instead of
14
+ * printing it. Scoped by AsyncLocalStorage, so concurrent work outside the
15
+ * block is not captured; nested blocks capture into the innermost one.
16
+ */
17
+ export declare function recordWarnings<T>(fn: () => T | Promise<T>): Promise<{
18
+ result?: T;
19
+ error?: unknown;
20
+ warnings: RecordedWarning[];
21
+ }>;
22
+ /**
23
+ * Emitted when a caller has a setting enabled that can cause detection.
24
+ */
25
+ export declare class LeakWarning extends Error {
26
+ constructor(message: string);
27
+ /**
28
+ * Warns the caller if a passed parameter can cause leaks. `warning` is the
29
+ * message itself: each launcher words its own.
30
+ */
31
+ static warn(warning: string, iKnowWhatImDoing?: boolean): void;
32
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The warning channel every launcher on camoucore reports through, and the
3
+ * core's own messages (warnings.yml).
4
+ *
5
+ * TypeScript twin of python/src/camoucore/_warnings.py. Python routes these
6
+ * through the `warnings` module; the Node equivalent is `process.emitWarning`,
7
+ * which prints `(node:<pid>) <Category>: <message>` to stderr and fires
8
+ * `process.on("warning")`. Python's `warnings.catch_warnings(record=True)` is
9
+ * `recordWarnings()` here. A launcher emits through this module's `warn`, so
10
+ * one recorder sees the core's warnings and the launcher's.
11
+ */
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+ import { loadDataFile } from "./data.js";
14
+ let warningsData;
15
+ /** camoucore's warnings.yml, loaded once. */
16
+ export function loadWarnings() {
17
+ warningsData ??= loadDataFile("warnings.yml");
18
+ return warningsData;
19
+ }
20
+ const recorder = new AsyncLocalStorage();
21
+ /**
22
+ * Emit a warning. While a `recordWarnings()` block is active the warning is
23
+ * captured instead of printed, as Python's catch_warnings(record=True) does.
24
+ */
25
+ export function warn(message, category = "RuntimeWarning") {
26
+ const captured = recorder.getStore();
27
+ if (captured) {
28
+ captured.push({ category, message });
29
+ return;
30
+ }
31
+ process.emitWarning(message, { type: category });
32
+ }
33
+ /**
34
+ * Run `fn`, capturing every warning it emits (sync or async) instead of
35
+ * printing it. Scoped by AsyncLocalStorage, so concurrent work outside the
36
+ * block is not captured; nested blocks capture into the innermost one.
37
+ */
38
+ export async function recordWarnings(fn) {
39
+ const captured = [];
40
+ try {
41
+ return { result: await recorder.run(captured, fn), warnings: captured };
42
+ }
43
+ catch (error) {
44
+ return { error, warnings: captured };
45
+ }
46
+ }
47
+ /**
48
+ * Emitted when a caller has a setting enabled that can cause detection.
49
+ */
50
+ export class LeakWarning extends Error {
51
+ constructor(message) {
52
+ super(message);
53
+ this.name = "LeakWarning";
54
+ }
55
+ /**
56
+ * Warns the caller if a passed parameter can cause leaks. `warning` is the
57
+ * message itself: each launcher words its own.
58
+ */
59
+ static warn(warning, iKnowWhatImDoing) {
60
+ if (iKnowWhatImDoing) {
61
+ return;
62
+ }
63
+ if (iKnowWhatImDoing !== undefined) {
64
+ warning += "\nIf this is intentional, pass `i_know_what_im_doing=True`.";
65
+ }
66
+ warn(warning, "LeakWarning");
67
+ }
68
+ }
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "camoucore",
3
+ "version": "0.1.2",
4
+ "description": "The browser-independent core of the Camoufox and Camouwolf launchers",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": "./dist/index.js",
10
+ "./*.js": "./dist/*.js"
11
+ },
12
+ "scripts": {
13
+ "build": "rimraf dist && tsc && node scripts/copy-files.mjs",
14
+ "test": "vitest run",
15
+ "check": "biome check",
16
+ "typecheck": "tsc --noEmit",
17
+ "prepare": "pnpm build"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "THIRD_PARTY_NOTICES.md"
22
+ ],
23
+ "author": "JWriter20",
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/CamouBrowser/camoucore.git",
28
+ "directory": "typescript"
29
+ },
30
+ "engines": {
31
+ "node": ">=22.15"
32
+ },
33
+ "dependencies": {
34
+ "adm-zip": "^0.6.1",
35
+ "cli-progress": "^3.12.0",
36
+ "language-tags": "^2.0.1",
37
+ "maxmind": "^5.0.0",
38
+ "pretty-bytes": "^7.1.0",
39
+ "xml2js": "^0.6.2",
40
+ "yaml": "^2.9.1"
41
+ },
42
+ "devDependencies": {
43
+ "@biomejs/biome": "2.4.10",
44
+ "@types/cli-progress": "^3.11.6",
45
+ "@types/language-tags": "^1.0.4",
46
+ "@types/node": "^24.0.0",
47
+ "@types/xml2js": "^0.4.14",
48
+ "fpgen-js": "1.3.0",
49
+ "rimraf": "^6.0.1",
50
+ "typescript": "^5.8.3",
51
+ "vite": "8.3.8",
52
+ "vitest": "^4.0.0"
53
+ },
54
+ "devEngines": {
55
+ "packageManager": {
56
+ "name": "pnpm",
57
+ "version": "10.33.4",
58
+ "onFail": "warn"
59
+ }
60
+ }
61
+ }