bexxcv 1.0.8 → 1.0.9

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,8 @@
1
+ import type { BexxcvPlugin } from "./types.js";
2
+ export interface StashOptions {
3
+ file: string;
4
+ names?: string[];
5
+ domains?: string[];
6
+ saveEvery?: number;
7
+ }
8
+ export declare function stash(options: StashOptions): BexxcvPlugin;
@@ -0,0 +1,108 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ function domainKey(cookie) {
4
+ return cookie.domain.replace(/^\./, "").toLowerCase();
5
+ }
6
+ function expired(cookie) {
7
+ return cookie.expires > 0 && cookie.expires < Date.now() / 1000;
8
+ }
9
+ function readFile(file) {
10
+ try {
11
+ const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
12
+ if (raw && typeof raw === "object" && raw.domains)
13
+ return raw;
14
+ }
15
+ catch {
16
+ return { version: 1, saved: new Date(0).toISOString(), domains: {} };
17
+ }
18
+ return { version: 1, saved: new Date(0).toISOString(), domains: {} };
19
+ }
20
+ export function stash(options) {
21
+ const file = path.resolve(options.file);
22
+ const names = options.names ? new Set(options.names) : null;
23
+ const domains = options.domains?.map((d) => d.toLowerCase().replace(/^\./, "")) ?? null;
24
+ const known = new Set();
25
+ let timer = null;
26
+ let launchProxy = "direct";
27
+ const contextProxy = new WeakMap();
28
+ const wanted = (cookie) => {
29
+ if (names && !names.has(cookie.name))
30
+ return false;
31
+ if (domains) {
32
+ const key = domainKey(cookie);
33
+ if (!domains.some((d) => key === d || key.endsWith(`.${d}`)))
34
+ return false;
35
+ }
36
+ return true;
37
+ };
38
+ const BOUND = new Set(["cf_clearance"]);
39
+ const save = async (contexts) => {
40
+ const data = readFile(file);
41
+ for (const context of contexts) {
42
+ const grouped = {};
43
+ for (const cookie of await context.cookies()) {
44
+ if (!wanted(cookie) || expired(cookie))
45
+ continue;
46
+ (grouped[domainKey(cookie)] ??= []).push(cookie);
47
+ }
48
+ for (const [key, list] of Object.entries(grouped)) {
49
+ data.domains[key] = list;
50
+ (data.bound ??= {})[key] = contextProxy.get(context) ?? launchProxy;
51
+ }
52
+ }
53
+ for (const [key, list] of Object.entries(data.domains)) {
54
+ const alive = list.filter((cookie) => !expired(cookie));
55
+ if (alive.length > 0)
56
+ data.domains[key] = alive;
57
+ else
58
+ delete data.domains[key];
59
+ }
60
+ data.saved = new Date().toISOString();
61
+ fs.mkdirSync(path.dirname(file), { recursive: true });
62
+ fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
63
+ };
64
+ return {
65
+ name: "stash",
66
+ order: 20,
67
+ beforeLaunch(launch) {
68
+ const proxy = launch.proxy;
69
+ if (typeof proxy === "string")
70
+ launchProxy = proxy;
71
+ else if (proxy && proxy.server)
72
+ launchProxy = proxy.server;
73
+ },
74
+ async onContext(context, contextOptions) {
75
+ known.add(context);
76
+ const current = contextOptions.proxy?.server ?? launchProxy;
77
+ contextProxy.set(context, current);
78
+ const data = readFile(file);
79
+ const cookies = Object.entries(data.domains).flatMap(([key, list]) => list.filter((cookie) => {
80
+ if (!wanted(cookie) || expired(cookie))
81
+ return false;
82
+ if (BOUND.has(cookie.name) && (data.bound?.[key] ?? "direct") !== current)
83
+ return false;
84
+ return true;
85
+ }));
86
+ if (cookies.length > 0) {
87
+ try {
88
+ await context.addCookies(cookies);
89
+ }
90
+ catch (error) {
91
+ console.warn(`[bexxcv] stash could not load cookies: ${error.message}`);
92
+ }
93
+ }
94
+ if (options.saveEvery && !timer) {
95
+ timer = setInterval(() => {
96
+ void save([...known]).catch(() => undefined);
97
+ }, options.saveEvery);
98
+ timer.unref();
99
+ }
100
+ },
101
+ async beforeClose(contexts) {
102
+ if (timer)
103
+ clearInterval(timer);
104
+ timer = null;
105
+ await save(contexts);
106
+ },
107
+ };
108
+ }
@@ -0,0 +1,13 @@
1
+ import type { Browser, BrowserContext, Page } from "playwright-core";
2
+ import { type ContextOptions } from "../pagehooks.js";
3
+ export interface BexxcvPlugin {
4
+ name: string;
5
+ order?: number;
6
+ beforeLaunch?(options: Record<string, unknown>): void | Promise<void>;
7
+ beforeContext?(options: ContextOptions): void | Promise<void>;
8
+ onContext?(context: BrowserContext, options: ContextOptions): void | Promise<void>;
9
+ onPage?(page: Page, context: BrowserContext): void;
10
+ beforeClose?(contexts: BrowserContext[]): void | Promise<void>;
11
+ }
12
+ export declare function runBeforeLaunch(plugins: BexxcvPlugin[], options: Record<string, unknown>): Promise<void>;
13
+ export declare function applyPlugins<T extends Browser | BrowserContext>(target: T, plugins: BexxcvPlugin[]): Promise<T>;
@@ -0,0 +1,49 @@
1
+ import { onEachContext, onEachPage, } from "../pagehooks.js";
2
+ const DEFAULT_ORDER = 50;
3
+ function sortPlugins(plugins) {
4
+ return [...plugins].sort((a, b) => (a.order ?? DEFAULT_ORDER) - (b.order ?? DEFAULT_ORDER));
5
+ }
6
+ export async function runBeforeLaunch(plugins, options) {
7
+ for (const plugin of sortPlugins(plugins)) {
8
+ await plugin.beforeLaunch?.(options);
9
+ }
10
+ }
11
+ export async function applyPlugins(target, plugins) {
12
+ const sorted = sortPlugins(plugins);
13
+ await onEachContext(target, {
14
+ before: async (options) => {
15
+ for (const plugin of sorted)
16
+ await plugin.beforeContext?.(options);
17
+ },
18
+ after: async (context, options) => {
19
+ for (const plugin of sorted)
20
+ await plugin.onContext?.(context, options);
21
+ },
22
+ });
23
+ for (const plugin of sorted) {
24
+ if (!plugin.onPage)
25
+ continue;
26
+ const handler = plugin.onPage.bind(plugin);
27
+ onEachPage(target, (page) => handler(page, page.context()));
28
+ }
29
+ const closers = sorted.filter((plugin) => plugin.beforeClose);
30
+ if (closers.length > 0) {
31
+ const holder = target;
32
+ const originalClose = holder.close.bind(target);
33
+ holder.close = async (...args) => {
34
+ const contexts = typeof target.contexts === "function"
35
+ ? target.contexts()
36
+ : [target];
37
+ for (const plugin of [...closers].reverse()) {
38
+ try {
39
+ await plugin.beforeClose?.(contexts);
40
+ }
41
+ catch (error) {
42
+ console.warn(`[bexxcv] plugin "${plugin.name}" failed on close: ${error.message}`);
43
+ }
44
+ }
45
+ return originalClose(...args);
46
+ };
47
+ }
48
+ return target;
49
+ }
@@ -0,0 +1,5 @@
1
+ import type { BexxcvPlugin } from "./types.js";
2
+ export interface VeneerOptions {
3
+ strict?: boolean;
4
+ }
5
+ export declare function veneer(options?: VeneerOptions): BexxcvPlugin;
@@ -0,0 +1,37 @@
1
+ export function veneer(options = {}) {
2
+ let warned = false;
3
+ return {
4
+ name: "veneer",
5
+ order: 30,
6
+ async onContext(context) {
7
+ if (options.strict) {
8
+ await context.route("**/*", async (route) => {
9
+ const headers = route.request().headers();
10
+ if (/firefox/i.test(headers["user-agent"] ?? "")) {
11
+ const cleaned = {};
12
+ for (const [key, value] of Object.entries(headers)) {
13
+ if (!key.toLowerCase().startsWith("sec-ch-ua"))
14
+ cleaned[key] = value;
15
+ }
16
+ if (Object.keys(cleaned).length !== Object.keys(headers).length) {
17
+ await route.continue({ headers: cleaned });
18
+ return;
19
+ }
20
+ }
21
+ await route.continue();
22
+ });
23
+ return;
24
+ }
25
+ context.on("request", (request) => {
26
+ if (warned)
27
+ return;
28
+ const headers = request.headers();
29
+ if (/firefox/i.test(headers["user-agent"] ?? "") &&
30
+ Object.keys(headers).some((key) => key.toLowerCase().startsWith("sec-ch-ua"))) {
31
+ warned = true;
32
+ console.warn("[bexxcv] veneer: a Firefox user agent is sending sec-ch-ua headers, something upstream is injecting them. Use veneer: { strict: true } to strip them.");
33
+ }
34
+ });
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,26 @@
1
+ import type { BrowserContext } from "playwright-core";
2
+ import type { BexxcvPlugin } from "./types.js";
3
+ export interface WiretapOptions {
4
+ match?: string[];
5
+ methods?: string[];
6
+ out?: string;
7
+ bodies?: boolean;
8
+ maxBodyBytes?: number;
9
+ streamTimeout?: number;
10
+ redact?: boolean;
11
+ }
12
+ export interface WiretapEntry {
13
+ time: string;
14
+ method: string;
15
+ url: string;
16
+ status: number;
17
+ requestHeaders: Record<string, string>;
18
+ postData: string | null;
19
+ responseHeaders: Record<string, string>;
20
+ contentType: string;
21
+ body: string | null;
22
+ bodyNote?: string;
23
+ events?: string[];
24
+ }
25
+ export declare function wiretapEntries(context: BrowserContext): WiretapEntry[];
26
+ export declare function wiretap(options?: WiretapOptions): BexxcvPlugin;
@@ -0,0 +1,123 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ const SENSITIVE = new Set([
4
+ "cookie",
5
+ "set-cookie",
6
+ "authorization",
7
+ "proxy-authorization",
8
+ "x-api-key",
9
+ ]);
10
+ const STORES = new WeakMap();
11
+ export function wiretapEntries(context) {
12
+ return STORES.get(context) ?? [];
13
+ }
14
+ function scrub(headers, redact) {
15
+ if (!redact)
16
+ return { ...headers };
17
+ const out = {};
18
+ for (const [key, value] of Object.entries(headers)) {
19
+ out[key] = SENSITIVE.has(key.toLowerCase()) ? "[redacted]" : value;
20
+ }
21
+ return out;
22
+ }
23
+ function matcher(patterns) {
24
+ if (!patterns || patterns.length === 0)
25
+ return () => true;
26
+ const tests = patterns.map((pattern) => {
27
+ if (pattern.startsWith("re:")) {
28
+ const re = new RegExp(pattern.slice(3));
29
+ return (url) => re.test(url);
30
+ }
31
+ return (url) => url.includes(pattern);
32
+ });
33
+ return (url) => tests.some((test) => test(url));
34
+ }
35
+ function withTimeout(promise, ms) {
36
+ return new Promise((resolve, reject) => {
37
+ const timer = setTimeout(() => reject(new Error("timeout")), ms);
38
+ promise.then((value) => {
39
+ clearTimeout(timer);
40
+ resolve(value);
41
+ }, (error) => {
42
+ clearTimeout(timer);
43
+ reject(error);
44
+ });
45
+ });
46
+ }
47
+ export function wiretap(options = {}) {
48
+ const match = matcher(options.match);
49
+ const methods = new Set((options.methods ?? []).map((m) => m.toUpperCase()));
50
+ const redact = options.redact ?? true;
51
+ const bodies = options.bodies ?? true;
52
+ const maxBytes = options.maxBodyBytes ?? 1_000_000;
53
+ const streamTimeout = options.streamTimeout ?? 60_000;
54
+ const pending = new Set();
55
+ const capture = async (response, list) => {
56
+ const request = response.request();
57
+ if (methods.size > 0 && !methods.has(request.method()))
58
+ return;
59
+ const url = response.url();
60
+ if (!match(url))
61
+ return;
62
+ const responseHeaders = response.headers();
63
+ const contentType = responseHeaders["content-type"] ?? "";
64
+ const entry = {
65
+ time: new Date().toISOString(),
66
+ method: request.method(),
67
+ url,
68
+ status: response.status(),
69
+ requestHeaders: scrub(request.headers(), redact),
70
+ postData: request.postData(),
71
+ responseHeaders: scrub(responseHeaders, redact),
72
+ contentType,
73
+ body: null,
74
+ };
75
+ if (bodies) {
76
+ const stream = /event-stream/i.test(contentType);
77
+ try {
78
+ const text = await withTimeout(response.text(), stream ? streamTimeout : 10_000);
79
+ if (Buffer.byteLength(text) > maxBytes) {
80
+ entry.body = text.slice(0, maxBytes);
81
+ entry.bodyNote = "truncated";
82
+ }
83
+ else {
84
+ entry.body = text;
85
+ }
86
+ if (stream) {
87
+ entry.events = text
88
+ .split(/\r?\n\r?\n/)
89
+ .map((chunk) => chunk.trim())
90
+ .filter(Boolean);
91
+ }
92
+ }
93
+ catch (error) {
94
+ entry.bodyNote = error.message;
95
+ }
96
+ }
97
+ list.push(entry);
98
+ };
99
+ const save = async (contexts) => {
100
+ if (!options.out)
101
+ return;
102
+ await Promise.allSettled([...pending]);
103
+ const entries = contexts.flatMap((context) => wiretapEntries(context));
104
+ entries.sort((a, b) => a.time.localeCompare(b.time));
105
+ fs.mkdirSync(path.dirname(path.resolve(options.out)), { recursive: true });
106
+ fs.writeFileSync(options.out, `${JSON.stringify({ captured: entries.length, entries }, null, 2)}\n`, { mode: 0o600 });
107
+ };
108
+ return {
109
+ name: "wiretap",
110
+ order: 30,
111
+ onContext(context) {
112
+ const list = [];
113
+ STORES.set(context, list);
114
+ context.on("response", (response) => {
115
+ const task = capture(response, list)
116
+ .catch(() => undefined)
117
+ .finally(() => pending.delete(task));
118
+ pending.add(task);
119
+ });
120
+ },
121
+ beforeClose: save,
122
+ };
123
+ }
package/dist/schema.js CHANGED
@@ -73,6 +73,91 @@ const SPEC = {
73
73
  ]),
74
74
  "a boolean or { interval, retryAfter }",
75
75
  ],
76
+ gauntlet: [
77
+ z.union([
78
+ z.boolean(),
79
+ z.object({
80
+ solve: z.array(z.enum(["uam", "turnstile"])).optional(),
81
+ maxTries: z.number().int().positive().optional(),
82
+ timeout: positive.optional(),
83
+ sustain: z.number().nonnegative().optional(),
84
+ }),
85
+ ]),
86
+ 'a boolean or { solve: ["uam", "turnstile"], maxTries, timeout, sustain }',
87
+ ],
88
+ wiretap: [
89
+ z.union([
90
+ z.boolean(),
91
+ z.object({
92
+ match: z.array(z.string()).optional(),
93
+ methods: z.array(z.string()).optional(),
94
+ out: z.string().min(1).optional(),
95
+ bodies: z.boolean().optional(),
96
+ maxBodyBytes: positive.optional(),
97
+ streamTimeout: positive.optional(),
98
+ redact: z.boolean().optional(),
99
+ }),
100
+ ]),
101
+ "a boolean or { match, methods, out, bodies, maxBodyBytes, streamTimeout, redact }",
102
+ ],
103
+ stash: [
104
+ z.union([
105
+ z.string().min(1),
106
+ z.object({
107
+ file: z.string().min(1),
108
+ names: z.array(z.string()).optional(),
109
+ domains: z.array(z.string()).optional(),
110
+ saveEvery: positive.optional(),
111
+ }),
112
+ ]),
113
+ "a file path or { file, names, domains, saveEvery }",
114
+ ],
115
+ veneer: [
116
+ z.union([z.boolean(), z.object({ strict: z.boolean().optional() })]),
117
+ "a boolean or { strict }",
118
+ ],
119
+ brake: [
120
+ z.union([
121
+ z.boolean(),
122
+ z.object({
123
+ maxRps: positive.optional(),
124
+ respectRetryAfter: z.boolean().optional(),
125
+ perHost: z.boolean().optional(),
126
+ maxBackoff: positive.optional(),
127
+ }),
128
+ ]),
129
+ "a boolean or { maxRps, respectRetryAfter, perHost, maxBackoff }",
130
+ ],
131
+ dodge: [
132
+ z.object({
133
+ pool: z.array(z.string().min(1)).min(1),
134
+ rotateOn: z.array(z.number().int()).optional(),
135
+ healthCheck: z.boolean().optional(),
136
+ healthTimeout: positive.optional(),
137
+ cooldown: positive.optional(),
138
+ onBlocked: z
139
+ .custom((v) => typeof v === "function")
140
+ .optional(),
141
+ }),
142
+ "{ pool: [proxy urls], rotateOn, healthCheck, healthTimeout, cooldown, onBlocked }",
143
+ ],
144
+ cocoon: [z.string().min(1), "a folder path"],
145
+ lens: [
146
+ z.union([
147
+ z.boolean(),
148
+ z.object({
149
+ audit: z.boolean().optional(),
150
+ target: z.literal("local").optional(),
151
+ quiet: z.boolean().optional(),
152
+ out: z.string().min(1).optional(),
153
+ }),
154
+ ]),
155
+ 'a boolean or { audit, target: "local", quiet, out }',
156
+ ],
157
+ plugins: [
158
+ z.array(z.custom((v) => typeof v === "object" && v !== null && typeof v.name === "string")),
159
+ "an array of plugin objects with a name",
160
+ ],
76
161
  uam: [
77
162
  z.union([
78
163
  z.boolean(),
@@ -1,6 +1,7 @@
1
1
  import { type Browser, type BrowserContext, type BrowserType } from "playwright-core";
2
2
  import { type LaunchOptions } from "./utils.js";
3
3
  import { type TurnstileOptions } from "./turnstile.js";
4
+ import { type PluginOptions } from "./plugins/index.js";
4
5
  import { type UamOptions } from "./uam.js";
5
6
  export interface BexxcvOptions extends LaunchOptions {
6
7
  user_data_dir?: string;
@@ -8,7 +9,8 @@ export interface BexxcvOptions extends LaunchOptions {
8
9
  turnstile?: boolean | TurnstileOptions;
9
10
  uam?: boolean | UamOptions;
10
11
  }
11
- export declare function Bexxcv<UserDataDir extends string | undefined = undefined, ReturnType = UserDataDir extends string ? BrowserContext : Browser>(launch_options?: BexxcvOptions & {
12
+ export type BexxcvLaunchOptions = BexxcvOptions & PluginOptions;
13
+ export declare function Bexxcv<UserDataDir extends string | undefined = undefined, ReturnType = UserDataDir extends string ? BrowserContext : Browser>(launch_options?: BexxcvOptions & PluginOptions & {
12
14
  user_data_dir?: UserDataDir;
13
15
  }): Promise<ReturnType>;
14
16
  export declare const Camoufox: typeof Bexxcv;
package/dist/sync_api.js CHANGED
@@ -3,13 +3,18 @@ import { attachNoViewportDefault, launchOptions, spoofsWindowDimensions, syncAtt
3
3
  import { warnIfDataStale } from "./doctor.js";
4
4
  import { validateOptions } from "./schema.js";
5
5
  import { attachTurnstile } from "./turnstile.js";
6
+ import { applyPlugins, buildPlugins, runBeforeLaunch, stripPluginOptions, } from "./plugins/index.js";
6
7
  import { attachUam } from "./uam.js";
7
8
  import { VirtualDisplay } from "./virtdisplay.js";
8
9
  import { needsXvfb } from "./xvfb.js";
9
10
  export async function Bexxcv(launch_options = {}) {
10
11
  validateOptions(launch_options);
11
12
  warnIfDataStale();
12
- const { headless, user_data_dir, auto_xvfb = true, turnstile = false, uam = false, ...opts } = launch_options;
13
+ const pluginList = buildPlugins(launch_options);
14
+ launch_options = { ...launch_options };
15
+ await runBeforeLaunch(pluginList, launch_options);
16
+ const { headless, user_data_dir, auto_xvfb = true, turnstile = false, uam = false, ...restOptions } = launch_options;
17
+ const opts = stripPluginOptions(restOptions);
13
18
  const needsDisplay = auto_xvfb && needsXvfb();
14
19
  const effectiveHeadless = (() => {
15
20
  if (headless === "virtual")
@@ -27,6 +32,9 @@ export async function Bexxcv(launch_options = {}) {
27
32
  if (uam) {
28
33
  attachUam(launched, uam === true ? {} : uam);
29
34
  }
35
+ if (pluginList.length > 0) {
36
+ await applyPlugins(launched, pluginList);
37
+ }
30
38
  return launched;
31
39
  }
32
40
  export const Camoufox = Bexxcv;
@@ -3,5 +3,17 @@ export interface TurnstileOptions {
3
3
  interval?: number;
4
4
  retryAfter?: number;
5
5
  }
6
+ export interface Widget {
7
+ x: number;
8
+ y: number;
9
+ w: number;
10
+ h: number;
11
+ solved: boolean;
12
+ key: string;
13
+ }
14
+ export declare function findWidgets(page: Page): Promise<Widget[]>;
15
+ export declare function readTurnstileToken(page: Page): Promise<string | null>;
16
+ export declare function createClicker(retryAfter?: number): (page: Page) => Promise<boolean>;
17
+ export declare function solveTurnstile(page: Page, timeout?: number, idleChecks?: number, retryAfter?: number): Promise<string | null>;
6
18
  export declare function watchTurnstile(page: Page, options?: TurnstileOptions): void;
7
19
  export declare function attachTurnstile<T extends Browser | BrowserContext>(target: T, options?: TurnstileOptions): T;
package/dist/turnstile.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { onEachPage } from "./pagehooks.js";
2
2
  import { between, sleep } from "./random.js";
3
3
  const WATCHED = new WeakSet();
4
- async function findWidgets(page) {
4
+ export async function findWidgets(page) {
5
5
  return page.evaluate(() => {
6
6
  const out = [];
7
7
  const seen = new Set();
@@ -45,6 +45,29 @@ async function findWidgets(page) {
45
45
  return out;
46
46
  });
47
47
  }
48
+ export async function readTurnstileToken(page) {
49
+ try {
50
+ return await page.evaluate(() => {
51
+ for (const el of Array.from(document.querySelectorAll('[name="cf-turnstile-response"]'))) {
52
+ if (el.value && el.value.length > 20)
53
+ return el.value;
54
+ }
55
+ try {
56
+ const w = window;
57
+ const value = w.turnstile?.getResponse?.();
58
+ if (value && value.length > 20)
59
+ return value;
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ return null;
65
+ });
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
48
71
  async function clickAt(page, x, y) {
49
72
  await page.mouse.move(x + between(-60, 60), y + between(-40, 40), { steps: 4 });
50
73
  await sleep(between(60, 160));
@@ -54,6 +77,51 @@ async function clickAt(page, x, y) {
54
77
  await sleep(between(60, 120));
55
78
  await page.mouse.up();
56
79
  }
80
+ async function clickPending(page, clicked, retryAfter) {
81
+ const widgets = await findWidgets(page);
82
+ let clicks = 0;
83
+ for (const widget of widgets) {
84
+ if (widget.solved)
85
+ continue;
86
+ const last = clicked.get(widget.key) ?? 0;
87
+ if (Date.now() - last < retryAfter)
88
+ continue;
89
+ clicked.set(widget.key, Date.now());
90
+ const x = widget.x + Math.min(30, widget.w / 2) + between(-4, 4);
91
+ const y = widget.y + widget.h / 2 + between(-4, 4);
92
+ await clickAt(page, x, y);
93
+ clicks++;
94
+ }
95
+ return { widgets, clicks };
96
+ }
97
+ export function createClicker(retryAfter = 8000) {
98
+ const clicked = new Map();
99
+ return async (page) => {
100
+ const result = await clickPending(page, clicked, retryAfter);
101
+ return result.clicks > 0;
102
+ };
103
+ }
104
+ export async function solveTurnstile(page, timeout = 30000, idleChecks = 4, retryAfter = 8000) {
105
+ const end = Date.now() + timeout;
106
+ const clicked = new Map();
107
+ let idle = 0;
108
+ while (Date.now() < end && !page.isClosed()) {
109
+ const token = await readTurnstileToken(page);
110
+ if (token)
111
+ return token;
112
+ try {
113
+ const result = await clickPending(page, clicked, retryAfter);
114
+ idle = result.widgets.length === 0 ? idle + 1 : 0;
115
+ }
116
+ catch {
117
+ idle++;
118
+ }
119
+ if (idle >= idleChecks)
120
+ return null;
121
+ await sleep(1000);
122
+ }
123
+ return readTurnstileToken(page);
124
+ }
57
125
  export function watchTurnstile(page, options = {}) {
58
126
  if (WATCHED.has(page))
59
127
  return;
@@ -68,18 +136,7 @@ export function watchTurnstile(page, options = {}) {
68
136
  const loop = async () => {
69
137
  while (active && !page.isClosed()) {
70
138
  try {
71
- const widgets = await findWidgets(page);
72
- for (const widget of widgets) {
73
- if (widget.solved)
74
- continue;
75
- const last = clicked.get(widget.key) ?? 0;
76
- if (Date.now() - last < retryAfter)
77
- continue;
78
- clicked.set(widget.key, Date.now());
79
- const x = widget.x + Math.min(30, widget.w / 2) + between(-4, 4);
80
- const y = widget.y + widget.h / 2 + between(-4, 4);
81
- await clickAt(page, x, y);
82
- }
139
+ await clickPending(page, clicked, retryAfter);
83
140
  }
84
141
  catch {
85
142
  await sleep(500);
package/dist/uam.d.ts CHANGED
@@ -3,12 +3,16 @@ export interface UamOptions {
3
3
  timeout?: number;
4
4
  interval?: number;
5
5
  waitOnGoto?: boolean;
6
+ assist?: (page: Page) => Promise<boolean>;
6
7
  }
7
8
  export interface UamResult {
8
9
  challenged: boolean;
9
10
  bypassed: boolean;
10
11
  cookie: string | null;
11
12
  }
13
+ export declare function trackMitigation(page: Page): void;
14
+ export declare function isChallenge(page: Page): Promise<boolean>;
15
+ export declare function humanActivity(page: Page, scale?: number): Promise<void>;
12
16
  export declare function waitForUam(page: Page, options?: UamOptions): Promise<UamResult>;
13
17
  export declare function watchUam(page: Page, options?: UamOptions): void;
14
18
  export declare function attachUam<T extends Browser | BrowserContext>(target: T, options?: UamOptions): T;