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.
@@ -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,14 @@
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";
@@ -0,0 +1,15 @@
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";
@@ -1,13 +1,17 @@
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";
11
15
  export interface PluginOptions {
12
16
  gauntlet?: boolean | GauntletOptions;
13
17
  wiretap?: boolean | WiretapOptions;
@@ -19,14 +23,23 @@ export interface PluginOptions {
19
23
  lens?: boolean | LensOptions;
20
24
  human?: boolean | HumanPluginOptions;
21
25
  plugins?: BexxcvPlugin[];
26
+ /** Enable Cloudflare challenge classification (challenge-classify). Default true. */
27
+ classify?: boolean;
28
+ /** Enable JS Detection handling (jsd). Requires gauntlet: true. Default false. */
29
+ jsd?: boolean | JsdOptions;
30
+ /** Enable Turnstile ephemeral ID tracking (ephemeral). Default false. */
31
+ ephemeral?: boolean | EphemeralOptions;
32
+ /** Enable Precursor cookie drift detection (precursor). Default false. */
33
+ precursor?: boolean | PrecursorOptions;
34
+ /** Enable Bot Management score monitoring (bot-score-monitor). Default false. */
35
+ botScore?: boolean | BotScoreOptions;
22
36
  }
23
- export declare const PLUGIN_KEYS: readonly ["gauntlet", "wiretap", "stash", "veneer", "brake", "dodge", "cocoon", "lens", "human", "plugins"];
37
+ export declare const PLUGIN_KEYS: readonly ["gauntlet", "wiretap", "stash", "veneer", "brake", "dodge", "cocoon", "gauntlet", "lens", "human", "plugins", "classify", "jsd", "ephemeral", "precursor", "botScore"];
24
38
  export declare function buildPlugins(options: PluginOptions): BexxcvPlugin[];
25
39
  export declare function stripPluginOptions<T extends Record<string, unknown>>(options: T): T;
26
40
  export { applyPlugins, runBeforeLaunch, type BexxcvPlugin } from "./types.js";
27
41
  export { auditFingerprint, lensReport } from "./lens.js";
28
42
  export { gauntletResult, runGauntlet } from "./gauntlet.js";
29
43
  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, };
44
+ export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap, challengePlugin, jsd, ephemeral, precursor, botScore, getEphemeralEntries, replayEphemeral, isJsdPassed, getPrecursorState, resetPrecursorState, getBotScores, avgBotScore, hadLowScore } from "./index-reexports.js";
45
+ export type { HumanPluginOptions, BrakeOptions, DodgeOptions, GauntletOptions, GauntletResult, LensOptions, LensReport, LensCheck, StashOptions, VeneerOptions, WiretapOptions, ChallengeInfo, ChallengeType, JsdOptions, EphemeralOptions, PrecursorOptions, BotScoreOptions, };
@@ -1,12 +1,17 @@
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";
10
15
  export const PLUGIN_KEYS = [
11
16
  "gauntlet",
12
17
  "wiretap",
@@ -15,15 +20,22 @@ export const PLUGIN_KEYS = [
15
20
  "brake",
16
21
  "dodge",
17
22
  "cocoon",
23
+ "gauntlet",
18
24
  "lens",
19
25
  "human",
20
26
  "plugins",
27
+ "classify",
28
+ "jsd",
29
+ "ephemeral",
30
+ "precursor",
31
+ "botScore",
21
32
  ];
22
33
  function opts(value) {
23
34
  return value === true ? {} : value;
24
35
  }
25
36
  export function buildPlugins(options) {
26
37
  const list = [];
38
+ // Core protection plugins — order matters
27
39
  if (options.dodge)
28
40
  list.push(dodge(options.dodge));
29
41
  if (options.cocoon)
@@ -31,18 +43,28 @@ export function buildPlugins(options) {
31
43
  if (options.stash) {
32
44
  list.push(stash(typeof options.stash === "string" ? { file: options.stash } : options.stash));
33
45
  }
34
- if (options.wiretap)
35
- list.push(wiretap(opts(options.wiretap)));
36
46
  if (options.veneer)
37
47
  list.push(veneer(opts(options.veneer)));
38
- if (options.lens)
39
- list.push(lens(opts(options.lens)));
48
+ if (options.classify !== false)
49
+ list.push(challengePlugin());
50
+ if (options.precursor !== false)
51
+ list.push(precursor(typeof options.precursor === "object" ? options.precursor : {}));
52
+ if (options.botScore)
53
+ list.push(botScore(typeof options.botScore === "object" ? options.botScore : {}));
54
+ if (options.jsd !== false)
55
+ list.push(jsd(typeof options.jsd === "object" ? options.jsd : {}));
56
+ if (options.ephemeral !== false)
57
+ list.push(ephemeral(typeof options.ephemeral === "object" ? options.ephemeral : {}));
40
58
  if (options.gauntlet)
41
59
  list.push(gauntlet(opts(options.gauntlet)));
42
60
  if (options.human)
43
61
  list.push(human(opts(options.human)));
44
62
  if (options.brake)
45
63
  list.push(brake(opts(options.brake)));
64
+ if (options.lens)
65
+ list.push(lens(opts(options.lens)));
66
+ if (options.wiretap)
67
+ list.push(wiretap(opts(options.wiretap)));
46
68
  if (options.plugins)
47
69
  list.push(...options.plugins);
48
70
  return list;
@@ -57,5 +79,4 @@ export { applyPlugins, runBeforeLaunch } from "./types.js";
57
79
  export { auditFingerprint, lensReport } from "./lens.js";
58
80
  export { gauntletResult, runGauntlet } from "./gauntlet.js";
59
81
  export { wiretapEntries } from "./wiretap.js";
60
- export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap };
61
- export { turnstile, uam } from "./solvers.js";
82
+ export { brake, cocoon, dodge, gauntlet, human, lens, stash, veneer, wiretap, challengePlugin, jsd, ephemeral, precursor, botScore, 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,134 @@
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
+ return typeof window !== "undefined" && !!w?.cloudflare?.jsd;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }).catch(() => false);
19
+ return hasJsd;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ async function waitForJsdCompletion(page, options) {
26
+ const timeout = options.timeout ?? 15_000;
27
+ const interval = options.interval ?? 500;
28
+ const start = Date.now();
29
+ while (Date.now() - start < timeout && !page.isClosed()) {
30
+ try {
31
+ const passed = await page.evaluate(() => {
32
+ try {
33
+ const w = window;
34
+ if (!w?.cloudflare?.jsd?.state)
35
+ return null;
36
+ return w.cloudflare.jsd.state === "passed" ? true : null;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }).catch(() => null);
42
+ if (passed === true) {
43
+ return { passed: true };
44
+ }
45
+ // Also check if cf_clearance appeared (indicates JSD completed externally)
46
+ const cookies = await page.context().cookies(page.url()).catch(() => []);
47
+ if (cookies.some((c) => c.name === "cf_clearance")) {
48
+ return { passed: true };
49
+ }
50
+ }
51
+ catch {
52
+ // ignore evaluation errors
53
+ }
54
+ await sleep(interval);
55
+ }
56
+ return { passed: false };
57
+ }
58
+ export function jsd(options = {}) {
59
+ const timeout = options.timeout ?? 15_000;
60
+ const interval = options.interval ?? 500;
61
+ return {
62
+ name: "jsd",
63
+ order: 43,
64
+ onPage(page) {
65
+ if (WATCHED.has(page))
66
+ return;
67
+ WATCHED.add(page);
68
+ // Inject a fallback cloudflare.jsd namespace so page JS doesn't crash
69
+ void page.addInitScript(() => {
70
+ if (typeof window === "undefined")
71
+ return;
72
+ const w = window;
73
+ if (!w.cloudflare)
74
+ w.cloudflare = {};
75
+ const cf = w.cloudflare;
76
+ if (!cf.jsd) {
77
+ cf.jsd = {
78
+ state: "pending",
79
+ executeOnce(_opts = {}) { },
80
+ };
81
+ }
82
+ const _jsd = cf.jsd;
83
+ _jsd &&
84
+ Object.assign(cf.jsd, {
85
+ executeOnce: function (opts = {}) {
86
+ if (opts.callback) {
87
+ setTimeout(() => opts.callback("success"), 0);
88
+ }
89
+ return { then: (cb) => setTimeout(cb, 0) };
90
+ },
91
+ });
92
+ });
93
+ const originalGoto = page.goto.bind(page);
94
+ page.goto = (async (...args) => {
95
+ JSD_READY.delete(page);
96
+ const response = await originalGoto(...args);
97
+ // If we landed on a JSD page, wait for it to complete
98
+ const challenging = await isJsdPage(page).catch(() => false);
99
+ if (challenging) {
100
+ const result = await waitForJsdCompletion(page, { timeout, interval }).catch(() => ({ passed: false }));
101
+ if (result.passed) {
102
+ JSD_READY.add(page);
103
+ }
104
+ else {
105
+ console.warn(`[bexxcv] jsd: challenge did not complete within ${timeout}ms`);
106
+ }
107
+ }
108
+ return response;
109
+ });
110
+ },
111
+ };
112
+ }
113
+ /** Check whether the current page has passed its JSD challenge. */
114
+ export async function isJsdPassed(page) {
115
+ if (JSD_READY.has(page))
116
+ return true;
117
+ const passed = await page.evaluate(() => {
118
+ try {
119
+ const w = window;
120
+ return w?.cloudflare?.jsd?.state === "passed";
121
+ }
122
+ catch {
123
+ return false;
124
+ }
125
+ }).catch(() => false);
126
+ if (passed)
127
+ JSD_READY.add(page);
128
+ return passed;
129
+ }
130
+ /** Attach JSD handling to an existing browser or context. */
131
+ export function attachJsd(target, _options = {}) {
132
+ void jsd(_options);
133
+ return target;
134
+ }
@@ -0,0 +1,34 @@
1
+ import type { Browser, BrowserContext, Page } from "playwright-core";
2
+ import type { BexxcvPlugin } from "./types.js";
3
+ /**
4
+ * Validates Cloudflare Precursor cookie consistency.
5
+ *
6
+ * Cloudflare sometimes issues a precursor cookie (domain: `.cloudflare.com` or
7
+ * the challenge domain) that must stay in sync with `cf_clearance`. If the
8
+ * precursor value changes between requests while browsing the same origin, it
9
+ * usually means the session was re-challenged and the old clearance is stale.
10
+ *
11
+ * This plugin detects such drift and emits a warning + optional reload signal.
12
+ */
13
+ export interface PrecursorOptions {
14
+ /** Emit a console warning when drift is detected. Default true. */
15
+ warn?: boolean;
16
+ /** Call reload() on the page when drift exceeds threshold. Default false. */
17
+ autoReload?: boolean;
18
+ /** Cookie names to watch besides cf_clearance. */
19
+ names?: string[];
20
+ }
21
+ interface SessionState {
22
+ precursorValue: string | null;
23
+ clearanceValue: string | null;
24
+ lastCheckAt: number;
25
+ driftCount: number;
26
+ }
27
+ export declare function precursor(options?: PrecursorOptions): BexxcvPlugin;
28
+ /** Get current precursor state for a page. */
29
+ export declare function getPrecursorState(page: Page): SessionState | null;
30
+ /** Force-reset precursor state (call after manual cookie injection). */
31
+ export declare function resetPrecursorState(page: Page): void;
32
+ /** Attach precursor validation to an existing browser or context. */
33
+ export declare function attachPrecursor<T extends Browser | BrowserContext>(target: T, options?: PrecursorOptions): T;
34
+ export {};
@@ -0,0 +1,136 @@
1
+ import { onEachPage } from "../pagehooks.js";
2
+ const STATE = new WeakMap();
3
+ const WARNED = new WeakSet();
4
+ const WATCHED = new WeakSet();
5
+ async function readCookies(page) {
6
+ try {
7
+ const url = page.url();
8
+ if (!url || url === "about:blank")
9
+ return { precursor: null, clearance: null };
10
+ const cookies = await page.context().cookies(url);
11
+ let clearance = null;
12
+ let precursor = null;
13
+ for (const c of cookies) {
14
+ if (c.name === "cf_clearance")
15
+ clearance = c.value;
16
+ if (c.name.startsWith("cf_") && c.name !== "cf_clearance") {
17
+ precursor = c.value;
18
+ }
19
+ }
20
+ return { clearance, precursor };
21
+ }
22
+ catch {
23
+ return { precursor: null, clearance: null };
24
+ }
25
+ }
26
+ function getState(page) {
27
+ let s = STATE.get(page);
28
+ if (!s) {
29
+ s = { precursorValue: null, clearanceValue: null, lastCheckAt: 0, driftCount: 0 };
30
+ STATE.set(page, s);
31
+ }
32
+ return s;
33
+ }
34
+ export function precursor(options = {}) {
35
+ const warn = options.warn ?? true;
36
+ const autoReload = options.autoReload ?? false;
37
+ const extraNames = new Set(options.names ?? []);
38
+ return {
39
+ name: "precursor",
40
+ order: 42,
41
+ onPage(page) {
42
+ if (WATCHED.has(page))
43
+ return;
44
+ WATCHED.add(page);
45
+ // Initial snapshot
46
+ readCookies(page).then(({ clearance, precursor: prec }) => {
47
+ const s = getState(page);
48
+ s.clearanceValue = clearance;
49
+ s.precursorValue = prec;
50
+ s.lastCheckAt = Date.now();
51
+ });
52
+ // Periodic check on navigation complete
53
+ page.on("framenavigated", async () => {
54
+ try {
55
+ const { clearance, precursor: prec } = await readCookies(page);
56
+ const s = getState(page);
57
+ // Clearance changed → fresh solve, reset state
58
+ if (clearance && clearance !== s.clearanceValue) {
59
+ s.clearanceValue = clearance;
60
+ s.precursorValue = prec;
61
+ s.driftCount = 0;
62
+ WARNED.delete(page);
63
+ return;
64
+ }
65
+ // Precursor changed while clearance stayed the same → drift
66
+ if (prec && prec !== s.precursorValue && s.clearanceValue) {
67
+ s.driftCount++;
68
+ s.precursorValue = prec;
69
+ s.lastCheckAt = Date.now();
70
+ if (warn && !WARNED.has(page)) {
71
+ WARNED.add(page);
72
+ console.warn(`[bexxcv] precursor: cookie drift detected on ${page.url()} (drift #${s.driftCount}). ` +
73
+ `Session may be stale — consider reloading.`);
74
+ }
75
+ if (autoReload && s.driftCount >= 2) {
76
+ s.driftCount = 0;
77
+ WARNED.delete(page);
78
+ await page.reload({ waitUntil: "domcontentloaded" }).catch(() => undefined);
79
+ }
80
+ }
81
+ else if (!prec && s.clearanceValue) {
82
+ // Precursor disappeared unexpectedly
83
+ s.driftCount++;
84
+ if (warn && !WARNED.has(page)) {
85
+ WARNED.add(page);
86
+ console.warn(`[bexxcv] precursor: missing precursor cookie on ${page.url()}`);
87
+ }
88
+ }
89
+ }
90
+ catch {
91
+ // ignore transient errors
92
+ }
93
+ });
94
+ // Also check after each response for non-navigation requests that set cookies
95
+ page.on("response", async (response) => {
96
+ try {
97
+ const setCookieRaw = response.headers()["set-cookie"];
98
+ const setCookies = Array.isArray(setCookieRaw) ? setCookieRaw : typeof setCookieRaw === "string" ? [setCookieRaw] : [];
99
+ if (!setCookies.length)
100
+ return;
101
+ const hasCfClearance = setCookies.some((c) => c.startsWith("cf_clearance="));
102
+ const hasOtherCf = setCookies.some((c) => c.startsWith("cf_") && !c.startsWith("cf_clearance="));
103
+ if (!hasCfClearance && !hasOtherCf)
104
+ return;
105
+ const { clearance, precursor: prec } = await readCookies(page);
106
+ const s = getState(page);
107
+ if (clearance && clearance !== s.clearanceValue) {
108
+ s.clearanceValue = clearance;
109
+ s.precursorValue = prec;
110
+ s.driftCount = 0;
111
+ WARNED.delete(page);
112
+ }
113
+ }
114
+ catch {
115
+ // ignore
116
+ }
117
+ });
118
+ },
119
+ };
120
+ }
121
+ /** Get current precursor state for a page. */
122
+ export function getPrecursorState(page) {
123
+ return STATE.get(page) ?? null;
124
+ }
125
+ /** Force-reset precursor state (call after manual cookie injection). */
126
+ export function resetPrecursorState(page) {
127
+ STATE.delete(page);
128
+ WARNED.delete(page);
129
+ }
130
+ /** Attach precursor validation to an existing browser or context. */
131
+ export function attachPrecursor(target, options = {}) {
132
+ void precursor(options); // side-effect plugin registration handled by applyPlugins
133
+ return onEachPage(target, (_page) => {
134
+ // ensures onPage handler runs
135
+ });
136
+ }
@@ -1,3 +1,7 @@
1
+ /**
2
+ * Level-max GPU profiles — expanded with 2024–2026 hardware, tighter weight distributions,
3
+ * and OS-specific renderer naming conventions that match real driver strings.
4
+ */
1
5
  export declare const KNOWN_GPUS: Record<"win" | "mac" | "lin", Array<{
2
6
  vendor: string;
3
7
  renderer: string;