turno-browser 0.3.0 → 0.5.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.
Files changed (131) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +95 -123
  3. package/dist/act-model.d.ts +85 -0
  4. package/dist/act-model.js +117 -0
  5. package/dist/act.d.ts +37 -0
  6. package/dist/act.js +600 -0
  7. package/dist/api.d.ts +90 -2
  8. package/dist/api.js +41 -4
  9. package/dist/argv.d.ts +16 -2
  10. package/dist/argv.js +100 -3
  11. package/dist/background-state.d.ts +54 -0
  12. package/dist/background-state.js +97 -0
  13. package/dist/background.d.ts +69 -0
  14. package/dist/background.js +458 -0
  15. package/dist/batch.d.ts +5 -0
  16. package/dist/batch.js +3 -3
  17. package/dist/bin/mcp.js +103 -6
  18. package/dist/captcha.d.ts +77 -0
  19. package/dist/captcha.js +334 -0
  20. package/dist/cdp-relay.d.ts +20 -0
  21. package/dist/cdp-relay.js +101 -0
  22. package/dist/chrome-features.d.ts +23 -0
  23. package/dist/chrome-features.js +44 -0
  24. package/dist/cli/background.d.ts +11 -0
  25. package/dist/cli/background.js +132 -0
  26. package/dist/cli/commands.d.ts +16 -0
  27. package/dist/cli/commands.js +515 -0
  28. package/dist/cli/context.d.ts +75 -0
  29. package/dist/cli/context.js +44 -0
  30. package/dist/cli/do-background.d.ts +27 -0
  31. package/dist/cli/do-background.js +212 -0
  32. package/dist/cli/do.d.ts +85 -0
  33. package/dist/cli/do.js +558 -0
  34. package/dist/cli/flows.d.ts +28 -0
  35. package/dist/cli/flows.js +303 -0
  36. package/dist/cli/identity.d.ts +37 -0
  37. package/dist/cli/identity.js +906 -0
  38. package/dist/cli/live.d.ts +7 -0
  39. package/dist/cli/live.js +99 -0
  40. package/dist/cli/main.d.ts +16 -0
  41. package/dist/cli/main.js +171 -0
  42. package/dist/cli/secret.d.ts +4 -0
  43. package/dist/cli/secret.js +151 -0
  44. package/dist/cli/session.d.ts +6 -0
  45. package/dist/cli/session.js +106 -0
  46. package/dist/cli/setup.d.ts +7 -0
  47. package/dist/cli/setup.js +180 -0
  48. package/dist/cli/vault.d.ts +5 -0
  49. package/dist/cli/vault.js +192 -0
  50. package/dist/client.d.ts +82 -0
  51. package/dist/client.js +303 -0
  52. package/dist/diagnose.d.ts +7 -0
  53. package/dist/diagnose.js +61 -6
  54. package/dist/doctor.d.ts +37 -3
  55. package/dist/doctor.js +264 -6
  56. package/dist/engine-attach.d.ts +27 -0
  57. package/dist/engine-attach.js +165 -0
  58. package/dist/engine-camoufox.d.ts +32 -0
  59. package/dist/engine-camoufox.js +271 -0
  60. package/dist/engine-lightpanda.d.ts +72 -0
  61. package/dist/engine-lightpanda.js +293 -0
  62. package/dist/engine.d.ts +63 -11
  63. package/dist/engine.js +106 -29
  64. package/dist/flows.d.ts +127 -0
  65. package/dist/flows.js +294 -0
  66. package/dist/governor.d.ts +42 -7
  67. package/dist/governor.js +82 -32
  68. package/dist/health.js +2 -1
  69. package/dist/host.d.ts +38 -2
  70. package/dist/host.js +689 -52
  71. package/dist/human-input.d.ts +84 -0
  72. package/dist/human-input.js +448 -0
  73. package/dist/humanize.d.ts +123 -0
  74. package/dist/humanize.js +241 -0
  75. package/dist/identities.js +4 -1
  76. package/dist/idle-timer.d.ts +12 -0
  77. package/dist/idle-timer.js +25 -0
  78. package/dist/index.d.ts +13 -4
  79. package/dist/index.js +7 -1
  80. package/dist/lifecycle.d.ts +11 -1
  81. package/dist/lifecycle.js +11 -2
  82. package/dist/live-client.d.ts +22 -0
  83. package/dist/live-client.js +95 -0
  84. package/dist/live-page.d.ts +4 -0
  85. package/dist/live-page.js +144 -0
  86. package/dist/live-server.d.ts +173 -0
  87. package/dist/live-server.js +643 -0
  88. package/dist/live.d.ts +120 -0
  89. package/dist/live.js +204 -0
  90. package/dist/login-tool.d.ts +13 -0
  91. package/dist/login-tool.js +8 -3
  92. package/dist/login.d.ts +4 -1
  93. package/dist/login.js +12 -2
  94. package/dist/names.d.ts +28 -0
  95. package/dist/names.js +25 -0
  96. package/dist/network-chrome.d.ts +74 -0
  97. package/dist/network-chrome.js +178 -0
  98. package/dist/network.d.ts +125 -0
  99. package/dist/network.js +264 -0
  100. package/dist/opt-in-settings.d.ts +69 -0
  101. package/dist/opt-in-settings.js +152 -0
  102. package/dist/recorder.d.ts +88 -0
  103. package/dist/recorder.js +538 -0
  104. package/dist/recordings.d.ts +116 -0
  105. package/dist/recordings.js +474 -0
  106. package/dist/redact.d.ts +7 -0
  107. package/dist/redact.js +18 -0
  108. package/dist/replay.d.ts +20 -0
  109. package/dist/replay.js +383 -0
  110. package/dist/reputation.d.ts +24 -2
  111. package/dist/reputation.js +63 -17
  112. package/dist/runtime-lock.js +3 -2
  113. package/dist/session-export.js +1 -1
  114. package/dist/session.d.ts +10 -2
  115. package/dist/session.js +10 -2
  116. package/dist/settings.d.ts +104 -2
  117. package/dist/settings.js +204 -6
  118. package/dist/sharing.d.ts +96 -0
  119. package/dist/sharing.js +269 -0
  120. package/dist/snippet.d.ts +8 -2
  121. package/dist/snippet.js +10 -4
  122. package/dist/tab-locks.d.ts +63 -0
  123. package/dist/tab-locks.js +179 -0
  124. package/dist/tools.d.ts +38 -0
  125. package/dist/tools.js +20 -1
  126. package/dist/tuning.d.ts +14 -0
  127. package/dist/tuning.js +9 -0
  128. package/dist/upstream.d.ts +11 -0
  129. package/dist/vault.js +5 -4
  130. package/npm-shrinkwrap.json +6 -5
  131. package/package.json +13 -7
@@ -0,0 +1,77 @@
1
+ import type { TurnoTool } from "./tools.js";
2
+ /**
3
+ * Captcha solving, off by default (identity.json `captcha`). `browser_solve_captcha` finds a
4
+ * captcha widget on the current tab, sends its kind, site key and the page URL to the solver
5
+ * service the person configured, and puts the token it returns into the page's response field
6
+ * (and the widget's callback, when it names one). The agent then submits the form itself.
7
+ *
8
+ * What it is and is not:
9
+ *
10
+ * - The solver is a third party: it sees the page URL and the widget, and usually loads the
11
+ * page on its own machines to answer. Its key comes from the secret store through a
12
+ * `keychain:` reference, joins the redactor, and never appears in a tool argument or result.
13
+ * - It answers only the widgets that hand back a token (`WIDGETS`). A full-page "checking your
14
+ * browser" interstitial, a "verify it's you" prompt or a block page is left to the person.
15
+ * - Every attempt, solved or not, is one line in the identity's reputation log (`reputation.ts`)
16
+ * with the host name, the widget kind and the provider: never the token or the key.
17
+ * - Many sites' terms forbid solving their captchas by machine; the docs say so and say it is
18
+ * meant for the person's own accounts.
19
+ */
20
+ /** The widgets a token answers, with the task type of the task protocol and where the token goes. */
21
+ export declare const WIDGETS: {
22
+ readonly recaptcha: {
23
+ readonly task: "RecaptchaV2TaskProxyless";
24
+ readonly fields: readonly ["g-recaptcha-response"];
25
+ readonly label: "reCAPTCHA v2";
26
+ };
27
+ readonly hcaptcha: {
28
+ readonly task: "HCaptchaTaskProxyless";
29
+ readonly fields: readonly ["h-captcha-response", "g-recaptcha-response"];
30
+ readonly label: "hCaptcha";
31
+ };
32
+ readonly turnstile: {
33
+ readonly task: "TurnstileTaskProxyless";
34
+ readonly fields: readonly ["cf-turnstile-response"];
35
+ readonly label: "Turnstile";
36
+ };
37
+ };
38
+ type WidgetKind = keyof typeof WIDGETS;
39
+ /** A widget found on a page. The site key is public: it is in the page's markup. */
40
+ interface CaptchaWidget {
41
+ kind: WidgetKind;
42
+ siteKey: string;
43
+ /** reCAPTCHA's invisible mode. */
44
+ invisible?: boolean;
45
+ /** The global function the widget calls with the token (`data-callback`), when it names one. */
46
+ callback?: string;
47
+ }
48
+ interface SolveRequest {
49
+ widget: CaptchaWidget;
50
+ pageUrl: string;
51
+ signal?: AbortSignal;
52
+ }
53
+ /** A solver service, behind one method. */
54
+ export interface CaptchaSolver {
55
+ /** How the result names it: "task-api at solver.example.com". */
56
+ readonly label: string;
57
+ /** The provider id for the reputation log. */
58
+ readonly provider: string;
59
+ solve(request: SolveRequest): Promise<{
60
+ token: string;
61
+ }>;
62
+ }
63
+ type Fetch = typeof fetch;
64
+ /**
65
+ * The task protocol many solver services share: `POST <endpoint>/createTask` with the account
66
+ * key and a task, then `POST <endpoint>/getTaskResult` until the task is ready. Errors come back
67
+ * as `errorId` with `errorCode` and `errorDescription`.
68
+ */
69
+ export declare function taskApiSolver(options: {
70
+ endpoint: string;
71
+ key: string;
72
+ fetch?: Fetch;
73
+ /** Waits between polls (ms); the last one repeats. Default: 1 s, 2 s, then every 3 s. */
74
+ polls?: readonly number[];
75
+ }): CaptchaSolver;
76
+ export declare function solveCaptchaTool(): TurnoTool;
77
+ export {};
@@ -0,0 +1,334 @@
1
+ import { secretStore } from "turno-core/secrets";
2
+ import { captchaTimeoutMs } from "./opt-in-settings.js";
3
+ import { recordSolve } from "./reputation.js";
4
+ import { readIdentitySettings } from "./settings.js";
5
+ import { upstream } from "./upstream.js";
6
+ import { names } from "./names.js";
7
+ /**
8
+ * Captcha solving, off by default (identity.json `captcha`). `browser_solve_captcha` finds a
9
+ * captcha widget on the current tab, sends its kind, site key and the page URL to the solver
10
+ * service the person configured, and puts the token it returns into the page's response field
11
+ * (and the widget's callback, when it names one). The agent then submits the form itself.
12
+ *
13
+ * What it is and is not:
14
+ *
15
+ * - The solver is a third party: it sees the page URL and the widget, and usually loads the
16
+ * page on its own machines to answer. Its key comes from the secret store through a
17
+ * `keychain:` reference, joins the redactor, and never appears in a tool argument or result.
18
+ * - It answers only the widgets that hand back a token (`WIDGETS`). A full-page "checking your
19
+ * browser" interstitial, a "verify it's you" prompt or a block page is left to the person.
20
+ * - Every attempt, solved or not, is one line in the identity's reputation log (`reputation.ts`)
21
+ * with the host name, the widget kind and the provider: never the token or the key.
22
+ * - Many sites' terms forbid solving their captchas by machine; the docs say so and say it is
23
+ * meant for the person's own accounts.
24
+ */
25
+ /** The widgets a token answers, with the task type of the task protocol and where the token goes. */
26
+ export const WIDGETS = {
27
+ recaptcha: { task: "RecaptchaV2TaskProxyless", fields: ["g-recaptcha-response"], label: "reCAPTCHA v2" },
28
+ hcaptcha: {
29
+ task: "HCaptchaTaskProxyless",
30
+ fields: ["h-captcha-response", "g-recaptcha-response"],
31
+ label: "hCaptcha",
32
+ },
33
+ turnstile: { task: "TurnstileTaskProxyless", fields: ["cf-turnstile-response"], label: "Turnstile" },
34
+ };
35
+ class SolverError extends Error {
36
+ constructor(message) {
37
+ super(message);
38
+ this.name = "SolverError";
39
+ }
40
+ }
41
+ /**
42
+ * The task protocol many solver services share: `POST <endpoint>/createTask` with the account
43
+ * key and a task, then `POST <endpoint>/getTaskResult` until the task is ready. Errors come back
44
+ * as `errorId` with `errorCode` and `errorDescription`.
45
+ */
46
+ export function taskApiSolver(options) {
47
+ const base = options.endpoint.replace(/\/+$/, "");
48
+ const host = new URL(options.endpoint).host;
49
+ const doFetch = options.fetch ?? fetch;
50
+ const polls = options.polls?.length ? options.polls : [1_000, 2_000, 3_000];
51
+ const post = async (path, body, signal) => {
52
+ let res;
53
+ try {
54
+ res = await doFetch(`${base}/${path}`, {
55
+ method: "POST",
56
+ headers: { "content-type": "application/json" },
57
+ body: JSON.stringify({ clientKey: options.key, ...body }),
58
+ ...(signal ? { signal } : {}),
59
+ });
60
+ }
61
+ catch (error) {
62
+ if (signal?.aborted)
63
+ throw new SolverError("the solver did not answer in time");
64
+ throw new SolverError(`cannot reach ${host}: ${error.message}`);
65
+ }
66
+ const text = await res.text().catch(() => "");
67
+ if (!res.ok)
68
+ throw new SolverError(`${host} answered ${res.status}`);
69
+ let json;
70
+ try {
71
+ json = JSON.parse(text);
72
+ }
73
+ catch {
74
+ throw new SolverError(`${host} did not answer with JSON`);
75
+ }
76
+ if (json.errorId !== undefined && json.errorId !== 0) {
77
+ const code = typeof json.errorCode === "string" ? json.errorCode : `error ${String(json.errorId)}`;
78
+ const why = typeof json.errorDescription === "string" ? `: ${json.errorDescription.slice(0, 200)}` : "";
79
+ throw new SolverError(`${host} refused the task (${code}${why})`);
80
+ }
81
+ return json;
82
+ };
83
+ return {
84
+ label: `task-api at ${host}`,
85
+ provider: "task-api",
86
+ async solve({ widget, pageUrl, signal }) {
87
+ const created = await post("createTask", {
88
+ task: {
89
+ type: WIDGETS[widget.kind].task,
90
+ websiteURL: pageUrl,
91
+ websiteKey: widget.siteKey,
92
+ ...(widget.invisible ? { isInvisible: true } : {}),
93
+ },
94
+ }, signal);
95
+ const taskId = created.taskId;
96
+ if (typeof taskId !== "string" && typeof taskId !== "number")
97
+ throw new SolverError(`${host} gave no task id`);
98
+ for (let i = 0;; i++) {
99
+ const wait = polls[Math.min(i, polls.length - 1)];
100
+ await new Promise((resolve, reject) => {
101
+ if (signal?.aborted) {
102
+ reject(new SolverError("the solver did not answer in time"));
103
+ return;
104
+ }
105
+ const t = setTimeout(resolve, wait);
106
+ signal?.addEventListener("abort", () => {
107
+ clearTimeout(t);
108
+ reject(new SolverError("the solver did not answer in time"));
109
+ }, { once: true });
110
+ });
111
+ const result = await post("getTaskResult", { taskId }, signal);
112
+ if (result.status === "processing")
113
+ continue;
114
+ const solution = result.solution;
115
+ const token = solution?.gRecaptchaResponse ?? solution?.token;
116
+ if (result.status === "ready" && typeof token === "string" && token)
117
+ return { token };
118
+ throw new SolverError(`${host} answered without a token`);
119
+ }
120
+ },
121
+ };
122
+ }
123
+ /** The captcha widgets of a page's main frame, first the ones its markup declares. */
124
+ async function findWidgets(page) {
125
+ return await page
126
+ .evaluate(() => {
127
+ const found = [];
128
+ const declared = [
129
+ ["recaptcha", ".g-recaptcha[data-sitekey]"],
130
+ ["hcaptcha", ".h-captcha[data-sitekey]"],
131
+ ["turnstile", ".cf-turnstile[data-sitekey]"],
132
+ ];
133
+ for (const [kind, selector] of declared) {
134
+ for (const el of Array.from(document.querySelectorAll(selector))) {
135
+ const siteKey = el.getAttribute("data-sitekey") ?? "";
136
+ const callback = el.getAttribute("data-callback") ?? undefined;
137
+ found.push({
138
+ kind,
139
+ siteKey,
140
+ ...(el.getAttribute("data-size") === "invisible" ? { invisible: true } : {}),
141
+ ...(callback ? { callback } : {}),
142
+ });
143
+ }
144
+ }
145
+ // A widget rendered from script has no declaring element: its frame's URL carries the key.
146
+ for (const frame of Array.from(document.querySelectorAll("iframe[src]"))) {
147
+ let url;
148
+ try {
149
+ url = new URL(frame.src);
150
+ }
151
+ catch {
152
+ continue;
153
+ }
154
+ const add = (kind, siteKey, invisible) => {
155
+ if (siteKey && !found.some((f) => f.kind === kind && f.siteKey === siteKey))
156
+ found.push({ kind, siteKey, ...(invisible ? { invisible } : {}) });
157
+ };
158
+ if (/\/recaptcha\/(api2|enterprise)\/anchor/.test(url.pathname))
159
+ add("recaptcha", url.searchParams.get("k"), url.searchParams.get("size") === "invisible");
160
+ else if (/hcaptcha/.test(url.hostname))
161
+ add("hcaptcha", url.searchParams.get("sitekey") ?? new URLSearchParams(url.hash.slice(1)).get("sitekey"));
162
+ else if (url.hostname === "challenges.cloudflare.com")
163
+ add("turnstile", /\/(0x[0-9A-Za-z_-]{10,})\//.exec(url.pathname)?.[1]);
164
+ }
165
+ return found.filter((f) => f.siteKey);
166
+ })
167
+ .then((list) => list)
168
+ .catch(() => []);
169
+ }
170
+ /**
171
+ * Puts a token where the widget's form reads it, and calls the widget's callback. The fields
172
+ * are set from Patchright's isolated world, like every other turno script; the callback is a
173
+ * function of the page's own scripts, so only that call runs in the page's main world.
174
+ */
175
+ async function applyToken(page, widget, token) {
176
+ const fields = await page.evaluate(({ names, token }) => {
177
+ let set = 0;
178
+ for (const name of names) {
179
+ for (const el of Array.from(document.querySelectorAll(`[name="${name}"], #${name}`))) {
180
+ el.value = token;
181
+ set++;
182
+ }
183
+ }
184
+ return set;
185
+ }, { names: [...WIDGETS[widget.kind].fields], token });
186
+ let callback = false;
187
+ if (widget.callback && /^[A-Za-z_$][\w$.]*$/.test(widget.callback)) {
188
+ callback = await page
189
+ .evaluate(({ path, token }) => {
190
+ let fn = window;
191
+ for (const part of path.split("."))
192
+ fn = fn?.[part];
193
+ if (typeof fn !== "function")
194
+ return false;
195
+ fn(token);
196
+ return true;
197
+ }, { path: widget.callback, token }, undefined, false)
198
+ .catch(() => false);
199
+ }
200
+ return { fields, callback };
201
+ }
202
+ /** The configured solver, its key from the secret store; the key joins the redactor first. */
203
+ async function resolveSolver(ctx, settings) {
204
+ const vault = ctx.vault;
205
+ const item = settings.key.slice("keychain:".length);
206
+ const store = vault.store ?? secretStore(vault.identity.env);
207
+ if (!store)
208
+ throw new SolverError(`captcha.key names ${settings.key}, but this machine has no secret store`);
209
+ const key = await store.get(item).catch(() => undefined);
210
+ if (key === undefined)
211
+ throw new SolverError(`the secret store has no item "${item}" for captcha.key (store it with: ${names().secretSet(item)})`);
212
+ vault.redactor.add(key, "captcha solver key");
213
+ return taskApiSolver({
214
+ endpoint: settings.endpoint,
215
+ key,
216
+ ...(ctx.providers?.fetch ? { fetch: ctx.providers.fetch } : {}),
217
+ });
218
+ }
219
+ function fail(message) {
220
+ return { content: [{ type: "text", text: `### Error\n${message}` }], isError: true };
221
+ }
222
+ function solveSchema() {
223
+ const z = upstream().utils.z;
224
+ return {
225
+ name: "browser_solve_captcha",
226
+ title: "Solve the captcha on the page",
227
+ description: [
228
+ "Solve the captcha widget on the current tab (reCAPTCHA v2, hCaptcha or Turnstile) through the solver service the person configured for this browser identity, and put the token into the page.",
229
+ "Call it only when a captcha stands between you and a step the person asked for on their own account; then submit the form yourself, before the token expires (about two minutes).",
230
+ "It does not answer full-page browser checks, verify-it's-you prompts or block pages: hand those to the person.",
231
+ "The solver sees the page URL and the widget. Every use is logged in the identity's reputation log.",
232
+ ].join(" "),
233
+ inputSchema: z.object({}),
234
+ type: "action",
235
+ };
236
+ }
237
+ export function solveCaptchaTool() {
238
+ let schema;
239
+ return {
240
+ get schema() {
241
+ schema ??= solveSchema();
242
+ return schema;
243
+ },
244
+ async handle(ctx) {
245
+ const vault = ctx.vault;
246
+ const page = ctx.stock?.currentPage();
247
+ if (!vault || !ctx.stock)
248
+ return fail("browser_solve_captcha needs a browser identity (turno-browser-mcp --identity <id>)");
249
+ const { identity } = vault;
250
+ let settings;
251
+ try {
252
+ settings = readIdentitySettings(identity.id, identity.env)?.captcha;
253
+ }
254
+ catch (error) {
255
+ return fail(error.message);
256
+ }
257
+ if (!settings)
258
+ return fail(`captcha solving is off for identity "${identity.id}"; only the person can turn it on (${names().identity("set", identity.id)} --captcha-provider task-api --captcha-endpoint <url> --captcha-key keychain:<item>). Otherwise ask them to answer it in the browser window.`);
259
+ if (!page)
260
+ return fail("there is no page open: navigate to the page with the captcha first");
261
+ let url;
262
+ try {
263
+ url = new URL(page.url());
264
+ }
265
+ catch {
266
+ return fail("the current page has no web address");
267
+ }
268
+ if (url.protocol !== "https:" && url.protocol !== "http:")
269
+ return fail("the current page is not a web page");
270
+ const widgets = await findWidgets(page);
271
+ const widget = widgets[0];
272
+ if (!widget)
273
+ return fail("no captcha widget this tool can answer is on the current page (reCAPTCHA v2, hCaptcha, Turnstile). A full-page browser check, a verify-it's-you prompt or a block page is for the person to handle in the window.");
274
+ const timeoutMs = captchaTimeoutMs(settings);
275
+ const controller = new AbortController();
276
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
277
+ timer.unref?.();
278
+ const onAbort = () => controller.abort();
279
+ ctx.signal?.addEventListener("abort", onAbort, { once: true });
280
+ const started = Date.now();
281
+ const log = (ok) => {
282
+ try {
283
+ recordSolve(identity.id, identity.env, {
284
+ site: url.hostname,
285
+ widget: widget.kind,
286
+ provider: settings.provider,
287
+ ok,
288
+ });
289
+ }
290
+ catch {
291
+ /* the log is best effort; a full disk must not break a tool call */
292
+ }
293
+ };
294
+ try {
295
+ const solver = ctx.providers?.solver ?? (await resolveSolver(ctx, settings));
296
+ const { token } = await solver.solve({ widget, pageUrl: page.url(), signal: controller.signal });
297
+ const applied = await applyToken(page, widget, token);
298
+ log(true);
299
+ const seconds = ((Date.now() - started) / 1000).toFixed(1);
300
+ const placed = applied.fields || applied.callback
301
+ ? `Token put into the page${applied.fields ? ` (${applied.fields} response field${applied.fields === 1 ? "" : "s"})` : ""}${applied.callback ? `; the widget's callback ${widget.callback} ran` : ""}.`
302
+ : "The page has no response field or callback for the token yet; its widget script may not have loaded. Try again after it shows.";
303
+ return {
304
+ content: [
305
+ {
306
+ type: "text",
307
+ text: [
308
+ "### Captcha",
309
+ `Widget: ${WIDGETS[widget.kind].label}${widgets.length > 1 ? ` (the first of ${widgets.length} on the page)` : ""}`,
310
+ `Solver: ${solver.label}, ${seconds} s`,
311
+ placed,
312
+ `Logged in the reputation log of "${identity.id}".`,
313
+ "Next: submit the form now; the token expires in about two minutes.",
314
+ ].join("\n"),
315
+ },
316
+ ],
317
+ ...(applied.fields || applied.callback ? {} : { isError: true }),
318
+ };
319
+ }
320
+ catch (error) {
321
+ log(false);
322
+ const why = controller.signal.aborted
323
+ ? `the solver did not answer within ${timeoutMs / 1000} s`
324
+ : error.message;
325
+ return fail(`the captcha was not solved: ${why}. Ask the person to answer it in the browser window.`);
326
+ }
327
+ finally {
328
+ clearTimeout(timer);
329
+ ctx.signal?.removeEventListener("abort", onAbort);
330
+ }
331
+ },
332
+ };
333
+ }
334
+ //# sourceMappingURL=captcha.js.map
@@ -0,0 +1,20 @@
1
+ interface Message {
2
+ id?: number;
3
+ sessionId?: string;
4
+ method?: string;
5
+ result?: Record<string, unknown>;
6
+ error?: unknown;
7
+ }
8
+ /**
9
+ * The reply to send instead of `reply`, or undefined to pass it through. A reply Patchright would
10
+ * choke on becomes a protocol error, which it handles (`_sendMayFail` returns nothing).
11
+ */
12
+ export declare function fixReply(method: string | undefined, reply: Message): Message | undefined;
13
+ export interface CdpRelay {
14
+ /** What Patchright connects to: `ws+unix://<socket>:/`. */
15
+ endpoint: string;
16
+ close(): Promise<void>;
17
+ }
18
+ /** Relays `listenPath` to the CDP server on `targetPath` (both Unix sockets). */
19
+ export declare function startCdpRelay(listenPath: string, targetPath: string): Promise<CdpRelay>;
20
+ export {};
@@ -0,0 +1,101 @@
1
+ import { createServer } from "node:http";
2
+ import { upstream } from "./upstream.js";
3
+ const OPEN = 1;
4
+ /**
5
+ * The reply to send instead of `reply`, or undefined to pass it through. A reply Patchright would
6
+ * choke on becomes a protocol error, which it handles (`_sendMayFail` returns nothing).
7
+ */
8
+ export function fixReply(method, reply) {
9
+ if (method === "DOM.getDocument" && reply.result && !reply.result.root) {
10
+ return {
11
+ id: reply.id,
12
+ ...(reply.sessionId ? { sessionId: reply.sessionId } : {}),
13
+ error: { code: -32000, message: "No document on this target" },
14
+ };
15
+ }
16
+ return undefined;
17
+ }
18
+ /** Relays `listenPath` to the CDP server on `targetPath` (both Unix sockets). */
19
+ export async function startCdpRelay(listenPath, targetPath) {
20
+ const { ws: WebSocket, wsServer: WebSocketServer } = upstream().utils;
21
+ const wss = new WebSocketServer({ noServer: true, maxPayload: 256 * 1024 * 1024 });
22
+ const live = new Set();
23
+ const server = createServer((_req, res) => {
24
+ res.writeHead(404).end();
25
+ });
26
+ server.on("upgrade", (request, socket, head) => {
27
+ wss.handleUpgrade(request, socket, head, (client) => {
28
+ const target = new WebSocket(`ws+unix://${targetPath}:/`, { maxPayload: 256 * 1024 * 1024 });
29
+ live.add(client);
30
+ live.add(target);
31
+ const queue = [];
32
+ // The method of each request in flight, by session and id, to know what a reply answers.
33
+ const methods = new Map();
34
+ target.on("open", () => {
35
+ for (const m of queue.splice(0))
36
+ target.send(m);
37
+ });
38
+ client.on("message", (data) => {
39
+ const text = data.toString();
40
+ try {
41
+ const m = JSON.parse(text);
42
+ if (m.id !== undefined && m.method)
43
+ methods.set(`${m.sessionId ?? ""}:${m.id}`, m.method);
44
+ }
45
+ catch {
46
+ /* not JSON: pass it on and let the browser answer */
47
+ }
48
+ if (target.readyState === OPEN)
49
+ target.send(text);
50
+ else
51
+ queue.push(text);
52
+ });
53
+ target.on("message", (data) => {
54
+ let text = data.toString();
55
+ try {
56
+ const m = JSON.parse(text);
57
+ if (m.id !== undefined) {
58
+ const key = `${m.sessionId ?? ""}:${m.id}`;
59
+ const fixed = fixReply(methods.get(key), m);
60
+ methods.delete(key);
61
+ if (fixed)
62
+ text = JSON.stringify(fixed);
63
+ }
64
+ }
65
+ catch {
66
+ /* pass it through */
67
+ }
68
+ if (client.readyState === OPEN)
69
+ client.send(text);
70
+ });
71
+ const end = () => {
72
+ live.delete(client);
73
+ live.delete(target);
74
+ client.close();
75
+ target.close();
76
+ };
77
+ client.on("close", end);
78
+ target.on("close", end);
79
+ client.on("error", end);
80
+ target.on("error", end);
81
+ });
82
+ });
83
+ await new Promise((resolve, reject) => {
84
+ server.once("error", reject);
85
+ server.listen(listenPath, () => {
86
+ server.off("error", reject);
87
+ resolve();
88
+ });
89
+ });
90
+ return {
91
+ endpoint: `ws+unix://${listenPath}:/`,
92
+ async close() {
93
+ for (const socket of live)
94
+ socket.terminate();
95
+ live.clear();
96
+ wss.close();
97
+ await new Promise((resolve) => server.close(() => resolve()));
98
+ },
99
+ };
100
+ }
101
+ //# sourceMappingURL=cdp-relay.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Chrome features Playwright turns off, and the one turno turns back on.
3
+ *
4
+ * Playwright starts Chrome with one `--disable-features=` list (its `chromiumSwitches`). Among
5
+ * them is `ThirdPartyStoragePartitioning`, which every Chrome since 115 has on: a site embedded
6
+ * in another site gets its own storage there (localStorage, IndexedDB, caches) instead of its
7
+ * first-party storage. A page can tell the difference, and a person's Chrome never has it off,
8
+ * so turno's Chrome engine drops Playwright's list and passes the same list without that one
9
+ * feature. Chrome reads the last `--disable-features` it is given, so the list goes before the
10
+ * user's own launch args: a `--disable-features` there still wins, as it did before.
11
+ *
12
+ * The list is a copy of Playwright's: `test/chrome-features.test.ts` reads the installed
13
+ * patchright-core and fails when they drift apart after an update.
14
+ */
15
+ /** The feature turno leaves on. */
16
+ export declare const KEPT_FEATURE = "ThirdPartyStoragePartitioning";
17
+ /** Playwright's `disabledFeatures` (patchright-core 1.64), in its order. */
18
+ export declare const PLAYWRIGHT_DISABLED_FEATURES: readonly string[];
19
+ /** The switches for a Chrome turno launches: Playwright's list to drop, and the one to pass. */
20
+ export declare function storagePartitioningArgs(): {
21
+ ignoreDefaultArgs: string[];
22
+ args: string[];
23
+ };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Chrome features Playwright turns off, and the one turno turns back on.
3
+ *
4
+ * Playwright starts Chrome with one `--disable-features=` list (its `chromiumSwitches`). Among
5
+ * them is `ThirdPartyStoragePartitioning`, which every Chrome since 115 has on: a site embedded
6
+ * in another site gets its own storage there (localStorage, IndexedDB, caches) instead of its
7
+ * first-party storage. A page can tell the difference, and a person's Chrome never has it off,
8
+ * so turno's Chrome engine drops Playwright's list and passes the same list without that one
9
+ * feature. Chrome reads the last `--disable-features` it is given, so the list goes before the
10
+ * user's own launch args: a `--disable-features` there still wins, as it did before.
11
+ *
12
+ * The list is a copy of Playwright's: `test/chrome-features.test.ts` reads the installed
13
+ * patchright-core and fails when they drift apart after an update.
14
+ */
15
+ /** The feature turno leaves on. */
16
+ export const KEPT_FEATURE = "ThirdPartyStoragePartitioning";
17
+ /** Playwright's `disabledFeatures` (patchright-core 1.64), in its order. */
18
+ export const PLAYWRIGHT_DISABLED_FEATURES = Object.freeze([
19
+ "AvoidUnnecessaryBeforeUnloadCheckSync",
20
+ "DestroyProfileOnBrowserClose",
21
+ "DialMediaRouteProvider",
22
+ "GlobalMediaControls",
23
+ "HttpsUpgrades",
24
+ "LensOverlay",
25
+ "PaintHolding",
26
+ "ThirdPartyStoragePartitioning",
27
+ "BlockOriginHeaderModificationOnRedirect",
28
+ "AvoidCorsURLLoaderRestartOnRedirect",
29
+ "Translate",
30
+ "AutoDeElevate",
31
+ "OptimizationHints",
32
+ "NetworkTimeServiceQuerying",
33
+ "AimEnabled",
34
+ "msForceBrowserSignIn",
35
+ "msEdgeUpdateLaunchServicesPreferredVersion",
36
+ ]);
37
+ /** The switches for a Chrome turno launches: Playwright's list to drop, and the one to pass. */
38
+ export function storagePartitioningArgs() {
39
+ return {
40
+ ignoreDefaultArgs: [`--disable-features=${PLAYWRIGHT_DISABLED_FEATURES.join(",")}`],
41
+ args: [`--disable-features=${PLAYWRIGHT_DISABLED_FEATURES.filter((f) => f !== KEPT_FEATURE).join(",")}`],
42
+ };
43
+ }
44
+ //# sourceMappingURL=chrome-features.js.map
@@ -0,0 +1,11 @@
1
+ import { type Command } from "turno-core/cli";
2
+ import type { Ctx } from "./context.js";
3
+ /**
4
+ * `turno-browser background`: the background server of each identity, the turno-browser-mcp
5
+ * that `turno-browser do` starts to reach the identity's browser from the shell. `status` shows
6
+ * which run, `start` starts one ahead, `stop` stops one (it closes its Chrome first).
7
+ */
8
+ /** `background status --json`: one element per running server. */
9
+ export declare const BACKGROUND_JSON: import("turno-core/cli").JsonOutput;
10
+ /** The `background` group. */
11
+ export declare function backgroundCommand(c: Ctx): Command;