@browsa/mcp 0.6.0 → 0.8.0
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/README.md +164 -7
- package/SECURITY.md +40 -0
- package/dist/server.js +1707 -64
- package/manifest.json +81 -0
- package/package.json +11 -5
package/dist/server.js
CHANGED
|
@@ -3,11 +3,474 @@
|
|
|
3
3
|
// src/server.ts
|
|
4
4
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
5
5
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
CallToolRequestSchema,
|
|
8
|
+
GetPromptRequestSchema,
|
|
9
|
+
ListPromptsRequestSchema,
|
|
10
|
+
ListToolsRequestSchema
|
|
11
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
12
|
+
|
|
13
|
+
// src/captcha/catalogue-snapshot.json
|
|
14
|
+
var catalogue_snapshot_default = {
|
|
15
|
+
asOf: "2026-11-21",
|
|
16
|
+
service: "https://captcha.browsa.io",
|
|
17
|
+
types: [
|
|
18
|
+
{
|
|
19
|
+
type: "ImageToTextTask",
|
|
20
|
+
title: "Image text",
|
|
21
|
+
kind: "recognition",
|
|
22
|
+
family: "image_text",
|
|
23
|
+
status: "live",
|
|
24
|
+
required: [],
|
|
25
|
+
oneOf: [
|
|
26
|
+
[
|
|
27
|
+
"body",
|
|
28
|
+
"images"
|
|
29
|
+
]
|
|
30
|
+
],
|
|
31
|
+
optional: [
|
|
32
|
+
"module",
|
|
33
|
+
"websiteURL"
|
|
34
|
+
],
|
|
35
|
+
proxy: "none",
|
|
36
|
+
credits: 4e-3
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
type: "ReCaptchaV2Classification",
|
|
40
|
+
title: "reCAPTCHA v2 grid classification",
|
|
41
|
+
kind: "recognition",
|
|
42
|
+
family: "recaptcha_grid",
|
|
43
|
+
status: "live",
|
|
44
|
+
required: [
|
|
45
|
+
"image",
|
|
46
|
+
"question"
|
|
47
|
+
],
|
|
48
|
+
oneOf: [],
|
|
49
|
+
optional: [
|
|
50
|
+
"size",
|
|
51
|
+
"escalate",
|
|
52
|
+
"websiteURL"
|
|
53
|
+
],
|
|
54
|
+
proxy: "none",
|
|
55
|
+
credits: 0.01
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
type: "AwsWafClassification",
|
|
59
|
+
title: "AWS WAF grid classification",
|
|
60
|
+
kind: "recognition",
|
|
61
|
+
family: "aws_waf",
|
|
62
|
+
status: "live",
|
|
63
|
+
required: [
|
|
64
|
+
"images",
|
|
65
|
+
"question"
|
|
66
|
+
],
|
|
67
|
+
oneOf: [],
|
|
68
|
+
optional: [
|
|
69
|
+
"websiteURL"
|
|
70
|
+
],
|
|
71
|
+
proxy: "none",
|
|
72
|
+
credits: 0.01
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
type: "VisionEngine",
|
|
76
|
+
title: "Slider gap (vision model)",
|
|
77
|
+
kind: "recognition",
|
|
78
|
+
family: "slider",
|
|
79
|
+
status: "off",
|
|
80
|
+
offReason: "switched off until a measured run passes",
|
|
81
|
+
required: [
|
|
82
|
+
"module",
|
|
83
|
+
"imageBackground"
|
|
84
|
+
],
|
|
85
|
+
oneOf: [],
|
|
86
|
+
optional: [
|
|
87
|
+
"image"
|
|
88
|
+
],
|
|
89
|
+
proxy: "none",
|
|
90
|
+
credits: 8e-3
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
type: "GeeTestSlide",
|
|
94
|
+
title: "GeeTest slide (v3 and v4)",
|
|
95
|
+
kind: "recognition",
|
|
96
|
+
family: "geetest_slide",
|
|
97
|
+
status: "live",
|
|
98
|
+
required: [
|
|
99
|
+
"version",
|
|
100
|
+
"imageBackground",
|
|
101
|
+
"imageFull",
|
|
102
|
+
"imageSlice",
|
|
103
|
+
"top",
|
|
104
|
+
"bgCssWidth"
|
|
105
|
+
],
|
|
106
|
+
oneOf: [],
|
|
107
|
+
optional: [
|
|
108
|
+
"cssWidth",
|
|
109
|
+
"shuffled",
|
|
110
|
+
"sliceCssWidth",
|
|
111
|
+
"websiteURL"
|
|
112
|
+
],
|
|
113
|
+
proxy: "none",
|
|
114
|
+
credits: 8e-3
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
type: "AltchaTask",
|
|
118
|
+
title: "ALTCHA proof of work",
|
|
119
|
+
kind: "recognition",
|
|
120
|
+
family: "altcha",
|
|
121
|
+
status: "off",
|
|
122
|
+
offReason: "switched off until a measured run passes",
|
|
123
|
+
required: [
|
|
124
|
+
"challenge"
|
|
125
|
+
],
|
|
126
|
+
oneOf: [],
|
|
127
|
+
optional: [
|
|
128
|
+
"websiteURL"
|
|
129
|
+
],
|
|
130
|
+
proxy: "none",
|
|
131
|
+
credits: 4e-3
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
type: "RotateTask",
|
|
135
|
+
title: "Rotate the disc",
|
|
136
|
+
kind: "recognition",
|
|
137
|
+
family: "rotate",
|
|
138
|
+
status: "off",
|
|
139
|
+
offReason: "switched off until a measured run passes",
|
|
140
|
+
required: [
|
|
141
|
+
"imageDisc",
|
|
142
|
+
"imageBackground"
|
|
143
|
+
],
|
|
144
|
+
oneOf: [],
|
|
145
|
+
optional: [
|
|
146
|
+
"discCssWidth",
|
|
147
|
+
"bgCssWidth",
|
|
148
|
+
"websiteURL"
|
|
149
|
+
],
|
|
150
|
+
proxy: "none",
|
|
151
|
+
credits: 8e-3
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
type: "ClickOrderTask",
|
|
155
|
+
title: "Click in order",
|
|
156
|
+
kind: "recognition",
|
|
157
|
+
family: "click_order",
|
|
158
|
+
status: "off",
|
|
159
|
+
offReason: "switched off until a measured run passes",
|
|
160
|
+
required: [
|
|
161
|
+
"image"
|
|
162
|
+
],
|
|
163
|
+
oneOf: [],
|
|
164
|
+
optional: [
|
|
165
|
+
"references",
|
|
166
|
+
"order",
|
|
167
|
+
"count",
|
|
168
|
+
"websiteURL"
|
|
169
|
+
],
|
|
170
|
+
proxy: "none",
|
|
171
|
+
credits: 0.01
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
type: "TextCaptchaTask",
|
|
175
|
+
title: "Question in words",
|
|
176
|
+
kind: "recognition",
|
|
177
|
+
family: "text_question",
|
|
178
|
+
status: "live",
|
|
179
|
+
required: [
|
|
180
|
+
"comment"
|
|
181
|
+
],
|
|
182
|
+
oneOf: [],
|
|
183
|
+
optional: [
|
|
184
|
+
"websiteURL"
|
|
185
|
+
],
|
|
186
|
+
proxy: "none",
|
|
187
|
+
credits: 4e-3
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
type: "BoundingBoxTask",
|
|
191
|
+
title: "Box around an object",
|
|
192
|
+
kind: "recognition",
|
|
193
|
+
family: "bounding_box",
|
|
194
|
+
status: "live",
|
|
195
|
+
required: [
|
|
196
|
+
"body",
|
|
197
|
+
"comment"
|
|
198
|
+
],
|
|
199
|
+
oneOf: [],
|
|
200
|
+
optional: [
|
|
201
|
+
"many",
|
|
202
|
+
"websiteURL"
|
|
203
|
+
],
|
|
204
|
+
proxy: "none",
|
|
205
|
+
credits: 0.01
|
|
206
|
+
},
|
|
207
|
+
{
|
|
208
|
+
type: "DrawAroundTask",
|
|
209
|
+
title: "Line drawn around an object",
|
|
210
|
+
kind: "recognition",
|
|
211
|
+
family: "draw_around",
|
|
212
|
+
status: "off",
|
|
213
|
+
offReason: "switched off until a measured run passes",
|
|
214
|
+
required: [
|
|
215
|
+
"body",
|
|
216
|
+
"comment"
|
|
217
|
+
],
|
|
218
|
+
oneOf: [],
|
|
219
|
+
optional: [
|
|
220
|
+
"many",
|
|
221
|
+
"websiteURL"
|
|
222
|
+
],
|
|
223
|
+
proxy: "none",
|
|
224
|
+
credits: 0.01
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
type: "DragDropTask",
|
|
228
|
+
title: "Drag pieces into the picture",
|
|
229
|
+
kind: "recognition",
|
|
230
|
+
family: "drag_drop",
|
|
231
|
+
status: "live",
|
|
232
|
+
required: [
|
|
233
|
+
"body",
|
|
234
|
+
"pieces"
|
|
235
|
+
],
|
|
236
|
+
oneOf: [],
|
|
237
|
+
optional: [
|
|
238
|
+
"websiteURL"
|
|
239
|
+
],
|
|
240
|
+
proxy: "none",
|
|
241
|
+
credits: 0.01
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
type: "AntiTurnstileTaskProxyLess",
|
|
245
|
+
title: "Cloudflare Turnstile token",
|
|
246
|
+
kind: "token",
|
|
247
|
+
family: "turnstile",
|
|
248
|
+
status: "live",
|
|
249
|
+
required: [
|
|
250
|
+
"websiteURL",
|
|
251
|
+
"websiteKey"
|
|
252
|
+
],
|
|
253
|
+
oneOf: [],
|
|
254
|
+
optional: [
|
|
255
|
+
"metadata",
|
|
256
|
+
"userAgent"
|
|
257
|
+
],
|
|
258
|
+
proxy: "none",
|
|
259
|
+
credits: 8e-3
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
type: "AntiTurnstileTask",
|
|
263
|
+
title: "Cloudflare Turnstile token (your proxy)",
|
|
264
|
+
kind: "token",
|
|
265
|
+
family: "turnstile",
|
|
266
|
+
status: "live",
|
|
267
|
+
required: [
|
|
268
|
+
"websiteURL",
|
|
269
|
+
"websiteKey",
|
|
270
|
+
"proxy"
|
|
271
|
+
],
|
|
272
|
+
oneOf: [],
|
|
273
|
+
optional: [
|
|
274
|
+
"metadata",
|
|
275
|
+
"userAgent"
|
|
276
|
+
],
|
|
277
|
+
proxy: "required",
|
|
278
|
+
credits: 8e-3
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
type: "ReCaptchaV3TaskProxyLess",
|
|
282
|
+
title: "reCAPTCHA v3 token",
|
|
283
|
+
kind: "token",
|
|
284
|
+
family: "recaptcha_v3",
|
|
285
|
+
status: "live",
|
|
286
|
+
required: [
|
|
287
|
+
"websiteURL",
|
|
288
|
+
"websiteKey"
|
|
289
|
+
],
|
|
290
|
+
oneOf: [],
|
|
291
|
+
optional: [
|
|
292
|
+
"pageAction",
|
|
293
|
+
"apiDomain",
|
|
294
|
+
"minScore",
|
|
295
|
+
"enterprisePayload",
|
|
296
|
+
"userAgent"
|
|
297
|
+
],
|
|
298
|
+
proxy: "none",
|
|
299
|
+
credits: 8e-3
|
|
300
|
+
},
|
|
301
|
+
{
|
|
302
|
+
type: "ReCaptchaV3Task",
|
|
303
|
+
title: "reCAPTCHA v3 token (your proxy)",
|
|
304
|
+
kind: "token",
|
|
305
|
+
family: "recaptcha_v3",
|
|
306
|
+
status: "live",
|
|
307
|
+
required: [
|
|
308
|
+
"websiteURL",
|
|
309
|
+
"websiteKey",
|
|
310
|
+
"proxy"
|
|
311
|
+
],
|
|
312
|
+
oneOf: [],
|
|
313
|
+
optional: [
|
|
314
|
+
"pageAction",
|
|
315
|
+
"apiDomain",
|
|
316
|
+
"minScore",
|
|
317
|
+
"enterprisePayload",
|
|
318
|
+
"userAgent"
|
|
319
|
+
],
|
|
320
|
+
proxy: "required",
|
|
321
|
+
credits: 8e-3
|
|
322
|
+
},
|
|
323
|
+
{
|
|
324
|
+
type: "ReCaptchaV3EnterpriseTaskProxyLess",
|
|
325
|
+
title: "reCAPTCHA v3 Enterprise token",
|
|
326
|
+
kind: "token",
|
|
327
|
+
family: "recaptcha_v3_enterprise",
|
|
328
|
+
status: "live",
|
|
329
|
+
required: [
|
|
330
|
+
"websiteURL",
|
|
331
|
+
"websiteKey"
|
|
332
|
+
],
|
|
333
|
+
oneOf: [],
|
|
334
|
+
optional: [
|
|
335
|
+
"pageAction",
|
|
336
|
+
"apiDomain",
|
|
337
|
+
"minScore",
|
|
338
|
+
"enterprisePayload",
|
|
339
|
+
"userAgent"
|
|
340
|
+
],
|
|
341
|
+
proxy: "none",
|
|
342
|
+
credits: 0.012
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
type: "ReCaptchaV3EnterpriseTask",
|
|
346
|
+
title: "reCAPTCHA v3 Enterprise token (your proxy)",
|
|
347
|
+
kind: "token",
|
|
348
|
+
family: "recaptcha_v3_enterprise",
|
|
349
|
+
status: "live",
|
|
350
|
+
required: [
|
|
351
|
+
"websiteURL",
|
|
352
|
+
"websiteKey",
|
|
353
|
+
"proxy"
|
|
354
|
+
],
|
|
355
|
+
oneOf: [],
|
|
356
|
+
optional: [
|
|
357
|
+
"pageAction",
|
|
358
|
+
"apiDomain",
|
|
359
|
+
"minScore",
|
|
360
|
+
"enterprisePayload",
|
|
361
|
+
"userAgent"
|
|
362
|
+
],
|
|
363
|
+
proxy: "required",
|
|
364
|
+
credits: 0.012
|
|
365
|
+
},
|
|
366
|
+
{
|
|
367
|
+
type: "ReCaptchaV2TaskProxyLess",
|
|
368
|
+
title: "reCAPTCHA v2 token",
|
|
369
|
+
kind: "token",
|
|
370
|
+
family: "recaptcha_v2",
|
|
371
|
+
status: "live",
|
|
372
|
+
required: [
|
|
373
|
+
"websiteURL",
|
|
374
|
+
"websiteKey"
|
|
375
|
+
],
|
|
376
|
+
oneOf: [],
|
|
377
|
+
optional: [
|
|
378
|
+
"isInvisible",
|
|
379
|
+
"apiDomain",
|
|
380
|
+
"enterprisePayload",
|
|
381
|
+
"userAgent"
|
|
382
|
+
],
|
|
383
|
+
proxy: "none",
|
|
384
|
+
credits: 0.01
|
|
385
|
+
},
|
|
386
|
+
{
|
|
387
|
+
type: "ReCaptchaV2Task",
|
|
388
|
+
title: "reCAPTCHA v2 token (your proxy)",
|
|
389
|
+
kind: "token",
|
|
390
|
+
family: "recaptcha_v2",
|
|
391
|
+
status: "live",
|
|
392
|
+
required: [
|
|
393
|
+
"websiteURL",
|
|
394
|
+
"websiteKey",
|
|
395
|
+
"proxy"
|
|
396
|
+
],
|
|
397
|
+
oneOf: [],
|
|
398
|
+
optional: [
|
|
399
|
+
"isInvisible",
|
|
400
|
+
"apiDomain",
|
|
401
|
+
"enterprisePayload",
|
|
402
|
+
"userAgent"
|
|
403
|
+
],
|
|
404
|
+
proxy: "required",
|
|
405
|
+
credits: 0.01
|
|
406
|
+
},
|
|
407
|
+
{
|
|
408
|
+
type: "ReCaptchaV2EnterpriseTaskProxyLess",
|
|
409
|
+
title: "reCAPTCHA v2 Enterprise token",
|
|
410
|
+
kind: "token",
|
|
411
|
+
family: "recaptcha_v2_enterprise",
|
|
412
|
+
status: "live",
|
|
413
|
+
required: [
|
|
414
|
+
"websiteURL",
|
|
415
|
+
"websiteKey"
|
|
416
|
+
],
|
|
417
|
+
oneOf: [],
|
|
418
|
+
optional: [
|
|
419
|
+
"isInvisible",
|
|
420
|
+
"apiDomain",
|
|
421
|
+
"enterprisePayload",
|
|
422
|
+
"userAgent"
|
|
423
|
+
],
|
|
424
|
+
proxy: "none",
|
|
425
|
+
credits: 0.012
|
|
426
|
+
},
|
|
427
|
+
{
|
|
428
|
+
type: "ReCaptchaV2EnterpriseTask",
|
|
429
|
+
title: "reCAPTCHA v2 Enterprise token (your proxy)",
|
|
430
|
+
kind: "token",
|
|
431
|
+
family: "recaptcha_v2_enterprise",
|
|
432
|
+
status: "live",
|
|
433
|
+
required: [
|
|
434
|
+
"websiteURL",
|
|
435
|
+
"websiteKey",
|
|
436
|
+
"proxy"
|
|
437
|
+
],
|
|
438
|
+
oneOf: [],
|
|
439
|
+
optional: [
|
|
440
|
+
"isInvisible",
|
|
441
|
+
"apiDomain",
|
|
442
|
+
"enterprisePayload",
|
|
443
|
+
"userAgent"
|
|
444
|
+
],
|
|
445
|
+
proxy: "required",
|
|
446
|
+
credits: 0.012
|
|
447
|
+
},
|
|
448
|
+
{
|
|
449
|
+
type: "AntiCloudflareTask",
|
|
450
|
+
title: "Cloudflare full-page check",
|
|
451
|
+
kind: "token",
|
|
452
|
+
family: "cloudflare",
|
|
453
|
+
status: "live",
|
|
454
|
+
required: [
|
|
455
|
+
"websiteURL",
|
|
456
|
+
"proxy"
|
|
457
|
+
],
|
|
458
|
+
oneOf: [],
|
|
459
|
+
optional: [
|
|
460
|
+
"userAgent"
|
|
461
|
+
],
|
|
462
|
+
proxy: "required",
|
|
463
|
+
credits: 0.012
|
|
464
|
+
}
|
|
465
|
+
]
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
// src/captcha/client.ts
|
|
469
|
+
import { BrowsaError } from "browsa";
|
|
7
470
|
|
|
8
471
|
// src/config.ts
|
|
9
|
-
var VERSION = "0.
|
|
10
|
-
var API_KEY = process.env.BROWSA_API_KEY;
|
|
472
|
+
var VERSION = "0.8.0";
|
|
473
|
+
var API_KEY = process.env.BROWSA_API_KEY?.trim() || void 0;
|
|
11
474
|
var BASE_URL = (process.env.BROWSA_BASE_URL || "https://browsa.io").replace(/\/+$/, "");
|
|
12
475
|
var BASE_URL_SET = !!process.env.BROWSA_BASE_URL;
|
|
13
476
|
var DEFAULT_COUNTRY = process.env.BROWSA_COUNTRY || void 0;
|
|
@@ -20,10 +483,12 @@ var GROUPS = {
|
|
|
20
483
|
schedules: ["create_schedule", "list_schedules"],
|
|
21
484
|
webhooks: ["list_webhooks", "create_webhook", "delete_webhook"],
|
|
22
485
|
cdp: ["start_browser", "stop_browser"],
|
|
23
|
-
captcha: ["solve_captcha_task"],
|
|
486
|
+
captcha: ["solve_captcha_task", "list_captcha_types", "report_captcha_result"],
|
|
487
|
+
captcha_page: ["detect_captcha", "solve_captcha_on_page", "captcha_allowance"],
|
|
24
488
|
admin: ["credits", "list_browsers", "list_identities", "proxy_network", "list_llm_keys", "list_models"]
|
|
25
489
|
};
|
|
26
490
|
var CORE_TOOLS = ["open", "observe", "act", "read", "screenshot", "secrets", "handoff", "flow", "close"];
|
|
491
|
+
var NO_KEY_TOOLS = ["detect_captcha", "captcha_allowance", "list_captcha_types"];
|
|
27
492
|
function toolsSetting(argv) {
|
|
28
493
|
for (let i = 0; i < argv.length; i++) {
|
|
29
494
|
const a = argv[i];
|
|
@@ -34,21 +499,1026 @@ function toolsSetting(argv) {
|
|
|
34
499
|
}
|
|
35
500
|
function enabledExtras(setting = toolsSetting(process.argv.slice(2))) {
|
|
36
501
|
const tools2 = /* @__PURE__ */ new Set();
|
|
502
|
+
const core = new Set(CORE_TOOLS);
|
|
37
503
|
const unknown = [];
|
|
38
504
|
const all = Object.values(GROUPS).flat();
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
505
|
+
const words = setting.split(/[,\s]+/).map((w) => w.trim()).filter(Boolean);
|
|
506
|
+
for (const raw of words) {
|
|
507
|
+
const w = raw.toLowerCase();
|
|
508
|
+
if (w.startsWith("-") || w === "core") continue;
|
|
42
509
|
if (w === "all") all.forEach((t) => tools2.add(t));
|
|
43
510
|
else if (GROUPS[w]) GROUPS[w].forEach((t) => tools2.add(t));
|
|
44
511
|
else if (all.includes(w)) tools2.add(w);
|
|
45
|
-
else unknown.push(raw
|
|
512
|
+
else if (!CORE_TOOLS.includes(w)) unknown.push(raw);
|
|
513
|
+
}
|
|
514
|
+
for (const raw of words) {
|
|
515
|
+
if (!raw.startsWith("-")) continue;
|
|
516
|
+
const w = raw.slice(1).toLowerCase();
|
|
517
|
+
if (w === "core") core.clear();
|
|
518
|
+
else if (GROUPS[w]) GROUPS[w].forEach((t) => tools2.delete(t));
|
|
519
|
+
else if (all.includes(w)) tools2.delete(w);
|
|
520
|
+
else if (CORE_TOOLS.includes(w)) core.delete(w);
|
|
521
|
+
else unknown.push(raw);
|
|
522
|
+
}
|
|
523
|
+
return { tools: tools2, core, unknown };
|
|
524
|
+
}
|
|
525
|
+
function numEnv(name, fallback, min = 0, max = Number.MAX_SAFE_INTEGER) {
|
|
526
|
+
const raw = (process.env[name] ?? "").trim();
|
|
527
|
+
if (!raw) return fallback;
|
|
528
|
+
const n = Number(raw);
|
|
529
|
+
if (!Number.isFinite(n) || n < min) return fallback;
|
|
530
|
+
return Math.min(n, max);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// src/retry.ts
|
|
534
|
+
var RETRIES = numEnv("BROWSA_MCP_RETRIES", 2, 0, 5);
|
|
535
|
+
var BASE_MS = numEnv("BROWSA_MCP_RETRY_BASE_MS", 500, 1, 1e4);
|
|
536
|
+
var CAP_MS = 8e3;
|
|
537
|
+
var MAX_RETRY_AFTER_MS = 3e4;
|
|
538
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
539
|
+
function backoffMs(attempt, base = BASE_MS, random = Math.random) {
|
|
540
|
+
return Math.round(random() * Math.min(CAP_MS, base * 2 ** attempt));
|
|
541
|
+
}
|
|
542
|
+
function retryAfterMs(value, now = Date.now()) {
|
|
543
|
+
if (!value) return null;
|
|
544
|
+
const v = value.trim();
|
|
545
|
+
if (/^\d+(\.\d+)?$/.test(v)) return Math.round(Number(v) * 1e3);
|
|
546
|
+
const at = Date.parse(v);
|
|
547
|
+
return Number.isFinite(at) ? Math.max(0, at - now) : null;
|
|
548
|
+
}
|
|
549
|
+
var defaultIsApiAnswer = (b) => !!b && typeof b === "object" && typeof b.code === "string";
|
|
550
|
+
async function fetchRetry(url, init, opts) {
|
|
551
|
+
const max = opts.retries ?? RETRIES;
|
|
552
|
+
const isApi = opts.isApiAnswer ?? defaultIsApiAnswer;
|
|
553
|
+
for (let attempt = 0; ; attempt++) {
|
|
554
|
+
let resp;
|
|
555
|
+
try {
|
|
556
|
+
resp = await fetch(url, init());
|
|
557
|
+
} catch (e) {
|
|
558
|
+
if (!opts.idempotent || attempt >= max || e?.name === "TimeoutError") throw e;
|
|
559
|
+
await sleep(backoffMs(attempt));
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (attempt >= max) return resp;
|
|
563
|
+
const after = retryAfterMs(resp.headers.get("retry-after"));
|
|
564
|
+
let again = resp.status === 429;
|
|
565
|
+
if (!again && resp.status >= 500 && opts.idempotent) {
|
|
566
|
+
again = after !== null || !isApi(await resp.clone().json().catch(() => null));
|
|
567
|
+
}
|
|
568
|
+
if (!again) return resp;
|
|
569
|
+
if (after !== null && after > MAX_RETRY_AFTER_MS) return resp;
|
|
570
|
+
await resp.body?.cancel().catch(() => {
|
|
571
|
+
});
|
|
572
|
+
await sleep(after ?? backoffMs(attempt));
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// src/captcha/client.ts
|
|
577
|
+
var CAPTCHA_URL = (process.env.BROWSA_CAPTCHA_URL || (BASE_URL_SET ? `${BASE_URL}/captcha-api` : "https://captcha.browsa.io")).replace(/\/+$/, "");
|
|
578
|
+
var POLL_MS = numEnv("BROWSA_CAPTCHA_POLL_MS", 3e3, 1);
|
|
579
|
+
var WAIT_S = 20;
|
|
580
|
+
var IDEMPOTENT = /* @__PURE__ */ new Set(["types", "errors", "health", "getTaskResult", "getBalance"]);
|
|
581
|
+
async function captchaCall(method, payload, opts = {}) {
|
|
582
|
+
const timeoutMs = opts.timeoutMs ?? 3e4;
|
|
583
|
+
const retries = opts.retries ?? RETRIES;
|
|
584
|
+
const init = () => payload === null ? { method: "GET", headers: { Accept: "application/json", "User-Agent": "browsa-mcp" }, signal: AbortSignal.timeout(timeoutMs) } : {
|
|
585
|
+
method: "POST",
|
|
586
|
+
headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "browsa-mcp" },
|
|
587
|
+
body: JSON.stringify({ clientKey: API_KEY, ...payload }),
|
|
588
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
589
|
+
};
|
|
590
|
+
const isApiAnswer = (b) => !!b && typeof b === "object" && "errorId" in b;
|
|
591
|
+
for (let attempt = 0; ; attempt++) {
|
|
592
|
+
const resp = await fetchRetry(`${CAPTCHA_URL}/${method}`, init, { idempotent: IDEMPOTENT.has(method), isApiAnswer, retries });
|
|
593
|
+
const body = await resp.json().catch(() => null);
|
|
594
|
+
if (!isApiAnswer(body)) {
|
|
595
|
+
throw new BrowsaError(`captcha API: unexpected answer (HTTP ${resp.status})`, { code: `HTTP_${resp.status}`, status: resp.status });
|
|
596
|
+
}
|
|
597
|
+
if (body.errorCode === "ERROR_RATE_LIMIT" && attempt < retries) {
|
|
598
|
+
await sleep(backoffMs(attempt, 1e3));
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
return body;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async function runCaptchaTask(task, timeoutMs) {
|
|
605
|
+
const started = Date.now();
|
|
606
|
+
const deadline = started + timeoutMs;
|
|
607
|
+
const hold = () => Math.max(0, Math.min(WAIT_S, Math.floor((deadline - Date.now()) / 1e3)));
|
|
608
|
+
const solved = (taskId, b) => ({
|
|
609
|
+
state: "solved",
|
|
610
|
+
taskId,
|
|
611
|
+
body: b,
|
|
612
|
+
seconds: typeof b.solveSeconds === "number" ? b.solveSeconds : Math.round((Date.now() - started) / 100) / 10
|
|
613
|
+
});
|
|
614
|
+
const created = await captchaCall("createTask", { task, ...hold() ? { waitSeconds: hold() } : {} });
|
|
615
|
+
if (created.errorId) return { state: "error", body: created };
|
|
616
|
+
if (created.status === "ready" && created.solution) return solved(created.taskId, created);
|
|
617
|
+
while (Date.now() < deadline) {
|
|
618
|
+
const wait = hold();
|
|
619
|
+
if (!wait) await sleep(Math.min(POLL_MS, Math.max(0, deadline - Date.now())));
|
|
620
|
+
const asked = Date.now();
|
|
621
|
+
const r = await captchaCall("getTaskResult", { taskId: created.taskId, ...wait ? { waitSeconds: wait } : {} });
|
|
622
|
+
if (r.errorId) return { state: "error", body: { taskId: created.taskId, ...r } };
|
|
623
|
+
if (r.status === "ready") return solved(created.taskId, r);
|
|
624
|
+
if (wait && Date.now() - asked < 1e3) {
|
|
625
|
+
await sleep(Math.min(POLL_MS, Math.max(0, deadline - Date.now())));
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return { state: "timeout", taskId: created.taskId, timeoutMs };
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// src/captcha/catalogue.ts
|
|
632
|
+
var TTL_MS = 60 * 60 * 1e3;
|
|
633
|
+
var PINNED = /^bundled$/i.test((process.env.BROWSA_CAPTCHA_CATALOGUE ?? "").trim());
|
|
634
|
+
var current = { source: "bundled", asOf: catalogue_snapshot_default.asOf, types: catalogue_snapshot_default.types };
|
|
635
|
+
var RETRY_AFTER_FAIL_MS = 60 * 1e3;
|
|
636
|
+
var fetchedAt = 0;
|
|
637
|
+
var failedAt = 0;
|
|
638
|
+
var pending = null;
|
|
639
|
+
function catalogue() {
|
|
640
|
+
return current;
|
|
641
|
+
}
|
|
642
|
+
function typeInfo(name, cat = current) {
|
|
643
|
+
return cat.types.find((t) => t.type === name);
|
|
644
|
+
}
|
|
645
|
+
function fromApi(body, asOf) {
|
|
646
|
+
if (!body || body.errorId || !Array.isArray(body.types) || !body.types.length) return null;
|
|
647
|
+
const names = (ps) => (ps ?? []).map((p) => String(p.name));
|
|
648
|
+
return {
|
|
649
|
+
source: "live",
|
|
650
|
+
asOf,
|
|
651
|
+
types: body.types.map((t) => ({
|
|
652
|
+
type: String(t.type),
|
|
653
|
+
title: String(t.title ?? t.type),
|
|
654
|
+
kind: String(t.kind ?? ""),
|
|
655
|
+
family: String(t.family ?? ""),
|
|
656
|
+
status: String(t.status ?? ""),
|
|
657
|
+
...t.offReason ? { offReason: String(t.offReason) } : {},
|
|
658
|
+
required: names(t.required),
|
|
659
|
+
oneOf: (t.requiredOneOf ?? []).map(names),
|
|
660
|
+
optional: names(t.optional),
|
|
661
|
+
proxy: String(t.proxy ?? "none"),
|
|
662
|
+
credits: typeof t.price?.creditsPerSolve === "number" ? t.price.creditsPerSolve : null
|
|
663
|
+
}))
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
function refreshCatalogue() {
|
|
667
|
+
if (PINNED || Date.now() - fetchedAt < TTL_MS || Date.now() - failedAt < RETRY_AFTER_FAIL_MS) return Promise.resolve();
|
|
668
|
+
pending ??= (async () => {
|
|
669
|
+
try {
|
|
670
|
+
const live = fromApi(await captchaCall("types", null, { timeoutMs: 5e3, retries: 0 }), (/* @__PURE__ */ new Date()).toISOString());
|
|
671
|
+
if (live) {
|
|
672
|
+
current = live;
|
|
673
|
+
fetchedAt = Date.now();
|
|
674
|
+
} else failedAt = Date.now();
|
|
675
|
+
} catch {
|
|
676
|
+
failedAt = Date.now();
|
|
677
|
+
} finally {
|
|
678
|
+
pending = null;
|
|
679
|
+
}
|
|
680
|
+
})();
|
|
681
|
+
return pending;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// src/captcha/tools.ts
|
|
685
|
+
import { BrowsaError as BrowsaError2 } from "browsa";
|
|
686
|
+
|
|
687
|
+
// src/captcha/apply.ts
|
|
688
|
+
var js = (v) => JSON.stringify(v ?? null).replace(/</g, "\\u003c").replace(/[\u2028\u2029]/g, (c) => c === "\u2028" ? "\\u2028" : "\\u2029");
|
|
689
|
+
var HELPERS = `
|
|
690
|
+
const out = { applied: false, fields: 0, callback: "none" };
|
|
691
|
+
const put = (el) => { el.value = token; for (const ev of ["input", "change"]) el.dispatchEvent(new Event(ev, { bubbles: true })); out.fields += 1; };
|
|
692
|
+
const call = (fn, label) => { try { fn(token); out.callback = "called " + label; } catch (e) { out.callback = "threw in " + label + ": " + (e && e.message); } };
|
|
693
|
+
const named = (name) => { const f = String(name).split(".").reduce((o, k) => (o == null ? o : o[k]), window); if (typeof f === "function") call(f, name); else out.callback = "not a function: " + name; };`;
|
|
694
|
+
function turnstileExpression(token, hints = {}) {
|
|
695
|
+
return `(() => {
|
|
696
|
+
const token = ${js(token)};
|
|
697
|
+
const wanted = ${js(hints.callback ?? null)};
|
|
698
|
+
const fieldName = ${js(hints.responseField || "cf-turnstile-response")};${HELPERS}
|
|
699
|
+
const widgets = Array.from(document.querySelectorAll(".cf-turnstile"));
|
|
700
|
+
let fields = Array.from(document.querySelectorAll("input[name='" + fieldName + "'], textarea[name='" + fieldName + "']"));
|
|
701
|
+
if (!fields.length) {
|
|
702
|
+
const host = widgets[0] || document.querySelector("form");
|
|
703
|
+
if (host) { const i = document.createElement("input"); i.type = "hidden"; i.name = fieldName; host.appendChild(i); fields = [i]; out.created_field = true; }
|
|
704
|
+
}
|
|
705
|
+
fields.forEach(put);
|
|
706
|
+
for (const w of widgets) w.querySelectorAll("[name='g-recaptcha-response']").forEach(put);
|
|
707
|
+
if (window.turnstile && typeof window.turnstile.getResponse === "function") { try { window.turnstile.getResponse = () => token; out.get_response = "answers this token"; } catch (e) {} }
|
|
708
|
+
const cb = wanted || widgets.map((w) => w.getAttribute("data-callback")).find(Boolean);
|
|
709
|
+
if (cb) named(cb);
|
|
710
|
+
out.applied = out.fields > 0 || out.callback.indexOf("called") === 0;
|
|
711
|
+
return out;
|
|
712
|
+
})()`;
|
|
713
|
+
}
|
|
714
|
+
function recaptchaExpression(token, hints = {}, v3 = false) {
|
|
715
|
+
return `(() => {
|
|
716
|
+
const token = ${js(token)};
|
|
717
|
+
const wanted = ${js(hints.callback ?? null)};
|
|
718
|
+
const v3 = ${v3 ? "true" : "false"};${HELPERS}
|
|
719
|
+
const widgets = Array.from(document.querySelectorAll(".g-recaptcha"));
|
|
720
|
+
let fields = Array.from(document.querySelectorAll("textarea[name='g-recaptcha-response'], textarea[id^='g-recaptcha-response'], input[name='g-recaptcha-response']"));
|
|
721
|
+
if (!fields.length && !v3) {
|
|
722
|
+
const host = widgets[0] || document.querySelector("form");
|
|
723
|
+
if (host) { const t = document.createElement("textarea"); t.name = "g-recaptcha-response"; t.style.display = "none"; host.appendChild(t); fields = [t]; out.created_field = true; }
|
|
724
|
+
}
|
|
725
|
+
fields.forEach(put);
|
|
726
|
+
const apis = [window.grecaptcha, window.grecaptcha && window.grecaptcha.enterprise].filter(Boolean);
|
|
727
|
+
for (const g of apis) {
|
|
728
|
+
try { if (typeof g.getResponse === "function") { g.getResponse = () => token; out.get_response = "answers this token"; } } catch (e) {}
|
|
729
|
+
try { if (v3 && typeof g.execute === "function") { g.execute = () => Promise.resolve(token); out.execute = "answers this token"; } } catch (e) {}
|
|
730
|
+
}
|
|
731
|
+
let cb = wanted || widgets.map((w) => w.getAttribute("data-callback")).find(Boolean);
|
|
732
|
+
if (cb) named(cb);
|
|
733
|
+
else if (!v3) {
|
|
734
|
+
const seen = new Set();
|
|
735
|
+
const find = (o, depth) => {
|
|
736
|
+
if (!o || typeof o !== "object" || depth > 5 || seen.has(o)) return null;
|
|
737
|
+
if (typeof Node !== "undefined" && o instanceof Node) return null;
|
|
738
|
+
seen.add(o);
|
|
739
|
+
for (const k of Object.keys(o)) {
|
|
740
|
+
let v; try { v = o[k]; } catch (e) { continue; }
|
|
741
|
+
if (k === "callback" && (typeof v === "function" || typeof v === "string")) return v;
|
|
742
|
+
const r = find(v, depth + 1);
|
|
743
|
+
if (r) return r;
|
|
744
|
+
}
|
|
745
|
+
return null;
|
|
746
|
+
};
|
|
747
|
+
const cfg = window.___grecaptcha_cfg;
|
|
748
|
+
const found = cfg && cfg.clients ? find(cfg.clients, 0) : null;
|
|
749
|
+
if (typeof found === "function") call(found, "the widget's callback");
|
|
750
|
+
else if (typeof found === "string") named(found);
|
|
751
|
+
}
|
|
752
|
+
out.applied = out.fields > 0 || out.callback.indexOf("called") === 0 || !!out.execute;
|
|
753
|
+
return out;
|
|
754
|
+
})()`;
|
|
755
|
+
}
|
|
756
|
+
var TOKEN_STEPS = [
|
|
757
|
+
"Evaluate apply.expression in the page's main frame.",
|
|
758
|
+
'If its result has callback "called ...", the page has the token: wait for the page to move on. Otherwise submit the form the widget is in.',
|
|
759
|
+
"Check the page's own answer. applied false means no field or callback was found: the widget may be in another frame, or not rendered yet."
|
|
760
|
+
];
|
|
761
|
+
function buildApply(type, solution, websiteURL, hints = {}) {
|
|
762
|
+
const s = solution ?? {};
|
|
763
|
+
if (/Cloudflare/i.test(type) || s.cookies && typeof s.cookies === "object") {
|
|
764
|
+
let host = "";
|
|
765
|
+
try {
|
|
766
|
+
host = new URL(String(websiteURL)).hostname;
|
|
767
|
+
} catch {
|
|
768
|
+
}
|
|
769
|
+
const cookies = Object.entries(s.cookies ?? (s.token ? { cf_clearance: s.token } : {})).map(([name, value]) => ({ name, value: String(value), domain: host, path: "/", secure: true }));
|
|
770
|
+
return {
|
|
771
|
+
how: "cookies",
|
|
772
|
+
cookies,
|
|
773
|
+
...s.userAgent ? { user_agent: String(s.userAgent) } : {},
|
|
774
|
+
steps: [
|
|
775
|
+
"Set these cookies in your browser for that domain, and send exactly this user agent.",
|
|
776
|
+
"Re-request the URL through the same proxy the task used. Do not reload the challenge page: a reload asks for a new check.",
|
|
777
|
+
"The cookie only works from the address that passed the check."
|
|
778
|
+
]
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
if (typeof s.token === "string" && /Turnstile/i.test(type)) {
|
|
782
|
+
return { how: "evaluate", expression: turnstileExpression(s.token, hints), steps: TOKEN_STEPS, valid_seconds: 300 };
|
|
783
|
+
}
|
|
784
|
+
if (typeof s.gRecaptchaResponse === "string") {
|
|
785
|
+
const v3 = /V3/i.test(type);
|
|
786
|
+
return {
|
|
787
|
+
how: "evaluate",
|
|
788
|
+
expression: recaptchaExpression(s.gRecaptchaResponse, hints, v3),
|
|
789
|
+
valid_seconds: 120,
|
|
790
|
+
steps: v3 ? [
|
|
791
|
+
"Evaluate apply.expression in the page's main frame: the page's next grecaptcha.execute() call answers this token.",
|
|
792
|
+
"Then do the page's own action (its button): its script sends the token.",
|
|
793
|
+
"A v3 token is scored by the site; check the page's own answer."
|
|
794
|
+
] : TOKEN_STEPS
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
return { how: "manual", steps: ["This solution has no page step this server knows: use its fields as the page's own code would."] };
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// src/captcha/detect.ts
|
|
801
|
+
var MAX_HTML = 3e6;
|
|
802
|
+
var ENT = { amp: "&", quot: '"', apos: "'", lt: "<", gt: ">", "#39": "'", "#x27": "'", "#34": '"', "#38": "&" };
|
|
803
|
+
var decode = (s) => s.replace(/&(amp|quot|apos|lt|gt|#39|#x27|#34|#38);/gi, (_, e) => ENT[e.toLowerCase()] ?? _);
|
|
804
|
+
var TAG = /<\/form\s*>|<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^\s"'<>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>]+))?)*)\s*\/?>/g;
|
|
805
|
+
var ATTR = /([^\s"'<>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>]+)))?/g;
|
|
806
|
+
function attrsOf(raw) {
|
|
807
|
+
const out = {};
|
|
808
|
+
for (const m of raw.matchAll(ATTR)) {
|
|
809
|
+
const k = m[1].toLowerCase();
|
|
810
|
+
if (!(k in out)) out[k] = decode(m[2] ?? m[3] ?? m[4] ?? "");
|
|
811
|
+
}
|
|
812
|
+
return out;
|
|
813
|
+
}
|
|
814
|
+
function scan(input) {
|
|
815
|
+
const truncated = input.length > MAX_HTML;
|
|
816
|
+
let html = truncated ? input.slice(0, MAX_HTML) : input;
|
|
817
|
+
html = html.replace(/<!--[\s\S]*?-->/g, " ");
|
|
818
|
+
const title = decode((/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? "").replace(/\s+/g, " ").trim());
|
|
819
|
+
const scripts = [];
|
|
820
|
+
html = html.replace(/(<script\b[^>]*>)([\s\S]*?)<\/script\s*>/gi, (_, open2, body) => {
|
|
821
|
+
const type = /\btype\s*=\s*["']?([^"'\s>]+)/i.exec(open2)?.[1]?.toLowerCase() ?? "";
|
|
822
|
+
if (body.trim() && (!type || /javascript|ecmascript|^module$/.test(type))) scripts.push(body);
|
|
823
|
+
return open2;
|
|
824
|
+
});
|
|
825
|
+
html = html.replace(/<(style|pre|code|xmp|noscript|template|svg)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, " ");
|
|
826
|
+
html = html.replace(/(<textarea\b[^>]*>)[\s\S]*?<\/textarea\s*>/gi, "$1");
|
|
827
|
+
const tags = [];
|
|
828
|
+
let form = -1;
|
|
829
|
+
let forms = 0;
|
|
830
|
+
for (const m of html.matchAll(TAG)) {
|
|
831
|
+
if (!m[1]) {
|
|
832
|
+
form = -1;
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
835
|
+
const name = m[1].toLowerCase();
|
|
836
|
+
if (name === "form") form = forms++;
|
|
837
|
+
tags.push({ name, attrs: attrsOf(m[2] ?? ""), form });
|
|
838
|
+
}
|
|
839
|
+
return { tags, scripts, title, truncated };
|
|
840
|
+
}
|
|
841
|
+
function parseUrl(raw, base, from) {
|
|
842
|
+
const v = (raw || "").trim();
|
|
843
|
+
if (!v || /^(data|blob|javascript|about):/i.test(v)) return null;
|
|
844
|
+
try {
|
|
845
|
+
const u = new URL(v.startsWith("//") ? `https:${v}` : v, base || "https://page.invalid/");
|
|
846
|
+
return { url: u.href, host: u.hostname.toLowerCase(), path: u.pathname, search: u.searchParams, from };
|
|
847
|
+
} catch {
|
|
848
|
+
return null;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
var hasClass = (t, cls) => (t.attrs.class ?? "").split(/\s+/).includes(cls);
|
|
852
|
+
var hostIs = (h, re) => re.test(h);
|
|
853
|
+
var uniq = (xs) => [...new Set(xs)];
|
|
854
|
+
var TURNSTILE_KEY = /^(0x[0-9A-Za-z_-]{18,}|[123]x0{8,}[0-9A-Za-z]{2})$/;
|
|
855
|
+
var TURNSTILE_KEY_IN = /(0x4[0-9A-Za-z_-]{18,}|[123]x0{8,}[0-9A-Za-z]{2})/;
|
|
856
|
+
var RECAPTCHA_KEY = /^6L[0-9A-Za-z_-]{38}$/;
|
|
857
|
+
var TEST_KEYS = /^([123]x0{8,}[0-9A-Za-z]{2}|6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI|10000000-ffff-ffff-ffff-000000000001)$/;
|
|
858
|
+
var CHECK_TITLE = /just a moment|un instant|einen moment|un momento|um momento|attention required|checking your browser|ちょっと待|請稍候|请稍候/i;
|
|
859
|
+
var OTHER_FRAMES = [
|
|
860
|
+
[/(^|\.)(arkoselabs\.com|funcaptcha\.com)$/, "arkose", "Arkose (FunCaptcha)"],
|
|
861
|
+
[/(^|\.)mtcaptcha\.com$/, "mtcaptcha", "MTCaptcha"],
|
|
862
|
+
[/(^|\.)captcha\.(qcloud|qq)\.com$|(^|\.)turing\.captcha\.qcloud\.com$/, "tencent", "Tencent captcha"],
|
|
863
|
+
[/(^|\.)friendlycaptcha\.(com|eu)$/, "friendly_captcha", "Friendly Captcha"],
|
|
864
|
+
[/(^|\.)captchafox\.com$/, "captchafox", "CaptchaFox"],
|
|
865
|
+
[/(^|\.)leminnow\.com$/, "lemin", "Lemin"]
|
|
866
|
+
];
|
|
867
|
+
var PX_HOSTS = /(^|\.)(px-cdn\.net|px-cloud\.net|perimeterx\.net|pxchk\.net|px-cdn\.com|humansecurity\.com)$/;
|
|
868
|
+
var PX_PATH = /\/px\/[A-Za-z0-9]+\/(captcha|init)/i;
|
|
869
|
+
function near(script, at, re, span = 600) {
|
|
870
|
+
return re.exec(script.slice(at, at + span))?.[1];
|
|
871
|
+
}
|
|
872
|
+
function detectCaptchas(input) {
|
|
873
|
+
const { tags, scripts, title, truncated } = scan(String(input.html ?? ""));
|
|
874
|
+
const pageUrl = /^https?:\/\//i.test(input.url ?? "") ? String(input.url) : void 0;
|
|
875
|
+
const res = [];
|
|
876
|
+
for (const t of tags) {
|
|
877
|
+
if (t.name === "script" && t.attrs.src) {
|
|
878
|
+
const r = parseUrl(t.attrs.src, pageUrl, "script");
|
|
879
|
+
if (r) res.push(r);
|
|
880
|
+
}
|
|
881
|
+
if (t.name === "iframe" && t.attrs.src) {
|
|
882
|
+
const r = parseUrl(t.attrs.src, pageUrl, "frame");
|
|
883
|
+
if (r) res.push(r);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
for (const u of input.resources ?? []) {
|
|
887
|
+
const r = parseUrl(String(u), pageUrl, "resource");
|
|
888
|
+
if (r) res.push(r);
|
|
889
|
+
}
|
|
890
|
+
const code = scripts.join("\n;\n");
|
|
891
|
+
const findings = [];
|
|
892
|
+
const urlMissing = pageUrl ? [] : ["websiteURL: pass url, the address of the page"];
|
|
893
|
+
const base = () => ({ params: pageUrl ? { websiteURL: pageUrl } : {}, page: {}, missing: [...urlMissing], evidence: [], notes: [] });
|
|
894
|
+
const cfOpt = /\b_cf_chl_opt\b/.test(code);
|
|
895
|
+
const cfOrchestrate = res.some((r) => /\/cdn-cgi\/challenge-platform\/.*\/orchestrate\/(chl_page|managed|jsch)\//.test(r.path));
|
|
896
|
+
const cfForm = tags.some((t) => t.attrs.id === "challenge-form" || t.attrs.id === "challenge-error-text" || t.attrs.id === "cf-challenge-running");
|
|
897
|
+
const cfPage = cfOpt || cfOrchestrate || CHECK_TITLE.test(title) && cfForm;
|
|
898
|
+
if (cfPage) {
|
|
899
|
+
const f = { kind: "cloudflare", name: "Cloudflare check page", ...base(), confidence: cfOpt || cfOrchestrate ? "high" : "medium" };
|
|
900
|
+
if (cfOpt) f.evidence.push("script: window._cf_chl_opt");
|
|
901
|
+
if (cfOrchestrate) f.evidence.push("script: /cdn-cgi/challenge-platform/.../orchestrate/");
|
|
902
|
+
if (CHECK_TITLE.test(title)) f.evidence.push(`title: ${title.slice(0, 60)}`);
|
|
903
|
+
f.missing.push("proxy: your proxy URL (the cookie only works from the address that passed the check)");
|
|
904
|
+
f.notes.push("The answer is a cookie, not a token: set it, send the same user agent, and request the page again.");
|
|
905
|
+
findings.push(f);
|
|
906
|
+
}
|
|
907
|
+
{
|
|
908
|
+
const widgets = tags.filter((t) => hasClass(t, "cf-turnstile"));
|
|
909
|
+
const frames = res.filter((r) => r.host === "challenges.cloudflare.com" && /\/turnstile\//.test(r.path) && !/\/api\.js$/.test(r.path));
|
|
910
|
+
const api = res.some((r) => r.host === "challenges.cloudflare.com" && /\/turnstile\/v0\/api\.js$/.test(r.path));
|
|
911
|
+
const field = tags.some((t) => t.attrs.name === "cf-turnstile-response");
|
|
912
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
913
|
+
const get = (key) => {
|
|
914
|
+
let f = byKey.get(key);
|
|
915
|
+
if (!f) {
|
|
916
|
+
f = { kind: "turnstile", name: "Cloudflare Turnstile", ...base(), confidence: "high" };
|
|
917
|
+
f.params.websiteKey = key;
|
|
918
|
+
byKey.set(key, f);
|
|
919
|
+
}
|
|
920
|
+
return f;
|
|
921
|
+
};
|
|
922
|
+
for (const r of frames) {
|
|
923
|
+
const key = TURNSTILE_KEY_IN.exec(r.path)?.[1];
|
|
924
|
+
if (key) get(key).evidence.push(`${r.from}: challenges.cloudflare.com widget frame with the key`);
|
|
925
|
+
}
|
|
926
|
+
for (const w of widgets) {
|
|
927
|
+
const key = (w.attrs["data-sitekey"] ?? "").trim();
|
|
928
|
+
if (!TURNSTILE_KEY.test(key)) continue;
|
|
929
|
+
const f = get(key);
|
|
930
|
+
f.evidence.push(`<${w.name} class="cf-turnstile" data-sitekey>`);
|
|
931
|
+
const meta = {};
|
|
932
|
+
if (w.attrs["data-action"]) meta.action = w.attrs["data-action"];
|
|
933
|
+
if (w.attrs["data-cdata"]) meta.cdata = w.attrs["data-cdata"];
|
|
934
|
+
if (Object.keys(meta).length) f.params.metadata = meta;
|
|
935
|
+
if (w.attrs["data-callback"]) f.page.callback = w.attrs["data-callback"];
|
|
936
|
+
if (w.attrs["data-response-field-name"]) f.page.responseField = w.attrs["data-response-field-name"];
|
|
937
|
+
}
|
|
938
|
+
for (const m of code.matchAll(/\bturnstile\s*\.\s*render\s*\(/g)) {
|
|
939
|
+
const key = near(code, m.index, /sitekey["']?\s*:\s*["']([^"']+)["']/);
|
|
940
|
+
if (!key || !TURNSTILE_KEY.test(key)) continue;
|
|
941
|
+
const f = get(key);
|
|
942
|
+
f.evidence.push("script: turnstile.render({sitekey})");
|
|
943
|
+
const action = near(code, m.index, /\baction["']?\s*:\s*["']([^"']+)["']/);
|
|
944
|
+
const cdata = near(code, m.index, /\bcData["']?\s*:\s*["']([^"']+)["']/);
|
|
945
|
+
if (action || cdata) f.params.metadata = { ...f.params.metadata ?? {}, ...action ? { action } : {}, ...cdata ? { cdata } : {} };
|
|
946
|
+
const cb = near(code, m.index, /\bcallback["']?\s*:\s*([A-Za-z_$][\w$.]*)\s*[,}]/);
|
|
947
|
+
if (cb && !f.page.callback && !/^function$/.test(cb)) f.page.callback = cb;
|
|
948
|
+
}
|
|
949
|
+
for (const f of byKey.values()) findings.push(f);
|
|
950
|
+
if (!byKey.size && !cfPage && (api || field || widgets.length)) {
|
|
951
|
+
const f = { kind: "turnstile", name: "Cloudflare Turnstile", ...base(), confidence: widgets.length || field ? "medium" : "low" };
|
|
952
|
+
if (api) f.evidence.push("script: challenges.cloudflare.com/turnstile/v0/api.js");
|
|
953
|
+
if (field) f.evidence.push("input name=cf-turnstile-response");
|
|
954
|
+
if (widgets.length) f.evidence.push("class cf-turnstile without data-sitekey");
|
|
955
|
+
f.missing.push("websiteKey: not in the HTML; pass resources (the page's frame URLs): the challenges.cloudflare.com frame address holds the key (0x...)");
|
|
956
|
+
findings.push(f);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
{
|
|
960
|
+
const G = /^(www\.)?(google\.com|recaptcha\.net)$/;
|
|
961
|
+
const apis = res.filter((r) => hostIs(r.host, G) && /\/recaptcha\/(api|enterprise)\.js$/.test(r.path));
|
|
962
|
+
const anchors = res.filter((r) => hostIs(r.host, G) && /\/recaptcha\/(api2|enterprise)\/anchor$/.test(r.path));
|
|
963
|
+
const widgets = tags.filter((t) => hasClass(t, "g-recaptcha"));
|
|
964
|
+
const field = tags.some((t) => t.attrs.name === "g-recaptcha-response");
|
|
965
|
+
const enterprise = apis.some((r) => /enterprise\.js$/.test(r.path)) || anchors.some((r) => /\/enterprise\//.test(r.path)) || /\bgrecaptcha\s*\.\s*enterprise\b/.test(code);
|
|
966
|
+
const net = [...apis, ...anchors].some((r) => /recaptcha\.net$/.test(r.host));
|
|
967
|
+
const keys = /* @__PURE__ */ new Map();
|
|
968
|
+
const get = (key) => {
|
|
969
|
+
let k = keys.get(key);
|
|
970
|
+
if (!k) {
|
|
971
|
+
k = { v3: false, invisible: false, evidence: [], sure: false };
|
|
972
|
+
keys.set(key, k);
|
|
973
|
+
}
|
|
974
|
+
return k;
|
|
975
|
+
};
|
|
976
|
+
for (const r of anchors) {
|
|
977
|
+
const key = r.search.get("k") ?? "";
|
|
978
|
+
if (!RECAPTCHA_KEY.test(key)) continue;
|
|
979
|
+
const k = get(key);
|
|
980
|
+
k.sure = true;
|
|
981
|
+
if (r.search.get("size") === "invisible") k.invisible = true;
|
|
982
|
+
k.evidence.push(`${r.from}: recaptcha anchor frame, k=`);
|
|
983
|
+
}
|
|
984
|
+
for (const r of apis) {
|
|
985
|
+
const render = r.search.get("render") ?? "";
|
|
986
|
+
if (!RECAPTCHA_KEY.test(render)) continue;
|
|
987
|
+
const k = get(render);
|
|
988
|
+
k.v3 = true;
|
|
989
|
+
k.sure = true;
|
|
990
|
+
k.evidence.push(`script: recaptcha/${/enterprise/.test(r.path) ? "enterprise" : "api"}.js?render=<key>`);
|
|
991
|
+
}
|
|
992
|
+
for (const w of widgets) {
|
|
993
|
+
const key = (w.attrs["data-sitekey"] ?? "").trim();
|
|
994
|
+
if (!RECAPTCHA_KEY.test(key)) continue;
|
|
995
|
+
const k = get(key);
|
|
996
|
+
k.evidence.push(`<${w.name} class="g-recaptcha" data-sitekey>`);
|
|
997
|
+
if ((w.attrs["data-size"] ?? "").toLowerCase() === "invisible") k.invisible = true;
|
|
998
|
+
if (w.attrs["data-callback"]) k.callback = w.attrs["data-callback"];
|
|
999
|
+
if (w.attrs["data-action"]) {
|
|
1000
|
+
k.v3 = true;
|
|
1001
|
+
k.action = w.attrs["data-action"];
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
for (const m of code.matchAll(/\bgrecaptcha\s*(?:\.\s*enterprise\s*)?\.\s*execute\s*\(\s*["']([^"']+)["']/g)) {
|
|
1005
|
+
if (!RECAPTCHA_KEY.test(m[1])) continue;
|
|
1006
|
+
const k = get(m[1]);
|
|
1007
|
+
k.v3 = true;
|
|
1008
|
+
k.action ??= near(code, m.index, /\baction["']?\s*:\s*["']([^"']+)["']/, 300);
|
|
1009
|
+
k.evidence.push("script: grecaptcha.execute(key, {action})");
|
|
1010
|
+
}
|
|
1011
|
+
for (const m of code.matchAll(/\bgrecaptcha\s*(?:\.\s*enterprise\s*)?\.\s*render\s*\(/g)) {
|
|
1012
|
+
const key = near(code, m.index, /sitekey["']?\s*:\s*["']([^"']+)["']/);
|
|
1013
|
+
if (!key || !RECAPTCHA_KEY.test(key)) continue;
|
|
1014
|
+
const k = get(key);
|
|
1015
|
+
if (near(code, m.index, /\bsize["']?\s*:\s*["'](invisible)["']/)) k.invisible = true;
|
|
1016
|
+
const cb = near(code, m.index, /\bcallback["']?\s*:\s*([A-Za-z_$][\w$.]*)\s*[,}]/);
|
|
1017
|
+
if (cb && !k.callback && cb !== "function") k.callback = cb;
|
|
1018
|
+
k.evidence.push("script: grecaptcha.render({sitekey})");
|
|
1019
|
+
}
|
|
1020
|
+
for (const [key, k] of keys) {
|
|
1021
|
+
const fam = `recaptcha_${k.v3 ? "v3" : "v2"}${enterprise ? "_enterprise" : ""}`;
|
|
1022
|
+
const f = { kind: fam, name: `reCAPTCHA ${k.v3 ? "v3" : "v2"}${enterprise ? " Enterprise" : ""}`, ...base(), confidence: "high" };
|
|
1023
|
+
f.params.websiteKey = key;
|
|
1024
|
+
if (k.v3) {
|
|
1025
|
+
if (k.action) f.params.pageAction = k.action;
|
|
1026
|
+
} else if (k.invisible) f.params.isInvisible = true;
|
|
1027
|
+
if (net) f.params.apiDomain = "recaptcha.net";
|
|
1028
|
+
if (k.callback) f.page.callback = k.callback;
|
|
1029
|
+
f.evidence.push(...uniq(k.evidence));
|
|
1030
|
+
if (k.v3 && !k.action) f.notes.push("pageAction was not found in the HTML: read it from the page's grecaptcha.execute call, the site may check it.");
|
|
1031
|
+
if (!k.v3 && !k.sure && widgets.some((w) => w.attrs["data-sitekey"] === key && w.name === "button")) {
|
|
1032
|
+
f.notes.push("A key bound to a button can be v2 invisible or v3: if the token is refused, solve again as the other version.");
|
|
1033
|
+
}
|
|
1034
|
+
findings.push(f);
|
|
1035
|
+
}
|
|
1036
|
+
if (!keys.size && (apis.length || widgets.length || field)) {
|
|
1037
|
+
const v3ish = apis.some((r) => {
|
|
1038
|
+
const x = r.search.get("render");
|
|
1039
|
+
return !!x && x !== "explicit" && x !== "onload";
|
|
1040
|
+
});
|
|
1041
|
+
const f = {
|
|
1042
|
+
kind: `recaptcha_${v3ish ? "v3" : "v2"}${enterprise ? "_enterprise" : ""}`,
|
|
1043
|
+
name: `reCAPTCHA${enterprise ? " Enterprise" : ""}`,
|
|
1044
|
+
...base(),
|
|
1045
|
+
confidence: widgets.length || field ? "medium" : "low"
|
|
1046
|
+
};
|
|
1047
|
+
if (apis.length) f.evidence.push("script: recaptcha api.js");
|
|
1048
|
+
if (widgets.length) f.evidence.push("class g-recaptcha without data-sitekey");
|
|
1049
|
+
if (field) f.evidence.push("textarea name=g-recaptcha-response");
|
|
1050
|
+
f.missing.push("websiteKey: not in the HTML; pass resources (the page's frame URLs): the recaptcha anchor frame has it as k=");
|
|
1051
|
+
f.notes.push("The version (v2 or v3) could not be told without the key's frame or script.");
|
|
1052
|
+
findings.push(f);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
{
|
|
1056
|
+
const gt = res.filter((r) => /(^|\.)(geetest|geevisit)\.com$/.test(r.host));
|
|
1057
|
+
const init3 = /\binitGeetest\s*\(/.test(code);
|
|
1058
|
+
const init4 = /\binitGeetest4\s*\(/.test(code);
|
|
1059
|
+
if (gt.length || init3 || init4) {
|
|
1060
|
+
const v4 = init4 || gt.some((r) => /^gcaptcha4\./.test(r.host) || /\/v4\/|gt4\.js/.test(r.path));
|
|
1061
|
+
const f = { kind: "geetest_slide", name: `GeeTest v${v4 ? 4 : 3}`, ...base(), confidence: "high" };
|
|
1062
|
+
f.missing = [];
|
|
1063
|
+
f.params = { version: v4 ? 4 : 3 };
|
|
1064
|
+
if (gt.length) f.evidence.push(`${gt[0].from}: ${gt[0].host}`);
|
|
1065
|
+
if (init3 || init4) f.evidence.push(`script: ${init4 ? "initGeetest4" : "initGeetest"}()`);
|
|
1066
|
+
f.missing.push(v4 ? "imageBackground, imageSlice, top, bgCssWidth: the puzzle's two pictures and the piece's position, from the open widget" : "imageBackground, imageFull: GeeTest's two pictures as served, from the open widget");
|
|
1067
|
+
f.notes.push("Only the slide puzzle is answered, and only as a distance to drag: the drag is yours to make.");
|
|
1068
|
+
findings.push(f);
|
|
1069
|
+
}
|
|
1070
|
+
const waf = res.filter((r) => /(^|\.)awswaf\.com$/.test(r.host));
|
|
1071
|
+
const wafCaptcha = waf.some((r) => /captcha\.js$/.test(r.path)) || tags.some((t) => t.name === "awswaf-captcha") || /\bAwsWafCaptcha\s*\.\s*renderCaptcha\s*\(/.test(code) || waf.length > 0 && tags.some((t) => /\bamzn-captcha-/.test(t.attrs.class ?? ""));
|
|
1072
|
+
if (wafCaptcha) {
|
|
1073
|
+
const f = { kind: "aws_waf", name: "AWS WAF captcha", ...base(), confidence: "high" };
|
|
1074
|
+
f.missing = [];
|
|
1075
|
+
f.params = {};
|
|
1076
|
+
f.evidence.push(waf.length ? `${waf[0].from}: ${waf[0].host}` : "awswaf-captcha element");
|
|
1077
|
+
f.missing.push('images, question: the grid picture and "aws:grid:<object>" from the open puzzle');
|
|
1078
|
+
f.notes.push("The answer is the tiles to click: the clicks are yours to make.");
|
|
1079
|
+
findings.push(f);
|
|
1080
|
+
}
|
|
1081
|
+
const dd = res.filter((r) => /(^|\.)captcha-delivery\.com$/.test(r.host) && /\/captcha\//.test(r.path));
|
|
1082
|
+
if (dd.length) {
|
|
1083
|
+
const f = { kind: "slider", name: "DataDome slider", ...base(), confidence: "high" };
|
|
1084
|
+
f.missing = ["imageBackground: the puzzle picture with the gap, from the frame"];
|
|
1085
|
+
f.params = { module: "slider_1" };
|
|
1086
|
+
f.evidence.push(`${dd[0].from}: ${dd[0].host}/captcha/`);
|
|
1087
|
+
findings.push(f);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
{
|
|
1091
|
+
const hints = (t, keys) => keys.map((k) => t.attrs[k] ?? "").join(" ").toLowerCase();
|
|
1092
|
+
const inputs = tags.filter((t) => t.name === "input" && ["text", ""].includes((t.attrs.type ?? "text").toLowerCase()));
|
|
1093
|
+
const capInputs = inputs.filter((t) => hints(t, ["placeholder", "name", "id", "aria-label", "class"]).includes("captcha") && !/g-recaptcha|h-captcha|cf-turnstile/.test(hints(t, ["name", "id", "class"])));
|
|
1094
|
+
const imgs = tags.filter((t) => t.name === "img");
|
|
1095
|
+
const about = (t) => `${hints(t, ["alt", "id", "class", "title", "name"])} ${/^data:/i.test(t.attrs.src ?? "") ? "" : (t.attrs.src ?? "").toLowerCase()}`;
|
|
1096
|
+
const strong = imgs.find((t) => about(t).includes("captcha") && !(t.attrs.src ?? "").toLowerCase().split("?")[0].endsWith(".svg") && !/recaptcha|hcaptcha|logo|badge|icon/.test(about(t)));
|
|
1097
|
+
const inline = imgs.find((t) => /^(data:image\/(?!svg)|blob:)/i.test(t.attrs.src ?? ""));
|
|
1098
|
+
let img;
|
|
1099
|
+
let confidence = "high";
|
|
1100
|
+
if (strong && capInputs.length) img = strong;
|
|
1101
|
+
else if (strong) {
|
|
1102
|
+
const answer2 = inputs.find((t) => t.form >= 0 && t.form === strong.form && /captcha|answer|code|characters|text/.test(hints(t, ["placeholder", "name", "id", "aria-label"])));
|
|
1103
|
+
if (answer2) {
|
|
1104
|
+
img = strong;
|
|
1105
|
+
confidence = "medium";
|
|
1106
|
+
}
|
|
1107
|
+
} else if (capInputs.length && inline) img = inline;
|
|
1108
|
+
if (img) {
|
|
1109
|
+
const f = { kind: "image_text", name: "Image text captcha", ...base(), confidence };
|
|
1110
|
+
f.missing = [];
|
|
1111
|
+
const src = img.attrs.src ?? "";
|
|
1112
|
+
f.evidence.push(`<img ${img.attrs.id ? `id="${img.attrs.id}" ` : ""}src="${src.slice(0, 80)}${src.length > 80 ? "..." : ""}"> with an answer field`);
|
|
1113
|
+
f.missing.push(/^data:image\//i.test(src) ? "body: the picture; its src is a data: URL, pass that as body" : "body: the picture as base64 (take it from the element in your browser, e.g. a screenshot of the <img>)");
|
|
1114
|
+
f.notes.push("The answer is text to type into the page's field.");
|
|
1115
|
+
findings.push(f);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
{
|
|
1119
|
+
const add = (kind, name, evidence, extra) => {
|
|
1120
|
+
let f = findings.find((x) => x.kind === kind);
|
|
1121
|
+
if (!f) {
|
|
1122
|
+
f = { kind, name, params: {}, page: {}, missing: [], evidence: [], confidence: "high", notes: [] };
|
|
1123
|
+
findings.push(f);
|
|
1124
|
+
}
|
|
1125
|
+
f.evidence.push(evidence);
|
|
1126
|
+
extra?.(f);
|
|
1127
|
+
};
|
|
1128
|
+
const hc = tags.filter((t) => hasClass(t, "h-captcha") && t.attrs["data-sitekey"]);
|
|
1129
|
+
const hcRes = res.filter((r) => /(^|\.)hcaptcha\.com$/.test(r.host));
|
|
1130
|
+
for (const w of hc) add("hcaptcha", "hCaptcha", `<${w.name} class="h-captcha" data-sitekey>`, (f) => {
|
|
1131
|
+
f.params.websiteKey = w.attrs["data-sitekey"];
|
|
1132
|
+
});
|
|
1133
|
+
if (hcRes.length) add("hcaptcha", "hCaptcha", `${hcRes[0].from}: ${hcRes[0].host}`);
|
|
1134
|
+
for (const [re, kind, name] of OTHER_FRAMES) {
|
|
1135
|
+
const r = res.find((x) => re.test(x.host));
|
|
1136
|
+
if (r) add(kind, name, `${r.from}: ${r.host}`);
|
|
1137
|
+
}
|
|
1138
|
+
const sel = [
|
|
1139
|
+
[(t) => t.attrs.id === "FunCaptcha" || /^arkose/i.test(t.attrs.id ?? "") || "data-pkey" in t.attrs, "arkose", "Arkose (FunCaptcha)", "Arkose element"],
|
|
1140
|
+
[(t) => hasClass(t, "frc-captcha"), "friendly_captcha", "Friendly Captcha", "class frc-captcha"],
|
|
1141
|
+
[(t) => hasClass(t, "mtcaptcha"), "mtcaptcha", "MTCaptcha", "class mtcaptcha"],
|
|
1142
|
+
[(t) => t.attrs.id === "div_for_keycaptcha", "keycaptcha", "KeyCaptcha", "id div_for_keycaptcha"],
|
|
1143
|
+
[(t) => t.attrs.id === "lemin-cropped-captcha", "lemin", "Lemin", "id lemin-cropped-captcha"],
|
|
1144
|
+
[(t) => hasClass(t, "captchafox"), "captchafox", "CaptchaFox", "class captchafox"],
|
|
1145
|
+
[(t) => t.name === "altcha-widget", "altcha", "ALTCHA", "<altcha-widget>"]
|
|
1146
|
+
];
|
|
1147
|
+
for (const [test, kind, name, ev] of sel) if (tags.some(test)) add(kind, name, ev);
|
|
1148
|
+
const px = tags.some((t) => t.attrs.id === "px-captcha");
|
|
1149
|
+
const pxRes = res.some((r) => PX_HOSTS.test(r.host) || PX_PATH.test(r.path));
|
|
1150
|
+
if (px) {
|
|
1151
|
+
add("press_and_hold", "HUMAN press and hold", "id px-captcha", (f) => {
|
|
1152
|
+
if (!pxRes) f.confidence = "medium";
|
|
1153
|
+
f.notes.push("Passed by pressing and holding the button with real pointer input: there is nothing to solve remotely.");
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
const altcha = findings.find((f) => f.kind === "altcha");
|
|
1157
|
+
if (altcha) altcha.notes.push(`A proof of work the page's own script does when its checkbox is clicked: click it and wait for "verified".`);
|
|
1158
|
+
}
|
|
1159
|
+
for (const f of findings) {
|
|
1160
|
+
f.evidence = uniq(f.evidence).slice(0, 4);
|
|
1161
|
+
const key = String(f.params.websiteKey ?? "");
|
|
1162
|
+
if (key && TEST_KEYS.test(key)) f.notes.push("This is the provider's public test key: it passes (or fails) for everyone by design, so solving it proves nothing.");
|
|
1163
|
+
}
|
|
1164
|
+
return { findings, truncated };
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
// src/captcha/guards.ts
|
|
1168
|
+
function limitsFromEnv() {
|
|
1169
|
+
const whole = (n) => n === null ? null : Math.max(1, Math.floor(n));
|
|
1170
|
+
return {
|
|
1171
|
+
maxCredits: numEnv("BROWSA_CAPTCHA_MAX_CREDITS", null),
|
|
1172
|
+
ratePerMinute: whole(numEnv("BROWSA_CAPTCHA_RATE_PER_MINUTE", null, 1)),
|
|
1173
|
+
concurrency: whole(numEnv("BROWSA_CAPTCHA_CONCURRENCY", null, 1))
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
var WINDOW_MS = 6e4;
|
|
1177
|
+
var round = (n) => Math.round(n * 1e6) / 1e6;
|
|
1178
|
+
var Guard = class {
|
|
1179
|
+
constructor(limits, now = Date.now) {
|
|
1180
|
+
this.limits = limits;
|
|
1181
|
+
this.now = now;
|
|
1182
|
+
}
|
|
1183
|
+
limits;
|
|
1184
|
+
now;
|
|
1185
|
+
spent = 0;
|
|
1186
|
+
reserved = 0;
|
|
1187
|
+
running = 0;
|
|
1188
|
+
solves = 0;
|
|
1189
|
+
starts = [];
|
|
1190
|
+
get configured() {
|
|
1191
|
+
const l = this.limits;
|
|
1192
|
+
return l.maxCredits !== null || l.ratePerMinute !== null || l.concurrency !== null;
|
|
1193
|
+
}
|
|
1194
|
+
recent() {
|
|
1195
|
+
const from = this.now() - WINDOW_MS;
|
|
1196
|
+
this.starts = this.starts.filter((t) => t > from);
|
|
1197
|
+
return this.starts;
|
|
1198
|
+
}
|
|
1199
|
+
/** Asks to start one solve that costs `price` credits when it succeeds. */
|
|
1200
|
+
begin(price) {
|
|
1201
|
+
const l = this.limits;
|
|
1202
|
+
if (l.concurrency !== null && this.running >= l.concurrency) {
|
|
1203
|
+
return { ok: false, refusal: {
|
|
1204
|
+
limit: "concurrency",
|
|
1205
|
+
retry_after_seconds: 5,
|
|
1206
|
+
retry: "when a running solve ends (a token solve takes seconds to about 2 minutes)",
|
|
1207
|
+
message: `${this.running} captcha solves are running and BROWSA_CAPTCHA_CONCURRENCY is ${l.concurrency}`
|
|
1208
|
+
} };
|
|
1209
|
+
}
|
|
1210
|
+
if (l.ratePerMinute !== null && this.recent().length >= l.ratePerMinute) {
|
|
1211
|
+
const wait = Math.max(1, Math.ceil((this.starts[0] + WINDOW_MS - this.now()) / 1e3));
|
|
1212
|
+
return { ok: false, refusal: {
|
|
1213
|
+
limit: "rate",
|
|
1214
|
+
retry_after_seconds: wait,
|
|
1215
|
+
retry: `in ${wait} s`,
|
|
1216
|
+
message: `${this.starts.length} solves started in the last minute and BROWSA_CAPTCHA_RATE_PER_MINUTE is ${l.ratePerMinute}`
|
|
1217
|
+
} };
|
|
1218
|
+
}
|
|
1219
|
+
if (l.maxCredits !== null && this.spent + this.reserved + price > l.maxCredits + 1e-9) {
|
|
1220
|
+
const waiting = this.reserved > 0;
|
|
1221
|
+
return { ok: false, refusal: {
|
|
1222
|
+
limit: "spend_cap",
|
|
1223
|
+
retry_after_seconds: waiting ? 5 : null,
|
|
1224
|
+
retry: waiting ? "when the running solves end: a failed solve gives its reserved credits back" : "not in this session: raise BROWSA_CAPTCHA_MAX_CREDITS in this server's env and restart it",
|
|
1225
|
+
message: `this solve costs ${price} credits; the session has spent ${round(this.spent)}${this.reserved ? ` and holds ${round(this.reserved)} for running solves` : ""}, and BROWSA_CAPTCHA_MAX_CREDITS is ${l.maxCredits}`
|
|
1226
|
+
} };
|
|
1227
|
+
}
|
|
1228
|
+
this.running += 1;
|
|
1229
|
+
this.reserved += price;
|
|
1230
|
+
this.starts.push(this.now());
|
|
1231
|
+
let open2 = true;
|
|
1232
|
+
return { ok: true, ticket: { done: (credits) => {
|
|
1233
|
+
if (!open2) return;
|
|
1234
|
+
open2 = false;
|
|
1235
|
+
this.running -= 1;
|
|
1236
|
+
this.reserved = Math.max(0, this.reserved - price);
|
|
1237
|
+
if (credits > 0) {
|
|
1238
|
+
this.spent += credits;
|
|
1239
|
+
this.solves += 1;
|
|
1240
|
+
}
|
|
1241
|
+
} } };
|
|
1242
|
+
}
|
|
1243
|
+
/** What is left, for the agent. Limits that are not set say so. */
|
|
1244
|
+
allowance() {
|
|
1245
|
+
const l = this.limits;
|
|
1246
|
+
const used = this.recent().length;
|
|
1247
|
+
return {
|
|
1248
|
+
spent_credits: round(this.spent),
|
|
1249
|
+
solved: this.solves,
|
|
1250
|
+
spend_cap: l.maxCredits === null ? "not set" : { max_credits: l.maxCredits, remaining_credits: round(Math.max(0, l.maxCredits - this.spent - this.reserved)), reserved_credits: round(this.reserved) },
|
|
1251
|
+
rate: l.ratePerMinute === null ? "not set" : {
|
|
1252
|
+
per_minute: l.ratePerMinute,
|
|
1253
|
+
remaining: Math.max(0, l.ratePerMinute - used),
|
|
1254
|
+
...used ? { oldest_frees_in_seconds: Math.max(1, Math.ceil((this.starts[0] + WINDOW_MS - this.now()) / 1e3)) } : {}
|
|
1255
|
+
},
|
|
1256
|
+
concurrency: l.concurrency === null ? "not set" : { max: l.concurrency, running: this.running, free: Math.max(0, l.concurrency - this.running) }
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
};
|
|
1260
|
+
var guard = new Guard(limitsFromEnv());
|
|
1261
|
+
|
|
1262
|
+
// src/captcha/tools.ts
|
|
1263
|
+
var captchaPageTools = [
|
|
1264
|
+
{
|
|
1265
|
+
name: "detect_captcha",
|
|
1266
|
+
description: "Find the captchas in a page's HTML, for a browser of your own. Runs locally: sends nothing, needs no key, free. Returns each one's task type, site key and parameters, whether Browsa's captcha API takes it (status), and what is missing.",
|
|
1267
|
+
inputSchema: {
|
|
1268
|
+
type: "object",
|
|
1269
|
+
required: ["html"],
|
|
1270
|
+
properties: {
|
|
1271
|
+
html: { type: "string", description: "The page's HTML, e.g. document.documentElement.outerHTML." },
|
|
1272
|
+
url: { type: "string", description: "The page's address." },
|
|
1273
|
+
resources: { type: "array", items: { type: "string" }, description: "The page's frame and script URLs; site keys are often only there." }
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
},
|
|
1277
|
+
{
|
|
1278
|
+
name: "solve_captcha_on_page",
|
|
1279
|
+
description: "Solve a token captcha that is on a page in your own browser (the catalogue's token types, e.g. Turnstile, reCAPTCHA v2 and v3) through Browsa's captcha API. Returns the solution, its cost, and apply: a JavaScript expression to evaluate in that page (sets the token, calls the page's callback), or cookies to set and re-request with. It does not touch your browser and cannot click. Picture puzzles: send the image to solve_captcha_task. Charged only when solved.",
|
|
1280
|
+
inputSchema: {
|
|
1281
|
+
type: "object",
|
|
1282
|
+
properties: {
|
|
1283
|
+
captcha: { type: "object", description: "One entry of detect_captcha's captchas, or {type, params: {websiteURL, websiteKey, ...}}." },
|
|
1284
|
+
html: { type: "string", description: "Instead of captcha: the page's HTML; detection runs first." },
|
|
1285
|
+
url: { type: "string", description: "With html: the page's address." },
|
|
1286
|
+
resources: { type: "array", items: { type: "string" }, description: "With html: frame and script URLs." },
|
|
1287
|
+
proxy: { type: "string", description: "Your proxy, http://user:pass@host:port, for types that need one (detect_captcha lists it under missing)." },
|
|
1288
|
+
timeout_seconds: { type: "number", description: "Default 180, at most 600." }
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
},
|
|
1292
|
+
{
|
|
1293
|
+
name: "captcha_allowance",
|
|
1294
|
+
description: "This server's local captcha limits: credits spent and left under the session cap, rate and concurrency. Free, no request.",
|
|
1295
|
+
inputSchema: { type: "object", properties: {} }
|
|
1296
|
+
}
|
|
1297
|
+
];
|
|
1298
|
+
var CAPTCHA_PAGE_TOOLS = captchaPageTools.map((t) => t.name);
|
|
1299
|
+
var FAMILY_TYPES = {
|
|
1300
|
+
turnstile: ["AntiTurnstileTaskProxyLess"],
|
|
1301
|
+
recaptcha_v2: ["ReCaptchaV2TaskProxyLess"],
|
|
1302
|
+
recaptcha_v2_enterprise: ["ReCaptchaV2EnterpriseTaskProxyLess"],
|
|
1303
|
+
recaptcha_v3: ["ReCaptchaV3TaskProxyLess"],
|
|
1304
|
+
recaptcha_v3_enterprise: ["ReCaptchaV3EnterpriseTaskProxyLess"],
|
|
1305
|
+
cloudflare: ["AntiCloudflareTask"],
|
|
1306
|
+
geetest_slide: ["GeeTestSlide"],
|
|
1307
|
+
aws_waf: ["AwsWafClassification"],
|
|
1308
|
+
slider: ["VisionEngine"],
|
|
1309
|
+
image_text: ["ImageToTextTask"],
|
|
1310
|
+
altcha: ["AltchaTask"]
|
|
1311
|
+
};
|
|
1312
|
+
function annotate(f, cat) {
|
|
1313
|
+
const info = (FAMILY_TYPES[f.kind] ?? []).map((n) => typeInfo(n, cat)).find(Boolean);
|
|
1314
|
+
const notes = [...f.notes];
|
|
1315
|
+
if (!info) {
|
|
1316
|
+
return {
|
|
1317
|
+
kind: f.kind,
|
|
1318
|
+
name: f.name,
|
|
1319
|
+
type: null,
|
|
1320
|
+
status: "not_in_catalogue",
|
|
1321
|
+
solve_with: null,
|
|
1322
|
+
ready: false,
|
|
1323
|
+
params: f.params,
|
|
1324
|
+
missing: [],
|
|
1325
|
+
confidence: f.confidence,
|
|
1326
|
+
evidence: f.evidence,
|
|
1327
|
+
notes: [...notes, "The captcha API has no task type for this captcha."]
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
if (info.status !== "live") notes.push(`This type is switched off in the catalogue${info.offReason ? `: ${info.offReason}` : ""}.`);
|
|
1331
|
+
const token = info.kind === "token";
|
|
1332
|
+
const out = {
|
|
1333
|
+
kind: f.kind,
|
|
1334
|
+
name: f.name,
|
|
1335
|
+
type: info.type,
|
|
1336
|
+
status: info.status,
|
|
1337
|
+
solve_with: token ? "solve_captcha_on_page" : "solve_captcha_task",
|
|
1338
|
+
ready: token && info.status === "live" && f.missing.every((m) => m.startsWith("proxy:")),
|
|
1339
|
+
params: f.params,
|
|
1340
|
+
missing: f.missing,
|
|
1341
|
+
credits_per_solve: info.credits,
|
|
1342
|
+
confidence: f.confidence,
|
|
1343
|
+
evidence: f.evidence
|
|
1344
|
+
};
|
|
1345
|
+
if (Object.keys(f.page).length) out.page = f.page;
|
|
1346
|
+
if (notes.length) out.notes = notes;
|
|
1347
|
+
return out;
|
|
1348
|
+
}
|
|
1349
|
+
function detect(args) {
|
|
1350
|
+
const cat = catalogue();
|
|
1351
|
+
const { findings, truncated } = detectCaptchas({
|
|
1352
|
+
html: String(args.html ?? ""),
|
|
1353
|
+
url: typeof args.url === "string" ? args.url : void 0,
|
|
1354
|
+
resources: Array.isArray(args.resources) ? args.resources.map(String) : void 0
|
|
1355
|
+
});
|
|
1356
|
+
return { captchas: findings.map((f) => annotate(f, cat)), truncated, cat };
|
|
1357
|
+
}
|
|
1358
|
+
var answer = (o) => ({ text: JSON.stringify(o) });
|
|
1359
|
+
var refuse = (message, extra = {}) => ({ isError: true, text: JSON.stringify({ error: message, ...extra }) });
|
|
1360
|
+
function detectTool(args) {
|
|
1361
|
+
if (typeof args.html !== "string" || !args.html.trim()) return refuse("html is required: the page's HTML as text");
|
|
1362
|
+
const { captchas, truncated, cat } = detect(args);
|
|
1363
|
+
return answer({
|
|
1364
|
+
found: captchas.length,
|
|
1365
|
+
captchas,
|
|
1366
|
+
...captchas.length ? {} : { note: "No captcha in this HTML. A widget inside a frame is only seen through its frame URL: pass resources." },
|
|
1367
|
+
...truncated ? { truncated: "only the first 3,000,000 characters were read" } : {},
|
|
1368
|
+
catalogue: { source: cat.source, as_of: cat.asOf }
|
|
1369
|
+
});
|
|
1370
|
+
}
|
|
1371
|
+
function limitRefusal(r) {
|
|
1372
|
+
return refuse(`refused by this server's local limit (${r.limit}): ${r.message}`, {
|
|
1373
|
+
code: "LOCAL_LIMIT",
|
|
1374
|
+
limit: r.limit,
|
|
1375
|
+
retry_after_seconds: r.retry_after_seconds,
|
|
1376
|
+
retry: r.retry,
|
|
1377
|
+
charged: false,
|
|
1378
|
+
allowance: guard.allowance()
|
|
1379
|
+
});
|
|
1380
|
+
}
|
|
1381
|
+
async function guardedSolve(price, run) {
|
|
1382
|
+
const g = guard.begin(price);
|
|
1383
|
+
if (!g.ok) return { refused: limitRefusal(g.refusal) };
|
|
1384
|
+
let credits = 0;
|
|
1385
|
+
try {
|
|
1386
|
+
const r = await run();
|
|
1387
|
+
credits = r.credits;
|
|
1388
|
+
return { value: r.value };
|
|
1389
|
+
} finally {
|
|
1390
|
+
g.ticket.done(credits);
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
function priceOf(type) {
|
|
1394
|
+
const cat = catalogue();
|
|
1395
|
+
return typeInfo(type, cat)?.credits ?? Math.max(0, ...cat.types.map((t) => t.credits ?? 0));
|
|
1396
|
+
}
|
|
1397
|
+
function chargedCredits(body, type) {
|
|
1398
|
+
const c = body?.cost;
|
|
1399
|
+
if (c && c.charged === false) return 0;
|
|
1400
|
+
if (c && typeof c.credits === "number") return c.credits;
|
|
1401
|
+
if (c && c.unit === "credits" && typeof c.amount === "number") return c.amount;
|
|
1402
|
+
return priceOf(type);
|
|
1403
|
+
}
|
|
1404
|
+
var reportToolListed = false;
|
|
1405
|
+
function setReportToolListed(v) {
|
|
1406
|
+
reportToolListed = v;
|
|
1407
|
+
}
|
|
1408
|
+
async function solveOnPage(args) {
|
|
1409
|
+
await refreshCatalogue();
|
|
1410
|
+
const cat = catalogue();
|
|
1411
|
+
let picked = null;
|
|
1412
|
+
if (args.captcha && typeof args.captcha === "object") {
|
|
1413
|
+
const c = args.captcha;
|
|
1414
|
+
picked = { type: typeof c.type === "string" ? c.type : null, params: { ...c.params ?? {} }, page: c.page, missing: [] };
|
|
1415
|
+
for (const k of ["websiteURL", "websiteKey", "pageAction", "isInvisible", "metadata", "apiDomain", "userAgent"]) {
|
|
1416
|
+
if (c[k] !== void 0 && picked.params[k] === void 0) picked.params[k] = c[k];
|
|
1417
|
+
}
|
|
1418
|
+
if (!picked.type && typeof c.kind === "string") picked.type = (FAMILY_TYPES[c.kind] ?? []).find((n) => typeInfo(n, cat)) ?? null;
|
|
1419
|
+
} else if (typeof args.html === "string" && args.html.trim()) {
|
|
1420
|
+
const { captchas } = detect(args);
|
|
1421
|
+
const tokens = captchas.filter((c) => c.solve_with === "solve_captcha_on_page" && c.status === "live");
|
|
1422
|
+
if (tokens.length !== 1) {
|
|
1423
|
+
return refuse(
|
|
1424
|
+
tokens.length ? "more than one token captcha is in this HTML: pass the one to solve as captcha" : captchas.length ? "no captcha in this HTML can be solved by this tool" : "no captcha was found in this HTML",
|
|
1425
|
+
{ code: tokens.length ? "SEVERAL_CAPTCHAS" : captchas.length ? "NOT_SOLVABLE_HERE" : "NO_CAPTCHA", charged: false, captchas }
|
|
1426
|
+
);
|
|
1427
|
+
}
|
|
1428
|
+
picked = { type: tokens[0].type, params: { ...tokens[0].params }, page: tokens[0].page, missing: tokens[0].missing };
|
|
1429
|
+
} else {
|
|
1430
|
+
return refuse("pass captcha (an entry from detect_captcha) or html with url", { charged: false });
|
|
1431
|
+
}
|
|
1432
|
+
if (!picked.type) return refuse("the captcha API has no task type for this captcha", { code: "NOT_IN_CATALOGUE", charged: false });
|
|
1433
|
+
let type = picked.type;
|
|
1434
|
+
const proxy = typeof args.proxy === "string" && args.proxy.trim() ? args.proxy.trim() : picked.params.proxy;
|
|
1435
|
+
if (proxy && /ProxyLess$/i.test(type) && typeInfo(type.replace(/ProxyLess$/i, ""), cat)) type = type.replace(/ProxyLess$/i, "");
|
|
1436
|
+
const info = typeInfo(type, cat);
|
|
1437
|
+
if (!info) {
|
|
1438
|
+
return refuse(
|
|
1439
|
+
`${type} is not a type in the catalogue (names are case-sensitive)`,
|
|
1440
|
+
{ code: "NOT_IN_CATALOGUE", charged: false, token_types: cat.types.filter((t) => t.kind === "token" && t.status === "live").map((t) => t.type) }
|
|
1441
|
+
);
|
|
1442
|
+
}
|
|
1443
|
+
if (info.kind !== "token") {
|
|
1444
|
+
return refuse(
|
|
1445
|
+
`${type} is answered from a picture, not from the page's address: send the image with solve_captcha_task`,
|
|
1446
|
+
{ code: "NOT_A_TOKEN_TYPE", charged: false, required: [...info.required, ...info.oneOf.map((g) => g.join(" or "))] }
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
if (info.status !== "live") {
|
|
1450
|
+
return refuse(`${type} is switched off in the catalogue${info.offReason ? `: ${info.offReason}` : ""}`, { code: "TYPE_OFF", charged: false });
|
|
1451
|
+
}
|
|
1452
|
+
const task = { ...picked.params, type };
|
|
1453
|
+
if (proxy) task.proxy = proxy;
|
|
1454
|
+
const missing = info.required.filter((p) => task[p] === void 0 || task[p] === "");
|
|
1455
|
+
if (missing.length) {
|
|
1456
|
+
return refuse(`${type} needs ${missing.join(", ")}`, {
|
|
1457
|
+
code: "MISSING_PARAMETER",
|
|
1458
|
+
charged: false,
|
|
1459
|
+
missing,
|
|
1460
|
+
...picked.missing?.length ? { where: picked.missing } : {}
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
const timeoutMs = Math.min(Math.max(Number(args.timeout_seconds) || 180, 5), 600) * 1e3;
|
|
1464
|
+
const r = await guardedSolve(priceOf(type), async () => {
|
|
1465
|
+
const o2 = await runCaptchaTask(task, timeoutMs);
|
|
1466
|
+
return { credits: o2.state === "solved" ? chargedCredits(o2.body, type) : 0, value: o2 };
|
|
1467
|
+
});
|
|
1468
|
+
if ("refused" in r) return r.refused;
|
|
1469
|
+
const o = r.value;
|
|
1470
|
+
if (o.state === "error") {
|
|
1471
|
+
const b = o.body;
|
|
1472
|
+
return refuse(b.errorDescription || b.errorCode, {
|
|
1473
|
+
code: b.errorCode,
|
|
1474
|
+
...b.taskId ? { task_id: b.taskId } : {},
|
|
1475
|
+
charged: b.charged === true,
|
|
1476
|
+
...b.fix ? { fix: b.fix } : {},
|
|
1477
|
+
allowance: guard.allowance()
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
if (o.state === "timeout") {
|
|
1481
|
+
return refuse(
|
|
1482
|
+
`no solution after ${Math.round(o.timeoutMs / 1e3)}s; the task may still finish (charged only if solved)`,
|
|
1483
|
+
{ code: "TIMEOUT", task_id: o.taskId, allowance: guard.allowance() }
|
|
1484
|
+
);
|
|
1485
|
+
}
|
|
1486
|
+
const apply = buildApply(type, o.body.solution, String(task.websiteURL ?? ""), picked.page ?? {});
|
|
1487
|
+
return answer({
|
|
1488
|
+
task_id: o.taskId,
|
|
1489
|
+
type,
|
|
1490
|
+
solution: o.body.solution,
|
|
1491
|
+
seconds: o.seconds,
|
|
1492
|
+
cost: o.body.cost ?? { charged: true, credits: chargedCredits(o.body, type), note: "The catalogue's price: the API's answer carried no cost." },
|
|
1493
|
+
apply,
|
|
1494
|
+
allowance: guard.allowance(),
|
|
1495
|
+
next: `do apply.steps in your browser, then check the page's own answer${reportToolListed ? "; then report_captcha_result" : ""}`
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
async function callCaptchaPage(name, args) {
|
|
1499
|
+
try {
|
|
1500
|
+
switch (name) {
|
|
1501
|
+
case "detect_captcha":
|
|
1502
|
+
return detectTool(args);
|
|
1503
|
+
case "solve_captcha_on_page":
|
|
1504
|
+
return await solveOnPage(args);
|
|
1505
|
+
case "captcha_allowance":
|
|
1506
|
+
return answer({ ...guard.allowance(), ...guard.configured ? {} : { note: "No local limit is set (BROWSA_CAPTCHA_MAX_CREDITS, BROWSA_CAPTCHA_RATE_PER_MINUTE, BROWSA_CAPTCHA_CONCURRENCY). The workspace's own limits still apply." } });
|
|
1507
|
+
default:
|
|
1508
|
+
return refuse(`unknown tool: ${name}`);
|
|
1509
|
+
}
|
|
1510
|
+
} catch (e) {
|
|
1511
|
+
if (e instanceof BrowsaError2) return refuse(e.message, { code: e.code, status: e.status });
|
|
1512
|
+
const msg = e.message || String(e);
|
|
1513
|
+
if (e?.name === "TimeoutError" || /fetch failed|network|ECONN|ENOTFOUND|EAI_AGAIN/i.test(msg)) {
|
|
1514
|
+
return refuse(`could not reach the captcha API (${msg}); try again when the network is back`, { code: "NETWORK", allowance: guard.allowance() });
|
|
1515
|
+
}
|
|
1516
|
+
return refuse(msg);
|
|
46
1517
|
}
|
|
47
|
-
return { tools: tools2, unknown };
|
|
48
1518
|
}
|
|
49
1519
|
|
|
50
1520
|
// src/api.ts
|
|
51
|
-
import { BrowsaError } from "browsa";
|
|
1521
|
+
import { BrowsaError as BrowsaError3 } from "browsa";
|
|
52
1522
|
function headers(json) {
|
|
53
1523
|
const h = { "X-API-Key": API_KEY ?? "", Accept: "application/json", "User-Agent": `browsa-mcp/${VERSION}` };
|
|
54
1524
|
if (json) h["Content-Type"] = "application/json";
|
|
@@ -57,7 +1527,7 @@ function headers(json) {
|
|
|
57
1527
|
async function parse(resp) {
|
|
58
1528
|
const body = await resp.json().catch(() => ({}));
|
|
59
1529
|
if (!resp.ok) {
|
|
60
|
-
throw new
|
|
1530
|
+
throw new BrowsaError3(body?.error || body?.message || `HTTP ${resp.status}`, {
|
|
61
1531
|
code: body?.code ?? `HTTP_${resp.status}`,
|
|
62
1532
|
requestId: body?.request_id,
|
|
63
1533
|
status: resp.status
|
|
@@ -66,18 +1536,26 @@ async function parse(resp) {
|
|
|
66
1536
|
return body;
|
|
67
1537
|
}
|
|
68
1538
|
async function apiGet(path, timeoutMs = 9e4) {
|
|
69
|
-
return parse(await
|
|
1539
|
+
return parse(await fetchRetry(
|
|
1540
|
+
`${BASE_URL}${path}`,
|
|
1541
|
+
() => ({ headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }),
|
|
1542
|
+
{ idempotent: true }
|
|
1543
|
+
));
|
|
70
1544
|
}
|
|
71
1545
|
async function apiPost(path, payload, timeoutMs = 9e4) {
|
|
72
|
-
return parse(await
|
|
1546
|
+
return parse(await fetchRetry(`${BASE_URL}${path}`, () => ({
|
|
73
1547
|
method: "POST",
|
|
74
1548
|
headers: headers(true),
|
|
75
1549
|
body: JSON.stringify(payload ?? {}),
|
|
76
1550
|
signal: AbortSignal.timeout(timeoutMs)
|
|
77
|
-
}));
|
|
1551
|
+
}), { idempotent: false }));
|
|
78
1552
|
}
|
|
79
1553
|
async function apiDelete(path, timeoutMs = 3e4) {
|
|
80
|
-
return parse(await
|
|
1554
|
+
return parse(await fetchRetry(
|
|
1555
|
+
`${BASE_URL}${path}`,
|
|
1556
|
+
() => ({ method: "DELETE", headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }),
|
|
1557
|
+
{ idempotent: true }
|
|
1558
|
+
));
|
|
81
1559
|
}
|
|
82
1560
|
|
|
83
1561
|
// src/flow.ts
|
|
@@ -493,7 +1971,7 @@ function forget(id) {
|
|
|
493
1971
|
}
|
|
494
1972
|
function explain(e, tool, browserId) {
|
|
495
1973
|
if (e instanceof ToolError) return e.message;
|
|
496
|
-
if (!(e instanceof
|
|
1974
|
+
if (!(e instanceof BrowsaError3)) {
|
|
497
1975
|
const msg = e?.name === "TimeoutError" ? "the API did not answer in time" : e?.message || String(e);
|
|
498
1976
|
return `error: ${msg}
|
|
499
1977
|
next: try again; if it keeps failing, observe to see the page`;
|
|
@@ -781,7 +2259,7 @@ async function secrets() {
|
|
|
781
2259
|
try {
|
|
782
2260
|
body = await apiGet("/v1/secrets");
|
|
783
2261
|
} catch (e) {
|
|
784
|
-
if (e instanceof
|
|
2262
|
+
if (e instanceof BrowsaError3 && (e.status === 404 || e.status === 503 || e.status === 405)) {
|
|
785
2263
|
return "secrets: not available on this Browsa server yet\nnext: type values yourself, or call handoff for a login";
|
|
786
2264
|
}
|
|
787
2265
|
throw e;
|
|
@@ -927,7 +2405,7 @@ async function close(args) {
|
|
|
927
2405
|
try {
|
|
928
2406
|
await apiDelete(`/v1/agents/${encodeURIComponent(b.id)}`);
|
|
929
2407
|
} catch (e) {
|
|
930
|
-
if (!(e instanceof
|
|
2408
|
+
if (!(e instanceof BrowsaError3 && (e.status === 404 || e.code === "AGENT_NOT_RUNNING"))) throw e;
|
|
931
2409
|
}
|
|
932
2410
|
forget(b.id);
|
|
933
2411
|
return `ok: closed ${b.id}${dropped}`;
|
|
@@ -963,7 +2441,6 @@ async function callCore(name, args) {
|
|
|
963
2441
|
|
|
964
2442
|
// src/legacy.ts
|
|
965
2443
|
import { Client } from "browsa";
|
|
966
|
-
var CAPTCHA_URL = (process.env.BROWSA_CAPTCHA_URL || (BASE_URL_SET ? `${BASE_URL}/captcha-api` : "https://captcha.browsa.io")).replace(/\/+$/, "");
|
|
967
2444
|
var DEFAULT_LLM = process.env.BROWSA_LLM || void 0;
|
|
968
2445
|
var BYOK_DEFAULT_LLM = "claude-opus-5-5";
|
|
969
2446
|
var DEFAULT_LLM_KEY = process.env.BROWSA_LLM_API_KEY || void 0;
|
|
@@ -979,7 +2456,7 @@ var REASONING_PROP = {
|
|
|
979
2456
|
var legacyTools = [
|
|
980
2457
|
{
|
|
981
2458
|
name: "run_task",
|
|
982
|
-
description: "Run a browser-driven AI task on a fresh Phantom cloud browser. Returns the final result, the outcome and the total steps. `status: completed` only means the run ended: read `outcome`. `outcome: failed` with `status: completed` means the agent finished but could not do the task, and `final_result` says what stopped it. Use this when the user asks for anything web-shaped: scrape, fill, click, extract, login, place an order, search, summarize a page, etc. The browser is a real macOS-Chrome-fingerprinted Phantom browser with built-in captcha solving (the measured types are listed at https://browsa.io/captcha) and behavioral humanization. Default timeout: 10 minutes.",
|
|
2459
|
+
description: "Run a browser-driven AI task on a fresh Phantom cloud browser. Returns the final result, the outcome and the total steps. `status: completed` only means the run ended: read `outcome`. `outcome: failed` with `status: completed` means the agent finished but could not do the task, and `final_result` says what stopped it. Use this when the user asks for anything web-shaped: scrape, fill, click, extract, login, place an order, search, summarize a page, etc. The browser is a real macOS-Chrome-fingerprinted Phantom browser with built-in captcha solving (the measured types are listed at https://browsa.io/captcha) and behavioral humanization. Default timeout: 10 minutes. When the run creates a login (a signup), the result may list it in `saved_secrets` (saved as a workspace secret, never the value).",
|
|
983
2460
|
inputSchema: {
|
|
984
2461
|
type: "object",
|
|
985
2462
|
required: ["task"],
|
|
@@ -1015,6 +2492,16 @@ var legacyTools = [
|
|
|
1015
2492
|
type: "string",
|
|
1016
2493
|
description: "Id of a persistent identity (agt_..., from list_identities). If set, reuses that browser identity (cookies, history, fingerprint stay sticky). Omit for a fresh burner."
|
|
1017
2494
|
},
|
|
2495
|
+
secret_ids: {
|
|
2496
|
+
type: "array",
|
|
2497
|
+
items: { type: "string" },
|
|
2498
|
+
maxItems: 20,
|
|
2499
|
+
description: "Names or ids of workspace secrets the task may type; refer to them in the task as secrets.NAME (or secrets.NAME.username, .password, .totp)."
|
|
2500
|
+
},
|
|
2501
|
+
save_secrets: {
|
|
2502
|
+
type: "boolean",
|
|
2503
|
+
description: "Set false to stop the run from saving a login it creates as a workspace secret (on by default)."
|
|
2504
|
+
},
|
|
1018
2505
|
timeout_minutes: {
|
|
1019
2506
|
type: "integer",
|
|
1020
2507
|
description: "Max wall-clock minutes to wait before returning. Default 10.",
|
|
@@ -1251,6 +2738,29 @@ var legacyTools = [
|
|
|
1251
2738
|
timeout_seconds: { type: "number", description: "How long to wait for the solution. Default 180, at most 600." }
|
|
1252
2739
|
}
|
|
1253
2740
|
}
|
|
2741
|
+
},
|
|
2742
|
+
{
|
|
2743
|
+
name: "list_captcha_types",
|
|
2744
|
+
description: "List the captcha task types Browsa's captcha API accepts: whether each is live or off, its required and optional parameters, its price per solve and, where measured, its pass rate with the date of the run. Call it before solve_captcha_task when unsure of a type name or of a parameter: names are case-sensitive. Uses no credits.",
|
|
2745
|
+
inputSchema: {
|
|
2746
|
+
type: "object",
|
|
2747
|
+
properties: {
|
|
2748
|
+
type: { type: "string", description: "Only this type, with the description of every parameter." },
|
|
2749
|
+
live_only: { type: "boolean", description: "Leave out the types that are switched off." }
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
},
|
|
2753
|
+
{
|
|
2754
|
+
name: "report_captcha_result",
|
|
2755
|
+
description: "Tell Browsa whether the site accepted a solution from solve_captcha_task: correct=true records that it worked, correct=false that the site refused it. An incorrect report refunds that solve once, within the workspace's report limits; the answer says whether it did (refunded). A task can be reported once, within 15 minutes of the solve. Report only what the site itself answered.",
|
|
2756
|
+
inputSchema: {
|
|
2757
|
+
type: "object",
|
|
2758
|
+
required: ["task_id", "correct"],
|
|
2759
|
+
properties: {
|
|
2760
|
+
task_id: { type: "string", description: "task_id from solve_captcha_task." },
|
|
2761
|
+
correct: { type: "boolean", description: "true when the site accepted the solution, false when it refused it." }
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
1254
2764
|
}
|
|
1255
2765
|
];
|
|
1256
2766
|
function ok(payload) {
|
|
@@ -1287,7 +2797,7 @@ async function submitWithHostedFallback(choice, submit) {
|
|
|
1287
2797
|
try {
|
|
1288
2798
|
return { result: await submit(choice), fellBack: false };
|
|
1289
2799
|
} catch (e) {
|
|
1290
|
-
if (e instanceof
|
|
2800
|
+
if (e instanceof BrowsaError3 && canFallBackToHosted(e, choice)) {
|
|
1291
2801
|
return { result: await submit(HOSTED), fellBack: true };
|
|
1292
2802
|
}
|
|
1293
2803
|
throw e;
|
|
@@ -1322,7 +2832,7 @@ async function proxyNetwork() {
|
|
|
1322
2832
|
const body = await resp.json().catch(() => ({}));
|
|
1323
2833
|
if (resp.status === 404) return { enabled: false, tiers: [] };
|
|
1324
2834
|
if (!resp.ok) {
|
|
1325
|
-
throw new
|
|
2835
|
+
throw new BrowsaError3(body?.error || `HTTP ${resp.status}`, { code: body?.code, requestId: body?.request_id, status: resp.status });
|
|
1326
2836
|
}
|
|
1327
2837
|
const tiers = body?.enabled === true && Array.isArray(body?.tiers) ? body.tiers : [];
|
|
1328
2838
|
return {
|
|
@@ -1355,6 +2865,23 @@ function llmResultFields(job) {
|
|
|
1355
2865
|
if (!r || typeof r !== "object") return {};
|
|
1356
2866
|
return { llm_tier: r.llm_tier, reasoning: r.reasoning, usage: r.usage, llm_cost_usd: r.llm_cost_usd };
|
|
1357
2867
|
}
|
|
2868
|
+
function savedSecretFields(job) {
|
|
2869
|
+
const r = job.raw?.result;
|
|
2870
|
+
if (!r || typeof r !== "object") return {};
|
|
2871
|
+
const saved = Array.isArray(r.saved_secrets) ? r.saved_secrets.filter((s) => s && typeof s === "object").map((s) => ({
|
|
2872
|
+
name: s.name,
|
|
2873
|
+
id: s.id,
|
|
2874
|
+
type: s.type,
|
|
2875
|
+
origins: s.origins,
|
|
2876
|
+
...s.username_masked ? { username_masked: s.username_masked } : {},
|
|
2877
|
+
existing: s.existing === true
|
|
2878
|
+
})) : [];
|
|
2879
|
+
const notSaved = r.secrets_not_saved && typeof r.secrets_not_saved === "object" && r.secrets_not_saved.code ? { code: r.secrets_not_saved.code, message: r.secrets_not_saved.message } : void 0;
|
|
2880
|
+
return {
|
|
2881
|
+
...saved.length ? { saved_secrets: saved } : {},
|
|
2882
|
+
...notSaved ? { secrets_not_saved: notSaved } : {}
|
|
2883
|
+
};
|
|
2884
|
+
}
|
|
1358
2885
|
async function listLlmKeys() {
|
|
1359
2886
|
const body = await apiGet("/v1/llm-keys");
|
|
1360
2887
|
return {
|
|
@@ -1455,52 +2982,81 @@ var CAPTCHA_ALIASES = {
|
|
|
1455
2982
|
imagetotexttask: ["ImageToTextTask", "ImageToTextTask"],
|
|
1456
2983
|
recaptchav2classification: ["ReCaptchaV2Classification", "ReCaptchaV2Classification"]
|
|
1457
2984
|
};
|
|
1458
|
-
async function captchaCall(method, payload) {
|
|
1459
|
-
const resp = await fetch(`${CAPTCHA_URL}/${method}`, {
|
|
1460
|
-
method: "POST",
|
|
1461
|
-
headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "browsa-mcp" },
|
|
1462
|
-
body: JSON.stringify({ clientKey: API_KEY, ...payload }),
|
|
1463
|
-
signal: AbortSignal.timeout(3e4)
|
|
1464
|
-
});
|
|
1465
|
-
const body = await resp.json().catch(() => null);
|
|
1466
|
-
if (!body || typeof body !== "object" || !("errorId" in body)) {
|
|
1467
|
-
throw new BrowsaError(`captcha API: unexpected answer (HTTP ${resp.status})`, { code: `HTTP_${resp.status}`, status: resp.status });
|
|
1468
|
-
}
|
|
1469
|
-
return body;
|
|
1470
|
-
}
|
|
1471
2985
|
async function solveCaptchaTask(args) {
|
|
1472
2986
|
const task = { ...args.task ?? {} };
|
|
1473
2987
|
if (typeof task.type !== "string" || !task.type) return fail("task.type is required");
|
|
1474
2988
|
const pair = CAPTCHA_ALIASES[task.type.toLowerCase()];
|
|
1475
2989
|
if (pair) task.type = task.proxy || task.proxyAddress ? pair[1] : pair[0];
|
|
1476
2990
|
const timeoutMs = Math.min(Math.max(Number(args.timeout_seconds) || 180, 5), 600) * 1e3;
|
|
1477
|
-
const
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
charged: false,
|
|
1481
|
-
...b.errorCode === "ERROR_TASK_NOT_SUPPORTED" ? { measured_types: "https://browsa.io/captcha" } : {}
|
|
2991
|
+
const r = await guardedSolve(priceOf(task.type), async () => {
|
|
2992
|
+
const o2 = await runCaptchaTask(task, timeoutMs);
|
|
2993
|
+
return { credits: o2.state === "solved" ? chargedCredits(o2.body, task.type) : 0, value: o2 };
|
|
1482
2994
|
});
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
return
|
|
2995
|
+
if ("refused" in r) return { isError: true, content: [{ type: "text", text: r.refused.text }] };
|
|
2996
|
+
const o = r.value;
|
|
2997
|
+
if (o.state === "error") {
|
|
2998
|
+
const b = o.body;
|
|
2999
|
+
return fail(b.errorDescription || b.errorCode, {
|
|
3000
|
+
code: b.errorCode,
|
|
3001
|
+
task_id: b.taskId,
|
|
3002
|
+
charged: b.charged === true,
|
|
3003
|
+
...b.fix ? { fix: b.fix } : {},
|
|
3004
|
+
...b.errorCode === "ERROR_TASK_NOT_SUPPORTED" ? { measured_types: "https://browsa.io/captcha", next: "call list_captcha_types for the type names and their parameters" } : {}
|
|
3005
|
+
});
|
|
1488
3006
|
}
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
3007
|
+
if (o.state === "timeout") {
|
|
3008
|
+
return fail(
|
|
3009
|
+
`no solution after ${Math.round(timeoutMs / 1e3)}s; the task may still finish (charged only if solved)`,
|
|
3010
|
+
{ code: "TIMEOUT", task_id: o.taskId }
|
|
3011
|
+
);
|
|
3012
|
+
}
|
|
3013
|
+
return ok({
|
|
3014
|
+
task_id: o.taskId,
|
|
3015
|
+
type: task.type,
|
|
3016
|
+
solution: o.body.solution,
|
|
3017
|
+
seconds: o.seconds,
|
|
3018
|
+
...o.body.cost ? { cost: o.body.cost } : {},
|
|
3019
|
+
next: "when the site has answered, call report_captcha_result with correct=true or correct=false"
|
|
3020
|
+
});
|
|
3021
|
+
}
|
|
3022
|
+
async function listCaptchaTypes(args) {
|
|
3023
|
+
const r = await captchaCall("types", null);
|
|
3024
|
+
if (r.errorId || !Array.isArray(r.types)) return fail(r.errorDescription || "the type catalogue is not available", { code: r.errorCode });
|
|
3025
|
+
const names = (ps) => (ps ?? []).map((p) => p.name);
|
|
3026
|
+
const measured = (t) => (t.measured ?? []).map((m) => ({ what: m.name, passes: `${m.passes} of ${m.attempts}`, median_seconds: m.medianSeconds, measured_on: m.measuredOn, exit: m.exit }));
|
|
3027
|
+
if (typeof args.type === "string" && args.type) {
|
|
3028
|
+
const want = args.type.toLowerCase();
|
|
3029
|
+
const t = r.types.find((x) => String(x.type).toLowerCase() === want);
|
|
3030
|
+
if (!t) return fail(`no type named ${args.type}`, { types: r.types.map((x) => x.type) });
|
|
3031
|
+
return ok({ ...t, measured: measured(t) });
|
|
3032
|
+
}
|
|
3033
|
+
const types = r.types.filter((t) => !args.live_only || t.status === "live").map((t) => ({
|
|
3034
|
+
type: t.type,
|
|
3035
|
+
what: t.summary,
|
|
3036
|
+
status: t.status,
|
|
3037
|
+
...t.offReason ? { off_reason: t.offReason } : {},
|
|
3038
|
+
required: [...names(t.required), ...(t.requiredOneOf ?? []).map((g) => names(g).join(" or "))],
|
|
3039
|
+
optional: names(t.optional),
|
|
3040
|
+
proxy: t.proxy,
|
|
3041
|
+
credits_per_solve: t.price?.creditsPerSolve,
|
|
3042
|
+
measured: measured(t)
|
|
3043
|
+
}));
|
|
3044
|
+
return ok({ types, note: "Names are case-sensitive. A failed solve is not charged. Pass `type` for one type's parameter descriptions." });
|
|
3045
|
+
}
|
|
3046
|
+
async function reportCaptchaResult(args) {
|
|
3047
|
+
if (typeof args.task_id !== "string" || !args.task_id) return fail("task_id is required");
|
|
3048
|
+
if (typeof args.correct !== "boolean") return fail("correct must be true or false");
|
|
3049
|
+
const r = await captchaCall(args.correct ? "reportCorrect" : "reportIncorrect", { taskId: args.task_id });
|
|
3050
|
+
if (r.errorId) {
|
|
3051
|
+
return fail(r.errorDescription || r.errorCode, {
|
|
3052
|
+
code: r.errorCode,
|
|
3053
|
+
task_id: args.task_id,
|
|
3054
|
+
...r.fix ? { fix: r.fix } : {},
|
|
3055
|
+
...typeof r.refunded === "boolean" ? { refunded: r.refunded } : {}
|
|
3056
|
+
});
|
|
1497
3057
|
}
|
|
1498
|
-
return
|
|
1499
|
-
`no solution after ${Math.round(timeoutMs / 1e3)}s; the task may still finish (charged only if solved)`,
|
|
1500
|
-
{ code: "TIMEOUT", task_id: created.taskId }
|
|
1501
|
-
);
|
|
3058
|
+
return ok({ task_id: args.task_id, outcome: r.outcome, refunded: r.refunded === true, refund: r.refund, message: r.message });
|
|
1502
3059
|
}
|
|
1503
|
-
var CAPTCHA_POLL_MS = Number(process.env.BROWSA_CAPTCHA_POLL_MS) || 3e3;
|
|
1504
3060
|
async function callLegacy(name, args) {
|
|
1505
3061
|
let choice = null;
|
|
1506
3062
|
try {
|
|
@@ -1521,6 +3077,9 @@ async function callLegacy(name, args) {
|
|
|
1521
3077
|
initialUrl: args.initial_url,
|
|
1522
3078
|
ja3Profile: args.ja3_profile,
|
|
1523
3079
|
profileId: args.profile_id,
|
|
3080
|
+
// Sent as is (snake_case) and only when given.
|
|
3081
|
+
secret_ids: Array.isArray(args.secret_ids) && args.secret_ids.length ? args.secret_ids : void 0,
|
|
3082
|
+
save_secrets: typeof args.save_secrets === "boolean" ? args.save_secrets : void 0,
|
|
1524
3083
|
timeoutMs: (args.timeout_minutes ?? 10) * 6e4
|
|
1525
3084
|
})
|
|
1526
3085
|
);
|
|
@@ -1536,6 +3095,7 @@ async function callLegacy(name, args) {
|
|
|
1536
3095
|
llm_key_masked: job.raw?.llm_key_masked,
|
|
1537
3096
|
llm_key_source: job.raw?.llm_key_source,
|
|
1538
3097
|
...llmResultFields(job),
|
|
3098
|
+
...savedSecretFields(job),
|
|
1539
3099
|
final_result: job.finalResult,
|
|
1540
3100
|
error: job.errorMessage,
|
|
1541
3101
|
error_code: job.errorCode
|
|
@@ -1551,6 +3111,7 @@ async function callLegacy(name, args) {
|
|
|
1551
3111
|
live_url: job.liveUrl,
|
|
1552
3112
|
input_question: job.inputQuestion,
|
|
1553
3113
|
...llmResultFields(job),
|
|
3114
|
+
...savedSecretFields(job),
|
|
1554
3115
|
final_result: job.finalResult,
|
|
1555
3116
|
error: job.errorMessage,
|
|
1556
3117
|
error_code: job.errorCode,
|
|
@@ -1665,11 +3226,15 @@ async function callLegacy(name, args) {
|
|
|
1665
3226
|
return ok(robotRunView(await apiGet(`/v1/robot-runs/${encodeURIComponent(String(args.run_id))}`)));
|
|
1666
3227
|
case "solve_captcha_task":
|
|
1667
3228
|
return await solveCaptchaTask(args);
|
|
3229
|
+
case "list_captcha_types":
|
|
3230
|
+
return await listCaptchaTypes(args);
|
|
3231
|
+
case "report_captcha_result":
|
|
3232
|
+
return await reportCaptchaResult(args);
|
|
1668
3233
|
default:
|
|
1669
3234
|
return fail(`unknown tool: ${name}`);
|
|
1670
3235
|
}
|
|
1671
3236
|
} catch (e) {
|
|
1672
|
-
if (e instanceof
|
|
3237
|
+
if (e instanceof BrowsaError3) {
|
|
1673
3238
|
const keyErr = choice ? llmKeyError(e, choice) : null;
|
|
1674
3239
|
if (keyErr) return keyErr;
|
|
1675
3240
|
return fail(e.message, {
|
|
@@ -1682,6 +3247,67 @@ async function callLegacy(name, args) {
|
|
|
1682
3247
|
}
|
|
1683
3248
|
}
|
|
1684
3249
|
|
|
3250
|
+
// src/prompts.ts
|
|
3251
|
+
var PROMPTS = [
|
|
3252
|
+
{
|
|
3253
|
+
name: "solve_captcha_on_my_page",
|
|
3254
|
+
title: "Solve the captcha on my current page",
|
|
3255
|
+
description: "For a browser of your own: detect the captcha, solve it, apply the answer, verify.",
|
|
3256
|
+
arguments: [{ name: "url", description: "The page, when it is not the one already open." }],
|
|
3257
|
+
needs: ["detect_captcha", "solve_captcha_on_page"],
|
|
3258
|
+
text: (a) => [
|
|
3259
|
+
`Solve the captcha on ${a.url ? `the page ${a.url}` : "the page that is open in my browser"}, using my own browser tools for the page and Browsa's tools for the captcha.`,
|
|
3260
|
+
"",
|
|
3261
|
+
"1. Detect. With my browser tools, read the page's address, its HTML (document.documentElement.outerHTML) and the URLs of its frames and scripts. Call detect_captcha with html, url and resources. It runs locally and is free.",
|
|
3262
|
+
"2. Decide. Take the entry with ready true. If none is ready, tell me what its missing list asks for, or that the type is not in the catalogue, and stop. An entry with solve_with solve_captcha_task is a picture puzzle: this recipe does not cover it.",
|
|
3263
|
+
"3. Solve. Call solve_captcha_on_page with that entry as captcha (add proxy when the entry asks for one). Note cost in the answer. On a refusal with code LOCAL_LIMIT, wait retry_after_seconds, or stop when it is null.",
|
|
3264
|
+
"4. Apply. Do apply.steps in my browser: evaluate apply.expression in the page's main frame, or set apply.cookies and request the page again. Do not reload the page between solving and applying.",
|
|
3265
|
+
"5. Verify. Read the page again: say whether the site accepted the answer, quoting what the page shows. If it refused, solve once more at most, then stop and tell me.",
|
|
3266
|
+
"",
|
|
3267
|
+
"Report: the captcha type, whether the site accepted it, the credits it cost, and the allowance left."
|
|
3268
|
+
].join("\n")
|
|
3269
|
+
},
|
|
3270
|
+
{
|
|
3271
|
+
name: "what_captcha_is_this",
|
|
3272
|
+
title: "What captcha is on this page?",
|
|
3273
|
+
description: "Detect only: which captcha a page has, and whether Browsa's captcha API takes it. Free.",
|
|
3274
|
+
arguments: [{ name: "url", description: "The page, when it is not the one already open." }],
|
|
3275
|
+
needs: ["detect_captcha"],
|
|
3276
|
+
text: (a) => [
|
|
3277
|
+
`Tell me which captcha is on ${a.url ? `the page ${a.url}` : "the page that is open in my browser"}. Solve nothing and spend nothing.`,
|
|
3278
|
+
"",
|
|
3279
|
+
"With my browser tools, read the page's address, its HTML and the URLs of its frames and scripts, then call detect_captcha with html, url and resources.",
|
|
3280
|
+
"For each entry say: the provider's name, the task type, its status in the catalogue, the price per solve, what is missing, and how sure the detection is (confidence, evidence). If nothing is found, say so and say that a widget inside a frame only shows through its frame URL."
|
|
3281
|
+
].join("\n")
|
|
3282
|
+
},
|
|
3283
|
+
{
|
|
3284
|
+
name: "pass_check_in_browsa_browser",
|
|
3285
|
+
title: "Get past a check in a Browsa browser",
|
|
3286
|
+
description: "For a Browsa cloud browser: open the page, solve the check in place, hand over to a person if it stays.",
|
|
3287
|
+
arguments: [{ name: "url", description: "The page to open.", required: true }],
|
|
3288
|
+
needs: ["open", "act", "observe", "handoff"],
|
|
3289
|
+
text: (a) => [
|
|
3290
|
+
`Open ${a.url || "the page"} in a Browsa browser and get to its real content.`,
|
|
3291
|
+
"",
|
|
3292
|
+
"1. open the url. Read the first view.",
|
|
3293
|
+
"2. If an act or observe answer starts with challenge, call act with action solve_captcha once, then observe.",
|
|
3294
|
+
"3. If the check is still there, call handoff with the reason and give me the link; continue when the next observe says the page moved on.",
|
|
3295
|
+
"4. Tell me what the page shows now, then close the browser unless I asked to keep it."
|
|
3296
|
+
].join("\n")
|
|
3297
|
+
}
|
|
3298
|
+
];
|
|
3299
|
+
function listPrompts(listed2) {
|
|
3300
|
+
return PROMPTS.filter((p) => p.needs.every((t) => listed2.has(t))).map(({ name, title, description, arguments: args }) => ({ name, title, description, ...args ? { arguments: args } : {} }));
|
|
3301
|
+
}
|
|
3302
|
+
function getPrompt(name, args, listed2) {
|
|
3303
|
+
const p = PROMPTS.find((x) => x.name === name && x.needs.every((t) => listed2.has(t)));
|
|
3304
|
+
if (!p) return null;
|
|
3305
|
+
return {
|
|
3306
|
+
description: p.description,
|
|
3307
|
+
messages: [{ role: "user", content: { type: "text", text: p.text(args ?? {}) } }]
|
|
3308
|
+
};
|
|
3309
|
+
}
|
|
3310
|
+
|
|
1685
3311
|
// src/redact.ts
|
|
1686
3312
|
var SENSITIVE = /^(?:.*[_.-])?(?:token|access_?token|refresh_?token|id_?token|auth|authorization|key|api_?key|apikey|secret|client_?secret|password|passwd|pwd|pass|session|session_?id|sessionid|sid|jsessionid|phpsessid|code|otp|ticket|signature|sig|credential|jwt|assertion|saml_?response|nonce)(?:[_.-].*)?$/i;
|
|
1687
3313
|
var SAFE = /* @__PURE__ */ new Set(["country_code", "countrycode", "zip_code", "zipcode", "postal_code", "postcode", "currency_code", "lang_code", "keyword", "keywords", "keys", "token_type", "key_type"]);
|
|
@@ -1707,17 +3333,28 @@ function redactUrls(text) {
|
|
|
1707
3333
|
|
|
1708
3334
|
// src/server.ts
|
|
1709
3335
|
if (!API_KEY) {
|
|
1710
|
-
console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but
|
|
3336
|
+
console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but calls that reach Browsa will fail until it is.");
|
|
1711
3337
|
console.error(` Mint one at ${KEYS_URL}`);
|
|
1712
3338
|
}
|
|
1713
3339
|
var extras = enabledExtras();
|
|
1714
3340
|
for (const w of extras.unknown) {
|
|
1715
3341
|
console.error(`[browsa-mcp] BROWSA_MCP_TOOLS: unknown group or tool "${w}" (groups: ${Object.keys(GROUPS).join(", ")}, all)`);
|
|
1716
3342
|
}
|
|
1717
|
-
var tools = [
|
|
3343
|
+
var tools = [
|
|
3344
|
+
...coreTools.filter((t) => extras.core.has(t.name)),
|
|
3345
|
+
...captchaPageTools.filter((t) => extras.tools.has(t.name)),
|
|
3346
|
+
...legacyTools.filter((t) => extras.tools.has(t.name))
|
|
3347
|
+
];
|
|
1718
3348
|
var listed = new Set(tools.map((t) => t.name));
|
|
1719
|
-
|
|
3349
|
+
setReportToolListed(listed.has("report_captcha_result"));
|
|
3350
|
+
var server = new Server({ name: "browsa", version: VERSION }, { capabilities: { tools: {}, prompts: {} } });
|
|
1720
3351
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
3352
|
+
server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: listPrompts(listed) }));
|
|
3353
|
+
server.setRequestHandler(GetPromptRequestSchema, async (req) => {
|
|
3354
|
+
const p = getPrompt(req.params.name, req.params.arguments ?? {}, listed);
|
|
3355
|
+
if (!p) throw new Error(`unknown prompt: ${req.params.name}`);
|
|
3356
|
+
return p;
|
|
3357
|
+
});
|
|
1721
3358
|
var clean = (s) => REDACT ? redactUrls(s) : s;
|
|
1722
3359
|
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
1723
3360
|
const name = req.params.name;
|
|
@@ -1725,10 +3362,15 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
|
1725
3362
|
if (!listed.has(name)) {
|
|
1726
3363
|
const group = Object.entries(GROUPS).find(([, t]) => t.includes(name))?.[0];
|
|
1727
3364
|
const text = group ? `error: ${name} is in the optional group "${group}"
|
|
1728
|
-
next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it` : `error:
|
|
3365
|
+
next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it` : CORE_TOOLS.includes(name) ? `error: ${name} is a core tool and the core tools are switched off
|
|
3366
|
+
next: take "-core" out of BROWSA_MCP_TOOLS in this server's env and restart it` : `error: unknown tool ${name}`;
|
|
1729
3367
|
return { isError: true, content: [{ type: "text", text }] };
|
|
1730
3368
|
}
|
|
1731
|
-
if (!API_KEY) return { isError: true, content: [{ type: "text", text: NO_KEY_MESSAGE }] };
|
|
3369
|
+
if (!API_KEY && !NO_KEY_TOOLS.includes(name)) return { isError: true, content: [{ type: "text", text: NO_KEY_MESSAGE }] };
|
|
3370
|
+
if (CAPTCHA_PAGE_TOOLS.includes(name)) {
|
|
3371
|
+
const r2 = await callCaptchaPage(name, args);
|
|
3372
|
+
return { ...r2.isError ? { isError: true } : {}, content: [{ type: "text", text: clean(r2.text) }] };
|
|
3373
|
+
}
|
|
1732
3374
|
if (CORE_TOOLS.includes(name)) {
|
|
1733
3375
|
const r2 = await callCore(name, args);
|
|
1734
3376
|
const content = [];
|
|
@@ -1743,6 +3385,7 @@ next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it
|
|
|
1743
3385
|
async function main() {
|
|
1744
3386
|
const transport = new StdioServerTransport();
|
|
1745
3387
|
await server.connect(transport);
|
|
3388
|
+
if (GROUPS.captcha_page.some((t) => listed.has(t))) void refreshCatalogue();
|
|
1746
3389
|
console.error(`[browsa-mcp] ${VERSION} ready (tools=${tools.length})`);
|
|
1747
3390
|
}
|
|
1748
3391
|
main().catch((e) => {
|