@xbrowser/cli 1.9.2 → 1.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,434 @@
1
+ import {
2
+ getCaptchaConfig
3
+ } from "./chunk-IIM5GOD7.js";
4
+ import "./chunk-KFQGP6VL.js";
5
+
6
+ // src/human-interaction.ts
7
+ import { execSync } from "child_process";
8
+
9
+ // src/screencast.ts
10
+ var ScreencastCapturer = class {
11
+ interval;
12
+ quality;
13
+ type;
14
+ maxWidth;
15
+ maxHeight;
16
+ isCapturing = false;
17
+ frameCallback = null;
18
+ // CDP Cast state
19
+ cdpSession = null;
20
+ sessionId = "";
21
+ // Fallback polling state
22
+ fallbackTimer = null;
23
+ constructor(options = {}) {
24
+ this.interval = options.interval || 100;
25
+ this.quality = options.quality || 60;
26
+ this.type = options.type || "jpeg";
27
+ this.maxWidth = options.width || 1920;
28
+ this.maxHeight = options.height || 1080;
29
+ }
30
+ /**
31
+ * Start screencast capture using CDP Page.startScreencast.
32
+ *
33
+ * If CDP session creation fails (non-Chromium, restricted access),
34
+ * automatically falls back to `page.screenshot()` polling.
35
+ */
36
+ async startCapture(page, sessionId, onFrame) {
37
+ if (this.isCapturing) {
38
+ throw new Error("Screencast is already capturing");
39
+ }
40
+ this.isCapturing = true;
41
+ this.frameCallback = onFrame;
42
+ this.sessionId = sessionId;
43
+ try {
44
+ const cdp = await page.context().newCDPSession(page);
45
+ this.cdpSession = cdp;
46
+ cdp.on("Page.screencastFrame", async (params) => {
47
+ if (!this.frameCallback) return;
48
+ try {
49
+ await cdp.send("Page.screencastFrameAck", { sessionId: params.sessionId });
50
+ } catch {
51
+ }
52
+ const viewport = {
53
+ width: params.metadata?.deviceWidth || this.maxWidth,
54
+ height: params.metadata?.deviceHeight || this.maxHeight
55
+ };
56
+ this.frameCallback({
57
+ id: crypto.randomUUID(),
58
+ sessionId: this.sessionId,
59
+ timestamp: Date.now(),
60
+ data: Buffer.from(params.data, "base64"),
61
+ url: page.url(),
62
+ viewport
63
+ });
64
+ });
65
+ await cdp.send("Page.startScreencast", {
66
+ format: this.type === "png" ? "png" : "jpeg",
67
+ quality: this.type === "jpeg" ? this.quality : void 0,
68
+ maxWidth: this.maxWidth,
69
+ maxHeight: this.maxHeight
70
+ });
71
+ } catch {
72
+ this.cdpSession = null;
73
+ this.startFallbackPolling(page, sessionId);
74
+ }
75
+ }
76
+ /**
77
+ * Fallback: periodic page.screenshot() polling when CDP Cast is unavailable.
78
+ */
79
+ startFallbackPolling(page, sessionId) {
80
+ const captureLoop = async () => {
81
+ if (!this.frameCallback) return;
82
+ try {
83
+ const frame = await this.captureFrame(page, sessionId);
84
+ this.frameCallback(frame);
85
+ } catch {
86
+ }
87
+ };
88
+ captureLoop();
89
+ this.fallbackTimer = setInterval(captureLoop, this.interval);
90
+ }
91
+ /**
92
+ * Capture a single screenshot frame from the page (fallback mode).
93
+ */
94
+ async captureFrame(page, sessionId) {
95
+ let viewport = page.viewportSize();
96
+ if (!viewport) {
97
+ try {
98
+ viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
99
+ } catch {
100
+ viewport = { width: 1920, height: 1080 };
101
+ }
102
+ }
103
+ const screenshot = await page.screenshot({
104
+ type: this.type,
105
+ quality: this.type === "jpeg" ? this.quality : void 0
106
+ });
107
+ return {
108
+ id: crypto.randomUUID(),
109
+ sessionId,
110
+ timestamp: Date.now(),
111
+ data: screenshot,
112
+ url: page.url(),
113
+ viewport: viewport || { width: 0, height: 0 }
114
+ };
115
+ }
116
+ /**
117
+ * Stop the current screencast capture.
118
+ */
119
+ async stopCapture() {
120
+ if (this.cdpSession) {
121
+ try {
122
+ this.cdpSession.off("Page.screencastFrame", () => {
123
+ });
124
+ await this.cdpSession.send("Page.stopScreencast");
125
+ } catch {
126
+ }
127
+ try {
128
+ await this.cdpSession.detach();
129
+ } catch {
130
+ }
131
+ this.cdpSession = null;
132
+ }
133
+ if (this.fallbackTimer) {
134
+ clearInterval(this.fallbackTimer);
135
+ this.fallbackTimer = null;
136
+ }
137
+ this.isCapturing = false;
138
+ this.frameCallback = null;
139
+ }
140
+ isActive() {
141
+ return this.isCapturing;
142
+ }
143
+ setInterval(interval) {
144
+ this.interval = interval;
145
+ }
146
+ setQuality(quality) {
147
+ this.quality = quality;
148
+ }
149
+ };
150
+
151
+ // src/captcha-detector.ts
152
+ var CAPTCHA_SELECTORS = [
153
+ { selector: 'iframe[src*="recaptcha"]', type: "recaptcha", confidence: "high" },
154
+ { selector: ".g-recaptcha", type: "recaptcha", confidence: "high" },
155
+ { selector: "#recaptcha", type: "recaptcha", confidence: "high" },
156
+ { selector: "[data-sitekey]", type: "recaptcha", confidence: "medium" },
157
+ { selector: 'iframe[src*="hcaptcha"]', type: "hcaptcha", confidence: "high" },
158
+ { selector: ".h-captcha", type: "hcaptcha", confidence: "high" },
159
+ { selector: 'iframe[src*="challenges.cloudflare.com"]', type: "turnstile", confidence: "high" },
160
+ { selector: ".cf-turnstile", type: "turnstile", confidence: "high" },
161
+ { selector: 'iframe[src*="captcha"]', type: "generic", confidence: "medium" },
162
+ { selector: "[data-captcha]", type: "generic", confidence: "medium" },
163
+ { selector: ".captcha-container", type: "generic", confidence: "medium" },
164
+ { selector: "#captcha", type: "generic", confidence: "medium" },
165
+ { selector: ".captcha-image", type: "generic", confidence: "medium" },
166
+ { selector: "#captcha_image", type: "generic", confidence: "medium" },
167
+ // 小红书滑块验证
168
+ { selector: ".captcha-verify-image", type: "xhs-slider", confidence: "high" },
169
+ { selector: ".verify-wrap", type: "xhs-slider", confidence: "medium" },
170
+ { selector: '[class*="slider-verify"]', type: "xhs-slider", confidence: "medium" },
171
+ { selector: '[class*="captcha-verify"]', type: "xhs-slider", confidence: "medium" },
172
+ { selector: '[class*="verify-image"]', type: "xhs-slider", confidence: "low" }
173
+ ];
174
+ var CAPTCHA_TEXT_PATTERNS = [
175
+ "verify you are human",
176
+ "prove you are not a robot",
177
+ "complete the challenge",
178
+ "are you a robot",
179
+ "human verification",
180
+ "security check",
181
+ "prove you're human",
182
+ "not a robot",
183
+ // 小红书验证提示
184
+ /xiaohongshu.*verif/i,
185
+ /拖动滑块/,
186
+ /请完成验证/,
187
+ /slide.*verify/i
188
+ ];
189
+ var CaptchaDetector = class {
190
+ /**
191
+ * Scan the page for visible CAPTCHA elements or challenge text.
192
+ *
193
+ * @param page - The Playwright page to scan.
194
+ * @returns Detection result with type, selector, and confidence level.
195
+ */
196
+ static async detect(page) {
197
+ for (const rule of CAPTCHA_SELECTORS) {
198
+ try {
199
+ const el = await page.$(rule.selector);
200
+ if (el) {
201
+ const visible = await el.isVisible().catch(() => false);
202
+ if (visible) {
203
+ return {
204
+ detected: true,
205
+ type: rule.type,
206
+ selector: rule.selector,
207
+ confidence: rule.confidence
208
+ };
209
+ }
210
+ }
211
+ } catch {
212
+ }
213
+ }
214
+ try {
215
+ const bodyText = await page.textContent("body").catch(() => "");
216
+ if (bodyText) {
217
+ for (const pattern of CAPTCHA_TEXT_PATTERNS) {
218
+ const matches = pattern instanceof RegExp ? pattern.test(bodyText) : bodyText.toLowerCase().includes(pattern);
219
+ if (matches) {
220
+ return {
221
+ detected: true,
222
+ type: "text-challenge",
223
+ confidence: "low"
224
+ };
225
+ }
226
+ }
227
+ }
228
+ } catch {
229
+ }
230
+ return { detected: false, confidence: "low" };
231
+ }
232
+ /**
233
+ * Check whether a previously detected CAPTCHA has been solved.
234
+ *
235
+ * @param page - The Playwright page to check.
236
+ * @param previousSelector - The selector from a previous detection result.
237
+ * @returns `true` if the CAPTCHA is no longer visible.
238
+ */
239
+ static async isSolved(page, previousSelector) {
240
+ if (previousSelector) {
241
+ try {
242
+ const el = await page.$(previousSelector);
243
+ if (!el) return true;
244
+ const visible = await el.isVisible().catch(() => false);
245
+ if (!visible) return true;
246
+ } catch {
247
+ return true;
248
+ }
249
+ }
250
+ const result = await this.detect(page);
251
+ return !result.detected;
252
+ }
253
+ };
254
+
255
+ // src/webhook.ts
256
+ var WebhookNotifier = class {
257
+ url;
258
+ constructor(url) {
259
+ this.url = url || process.env.XBROWSER_NOTIFY_URL || null;
260
+ }
261
+ /**
262
+ * Send a webhook notification payload.
263
+ *
264
+ * @param payload - The event payload to send.
265
+ * @returns `true` if the request succeeded (HTTP 2xx), `false` otherwise.
266
+ */
267
+ async notify(payload) {
268
+ if (!this.url) return false;
269
+ try {
270
+ const response = await fetch(this.url, {
271
+ method: "POST",
272
+ headers: { "Content-Type": "application/json" },
273
+ body: JSON.stringify(payload),
274
+ signal: AbortSignal.timeout(5e3)
275
+ });
276
+ return response.ok;
277
+ } catch {
278
+ return false;
279
+ }
280
+ }
281
+ };
282
+
283
+ // src/utils/shell-escape.ts
284
+ function shellEscape(value) {
285
+ return `'${value.replace(/'/g, "'\\''")}'`;
286
+ }
287
+
288
+ // src/human-interaction.ts
289
+ var HumanInteractionManager = class {
290
+ wsServer;
291
+ page;
292
+ capturer;
293
+ webhook;
294
+ autoOpen;
295
+ constructor(wsServer, page) {
296
+ this.wsServer = wsServer;
297
+ this.page = page;
298
+ this.capturer = new ScreencastCapturer();
299
+ const cfg = getCaptchaConfig();
300
+ this.webhook = new WebhookNotifier(cfg.notifyUrl);
301
+ this.autoOpen = cfg.autoOpen;
302
+ this.wsServer.registerSession("default", page);
303
+ }
304
+ async sendWebhook(event, overrides = {}) {
305
+ await this.webhook.notify({
306
+ event,
307
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
308
+ url: this.page.url(),
309
+ previewUrl: `http://localhost:${this.wsServer.getPort()}`,
310
+ ...overrides
311
+ });
312
+ }
313
+ tryAutoOpen(previewUrl) {
314
+ if (!this.autoOpen) return;
315
+ try {
316
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "linux" ? "xdg-open" : "start";
317
+ execSync(`${cmd} ${shellEscape(previewUrl)}`, { stdio: "ignore" });
318
+ } catch {
319
+ }
320
+ }
321
+ /**
322
+ * Wait for a human to solve a CAPTCHA or complete an interaction.
323
+ *
324
+ * Starts screencast streaming, sends webhook and broadcast notifications,
325
+ * then polls for CAPTCHA resolution or waits for a manual solve signal.
326
+ *
327
+ * @param options - Configuration for timeout, auto-detection, and reason text.
328
+ * @returns Result indicating whether the CAPTCHA was solved and by what method.
329
+ */
330
+ async waitForHuman(options = {}) {
331
+ const {
332
+ reason = "Human interaction required",
333
+ timeout = 120,
334
+ autoDetect = true,
335
+ detectInterval = 2e3
336
+ } = options;
337
+ const captcha = await CaptchaDetector.detect(this.page);
338
+ const captchaInfo = captcha.detected ? captcha : void 0;
339
+ await this.capturer.startCapture(this.page, "default", (frame) => {
340
+ this.wsServer.broadcast({
341
+ type: "screenshot",
342
+ data: {
343
+ sessionId: frame.sessionId,
344
+ id: frame.id,
345
+ timestamp: frame.timestamp,
346
+ data: frame.data,
347
+ url: frame.url,
348
+ viewport: frame.viewport
349
+ }
350
+ });
351
+ });
352
+ const previewUrl = `http://localhost:${this.wsServer.getPort()}`;
353
+ await this.sendWebhook("captcha-detected", {
354
+ reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
355
+ timeout,
356
+ targetUrl: this.page.url()
357
+ });
358
+ this.wsServer.broadcast({
359
+ type: "captcha-detected",
360
+ sessionId: "default",
361
+ url: this.page.url(),
362
+ reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
363
+ timeout
364
+ });
365
+ this.tryAutoOpen(previewUrl);
366
+ console.log("");
367
+ console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
368
+ console.log(`\u26A0\uFE0F ${captchaInfo ? (captchaInfo.type ?? "UNKNOWN").toUpperCase() + " CAPTCHA" : "INTERACTION"} REQUIRED`);
369
+ console.log(`\u26A0\uFE0F URL: ${this.page.url()}`);
370
+ console.log(`\u26A0\uFE0F `);
371
+ console.log(`\u26A0\uFE0F Solve via:`);
372
+ console.log(`\u26A0\uFE0F \u{1F4FA} Preview: ${previewUrl}`);
373
+ console.log(`\u26A0\uFE0F \u{1F310} Direct: ${this.page.url()}`);
374
+ console.log(`\u26A0\uFE0F \u23ED\uFE0F Skip`);
375
+ console.log(`\u26A0\uFE0F \u274C Abort`);
376
+ console.log(`\u26A0\uFE0F `);
377
+ console.log(`\u26A0\uFE0F \u23F3 Waiting... (${timeout}s timeout)`);
378
+ console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
379
+ console.log("");
380
+ return new Promise((resolve) => {
381
+ let resolved = false;
382
+ let pollTimer = null;
383
+ let timeoutTimer = null;
384
+ const cleanup = () => {
385
+ if (pollTimer) clearInterval(pollTimer);
386
+ if (timeoutTimer) clearTimeout(timeoutTimer);
387
+ this.wsServer.removeListener("human-solved", onHumanSolved);
388
+ this.capturer.stopCapture();
389
+ };
390
+ if (autoDetect && captchaInfo) {
391
+ pollTimer = setInterval(async () => {
392
+ if (resolved) return;
393
+ try {
394
+ const solved = await CaptchaDetector.isSolved(this.page, captchaInfo.selector);
395
+ if (solved) {
396
+ resolved = true;
397
+ cleanup();
398
+ this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
399
+ console.log("\u2705 CAPTCHA auto-detected as solved!");
400
+ this.sendWebhook("captcha-resolved", { reason: "auto-detected" });
401
+ resolve({ solved: true, method: "auto-detected" });
402
+ }
403
+ } catch {
404
+ }
405
+ }, detectInterval);
406
+ }
407
+ const onHumanSolved = () => {
408
+ if (!resolved) {
409
+ resolved = true;
410
+ cleanup();
411
+ this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
412
+ console.log("\u2705 CAPTCHA solved via preview!");
413
+ this.sendWebhook("captcha-resolved", { reason: "preview" });
414
+ resolve({ solved: true, method: "preview" });
415
+ }
416
+ };
417
+ this.wsServer.on("human-solved", onHumanSolved);
418
+ if (timeout > 0) {
419
+ timeoutTimer = setTimeout(() => {
420
+ if (!resolved) {
421
+ resolved = true;
422
+ cleanup();
423
+ console.log("\u23F0 Timeout - skipping");
424
+ this.sendWebhook("captcha-resolved", { reason: "timeout" });
425
+ resolve({ solved: false, method: "timeout" });
426
+ }
427
+ }, timeout * 1e3);
428
+ }
429
+ });
430
+ }
431
+ };
432
+ export {
433
+ HumanInteractionManager
434
+ };
package/dist/index.d.ts CHANGED
@@ -961,11 +961,41 @@ declare class HumanInteractionManager {
961
961
  waitForHuman(options?: WaitForHumanOptions): Promise<WaitForHumanResult>;
962
962
  }
963
963
 
964
+ /**
965
+ * xbrowser — Anti-Bot Detection
966
+ *
967
+ * 主动检测页面的反机器人检测机制,在执行自动化动作前拦截可疑情况。
968
+ */
969
+
970
+ /**
971
+ * 检测结果类型
972
+ */
973
+ interface DetectionResult {
974
+ detected: boolean;
975
+ type?: string;
976
+ severity?: 'low' | 'medium' | 'high';
977
+ message?: string;
978
+ selector?: string;
979
+ actionRequired?: 'retry' | 'manual' | 'switch';
980
+ }
981
+ /**
982
+ * 检测器配置
983
+ */
984
+ interface DetectionConfig {
985
+ checkCaptcha?: boolean;
986
+ checkWarning?: boolean;
987
+ checkBlocked?: boolean;
988
+ checkLogin?: boolean;
989
+ checkWebdriver?: boolean;
990
+ timeout?: number;
991
+ }
992
+
964
993
  /**
965
994
  * Extended command context for browser automation commands.
966
995
  *
967
996
  * Provides Playwright Page, Browser, and BrowserContext instances,
968
- * along with an optional `waitForHuman` function for CAPTCHA handling.
997
+ * along with optional `waitForHuman` (CAPTCHA handling) and
998
+ * `detectAntiBot` (anti-bot detection) capabilities.
969
999
  */
970
1000
  interface BrowserCommandContext extends CommandContext {
971
1001
  page: XBPage;
@@ -974,6 +1004,7 @@ interface BrowserCommandContext extends CommandContext {
974
1004
  sessionId?: string;
975
1005
  cdpEndpoint?: string;
976
1006
  waitForHuman?: (options?: WaitForHumanOptions) => Promise<WaitForHumanResult>;
1007
+ detectAntiBot?: (page: XBPage, config?: DetectionConfig) => Promise<DetectionResult>;
977
1008
  }
978
1009
  /**
979
1010
  * Validate that the required browser scope is available in the context.