bexxcv 1.1.2 → 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.
@@ -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;
@@ -0,0 +1,174 @@
1
+ const CHALLENGE_TITLES = new Set([
2
+ "just a moment",
3
+ "tunggu sebentar",
4
+ "attention required",
5
+ "security check",
6
+ "un instant",
7
+ "einen moment",
8
+ "один момент",
9
+ "um momento",
10
+ "un momento",
11
+ ]);
12
+ const JSD_BODY_MARKERS = [
13
+ "window.cloudflare.jsd.executeOnce",
14
+ "cdn-cgi/challenge-platform",
15
+ "cf-jsds",
16
+ ];
17
+ const TURNSTILE_MARKERS = ["cf-turnstile", "turnstile.render", "data-cf-widget"];
18
+ function classifyFromResponse(response) {
19
+ const status = response.status();
20
+ const headers = response.headers();
21
+ const cfRay = headers["cf-ray"] ?? headers["x-cf-ray"];
22
+ const server = headers["server"] ?? "";
23
+ const cacheStatus = headers["cf-cache-status"] ?? "";
24
+ const contentType = headers["content-type"] ?? "";
25
+ // 429 / 503 → rate limit
26
+ if (status === 429 || status === 503) {
27
+ return {
28
+ type: "rate_limit",
29
+ clearanceLevel: "none",
30
+ confidence: 0.95,
31
+ reason: `HTTP ${status} with Retry-After`,
32
+ cfRay,
33
+ cached: cacheStatus === "DYNAMIC",
34
+ };
35
+ }
36
+ // Known blocked status with Cloudflare server header
37
+ if ((status === 403 || status === 400) && /cloudflare/i.test(server)) {
38
+ return {
39
+ type: "managed",
40
+ clearanceLevel: "managed",
41
+ confidence: 0.85,
42
+ reason: `HTTP ${status} from cloudflare server`,
43
+ cfRay,
44
+ cached: false,
45
+ };
46
+ }
47
+ // Challenge page served (interactive / non-interactive / managed)
48
+ if (status === 200 &&
49
+ contentType.includes("text/html") &&
50
+ /server.*cloudflare/i.test(server)) {
51
+ return {
52
+ type: "managed",
53
+ clearanceLevel: "managed",
54
+ confidence: 0.7,
55
+ reason: "Cloudflare server returned HTML (possible challenge page)",
56
+ cfRay,
57
+ cached: cacheStatus === "MISS" || cacheStatus === "EXPIRED",
58
+ };
59
+ }
60
+ return null;
61
+ }
62
+ function classifyFromBody(body, title) {
63
+ const lowerTitle = title.toLowerCase();
64
+ const lowerBody = body.toLowerCase();
65
+ // JSD marker
66
+ for (const marker of JSD_BODY_MARKERS) {
67
+ if (lowerBody.includes(marker)) {
68
+ return {
69
+ type: "jsd",
70
+ clearanceLevel: "js",
71
+ confidence: 0.9,
72
+ reason: "JS Detection script found in response body",
73
+ };
74
+ }
75
+ }
76
+ // Turnstile marker
77
+ for (const marker of TURNSTILE_MARKERS) {
78
+ if (lowerBody.includes(marker)) {
79
+ return {
80
+ type: "turnstile",
81
+ clearanceLevel: "managed",
82
+ confidence: 0.85,
83
+ reason: "Turnstile widget markup found in response body",
84
+ };
85
+ }
86
+ }
87
+ // Title-based classification
88
+ if (CHALLENGE_TITLES.has(lowerTitle.trim())) {
89
+ // Distinguish interactive vs non-interactive by DOM clues
90
+ const hasCheckbox = /checkbox|select-a|choose/i.test(lowerBody);
91
+ const hasButton = /button|continue|proceed/i.test(lowerBody);
92
+ const clearance = hasCheckbox || hasButton ? "high" : "js";
93
+ const type = hasCheckbox || hasButton ? "interactive" : "non_interactive";
94
+ return {
95
+ type,
96
+ clearanceLevel: clearance,
97
+ confidence: 0.95,
98
+ reason: `Challenge title matched: "${lowerTitle.trim()}"`,
99
+ };
100
+ }
101
+ return null;
102
+ }
103
+ const INFO_MAP = new WeakMap();
104
+ const PAGE_INFO = new WeakMap();
105
+ /** Cache the last N challenge infos per page (by page object identity). */
106
+ const PAGE_HIST = new WeakMap();
107
+ export function challengeInfoFor(response) {
108
+ const cached = INFO_MAP.get(response);
109
+ if (cached)
110
+ return cached;
111
+ const info = classifyFromResponse(response) ?? null;
112
+ if (info)
113
+ INFO_MAP.set(response, info);
114
+ return info;
115
+ }
116
+ export function pageChallengeHistory(page) {
117
+ return PAGE_HIST.get(page) ?? [];
118
+ }
119
+ export function appendChallengeInfo(page, info) {
120
+ const hist = PAGE_HIST.get(page) ?? [];
121
+ hist.push(info);
122
+ if (hist.length > 20)
123
+ hist.shift();
124
+ PAGE_HIST.set(page, hist);
125
+ }
126
+ export function latestChallenge(page) {
127
+ const hist = PAGE_HIST.get(page) ?? [];
128
+ return hist.length > 0 ? hist[hist.length - 1] : null;
129
+ }
130
+ export function classifyResponse(response) {
131
+ const fromResp = classifyFromResponse(response);
132
+ if (fromResp)
133
+ return fromResp;
134
+ // Fallback: try to read body for HTML responses
135
+ if (response.headers()["content-type"]?.includes("text/html")) {
136
+ try {
137
+ const body = response.text().then(String).catch(() => "");
138
+ body.then((b) => {
139
+ const fromBody = classifyFromBody(b, "");
140
+ if (fromBody)
141
+ appendChallengeInfo({ id: response.url() }, fromBody);
142
+ });
143
+ }
144
+ catch {
145
+ // ignore
146
+ }
147
+ }
148
+ return {
149
+ type: "none",
150
+ clearanceLevel: "none",
151
+ confidence: 0,
152
+ reason: "No challenge signals detected",
153
+ };
154
+ }
155
+ export function classifyPage(page) {
156
+ return page.title().then((title) => {
157
+ const info = classifyFromBody("", title);
158
+ return info ?? { type: "none", clearanceLevel: "none", confidence: 0, reason: "Title clean" };
159
+ });
160
+ }
161
+ export function challengePlugin() {
162
+ return {
163
+ name: "challenge-classify",
164
+ order: 40,
165
+ onContext(context) {
166
+ context.on("response", (response) => {
167
+ const info = challengeInfoFor(response);
168
+ if (info && info.type !== "none") {
169
+ appendChallengeInfo({ id: response.url() }, info);
170
+ }
171
+ });
172
+ },
173
+ };
174
+ }
@@ -0,0 +1,28 @@
1
+ import type { Browser, BrowserContext, Page } from "playwright-core";
2
+ import type { BexxcvPlugin } from "./types.js";
3
+ /**
4
+ * Extracts and replays Turnstile Ephemeral IDs.
5
+ *
6
+ * Cloudflare's Turnstile assigns an ephemeral_id per session that is sent back
7
+ * in the token payload. When the same widget is solved again (e.g. after a
8
+ * navigation), Cloudflare cross-references this id against the previous solve.
9
+ * Storing and replaying it reduces the chance of a fresh interactive challenge.
10
+ */
11
+ export interface EphemeralOptions {
12
+ /** Max age of a stored ephemeral entry before it is considered stale (ms). Default 10 min. */
13
+ maxAgeMs?: number;
14
+ /** If true, replay the ephemeral_id even if no new turnstile widget appears on next page. */
15
+ autoReplay?: boolean;
16
+ }
17
+ interface EphemeralEntry {
18
+ widgetKey: string;
19
+ ephemeralId: string;
20
+ expiresAt: number;
21
+ }
22
+ export declare function ephemeral(options?: EphemeralOptions): BexxcvPlugin;
23
+ /** Retrieve stored ephemeral entries for a context. */
24
+ export declare function getEphemeralEntries(context: BrowserContext): EphemeralEntry[];
25
+ /** Inject a stored ephemeral_id back into a hidden input on the target page. */
26
+ export declare function replayEphemeral(page: Page, ephemeralId: string): Promise<boolean>;
27
+ export declare function attachEphemeral<T extends Browser | BrowserContext>(target: T, options?: EphemeralOptions): T;
28
+ export {};