bexxcv 1.1.2 → 1.1.4

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 CHANGED
@@ -3,6 +3,8 @@
3
3
  Headless Firefox automation with realistic browser fingerprints, built on top of [Camoufox](https://github.com/daijro/camoufox).
4
4
 
5
5
  > **Fork notice:** Forked from [camoufox-js](https://github.com/apify/camoufox-js) by [Apify]. Full credit to the original authors for the architecture, fingerprint generation pipeline, and Playwright integration. This fork adds entropy improvements, GPU-aware WebGL sampling, session management, and ergonomic enhancements.
6
+ >
7
+ > **v1.1.4:** Enhanced fingerprint realism (canvas anti-aliasing offset, audio sample-rate jitter, performance clock drift), expanded 2024–2026 GPU profiles, six new Cloudflare-aware plugins (`jsd`, `ephemeral`, `precursor`, `classify`, `botscore`, `brake`), and improved JSD challenge detection that only activates on real Cloudflare challenge pages.
6
8
 
7
9
  ---
8
10
 
@@ -58,14 +60,42 @@ npx bexxcv fetch
58
60
  ```ts
59
61
  import { bexxcv } from "bexxcv";
60
62
 
63
+ // Firefox mode (default)
61
64
  const browser = await bexxcv({ headless: true });
62
65
  const page = await browser.newPage();
63
66
  await page.goto("https://example.com");
64
67
  await browser.close();
68
+
69
+ // Chromium mode
70
+ const chromium = await bexxcv({ browser: "chromium", headless: true });
71
+ const cPage = await chromium.newPage();
72
+ await cPage.goto("https://example.com");
73
+ await chromium.close();
65
74
  ```
66
75
 
67
76
  On a headless Linux server without `$DISPLAY`, Xvfb starts automatically when `headless` is `false` or unset — no `xvfb-run` wrapper required.
68
77
 
78
+ ### Browser engines
79
+
80
+ | `browser` value | Engine | UA string | Fingerprint source |
81
+ |---|---|---|---|
82
+ | `"firefox"` (default) | Camoufox (Firefox) | `Firefox/xxx` | GPU-aware WebGL sampling + Camoufox config pipeline |
83
+ | `"chromium"` | Playwright Chromium | `Chrome/xxx` | Chromium-native fingerprinting via Playwright |
84
+
85
+ Chromium mode auto-detects a system-installed browser in this order:
86
+ 1. `google-chrome` / `google-chrome-stable` (apt)
87
+ 2. `chromium` / `chromium-browser` (apt)
88
+ 3. Playwright's built-in Chromium (fallback)
89
+
90
+ It skips the Camoufox-specific fingerprint pipeline (no `CAMOUFOX_CONFIG` env vars, no `properties.json` validation). All plugins (JSD, ephemeral, precursor, stealth, etc.) work identically in both modes.
91
+
92
+ ```bash
93
+ # Install system Chromium (Debian/Ubuntu)
94
+ sudo apt install -y chromium
95
+ # or
96
+ sudo apt install -y google-chrome-stable
97
+ ```
98
+
69
99
  ---
70
100
 
71
101
  ## Options
@@ -79,6 +109,11 @@ const browser = await bexxcv({
79
109
  // --- OS targeting ---
80
110
  os: "windows", // "linux" | "macos" | "windows" | array
81
111
 
112
+
113
+ // --- Browser engine ---
114
+ browser: "firefox", // "firefox" (default) | "chromium"
115
+ chromium_sandbox: true, // set false to disable Chromium sandbox (Docker/root)
116
+
82
117
  // --- Fingerprint customization ---
83
118
  fingerprint: undefined, // pass a custom Fingerprint object
84
119
  ff_version: undefined, // override Firefox version in UA string
@@ -109,7 +144,23 @@ const browser = await bexxcv({
109
144
  enable_cache: false, // enable disk + memory cache
110
145
  main_world_eval: false, // allow JS eval in main world
111
146
 
112
- // --- Addons & fonts ---
147
+ // --- Cloudflare / anti-bot plugins (v1.1.4) ---
148
+ classify: true, // auto-detect Cloudflare challenge type per response (default)
149
+ jsd: true, // intercept JSD challenges, wait for cf_clearance (auto-activates on CF pages)
150
+ ephemeral: true, // capture & replay Turnstile ephemeral IDs (default)
151
+ precursor: true, // detect cf_ cookie drift between navigations (default)
152
+ botScore: false, // monitor Cloudflare bot score per page
153
+ brake: false, // rate-limit navigation after CF 403/429 responses
154
+ gauntlet: false, // run a full fingerprint audit gauntlet before each page
155
+ wiretap: false, // intercept & log network requests/responses
156
+ stash: false, // persist fingerprint state to a file for reuse across runs
157
+ veneer: false, // apply a visual "veneer" of extra browser-like CSS properties
158
+ cocoon: false, // sandboxed session isolation
159
+ dodge: false, // avoid re-challenge by rotating ephemeral identifiers
160
+ lens: false, // run the lens audit on each page (fingerprint consistency check)
161
+ human: false, // attach human-like behavior wrapper per page
162
+
163
+ // --- Addons & fonts ---
113
164
  addons: [], // paths to Firefox extension XPIs
114
165
  exclude_addons: [], // built-in addon keys to skip
115
166
  fonts: [], // additional font names to inject
@@ -197,6 +248,162 @@ Can be combined with `turnstile`.
197
248
 
198
249
  ---
199
250
 
251
+ ## Cloudflare plugins (v1.1.4)
252
+
253
+ bexxcv ships six Cloudflare-aware plugins that are enabled by default (or opt-in). Each plugin integrates via the `PluginOptions` interface and is built into the browser context by `buildPlugins()`.
254
+
255
+ ### `classify` — challenge-classify (default: `true`)
256
+
257
+ Reads HTTP responses and page titles to detect which Cloudflare anti-bot layer fired. Classifies as `jsd`, `managed`, `interactive`, `non_interactive`, `turnstile`, `rate_limit`, or `bot_score_low`. Results are cached per-response and exposed via `challengeInfoFor(response)` and `pageChallengeHistory(page)`.
258
+
259
+ ```ts
260
+ import { bexxcv, challengeInfoFor } from "bexxcv";
261
+
262
+ const browser = await bexxcv({ classify: true });
263
+ // On response inspection:
264
+ const page = await browser.newPage();
265
+ const resp = await page.goto("https://protected-site.com");
266
+ const info = challengeInfoFor(resp);
267
+ if (info.type === "managed") console.log("Managed challenge detected");
268
+ ```
269
+
270
+ ### `jsd` — JS Detection handler (default: `true`)
271
+
272
+ Intercepts `page.goto()` and detects real Cloudflare JavaScript Detection challenges by checking for:
273
+ - "Just a moment" / "Attention required" page titles
274
+ - `window.cloudflare.jsd` with `state === "pending"` (only when Cloudflare itself injected the namespace)
275
+
276
+ If a challenge is detected, polls for `cf_clearance` cookie or JSD state transition. Pages without a Cloudflare challenge pass through instantly — no 15s penalty.
277
+
278
+ ```ts
279
+ import { bexxcv, isJsdPassed } from "bexxcv";
280
+
281
+ const browser = await bexxcv({
282
+ jsd: { timeout: 20_000, interval: 500 },
283
+ });
284
+ const page = await browser.newPage();
285
+ await page.goto("https://protected-site.com");
286
+ const passed = await isJsdPassed(page);
287
+ ```
288
+
289
+ Options: `{ timeout?: number, interval?: number }`
290
+
291
+ ### `ephemeral` — Turnstile ephemeral ID tracking (default: `true`)
292
+
293
+ Captures `ephemeral_id` from Turnstile responses and replays it on subsequent navigations to reduce re-challenge frequency. Stored per-context with a 10-minute TTL.
294
+
295
+ ```ts
296
+ import { bexxcv, getEphemeralEntries, replayEphemeral } from "bexxcv";
297
+
298
+ const browser = await bexxcv({
299
+ ephemeral: { autoReplay: true, maxAgeMs: 1_800_000 },
300
+ });
301
+ const context = (browser as any).contexts()[0];
302
+ const entries = getEphemeralEntries(context);
303
+ ```
304
+
305
+ ### `precursor` — cookie drift detection (default: `true`)
306
+
307
+ Watches `cf_` prefixed cookies on every navigation and response. When `cf_clearance` stays the same but a precursor cookie value changes, it signals a stale session. Emits a warning and optionally auto-reloads.
308
+
309
+ ```ts
310
+ import { bexxcv, getPrecursorState } from "bexxcv";
311
+
312
+ const browser = await bexxcv({
313
+ precursor: { warn: true, autoReload: true },
314
+ });
315
+ const page = await browser.newPage();
316
+ await page.goto("https://protected-site.com");
317
+ const state = getPrecursorState(page);
318
+ ```
319
+
320
+ Options: `{ warn?: boolean, autoReload?: boolean, names?: string[] }`
321
+
322
+ ### `botScore` — bot score monitor (default: `false`)
323
+
324
+ Periodically checks Cloudflare's bot score via the page's `window.__cfBotScore` (when available) and logs the value. Useful for debugging why a site is issuing managed challenges.
325
+
326
+ ```ts
327
+ import { bexxcv, getBotScores, hadLowScore } from "bexxcv";
328
+
329
+ const browser = await bexxcv({ botScore: { log: true } });
330
+ const page = await browser.newPage();
331
+ await page.goto("https://protected-site.com");
332
+ const scores = getBotScores(page);
333
+ if (hadLowScore(page, 40)) console.log("Bot score was low — expect challenges");
334
+ ```
335
+
336
+ ### `brake` — rate limiter with CF 403 support (default: `false`)
337
+
338
+ Intercepts `page.goto()` and applies exponential backoff when Cloudflare returns HTTP 403 or 429. Prevents rapid re-challenge loops.
339
+
340
+ ```ts
341
+ import { bexxcv, brake } from "bexxcv";
342
+
343
+ const browser = await bexxcv({
344
+ brake: { maxRetries: 3, baseDelayMs: 2000 },
345
+ });
346
+ ```
347
+
348
+ Options: `{ maxRetries?: number, baseDelayMs?: number }`
349
+
350
+ ### `stealth` — automation marker spoofing (default: `false`)
351
+
352
+ Patches `navigator.webdriver`, `navigator.plugins`, `navigator.languages`, and removes framework markers (`window.Cypress`, `window.__playwright`, `window._phantom`, etc.) via `addInitScript`. All patches run in the page's main world before any site JavaScript executes.
353
+
354
+ ```ts
355
+ import { bexxcv, stealth, attachStealth } from "bexxcv";
356
+
357
+ // Use as a launch option:
358
+ const browser = await bexxcv({
359
+ stealth: {
360
+ webdriver: true,
361
+ plugins: true,
362
+ languages: true,
363
+ frameworkMarkers: true,
364
+ },
365
+ });
366
+
367
+ // Or attach to an existing browser:
368
+ attachStealth(browser, { webdriver: true });
369
+ ```
370
+
371
+ Options: `{ webdriver?: boolean, plugins?: boolean, languages?: boolean, frameworkMarkers?: boolean }`
372
+
373
+ ---
374
+
375
+ ## Fingerprint quality (v1.1.4)
376
+
377
+ bexxcv generates fingerprints with per-GPU WebGL data, canvas anti-aliasing offsets, audio sample-rate jitter, and performance clock drift. The fingerprint pipeline:
378
+
379
+ 1. **OS selection** — picks a Firefox version, platform, and screen size from a weighted pool
380
+ 2. **DPR coherence** — selects a device pixel ratio such that CSS × DPR matches a known monitor resolution
381
+ 3. **WebGL sampling** — queries `webgl_data.db` for vendor/renderer pairs weighted by OS and GPU generation (2024–2026 hardware included)
382
+ 4. **Canvas AA offset** — applies a per-GPU anti-aliasing sub-pixel offset to `canvasAaOffset`
383
+ 5. **Audio jitter** — applies `audioSampleRateJitter` (±0.5 Hz) to the Web Audio API clock
384
+ 6. **Perf jitter** — applies Gaussian `perfJitterSigma` drift to `performance.now()`
385
+ 7. **Font spacing** — picks a font rendering seed from a weighted list per OS
386
+
387
+ ```ts
388
+ import { generateFingerprint, sampleGPUProfile, resolveUAOS } from "bexxcv";
389
+
390
+ const fp = generateFingerprint([1920, 1080], {
391
+ operatingSystems: ["windows"],
392
+ canvasAaOffset: true,
393
+ audioSampleRateJitter: true,
394
+ perfJitterSigma: 0.15,
395
+ });
396
+ console.log(fp.webglVendor, fp.webglRenderer, fp.canvasAaOffset);
397
+
398
+ const gpu = sampleGPUProfile("linux");
399
+ console.log(gpu.vendor, gpu.renderer);
400
+
401
+ const os = resolveUAOS(gpu.vendor, gpu.renderer);
402
+ console.log(os); // "linux" | "windows" | "macos"
403
+ ```
404
+
405
+ ---
406
+
200
407
  ## Session API
201
408
 
202
409
  Bexxcv maintains per-page session state for consistent fingerprinting and human-like behavior across multiple page navigations.
@@ -21,7 +21,9 @@ export interface ExtendedScreen extends ScreenFingerprint {
21
21
  onlineState?: boolean;
22
22
  platformDeviceMemory?: number;
23
23
  }
24
- export declare function generateFingerprint(window?: [number, number], config?: Partial<FingerprintGeneratorOptions>): Fingerprint & ExtendedScreen;
24
+ export declare function generateFingerprint(window?: [number, number], config?: Partial<FingerprintGeneratorOptions> & {
25
+ browser?: "firefox" | "chromium";
26
+ }): Fingerprint & ExtendedScreen;
25
27
  export declare function fromBrowserforge(fingerprint: Fingerprint, ffVersion?: string): Record<string, any>;
26
28
  /**
27
29
  * Returns a realistic font list for the given OS.
@@ -2,10 +2,14 @@ import { FingerprintGenerator, } from "fingerprint-generator";
2
2
  import BROWSERFORGE_DATA from "./mappings/browserforge.config.js";
3
3
  import { sampleGPUProfile, resolveUAOS } from "./webgl/profiles.js";
4
4
  export const SUPPORTED_OS = ["linux", "macos", "windows"];
5
- const FP_GENERATOR = new FingerprintGenerator({
5
+ const FP_GENERATOR_FF = new FingerprintGenerator({
6
6
  browsers: ["firefox"],
7
7
  operatingSystems: SUPPORTED_OS,
8
8
  });
9
+ const FP_GENERATOR_CR = new FingerprintGenerator({
10
+ browsers: ["chrome"],
11
+ operatingSystems: SUPPORTED_OS,
12
+ });
9
13
  export function cryptoRandInt(min, max) {
10
14
  const buf = new Uint32Array(1);
11
15
  crypto.getRandomValues(buf);
@@ -150,14 +154,19 @@ function applyRealismSeeds(fp, ua) {
150
154
  fp.onlineState = cryptoFloat() > 0.001;
151
155
  }
152
156
  export function generateFingerprint(window, config) {
157
+ const browser = config?.browser ?? "firefox";
158
+ const generator = browser === "chromium" ? FP_GENERATOR_CR : FP_GENERATOR_FF;
159
+ // Strip browser from config before passing to generator
160
+ const genConfig = { ...config };
161
+ delete genConfig.browser;
153
162
  let fp;
154
163
  if (window) {
155
- const generated = FP_GENERATOR.getFingerprint(config);
164
+ const generated = generator.getFingerprint(genConfig);
156
165
  fp = generated.fingerprint;
157
166
  handleWindowSize(fp, window[0], window[1]);
158
167
  }
159
168
  else {
160
- const generated = FP_GENERATOR.getFingerprint(config);
169
+ const generated = generator.getFingerprint(genConfig);
161
170
  fp = generated.fingerprint;
162
171
  }
163
172
  const ua = fp.navigator?.userAgent ?? "";
package/dist/index.d.ts CHANGED
@@ -11,7 +11,11 @@ export { dataStatus, doctor, type DataStatus } from "./doctor.js";
11
11
  export { validateOptions } from "./schema.js";
12
12
  export { applyPlugins, auditFingerprint, buildPlugins, gauntletResult, lensReport, runGauntlet, wiretapEntries, type BexxcvPlugin, type BrakeOptions, type DodgeOptions, type GauntletOptions, type GauntletResult, type LensOptions, type LensReport, type LensCheck, type PluginOptions, type StashOptions, type VeneerOptions, type WiretapOptions, } from "./plugins/index.js";
13
13
  export { solveTurnstile } from "./turnstile.js";
14
- export { brake, cocoon, dodge, gauntlet, human, lens, stash, turnstile, uam, veneer, wiretap, type HumanPluginOptions, } from "./plugins/index.js";
14
+ export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap, challengePlugin, jsd, ephemeral, precursor, botScore, stealth, attachStealth, type HumanPluginOptions, } from "./plugins/index.js";
15
+ export { turnstile, uam } from "./plugins/solvers.js";
16
+ export { getEphemeralEntries, replayEphemeral, isJsdPassed } from "./plugins/index.js";
17
+ export { getPrecursorState, resetPrecursorState } from "./plugins/precursor.js";
18
+ export { getBotScores, avgBotScore, hadLowScore } from "./plugins/botscore.js";
15
19
  export { attachHumanBehavior, detachHumanBehavior, getSessionInfo, type HumanBehaviorOptions, } from "./human_behavior.js";
16
20
  export { initSession, getSessionId, advancePage, endSession, isSessionExpired, getSeededFloat, getSeededInt, getSeededGauss, type SessionOptions, } from "./session.js";
17
21
  export { generateFingerprint, cryptoRandInt, cryptoFloat, SUPPORTED_OS, type ExtendedScreen } from "./fingerprints.js";
package/dist/index.js CHANGED
@@ -11,7 +11,11 @@ export { dataStatus, doctor } from "./doctor.js";
11
11
  export { validateOptions } from "./schema.js";
12
12
  export { applyPlugins, auditFingerprint, buildPlugins, gauntletResult, lensReport, runGauntlet, wiretapEntries, } from "./plugins/index.js";
13
13
  export { solveTurnstile } from "./turnstile.js";
14
- export { brake, cocoon, dodge, gauntlet, human, lens, stash, turnstile, uam, veneer, wiretap, } from "./plugins/index.js";
14
+ export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap, challengePlugin, jsd, ephemeral, precursor, botScore, stealth, attachStealth, } from "./plugins/index.js";
15
+ export { turnstile, uam } from "./plugins/solvers.js";
16
+ export { getEphemeralEntries, replayEphemeral, isJsdPassed } from "./plugins/index.js";
17
+ export { getPrecursorState, resetPrecursorState } from "./plugins/precursor.js";
18
+ export { getBotScores, avgBotScore, hadLowScore } from "./plugins/botscore.js";
15
19
  export { attachHumanBehavior, detachHumanBehavior, getSessionInfo, } from "./human_behavior.js";
16
20
  export { initSession, getSessionId, advancePage, endSession, isSessionExpired, getSeededFloat, getSeededInt, getSeededGauss, } from "./session.js";
17
21
  export { generateFingerprint, cryptoRandInt, cryptoFloat, SUPPORTED_OS } from "./fingerprints.js";
@@ -0,0 +1,34 @@
1
+ import type { Browser, BrowserContext } from "playwright-core";
2
+ import type { BexxcvPlugin } from "./types.js";
3
+ /**
4
+ * Monitors Cloudflare Bot Management scores from response headers.
5
+ *
6
+ * When Bot Management is enabled, Cloudflare may expose the computed bot score
7
+ * via custom headers. This plugin parses those headers and exposes them through
8
+ * a query API so downstream code can make decisions based on the score.
9
+ *
10
+ * Supported header names (case-insensitive):
11
+ * - cf-bay-pass (Enterprise JS Detection pass/fail)
12
+ * - cf-ray (used alongside classification)
13
+ * - x-moz (Firefox-specific anti-bot marker observed in the wild)
14
+ */
15
+ export interface BotScoreOptions {
16
+ /** Cache collected scores per-context for later retrieval. Default true. */
17
+ cache?: boolean;
18
+ }
19
+ interface ScoreEntry {
20
+ url: string;
21
+ score: number | null;
22
+ src: string;
23
+ timestamp: number;
24
+ }
25
+ export declare function botScore(options?: BotScoreOptions): BexxcvPlugin;
26
+ /** Retrieve cached bot-score entries for a context. */
27
+ export declare function getBotScores(context: BrowserContext): ScoreEntry[];
28
+ /** Get the average bot score across all cached entries for a context. */
29
+ export declare function avgBotScore(context: BrowserContext): number | null;
30
+ /** Check whether any recent score fell below threshold. */
31
+ export declare function hadLowScore(context: BrowserContext, threshold?: number, windowMs?: number): boolean;
32
+ /** Attach bot-score monitoring to an existing browser or context. */
33
+ export declare function attachBotScore<T extends Browser | BrowserContext>(target: T, _options?: BotScoreOptions): T;
34
+ export {};
@@ -0,0 +1,79 @@
1
+ const SCORES = new WeakMap();
2
+ const WATCHED = new WeakSet();
3
+ /** Parse a bot-management score from a response. Returns null if not present. */
4
+ function parseBotScore(response) {
5
+ const headers = response.headers();
6
+ // Cloudflare Enterprise Bot Management sometimes echoes score
7
+ const raw = headers["cf-bot-management-score"] ??
8
+ headers["x-cf-bot-score"] ??
9
+ headers["x-moz"] ??
10
+ null;
11
+ if (!raw)
12
+ return null;
13
+ const score = Number(raw);
14
+ if (!Number.isFinite(score))
15
+ return null;
16
+ return { score, src: raw };
17
+ }
18
+ export function botScore(options = {}) {
19
+ const cacheEnabled = options.cache ?? true;
20
+ return {
21
+ name: "bot-score-monitor",
22
+ order: 41,
23
+ onContext(context) {
24
+ if (!cacheEnabled)
25
+ return;
26
+ SCORES.set(context, []);
27
+ },
28
+ onPage(page) {
29
+ if (WATCHED.has(page))
30
+ return;
31
+ WATCHED.add(page);
32
+ page.context()?.on?.("response", (response) => {
33
+ const result = parseBotScore(response);
34
+ if (!result || result.score === null)
35
+ return;
36
+ const entry = {
37
+ url: response.url(),
38
+ score: result.score,
39
+ src: result.src,
40
+ timestamp: Date.now(),
41
+ };
42
+ if (cacheEnabled && page.context()) {
43
+ const list = SCORES.get(page.context()) ?? [];
44
+ list.push(entry);
45
+ if (list.length > 50)
46
+ list.shift();
47
+ if (page.context())
48
+ SCORES.set(page.context(), list);
49
+ }
50
+ // Log low scores as warnings (score < 30 = likely automated per CF docs)
51
+ if (result.score < 30) {
52
+ console.warn(`[bexxcv] bot-score: low score ${result.score} on ${response.url()} (src: ${result.src})`);
53
+ }
54
+ });
55
+ },
56
+ };
57
+ }
58
+ /** Retrieve cached bot-score entries for a context. */
59
+ export function getBotScores(context) {
60
+ return SCORES.get(context) ?? [];
61
+ }
62
+ /** Get the average bot score across all cached entries for a context. */
63
+ export function avgBotScore(context) {
64
+ const entries = SCORES.get(context) ?? [];
65
+ const scored = entries.filter((e) => e.score !== null && e.score !== undefined);
66
+ if (scored.length === 0)
67
+ return null;
68
+ return scored.reduce((sum, e) => sum + (e.score ?? 0), 0) / scored.length;
69
+ }
70
+ /** Check whether any recent score fell below threshold. */
71
+ export function hadLowScore(context, threshold = 30, windowMs = 300_000) {
72
+ const now = Date.now();
73
+ return SCORES.get(context)?.some((e) => e.score !== null && e.score < threshold && now - e.timestamp < windowMs) ?? false;
74
+ }
75
+ /** Attach bot-score monitoring to an existing browser or context. */
76
+ export function attachBotScore(target, _options = {}) {
77
+ void botScore(_options);
78
+ return target;
79
+ }
@@ -4,5 +4,9 @@ export interface BrakeOptions {
4
4
  respectRetryAfter?: boolean;
5
5
  perHost?: boolean;
6
6
  maxBackoff?: number;
7
+ /** Enable detection of Cloudflare 403s and back off accordingly. Default true. */
8
+ respectCf403?: boolean;
7
9
  }
8
10
  export declare function brake(options?: BrakeOptions): BexxcvPlugin;
11
+ /** Get the current consecutive-403 counter for a host. */
12
+ export declare function getConsecutive403(host: string): number;
@@ -19,11 +19,14 @@ function parseRetryAfter(value) {
19
19
  const date = Date.parse(value);
20
20
  return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
21
21
  }
22
+ /** Count consecutive 403s per host — useful for detecting repeated CF blocks. */
23
+ const CONSECUTIVE_403 = new Map();
22
24
  export function brake(options = {}) {
23
25
  const interval = 1000 / (options.maxRps ?? 2);
24
26
  const respect = options.respectRetryAfter ?? true;
25
27
  const perHost = options.perHost ?? true;
26
28
  const maxBackoff = options.maxBackoff ?? 120_000;
29
+ const respectCf403 = options.respectCf403 ?? true;
27
30
  const nextSlot = new Map();
28
31
  const blockedUntil = new Map();
29
32
  const backoff = new Map();
@@ -47,16 +50,36 @@ export function brake(options = {}) {
47
50
  return;
48
51
  const host = hostOf(response.url(), perHost);
49
52
  const status = response.status();
53
+ const headers = response.headers();
54
+ // Rate limit: 429 / 503
50
55
  if (status === 429 || status === 503) {
51
56
  const header = respect
52
- ? parseRetryAfter(response.headers()["retry-after"])
57
+ ? parseRetryAfter(headers["retry-after"])
53
58
  : null;
54
59
  const next = Math.min(maxBackoff, (backoff.get(host) ?? 1000) * 2);
55
60
  backoff.set(host, next);
56
61
  blockedUntil.set(host, Date.now() + Math.min(maxBackoff, header ?? next));
62
+ CONSECUTIVE_403.delete(host);
63
+ return;
64
+ }
65
+ // Cloudflare 403 with cf-ray → likely a bot block, apply exponential backoff
66
+ if (respectCf403 && status === 403 && headers["cf-ray"]) {
67
+ const prev = CONSECUTIVE_403.get(host) ?? 0;
68
+ const count = prev + 1;
69
+ CONSECUTIVE_403.set(host, count);
70
+ if (count >= 2) {
71
+ // Second+ 403: longer backoff, may need fresh clearance
72
+ const penalty = Math.min(maxBackoff, 5_000 * count);
73
+ blockedUntil.set(host, Date.now() + penalty);
74
+ console.warn(`[bexxcv] brake: Cloudflare 403 detected on ${host} (consecutive: ${count}). ` +
75
+ `Backing off ${penalty}ms. Consider rotating proxy or clearing cookies.`);
76
+ }
77
+ return;
57
78
  }
58
- else if (status < 400) {
79
+ // Successful response clears counters
80
+ if (status < 400) {
59
81
  backoff.delete(host);
82
+ CONSECUTIVE_403.delete(host);
60
83
  }
61
84
  });
62
85
  },
@@ -72,3 +95,7 @@ export function brake(options = {}) {
72
95
  },
73
96
  };
74
97
  }
98
+ /** Get the current consecutive-403 counter for a host. */
99
+ export function getConsecutive403(host) {
100
+ return CONSECUTIVE_403.get(host) ?? 0;
101
+ }
@@ -0,0 +1,36 @@
1
+ import type { Response } from "playwright-core";
2
+ import type { BexxcvPlugin } from "./types.js";
3
+ /**
4
+ * Classifies Cloudflare challenge types from HTTP responses.
5
+ *
6
+ * Reads response status, selected headers (cf-ray, cf-cache-status, server),
7
+ * and page title / body markers to decide which anti-bot layer fired and at
8
+ * what clearance level. Results are attached to every page via a WeakMap so
9
+ * downstream plugins (gauntlet, wiretap) can query them.
10
+ */
11
+ export type ChallengeType = "none" | "jsd" | "managed" | "interactive" | "non_interactive" | "turnstile" | "rate_limit" | "bot_score_low" | "unknown";
12
+ export type ClearanceLevel = "none" | "js" | "managed" | "high";
13
+ export interface ChallengeInfo {
14
+ type: ChallengeType;
15
+ clearanceLevel: ClearanceLevel;
16
+ confidence: number;
17
+ reason: string;
18
+ cfRay?: string;
19
+ cached?: boolean;
20
+ }
21
+ export declare function challengeInfoFor(response: Response): ChallengeInfo | null;
22
+ export declare function pageChallengeHistory(page: {
23
+ id: string;
24
+ }): ChallengeInfo[];
25
+ export declare function appendChallengeInfo(page: {
26
+ id: string;
27
+ }, info: ChallengeInfo): void;
28
+ export declare function latestChallenge(page: {
29
+ id: string;
30
+ }): ChallengeInfo | null;
31
+ export declare function classifyResponse(response: Response): ChallengeInfo;
32
+ export declare function classifyPage(page: {
33
+ url(): string;
34
+ title(): Promise<string>;
35
+ }): Promise<ChallengeInfo>;
36
+ export declare function challengePlugin(): BexxcvPlugin;