turno-browser 0.2.0 → 0.4.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 (121) hide show
  1. package/CHANGELOG.md +228 -0
  2. package/README.md +205 -16
  3. package/dist/act-model.d.ts +85 -0
  4. package/dist/act-model.js +116 -0
  5. package/dist/act.d.ts +37 -0
  6. package/dist/act.js +599 -0
  7. package/dist/api.d.ts +96 -0
  8. package/dist/api.js +88 -0
  9. package/dist/argv.d.ts +55 -3
  10. package/dist/argv.js +190 -10
  11. package/dist/batch.d.ts +19 -0
  12. package/dist/batch.js +148 -0
  13. package/dist/bench.d.ts +1 -1
  14. package/dist/bench.js +21 -5
  15. package/dist/bin/mcp.js +108 -12
  16. package/dist/captcha.d.ts +77 -0
  17. package/dist/captcha.js +333 -0
  18. package/dist/cdp-relay.d.ts +20 -0
  19. package/dist/cdp-relay.js +101 -0
  20. package/dist/chrome-features.d.ts +23 -0
  21. package/dist/chrome-features.js +44 -0
  22. package/dist/detectors.d.ts +11 -0
  23. package/dist/detectors.js +46 -4
  24. package/dist/diagnose.d.ts +45 -0
  25. package/dist/diagnose.js +326 -0
  26. package/dist/doctor.d.ts +85 -0
  27. package/dist/doctor.js +556 -0
  28. package/dist/engine-attach.d.ts +27 -0
  29. package/dist/engine-attach.js +165 -0
  30. package/dist/engine-camoufox.d.ts +32 -0
  31. package/dist/engine-camoufox.js +270 -0
  32. package/dist/engine-lightpanda.d.ts +72 -0
  33. package/dist/engine-lightpanda.js +292 -0
  34. package/dist/engine.d.ts +119 -0
  35. package/dist/engine.js +355 -0
  36. package/dist/flows.d.ts +127 -0
  37. package/dist/flows.js +294 -0
  38. package/dist/governor.d.ts +119 -0
  39. package/dist/governor.js +325 -0
  40. package/dist/health.d.ts +60 -0
  41. package/dist/health.js +86 -0
  42. package/dist/host.d.ts +95 -0
  43. package/dist/host.js +1181 -0
  44. package/dist/human-input.d.ts +84 -0
  45. package/dist/human-input.js +443 -0
  46. package/dist/humanize.d.ts +123 -0
  47. package/dist/humanize.js +241 -0
  48. package/dist/identities.d.ts +23 -10
  49. package/dist/identities.js +45 -37
  50. package/dist/idle-timer.d.ts +12 -0
  51. package/dist/idle-timer.js +25 -0
  52. package/dist/ids.d.ts +9 -0
  53. package/dist/ids.js +34 -0
  54. package/dist/index.d.ts +21 -6
  55. package/dist/index.js +19 -18
  56. package/dist/lifecycle.d.ts +99 -0
  57. package/dist/lifecycle.js +172 -0
  58. package/dist/live-client.d.ts +22 -0
  59. package/dist/live-client.js +93 -0
  60. package/dist/live-page.d.ts +11 -0
  61. package/dist/live-page.js +143 -0
  62. package/dist/live-server.d.ts +173 -0
  63. package/dist/live-server.js +640 -0
  64. package/dist/live.d.ts +120 -0
  65. package/dist/live.js +203 -0
  66. package/dist/login-tool.d.ts +45 -0
  67. package/dist/login-tool.js +233 -0
  68. package/dist/login.d.ts +8 -3
  69. package/dist/login.js +65 -26
  70. package/dist/network-chrome.d.ts +74 -0
  71. package/dist/network-chrome.js +178 -0
  72. package/dist/network.d.ts +125 -0
  73. package/dist/network.js +263 -0
  74. package/dist/opt-in-settings.d.ts +69 -0
  75. package/dist/opt-in-settings.js +151 -0
  76. package/dist/patchright.d.ts +4 -2
  77. package/dist/patchright.js +4 -2
  78. package/dist/recorder.d.ts +88 -0
  79. package/dist/recorder.js +538 -0
  80. package/dist/recordings.d.ts +116 -0
  81. package/dist/recordings.js +474 -0
  82. package/dist/redact.d.ts +34 -0
  83. package/dist/redact.js +135 -0
  84. package/dist/replay.d.ts +20 -0
  85. package/dist/replay.js +382 -0
  86. package/dist/reputation.d.ts +89 -0
  87. package/dist/reputation.js +203 -0
  88. package/dist/resources.d.ts +76 -0
  89. package/dist/resources.js +341 -0
  90. package/dist/runtime-lock.d.ts +59 -0
  91. package/dist/runtime-lock.js +131 -0
  92. package/dist/sealed.d.ts +8 -0
  93. package/dist/sealed.js +96 -0
  94. package/dist/session-export.d.ts +67 -0
  95. package/dist/session-export.js +194 -0
  96. package/dist/session.d.ts +20 -0
  97. package/dist/session.js +30 -0
  98. package/dist/settings.d.ts +246 -0
  99. package/dist/settings.js +530 -0
  100. package/dist/sharing.d.ts +96 -0
  101. package/dist/sharing.js +269 -0
  102. package/dist/snippet.d.ts +8 -0
  103. package/dist/snippet.js +22 -0
  104. package/dist/tab-locks.d.ts +63 -0
  105. package/dist/tab-locks.js +179 -0
  106. package/dist/tools.d.ts +111 -0
  107. package/dist/tools.js +59 -0
  108. package/dist/totp.d.ts +32 -0
  109. package/dist/totp.js +82 -0
  110. package/dist/tuning.d.ts +76 -0
  111. package/dist/tuning.js +69 -0
  112. package/dist/units.d.ts +8 -0
  113. package/dist/units.js +20 -0
  114. package/dist/upstream.d.ts +243 -0
  115. package/dist/upstream.js +46 -0
  116. package/dist/vault.d.ts +91 -0
  117. package/dist/vault.js +273 -0
  118. package/npm-shrinkwrap.json +1074 -3
  119. package/package.json +5 -4
  120. package/dist/paths.d.ts +0 -17
  121. package/dist/paths.js +0 -17
package/dist/doctor.js ADDED
@@ -0,0 +1,556 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { browserPaths as paths } from "turno-core/paths";
6
+ import { readProcTable, signalProcess } from "turno-core/process";
7
+ import { secretStore } from "turno-core/secrets";
8
+ import { readHealth } from "./health.js";
9
+ import { identityDir, isValidIdentityId } from "./ids.js";
10
+ import { defaultChromeUserDataDir, parseAttachTarget, resolveAttachEndpoint } from "./engine-attach.js";
11
+ import { findLightpanda, findOrphanLightpandas, lightpandaCookieJar, lightpandaInstallHint, } from "./engine-lightpanda.js";
12
+ import { camoufoxInstallHint, camoufoxProfileDir, findCamoufox, findPlaywrightCore, playwrightCoreHint, } from "./engine-camoufox.js";
13
+ import { findProfileChrome, sweepOrphan } from "./lifecycle.js";
14
+ import { readChallenges, summarizeChallenges } from "./reputation.js";
15
+ import { inUseMessage, readRuntimeLock, runtimeLockAlive, runtimeLockPath } from "./runtime-lock.js";
16
+ import { acceptLanguages, checkIdentitySettings, systemTimezone } from "./settings.js";
17
+ const FIX = "turno browser doctor --fix";
18
+ const CHROME_PATHS = (env, platform) => {
19
+ const home = paths(env).home;
20
+ if (platform === "darwin")
21
+ return [
22
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
23
+ join(home, "Applications", "Google Chrome.app", "Contents", "MacOS", "Google Chrome"),
24
+ ];
25
+ if (platform === "win32") {
26
+ return [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]]
27
+ .filter(Boolean)
28
+ .map((root) => join(root, "Google", "Chrome", "Application", "chrome.exe"));
29
+ }
30
+ return ["/opt/google/chrome/chrome", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
31
+ };
32
+ /** CFBundleShortVersionString of a macOS Info.plist (XML). */
33
+ export function chromeVersionFromPlist(xml) {
34
+ return /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(xml)?.[1]?.trim();
35
+ }
36
+ /** The installed Google Chrome (the `chrome` channel Playwright launches) and its version. */
37
+ export function findChrome(env = process.env, platform = process.platform) {
38
+ const path = CHROME_PATHS(env, platform).find((p) => existsSync(p));
39
+ if (!path)
40
+ return undefined;
41
+ let version;
42
+ try {
43
+ if (platform === "darwin")
44
+ version = chromeVersionFromPlist(readFileSync(join(dirname(dirname(path)), "Info.plist"), "utf8"));
45
+ else
46
+ version = /(\d+\.\d+\.\d+\.\d+)/.exec(execFileSync(path, ["--version"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }))?.[1];
47
+ }
48
+ catch {
49
+ /* found, version unknown */
50
+ }
51
+ return version ? { path, version } : { path };
52
+ }
53
+ /** Starts Chrome headless on a throwaway profile, opens a blank page and closes it. */
54
+ async function smokeLaunch(env) {
55
+ const dir = mkdtempSync(join(tmpdir(), "turno-browser-doctor-"));
56
+ const t0 = Date.now();
57
+ try {
58
+ const { chromium } = await import("patchright-core");
59
+ const context = await chromium.launchPersistentContext(join(dir, "profile"), {
60
+ channel: "chrome",
61
+ headless: true,
62
+ timeout: 30_000,
63
+ env: { ...env },
64
+ });
65
+ try {
66
+ const page = context.pages()[0] ?? (await context.newPage());
67
+ await page.goto("about:blank");
68
+ }
69
+ finally {
70
+ await context.close();
71
+ }
72
+ return Date.now() - t0;
73
+ }
74
+ finally {
75
+ rmSync(dir, { recursive: true, force: true });
76
+ }
77
+ }
78
+ const firstLine = (e) => String(e.message ?? e).split("\n")[0];
79
+ function systemChecks(env, platform) {
80
+ const out = [];
81
+ if (platform === "darwin") {
82
+ out.push({
83
+ area: "system",
84
+ level: "ok",
85
+ text: "macOS: driving Chrome through its DevTools pipe needs no Accessibility or Screen Recording permission",
86
+ });
87
+ if (env.SSH_CONNECTION || env.SSH_TTY) {
88
+ out.push({
89
+ area: "system",
90
+ level: "warn",
91
+ text: "this is an SSH session: a headed Chrome opens only in the signed-in desktop session (where mcpd runs)",
92
+ manual: "run the browser through mcpd, or pass --headless when you start turno-browser-mcp here",
93
+ });
94
+ }
95
+ }
96
+ else if (platform === "linux") {
97
+ if (env.DISPLAY || env.WAYLAND_DISPLAY)
98
+ out.push({
99
+ area: "system",
100
+ level: "ok",
101
+ text: `display: ${env.WAYLAND_DISPLAY ? `Wayland ${env.WAYLAND_DISPLAY}` : `X11 ${env.DISPLAY}`}`,
102
+ });
103
+ else
104
+ out.push({
105
+ area: "system",
106
+ level: "warn",
107
+ text: "no display: a headed Chrome cannot open here",
108
+ manual: "pass --headless to turno-browser-mcp, or run it inside a desktop session",
109
+ });
110
+ }
111
+ return out;
112
+ }
113
+ function describeSettings(s) {
114
+ const parts = [];
115
+ if (s.timezone)
116
+ parts.push(`time zone ${s.timezone}`);
117
+ const langs = acceptLanguages(s);
118
+ if (langs)
119
+ parts.push(`languages ${langs.join(", ")}`);
120
+ if (s.region)
121
+ parts.push(`region ${s.region}`);
122
+ return parts.length ? parts.join(", ") : "no fixed time zone or languages";
123
+ }
124
+ /** The `turno identity set` flag that replaces the value a problem is about. */
125
+ function settingsFix(id, problem) {
126
+ const flag = [
127
+ ["timezone", "--timezone <zone>"],
128
+ ["locale", "--locale <tag>"],
129
+ ["languages", "--languages <tag,...>"],
130
+ ["region", "--region <CC>"],
131
+ ["health", "--health-url <url> --health-text <text>"],
132
+ ].find(([key]) => problem.startsWith(key))?.[1];
133
+ return flag ? `turno identity set browser:${id} ${flag}` : undefined;
134
+ }
135
+ /**
136
+ * A server that lets several client sessions in (`exclusive = false`, one server for all of
137
+ * them) on an identity that serves one session at a time: those sessions silently share one
138
+ * current tab, and one agent's navigation replaces the page another is reading.
139
+ */
140
+ function servingRows(id, settings, servers) {
141
+ const out = [];
142
+ for (const server of servers) {
143
+ if (server.identity !== id || server.exclusive || server.scope === "session")
144
+ continue;
145
+ if ((server.sharing ?? settings?.sharing ?? "session") !== "session")
146
+ continue;
147
+ out.push({
148
+ level: "warn",
149
+ text: `[server.${server.name}] in mcp.toml lets several sessions in (exclusive = false), but this identity serves one at a time ("sharing": "session"), so those sessions share one current tab`,
150
+ fix: `turno browser set ${id} --sharing tabs`,
151
+ });
152
+ }
153
+ return out;
154
+ }
155
+ function identityChecks(id, env, now, servers = []) {
156
+ const area = `identity ${id}`;
157
+ const out = [];
158
+ const add = (c) => out.push({ area, ...c });
159
+ const { path, settings, problems } = checkIdentitySettings(id, env);
160
+ if (problems.length) {
161
+ const fix = settingsFix(id, problems[0]);
162
+ add({
163
+ level: "fail",
164
+ text: `identity.json ${problems[0].startsWith("is ") ? problems[0] : `is invalid: ${problems.join("; ")}`}`,
165
+ ...(fix ? { fix } : {}),
166
+ manual: problems[0].startsWith("is format")
167
+ ? "update turno-browser: npm install --global turno-browser@latest"
168
+ : `edit or delete ${path}`,
169
+ });
170
+ }
171
+ else if (!settings) {
172
+ add({
173
+ level: "info",
174
+ text: "no identity.json: Chrome's own time zone and languages, which follow this computer",
175
+ fix: `turno identity set browser:${id} --timezone ${systemTimezone()}`,
176
+ });
177
+ }
178
+ else {
179
+ add({ level: "ok", text: `identity.json: ${describeSettings(settings)}` });
180
+ }
181
+ if (settings)
182
+ for (const c of engineRows(id, settings, env))
183
+ add(c);
184
+ if (!problems.length)
185
+ for (const c of servingRows(id, settings, servers))
186
+ add(c);
187
+ const lock = readRuntimeLock(id, env);
188
+ const chrome = findProfileChrome(identityDir(id, env));
189
+ if (lock && runtimeLockAlive(lock)) {
190
+ add({
191
+ level: "ok",
192
+ text: inUseMessage(id, lock)
193
+ .replace(/^browser identity "[^"]+" is /, "")
194
+ .replace(/\. .*$/, ""),
195
+ });
196
+ }
197
+ else if (chrome?.owner === "orphan") {
198
+ add({
199
+ level: "warn",
200
+ text: `Chrome pid ${chrome.pid} was left running on this profile with no server`,
201
+ fix: FIX,
202
+ auto: true,
203
+ });
204
+ }
205
+ else if (chrome) {
206
+ add({
207
+ level: "warn",
208
+ text: `Chrome pid ${chrome.pid} holds this profile, but no turno process does`,
209
+ manual: "close that Chrome window (a Chrome opened by hand, or a login of an older turno)",
210
+ });
211
+ }
212
+ else if (lock) {
213
+ add({
214
+ level: "warn",
215
+ text: `stale runtime lock of pid ${lock.nodePid} (that process is gone)`,
216
+ fix: FIX,
217
+ auto: true,
218
+ });
219
+ }
220
+ else {
221
+ add({ level: "ok", text: "free: no process holds it" });
222
+ }
223
+ const check = settings?.health;
224
+ const health = readHealth(id, env);
225
+ if (!check) {
226
+ add({
227
+ level: "info",
228
+ text: "no session health check: a signed-out session shows up only when a page asks to sign in",
229
+ fix: `turno identity set browser:${id} --health-url <url> --health-text <text>`,
230
+ });
231
+ }
232
+ else if (!health || health.url !== check.url) {
233
+ add({ level: "info", text: `health check of ${check.url}: not run yet (it runs when the browser starts)` });
234
+ }
235
+ else if (health.status === "ok") {
236
+ add({ level: "ok", text: `signed in at ${health.url} (checked ${health.checkedAt})` });
237
+ }
238
+ else if (health.status === "needs_auth") {
239
+ add({
240
+ level: "fail",
241
+ text: `NEEDS_AUTH: not signed in at ${health.url}: ${health.detail ?? "the check failed"} (checked ${health.checkedAt})`,
242
+ fix: `turno browser login ${id}`,
243
+ });
244
+ }
245
+ else {
246
+ add({
247
+ level: "warn",
248
+ text: `the health check of ${health.url} could not run: ${health.detail ?? "unknown error"} (checked ${health.checkedAt})`,
249
+ manual: "check the URL and the network; the next browser start tries again",
250
+ });
251
+ }
252
+ const sites = summarizeChallenges(readChallenges(id, env), now).filter((s) => s.last7d > 0);
253
+ if (sites.length) {
254
+ const recent = readChallenges(id, env).filter((e) => now.getTime() - Date.parse(e.ts) <= 7 * 86_400_000);
255
+ const kinds = ["captcha", "verify", "block"]
256
+ .map((k) => [k, recent.filter((e) => e.kind === k).length])
257
+ .filter(([, n]) => n)
258
+ .map(([k, n]) => `${n} ${k}`);
259
+ add({
260
+ level: "warn",
261
+ text: `${recent.length} challenge${recent.length === 1 ? "" : "s"} in the last 7 days on ${sites.length} site${sites.length === 1 ? "" : "s"} (${kinds.join(", ")})`,
262
+ fix: `turno browser reputation ${id}`,
263
+ });
264
+ }
265
+ return out;
266
+ }
267
+ const ENABLE_DEBUGGING = "start Chrome, open chrome://inspect/#remote-debugging and turn remote debugging on";
268
+ /** What an identity's engine needs (identity.json `engine`, `attach`); none for Chrome. */
269
+ function engineRows(id, settings, env) {
270
+ if (settings.engine === "camoufox")
271
+ return [
272
+ {
273
+ level: "info",
274
+ text: `Camoufox: its own Firefox profile in ${camoufoxProfileDir(id, env)}, not the Chrome profile (sign-ins do not carry over)`,
275
+ fix: `turno browser set ${id} --engine chrome`,
276
+ },
277
+ ];
278
+ if (settings.engine === "lightpanda")
279
+ return [
280
+ {
281
+ level: "info",
282
+ text: `read mode on Lightpanda: its own cookies in ${lightpandaCookieJar(id, env)}, not the Chrome profile`,
283
+ fix: `turno browser set ${id} --engine chrome`,
284
+ },
285
+ ];
286
+ if (settings.attach === undefined)
287
+ return [];
288
+ const target = parseAttachTarget(settings.attach);
289
+ if ("error" in target)
290
+ return [];
291
+ try {
292
+ const endpoint = resolveAttachEndpoint(target, env);
293
+ return [
294
+ {
295
+ level: "ok",
296
+ text: `attach: a Chrome listens at ${endpoint.replace(/\/devtools\/.*$/, "")}; it asks you to allow each new connection, and the agent then sees every window of that profile`,
297
+ },
298
+ ];
299
+ }
300
+ catch {
301
+ const dir = target.kind === "dir" ? target.dir : target.kind === "auto" ? defaultChromeUserDataDir(env) : undefined;
302
+ return [
303
+ {
304
+ level: "warn",
305
+ text: `attach: no Chrome with remote debugging on${dir ? ` for ${dir}` : ""}, so the next tool call fails`,
306
+ manual: ENABLE_DEBUGGING,
307
+ },
308
+ ];
309
+ }
310
+ }
311
+ /** A `lightpanda serve` that a turno-browser-mcp started and that outlived it. */
312
+ function strayLightpandas(table) {
313
+ return table ? findOrphanLightpandas("any", table).map((o) => o.pid) : [];
314
+ }
315
+ function engineChecks(opts, env, ids) {
316
+ const out = [];
317
+ const area = "engines";
318
+ const lightpanda = (opts.lightpanda ?? findLightpanda)(env);
319
+ const users = ids.filter((id) => checkIdentitySettings(id, env).settings?.engine === "lightpanda");
320
+ const platform = opts.platform ?? process.platform;
321
+ const hint = lightpandaInstallHint(platform);
322
+ const install = platform === "darwin" || platform === "linux" ? { fix: hint } : { manual: hint };
323
+ if (lightpanda)
324
+ out.push({
325
+ area,
326
+ level: "ok",
327
+ text: `Lightpanda${lightpanda.version ? ` ${lightpanda.version}` : ""} at ${lightpanda.path} (read mode)`,
328
+ });
329
+ else if (users.length)
330
+ out.push({
331
+ area,
332
+ level: "fail",
333
+ text: `Lightpanda not found, and read mode needs it for ${users.map((u) => `browser:${u}`).join(", ")}`,
334
+ ...install,
335
+ });
336
+ else
337
+ out.push({
338
+ area,
339
+ level: "info",
340
+ text: "Lightpanda not found: only read mode (--engine lightpanda) needs it, and turno never downloads it",
341
+ ...install,
342
+ });
343
+ out.push(...camoufoxChecks(opts, env, ids, platform));
344
+ const stray = strayLightpandas((opts.procTable ?? readProcTable)());
345
+ if (stray.length)
346
+ out.push({
347
+ area,
348
+ level: "warn",
349
+ text: `Lightpanda pid ${stray.join(", ")} was left running by a server that is gone`,
350
+ fix: FIX,
351
+ auto: true,
352
+ });
353
+ return out;
354
+ }
355
+ /** Camoufox and the stock Playwright it runs on: a failure only when an identity uses the engine. */
356
+ function camoufoxChecks(opts, env, ids, platform) {
357
+ const out = [];
358
+ const area = "engines";
359
+ const users = ids.filter((id) => checkIdentitySettings(id, env).settings?.engine === "camoufox");
360
+ const needed = users.length > 0;
361
+ const who = users.map((u) => `browser:${u}`).join(", ");
362
+ const camoufox = (opts.camoufox ?? findCamoufox)(env);
363
+ const fix = camoufoxInstallHint(platform);
364
+ if (camoufox)
365
+ out.push({
366
+ area,
367
+ level: "ok",
368
+ text: `Camoufox${camoufox.version ? ` (${camoufox.version})` : ""} at ${camoufox.path}`,
369
+ });
370
+ else if (needed)
371
+ out.push({ area, level: "fail", text: `Camoufox not found, and the camoufox engine needs it for ${who}`, fix });
372
+ else
373
+ out.push({
374
+ area,
375
+ level: "info",
376
+ text: "Camoufox not found: only the camoufox engine (--engine camoufox) needs it, and turno never downloads it",
377
+ fix,
378
+ });
379
+ const pw = (opts.playwrightCore ?? findPlaywrightCore)(env);
380
+ const pwFix = playwrightCoreHint();
381
+ if (pw?.ok)
382
+ out.push({ area, level: "ok", text: `playwright-core ${pw.version} at ${pw.dir} (for Camoufox)` });
383
+ else if (pw)
384
+ out.push({
385
+ area,
386
+ level: needed ? "fail" : "warn",
387
+ text: `playwright-core ${pw.version} at ${pw.dir} is not the version patchright-core is built on, so Camoufox cannot run on it`,
388
+ fix: pwFix,
389
+ });
390
+ else if (needed)
391
+ out.push({
392
+ area,
393
+ level: "fail",
394
+ text: `playwright-core not found, and Camoufox runs on stock Playwright (patchright-core drives Chromium only): needed for ${who}`,
395
+ fix: pwFix,
396
+ });
397
+ else if (camoufox)
398
+ out.push({
399
+ area,
400
+ level: "info",
401
+ text: "playwright-core not found: the camoufox engine runs on stock Playwright, since patchright-core drives Chromium only",
402
+ fix: pwFix,
403
+ });
404
+ return out;
405
+ }
406
+ /**
407
+ * The opt-in network settings of an identity: where its traffic goes, and whether the secret
408
+ * store holds the proxy credentials (it asks whether the item exists, never reads its value).
409
+ */
410
+ async function networkRows(id, env, opts) {
411
+ const settings = checkIdentitySettings(id, env).settings;
412
+ const out = [];
413
+ const area = `identity ${id}`;
414
+ if (settings?.userAgent === "coherent")
415
+ out.push({
416
+ area,
417
+ level: "info",
418
+ text: "userAgent coherent: the installed Chrome's own user agent and client hints, with the identity's languages and time zone, checked at every launch",
419
+ });
420
+ const proxy = settings?.proxy;
421
+ if (!proxy)
422
+ return out;
423
+ out.push({
424
+ area,
425
+ level: "info",
426
+ text: `proxy ${proxy.server}: the proxy's operator sees where this identity goes (and the content of plain http:// pages), and sites see the proxy's address`,
427
+ });
428
+ const refs = [proxy.username, proxy.password].filter((r) => r?.startsWith("keychain:") === true);
429
+ if (!refs.length)
430
+ return out;
431
+ const store = opts.secrets ?? secretStore(env);
432
+ if (!store) {
433
+ out.push({
434
+ area,
435
+ level: "fail",
436
+ text: "the proxy credentials are in the secret store, and this machine has none",
437
+ manual: "install libsecret (secret-tool), or use a proxy without a password",
438
+ });
439
+ return out;
440
+ }
441
+ for (const ref of refs) {
442
+ const item = ref.slice("keychain:".length);
443
+ const has = await store.has(item).catch(() => false);
444
+ if (has)
445
+ out.push({ area, level: "ok", text: `proxy credentials: ${store.label} item "${item}" is there` });
446
+ else
447
+ out.push({
448
+ area,
449
+ level: "fail",
450
+ text: `proxy credentials: ${store.label} has no item "${item}", so the browser does not start`,
451
+ fix: `turno secret set ${item}`,
452
+ });
453
+ }
454
+ return out;
455
+ }
456
+ /** Every identity id, including profile dirs with an identity.json only. */
457
+ function identityIds(env) {
458
+ try {
459
+ return readdirSync(paths(env).identitiesDir, { withFileTypes: true })
460
+ .filter((d) => d.isDirectory() && isValidIdentityId(d.name))
461
+ .map((d) => d.name)
462
+ .sort();
463
+ }
464
+ catch {
465
+ return [];
466
+ }
467
+ }
468
+ async function collect(opts, env, platform, now) {
469
+ const checks = [];
470
+ const chrome = (opts.chrome ?? findChrome)(env, platform);
471
+ if (chrome)
472
+ checks.push({
473
+ area: "chrome",
474
+ level: "ok",
475
+ text: `Google Chrome${chrome.version ? ` ${chrome.version}` : ""} at ${chrome.path}`,
476
+ });
477
+ else {
478
+ checks.push({
479
+ area: "chrome",
480
+ level: "fail",
481
+ text: "Google Chrome not found",
482
+ manual: "install Google Chrome (https://www.google.com/chrome/): turno-browser drives the installed Chrome, not a bundled browser",
483
+ });
484
+ }
485
+ if (opts.launch === false)
486
+ checks.push({ area: "chrome", level: "info", text: "smoke launch skipped (--no-launch)" });
487
+ else {
488
+ try {
489
+ const ms = await (opts.smoke ?? smokeLaunch)(env);
490
+ checks.push({
491
+ area: "chrome",
492
+ level: "ok",
493
+ text: `smoke launch: Chrome started and closed in ${(ms / 1000).toFixed(1)}s on a temporary profile`,
494
+ });
495
+ }
496
+ catch (err) {
497
+ checks.push({
498
+ area: "chrome",
499
+ level: "fail",
500
+ text: `smoke launch failed: ${firstLine(err)}`,
501
+ manual: "open Chrome by hand once; on Linux install its system libraries",
502
+ });
503
+ }
504
+ }
505
+ checks.push(...systemChecks(env, platform));
506
+ const ids = identityIds(env);
507
+ checks.push(...engineChecks(opts, env, ids));
508
+ if (!ids.length)
509
+ checks.push({
510
+ area: "identities",
511
+ level: "info",
512
+ text: "no browser identities yet",
513
+ fix: "turno identity add browser:<id>",
514
+ });
515
+ for (const id of ids)
516
+ checks.push(...identityChecks(id, env, now, opts.servers), ...(await networkRows(id, env, opts)));
517
+ return checks;
518
+ }
519
+ /** Repairs what is safe: stale runtime locks, a Chrome left running with no server, a stray Lightpanda. */
520
+ async function repair(env, opts) {
521
+ const done = [];
522
+ for (const pid of strayLightpandas((opts.procTable ?? readProcTable)())) {
523
+ signalProcess(pid, "SIGTERM");
524
+ done.push(`stopped Lightpanda pid ${pid}, left running by a server that is gone`);
525
+ }
526
+ for (const id of identityIds(env)) {
527
+ const lock = readRuntimeLock(id, env);
528
+ if (lock && !runtimeLockAlive(lock)) {
529
+ rmSync(runtimeLockPath(id, env), { force: true });
530
+ done.push(`${id}: removed the stale runtime lock of pid ${lock.nodePid}`);
531
+ }
532
+ const swept = await sweepOrphan(identityDir(id, env));
533
+ if (swept.action === "exited" || swept.action === "killed")
534
+ done.push(`${id}: closed Chrome pid ${swept.pid}, left running with no server`);
535
+ else if (swept.action === "survived")
536
+ done.push(`${id}: Chrome pid ${swept.pid} did not stop`);
537
+ }
538
+ return done;
539
+ }
540
+ export async function runDoctor(opts = {}) {
541
+ const env = opts.env ?? process.env;
542
+ const platform = opts.platform ?? process.platform;
543
+ const now = opts.now ?? new Date();
544
+ let checks = await collect(opts, env, platform, now);
545
+ const fixed = [];
546
+ if (opts.fix && checks.some((c) => c.auto && (c.level === "warn" || c.level === "fail"))) {
547
+ fixed.push(...(await repair(env, opts)));
548
+ checks = await collect({ ...opts, launch: false }, env, platform, now).then((again) => {
549
+ // Keep the smoke launch result of the first pass: it does not change with a repair.
550
+ const smoke = checks.find((c) => c.area === "chrome" && /^smoke launch/.test(c.text));
551
+ return smoke ? again.map((c) => (c.area === "chrome" && /^smoke launch/.test(c.text) ? smoke : c)) : again;
552
+ });
553
+ }
554
+ return { checks, fixed };
555
+ }
556
+ //# sourceMappingURL=doctor.js.map
@@ -0,0 +1,27 @@
1
+ import type { Engine } from "./engine.js";
2
+ export type AttachTarget = {
3
+ kind: "auto";
4
+ } | {
5
+ kind: "dir";
6
+ dir: string;
7
+ } | {
8
+ kind: "endpoint";
9
+ url: string;
10
+ };
11
+ /** The target an `attach` value names, or a message saying what is wrong with it. */
12
+ export declare function parseAttachTarget(value: string): AttachTarget | {
13
+ error: string;
14
+ };
15
+ /** The user data dir of the installed Chrome's default profile, where Chrome writes `DevToolsActivePort`. */
16
+ export declare function defaultChromeUserDataDir(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
17
+ /** `DevToolsActivePort`: the port on the first line, the browser's WebSocket path on the second. */
18
+ export declare function parseDevToolsActivePort(text: string): {
19
+ port: number;
20
+ path: string;
21
+ } | undefined;
22
+ /**
23
+ * Where to connect for a target, without connecting: for `auto` and a dir, the endpoint in its
24
+ * `DevToolsActivePort`. Throws with what the user should do when Chrome does not listen.
25
+ */
26
+ export declare function resolveAttachEndpoint(target: AttachTarget, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
27
+ export declare function createAttachEngine(target: AttachTarget): Engine;