browserclaw 0.6.0 → 0.7.1

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.
package/dist/index.d.cts CHANGED
@@ -545,6 +545,22 @@ interface HttpCredentials {
545
545
  interface ContextState {
546
546
  traceActive: boolean;
547
547
  }
548
+ /** The kind of anti-bot challenge detected on a page. */
549
+ type ChallengeKind = 'cloudflare-js' | 'cloudflare-block' | 'cloudflare-turnstile' | 'hcaptcha' | 'recaptcha' | 'blocked' | 'rate-limited';
550
+ /** Information about a detected anti-bot challenge. */
551
+ interface ChallengeInfo {
552
+ /** What type of challenge is present */
553
+ kind: ChallengeKind;
554
+ /** Human-readable description */
555
+ message: string;
556
+ }
557
+ /** Result of waiting for an anti-bot challenge to resolve. */
558
+ interface ChallengeWaitResult {
559
+ /** Whether the challenge cleared within the timeout */
560
+ resolved: boolean;
561
+ /** The challenge still present (null if resolved) */
562
+ challenge: ChallengeInfo | null;
563
+ }
548
564
  /** Result of DNS pinning resolution — hostname locked to resolved addresses. */
549
565
  interface PinnedHostname {
550
566
  hostname: string;
@@ -1162,6 +1178,46 @@ declare class CrawlPage {
1162
1178
  * ```
1163
1179
  */
1164
1180
  setDevice(name: string): Promise<void>;
1181
+ /**
1182
+ * Detect whether the page is showing an anti-bot challenge
1183
+ * (Cloudflare, hCaptcha, reCAPTCHA, access-denied, rate-limit, etc.).
1184
+ *
1185
+ * Returns `null` if no challenge is detected.
1186
+ *
1187
+ * @example
1188
+ * ```ts
1189
+ * const challenge = await page.detectChallenge();
1190
+ * if (challenge) {
1191
+ * console.log(challenge.kind); // 'cloudflare-js'
1192
+ * console.log(challenge.message); // 'Cloudflare JS challenge'
1193
+ * }
1194
+ * ```
1195
+ */
1196
+ detectChallenge(): Promise<ChallengeInfo | null>;
1197
+ /**
1198
+ * Wait for an anti-bot challenge to resolve on its own.
1199
+ *
1200
+ * Cloudflare JS challenges typically auto-resolve in ~5 seconds.
1201
+ * CAPTCHA challenges will only resolve if solved in a visible browser window.
1202
+ *
1203
+ * @param opts.timeoutMs - Maximum wait time (default: `15000`)
1204
+ * @param opts.pollMs - Poll interval (default: `500`)
1205
+ * @returns Whether the challenge resolved, and the remaining challenge info if not
1206
+ *
1207
+ * @example
1208
+ * ```ts
1209
+ * await page.goto('https://example.com');
1210
+ * const challenge = await page.detectChallenge();
1211
+ * if (challenge?.kind === 'cloudflare-js') {
1212
+ * const { resolved } = await page.waitForChallenge({ timeoutMs: 20000 });
1213
+ * if (!resolved) throw new Error('Challenge did not resolve');
1214
+ * }
1215
+ * ```
1216
+ */
1217
+ waitForChallenge(opts?: {
1218
+ timeoutMs?: number;
1219
+ pollMs?: number;
1220
+ }): Promise<ChallengeWaitResult>;
1165
1221
  }
1166
1222
  /**
1167
1223
  * Main entry point for browserclaw.
@@ -1454,4 +1510,42 @@ declare function getRestoredPageForTarget(opts: {
1454
1510
  targetId?: string;
1455
1511
  }): Promise<Page>;
1456
1512
 
1457
- export { type AriaNode, type AriaSnapshotResult, type BatchAction, type BatchActionResult, BrowserClaw, type BrowserNavigationPolicyOptions, type BrowserNavigationRequestLike, type BrowserTab, BrowserTabNotFoundError, type ChromeExecutable, type ChromeKind, type ClickOptions, type ColorScheme, type ConnectOptions, type ConsoleMessage, type ContextState, type CookieData, CrawlPage, type DialogOptions, type DownloadResult, type FormField, type FrameEvalResult, type GeolocationOptions, type HttpCredentials, InvalidBrowserNavigationUrlError, type LaunchOptions, type LookupFn, type NetworkRequest, type PageError, type PinnedHostname, type ResponseBodyResult, type RoleRefInfo, type RoleRefs, type ScreenshotOptions, type SnapshotOptions, type SnapshotResult, type SnapshotStats, type SsrfPolicy, type StorageKind, type TraceStartOptions, type TypeOptions, type UntrustedContentMeta, type WaitOptions, assertBrowserNavigationAllowed, assertBrowserNavigationRedirectChainAllowed, assertBrowserNavigationResultAllowed, assertSafeUploadPaths, batchViaPlaywright, createPinnedLookup, ensureContextState, executeSingleAction, forceDisconnectPlaywrightForTarget, getChromeWebSocketUrl, getRestoredPageForTarget, isChromeCdpReady, isChromeReachable, normalizeCdpHttpBaseForJsonEndpoints, parseRoleRef, requireRef, requireRefOrSelector, requiresInspectableBrowserNavigationRedirects, resolveBoundedDelayMs, resolveInteractionTimeoutMs, resolvePageByTargetIdOrThrow, resolvePinnedHostnameWithPolicy, resolveStrictExistingUploadPaths, sanitizeUntrustedFileName, withBrowserNavigationPolicy, withPageScopedCdpClient, withPlaywrightPageCdpSession, writeViaSiblingTempPath };
1513
+ /**
1514
+ * Comprehensive browser stealth evasions.
1515
+ *
1516
+ * Injected via `addInitScript()` (runs before any page JS) and via
1517
+ * `page.evaluate()` for already-loaded pages. Each patch is wrapped
1518
+ * in try/catch so a single failure never breaks the rest.
1519
+ *
1520
+ * Covers: navigator.webdriver, plugins, languages, window.chrome,
1521
+ * Permissions API, WebGL fingerprint, Notification.permission,
1522
+ * navigator.connection, console toString, headless-mode quirks,
1523
+ * hardwareConcurrency, and deviceMemory.
1524
+ */
1525
+ declare const STEALTH_SCRIPT = "(function() {\n 'use strict';\n function p(fn) { try { fn(); } catch(_) {} }\n\n // \u2500\u2500 1. navigator.webdriver \u2192 undefined \u2500\u2500\n p(function() {\n Object.defineProperty(navigator, 'webdriver', { get: function() { return undefined; }, configurable: true });\n });\n\n // \u2500\u2500 2. navigator.plugins + mimeTypes (only if empty \u2014 Chrome 92+ populates them natively) \u2500\u2500\n p(function() {\n if (navigator.plugins && navigator.plugins.length > 0) return;\n\n function FakePlugin(name, fn, desc, mimes) {\n this.name = name; this.filename = fn; this.description = desc; this.length = mimes.length;\n for (var i = 0; i < mimes.length; i++) { this[i] = mimes[i]; mimes[i].enabledPlugin = this; }\n }\n FakePlugin.prototype.item = function(i) { return this[i] || null; };\n FakePlugin.prototype.namedItem = function(n) {\n for (var i = 0; i < this.length; i++) if (this[i].type === n) return this[i];\n return null;\n };\n\n function M(type, suf, desc) { this.type = type; this.suffixes = suf; this.description = desc; }\n\n var m1 = new M('application/pdf', 'pdf', 'Portable Document Format');\n var m2 = new M('application/x-google-chrome-pdf', 'pdf', 'Portable Document Format');\n var m3 = new M('application/x-nacl', '', 'Native Client Executable');\n var m4 = new M('application/x-pnacl', '', 'Portable Native Client Executable');\n\n var plugins = [\n new FakePlugin('Chrome PDF Plugin', 'internal-pdf-viewer', 'Portable Document Format', [m1]),\n new FakePlugin('Chrome PDF Viewer', 'mhjfbmdgcfjbbpaeojofohoefgiehjai', '', [m2]),\n new FakePlugin('Native Client', 'internal-nacl-plugin', '', [m3, m4]),\n ];\n\n function makeIterable(arr, items) {\n arr.length = items.length;\n for (var i = 0; i < items.length; i++) arr[i] = items[i];\n arr[Symbol.iterator] = function() {\n var idx = 0;\n return { next: function() {\n return idx < items.length ? { value: items[idx++], done: false } : { done: true };\n }};\n };\n }\n\n var pa = { item: function(i) { return plugins[i] || null; },\n namedItem: function(n) { for (var i = 0; i < plugins.length; i++) if (plugins[i].name === n) return plugins[i]; return null; },\n refresh: function() {} };\n makeIterable(pa, plugins);\n Object.defineProperty(navigator, 'plugins', { get: function() { return pa; } });\n\n var allMimes = [m1, m2, m3, m4];\n var ma = { item: function(i) { return allMimes[i] || null; },\n namedItem: function(n) { for (var i = 0; i < allMimes.length; i++) if (allMimes[i].type === n) return allMimes[i]; return null; } };\n makeIterable(ma, allMimes);\n Object.defineProperty(navigator, 'mimeTypes', { get: function() { return ma; } });\n });\n\n // \u2500\u2500 3. navigator.languages (cached + frozen so identity check passes) \u2500\u2500\n p(function() {\n if (!navigator.languages || navigator.languages.length === 0) {\n var langs = Object.freeze(['en-US', 'en']);\n Object.defineProperty(navigator, 'languages', { get: function() { return langs; } });\n }\n });\n\n // \u2500\u2500 4. window.chrome \u2500\u2500\n p(function() {\n if (window.chrome && window.chrome.runtime && window.chrome.runtime.connect) return;\n\n var chrome = window.chrome || {};\n var noop = function() {};\n var evtStub = { addListener: noop, removeListener: noop, hasListeners: function() { return false; } };\n chrome.runtime = chrome.runtime || {};\n chrome.runtime.onMessage = chrome.runtime.onMessage || evtStub;\n chrome.runtime.onConnect = chrome.runtime.onConnect || evtStub;\n chrome.runtime.sendMessage = chrome.runtime.sendMessage || noop;\n chrome.runtime.connect = chrome.runtime.connect || function() {\n return { onMessage: { addListener: noop }, postMessage: noop, disconnect: noop };\n };\n if (chrome.runtime.id === undefined) chrome.runtime.id = undefined;\n if (!chrome.loadTimes) chrome.loadTimes = function() { return {}; };\n if (!chrome.csi) chrome.csi = function() { return {}; };\n if (!chrome.app) {\n chrome.app = {\n isInstalled: false,\n InstallState: { INSTALLED: 'installed', NOT_INSTALLED: 'not_installed', DISABLED: 'disabled' },\n RunningState: { CANNOT_RUN: 'cannot_run', READY_TO_RUN: 'ready_to_run', RUNNING: 'running' },\n getDetails: function() { return null; },\n getIsInstalled: function() { return false; },\n runningState: function() { return 'cannot_run'; },\n };\n }\n\n if (!window.chrome) {\n Object.defineProperty(window, 'chrome', { value: chrome, writable: false, enumerable: true, configurable: false });\n }\n });\n\n // \u2500\u2500 5. Permissions API consistency \u2500\u2500\n p(function() {\n var orig = navigator.permissions.query.bind(navigator.permissions);\n function q(params) {\n if (params.name === 'notifications') {\n return Promise.resolve({\n state: typeof Notification !== 'undefined' ? Notification.permission : 'prompt',\n name: 'notifications', onchange: null,\n addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){ return true; },\n });\n }\n return orig(params);\n }\n q.toString = function() { return 'function query() { [native code] }'; };\n navigator.permissions.query = q;\n });\n\n // \u2500\u2500 6. WebGL vendor / renderer \u2500\u2500\n p(function() {\n var h = {\n apply: function(target, self, args) {\n var param = args[0];\n if (param === 0x9245) return 'Intel Inc.';\n if (param === 0x9246) return 'Intel Iris OpenGL Engine';\n return Reflect.apply(target, self, args);\n }\n };\n if (typeof WebGLRenderingContext !== 'undefined')\n WebGLRenderingContext.prototype.getParameter = new Proxy(WebGLRenderingContext.prototype.getParameter, h);\n if (typeof WebGL2RenderingContext !== 'undefined')\n WebGL2RenderingContext.prototype.getParameter = new Proxy(WebGL2RenderingContext.prototype.getParameter, h);\n });\n\n // \u2500\u2500 7. Notification.permission \u2500\u2500\n p(function() {\n if (typeof Notification !== 'undefined' && Notification.permission === 'denied') {\n Object.defineProperty(Notification, 'permission', { get: function() { return 'default'; }, configurable: true });\n }\n });\n\n // \u2500\u2500 8. navigator.connection (cached so identity check passes) \u2500\u2500\n p(function() {\n if (navigator.connection) return;\n var conn = {\n effectiveType: '4g', rtt: 50, downlink: 10, saveData: false, onchange: null,\n addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){ return true; },\n };\n Object.defineProperty(navigator, 'connection', { get: function() { return conn; } });\n });\n\n // \u2500\u2500 9. Iframe contentWindow.chrome \u2500\u2500\n // Handled by patch 4 \u2014 chrome object is now on window, propagates to iframes on same origin.\n\n // \u2500\u2500 10. console method toString \u2500\u2500\n p(function() {\n ['log','info','warn','error','debug','table','trace'].forEach(function(n) {\n if (console[n]) {\n console[n].toString = function() { return 'function ' + n + '() { [native code] }'; };\n }\n });\n });\n\n // \u2500\u2500 11. Headless-mode window / screen fixes \u2500\u2500\n p(function() {\n if (window.outerWidth === 0)\n Object.defineProperty(window, 'outerWidth', { get: function() { return window.innerWidth || 1920; } });\n if (window.outerHeight === 0)\n Object.defineProperty(window, 'outerHeight', { get: function() { return (window.innerHeight || 1080) + 85; } });\n });\n\n p(function() {\n if (screen.colorDepth === 0) {\n Object.defineProperty(screen, 'colorDepth', { get: function() { return 24; } });\n Object.defineProperty(screen, 'pixelDepth', { get: function() { return 24; } });\n }\n });\n\n // \u2500\u2500 12. navigator.hardwareConcurrency \u2500\u2500\n p(function() {\n if (!navigator.hardwareConcurrency)\n Object.defineProperty(navigator, 'hardwareConcurrency', { get: function() { return 4; } });\n });\n\n // \u2500\u2500 13. navigator.deviceMemory \u2500\u2500\n p(function() {\n if (!navigator.deviceMemory)\n Object.defineProperty(navigator, 'deviceMemory', { get: function() { return 8; } });\n });\n})()";
1526
+
1527
+ /**
1528
+ * Detect whether the current page is showing an anti-bot challenge.
1529
+ * Returns `null` if no challenge is detected.
1530
+ */
1531
+ declare function detectChallengeViaPlaywright(opts: {
1532
+ cdpUrl: string;
1533
+ targetId?: string;
1534
+ }): Promise<ChallengeInfo | null>;
1535
+ /**
1536
+ * Wait for an anti-bot challenge to resolve on its own (e.g. Cloudflare JS challenge).
1537
+ *
1538
+ * Returns `{ resolved: true }` if the challenge cleared within the timeout,
1539
+ * or `{ resolved: false, challenge }` with the still-present challenge info.
1540
+ *
1541
+ * For challenges that require human interaction (CAPTCHA), this will time out
1542
+ * unless the user solves the challenge in the visible browser window.
1543
+ */
1544
+ declare function waitForChallengeViaPlaywright(opts: {
1545
+ cdpUrl: string;
1546
+ targetId?: string;
1547
+ timeoutMs?: number;
1548
+ pollMs?: number;
1549
+ }): Promise<ChallengeWaitResult>;
1550
+
1551
+ export { type AriaNode, type AriaSnapshotResult, type BatchAction, type BatchActionResult, BrowserClaw, type BrowserNavigationPolicyOptions, type BrowserNavigationRequestLike, type BrowserTab, BrowserTabNotFoundError, type ChallengeInfo, type ChallengeKind, type ChallengeWaitResult, type ChromeExecutable, type ChromeKind, type ClickOptions, type ColorScheme, type ConnectOptions, type ConsoleMessage, type ContextState, type CookieData, CrawlPage, type DialogOptions, type DownloadResult, type FormField, type FrameEvalResult, type GeolocationOptions, type HttpCredentials, InvalidBrowserNavigationUrlError, type LaunchOptions, type LookupFn, type NetworkRequest, type PageError, type PinnedHostname, type ResponseBodyResult, type RoleRefInfo, type RoleRefs, STEALTH_SCRIPT, type ScreenshotOptions, type SnapshotOptions, type SnapshotResult, type SnapshotStats, type SsrfPolicy, type StorageKind, type TraceStartOptions, type TypeOptions, type UntrustedContentMeta, type WaitOptions, assertBrowserNavigationAllowed, assertBrowserNavigationRedirectChainAllowed, assertBrowserNavigationResultAllowed, assertSafeUploadPaths, batchViaPlaywright, createPinnedLookup, detectChallengeViaPlaywright, ensureContextState, executeSingleAction, forceDisconnectPlaywrightForTarget, getChromeWebSocketUrl, getRestoredPageForTarget, isChromeCdpReady, isChromeReachable, normalizeCdpHttpBaseForJsonEndpoints, parseRoleRef, requireRef, requireRefOrSelector, requiresInspectableBrowserNavigationRedirects, resolveBoundedDelayMs, resolveInteractionTimeoutMs, resolvePageByTargetIdOrThrow, resolvePinnedHostnameWithPolicy, resolveStrictExistingUploadPaths, sanitizeUntrustedFileName, waitForChallengeViaPlaywright, withBrowserNavigationPolicy, withPageScopedCdpClient, withPlaywrightPageCdpSession, writeViaSiblingTempPath };
package/dist/index.d.ts CHANGED
@@ -545,6 +545,22 @@ interface HttpCredentials {
545
545
  interface ContextState {
546
546
  traceActive: boolean;
547
547
  }
548
+ /** The kind of anti-bot challenge detected on a page. */
549
+ type ChallengeKind = 'cloudflare-js' | 'cloudflare-block' | 'cloudflare-turnstile' | 'hcaptcha' | 'recaptcha' | 'blocked' | 'rate-limited';
550
+ /** Information about a detected anti-bot challenge. */
551
+ interface ChallengeInfo {
552
+ /** What type of challenge is present */
553
+ kind: ChallengeKind;
554
+ /** Human-readable description */
555
+ message: string;
556
+ }
557
+ /** Result of waiting for an anti-bot challenge to resolve. */
558
+ interface ChallengeWaitResult {
559
+ /** Whether the challenge cleared within the timeout */
560
+ resolved: boolean;
561
+ /** The challenge still present (null if resolved) */
562
+ challenge: ChallengeInfo | null;
563
+ }
548
564
  /** Result of DNS pinning resolution — hostname locked to resolved addresses. */
549
565
  interface PinnedHostname {
550
566
  hostname: string;
@@ -1162,6 +1178,46 @@ declare class CrawlPage {
1162
1178
  * ```
1163
1179
  */
1164
1180
  setDevice(name: string): Promise<void>;
1181
+ /**
1182
+ * Detect whether the page is showing an anti-bot challenge
1183
+ * (Cloudflare, hCaptcha, reCAPTCHA, access-denied, rate-limit, etc.).
1184
+ *
1185
+ * Returns `null` if no challenge is detected.
1186
+ *
1187
+ * @example
1188
+ * ```ts
1189
+ * const challenge = await page.detectChallenge();
1190
+ * if (challenge) {
1191
+ * console.log(challenge.kind); // 'cloudflare-js'
1192
+ * console.log(challenge.message); // 'Cloudflare JS challenge'
1193
+ * }
1194
+ * ```
1195
+ */
1196
+ detectChallenge(): Promise<ChallengeInfo | null>;
1197
+ /**
1198
+ * Wait for an anti-bot challenge to resolve on its own.
1199
+ *
1200
+ * Cloudflare JS challenges typically auto-resolve in ~5 seconds.
1201
+ * CAPTCHA challenges will only resolve if solved in a visible browser window.
1202
+ *
1203
+ * @param opts.timeoutMs - Maximum wait time (default: `15000`)
1204
+ * @param opts.pollMs - Poll interval (default: `500`)
1205
+ * @returns Whether the challenge resolved, and the remaining challenge info if not
1206
+ *
1207
+ * @example
1208
+ * ```ts
1209
+ * await page.goto('https://example.com');
1210
+ * const challenge = await page.detectChallenge();
1211
+ * if (challenge?.kind === 'cloudflare-js') {
1212
+ * const { resolved } = await page.waitForChallenge({ timeoutMs: 20000 });
1213
+ * if (!resolved) throw new Error('Challenge did not resolve');
1214
+ * }
1215
+ * ```
1216
+ */
1217
+ waitForChallenge(opts?: {
1218
+ timeoutMs?: number;
1219
+ pollMs?: number;
1220
+ }): Promise<ChallengeWaitResult>;
1165
1221
  }
1166
1222
  /**
1167
1223
  * Main entry point for browserclaw.
@@ -1454,4 +1510,42 @@ declare function getRestoredPageForTarget(opts: {
1454
1510
  targetId?: string;
1455
1511
  }): Promise<Page>;
1456
1512
 
1457
- export { type AriaNode, type AriaSnapshotResult, type BatchAction, type BatchActionResult, BrowserClaw, type BrowserNavigationPolicyOptions, type BrowserNavigationRequestLike, type BrowserTab, BrowserTabNotFoundError, type ChromeExecutable, type ChromeKind, type ClickOptions, type ColorScheme, type ConnectOptions, type ConsoleMessage, type ContextState, type CookieData, CrawlPage, type DialogOptions, type DownloadResult, type FormField, type FrameEvalResult, type GeolocationOptions, type HttpCredentials, InvalidBrowserNavigationUrlError, type LaunchOptions, type LookupFn, type NetworkRequest, type PageError, type PinnedHostname, type ResponseBodyResult, type RoleRefInfo, type RoleRefs, type ScreenshotOptions, type SnapshotOptions, type SnapshotResult, type SnapshotStats, type SsrfPolicy, type StorageKind, type TraceStartOptions, type TypeOptions, type UntrustedContentMeta, type WaitOptions, assertBrowserNavigationAllowed, assertBrowserNavigationRedirectChainAllowed, assertBrowserNavigationResultAllowed, assertSafeUploadPaths, batchViaPlaywright, createPinnedLookup, ensureContextState, executeSingleAction, forceDisconnectPlaywrightForTarget, getChromeWebSocketUrl, getRestoredPageForTarget, isChromeCdpReady, isChromeReachable, normalizeCdpHttpBaseForJsonEndpoints, parseRoleRef, requireRef, requireRefOrSelector, requiresInspectableBrowserNavigationRedirects, resolveBoundedDelayMs, resolveInteractionTimeoutMs, resolvePageByTargetIdOrThrow, resolvePinnedHostnameWithPolicy, resolveStrictExistingUploadPaths, sanitizeUntrustedFileName, withBrowserNavigationPolicy, withPageScopedCdpClient, withPlaywrightPageCdpSession, writeViaSiblingTempPath };
1513
+ /**
1514
+ * Comprehensive browser stealth evasions.
1515
+ *
1516
+ * Injected via `addInitScript()` (runs before any page JS) and via
1517
+ * `page.evaluate()` for already-loaded pages. Each patch is wrapped
1518
+ * in try/catch so a single failure never breaks the rest.
1519
+ *
1520
+ * Covers: navigator.webdriver, plugins, languages, window.chrome,
1521
+ * Permissions API, WebGL fingerprint, Notification.permission,
1522
+ * navigator.connection, console toString, headless-mode quirks,
1523
+ * hardwareConcurrency, and deviceMemory.
1524
+ */
1525
+ declare const STEALTH_SCRIPT = "(function() {\n 'use strict';\n function p(fn) { try { fn(); } catch(_) {} }\n\n // \u2500\u2500 1. navigator.webdriver \u2192 undefined \u2500\u2500\n p(function() {\n Object.defineProperty(navigator, 'webdriver', { get: function() { return undefined; }, configurable: true });\n });\n\n // \u2500\u2500 2. navigator.plugins + mimeTypes (only if empty \u2014 Chrome 92+ populates them natively) \u2500\u2500\n p(function() {\n if (navigator.plugins && navigator.plugins.length > 0) return;\n\n function FakePlugin(name, fn, desc, mimes) {\n this.name = name; this.filename = fn; this.description = desc; this.length = mimes.length;\n for (var i = 0; i < mimes.length; i++) { this[i] = mimes[i]; mimes[i].enabledPlugin = this; }\n }\n FakePlugin.prototype.item = function(i) { return this[i] || null; };\n FakePlugin.prototype.namedItem = function(n) {\n for (var i = 0; i < this.length; i++) if (this[i].type === n) return this[i];\n return null;\n };\n\n function M(type, suf, desc) { this.type = type; this.suffixes = suf; this.description = desc; }\n\n var m1 = new M('application/pdf', 'pdf', 'Portable Document Format');\n var m2 = new M('application/x-google-chrome-pdf', 'pdf', 'Portable Document Format');\n var m3 = new M('application/x-nacl', '', 'Native Client Executable');\n var m4 = new M('application/x-pnacl', '', 'Portable Native Client Executable');\n\n var plugins = [\n new FakePlugin('Chrome PDF Plugin', 'internal-pdf-viewer', 'Portable Document Format', [m1]),\n new FakePlugin('Chrome PDF Viewer', 'mhjfbmdgcfjbbpaeojofohoefgiehjai', '', [m2]),\n new FakePlugin('Native Client', 'internal-nacl-plugin', '', [m3, m4]),\n ];\n\n function makeIterable(arr, items) {\n arr.length = items.length;\n for (var i = 0; i < items.length; i++) arr[i] = items[i];\n arr[Symbol.iterator] = function() {\n var idx = 0;\n return { next: function() {\n return idx < items.length ? { value: items[idx++], done: false } : { done: true };\n }};\n };\n }\n\n var pa = { item: function(i) { return plugins[i] || null; },\n namedItem: function(n) { for (var i = 0; i < plugins.length; i++) if (plugins[i].name === n) return plugins[i]; return null; },\n refresh: function() {} };\n makeIterable(pa, plugins);\n Object.defineProperty(navigator, 'plugins', { get: function() { return pa; } });\n\n var allMimes = [m1, m2, m3, m4];\n var ma = { item: function(i) { return allMimes[i] || null; },\n namedItem: function(n) { for (var i = 0; i < allMimes.length; i++) if (allMimes[i].type === n) return allMimes[i]; return null; } };\n makeIterable(ma, allMimes);\n Object.defineProperty(navigator, 'mimeTypes', { get: function() { return ma; } });\n });\n\n // \u2500\u2500 3. navigator.languages (cached + frozen so identity check passes) \u2500\u2500\n p(function() {\n if (!navigator.languages || navigator.languages.length === 0) {\n var langs = Object.freeze(['en-US', 'en']);\n Object.defineProperty(navigator, 'languages', { get: function() { return langs; } });\n }\n });\n\n // \u2500\u2500 4. window.chrome \u2500\u2500\n p(function() {\n if (window.chrome && window.chrome.runtime && window.chrome.runtime.connect) return;\n\n var chrome = window.chrome || {};\n var noop = function() {};\n var evtStub = { addListener: noop, removeListener: noop, hasListeners: function() { return false; } };\n chrome.runtime = chrome.runtime || {};\n chrome.runtime.onMessage = chrome.runtime.onMessage || evtStub;\n chrome.runtime.onConnect = chrome.runtime.onConnect || evtStub;\n chrome.runtime.sendMessage = chrome.runtime.sendMessage || noop;\n chrome.runtime.connect = chrome.runtime.connect || function() {\n return { onMessage: { addListener: noop }, postMessage: noop, disconnect: noop };\n };\n if (chrome.runtime.id === undefined) chrome.runtime.id = undefined;\n if (!chrome.loadTimes) chrome.loadTimes = function() { return {}; };\n if (!chrome.csi) chrome.csi = function() { return {}; };\n if (!chrome.app) {\n chrome.app = {\n isInstalled: false,\n InstallState: { INSTALLED: 'installed', NOT_INSTALLED: 'not_installed', DISABLED: 'disabled' },\n RunningState: { CANNOT_RUN: 'cannot_run', READY_TO_RUN: 'ready_to_run', RUNNING: 'running' },\n getDetails: function() { return null; },\n getIsInstalled: function() { return false; },\n runningState: function() { return 'cannot_run'; },\n };\n }\n\n if (!window.chrome) {\n Object.defineProperty(window, 'chrome', { value: chrome, writable: false, enumerable: true, configurable: false });\n }\n });\n\n // \u2500\u2500 5. Permissions API consistency \u2500\u2500\n p(function() {\n var orig = navigator.permissions.query.bind(navigator.permissions);\n function q(params) {\n if (params.name === 'notifications') {\n return Promise.resolve({\n state: typeof Notification !== 'undefined' ? Notification.permission : 'prompt',\n name: 'notifications', onchange: null,\n addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){ return true; },\n });\n }\n return orig(params);\n }\n q.toString = function() { return 'function query() { [native code] }'; };\n navigator.permissions.query = q;\n });\n\n // \u2500\u2500 6. WebGL vendor / renderer \u2500\u2500\n p(function() {\n var h = {\n apply: function(target, self, args) {\n var param = args[0];\n if (param === 0x9245) return 'Intel Inc.';\n if (param === 0x9246) return 'Intel Iris OpenGL Engine';\n return Reflect.apply(target, self, args);\n }\n };\n if (typeof WebGLRenderingContext !== 'undefined')\n WebGLRenderingContext.prototype.getParameter = new Proxy(WebGLRenderingContext.prototype.getParameter, h);\n if (typeof WebGL2RenderingContext !== 'undefined')\n WebGL2RenderingContext.prototype.getParameter = new Proxy(WebGL2RenderingContext.prototype.getParameter, h);\n });\n\n // \u2500\u2500 7. Notification.permission \u2500\u2500\n p(function() {\n if (typeof Notification !== 'undefined' && Notification.permission === 'denied') {\n Object.defineProperty(Notification, 'permission', { get: function() { return 'default'; }, configurable: true });\n }\n });\n\n // \u2500\u2500 8. navigator.connection (cached so identity check passes) \u2500\u2500\n p(function() {\n if (navigator.connection) return;\n var conn = {\n effectiveType: '4g', rtt: 50, downlink: 10, saveData: false, onchange: null,\n addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){ return true; },\n };\n Object.defineProperty(navigator, 'connection', { get: function() { return conn; } });\n });\n\n // \u2500\u2500 9. Iframe contentWindow.chrome \u2500\u2500\n // Handled by patch 4 \u2014 chrome object is now on window, propagates to iframes on same origin.\n\n // \u2500\u2500 10. console method toString \u2500\u2500\n p(function() {\n ['log','info','warn','error','debug','table','trace'].forEach(function(n) {\n if (console[n]) {\n console[n].toString = function() { return 'function ' + n + '() { [native code] }'; };\n }\n });\n });\n\n // \u2500\u2500 11. Headless-mode window / screen fixes \u2500\u2500\n p(function() {\n if (window.outerWidth === 0)\n Object.defineProperty(window, 'outerWidth', { get: function() { return window.innerWidth || 1920; } });\n if (window.outerHeight === 0)\n Object.defineProperty(window, 'outerHeight', { get: function() { return (window.innerHeight || 1080) + 85; } });\n });\n\n p(function() {\n if (screen.colorDepth === 0) {\n Object.defineProperty(screen, 'colorDepth', { get: function() { return 24; } });\n Object.defineProperty(screen, 'pixelDepth', { get: function() { return 24; } });\n }\n });\n\n // \u2500\u2500 12. navigator.hardwareConcurrency \u2500\u2500\n p(function() {\n if (!navigator.hardwareConcurrency)\n Object.defineProperty(navigator, 'hardwareConcurrency', { get: function() { return 4; } });\n });\n\n // \u2500\u2500 13. navigator.deviceMemory \u2500\u2500\n p(function() {\n if (!navigator.deviceMemory)\n Object.defineProperty(navigator, 'deviceMemory', { get: function() { return 8; } });\n });\n})()";
1526
+
1527
+ /**
1528
+ * Detect whether the current page is showing an anti-bot challenge.
1529
+ * Returns `null` if no challenge is detected.
1530
+ */
1531
+ declare function detectChallengeViaPlaywright(opts: {
1532
+ cdpUrl: string;
1533
+ targetId?: string;
1534
+ }): Promise<ChallengeInfo | null>;
1535
+ /**
1536
+ * Wait for an anti-bot challenge to resolve on its own (e.g. Cloudflare JS challenge).
1537
+ *
1538
+ * Returns `{ resolved: true }` if the challenge cleared within the timeout,
1539
+ * or `{ resolved: false, challenge }` with the still-present challenge info.
1540
+ *
1541
+ * For challenges that require human interaction (CAPTCHA), this will time out
1542
+ * unless the user solves the challenge in the visible browser window.
1543
+ */
1544
+ declare function waitForChallengeViaPlaywright(opts: {
1545
+ cdpUrl: string;
1546
+ targetId?: string;
1547
+ timeoutMs?: number;
1548
+ pollMs?: number;
1549
+ }): Promise<ChallengeWaitResult>;
1550
+
1551
+ export { type AriaNode, type AriaSnapshotResult, type BatchAction, type BatchActionResult, BrowserClaw, type BrowserNavigationPolicyOptions, type BrowserNavigationRequestLike, type BrowserTab, BrowserTabNotFoundError, type ChallengeInfo, type ChallengeKind, type ChallengeWaitResult, type ChromeExecutable, type ChromeKind, type ClickOptions, type ColorScheme, type ConnectOptions, type ConsoleMessage, type ContextState, type CookieData, CrawlPage, type DialogOptions, type DownloadResult, type FormField, type FrameEvalResult, type GeolocationOptions, type HttpCredentials, InvalidBrowserNavigationUrlError, type LaunchOptions, type LookupFn, type NetworkRequest, type PageError, type PinnedHostname, type ResponseBodyResult, type RoleRefInfo, type RoleRefs, STEALTH_SCRIPT, type ScreenshotOptions, type SnapshotOptions, type SnapshotResult, type SnapshotStats, type SsrfPolicy, type StorageKind, type TraceStartOptions, type TypeOptions, type UntrustedContentMeta, type WaitOptions, assertBrowserNavigationAllowed, assertBrowserNavigationRedirectChainAllowed, assertBrowserNavigationResultAllowed, assertSafeUploadPaths, batchViaPlaywright, createPinnedLookup, detectChallengeViaPlaywright, ensureContextState, executeSingleAction, forceDisconnectPlaywrightForTarget, getChromeWebSocketUrl, getRestoredPageForTarget, isChromeCdpReady, isChromeReachable, normalizeCdpHttpBaseForJsonEndpoints, parseRoleRef, requireRef, requireRefOrSelector, requiresInspectableBrowserNavigationRedirects, resolveBoundedDelayMs, resolveInteractionTimeoutMs, resolvePageByTargetIdOrThrow, resolvePinnedHostnameWithPolicy, resolveStrictExistingUploadPaths, sanitizeUntrustedFileName, waitForChallengeViaPlaywright, withBrowserNavigationPolicy, withPageScopedCdpClient, withPlaywrightPageCdpSession, writeViaSiblingTempPath };
package/dist/index.js CHANGED
@@ -1284,7 +1284,7 @@ async function fetchChromeVersion(cdpUrl, timeoutMs = 500, authToken) {
1284
1284
  async function isChromeReachable(cdpUrl, timeoutMs = 500, authToken) {
1285
1285
  if (isWebSocketUrl(cdpUrl)) return await canOpenWebSocket(cdpUrl, timeoutMs);
1286
1286
  const version = await fetchChromeVersion(cdpUrl, timeoutMs, authToken);
1287
- return Boolean(version);
1287
+ return version !== null;
1288
1288
  }
1289
1289
  async function getChromeWebSocketUrl(cdpUrl, timeoutMs = 500, authToken) {
1290
1290
  if (isWebSocketUrl(cdpUrl)) return cdpUrl;
@@ -1476,6 +1476,198 @@ async function stopChrome(running, timeoutMs = 2500) {
1476
1476
  }
1477
1477
  }
1478
1478
 
1479
+ // src/stealth.ts
1480
+ var STEALTH_SCRIPT = `(function() {
1481
+ 'use strict';
1482
+ function p(fn) { try { fn(); } catch(_) {} }
1483
+
1484
+ // \u2500\u2500 1. navigator.webdriver \u2192 undefined \u2500\u2500
1485
+ p(function() {
1486
+ Object.defineProperty(navigator, 'webdriver', { get: function() { return undefined; }, configurable: true });
1487
+ });
1488
+
1489
+ // \u2500\u2500 2. navigator.plugins + mimeTypes (only if empty \u2014 Chrome 92+ populates them natively) \u2500\u2500
1490
+ p(function() {
1491
+ if (navigator.plugins && navigator.plugins.length > 0) return;
1492
+
1493
+ function FakePlugin(name, fn, desc, mimes) {
1494
+ this.name = name; this.filename = fn; this.description = desc; this.length = mimes.length;
1495
+ for (var i = 0; i < mimes.length; i++) { this[i] = mimes[i]; mimes[i].enabledPlugin = this; }
1496
+ }
1497
+ FakePlugin.prototype.item = function(i) { return this[i] || null; };
1498
+ FakePlugin.prototype.namedItem = function(n) {
1499
+ for (var i = 0; i < this.length; i++) if (this[i].type === n) return this[i];
1500
+ return null;
1501
+ };
1502
+
1503
+ function M(type, suf, desc) { this.type = type; this.suffixes = suf; this.description = desc; }
1504
+
1505
+ var m1 = new M('application/pdf', 'pdf', 'Portable Document Format');
1506
+ var m2 = new M('application/x-google-chrome-pdf', 'pdf', 'Portable Document Format');
1507
+ var m3 = new M('application/x-nacl', '', 'Native Client Executable');
1508
+ var m4 = new M('application/x-pnacl', '', 'Portable Native Client Executable');
1509
+
1510
+ var plugins = [
1511
+ new FakePlugin('Chrome PDF Plugin', 'internal-pdf-viewer', 'Portable Document Format', [m1]),
1512
+ new FakePlugin('Chrome PDF Viewer', 'mhjfbmdgcfjbbpaeojofohoefgiehjai', '', [m2]),
1513
+ new FakePlugin('Native Client', 'internal-nacl-plugin', '', [m3, m4]),
1514
+ ];
1515
+
1516
+ function makeIterable(arr, items) {
1517
+ arr.length = items.length;
1518
+ for (var i = 0; i < items.length; i++) arr[i] = items[i];
1519
+ arr[Symbol.iterator] = function() {
1520
+ var idx = 0;
1521
+ return { next: function() {
1522
+ return idx < items.length ? { value: items[idx++], done: false } : { done: true };
1523
+ }};
1524
+ };
1525
+ }
1526
+
1527
+ var pa = { item: function(i) { return plugins[i] || null; },
1528
+ namedItem: function(n) { for (var i = 0; i < plugins.length; i++) if (plugins[i].name === n) return plugins[i]; return null; },
1529
+ refresh: function() {} };
1530
+ makeIterable(pa, plugins);
1531
+ Object.defineProperty(navigator, 'plugins', { get: function() { return pa; } });
1532
+
1533
+ var allMimes = [m1, m2, m3, m4];
1534
+ var ma = { item: function(i) { return allMimes[i] || null; },
1535
+ namedItem: function(n) { for (var i = 0; i < allMimes.length; i++) if (allMimes[i].type === n) return allMimes[i]; return null; } };
1536
+ makeIterable(ma, allMimes);
1537
+ Object.defineProperty(navigator, 'mimeTypes', { get: function() { return ma; } });
1538
+ });
1539
+
1540
+ // \u2500\u2500 3. navigator.languages (cached + frozen so identity check passes) \u2500\u2500
1541
+ p(function() {
1542
+ if (!navigator.languages || navigator.languages.length === 0) {
1543
+ var langs = Object.freeze(['en-US', 'en']);
1544
+ Object.defineProperty(navigator, 'languages', { get: function() { return langs; } });
1545
+ }
1546
+ });
1547
+
1548
+ // \u2500\u2500 4. window.chrome \u2500\u2500
1549
+ p(function() {
1550
+ if (window.chrome && window.chrome.runtime && window.chrome.runtime.connect) return;
1551
+
1552
+ var chrome = window.chrome || {};
1553
+ var noop = function() {};
1554
+ var evtStub = { addListener: noop, removeListener: noop, hasListeners: function() { return false; } };
1555
+ chrome.runtime = chrome.runtime || {};
1556
+ chrome.runtime.onMessage = chrome.runtime.onMessage || evtStub;
1557
+ chrome.runtime.onConnect = chrome.runtime.onConnect || evtStub;
1558
+ chrome.runtime.sendMessage = chrome.runtime.sendMessage || noop;
1559
+ chrome.runtime.connect = chrome.runtime.connect || function() {
1560
+ return { onMessage: { addListener: noop }, postMessage: noop, disconnect: noop };
1561
+ };
1562
+ if (chrome.runtime.id === undefined) chrome.runtime.id = undefined;
1563
+ if (!chrome.loadTimes) chrome.loadTimes = function() { return {}; };
1564
+ if (!chrome.csi) chrome.csi = function() { return {}; };
1565
+ if (!chrome.app) {
1566
+ chrome.app = {
1567
+ isInstalled: false,
1568
+ InstallState: { INSTALLED: 'installed', NOT_INSTALLED: 'not_installed', DISABLED: 'disabled' },
1569
+ RunningState: { CANNOT_RUN: 'cannot_run', READY_TO_RUN: 'ready_to_run', RUNNING: 'running' },
1570
+ getDetails: function() { return null; },
1571
+ getIsInstalled: function() { return false; },
1572
+ runningState: function() { return 'cannot_run'; },
1573
+ };
1574
+ }
1575
+
1576
+ if (!window.chrome) {
1577
+ Object.defineProperty(window, 'chrome', { value: chrome, writable: false, enumerable: true, configurable: false });
1578
+ }
1579
+ });
1580
+
1581
+ // \u2500\u2500 5. Permissions API consistency \u2500\u2500
1582
+ p(function() {
1583
+ var orig = navigator.permissions.query.bind(navigator.permissions);
1584
+ function q(params) {
1585
+ if (params.name === 'notifications') {
1586
+ return Promise.resolve({
1587
+ state: typeof Notification !== 'undefined' ? Notification.permission : 'prompt',
1588
+ name: 'notifications', onchange: null,
1589
+ addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){ return true; },
1590
+ });
1591
+ }
1592
+ return orig(params);
1593
+ }
1594
+ q.toString = function() { return 'function query() { [native code] }'; };
1595
+ navigator.permissions.query = q;
1596
+ });
1597
+
1598
+ // \u2500\u2500 6. WebGL vendor / renderer \u2500\u2500
1599
+ p(function() {
1600
+ var h = {
1601
+ apply: function(target, self, args) {
1602
+ var param = args[0];
1603
+ if (param === 0x9245) return 'Intel Inc.';
1604
+ if (param === 0x9246) return 'Intel Iris OpenGL Engine';
1605
+ return Reflect.apply(target, self, args);
1606
+ }
1607
+ };
1608
+ if (typeof WebGLRenderingContext !== 'undefined')
1609
+ WebGLRenderingContext.prototype.getParameter = new Proxy(WebGLRenderingContext.prototype.getParameter, h);
1610
+ if (typeof WebGL2RenderingContext !== 'undefined')
1611
+ WebGL2RenderingContext.prototype.getParameter = new Proxy(WebGL2RenderingContext.prototype.getParameter, h);
1612
+ });
1613
+
1614
+ // \u2500\u2500 7. Notification.permission \u2500\u2500
1615
+ p(function() {
1616
+ if (typeof Notification !== 'undefined' && Notification.permission === 'denied') {
1617
+ Object.defineProperty(Notification, 'permission', { get: function() { return 'default'; }, configurable: true });
1618
+ }
1619
+ });
1620
+
1621
+ // \u2500\u2500 8. navigator.connection (cached so identity check passes) \u2500\u2500
1622
+ p(function() {
1623
+ if (navigator.connection) return;
1624
+ var conn = {
1625
+ effectiveType: '4g', rtt: 50, downlink: 10, saveData: false, onchange: null,
1626
+ addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){ return true; },
1627
+ };
1628
+ Object.defineProperty(navigator, 'connection', { get: function() { return conn; } });
1629
+ });
1630
+
1631
+ // \u2500\u2500 9. Iframe contentWindow.chrome \u2500\u2500
1632
+ // Handled by patch 4 \u2014 chrome object is now on window, propagates to iframes on same origin.
1633
+
1634
+ // \u2500\u2500 10. console method toString \u2500\u2500
1635
+ p(function() {
1636
+ ['log','info','warn','error','debug','table','trace'].forEach(function(n) {
1637
+ if (console[n]) {
1638
+ console[n].toString = function() { return 'function ' + n + '() { [native code] }'; };
1639
+ }
1640
+ });
1641
+ });
1642
+
1643
+ // \u2500\u2500 11. Headless-mode window / screen fixes \u2500\u2500
1644
+ p(function() {
1645
+ if (window.outerWidth === 0)
1646
+ Object.defineProperty(window, 'outerWidth', { get: function() { return window.innerWidth || 1920; } });
1647
+ if (window.outerHeight === 0)
1648
+ Object.defineProperty(window, 'outerHeight', { get: function() { return (window.innerHeight || 1080) + 85; } });
1649
+ });
1650
+
1651
+ p(function() {
1652
+ if (screen.colorDepth === 0) {
1653
+ Object.defineProperty(screen, 'colorDepth', { get: function() { return 24; } });
1654
+ Object.defineProperty(screen, 'pixelDepth', { get: function() { return 24; } });
1655
+ }
1656
+ });
1657
+
1658
+ // \u2500\u2500 12. navigator.hardwareConcurrency \u2500\u2500
1659
+ p(function() {
1660
+ if (!navigator.hardwareConcurrency)
1661
+ Object.defineProperty(navigator, 'hardwareConcurrency', { get: function() { return 4; } });
1662
+ });
1663
+
1664
+ // \u2500\u2500 13. navigator.deviceMemory \u2500\u2500
1665
+ p(function() {
1666
+ if (!navigator.deviceMemory)
1667
+ Object.defineProperty(navigator, 'deviceMemory', { get: function() { return 8; } });
1668
+ });
1669
+ })()`;
1670
+
1479
1671
  // src/connection.ts
1480
1672
  var BrowserTabNotFoundError = class extends Error {
1481
1673
  constructor(message = "Tab not found") {
@@ -1716,7 +1908,6 @@ function ensurePageState(page) {
1716
1908
  }
1717
1909
  return state;
1718
1910
  }
1719
- var STEALTH_SCRIPT = `Object.defineProperty(navigator, 'webdriver', { get: () => undefined })`;
1720
1911
  function applyStealthToPage(page) {
1721
1912
  page.evaluate(STEALTH_SCRIPT).catch((e) => {
1722
1913
  if (process.env.DEBUG !== void 0 && process.env.DEBUG !== "")
@@ -1838,6 +2029,8 @@ async function disconnectBrowser() {
1838
2029
  }
1839
2030
  }
1840
2031
  for (const cur of cachedByCdpUrl.values()) {
2032
+ if (cur.onDisconnected && typeof cur.browser.off === "function")
2033
+ cur.browser.off("disconnected", cur.onDisconnected);
1841
2034
  await cur.browser.close().catch(() => {
1842
2035
  });
1843
2036
  }
@@ -3536,6 +3729,99 @@ async function setTimezoneViaPlaywright(opts) {
3536
3729
  });
3537
3730
  }
3538
3731
 
3732
+ // src/anti-bot.ts
3733
+ var DETECT_CHALLENGE_SCRIPT = `(function() {
3734
+ var title = (document.title || '').toLowerCase();
3735
+
3736
+ // Cloudflare JS challenge
3737
+ if (title === 'just a moment...'
3738
+ || document.querySelector('#challenge-running, #cf-please-wait, #challenge-form')
3739
+ || title.indexOf('checking your browser') !== -1) {
3740
+ return { kind: 'cloudflare-js', message: 'Cloudflare JS challenge' };
3741
+ }
3742
+
3743
+ // Cloudflare block page (needs body text \u2014 read lazily)
3744
+ var body = null;
3745
+ function getBody() { if (body === null) body = (document.body && document.body.textContent) || ''; return body; }
3746
+
3747
+ if (title.indexOf('attention required') !== -1
3748
+ || (document.querySelector('.cf-error-details') && getBody().indexOf('blocked') !== -1)) {
3749
+ return { kind: 'cloudflare-block', message: 'Cloudflare block page' };
3750
+ }
3751
+
3752
+ // Cloudflare Turnstile
3753
+ if (document.querySelector('.cf-turnstile, iframe[src*="challenges.cloudflare.com"]')) {
3754
+ return { kind: 'cloudflare-turnstile', message: 'Cloudflare Turnstile challenge' };
3755
+ }
3756
+
3757
+ // hCaptcha
3758
+ if (document.querySelector('.h-captcha, iframe[src*="hcaptcha.com"]')) {
3759
+ return { kind: 'hcaptcha', message: 'hCaptcha challenge' };
3760
+ }
3761
+
3762
+ // reCAPTCHA
3763
+ if (document.querySelector('.g-recaptcha, iframe[src*="google.com/recaptcha"]')) {
3764
+ return { kind: 'recaptcha', message: 'reCAPTCHA challenge' };
3765
+ }
3766
+
3767
+ // Generic access-denied / rate-limit pages (only read body for short pages)
3768
+ var b = getBody();
3769
+ if (b.length < 5000) {
3770
+ if (/access denied|403 forbidden/i.test(title) || /access denied/i.test(b)) {
3771
+ return { kind: 'blocked', message: 'Access denied' };
3772
+ }
3773
+ if (/\\b429\\b/i.test(title) || /too many requests|rate limit/i.test(b)) {
3774
+ return { kind: 'rate-limited', message: 'Rate limited' };
3775
+ }
3776
+ }
3777
+
3778
+ return null;
3779
+ })()`;
3780
+ function parseChallengeResult(raw) {
3781
+ if (raw !== null && typeof raw === "object" && "kind" in raw) {
3782
+ return raw;
3783
+ }
3784
+ return null;
3785
+ }
3786
+ async function detectChallengeViaPlaywright(opts) {
3787
+ const page = await getPageForTargetId({ cdpUrl: opts.cdpUrl, targetId: opts.targetId });
3788
+ ensurePageState(page);
3789
+ return parseChallengeResult(await page.evaluate(DETECT_CHALLENGE_SCRIPT));
3790
+ }
3791
+ async function waitForChallengeViaPlaywright(opts) {
3792
+ const page = await getPageForTargetId({ cdpUrl: opts.cdpUrl, targetId: opts.targetId });
3793
+ ensurePageState(page);
3794
+ const timeout = normalizeTimeoutMs(opts.timeoutMs, 15e3);
3795
+ const poll = Math.max(250, Math.min(5e3, opts.pollMs ?? 500));
3796
+ const detect = async () => parseChallengeResult(await page.evaluate(DETECT_CHALLENGE_SCRIPT));
3797
+ const initial = await detect();
3798
+ if (initial === null) return { resolved: true, challenge: null };
3799
+ if (initial.kind === "cloudflare-js") {
3800
+ try {
3801
+ await page.waitForFunction(
3802
+ "document.title.toLowerCase() !== 'just a moment...' && !document.querySelector('#challenge-running')",
3803
+ void 0,
3804
+ { timeout }
3805
+ );
3806
+ await page.waitForLoadState("domcontentloaded", { timeout: 5e3 }).catch(() => {
3807
+ });
3808
+ const after = await detect();
3809
+ return { resolved: after === null, challenge: after };
3810
+ } catch {
3811
+ const after = await detect();
3812
+ return { resolved: after === null, challenge: after };
3813
+ }
3814
+ }
3815
+ const deadline = Date.now() + timeout;
3816
+ while (Date.now() < deadline) {
3817
+ await page.waitForTimeout(poll);
3818
+ const current = await detect();
3819
+ if (current === null) return { resolved: true, challenge: null };
3820
+ }
3821
+ const final = await detect();
3822
+ return { resolved: final === null, challenge: final };
3823
+ }
3824
+
3539
3825
  // src/capture/activity.ts
3540
3826
  function consolePriority(level) {
3541
3827
  switch (level) {
@@ -5140,6 +5426,53 @@ var CrawlPage = class {
5140
5426
  name
5141
5427
  });
5142
5428
  }
5429
+ // ── Anti-Bot ──────────────────────────────────────────────────
5430
+ /**
5431
+ * Detect whether the page is showing an anti-bot challenge
5432
+ * (Cloudflare, hCaptcha, reCAPTCHA, access-denied, rate-limit, etc.).
5433
+ *
5434
+ * Returns `null` if no challenge is detected.
5435
+ *
5436
+ * @example
5437
+ * ```ts
5438
+ * const challenge = await page.detectChallenge();
5439
+ * if (challenge) {
5440
+ * console.log(challenge.kind); // 'cloudflare-js'
5441
+ * console.log(challenge.message); // 'Cloudflare JS challenge'
5442
+ * }
5443
+ * ```
5444
+ */
5445
+ async detectChallenge() {
5446
+ return detectChallengeViaPlaywright({ cdpUrl: this.cdpUrl, targetId: this.targetId });
5447
+ }
5448
+ /**
5449
+ * Wait for an anti-bot challenge to resolve on its own.
5450
+ *
5451
+ * Cloudflare JS challenges typically auto-resolve in ~5 seconds.
5452
+ * CAPTCHA challenges will only resolve if solved in a visible browser window.
5453
+ *
5454
+ * @param opts.timeoutMs - Maximum wait time (default: `15000`)
5455
+ * @param opts.pollMs - Poll interval (default: `500`)
5456
+ * @returns Whether the challenge resolved, and the remaining challenge info if not
5457
+ *
5458
+ * @example
5459
+ * ```ts
5460
+ * await page.goto('https://example.com');
5461
+ * const challenge = await page.detectChallenge();
5462
+ * if (challenge?.kind === 'cloudflare-js') {
5463
+ * const { resolved } = await page.waitForChallenge({ timeoutMs: 20000 });
5464
+ * if (!resolved) throw new Error('Challenge did not resolve');
5465
+ * }
5466
+ * ```
5467
+ */
5468
+ async waitForChallenge(opts) {
5469
+ return waitForChallengeViaPlaywright({
5470
+ cdpUrl: this.cdpUrl,
5471
+ targetId: this.targetId,
5472
+ timeoutMs: opts?.timeoutMs,
5473
+ pollMs: opts?.pollMs
5474
+ });
5475
+ }
5143
5476
  };
5144
5477
  var BrowserClaw = class _BrowserClaw {
5145
5478
  cdpUrl;
@@ -5285,6 +5618,6 @@ var BrowserClaw = class _BrowserClaw {
5285
5618
  }
5286
5619
  };
5287
5620
 
5288
- export { BrowserClaw, BrowserTabNotFoundError, CrawlPage, InvalidBrowserNavigationUrlError, assertBrowserNavigationAllowed, assertBrowserNavigationRedirectChainAllowed, assertBrowserNavigationResultAllowed, assertSafeUploadPaths, batchViaPlaywright, createPinnedLookup, ensureContextState, executeSingleAction, forceDisconnectPlaywrightForTarget, getChromeWebSocketUrl, getRestoredPageForTarget, isChromeCdpReady, isChromeReachable, normalizeCdpHttpBaseForJsonEndpoints, parseRoleRef, requireRef, requireRefOrSelector, requiresInspectableBrowserNavigationRedirects, resolveBoundedDelayMs, resolveInteractionTimeoutMs, resolvePageByTargetIdOrThrow, resolvePinnedHostnameWithPolicy, resolveStrictExistingUploadPaths, sanitizeUntrustedFileName, withBrowserNavigationPolicy, withPageScopedCdpClient, withPlaywrightPageCdpSession, writeViaSiblingTempPath };
5621
+ export { BrowserClaw, BrowserTabNotFoundError, CrawlPage, InvalidBrowserNavigationUrlError, STEALTH_SCRIPT, assertBrowserNavigationAllowed, assertBrowserNavigationRedirectChainAllowed, assertBrowserNavigationResultAllowed, assertSafeUploadPaths, batchViaPlaywright, createPinnedLookup, detectChallengeViaPlaywright, ensureContextState, executeSingleAction, forceDisconnectPlaywrightForTarget, getChromeWebSocketUrl, getRestoredPageForTarget, isChromeCdpReady, isChromeReachable, normalizeCdpHttpBaseForJsonEndpoints, parseRoleRef, requireRef, requireRefOrSelector, requiresInspectableBrowserNavigationRedirects, resolveBoundedDelayMs, resolveInteractionTimeoutMs, resolvePageByTargetIdOrThrow, resolvePinnedHostnameWithPolicy, resolveStrictExistingUploadPaths, sanitizeUntrustedFileName, waitForChallengeViaPlaywright, withBrowserNavigationPolicy, withPageScopedCdpClient, withPlaywrightPageCdpSession, writeViaSiblingTempPath };
5289
5622
  //# sourceMappingURL=index.js.map
5290
5623
  //# sourceMappingURL=index.js.map