@xbrowser/cli 1.9.1 → 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,312 @@
1
+ import {
2
+ ScreencastCapturer
3
+ } from "./chunk-7ZDWM6T2.js";
4
+ import "./chunk-KFQGP6VL.js";
5
+
6
+ // src/human-interaction.ts
7
+ import { execSync } from "child_process";
8
+
9
+ // src/captcha-detector.ts
10
+ var CAPTCHA_SELECTORS = [
11
+ { selector: 'iframe[src*="recaptcha"]', type: "recaptcha", confidence: "high" },
12
+ { selector: ".g-recaptcha", type: "recaptcha", confidence: "high" },
13
+ { selector: "#recaptcha", type: "recaptcha", confidence: "high" },
14
+ { selector: "[data-sitekey]", type: "recaptcha", confidence: "medium" },
15
+ { selector: 'iframe[src*="hcaptcha"]', type: "hcaptcha", confidence: "high" },
16
+ { selector: ".h-captcha", type: "hcaptcha", confidence: "high" },
17
+ { selector: 'iframe[src*="challenges.cloudflare.com"]', type: "turnstile", confidence: "high" },
18
+ { selector: ".cf-turnstile", type: "turnstile", confidence: "high" },
19
+ { selector: 'iframe[src*="captcha"]', type: "generic", confidence: "medium" },
20
+ { selector: "[data-captcha]", type: "generic", confidence: "medium" },
21
+ { selector: ".captcha-container", type: "generic", confidence: "medium" },
22
+ { selector: "#captcha", type: "generic", confidence: "medium" },
23
+ { selector: ".captcha-image", type: "generic", confidence: "medium" },
24
+ { selector: "#captcha_image", type: "generic", confidence: "medium" },
25
+ // 小红书滑块验证
26
+ { selector: ".captcha-verify-image", type: "xhs-slider", confidence: "high" },
27
+ { selector: ".verify-wrap", type: "xhs-slider", confidence: "medium" },
28
+ { selector: '[class*="slider-verify"]', type: "xhs-slider", confidence: "medium" },
29
+ { selector: '[class*="captcha-verify"]', type: "xhs-slider", confidence: "medium" },
30
+ { selector: '[class*="verify-image"]', type: "xhs-slider", confidence: "low" }
31
+ ];
32
+ var CAPTCHA_TEXT_PATTERNS = [
33
+ "verify you are human",
34
+ "prove you are not a robot",
35
+ "complete the challenge",
36
+ "are you a robot",
37
+ "human verification",
38
+ "security check",
39
+ "prove you're human",
40
+ "not a robot",
41
+ // 小红书验证提示
42
+ /xiaohongshu.*verif/i,
43
+ /拖动滑块/,
44
+ /请完成验证/,
45
+ /slide.*verify/i
46
+ ];
47
+ var CaptchaDetector = class {
48
+ /**
49
+ * Scan the page for visible CAPTCHA elements or challenge text.
50
+ *
51
+ * @param page - The Playwright page to scan.
52
+ * @returns Detection result with type, selector, and confidence level.
53
+ */
54
+ static async detect(page) {
55
+ for (const rule of CAPTCHA_SELECTORS) {
56
+ try {
57
+ const el = await page.$(rule.selector);
58
+ if (el) {
59
+ const visible = await el.isVisible().catch(() => false);
60
+ if (visible) {
61
+ return {
62
+ detected: true,
63
+ type: rule.type,
64
+ selector: rule.selector,
65
+ confidence: rule.confidence
66
+ };
67
+ }
68
+ }
69
+ } catch {
70
+ }
71
+ }
72
+ try {
73
+ const bodyText = await page.textContent("body").catch(() => "");
74
+ if (bodyText) {
75
+ for (const pattern of CAPTCHA_TEXT_PATTERNS) {
76
+ const matches = pattern instanceof RegExp ? pattern.test(bodyText) : bodyText.toLowerCase().includes(pattern);
77
+ if (matches) {
78
+ return {
79
+ detected: true,
80
+ type: "text-challenge",
81
+ confidence: "low"
82
+ };
83
+ }
84
+ }
85
+ }
86
+ } catch {
87
+ }
88
+ return { detected: false, confidence: "low" };
89
+ }
90
+ /**
91
+ * Check whether a previously detected CAPTCHA has been solved.
92
+ *
93
+ * @param page - The Playwright page to check.
94
+ * @param previousSelector - The selector from a previous detection result.
95
+ * @returns `true` if the CAPTCHA is no longer visible.
96
+ */
97
+ static async isSolved(page, previousSelector) {
98
+ if (previousSelector) {
99
+ try {
100
+ const el = await page.$(previousSelector);
101
+ if (!el) return true;
102
+ const visible = await el.isVisible().catch(() => false);
103
+ if (!visible) return true;
104
+ } catch {
105
+ return true;
106
+ }
107
+ }
108
+ const result = await this.detect(page);
109
+ return !result.detected;
110
+ }
111
+ };
112
+
113
+ // src/webhook.ts
114
+ var WebhookNotifier = class {
115
+ url;
116
+ constructor(url) {
117
+ this.url = url || process.env.XBROWSER_NOTIFY_URL || null;
118
+ }
119
+ /**
120
+ * Send a webhook notification payload.
121
+ *
122
+ * @param payload - The event payload to send.
123
+ * @returns `true` if the request succeeded (HTTP 2xx), `false` otherwise.
124
+ */
125
+ async notify(payload) {
126
+ if (!this.url) return false;
127
+ try {
128
+ const response = await fetch(this.url, {
129
+ method: "POST",
130
+ headers: { "Content-Type": "application/json" },
131
+ body: JSON.stringify(payload),
132
+ signal: AbortSignal.timeout(5e3)
133
+ });
134
+ return response.ok;
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+ };
140
+
141
+ // src/config.ts
142
+ import { homedir, tmpdir } from "os";
143
+ import { join } from "path";
144
+ import { loadConfig as coreLoadConfig, saveConfig as coreSaveConfig } from "@dyyz1993/xcli-core";
145
+ function getConfigSource() {
146
+ return { configDir: join(homedir() || tmpdir(), ".xbrowser") };
147
+ }
148
+ function loadConfig() {
149
+ return coreLoadConfig(getConfigSource());
150
+ }
151
+ function getCaptchaConfig() {
152
+ const config = loadConfig();
153
+ return {
154
+ notifyUrl: process.env.XBROWSER_NOTIFY_URL || config.captcha?.notifyUrl,
155
+ autoOpen: process.env.XBROWSER_AUTO_OPEN === "true" || config.captcha?.autoOpen === true,
156
+ timeout: parseInt(process.env.XBROWSER_CAPTCHA_TIMEOUT || "") || config.captcha?.timeout || 120,
157
+ previewPort: parseInt(process.env.XBROWSER_PREVIEW_PORT || "") || config.preview?.port || 9223
158
+ };
159
+ }
160
+
161
+ // src/utils/shell-escape.ts
162
+ function shellEscape(value) {
163
+ return `'${value.replace(/'/g, "'\\''")}'`;
164
+ }
165
+
166
+ // src/human-interaction.ts
167
+ var HumanInteractionManager = class {
168
+ wsServer;
169
+ page;
170
+ capturer;
171
+ webhook;
172
+ autoOpen;
173
+ constructor(wsServer, page) {
174
+ this.wsServer = wsServer;
175
+ this.page = page;
176
+ this.capturer = new ScreencastCapturer();
177
+ const cfg = getCaptchaConfig();
178
+ this.webhook = new WebhookNotifier(cfg.notifyUrl);
179
+ this.autoOpen = cfg.autoOpen;
180
+ this.wsServer.registerSession("default", page);
181
+ }
182
+ async sendWebhook(event, overrides = {}) {
183
+ await this.webhook.notify({
184
+ event,
185
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
186
+ url: this.page.url(),
187
+ previewUrl: `http://localhost:${this.wsServer.getPort()}`,
188
+ ...overrides
189
+ });
190
+ }
191
+ tryAutoOpen(previewUrl) {
192
+ if (!this.autoOpen) return;
193
+ try {
194
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "linux" ? "xdg-open" : "start";
195
+ execSync(`${cmd} ${shellEscape(previewUrl)}`, { stdio: "ignore" });
196
+ } catch {
197
+ }
198
+ }
199
+ /**
200
+ * Wait for a human to solve a CAPTCHA or complete an interaction.
201
+ *
202
+ * Starts screencast streaming, sends webhook and broadcast notifications,
203
+ * then polls for CAPTCHA resolution or waits for a manual solve signal.
204
+ *
205
+ * @param options - Configuration for timeout, auto-detection, and reason text.
206
+ * @returns Result indicating whether the CAPTCHA was solved and by what method.
207
+ */
208
+ async waitForHuman(options = {}) {
209
+ const {
210
+ reason = "Human interaction required",
211
+ timeout = 120,
212
+ autoDetect = true,
213
+ detectInterval = 2e3
214
+ } = options;
215
+ const captcha = await CaptchaDetector.detect(this.page);
216
+ const captchaInfo = captcha.detected ? captcha : void 0;
217
+ await this.capturer.startCapture(this.page, "default", (frame) => {
218
+ this.wsServer.broadcast({
219
+ type: "screenshot",
220
+ data: {
221
+ sessionId: frame.sessionId,
222
+ id: frame.id,
223
+ timestamp: frame.timestamp,
224
+ data: frame.data,
225
+ url: frame.url,
226
+ viewport: frame.viewport
227
+ }
228
+ });
229
+ });
230
+ const previewUrl = `http://localhost:${this.wsServer.getPort()}`;
231
+ await this.sendWebhook("captcha-detected", {
232
+ reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
233
+ timeout,
234
+ targetUrl: this.page.url()
235
+ });
236
+ this.wsServer.broadcast({
237
+ type: "captcha-detected",
238
+ sessionId: "default",
239
+ url: this.page.url(),
240
+ reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
241
+ timeout
242
+ });
243
+ this.tryAutoOpen(previewUrl);
244
+ console.log("");
245
+ 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");
246
+ console.log(`\u26A0\uFE0F ${captchaInfo ? (captchaInfo.type ?? "UNKNOWN").toUpperCase() + " CAPTCHA" : "INTERACTION"} REQUIRED`);
247
+ console.log(`\u26A0\uFE0F URL: ${this.page.url()}`);
248
+ console.log(`\u26A0\uFE0F `);
249
+ console.log(`\u26A0\uFE0F Solve via:`);
250
+ console.log(`\u26A0\uFE0F \u{1F4FA} Preview: ${previewUrl}`);
251
+ console.log(`\u26A0\uFE0F \u{1F310} Direct: ${this.page.url()}`);
252
+ console.log(`\u26A0\uFE0F \u23ED\uFE0F Skip`);
253
+ console.log(`\u26A0\uFE0F \u274C Abort`);
254
+ console.log(`\u26A0\uFE0F `);
255
+ console.log(`\u26A0\uFE0F \u23F3 Waiting... (${timeout}s timeout)`);
256
+ 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");
257
+ console.log("");
258
+ return new Promise((resolve) => {
259
+ let resolved = false;
260
+ let pollTimer = null;
261
+ let timeoutTimer = null;
262
+ const cleanup = () => {
263
+ if (pollTimer) clearInterval(pollTimer);
264
+ if (timeoutTimer) clearTimeout(timeoutTimer);
265
+ this.wsServer.removeListener("human-solved", onHumanSolved);
266
+ this.capturer.stopCapture();
267
+ };
268
+ if (autoDetect && captchaInfo) {
269
+ pollTimer = setInterval(async () => {
270
+ if (resolved) return;
271
+ try {
272
+ const solved = await CaptchaDetector.isSolved(this.page, captchaInfo.selector);
273
+ if (solved) {
274
+ resolved = true;
275
+ cleanup();
276
+ this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
277
+ console.log("\u2705 CAPTCHA auto-detected as solved!");
278
+ this.sendWebhook("captcha-resolved", { reason: "auto-detected" });
279
+ resolve({ solved: true, method: "auto-detected" });
280
+ }
281
+ } catch {
282
+ }
283
+ }, detectInterval);
284
+ }
285
+ const onHumanSolved = () => {
286
+ if (!resolved) {
287
+ resolved = true;
288
+ cleanup();
289
+ this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
290
+ console.log("\u2705 CAPTCHA solved via preview!");
291
+ this.sendWebhook("captcha-resolved", { reason: "preview" });
292
+ resolve({ solved: true, method: "preview" });
293
+ }
294
+ };
295
+ this.wsServer.on("human-solved", onHumanSolved);
296
+ if (timeout > 0) {
297
+ timeoutTimer = setTimeout(() => {
298
+ if (!resolved) {
299
+ resolved = true;
300
+ cleanup();
301
+ console.log("\u23F0 Timeout - skipping");
302
+ this.sendWebhook("captcha-resolved", { reason: "timeout" });
303
+ resolve({ solved: false, method: "timeout" });
304
+ }
305
+ }, timeout * 1e3);
306
+ }
307
+ });
308
+ }
309
+ };
310
+ export {
311
+ HumanInteractionManager
312
+ };