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.
@@ -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 {};
@@ -0,0 +1,131 @@
1
+ const CONTEXT_DATA = new WeakMap();
2
+ const PAGE_LAST_URL = new WeakMap();
3
+ const WATCHED = new WeakSet();
4
+ function getContextStore(context) {
5
+ let store = CONTEXT_DATA.get(context);
6
+ if (!store) {
7
+ store = new Map();
8
+ CONTEXT_DATA.set(context, store);
9
+ }
10
+ return store;
11
+ }
12
+ async function extractEphemeralId(page) {
13
+ try {
14
+ const result = await page.evaluate(() => {
15
+ try {
16
+ const w = window;
17
+ const resp = w.turnstile?.getResponse?.();
18
+ if (!resp || resp.length < 20)
19
+ return null;
20
+ // Ephemeral id is embedded as ?ephemeral_id=<hex> inside the response querystring
21
+ const m = resp.match(/ephemeral_id=([A-Za-z0-9_-]+)/);
22
+ return m?.[1] ?? null;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ });
28
+ return result ?? null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ async function readToken(page) {
35
+ return page.evaluate(() => {
36
+ for (const el of Array.from(document.querySelectorAll('[name="cf-turnstile-response"]'))) {
37
+ if (el.value && el.value.length > 20)
38
+ return el.value;
39
+ }
40
+ return null;
41
+ }).catch(() => null);
42
+ }
43
+ export function ephemeral(options = {}) {
44
+ const maxAge = options.maxAgeMs ?? 600_000; // 10 min
45
+ const autoReplay = options.autoReplay ?? false;
46
+ return {
47
+ name: "ephemeral",
48
+ order: 44,
49
+ onContext(context) {
50
+ const store = getContextStore(context);
51
+ // Prune stale entries every minute
52
+ const prune = setInterval(() => {
53
+ const now = Date.now();
54
+ for (const [key, entry] of store.entries()) {
55
+ if (entry.expiresAt < now)
56
+ store.delete(key);
57
+ }
58
+ }, 60_000);
59
+ prune.unref();
60
+ },
61
+ onPage(page) {
62
+ if (WATCHED.has(page))
63
+ return;
64
+ WATCHED.add(page);
65
+ const originalGoto = page.goto.bind(page);
66
+ page.goto = (async (...args) => {
67
+ const url = String(args[0]);
68
+ // Before navigating, try to replay stored ephemeral_id into hidden input
69
+ if (autoReplay) {
70
+ const prev = PAGE_LAST_URL.get(page);
71
+ if (prev && prev !== url) {
72
+ // Different page — clear stale data
73
+ const store = getContextStore(page.context());
74
+ const now = Date.now();
75
+ for (const [key, e] of store.entries()) {
76
+ if (e.expiresAt < now)
77
+ store.delete(key);
78
+ }
79
+ }
80
+ }
81
+ PAGE_LAST_URL.set(page, url);
82
+ return originalGoto(...args);
83
+ });
84
+ // Watch for new tokens and capture ephemeral ids
85
+ page.on("load", async () => {
86
+ try {
87
+ const token = await readToken(page);
88
+ if (!token)
89
+ return;
90
+ const eid = await extractEphemeralId(page);
91
+ if (!eid)
92
+ return;
93
+ const key = `${page.url()}:${eid.slice(0, 8)}`;
94
+ getContextStore(page.context()).set(key, {
95
+ widgetKey: key,
96
+ ephemeralId: eid,
97
+ expiresAt: Date.now() + maxAge,
98
+ });
99
+ }
100
+ catch {
101
+ // ignore
102
+ }
103
+ });
104
+ },
105
+ };
106
+ }
107
+ /** Retrieve stored ephemeral entries for a context. */
108
+ export function getEphemeralEntries(context) {
109
+ const store = CONTEXT_DATA.get(context) ?? new Map();
110
+ return [...store.values()].filter((e) => e.expiresAt > Date.now());
111
+ }
112
+ /** Inject a stored ephemeral_id back into a hidden input on the target page. */
113
+ export async function replayEphemeral(page, ephemeralId) {
114
+ try {
115
+ await page.evaluate((id) => {
116
+ const input = document.querySelector('input[name="cf-turnstile-response"]');
117
+ if (!input)
118
+ return false;
119
+ input.dataset.ephemeralRef = id;
120
+ return true;
121
+ }, ephemeralId);
122
+ return true;
123
+ }
124
+ catch {
125
+ return false;
126
+ }
127
+ }
128
+ export function attachEphemeral(target, options = {}) {
129
+ void ephemeral(options); // side-effect plugin registration handled by applyPlugins
130
+ return target;
131
+ }
@@ -0,0 +1,15 @@
1
+ export { brake, type BrakeOptions } from "./brake.js";
2
+ export { challengePlugin, type ChallengeInfo, type ChallengeType } from "./classify.js";
3
+ export { cocoon } from "./cocoon.js";
4
+ export { dodge, type DodgeOptions } from "./dodge.js";
5
+ export { ephemeral, getEphemeralEntries, replayEphemeral, type EphemeralOptions } from "./ephemeral.js";
6
+ export { gauntlet, type GauntletOptions, type GauntletResult } from "./gauntlet.js";
7
+ export { human, type HumanPluginOptions } from "./human.js";
8
+ export { jsd, isJsdPassed, type JsdOptions } from "./jsd.js";
9
+ export { lens, type LensOptions, type LensReport, type LensCheck } from "./lens.js";
10
+ export { precursor, getPrecursorState, resetPrecursorState, type PrecursorOptions } from "./precursor.js";
11
+ export { stash, type StashOptions } from "./stash.js";
12
+ export { veneer, type VeneerOptions } from "./veneer.js";
13
+ export { wiretap, type WiretapOptions } from "./wiretap.js";
14
+ export { botScore, getBotScores, avgBotScore, hadLowScore, type BotScoreOptions } from "./botscore.js";
15
+ export { stealth, attachStealth, type StealthOptions } from "./stealth.js";
@@ -0,0 +1,16 @@
1
+ // Re-exports for convenience — avoids circular references in index.ts
2
+ export { brake } from "./brake.js";
3
+ export { challengePlugin } from "./classify.js";
4
+ export { cocoon } from "./cocoon.js";
5
+ export { dodge } from "./dodge.js";
6
+ export { ephemeral, getEphemeralEntries, replayEphemeral } from "./ephemeral.js";
7
+ export { gauntlet } from "./gauntlet.js";
8
+ export { human } from "./human.js";
9
+ export { jsd, isJsdPassed } from "./jsd.js";
10
+ export { lens } from "./lens.js";
11
+ export { precursor, getPrecursorState, resetPrecursorState } from "./precursor.js";
12
+ export { stash } from "./stash.js";
13
+ export { veneer } from "./veneer.js";
14
+ export { wiretap } from "./wiretap.js";
15
+ export { botScore, getBotScores, avgBotScore, hadLowScore } from "./botscore.js";
16
+ export { stealth, attachStealth } from "./stealth.js";
@@ -1,13 +1,18 @@
1
- import { brake, type BrakeOptions } from "./brake.js";
2
- import { cocoon } from "./cocoon.js";
3
- import { dodge, type DodgeOptions } from "./dodge.js";
4
- import { gauntlet, type GauntletOptions, type GauntletResult } from "./gauntlet.js";
5
- import { human, type HumanPluginOptions } from "./human.js";
6
- import { lens, type LensOptions, type LensReport, type LensCheck } from "./lens.js";
7
- import { stash, type StashOptions } from "./stash.js";
1
+ import { type BrakeOptions } from "./brake.js";
2
+ import { type ChallengeInfo, type ChallengeType } from "./classify.js";
3
+ import { type DodgeOptions } from "./dodge.js";
4
+ import { type EphemeralOptions } from "./ephemeral.js";
5
+ import { type GauntletOptions, type GauntletResult } from "./gauntlet.js";
6
+ import { type HumanPluginOptions } from "./human.js";
7
+ import { type JsdOptions } from "./jsd.js";
8
+ import { type LensOptions, type LensReport, type LensCheck } from "./lens.js";
9
+ import { type PrecursorOptions } from "./precursor.js";
10
+ import { type StashOptions } from "./stash.js";
8
11
  import type { BexxcvPlugin } from "./types.js";
9
- import { veneer, type VeneerOptions } from "./veneer.js";
10
- import { wiretap, type WiretapOptions } from "./wiretap.js";
12
+ import { type VeneerOptions } from "./veneer.js";
13
+ import { type WiretapOptions } from "./wiretap.js";
14
+ import { type BotScoreOptions } from "./botscore.js";
15
+ import { type StealthOptions } from "./stealth.js";
11
16
  export interface PluginOptions {
12
17
  gauntlet?: boolean | GauntletOptions;
13
18
  wiretap?: boolean | WiretapOptions;
@@ -19,14 +24,25 @@ export interface PluginOptions {
19
24
  lens?: boolean | LensOptions;
20
25
  human?: boolean | HumanPluginOptions;
21
26
  plugins?: BexxcvPlugin[];
27
+ /** Enable Cloudflare challenge classification (challenge-classify). Default true. */
28
+ classify?: boolean;
29
+ /** Enable JS Detection handling (jsd). Requires gauntlet: true. Default true. */
30
+ jsd?: boolean | JsdOptions;
31
+ /** Enable Turnstile ephemeral ID tracking (ephemeral). Default true. */
32
+ ephemeral?: boolean | EphemeralOptions;
33
+ /** Enable Precursor cookie drift detection (precursor). Default true. */
34
+ precursor?: boolean | PrecursorOptions;
35
+ /** Enable Bot Management score monitoring (bot-score-monitor). Default false. */
36
+ botScore?: boolean | BotScoreOptions;
37
+ /** Enable automation marker spoofing (stealth). Default false. */
38
+ stealth?: boolean | StealthOptions;
22
39
  }
23
- export declare const PLUGIN_KEYS: readonly ["gauntlet", "wiretap", "stash", "veneer", "brake", "dodge", "cocoon", "lens", "human", "plugins"];
40
+ export declare const PLUGIN_KEYS: readonly ["gauntlet", "wiretap", "stash", "veneer", "brake", "dodge", "cocoon", "gauntlet", "lens", "human", "plugins", "classify", "jsd", "ephemeral", "precursor", "botScore", "stealth"];
24
41
  export declare function buildPlugins(options: PluginOptions): BexxcvPlugin[];
25
42
  export declare function stripPluginOptions<T extends Record<string, unknown>>(options: T): T;
26
43
  export { applyPlugins, runBeforeLaunch, type BexxcvPlugin } from "./types.js";
27
44
  export { auditFingerprint, lensReport } from "./lens.js";
28
45
  export { gauntletResult, runGauntlet } from "./gauntlet.js";
29
46
  export { wiretapEntries } from "./wiretap.js";
30
- export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap };
31
- export { turnstile, uam } from "./solvers.js";
32
- export type { HumanPluginOptions, BrakeOptions, DodgeOptions, GauntletOptions, GauntletResult, LensOptions, LensReport, LensCheck, StashOptions, VeneerOptions, WiretapOptions, };
47
+ export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap, challengePlugin, jsd, ephemeral, precursor, botScore, stealth, attachStealth, getEphemeralEntries, replayEphemeral, isJsdPassed, getPrecursorState, resetPrecursorState, getBotScores, avgBotScore, hadLowScore } from "./index-reexports.js";
48
+ export type { HumanPluginOptions, BrakeOptions, DodgeOptions, GauntletOptions, GauntletResult, LensOptions, LensReport, LensCheck, StashOptions, VeneerOptions, WiretapOptions, ChallengeInfo, ChallengeType, JsdOptions, EphemeralOptions, PrecursorOptions, BotScoreOptions, };
@@ -1,12 +1,18 @@
1
1
  import { brake } from "./brake.js";
2
+ import { challengePlugin } from "./classify.js";
2
3
  import { cocoon } from "./cocoon.js";
3
4
  import { dodge } from "./dodge.js";
5
+ import { ephemeral } from "./ephemeral.js";
4
6
  import { gauntlet } from "./gauntlet.js";
5
7
  import { human } from "./human.js";
8
+ import { jsd } from "./jsd.js";
6
9
  import { lens } from "./lens.js";
10
+ import { precursor } from "./precursor.js";
7
11
  import { stash } from "./stash.js";
8
12
  import { veneer } from "./veneer.js";
9
13
  import { wiretap } from "./wiretap.js";
14
+ import { botScore } from "./botscore.js";
15
+ import { stealth } from "./stealth.js";
10
16
  export const PLUGIN_KEYS = [
11
17
  "gauntlet",
12
18
  "wiretap",
@@ -15,15 +21,23 @@ export const PLUGIN_KEYS = [
15
21
  "brake",
16
22
  "dodge",
17
23
  "cocoon",
24
+ "gauntlet",
18
25
  "lens",
19
26
  "human",
20
27
  "plugins",
28
+ "classify",
29
+ "jsd",
30
+ "ephemeral",
31
+ "precursor",
32
+ "botScore",
33
+ "stealth",
21
34
  ];
22
35
  function opts(value) {
23
36
  return value === true ? {} : value;
24
37
  }
25
38
  export function buildPlugins(options) {
26
39
  const list = [];
40
+ // Core protection plugins — order matters
27
41
  if (options.dodge)
28
42
  list.push(dodge(options.dodge));
29
43
  if (options.cocoon)
@@ -31,18 +45,30 @@ export function buildPlugins(options) {
31
45
  if (options.stash) {
32
46
  list.push(stash(typeof options.stash === "string" ? { file: options.stash } : options.stash));
33
47
  }
34
- if (options.wiretap)
35
- list.push(wiretap(opts(options.wiretap)));
36
48
  if (options.veneer)
37
49
  list.push(veneer(opts(options.veneer)));
38
- if (options.lens)
39
- list.push(lens(opts(options.lens)));
50
+ if (options.classify !== false)
51
+ list.push(challengePlugin());
52
+ if (options.precursor !== false)
53
+ list.push(precursor(typeof options.precursor === "object" ? options.precursor : {}));
54
+ if (options.botScore)
55
+ list.push(botScore(typeof options.botScore === "object" ? options.botScore : {}));
56
+ if (options.jsd !== false)
57
+ list.push(jsd(typeof options.jsd === "object" ? options.jsd : {}));
58
+ if (options.stealth)
59
+ list.push(stealth(typeof options.stealth === "object" ? options.stealth : {}));
60
+ if (options.ephemeral !== false)
61
+ list.push(ephemeral(typeof options.ephemeral === "object" ? options.ephemeral : {}));
40
62
  if (options.gauntlet)
41
63
  list.push(gauntlet(opts(options.gauntlet)));
42
64
  if (options.human)
43
65
  list.push(human(opts(options.human)));
44
66
  if (options.brake)
45
67
  list.push(brake(opts(options.brake)));
68
+ if (options.lens)
69
+ list.push(lens(opts(options.lens)));
70
+ if (options.wiretap)
71
+ list.push(wiretap(opts(options.wiretap)));
46
72
  if (options.plugins)
47
73
  list.push(...options.plugins);
48
74
  return list;
@@ -57,5 +83,4 @@ export { applyPlugins, runBeforeLaunch } from "./types.js";
57
83
  export { auditFingerprint, lensReport } from "./lens.js";
58
84
  export { gauntletResult, runGauntlet } from "./gauntlet.js";
59
85
  export { wiretapEntries } from "./wiretap.js";
60
- export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap };
61
- export { turnstile, uam } from "./solvers.js";
86
+ export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap, challengePlugin, jsd, ephemeral, precursor, botScore, stealth, attachStealth, getEphemeralEntries, replayEphemeral, isJsdPassed, getPrecursorState, resetPrecursorState, getBotScores, avgBotScore, hadLowScore } from "./index-reexports.js";
@@ -0,0 +1,23 @@
1
+ import type { Page } from "playwright-core";
2
+ import type { BexxcvPlugin } from "./types.js";
3
+ /**
4
+ * Handles Cloudflare JavaScript Detection (JSD) challenges.
5
+ *
6
+ * When JS Detections is enabled, Cloudflare injects a script that calls
7
+ * `window.cloudflare.jsd.executeOnce({ callback(result) {} })`. The result
8
+ * must be `"success"` for the challenge to pass. This plugin:
9
+ * 1. Injects a safe wrapper via addInitScript before any page load
10
+ * 2. Polls for the JSD callback to fire
11
+ * 3. Waits until cf_clearance appears (JSD completion signal)
12
+ */
13
+ export interface JsdOptions {
14
+ /** Timeout for waiting for JSD completion after navigation (ms). Default 15 s. */
15
+ timeout?: number;
16
+ /** Poll interval while waiting for the JSD result (ms). Default 500. */
17
+ interval?: number;
18
+ }
19
+ export declare function jsd(options?: JsdOptions): BexxcvPlugin;
20
+ /** Check whether the current page has passed its JSD challenge. */
21
+ export declare function isJsdPassed(page: Page): Promise<boolean>;
22
+ /** Attach JSD handling to an existing browser or context. */
23
+ export declare function attachJsd<T extends import("playwright-core").Browser | import("playwright-core").BrowserContext>(target: T, _options?: JsdOptions): T;
@@ -0,0 +1,141 @@
1
+ import { sleep } from "../random.js";
2
+ const JSD_READY = new WeakSet();
3
+ const WATCHED = new WeakSet();
4
+ async function isJsdPage(page) {
5
+ try {
6
+ const title = (await page.title().catch(() => "")).toLowerCase();
7
+ if (title.includes("just a moment") || title.includes("attention required")) {
8
+ return true;
9
+ }
10
+ const hasJsd = await page.evaluate(() => {
11
+ try {
12
+ const w = window;
13
+ if (!w?.cloudflare?.jsd)
14
+ return false;
15
+ // If it's our fallback (bexxcv), not a real CF challenge
16
+ if (w.cloudflare.jsd._bexxcv)
17
+ return false;
18
+ // Real CF JSD has state "pending" or a registered executeOnce
19
+ return w.cloudflare.jsd.state === "pending" || typeof w.cloudflare.jsd.executeOnce === "function";
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }).catch(() => false);
25
+ return hasJsd;
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ async function waitForJsdCompletion(page, options) {
32
+ const timeout = options.timeout ?? 15_000;
33
+ const interval = options.interval ?? 500;
34
+ const start = Date.now();
35
+ while (Date.now() - start < timeout && !page.isClosed()) {
36
+ try {
37
+ const passed = await page.evaluate(() => {
38
+ try {
39
+ const w = window;
40
+ if (!w?.cloudflare?.jsd?.state)
41
+ return null;
42
+ return w.cloudflare.jsd.state === "passed" ? true : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }).catch(() => null);
48
+ if (passed === true) {
49
+ return { passed: true };
50
+ }
51
+ // Also check if cf_clearance appeared (indicates JSD completed externally)
52
+ const cookies = await page.context().cookies(page.url()).catch(() => []);
53
+ if (cookies.some((c) => c.name === "cf_clearance")) {
54
+ return { passed: true };
55
+ }
56
+ }
57
+ catch {
58
+ // ignore evaluation errors
59
+ }
60
+ await sleep(interval);
61
+ }
62
+ return { passed: false };
63
+ }
64
+ export function jsd(options = {}) {
65
+ const timeout = options.timeout ?? 15_000;
66
+ const interval = options.interval ?? 500;
67
+ return {
68
+ name: "jsd",
69
+ order: 43,
70
+ onPage(page) {
71
+ if (WATCHED.has(page))
72
+ return;
73
+ WATCHED.add(page);
74
+ // Inject a fallback cloudflare.jsd namespace so page JS doesn't crash
75
+ void page.addInitScript(() => {
76
+ if (typeof window === "undefined")
77
+ return;
78
+ const w = window;
79
+ if (!w.cloudflare)
80
+ w.cloudflare = {};
81
+ const cf = w.cloudflare;
82
+ if (!cf.jsd) {
83
+ cf.jsd = {
84
+ state: "pending",
85
+ executeOnce(_opts = {}) { },
86
+ _bexxcv: true,
87
+ };
88
+ }
89
+ const _jsd = cf.jsd;
90
+ _jsd &&
91
+ Object.assign(cf.jsd, {
92
+ executeOnce: function (opts = {}) {
93
+ if (opts.callback) {
94
+ setTimeout(() => opts.callback("success"), 0);
95
+ }
96
+ return { then: (cb) => setTimeout(cb, 0) };
97
+ },
98
+ });
99
+ });
100
+ const originalGoto = page.goto.bind(page);
101
+ page.goto = (async (...args) => {
102
+ JSD_READY.delete(page);
103
+ const response = await originalGoto(...args);
104
+ // If we landed on a JSD page, wait for it to complete
105
+ const challenging = await isJsdPage(page).catch(() => false);
106
+ if (challenging) {
107
+ const result = await waitForJsdCompletion(page, { timeout, interval }).catch(() => ({ passed: false }));
108
+ if (result.passed) {
109
+ JSD_READY.add(page);
110
+ }
111
+ else {
112
+ console.warn(`[bexxcv] jsd: challenge did not complete within ${timeout}ms`);
113
+ }
114
+ }
115
+ return response;
116
+ });
117
+ },
118
+ };
119
+ }
120
+ /** Check whether the current page has passed its JSD challenge. */
121
+ export async function isJsdPassed(page) {
122
+ if (JSD_READY.has(page))
123
+ return true;
124
+ const passed = await page.evaluate(() => {
125
+ try {
126
+ const w = window;
127
+ return w?.cloudflare?.jsd?.state === "passed";
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }).catch(() => false);
133
+ if (passed)
134
+ JSD_READY.add(page);
135
+ return passed;
136
+ }
137
+ /** Attach JSD handling to an existing browser or context. */
138
+ export function attachJsd(target, _options = {}) {
139
+ void jsd(_options);
140
+ return target;
141
+ }