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.
@@ -48,6 +48,65 @@ export async function auditFingerprint(page) {
48
48
  mediaDevices = null;
49
49
  }
50
50
  const nav = navigator;
51
+ // AudioContext sampling
52
+ let audioSampleRate = null;
53
+ let audioLatency = null;
54
+ try {
55
+ const ac = new (window.AudioContext || window.webkitAudioContext)();
56
+ audioSampleRate = ac.sampleRate;
57
+ audioLatency = typeof ac.outputLatency === "number" ? ac.outputLatency : null;
58
+ ac.close();
59
+ }
60
+ catch {
61
+ audioSampleRate = null;
62
+ }
63
+ // Font enumeration
64
+ let fontCount = null;
65
+ let fontLoadError = null;
66
+ try {
67
+ await document.fonts.ready;
68
+ fontCount = document.fonts.size;
69
+ }
70
+ catch {
71
+ fontLoadError = true;
72
+ fontCount = null;
73
+ }
74
+ // WebGL shader precision
75
+ let webglPrecisionHighpFloat = null;
76
+ let webglPrecisionLowpFloat = null;
77
+ try {
78
+ const canvas2 = document.createElement("canvas");
79
+ const gl2 = canvas2.getContext("webgl");
80
+ if (gl2) {
81
+ const fmt = gl2.getShaderPrecisionFormat(WebGLRenderingContext.FRAGMENT_SHADER, WebGLRenderingContext.HIGH_FLOAT);
82
+ if (fmt)
83
+ webglPrecisionHighpFloat = fmt.precision;
84
+ const fmtLow = gl2.getShaderPrecisionFormat(WebGLRenderingContext.FRAGMENT_SHADER, WebGLRenderingContext.LOW_FLOAT);
85
+ if (fmtLow)
86
+ webglPrecisionLowpFloat = fmtLow.precision;
87
+ }
88
+ }
89
+ catch {
90
+ // WebGL unavailable — non-fatal
91
+ }
92
+ // Client Hints (userAgentData)
93
+ const uad = navigator.userAgentData;
94
+ let userAgentDataPlatform = null;
95
+ let clientHintsMobile = null;
96
+ if (uad && typeof uad.getHighEntropyValues === "function") {
97
+ try {
98
+ const hints = await uad.getHighEntropyValues(["platform", "mobile"]);
99
+ userAgentDataPlatform = hints.platform ?? null;
100
+ clientHintsMobile = hints.mobile ?? null;
101
+ }
102
+ catch {
103
+ // Permission denied or not available
104
+ }
105
+ }
106
+ else if (uad && uad.platform) {
107
+ userAgentDataPlatform = String(uad.platform);
108
+ clientHintsMobile = Boolean(uad.mobile);
109
+ }
51
110
  return {
52
111
  ua: navigator.userAgent,
53
112
  platform: navigator.platform,
@@ -74,6 +133,14 @@ export async function auditFingerprint(page) {
74
133
  visible: document.visibilityState === "visible",
75
134
  mediaDevices,
76
135
  mediaTimeout,
136
+ audioSampleRate,
137
+ audioLatency,
138
+ fontCount,
139
+ fontLoadError,
140
+ webglPrecisionHighpFloat,
141
+ webglPrecisionLowpFloat,
142
+ userAgentDataPlatform,
143
+ clientHintsMobile,
77
144
  };
78
145
  });
79
146
  const checks = [];
@@ -101,6 +168,16 @@ export async function auditFingerprint(page) {
101
168
  add("media-devices", (probe.mediaDevices === null || probe.mediaDevices > 0), probe.mediaTimeout
102
169
  ? "enumerateDevices timeout (headless fallback, non-fatal)"
103
170
  : `${probe.mediaDevices} media devices`);
171
+ // --- Audio Context sample rate ---
172
+ add("audio-sample-rate", probe.audioSampleRate !== null && (probe.audioSampleRate === 44100 || probe.audioSampleRate === 48000), `AudioContext sampleRate ${probe.audioSampleRate ?? "unavailable"} (expected 44100 or 48000)`);
173
+ // --- Font enumeration ---
174
+ add("fonts-enumerated", probe.fontCount !== null && probe.fontCount > 0 && !probe.fontLoadError, `${probe.fontCount ?? "unknown"} fonts available${probe.fontLoadError ? " (load error)" : ""}`);
175
+ // --- WebGL shader precision (desktop GPUs should report highp float precision >= 23) ---
176
+ add("webgl-shader-precision", probe.webglPrecisionHighpFloat !== null && probe.webglPrecisionHighpFloat >= 23, `highp float precision ${probe.webglPrecisionHighpFloat ?? "unknown"} (expected ≥23 on desktop GPU)`);
177
+ // --- Client Hints platform consistency ---
178
+ // Firefox must NOT expose userAgentData; when it does, platform must match navigator.platform
179
+ add("client-hints-platform", !firefox || probe.userAgentDataPlatform === null ||
180
+ probe.userAgentDataPlatform === probe.platform.toLowerCase().replace("winnt", "windows").replace("macintosh", "mac"), `userAgentData.platform "${probe.userAgentDataPlatform ?? "absent"}" vs navigator.platform "${probe.platform}"`);
104
181
  const passed = checks.filter((check) => check.ok).length;
105
182
  return { score: Math.round((passed / checks.length) * 100), checks };
106
183
  }
@@ -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,6 +1,8 @@
1
1
  import type { Browser, BrowserContext, Page } from "playwright-core";
2
2
  export interface TurnstileOptions {
3
+ /** Polling interval for checking widget state (ms). */
3
4
  interval?: number;
5
+ /** Minimum time between repeated clicks on the same widget (ms). */
4
6
  retryAfter?: number;
5
7
  }
6
8
  export interface Widget {
package/dist/turnstile.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { onEachPage } from "./pagehooks.js";
2
2
  import { between, sleep } from "./random.js";
3
3
  const WATCHED = new WeakSet();
4
+ // --- Widget discovery --------------------------------------------------------
4
5
  export async function findWidgets(page) {
5
6
  return page.evaluate(() => {
6
7
  const out = [];
@@ -19,12 +20,14 @@ export async function findWidgets(page) {
19
20
  seen.add(key);
20
21
  out.push({ x: rect.x, y: rect.y, w: rect.width, h: rect.height, solved, key });
21
22
  };
23
+ // 1. Implicit rendering: hidden input with the token
22
24
  for (const input of Array.from(document.querySelectorAll('[name="cf-turnstile-response"]'))) {
23
25
  const parent = input.parentElement;
24
26
  if (!parent)
25
27
  continue;
26
- push(parent, !!input.value && input.value.length > 10);
28
+ push(parent, !!(input.value && input.value.length > 20));
27
29
  }
30
+ // 2. Fallback: bare widget box heuristic (width ~300px, empty, compact)
28
31
  if (out.length === 0) {
29
32
  for (const strict of [true, false]) {
30
33
  for (const div of Array.from(document.querySelectorAll("div"))) {
@@ -45,6 +48,7 @@ export async function findWidgets(page) {
45
48
  return out;
46
49
  });
47
50
  }
51
+ // --- Token reading -----------------------------------------------------------
48
52
  export async function readTurnstileToken(page) {
49
53
  try {
50
54
  return await page.evaluate(() => {
@@ -68,6 +72,7 @@ export async function readTurnstileToken(page) {
68
72
  return null;
69
73
  }
70
74
  }
75
+ // --- Click helpers -----------------------------------------------------------
71
76
  async function clickAt(page, x, y) {
72
77
  await page.mouse.move(x + between(-60, 60), y + between(-40, 40), { steps: 4 });
73
78
  await sleep(between(60, 160));
@@ -101,6 +106,7 @@ export function createClicker(retryAfter = 8000) {
101
106
  return result.clicks > 0;
102
107
  };
103
108
  }
109
+ // --- Solve -------------------------------------------------------------------
104
110
  export async function solveTurnstile(page, timeout = 30000, idleChecks = 4, retryAfter = 8000) {
105
111
  const end = Date.now() + timeout;
106
112
  const clicked = new Map();
@@ -122,6 +128,7 @@ export async function solveTurnstile(page, timeout = 30000, idleChecks = 4, retr
122
128
  }
123
129
  return readTurnstileToken(page);
124
130
  }
131
+ // --- Watcher -----------------------------------------------------------------
125
132
  export function watchTurnstile(page, options = {}) {
126
133
  if (WATCHED.has(page))
127
134
  return;
package/dist/uam.d.ts CHANGED
@@ -1,18 +1,32 @@
1
1
  import type { Browser, BrowserContext, Page } from "playwright-core";
2
+ import { type HumanOptions } from "./human.js";
2
3
  export interface UamOptions {
4
+ /** Max time to wait for a cf_clearance cookie after navigation (ms). */
3
5
  timeout?: number;
6
+ /** Polling interval when watching for new challenges (ms). */
4
7
  interval?: number;
8
+ /** Whether to wait for clearance right after each page.goto(). */
5
9
  waitOnGoto?: boolean;
10
+ /**
11
+ * Optional external helper that can perform an action on the challenge page
12
+ * (e.g. click a checkbox). Return true if an action was taken.
13
+ */
6
14
  assist?: (page: Page) => Promise<boolean>;
15
+ /** Forwarded to the internal {@link Human} actor for mouse movements. */
16
+ human?: HumanOptions;
7
17
  }
8
18
  export interface UamResult {
9
19
  challenged: boolean;
10
20
  bypassed: boolean;
11
21
  cookie: string | null;
12
22
  }
13
- export declare function trackMitigation(page: Page): void;
14
23
  export declare function isChallenge(page: Page): Promise<boolean>;
15
24
  export declare function humanActivity(page: Page, scale?: number): Promise<void>;
25
+ /**
26
+ * Waits until a `cf_clearance` cookie is present for the current page origin.
27
+ * If a challenge page was seen, performs light human-like activity while
28
+ * polling — matching the strategy used by cf-clearance-scraper.
29
+ */
16
30
  export declare function waitForUam(page: Page, options?: UamOptions): Promise<UamResult>;
17
31
  export declare function watchUam(page: Page, options?: UamOptions): void;
18
32
  export declare function attachUam<T extends Browser | BrowserContext>(target: T, options?: UamOptions): T;
package/dist/uam.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { onEachPage } from "./pagehooks.js";
2
2
  import { between, sleep } from "./random.js";
3
+ import { Human } from "./human.js";
3
4
  const CHALLENGE_TITLES = [
4
5
  "just a moment",
5
6
  "tunggu sebentar",
@@ -13,86 +14,65 @@ const CHALLENGE_TITLES = [
13
14
  ];
14
15
  const WATCHED = new WeakSet();
15
16
  const BUSY = new WeakSet();
16
- const MITIGATED = new WeakMap();
17
- const TRACKED = new WeakSet();
18
- export function trackMitigation(page) {
19
- if (TRACKED.has(page))
20
- return;
21
- TRACKED.add(page);
22
- page.on("response", (response) => {
23
- const request = response.request();
24
- if (!request.isNavigationRequest())
25
- return;
26
- if (request.frame() !== page.mainFrame())
27
- return;
28
- MITIGATED.set(page, response.headers()["cf-mitigated"] === "challenge");
29
- });
30
- }
31
- export async function isChallenge(page) {
32
- if (MITIGATED.get(page))
33
- return true;
34
- const title = (await page.title().catch(() => "")).toLowerCase();
35
- return CHALLENGE_TITLES.some((t) => title.includes(t));
36
- }
17
+ // --- Helpers -----------------------------------------------------------------
37
18
  async function cookieValue(page, name) {
38
19
  try {
39
- const cookies = await page.context().cookies(page.url());
20
+ const url = page.url();
21
+ if (!url || url === "about:blank")
22
+ return null;
23
+ const cookies = await page.context().cookies(url);
40
24
  return cookies.find((c) => c.name === name)?.value ?? null;
41
25
  }
42
26
  catch {
43
27
  return null;
44
28
  }
45
29
  }
30
+ export async function isChallenge(page) {
31
+ const title = (await page.title().catch(() => "")).toLowerCase();
32
+ return CHALLENGE_TITLES.some((t) => title.includes(t));
33
+ }
46
34
  export async function humanActivity(page, scale = 1) {
47
- let width = 1280;
48
- let height = 720;
49
35
  const view = page.viewportSize();
50
- if (view) {
51
- width = view.width;
52
- height = view.height;
53
- }
54
- else {
55
- try {
56
- const size = await page.evaluate(() => ({
57
- w: window.innerWidth,
58
- h: window.innerHeight,
59
- }));
60
- width = size.w;
61
- height = size.h;
62
- }
63
- catch {
64
- width = 1280;
65
- }
66
- }
67
- const moves = Math.max(1, Math.floor(between(4, 8) * scale));
68
- for (let i = 0; i < moves; i++) {
69
- await page.mouse.move(between(width * 0.1, width * 0.9), between(height * 0.1, height * 0.9), { steps: Math.floor(between(6, 14)) });
70
- await sleep(between(250, 650));
71
- }
72
- const scrolls = Math.max(1, Math.floor(between(2, 5) * scale));
73
- for (let i = 0; i < scrolls; i++) {
74
- await page.mouse.wheel(0, between(60, 180));
75
- await sleep(between(400, 900));
36
+ const opts = { speed: scale < 1 ? 0.4 : 1 };
37
+ const actor = new Human(page, opts);
38
+ await actor.idle(Math.round(800 * (2 - scale)));
39
+ for (let i = 0; i < Math.max(1, Math.floor(2 * scale)); i++) {
40
+ await actor.scroll(between(60, 180));
76
41
  }
77
42
  }
43
+ // --- Main wait loop ----------------------------------------------------------
44
+ /**
45
+ * Waits until a `cf_clearance` cookie is present for the current page origin.
46
+ * If a challenge page was seen, performs light human-like activity while
47
+ * polling — matching the strategy used by cf-clearance-scraper.
48
+ */
78
49
  export async function waitForUam(page, options = {}) {
79
- trackMitigation(page);
80
50
  const timeout = options.timeout ?? 30000;
81
51
  const start = Date.now();
82
52
  let challenged = false;
83
- let missing = 0;
53
+ let consecutiveMisses = 0;
84
54
  while (Date.now() - start < timeout && !page.isClosed()) {
85
- if (await isChallenge(page)) {
55
+ const cookie = await cookieValue(page, "cf_clearance");
56
+ // Cookie present — done
57
+ if (cookie) {
58
+ return { challenged, bypassed: true, cookie };
59
+ }
60
+ // Detect whether we're currently on a challenge page
61
+ const challenging = await isChallenge(page);
62
+ if (challenging) {
86
63
  challenged = true;
64
+ // Give the external assist callback a chance to interact
87
65
  if (options.assist) {
88
66
  const acted = await options.assist(page).catch(() => false);
89
67
  if (acted) {
90
- await sleep(1500);
68
+ consecutiveMisses = 0;
69
+ await sleep(2000);
91
70
  continue;
92
71
  }
93
72
  }
73
+ // Light human activity while waiting for the JS challenge to complete
94
74
  try {
95
- await humanActivity(page);
75
+ await humanActivity(page, 0.5);
96
76
  }
97
77
  catch {
98
78
  await sleep(500);
@@ -100,36 +80,20 @@ export async function waitForUam(page, options = {}) {
100
80
  await sleep(1500);
101
81
  continue;
102
82
  }
103
- const cookie = await cookieValue(page, "cf_clearance");
104
- if (!cookie) {
105
- if (!challenged)
106
- return { challenged: false, bypassed: false, cookie: null };
107
- missing++;
108
- if (missing > 3)
109
- return { challenged: true, bypassed: true, cookie: null };
110
- await sleep(1000);
111
- continue;
112
- }
113
- const retry = await cookieValue(page, "cf_chl_rc_ni");
114
- if (!challenged && !retry) {
115
- return { challenged: false, bypassed: true, cookie };
116
- }
117
- try {
118
- await humanActivity(page, 0.4);
119
- }
120
- catch {
121
- await sleep(500);
83
+ // Not challenged but no cookie yet — could be mid-navigation or still loading
84
+ if (!challenged) {
85
+ return { challenged: false, bypassed: false, cookie: null };
122
86
  }
123
- await sleep(2000);
124
- const second = await cookieValue(page, "cf_clearance");
125
- const retrySecond = await cookieValue(page, "cf_chl_rc_ni");
126
- if (second === cookie && !retrySecond) {
127
- return { challenged, bypassed: true, cookie: second };
87
+ // Challenged before but cookie still missing after repeated polls
88
+ consecutiveMisses++;
89
+ if (consecutiveMisses > 8) {
90
+ return { challenged: true, bypassed: true, cookie: null };
128
91
  }
129
- await sleep(1500);
92
+ await sleep(1000);
130
93
  }
131
94
  return { challenged, bypassed: false, cookie: null };
132
95
  }
96
+ // --- Watcher -----------------------------------------------------------------
133
97
  async function runWait(page, options) {
134
98
  if (BUSY.has(page))
135
99
  return undefined;
@@ -145,7 +109,6 @@ export function watchUam(page, options = {}) {
145
109
  if (WATCHED.has(page))
146
110
  return;
147
111
  WATCHED.add(page);
148
- trackMitigation(page);
149
112
  const interval = options.interval ?? 1500;
150
113
  const timeout = options.timeout ?? 30000;
151
114
  const waitOnGoto = options.waitOnGoto ?? true;
package/dist/utils.js CHANGED
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { UAParser } from "ua-parser-js";
5
5
  import { addDefaultAddons, confirmPaths, } from "./addons.js";
6
6
  import { InvalidOS, InvalidPropertyType, NonFirefoxFingerprint, UnknownProperty, } from "./exceptions.js";
7
- import { fromBrowserforge, generateFingerprint, SUPPORTED_OS, } from "./fingerprints.js";
7
+ import { cryptoFloat, fromBrowserforge, generateFingerprint, SUPPORTED_OS, } from "./fingerprints.js";
8
8
  import { publicIP, validIPv4, validIPv6 } from "./ip.js";
9
9
  import { coherentDprWeights, languageList, realismDefaults, reconcileWebglKeys, snapScreen, } from "./realism.js";
10
10
  import { geoipAllowed, getGeolocation, handleLocales } from "./locale.js";
@@ -94,6 +94,97 @@ function loadProperties(filePath) {
94
94
  return acc;
95
95
  }, {});
96
96
  }
97
+ /**
98
+ * High-level behavioral property seeding.
99
+ * These are properties that aren't part of the raw fingerprint generator output
100
+ * but significantly affect detection scores when left at defaults or missing.
101
+ */
102
+ function seedBehavioralProperties(config, fpExtended, targetOS, headless, knownProperties, firefoxUserPrefs) {
103
+ // --- Battery API ---
104
+ // Desktops → always discharging with long remaining time.
105
+ // Laptops/macs → mixed charging states (real Macs report ~50-90% on most machines).
106
+ if ("battery:level" in knownProperties) {
107
+ const isLaptop = targetOS === "mac" || (targetOS === "win" && cryptoFloat() < 0.6);
108
+ if (isLaptop) {
109
+ setInto(config, "battery:level", +(0.2 + cryptoFloat() * 0.75).toFixed(2));
110
+ if (cryptoFloat() < 0.25) {
111
+ setInto(config, "battery:charging", true);
112
+ setInto(config, "battery:chargingTime", 0);
113
+ setInto(config, "battery:dischargingTime", +(900 + cryptoRandInt(0, 7200)).toString());
114
+ }
115
+ else {
116
+ setInto(config, "battery:charging", false);
117
+ setInto(config, "battery:chargingTime", Infinity);
118
+ setInto(config, "battery:dischargingTime", +(600 + cryptoRandInt(0, 10800)).toString());
119
+ }
120
+ }
121
+ else {
122
+ setInto(config, "battery:level", 1);
123
+ setInto(config, "battery:charging", false);
124
+ setInto(config, "battery:chargingTime", Infinity);
125
+ setInto(config, "battery:dischargingTime", Infinity);
126
+ }
127
+ }
128
+ // --- Media devices ---
129
+ // Realistic counts per OS: desktops often have 0-1 mic, laptops 1-2, webcams 0-2
130
+ const micPool = [0, 0, 1, 1, 1, 2, 2];
131
+ const camPool = [0, 0, 0, 1, 1, 2];
132
+ const spkPool = [0, 1, 1, 1, 2, 2, 3, 4];
133
+ if ("mediaDevices:enabled" in knownProperties)
134
+ setInto(config, "mediaDevices:enabled", true);
135
+ if ("mediaDevices:micros" in knownProperties)
136
+ setInto(config, "mediaDevices:micros", micPool[cryptoRandInt(0, micPool.length - 1)]);
137
+ if ("mediaDevices:webcams" in knownProperties)
138
+ setInto(config, "mediaDevices:webcams", camPool[cryptoRandInt(0, camPool.length - 1)]);
139
+ if ("mediaDevices:speakers" in knownProperties)
140
+ setInto(config, "mediaDevices:speakers", spkPool[cryptoRandInt(0, spkPool.length - 1)]);
141
+ // --- Speech synthesis voices ---
142
+ // Match locale language; vary count realistically
143
+ if ("voices" in knownProperties) {
144
+ const voiceCount = 2 + cryptoRandInt(0, 8);
145
+ const voiceList = [];
146
+ const lang = config["locale:language"] ?? "en";
147
+ for (let i = 0; i < voiceCount; i++) {
148
+ voiceList.push({ lang, name: `${lang}-Voice-${i + 1}` });
149
+ }
150
+ config["voices"] = voiceList;
151
+ if ("voices:blockIfNotDefined" in knownProperties)
152
+ setInto(config, "voices:blockIfNotDefined", false);
153
+ if ("voices:fakeCompletion" in knownProperties)
154
+ setInto(config, "voices:fakeCompletion", false);
155
+ }
156
+ // --- Do Not Track ---
157
+ // ~20% of real users have DNT enabled
158
+ if ("navigator.doNotTrack" in knownProperties) {
159
+ setInto(config, "navigator.doNotTrack", cryptoFloat() < 0.2 ? "1" : "0");
160
+ }
161
+ // --- Global Privacy Control ---
162
+ // ~10% of browsers signal GPC
163
+ if ("navigator.globalPrivacyControl" in knownProperties) {
164
+ setInto(config, "navigator.globalPrivacyControl", cryptoFloat() < 0.1);
165
+ }
166
+ // --- Cookie enabled ---
167
+ if ("navigator.cookieEnabled" in knownProperties)
168
+ setInto(config, "navigator.cookieEnabled", true);
169
+ // --- Online state ---
170
+ // Very rarely offline
171
+ if ("navigator.onLine" in knownProperties) {
172
+ setInto(config, "navigator.onLine", cryptoFloat() > 0.002);
173
+ }
174
+ if (!headless) {
175
+ firefoxUserPrefs["privacy.referrer_policy"] = 1; // Same-Origin on cross-origin
176
+ }
177
+ // --- Max touch points consistency ---
178
+ if ("navigator.maxTouchPoints" in knownProperties) {
179
+ if (fpExtended.touchSupport) {
180
+ setInto(config, "navigator.maxTouchPoints", fpExtended.touchPoints);
181
+ }
182
+ else {
183
+ setInto(config, "navigator.maxTouchPoints", 0);
184
+ }
185
+ }
186
+ // --- Performance timing jitter is already handled via performance:now_jitter above
187
+ }
97
188
  function formatTimezoneOffset(minutes) {
98
189
  const sign = minutes >= 0 ? "+" : "-";
99
190
  const abs = Math.abs(minutes);
@@ -473,6 +564,10 @@ export async function launchOptions({ config, os, block_images, block_webrtc, bl
473
564
  setInto(config, "session:stickiness", true);
474
565
  }
475
566
  const targetOS = getTargetOS(config);
567
+ // --- Behavioral property seeding (battery, media devices, DNT, etc.) ---
568
+ if (fpExtended) {
569
+ seedBehavioralProperties(config, fpExtended, targetOS, Boolean(headlessBoolean), knownProperties, firefox_user_prefs);
570
+ }
476
571
  setInto(config, "window.history.length", weightedPick([1, 2, 3, 4, 5, 6], [40, 25, 15, 10, 6, 4]));
477
572
  if (fonts) {
478
573
  config.fonts = fonts;
@@ -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;