bexxcv 1.0.7 → 1.0.9

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 (44) hide show
  1. package/README.md +81 -0
  2. package/dist/__main__.js +7 -0
  3. package/dist/data-files/data-version.json +7 -0
  4. package/dist/data-files/webgl_data.db +0 -0
  5. package/dist/doctor.d.ts +26 -0
  6. package/dist/doctor.js +149 -0
  7. package/dist/exceptions.d.ts +3 -0
  8. package/dist/exceptions.js +6 -0
  9. package/dist/index.d.ts +4 -0
  10. package/dist/index.js +4 -0
  11. package/dist/pagehooks.d.ts +6 -0
  12. package/dist/pagehooks.js +19 -0
  13. package/dist/plugins/brake.d.ts +8 -0
  14. package/dist/plugins/brake.js +74 -0
  15. package/dist/plugins/cocoon.d.ts +5 -0
  16. package/dist/plugins/cocoon.js +17 -0
  17. package/dist/plugins/dodge.d.ts +21 -0
  18. package/dist/plugins/dodge.js +102 -0
  19. package/dist/plugins/gauntlet.d.ts +20 -0
  20. package/dist/plugins/gauntlet.js +119 -0
  21. package/dist/plugins/index.d.ts +27 -0
  22. package/dist/plugins/index.js +55 -0
  23. package/dist/plugins/lens.d.ts +20 -0
  24. package/dist/plugins/lens.js +89 -0
  25. package/dist/plugins/stash.d.ts +8 -0
  26. package/dist/plugins/stash.js +108 -0
  27. package/dist/plugins/types.d.ts +13 -0
  28. package/dist/plugins/types.js +49 -0
  29. package/dist/plugins/veneer.d.ts +5 -0
  30. package/dist/plugins/veneer.js +37 -0
  31. package/dist/plugins/wiretap.d.ts +26 -0
  32. package/dist/plugins/wiretap.js +123 -0
  33. package/dist/realism.d.ts +3 -0
  34. package/dist/realism.js +57 -0
  35. package/dist/schema.d.ts +1 -0
  36. package/dist/schema.js +256 -0
  37. package/dist/sync_api.d.ts +3 -1
  38. package/dist/sync_api.js +13 -1
  39. package/dist/turnstile.d.ts +12 -0
  40. package/dist/turnstile.js +70 -13
  41. package/dist/uam.d.ts +4 -0
  42. package/dist/uam.js +32 -6
  43. package/dist/utils.js +9 -3
  44. package/package.json +13 -10
package/README.md CHANGED
@@ -28,6 +28,7 @@ High-performance stealth Firefox automation built on top of [Camoufox](https://g
28
28
  | Cloudflare UAM | Manual | `uam: true` — `page.goto()` waits until the challenge clears |
29
29
  | Human behavior | Cursor movement only (`humanize`) | `createHuman(page)` — clicks, typing with typos, scrolling, idle drift |
30
30
  | Launch speed | Sequential setup | Public IP lookup runs in parallel with the binary check; telemetry and update prefs off by default |
31
+ | Fingerprint coherence | `devicePixelRatio` picked independently of screen size | DPR is chosen so CSS size times DPR matches a real monitor resolution |
31
32
 
32
33
  ---
33
34
 
@@ -298,6 +299,85 @@ await human.idle(2000);
298
299
 
299
300
  ---
300
301
 
302
+ ## Options validation
303
+
304
+ `bexxcv()` checks option types with [zod](https://zod.dev) before launching, so a wrong value fails early with a readable message.
305
+
306
+ ```
307
+ InvalidOptions: Invalid bexxcv options:
308
+ turnstile: expected a boolean or { interval, retryAfter }, got the string "yes"
309
+ ```
310
+
311
+ Unknown options that look like a typo of a known one only print a warning, for example `Unknown option "turnsltile", did you mean "turnstile"?`. Other unknown options are passed to Playwright untouched. Set `BEXXCV_NO_VALIDATE=1` to skip the check.
312
+
313
+ ---
314
+
315
+ ## Fingerprint coherence
316
+
317
+ - `devicePixelRatio` is chosen together with the screen size, so the physical resolution (CSS size times DPR) is one that real monitors have. A 1920x1080 screen can have DPR 1 or 2, but not 1.25.
318
+ - WebGL data keys are matched against the properties of the installed Camoufox build. If the bundled `webgl_data.db` uses different key names or keys the browser does not know, bexxcv raises a clear `UnknownProperty` error instead of silently leaking the host GPU.
319
+
320
+ ---
321
+
322
+ ## Data files and `doctor`
323
+
324
+ `npx bexxcv doctor` checks the bundled `webgl_data.db`: the number of usable rows per OS, the data keys, whether they match the installed browser, and how long ago the data was last stamped. A warning is also printed at launch when the data is older than 180 days. Set `BEXXCV_NO_DATA_CHECK=1` to silence it.
325
+
326
+ Refresh the data from the repository root:
327
+
328
+ ```bash
329
+ node scripts/update-data.mjs --from /path/to/webgl_data.db
330
+ node scripts/update-data.mjs --npm camoufox-js
331
+ node scripts/update-data.mjs --stamp
332
+ node scripts/update-data.mjs --pin
333
+ ```
334
+
335
+ `--from` and `--npm` validate the database before replacing it and refuse a database with far fewer rows unless `--force` is given. `--pin` compares `browser-pin.json` with the latest Camoufox release and only writes the change with `--write`. Test before releasing a new pin.
336
+
337
+ ---
338
+
339
+ ## Plugins
340
+
341
+ Plugins are switched on with options and hook into the browser, its contexts and its pages. Each one is optional and does nothing unless you set its option.
342
+
343
+ ```ts
344
+ const browser = await bexxcv({
345
+ gauntlet: { solve: ["uam", "turnstile"], maxTries: 3 },
346
+ wiretap: { match: ["/api/"], out: "capture.json" },
347
+ stash: "./profiles/cookies.json",
348
+ brake: { maxRps: 2 },
349
+ });
350
+ ```
351
+
352
+ | Option | What it does |
353
+ |---|---|
354
+ | `gauntlet` | Runs the checks after every `page.goto()`: waits out the Cloudflare challenge (`uam`) and clicks Turnstile widgets (`turnstile`), retrying up to `maxTries`. While the challenge page is up it clicks the widget between mouse movements. `sustain` keeps human-like movement going for a number of milliseconds afterwards. A background check also runs every 1.5 seconds (`watch: false` turns it off), so a challenge that appears later in the session, for example when Cloudflare re-evaluates it, is handled too. Challenges are detected through the `cf-mitigated: challenge` header Cloudflare adds to every challenge page, with the page title as a fallback. Read the outcome with `gauntletResult(page)`. |
355
+ | `wiretap` | Records matching responses: `match` (substring, or `re:` plus a regular expression), `methods`, `bodies`, `maxBodyBytes`, `streamTimeout`. Server-sent event streams are split into `events`. Sensitive headers (`cookie`, `authorization`, `set-cookie`) are redacted unless `redact: false`. With `out` the capture is written to a private file when the browser closes, and `wiretapEntries(context)` returns it at any time. |
356
+ | `stash` | Cookie vault, a file path or `{ file, names, domains, saveEvery }`. Cookies are restored into every new context, expired ones are dropped, and everything is saved per domain when the browser closes. The file is created with mode 600. `cf_clearance` is tied to the device and IP it was issued for, so it is restored only when the proxy matches the one in use when it was saved, while other cookies are always restored. |
357
+ | `cocoon` | Persistent profile folder (`user_data_dir`) that keeps localStorage, IndexedDB and cache between runs. |
358
+ | `veneer` | Warns when a Firefox user agent is sent together with `sec-ch-ua` headers. With `{ strict: true }` those headers are stripped. |
359
+ | `brake` | Rate limiter for `page.goto()`: `maxRps` per host, and `Retry-After` is honored after 429 and 503 answers, with exponential backoff when the header is missing. |
360
+ | `dodge` | Proxy pool: `pool`, `rotateOn` (default 403 and 429), `healthCheck`, `cooldown`, `onBlocked`. Unhealthy proxies are skipped at launch, each new context gets the next proxy, and a proxy that answers a blocked status is paused. Keep the pool in one country, because the timezone and locale are derived from the launch proxy. |
361
+ | `lens` | Local fingerprint audit after the first page load: checks `navigator.webdriver`, user agent against platform, language, screen size against DPR, window size, core count and software WebGL renderers. Returns a score through `lensReport(page)` and prints failures unless `quiet: true`. Only `target: "local"` exists, no external site is contacted. |
362
+ | `plugins` | Your own plugins: an array of objects with a `name` and any of `beforeLaunch`, `beforeContext`, `onContext`, `onPage`, `beforeClose`. |
363
+
364
+ `gauntlet` already includes the `uam` waiting and the Turnstile clicking, so there is no need to set `uam` or `turnstile` next to it.
365
+
366
+ Writing a plugin:
367
+
368
+ ```ts
369
+ const timing = {
370
+ name: "timing",
371
+ onPage(page) {
372
+ page.on("load", () => console.log("loaded", page.url()));
373
+ },
374
+ };
375
+
376
+ const browser = await bexxcv({ plugins: [timing] });
377
+ ```
378
+
379
+ ---
380
+
301
381
  ## Xvfb module
302
382
 
303
383
  bexxcv exports all Xvfb utilities so you can manage virtual displays in your own code:
@@ -413,6 +493,7 @@ npx bexxcv version # Show installed version
413
493
  npx bexxcv path # Print install directory
414
494
  npx bexxcv test [url] # Open a test browser window
415
495
  npx bexxcv server # Start a Playwright remote server
496
+ npx bexxcv doctor # Check the bundled WebGL data
416
497
  ```
417
498
 
418
499
  ---
package/dist/__main__.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { existsSync, rmSync } from "node:fs";
3
3
  import { Command } from "commander";
4
4
  import { DefaultAddons, maybeDownloadAddons } from "./addons.js";
5
+ import { doctor } from "./doctor.js";
5
6
  import { ALLOW_GEOIP, downloadMMDB, removeMMDB } from "./locale.js";
6
7
  import { CamoufoxFetcher, INSTALL_DIR, installedVerStr } from "./pkgman.js";
7
8
  import { launchServer } from "./server.js";
@@ -126,6 +127,12 @@ program.command("version").action(async () => {
126
127
  console.log("(Up to date!)");
127
128
  }
128
129
  });
130
+ program.command("doctor").action(async () => {
131
+ const report = await doctor();
132
+ for (const line of report.lines)
133
+ console.log(line);
134
+ process.exitCode = report.ok ? 0 : 1;
135
+ });
129
136
  program.command("check-update").action(async () => {
130
137
  console.log("Checking for bexxcv updates...");
131
138
  try {
@@ -0,0 +1,7 @@
1
+ {
2
+ "webgl_data": {
3
+ "updated": "2026-10-21T19:41:35.701Z",
4
+ "rows": 33,
5
+ "sha256": "d293cabe7b546bf4ac3a2fb6c3cb6aee9891910659299d61fa2c88944d38c45d"
6
+ }
7
+ }
Binary file
@@ -0,0 +1,26 @@
1
+ export declare const DEFAULT_MAX_AGE_DAYS = 180;
2
+ export interface DataStamp {
3
+ updated: string;
4
+ rows?: number;
5
+ sha256?: string;
6
+ }
7
+ export interface DataStatus {
8
+ exists: boolean;
9
+ bytes: number;
10
+ stamp: DataStamp | null;
11
+ ageDays: number | null;
12
+ stale: boolean;
13
+ }
14
+ export declare function readStamp(dir?: string): DataStamp | null;
15
+ export declare function dataStatus(options?: {
16
+ dir?: string;
17
+ maxAgeDays?: number;
18
+ }): DataStatus;
19
+ export declare function warnIfDataStale(maxAgeDays?: number): void;
20
+ export declare function doctor(options?: {
21
+ dir?: string;
22
+ maxAgeDays?: number;
23
+ }): Promise<{
24
+ ok: boolean;
25
+ lines: string[];
26
+ }>;
package/dist/doctor.js ADDED
@@ -0,0 +1,149 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { getPath } from "./pkgman.js";
6
+ import { reconcileWebglKeys } from "./realism.js";
7
+ const currentDir = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
8
+ const DATA_DIR = path.join(currentDir, "data-files");
9
+ export const DEFAULT_MAX_AGE_DAYS = 180;
10
+ let warned = false;
11
+ function readProperties() {
12
+ try {
13
+ const list = JSON.parse(fs.readFileSync(getPath("properties.json"), "utf-8"));
14
+ return Object.fromEntries(list.map((p) => [p.property, p.type]));
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export function readStamp(dir = DATA_DIR) {
21
+ try {
22
+ const raw = JSON.parse(fs.readFileSync(path.join(dir, "data-version.json"), "utf-8"));
23
+ const stamp = raw?.webgl_data;
24
+ if (!stamp || typeof stamp.updated !== "string")
25
+ return null;
26
+ return stamp;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ export function dataStatus(options = {}) {
33
+ const dir = options.dir ?? DATA_DIR;
34
+ const maxAge = options.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS;
35
+ const file = path.join(dir, "webgl_data.db");
36
+ let bytes = 0;
37
+ try {
38
+ bytes = fs.statSync(file).size;
39
+ }
40
+ catch {
41
+ bytes = 0;
42
+ }
43
+ const stamp = readStamp(dir);
44
+ let ageDays = null;
45
+ if (stamp) {
46
+ const time = Date.parse(stamp.updated);
47
+ if (!Number.isNaN(time)) {
48
+ ageDays = Math.floor((Date.now() - time) / 86_400_000);
49
+ }
50
+ }
51
+ return {
52
+ exists: bytes > 0,
53
+ bytes,
54
+ stamp,
55
+ ageDays,
56
+ stale: ageDays !== null && ageDays > maxAge,
57
+ };
58
+ }
59
+ export function warnIfDataStale(maxAgeDays = DEFAULT_MAX_AGE_DAYS) {
60
+ if (warned || process.env.BEXXCV_NO_DATA_CHECK)
61
+ return;
62
+ const status = dataStatus({ maxAgeDays });
63
+ if (!status.stale)
64
+ return;
65
+ warned = true;
66
+ console.warn(`[bexxcv] WebGL data is ${status.ageDays} days old. Run "npx bexxcv doctor" to check it.`);
67
+ }
68
+ export async function doctor(options = {}) {
69
+ const dir = options.dir ?? DATA_DIR;
70
+ const status = dataStatus(options);
71
+ const lines = [];
72
+ let ok = true;
73
+ if (!status.exists) {
74
+ lines.push("webgl_data.db: missing or empty");
75
+ return { ok: false, lines };
76
+ }
77
+ lines.push(`webgl_data.db: ${status.bytes} bytes`);
78
+ try {
79
+ const { default: Database } = await import("better-sqlite3");
80
+ const db = new Database(path.join(dir, "webgl_data.db"), {
81
+ readonly: true,
82
+ fileMustExist: true,
83
+ });
84
+ try {
85
+ const counts = ["win", "mac", "lin"].map((os) => {
86
+ const row = db
87
+ .prepare(`SELECT COUNT(*) AS n FROM webgl_fingerprints WHERE ${os} > 0`)
88
+ .get();
89
+ return `${os}=${row.n}`;
90
+ });
91
+ lines.push(`webgl_fingerprints rows with data: ${counts.join(" ")}`);
92
+ if (counts.some((c) => c.endsWith("=0")))
93
+ ok = false;
94
+ const sample = db
95
+ .prepare("SELECT data FROM webgl_fingerprints LIMIT 1")
96
+ .get();
97
+ if (sample) {
98
+ const keys = Object.keys(JSON.parse(sample.data));
99
+ lines.push(`data keys: ${keys.join(", ")}`);
100
+ if (keys.length <= 3) {
101
+ ok = false;
102
+ lines.push("the database only holds vendor and renderer, other WebGL values would come from the host GPU");
103
+ }
104
+ const props = readProperties();
105
+ if (props) {
106
+ try {
107
+ const { webGl2Enabled: _skip, ...rest } = JSON.parse(sample.data);
108
+ reconcileWebglKeys(rest, props);
109
+ lines.push("data keys match the installed Camoufox build");
110
+ }
111
+ catch (error) {
112
+ ok = false;
113
+ lines.push(error.message);
114
+ }
115
+ }
116
+ else {
117
+ lines.push("properties.json not found, browser not installed yet");
118
+ }
119
+ }
120
+ }
121
+ finally {
122
+ db.close();
123
+ }
124
+ }
125
+ catch (error) {
126
+ ok = false;
127
+ lines.push(`webgl_fingerprints: cannot read (${error.message})`);
128
+ }
129
+ if (!status.stamp) {
130
+ lines.push("data-version.json: missing, run scripts/update-data.mjs --stamp");
131
+ }
132
+ else {
133
+ const actual = createHash("sha256")
134
+ .update(fs.readFileSync(path.join(dir, "webgl_data.db")))
135
+ .digest("hex");
136
+ if (status.stamp.sha256 && status.stamp.sha256 !== actual) {
137
+ ok = false;
138
+ lines.push("data-version.json: sha256 does not match webgl_data.db");
139
+ }
140
+ lines.push(`last stamped: ${status.stamp.updated} (${status.ageDays} days ago)`);
141
+ if (status.stale) {
142
+ ok = false;
143
+ lines.push("status: stale, refresh with scripts/update-data.mjs");
144
+ }
145
+ }
146
+ if (ok)
147
+ lines.push("status: ok");
148
+ return { ok, lines };
149
+ }
@@ -77,3 +77,6 @@ export declare class CorruptedDownload extends Error {
77
77
  export declare class FileNotFoundError extends Error {
78
78
  constructor(message?: string);
79
79
  }
80
+ export declare class InvalidOptions extends Error {
81
+ constructor(message?: string);
82
+ }
@@ -157,3 +157,9 @@ export class FileNotFoundError extends Error {
157
157
  this.name = "FileNotFoundError";
158
158
  }
159
159
  }
160
+ export class InvalidOptions extends Error {
161
+ constructor(message) {
162
+ super(message ?? "One or more options are invalid.");
163
+ this.name = "InvalidOptions";
164
+ }
165
+ }
package/dist/index.d.ts CHANGED
@@ -7,3 +7,7 @@ export { checkSelfUpdate, applySelfUpdate, type SelfUpdateInfo } from "./selfupd
7
7
  export { createHuman, Human, type HumanClickOptions, type HumanOptions, type HumanPage, } from "./human.js";
8
8
  export { attachTurnstile, watchTurnstile, type TurnstileOptions, } from "./turnstile.js";
9
9
  export { attachUam, waitForUam, watchUam, type UamOptions, type UamResult } from "./uam.js";
10
+ export { dataStatus, doctor, type DataStatus } from "./doctor.js";
11
+ export { validateOptions } from "./schema.js";
12
+ export { applyPlugins, auditFingerprint, buildPlugins, gauntletResult, lensReport, runGauntlet, wiretapEntries, type BexxcvPlugin, type BrakeOptions, type DodgeOptions, type GauntletOptions, type LensOptions, type PluginOptions, type StashOptions, type VeneerOptions, type WiretapOptions, } from "./plugins/index.js";
13
+ export { solveTurnstile } from "./turnstile.js";
package/dist/index.js CHANGED
@@ -7,3 +7,7 @@ export { checkSelfUpdate, applySelfUpdate } from "./selfupdate.js";
7
7
  export { createHuman, Human, } from "./human.js";
8
8
  export { attachTurnstile, watchTurnstile, } from "./turnstile.js";
9
9
  export { attachUam, waitForUam, watchUam } from "./uam.js";
10
+ export { dataStatus, doctor } from "./doctor.js";
11
+ export { validateOptions } from "./schema.js";
12
+ export { applyPlugins, auditFingerprint, buildPlugins, gauntletResult, lensReport, runGauntlet, wiretapEntries, } from "./plugins/index.js";
13
+ export { solveTurnstile } from "./turnstile.js";
@@ -1,2 +1,8 @@
1
1
  import type { Browser, BrowserContext, Page } from "playwright-core";
2
+ export type ContextOptions = NonNullable<Parameters<Browser["newContext"]>[0]>;
3
+ export interface ContextHooks {
4
+ before?: (options: ContextOptions) => void | Promise<void>;
5
+ after?: (context: BrowserContext, options: ContextOptions) => void | Promise<void>;
6
+ }
7
+ export declare function onEachContext<T extends Browser | BrowserContext>(target: T, hooks: ContextHooks): Promise<T>;
2
8
  export declare function onEachPage<T extends Browser | BrowserContext>(target: T, handler: (page: Page) => void): T;
package/dist/pagehooks.js CHANGED
@@ -1,3 +1,22 @@
1
+ export async function onEachContext(target, hooks) {
2
+ if (typeof target.newContext !== "function") {
3
+ await hooks.after?.(target, {});
4
+ return target;
5
+ }
6
+ const browser = target;
7
+ for (const context of browser.contexts()) {
8
+ await hooks.after?.(context, {});
9
+ }
10
+ const original = browser.newContext.bind(browser);
11
+ browser.newContext = async (options) => {
12
+ const next = { ...(options ?? {}) };
13
+ await hooks.before?.(next);
14
+ const context = await original(next);
15
+ await hooks.after?.(context, next);
16
+ return context;
17
+ };
18
+ return target;
19
+ }
1
20
  export function onEachPage(target, handler) {
2
21
  const seen = new WeakSet();
3
22
  const watchContext = (context) => {
@@ -0,0 +1,8 @@
1
+ import type { BexxcvPlugin } from "./types.js";
2
+ export interface BrakeOptions {
3
+ maxRps?: number;
4
+ respectRetryAfter?: boolean;
5
+ perHost?: boolean;
6
+ maxBackoff?: number;
7
+ }
8
+ export declare function brake(options?: BrakeOptions): BexxcvPlugin;
@@ -0,0 +1,74 @@
1
+ import { sleep } from "../random.js";
2
+ const WRAPPED = new WeakSet();
3
+ function hostOf(url, perHost) {
4
+ if (!perHost)
5
+ return "*";
6
+ try {
7
+ return new URL(url).host;
8
+ }
9
+ catch {
10
+ return "*";
11
+ }
12
+ }
13
+ function parseRetryAfter(value) {
14
+ if (!value)
15
+ return null;
16
+ const seconds = Number(value);
17
+ if (Number.isFinite(seconds))
18
+ return Math.max(0, seconds * 1000);
19
+ const date = Date.parse(value);
20
+ return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
21
+ }
22
+ export function brake(options = {}) {
23
+ const interval = 1000 / (options.maxRps ?? 2);
24
+ const respect = options.respectRetryAfter ?? true;
25
+ const perHost = options.perHost ?? true;
26
+ const maxBackoff = options.maxBackoff ?? 120_000;
27
+ const nextSlot = new Map();
28
+ const blockedUntil = new Map();
29
+ const backoff = new Map();
30
+ const take = async (host) => {
31
+ const blocked = (blockedUntil.get(host) ?? 0) - Date.now();
32
+ if (blocked > 0)
33
+ await sleep(blocked);
34
+ const at = Math.max(Date.now(), nextSlot.get(host) ?? 0);
35
+ nextSlot.set(host, at + interval);
36
+ const wait = at - Date.now();
37
+ if (wait > 0)
38
+ await sleep(wait);
39
+ };
40
+ return {
41
+ name: "brake",
42
+ order: 90,
43
+ onContext(context) {
44
+ context.on("response", (response) => {
45
+ const request = response.request();
46
+ if (!request.isNavigationRequest())
47
+ return;
48
+ const host = hostOf(response.url(), perHost);
49
+ const status = response.status();
50
+ if (status === 429 || status === 503) {
51
+ const header = respect
52
+ ? parseRetryAfter(response.headers()["retry-after"])
53
+ : null;
54
+ const next = Math.min(maxBackoff, (backoff.get(host) ?? 1000) * 2);
55
+ backoff.set(host, next);
56
+ blockedUntil.set(host, Date.now() + Math.min(maxBackoff, header ?? next));
57
+ }
58
+ else if (status < 400) {
59
+ backoff.delete(host);
60
+ }
61
+ });
62
+ },
63
+ onPage(page) {
64
+ if (WRAPPED.has(page))
65
+ return;
66
+ WRAPPED.add(page);
67
+ const originalGoto = page.goto.bind(page);
68
+ page.goto = (async (...args) => {
69
+ await take(hostOf(String(args[0]), perHost));
70
+ return originalGoto(...args);
71
+ });
72
+ },
73
+ };
74
+ }
@@ -0,0 +1,5 @@
1
+ import type { BexxcvPlugin } from "./types.js";
2
+ export interface CocoonOptions {
3
+ dir: string;
4
+ }
5
+ export declare function cocoon(options: CocoonOptions): BexxcvPlugin;
@@ -0,0 +1,17 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ export function cocoon(options) {
4
+ return {
5
+ name: "cocoon",
6
+ order: 5,
7
+ beforeLaunch(launch) {
8
+ const dir = path.resolve(options.dir);
9
+ const current = launch.user_data_dir;
10
+ if (typeof current === "string" && path.resolve(current) !== dir) {
11
+ throw new Error('cocoon and user_data_dir point to different folders, set only one of them');
12
+ }
13
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
14
+ launch.user_data_dir = dir;
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,21 @@
1
+ import type { BexxcvPlugin } from "./types.js";
2
+ export interface DodgeOptions {
3
+ pool: string[];
4
+ rotateOn?: number[];
5
+ healthCheck?: boolean;
6
+ healthTimeout?: number;
7
+ cooldown?: number;
8
+ onBlocked?: (info: {
9
+ proxy: string;
10
+ status: number;
11
+ url: string;
12
+ }) => void;
13
+ }
14
+ type ProxyConfig = {
15
+ server: string;
16
+ username?: string;
17
+ password?: string;
18
+ };
19
+ export declare function toProxyConfig(url: string): ProxyConfig;
20
+ export declare function dodge(options: DodgeOptions): BexxcvPlugin;
21
+ export {};
@@ -0,0 +1,102 @@
1
+ import { publicIP } from "../ip.js";
2
+ export function toProxyConfig(url) {
3
+ const parsed = new URL(url);
4
+ const config = { server: `${parsed.protocol}//${parsed.host}` };
5
+ if (parsed.username)
6
+ config.username = decodeURIComponent(parsed.username);
7
+ if (parsed.password)
8
+ config.password = decodeURIComponent(parsed.password);
9
+ return config;
10
+ }
11
+ function timeout(promise, ms) {
12
+ return new Promise((resolve, reject) => {
13
+ const timer = setTimeout(() => reject(new Error("timeout")), ms);
14
+ promise.then((value) => {
15
+ clearTimeout(timer);
16
+ resolve(value);
17
+ }, (error) => {
18
+ clearTimeout(timer);
19
+ reject(error);
20
+ });
21
+ });
22
+ }
23
+ export function dodge(options) {
24
+ if (!options.pool || options.pool.length === 0) {
25
+ throw new Error("dodge needs at least one proxy in pool");
26
+ }
27
+ const rotateOn = new Set(options.rotateOn ?? [403, 429]);
28
+ const cooldown = options.cooldown ?? 300_000;
29
+ const states = options.pool.map((url) => ({ url, badUntil: 0 }));
30
+ const owners = new WeakMap();
31
+ let cursor = 0;
32
+ let launchProxy = null;
33
+ let firstContext = true;
34
+ const pick = () => {
35
+ const now = Date.now();
36
+ for (let i = 0; i < states.length; i++) {
37
+ const state = states[(cursor + i) % states.length];
38
+ if (state.badUntil <= now) {
39
+ cursor = (cursor + i + 1) % states.length;
40
+ return state;
41
+ }
42
+ }
43
+ const soonest = [...states].sort((a, b) => a.badUntil - b.badUntil)[0];
44
+ console.warn("[bexxcv] dodge: every proxy is cooling down, reusing the one that recovers first");
45
+ return soonest;
46
+ };
47
+ return {
48
+ name: "dodge",
49
+ order: 10,
50
+ async beforeLaunch(launch) {
51
+ if (options.healthCheck !== false) {
52
+ const limit = options.healthTimeout ?? 10_000;
53
+ await Promise.all(states.map(async (state) => {
54
+ try {
55
+ state.ip = await timeout(publicIP(state.url), limit);
56
+ }
57
+ catch {
58
+ state.badUntil = Date.now() + cooldown;
59
+ }
60
+ }));
61
+ if (states.every((state) => state.badUntil > Date.now())) {
62
+ throw new Error("dodge: no healthy proxy in pool");
63
+ }
64
+ }
65
+ const chosen = pick();
66
+ launchProxy = chosen.url;
67
+ if (launch.proxy === undefined)
68
+ launch.proxy = toProxyConfig(chosen.url);
69
+ },
70
+ beforeContext(contextOptions) {
71
+ if (contextOptions.proxy)
72
+ return;
73
+ if (firstContext) {
74
+ firstContext = false;
75
+ return;
76
+ }
77
+ const chosen = pick();
78
+ contextOptions.proxy = toProxyConfig(chosen.url);
79
+ },
80
+ onContext(context, contextOptions) {
81
+ const server = contextOptions.proxy?.server;
82
+ const owner = states.find((state) => server && state.url.includes(new URL(state.url).host) && state.url.startsWith(server.split("//")[0]))?.url ??
83
+ launchProxy;
84
+ if (owner)
85
+ owners.set(context, owner);
86
+ context.on("response", (response) => {
87
+ const status = response.status();
88
+ if (!rotateOn.has(status))
89
+ return;
90
+ if (!response.request().isNavigationRequest())
91
+ return;
92
+ const proxy = owners.get(context);
93
+ const state = states.find((s) => s.url === proxy);
94
+ if (!state)
95
+ return;
96
+ state.badUntil = Date.now() + cooldown;
97
+ options.onBlocked?.({ proxy: state.url, status, url: response.url() });
98
+ console.warn(`[bexxcv] dodge: proxy answered ${status}, it is paused for ${Math.round(cooldown / 1000)}s. New contexts will use another proxy.`);
99
+ });
100
+ },
101
+ };
102
+ }
@@ -0,0 +1,20 @@
1
+ import type { Page } from "playwright-core";
2
+ import { type UamResult } from "../uam.js";
3
+ import type { BexxcvPlugin } from "./types.js";
4
+ export interface GauntletOptions {
5
+ solve?: Array<"uam" | "turnstile">;
6
+ maxTries?: number;
7
+ timeout?: number;
8
+ sustain?: number;
9
+ watch?: boolean;
10
+ interval?: number;
11
+ }
12
+ export interface GauntletResult {
13
+ passed: boolean;
14
+ tries: number;
15
+ uam: UamResult | null;
16
+ turnstile: string | null;
17
+ }
18
+ export declare function gauntletResult(page: Page): GauntletResult | null;
19
+ export declare function runGauntlet(page: Page, options?: GauntletOptions): Promise<GauntletResult>;
20
+ export declare function gauntlet(options?: GauntletOptions): BexxcvPlugin;