bexxcv 1.1.1 → 1.1.3

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
@@ -329,6 +329,108 @@ See individual plugin documentation for configuration options.
329
329
 
330
330
  ---
331
331
 
332
+ ## Lens Fingerprint Audit
333
+
334
+ The `lens` plugin audits the running browser's fingerprint in real time and reports any inconsistencies:
335
+
336
+ ```ts
337
+ import { bexxcv, lens, lensReport } from "bexxcv";
338
+
339
+ const browser = await bexxcv({ headless: true });
340
+ const page = await browser.newPage();
341
+ await page.goto("https://example.com");
342
+
343
+ // The lens plugin runs automatically when added to plugins
344
+ const report = lensReport(page);
345
+ if (report) {
346
+ console.log(`Score: ${report.score}/100`);
347
+ for (const check of report.checks) {
348
+ if (!check.ok) console.log(` ❌ ${check.id}: ${check.detail}`);
349
+ }
350
+ }
351
+ ```
352
+
353
+ Run the audit manually on any page:
354
+
355
+ ```ts
356
+ import { auditFingerprint } from "bexxcv";
357
+
358
+ const report = await auditFingerprint(page);
359
+ ```
360
+
361
+ ### Checks performed
362
+
363
+ | Check ID | What it validates |
364
+ |---|---|
365
+ | `webdriver` | `navigator.webdriver` is `undefined` / falsy |
366
+ | `ua-platform` | `navigator.platform` matches OS in UA string |
367
+ | `language` | First language in `navigator.languages` equals `navigator.language` |
368
+ | `locale-intl` | `Intl.DateTimeFormat()` locale matches `navigator.language` prefix |
369
+ | `dpr-screen` | CSS × DPR lands on a known physical monitor resolution |
370
+ | `window-size` | inner ≤ outer ≤ screen + 16 px (Chrome frame buffer) |
371
+ | `cores` | hardwareConcurrency is a plausible CPU core count |
372
+ | `touch` | `maxTouchPoints` is 0 on desktop UAs |
373
+ | `webgl` | WebGL vendor/renderer are present and non-null |
374
+ | `webgl-software` | Renderer is not a software fallback (llvmpipe/swiftshader) |
375
+ | `native-code` | Core APIs have `[native code]` toString output |
376
+ | `ua-hints` | `userAgentData` absent for Firefox, present for Chrome-like UAs |
377
+ | `chrome-object` | `window.chrome` absent for Firefox |
378
+ | `pdf-viewer` | `navigator.pdfViewerEnabled` is `true` on Firefox |
379
+ | `focus` | Page is focused and visible |
380
+ | `media-devices` | At least one media device or headless timeout fallback |
381
+ | `audio-sample-rate` | `AudioContext.sampleRate` is 44100 or 48000 |
382
+ | `fonts-enumerated` | `document.fonts.size > 0` and no load error |
383
+ | `webgl-shader-precision` | Highp float shader precision ≥ 23 (desktop GPU) |
384
+ | `client-hints-platform` | `userAgentData.platform` consistent with `navigator.platform` |
385
+
386
+ ---
387
+
388
+ ## Context Isolation
389
+
390
+ Every Playwright `browserContext` gets an independent fingerprint, storage, and cookies. Cross-context leakage is guarded by test coverage:
391
+
392
+ ```ts
393
+ import { Camoufox } from "bexxcv";
394
+
395
+ const browser = await Camoufox({ headless: true });
396
+
397
+ const ctxA = await browser.newContext();
398
+ const ctxB = await browser.newContext();
399
+
400
+ const pageA = await ctxA.newPage();
401
+ const pageB = await ctxB.newPage();
402
+
403
+ await pageA.goto("https://example.com");
404
+ await pageB.goto("https://example.com");
405
+
406
+ // localStorage set in A is invisible from B
407
+ await pageA.evaluate(() => localStorage.setItem("key", "secret-a"));
408
+ const leaked = await pageB.evaluate(() => localStorage.getItem("key"));
409
+ console.log(leaked); // null ✓
410
+ ```
411
+
412
+ Tests are in `test/isolation.test.ts`.
413
+
414
+ ---
415
+
416
+ ## Behavioral Seeding
417
+
418
+ Beyond raw fingerprint properties, bexxcv seeds high-level behavioral signals that detectors flag as suspicious when missing or default:
419
+
420
+ | Property Group | What Gets Seeded | Realism Logic |
421
+ |---|---|---|
422
+ | **Battery** | `battery:level`, `charging`, `dischargingTime` | Desktop → full & discharging; Laptop/Mac → 20–95% with ~25% charging state |
423
+ | **Media devices** | `mediaDevices:micros/webcams/speakers` | OS-weighted pools: mics [0-2], cams [0-2], speakers [0-4] |
424
+ | **Speech voices** | `voices[]`, `blockIfNotDefined`, `fakeCompletion` | 2–10 voices matching locale language |
425
+ | **Do Not Track** | `navigator.doNotTrack` | ~20% of real users enable DNT |
426
+ | **GPC** | `navigator.globalPrivacyControl` | ~10% signal GPC |
427
+ | **Referrer policy** | Firefox pref `privacy.referrer_policy` | Same-Origin on cross-origin for non-headless |
428
+ | **Online/cookies** | `navigator.onLine`, `cookieEnabled` | Almost always online and cookies enabled |
429
+
430
+ These are applied automatically when the installed Camoufox build supports the corresponding properties. Run `npx bexxcv doctor` to see your build's supported properties.
431
+
432
+ ---
433
+
332
434
  ## Persistent context
333
435
 
334
436
  ```ts
@@ -20,6 +20,12 @@ export interface ExtendedScreen extends ScreenFingerprint {
20
20
  pointerType?: "mouse" | "touch" | "pen";
21
21
  onlineState?: boolean;
22
22
  platformDeviceMemory?: number;
23
+ /** Randomised canvas anti-alias offset in sub-pixel range — larger range = harder to fingerprint */
24
+ canvasAaOffset?: number;
25
+ /** Audio sample-rate jitter in Hz (simulates OS-level audio clock variance) */
26
+ audioSampleRateJitter?: number;
27
+ /** Performance.now() Gaussian jitter sigma in ms (replaces uniform range) */
28
+ perfJitterSigma?: number;
23
29
  }
24
30
  export declare function generateFingerprint(window?: [number, number], config?: Partial<FingerprintGeneratorOptions>): Fingerprint & ExtendedScreen;
25
31
  export declare function fromBrowserforge(fingerprint: Fingerprint, ffVersion?: string): Record<string, any>;
@@ -16,12 +16,16 @@ export function cryptoFloat() {
16
16
  crypto.getRandomValues(buf);
17
17
  return buf[0] / 0x100000000;
18
18
  }
19
- // Realistic font lists per OS — these are actual system fonts, not random strings
19
+ // Realistic font lists per OS — expanded with 2024–2025 system fonts
20
20
  const REALISTIC_FONTS = {
21
21
  win: [
22
22
  "Arial", "Arial Black", "Calibri", "Cambria", "Cambria Math", "Comic Sans MS",
23
23
  "Consolas", "Courier New", "Georgia", "Impact", "Segoe UI", "Times New Roman",
24
24
  "Trebuchet MS", "Verdana", "Microsoft YaHei", "Microsoft JhengHei",
25
+ "Segoe MDL2 Assets", "Segoe Fluent Icons", "Ebrima", "Nirmala UI",
26
+ "Malgun Gothic", "Gulim", "Batang", "Dotum", "Apple Chancery",
27
+ "Lucida Console", "Palatino Linotype", "Book Antiqua", "Century Gothic",
28
+ "Franklin Gothic Medium", "Helvetica", "Monaco", "System Font",
25
29
  ],
26
30
  mac: [
27
31
  "Apple SD Gothic Neo", "Avenir", "Baskerville", "Big Caslon", "Chalkboard",
@@ -29,14 +33,19 @@ const REALISTIC_FONTS = {
29
33
  "Gill Sans", "Helvetica", "Helvetica Neue", "Hiragino Kaku Gothic Pro",
30
34
  "Hiragino Maru Gothic Pro", "Menlo", "Mukta Mahee", "MV Boli", "Noto Sans",
31
35
  "Palatino", "San Francisco", "STHeiti", "Symbol", "Tahoma", "Thonburi",
32
- "Times", "Trattatello", "Zapfino",
36
+ "Times", "Trattatello", "Zapfino", "Marker Felt", "Papyrus", "Cochin",
37
+ "American Typewriter", "Arial Hebrew", "Geeza Pro", "Kailasa", "Sinhala Sangam MN",
38
+ "Devanagari Sangam MN", "Oriya Sangam MN", "Tamil Sangam MN",
33
39
  ],
34
40
  lin: [
35
41
  "Arial", "Cantarell", "Comfortaa", "DejaVu Sans", "DejaVu Sans Mono",
36
42
  "Fira Code", "Fira Sans", "Google Sans", "Iosevka", "Liberation Mono",
37
43
  "Liberation Sans", "Liberation Serif", "Monospace", "Noto Color Emoji",
38
44
  "Noto Sans", "Noto Sans CJK", "Roboto", "Source Code Pro", "Ubuntu",
39
- "Ubuntu Condensed", "Ubuntu Mono",
45
+ "Ubuntu Condensed", "Ubuntu Mono", "Bitstream Vera Sans", "Vera",
46
+ "FreeSans", "FreeSerif", "Inconsolata", "Lato", "Open Sans",
47
+ "Philosopher", "PT Sans", "Raleway", "Source Sans Pro", "Work Sans",
48
+ "Overpass", "M+ 1m", "Noto Sans JP", "Noto Sans KR", "Noto Sans SC",
40
49
  ],
41
50
  };
42
51
  // Realistic canvas noise patterns that match GPU output characteristics
@@ -47,16 +56,17 @@ const CANVAS_NOISE_PATTERNS = [
47
56
  { type: "saltPepper", density: 0.02 },
48
57
  { type: "none" }, // clean renderers exist too
49
58
  ];
50
- // Subtle timing variations that differ by GPU class
59
+ // Subtle timing variations that differ by GPU class — expanded with more granular ranges
51
60
  const RENDER_TIME_VARIATIONS = {
52
- Intel: { minMs: 8, maxMs: 18 },
53
- NVIDIA: { minMs: 3, maxMs: 8 },
54
- AMD: { minMs: 4, maxMs: 10 },
55
- Mesa: { minMs: 15, maxMs: 35 },
56
- Apple: { minMs: 5, maxMs: 12 },
57
- Microsoft: { minMs: 20, maxMs: 50 },
58
- Mozilla: { minMs: 10, maxMs: 20 },
59
- Google: { minMs: 6, maxMs: 14 },
61
+ Intel: { minMs: 6, maxMs: 22 },
62
+ NVIDIA: { minMs: 2, maxMs: 10 },
63
+ AMD: { minMs: 3, maxMs: 12 },
64
+ Mesa: { minMs: 12, maxMs: 40 },
65
+ Apple: { minMs: 4, maxMs: 14 },
66
+ Microsoft: { minMs: 18, maxMs: 55 },
67
+ Mozilla: { minMs: 8, maxMs: 24 },
68
+ Google: { minMs: 5, maxMs: 16 },
69
+ llvmpipe: { minMs: 25, maxMs: 60 },
60
70
  };
61
71
  function pickWeighted(items, weights) {
62
72
  const total = weights.reduce((a, b) => a + b, 0);
@@ -114,6 +124,21 @@ function handleScreenXY(camoufoxData, fpScreen) {
114
124
  camoufoxData["window.screenY"] = cryptoRandInt(screenY, 0);
115
125
  }
116
126
  }
127
+ /**
128
+ * Approximate Gaussian using sum of 6 uniform randoms (Central Limit Theorem).
129
+ * Returns value in [min, max] with normal distribution centred at mid-point.
130
+ */
131
+ function gaussianBetween(min, max) {
132
+ const buf = new Uint32Array(6);
133
+ crypto.getRandomValues(buf);
134
+ let sum = 0;
135
+ for (let i = 0; i < 6; i++)
136
+ sum += buf[i] / 0x100000000;
137
+ // sum of 6 uniforms ≈ N(3, sqrt(6/12)) = N(3, 0.707)
138
+ // map to [0, 1] then to [min, max]
139
+ const clamped = Math.max(0, Math.min(6, sum)) / 6;
140
+ return min + clamped * (max - min);
141
+ }
117
142
  function applyRealismSeeds(fp, ua) {
118
143
  const os = resolveUAOS(ua);
119
144
  const gpu = sampleGPUProfile(os);
@@ -125,29 +150,35 @@ function applyRealismSeeds(fp, ua) {
125
150
  fp.webglRenderer = gpu.renderer;
126
151
  fp.webglGLSL = gpu.glslVersion;
127
152
  fp.webglExtensions = gpu.webglExtensions;
128
- // Performance timing jitter based on GPU class
153
+ // Performance timing jitter — Gaussian-like instead of uniform for realism
129
154
  const perfRange = RENDER_TIME_VARIATIONS[gpu.vendor] ?? { minMs: 5, maxMs: 20 };
130
- fp.perfJitter = (cryptoFloat() - 0.5) * (perfRange.maxMs - perfRange.minMs);
131
- // Timezone offset jitter (±15 min)
132
- fp.timezoneOffsetJitter = cryptoRandInt(-15, 15) * 60; // in seconds
133
- // Memory multiplier (0.85–1.15x base)
134
- fp.memoryMultiplier = 0.85 + cryptoFloat() * 0.3;
135
- // Hardware concurrency from realistic pool
136
- const possibleCores = [2, 4, 6, 8, 10, 12, 16, 20, 24];
155
+ fp.perfJitter = gaussianBetween(perfRange.minMs, perfRange.maxMs) - (perfRange.minMs + perfRange.maxMs) / 2;
156
+ fp.perfJitterSigma = (perfRange.maxMs - perfRange.minMs) / 4; // sigma for runtime sampling
157
+ // Timezone offset jitter — ±30 min (was ±15) for stronger anti-fingerprinting
158
+ fp.timezoneOffsetJitter = Math.round(gaussianBetween(-30, 30)) * 60; // seconds
159
+ // Memory multiplier — tighter realistic range 0.90–1.10 (was 0.85–1.15)
160
+ fp.memoryMultiplier = 0.90 + cryptoFloat() * 0.20;
161
+ // Hardware concurrency — expanded pool including rare but real configs
162
+ const possibleCores = [2, 3, 4, 6, 8, 10, 12, 14, 16, 20, 24, 32];
137
163
  fp.hardwareConcurrencySeed = possibleCores[cryptoRandInt(0, possibleCores.length - 1)];
138
- // Touch support correlates with device type (more common on mobile/tablets)
139
- const touchChance = os === "win" ? 0.15 : os === "mac" ? 0.05 : 0.02;
164
+ // Touch support correlates with device type
165
+ const touchChance = os === "win" ? 0.12 : os === "mac" ? 0.04 : 0.02;
140
166
  fp.touchSupport = cryptoFloat() < touchChance;
141
167
  fp.touchPoints = fp.touchSupport ? cryptoRandInt(1, 5) : 0;
142
- // Pointer type consistency — desktop has mouse, touch devices have pointer+touch
168
+ // Pointer type consistency
143
169
  if (fp.touchSupport) {
144
170
  fp.pointerType = cryptoFloat() < 0.3 ? "touch" : "mouse";
145
171
  }
146
172
  else {
147
173
  fp.pointerType = cryptoFloat() < 0.05 ? "pen" : "mouse";
148
174
  }
149
- // Online state is almost always true for real browsers
175
+ // Online state — virtually always true
150
176
  fp.onlineState = cryptoFloat() > 0.001;
177
+ // Canvas AA offset — wider range for level-max anti-detection (was 0..100 → now -75..75)
178
+ fp.canvasAaOffset = cryptoRandInt(-75, 75);
179
+ // Audio sample-rate jitter — simulates OS-level clock drift (±2 Hz around 44100/48000)
180
+ const baseSampleRate = [44100, 48000][cryptoRandInt(0, 1)];
181
+ fp.audioSampleRateJitter = cryptoRandInt(-2, 2); // ±2 Hz
151
182
  }
152
183
  export function generateFingerprint(window, config) {
153
184
  let fp;
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, 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, } 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;