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/login.js CHANGED
@@ -1,40 +1,79 @@
1
1
  import { mkdirSync } from "node:fs";
2
- import { IdentityError, identityDir, isInUse } from "./identities.js";
2
+ import { clearHealth } from "./health.js";
3
+ import { IdentityError, identityDir, inUseBy, isInUse } from "./identities.js";
4
+ import { readLockPid } from "./lifecycle.js";
5
+ import { CHROME_PROXY_ARGS, resolveProxy } from "./network.js";
6
+ import { acquireRuntimeLock } from "./runtime-lock.js";
7
+ import { chromeEnv, keychainArgs, launchSettings, readIdentitySettings, systemTimezone } from "./settings.js";
3
8
  /**
4
- * Opens the identity's persistent Chrome headed, with the same stealth settings as the MCP
5
- * server (Chrome channel, no fixed viewport), and resolves when the user closes the last
6
- * window or quits Chrome. Used once per site so the user signs in by hand.
9
+ * Opens the identity's persistent Chrome headed, with the same launch settings as the MCP
10
+ * server (Chrome channel, no fixed viewport, the identity's languages and time zone), and
11
+ * resolves when the user closes the last window or quits Chrome. Used once per site so the user
12
+ * signs in by hand. It holds the identity's runtime lock while the window is open, and clears
13
+ * the last session health result, so the next launch checks the sign-in again.
14
+ *
15
+ * With identity.json `proxy`, the sign-in goes through the same proxy as the agent's sessions,
16
+ * so the site sees one network for both. A Camoufox identity is refused: it keeps its own profile.
7
17
  */
8
18
  export async function loginIdentity(id, options = {}) {
9
19
  const env = options.env ?? process.env;
10
20
  const dir = identityDir(id, env);
21
+ const holder = inUseBy(id, env);
22
+ if (holder)
23
+ throw new IdentityError(holder);
11
24
  if (isInUse(id, env))
12
25
  throw new IdentityError(`identity "${id}" is in use (an MCP session holds its Chrome); close it first`);
13
- mkdirSync(dir, { recursive: true, mode: 0o700 });
14
- const { chromium } = await import("patchright-core");
15
- const ctx = await chromium.launchPersistentContext(dir, { channel: "chrome", headless: false, viewport: null });
16
- const closed = new Promise((resolve) => ctx.on("close", () => resolve()));
17
- // On macOS Chrome keeps running with no windows, so treat "last page closed" as done.
18
- const watch = (page) => page.on("close", () => {
19
- setTimeout(() => {
20
- if (ctx.pages().length === 0)
21
- void ctx.close().catch(() => undefined);
22
- }, 250);
23
- });
24
- ctx.pages().forEach(watch);
25
- ctx.on("page", watch);
26
- const stop = () => void ctx.close().catch(() => undefined);
27
- process.once("SIGINT", stop);
28
- process.once("SIGTERM", stop);
26
+ const settings = readIdentitySettings(id, env);
27
+ if (settings?.engine === "camoufox" && settings.attach === undefined)
28
+ throw new IdentityError(`identity "${id}" runs on Camoufox, which keeps its own profile, and \`turno browser login\` opens the Chrome profile: sign in from an agent session (browser_login with the vault), or use --engine chrome`);
29
+ // Read before the lock, so a missing secret leaves nothing to undo; the value goes only to Chrome.
30
+ const proxy = settings?.proxy ? await resolveProxy(settings.proxy, env, () => { }) : undefined;
31
+ const held = acquireRuntimeLock(id, env, { holder: "login" });
29
32
  try {
30
- const page = ctx.pages()[0] ?? (await ctx.newPage());
31
- if (options.url)
32
- await page.goto(options.url).catch(() => undefined);
33
- await closed;
33
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
34
+ const applied = launchSettings(settings, [], systemTimezone());
35
+ const { chromium } = await import("patchright-core");
36
+ const ctx = await chromium.launchPersistentContext(dir, {
37
+ channel: "chrome",
38
+ headless: false,
39
+ viewport: null,
40
+ ...(applied.args.length || proxy ? { args: [...applied.args, ...(proxy ? CHROME_PROXY_ARGS : [])] } : {}),
41
+ ...(proxy ? { proxy } : {}),
42
+ ...(applied.timezoneId ? { timezoneId: applied.timezoneId } : {}),
43
+ ...keychainArgs(settings),
44
+ // Chrome gets the caller's environment (HOME, XDG dirs), not this process's.
45
+ env: chromeEnv(env),
46
+ });
47
+ const pid = readLockPid(dir);
48
+ if (pid !== undefined)
49
+ held.update({ chromePid: pid, pgid: pid });
50
+ const closed = new Promise((resolve) => ctx.on("close", () => resolve()));
51
+ // On macOS Chrome keeps running with no windows, so treat "last page closed" as done.
52
+ const watch = (page) => page.on("close", () => {
53
+ setTimeout(() => {
54
+ if (ctx.pages().length === 0)
55
+ void ctx.close().catch(() => undefined);
56
+ }, 250);
57
+ });
58
+ ctx.pages().forEach(watch);
59
+ ctx.on("page", watch);
60
+ const stop = () => void ctx.close().catch(() => undefined);
61
+ process.once("SIGINT", stop);
62
+ process.once("SIGTERM", stop);
63
+ try {
64
+ const page = ctx.pages()[0] ?? (await ctx.newPage());
65
+ if (options.url)
66
+ await page.goto(options.url).catch(() => undefined);
67
+ await closed;
68
+ clearHealth(id, env);
69
+ }
70
+ finally {
71
+ process.off("SIGINT", stop);
72
+ process.off("SIGTERM", stop);
73
+ }
34
74
  }
35
75
  finally {
36
- process.off("SIGINT", stop);
37
- process.off("SIGTERM", stop);
76
+ held.release();
38
77
  }
39
78
  }
40
79
  //# sourceMappingURL=login.js.map
@@ -0,0 +1,74 @@
1
+ import type { BrowserContext, Page } from "patchright-core";
2
+ import { type ExpectedIdentity, type ResolvedProxy } from "./network.js";
3
+ import { type IdentitySettings } from "./settings.js";
4
+ import type { McpConfig } from "./upstream.js";
5
+ /**
6
+ * How the chrome engine applies identity.json `proxy` and `userAgent` (`network.ts`). Both are
7
+ * settled before Chrome starts: a missing secret or an unknown Chrome version stops the launch
8
+ * with nothing to undo.
9
+ *
10
+ * `userAgent: "coherent"` changes nothing in a headed Chrome, which already presents itself
11
+ * as it is; the launch check still runs. A headless Chrome says HeadlessChrome, so it gets two
12
+ * things, measured with Chrome 157:
13
+ *
14
+ * - the `--user-agent` switch with the headed string for the same version and OS, which every
15
+ * request, popup and worker carries from the start; on its own it blanks the client hints'
16
+ * high entropy values (full version list, architecture, platform version), which a real
17
+ * Chrome never does;
18
+ * - so each page also gets those values back through `Emulation.setUserAgentOverride`, with
19
+ * the metadata this same Chrome reports when nothing overrides it, read once per Chrome
20
+ * version by a short headless launch on a throwaway profile and kept in the state folder.
21
+ * Dedicated workers take them from their page.
22
+ *
23
+ * A tab a tool opens gets them before its first navigation. A popup a page opens gets them as
24
+ * soon as it exists, which can be after its first document loaded: that document reads blank
25
+ * high entropy values (the user agent string is right there too).
26
+ */
27
+ export interface ChromeNetwork {
28
+ /** Chrome switches to add. */
29
+ args: string[];
30
+ /** Playwright's `proxy` launch option, credentials included. */
31
+ proxy?: ResolvedProxy;
32
+ /** With `userAgent`, what the launch check expects the page to read. */
33
+ verify?: ExpectedIdentity;
34
+ /** With `userAgent` in a headless Chrome: the string and metadata each page gets. */
35
+ pin?: UserAgentPin;
36
+ }
37
+ /** The client hints metadata of `Emulation.setUserAgentOverride`, as this Chrome reports it. */
38
+ interface UserAgentMetadata {
39
+ brands: {
40
+ brand: string;
41
+ version: string;
42
+ }[];
43
+ fullVersionList: {
44
+ brand: string;
45
+ version: string;
46
+ }[];
47
+ platform: string;
48
+ platformVersion: string;
49
+ architecture: string;
50
+ model: string;
51
+ mobile: boolean;
52
+ bitness: string;
53
+ wow64: boolean;
54
+ }
55
+ export interface UserAgentPin {
56
+ userAgent: string;
57
+ metadata: UserAgentMetadata;
58
+ }
59
+ export declare function chromeNetwork(settings: IdentitySettings, config: McpConfig, env: NodeJS.ProcessEnv, secret: (value: string, label: string) => void): Promise<ChromeNetwork>;
60
+ /** Gives every page of the context the pinned user agent and metadata; `ready` resolves once a page has them. */
61
+ export declare function pinUserAgent(context: BrowserContext, pin: UserAgentPin): {
62
+ ready(page: Page): Promise<void>;
63
+ };
64
+ /**
65
+ * The launch check of `userAgent: "coherent"`: loads a blank page of its own on an https origin
66
+ * (client hints exist only in a secure context), answered by a route so no request leaves the
67
+ * machine, reads what the page sees and what the request carried, and refuses the browser when
68
+ * anything contradicts the rest, or the user agent names another version than the Chrome that
69
+ * runs. A headed Chrome shows that tab for a moment. The caller closes the browser on a throw.
70
+ */
71
+ export declare function verifyCoherence(context: BrowserContext, version: string, expected: ExpectedIdentity, pinned?: {
72
+ ready(page: Page): Promise<void>;
73
+ }): Promise<void>;
74
+ export {};
@@ -0,0 +1,178 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE, browserPaths as paths } from "turno-core/paths";
5
+ import { findChrome } from "./doctor.js";
6
+ import { CHROME_PROXY_ARGS, OBSERVE_SCRIPT, coherenceProblems, majorOf, reducedUserAgent, resolveProxy, } from "./network.js";
7
+ import { acceptLanguages } from "./settings.js";
8
+ /** Where the launch check and the metadata reading load their page: answered by a route, so nothing reaches the network. */
9
+ const CHECK_URL = "https://turno-check.invalid/";
10
+ const READ_METADATA = `(async () => {
11
+ const d = navigator.userAgentData;
12
+ const h = await d.getHighEntropyValues(["fullVersionList", "platformVersion", "architecture", "model", "bitness", "wow64"]);
13
+ return { brands: d.brands.map((b) => ({ brand: b.brand, version: b.version })), fullVersionList: h.fullVersionList.map((b) => ({ brand: b.brand, version: b.version })),
14
+ platform: d.platform, platformVersion: h.platformVersion, architecture: h.architecture, model: h.model || "", mobile: d.mobile, bitness: h.bitness, wow64: !!h.wow64 };
15
+ })()`;
16
+ /**
17
+ * The client hints metadata this Chrome reports with nothing overriding it: read by a short
18
+ * headless launch (no switch, throwaway profile, a routed page) and kept per Chrome version.
19
+ */
20
+ async function realMetadata(config, env, version) {
21
+ const file = join(paths(env).state, "browser", "chrome-ua", `${version.replace(/[^\w.-]/g, "_")}-${process.platform}-${process.arch}.json`);
22
+ try {
23
+ const cached = JSON.parse(readFileSync(file, "utf8"));
24
+ if (cached.fullVersionList?.length && cached.architecture)
25
+ return cached;
26
+ }
27
+ catch {
28
+ /* not read yet */
29
+ }
30
+ const lo = config.browser.launchOptions;
31
+ const { chromium } = await import("patchright-core");
32
+ const browser = await chromium.launch({
33
+ ...(typeof lo.executablePath === "string"
34
+ ? { executablePath: lo.executablePath }
35
+ : { channel: lo.channel ?? "chrome" }),
36
+ headless: true,
37
+ timeout: 20_000,
38
+ });
39
+ let metadata;
40
+ try {
41
+ const page = await browser.newPage();
42
+ await page.route(CHECK_URL, (route) => route.fulfill({ status: 200, contentType: "text/html", body: "<title>turno</title>" }));
43
+ await page.goto(CHECK_URL, { timeout: 15_000 });
44
+ metadata = (await page.evaluate(READ_METADATA));
45
+ }
46
+ finally {
47
+ await browser.close().catch(() => { });
48
+ }
49
+ if (!metadata.fullVersionList.length || !metadata.architecture)
50
+ throw new Error('userAgent "coherent": this Chrome reports no client hints metadata, so turno cannot present it coherently headless');
51
+ mkdirSync(dirname(file), { recursive: true, mode: PRIVATE_DIR_MODE });
52
+ writeFileSync(file, `${JSON.stringify(metadata, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
53
+ return metadata;
54
+ }
55
+ const hasArg = (args, flag) => args.some((a) => a === flag || a.startsWith(`${flag}=`));
56
+ /** The installed Chrome's version, for the user agent string a headless Chrome needs. */
57
+ function chromeVersion(config, env) {
58
+ const exe = config.browser.launchOptions.executablePath;
59
+ if (typeof exe === "string") {
60
+ try {
61
+ return /(\d+\.\d+\.\d+\.\d+)/.exec(execFileSync(exe, ["--version"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }))?.[1];
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ }
67
+ const channel = config.browser.launchOptions.channel ?? "chrome";
68
+ return channel === "chrome" ? findChrome(env)?.version : undefined;
69
+ }
70
+ export async function chromeNetwork(settings, config, env, secret) {
71
+ const out = { args: [] };
72
+ const userArgs = config.browser.launchOptions.args ?? [];
73
+ if (settings.proxy) {
74
+ if (config.browser.launchOptions.proxy !== undefined || hasArg(userArgs, "--proxy-server"))
75
+ throw new Error("identity.json proxy and a proxy of the server's own (--proxy-server, or the config's launchOptions.proxy) are both set: keep one");
76
+ out.proxy = await resolveProxy(settings.proxy, env, secret);
77
+ out.args.push(...CHROME_PROXY_ARGS.filter((a) => !hasArg(userArgs, a.split("=")[0])));
78
+ }
79
+ if (settings.userAgent === "coherent") {
80
+ if (config.browser.contextOptions?.userAgent !== undefined || hasArg(userArgs, "--user-agent"))
81
+ throw new Error('identity.json userAgent "coherent" and a user agent of the server\'s own (--user-agent, --device, or the config) are both set: keep one');
82
+ // Headed Chrome already sends its own reduced user agent; a headless one says
83
+ // HeadlessChrome, so it gets the headed string for the same version.
84
+ if (config.browser.launchOptions.headless) {
85
+ const version = chromeVersion(config, env);
86
+ const major = majorOf(version);
87
+ if (version === undefined || major === undefined)
88
+ throw new Error('userAgent "coherent" needs the installed Chrome\'s version for a headless browser, and turno could not read it: it supports Google Chrome (the chrome channel) or a Chrome given with an executable path');
89
+ const userAgent = reducedUserAgent(major);
90
+ out.args.push(`--user-agent=${userAgent}`);
91
+ out.pin = { userAgent, metadata: await realMetadata(config, env, version) };
92
+ }
93
+ const languages = acceptLanguages(settings);
94
+ const given = out.pin?.metadata;
95
+ out.verify = {
96
+ ...(languages ? { languages } : {}),
97
+ ...(settings.timezone ? { timezone: settings.timezone } : {}),
98
+ ...(given
99
+ ? {
100
+ high: {
101
+ fullVersionList: given.fullVersionList,
102
+ architecture: given.architecture,
103
+ platformVersion: given.platformVersion,
104
+ },
105
+ }
106
+ : {}),
107
+ };
108
+ }
109
+ return out;
110
+ }
111
+ /** Gives every page of the context the pinned user agent and metadata; `ready` resolves once a page has them. */
112
+ export function pinUserAgent(context, pin) {
113
+ const pending = new WeakMap();
114
+ const apply = (page) => {
115
+ // The session stays attached: Chrome drops a DevTools client's overrides when it detaches.
116
+ // A page that closes first rejects too; only `ready` (the launch check, a tool's new tab)
117
+ // reports it, so a page that did not get the values fails instead of loading without them.
118
+ const done = context
119
+ .newCDPSession(page)
120
+ .then((session) => session.send("Emulation.setUserAgentOverride", { userAgent: pin.userAgent, userAgentMetadata: pin.metadata }))
121
+ .then(() => undefined)
122
+ .catch((error) => {
123
+ throw new Error(`userAgent "coherent": this page did not take the user agent metadata: ${error.message}`);
124
+ });
125
+ done.catch(() => { });
126
+ pending.set(page, done);
127
+ };
128
+ for (const page of context.pages())
129
+ apply(page);
130
+ context.on("page", apply);
131
+ const ready = (page) => pending.get(page) ?? Promise.resolve();
132
+ // A tab a tool opens (browser_tabs) navigates right after newPage resolves: resolve it only
133
+ // once the page has the values, so its first request already carries them.
134
+ const newPage = context.newPage.bind(context);
135
+ context.newPage = async () => {
136
+ const page = await newPage();
137
+ await ready(page);
138
+ return page;
139
+ };
140
+ return { ready };
141
+ }
142
+ /**
143
+ * The launch check of `userAgent: "coherent"`: loads a blank page of its own on an https origin
144
+ * (client hints exist only in a secure context), answered by a route so no request leaves the
145
+ * machine, reads what the page sees and what the request carried, and refuses the browser when
146
+ * anything contradicts the rest, or the user agent names another version than the Chrome that
147
+ * runs. A headed Chrome shows that tab for a moment. The caller closes the browser on a throw.
148
+ */
149
+ export async function verifyCoherence(context, version, expected, pinned) {
150
+ const page = await context.newPage();
151
+ await pinned?.ready(page);
152
+ let observed;
153
+ let sent = {};
154
+ try {
155
+ await page.route(CHECK_URL, async (route) => {
156
+ sent = await route.request().allHeaders();
157
+ await route.fulfill({ status: 200, contentType: "text/html", body: "<title>turno</title>" });
158
+ });
159
+ await page.goto(CHECK_URL, { timeout: 15_000 });
160
+ observed = (await page.evaluate(`(${OBSERVE_SCRIPT})()`));
161
+ }
162
+ finally {
163
+ await page.close().catch(() => { });
164
+ }
165
+ const problems = coherenceProblems(observed, expected);
166
+ const major = majorOf(version);
167
+ const uaMajor = /Chrome\/(\d+)\./.exec(observed.userAgent)?.[1];
168
+ if (major !== undefined && uaMajor !== undefined && Number(uaMajor) !== major)
169
+ problems.push(`the user agent says Chrome ${uaMajor}, but Chrome ${major} runs`);
170
+ if (sent["user-agent"] !== undefined && sent["user-agent"] !== observed.userAgent)
171
+ problems.push("the User-Agent header differs from navigator.userAgent");
172
+ const hinted = sent["sec-ch-ua-platform"];
173
+ if (hinted !== undefined && observed.uaData && hinted !== `"${observed.uaData.platform}"`)
174
+ problems.push(`the Sec-CH-UA-Platform header is ${hinted}, but the page reads ${observed.uaData.platform}`);
175
+ if (problems.length)
176
+ throw new Error(`userAgent "coherent": this Chrome would not present one coherent identity, so turno did not use it: ${problems.join("; ")}`);
177
+ }
178
+ //# sourceMappingURL=network-chrome.js.map
@@ -0,0 +1,125 @@
1
+ import { type SecretStore } from "turno-core/secrets";
2
+ /**
3
+ * Opt-in network and user agent settings of an identity (identity.json format 11), both off by
4
+ * default. They are "not recommended": a real Chrome on the user's own connection is already
5
+ * the most coherent browser a site can see, and these settings can only keep it coherent or
6
+ * break it. The docs say what each one costs.
7
+ *
8
+ * `userAgent: "coherent"` presents the identity as the installed Chrome, as one set, verified
9
+ * at every launch:
10
+ *
11
+ * - the user agent string is Chrome's own reduced one for this OS and the installed major
12
+ * version, so a headless Chrome no longer says `HeadlessChrome` (headed, it is unchanged);
13
+ * - the client hints (`Sec-CH-UA*`, `navigator.userAgentData`: brands, full version list,
14
+ * platform, platform version, architecture) and `navigator.platform` stay Chrome's real ones;
15
+ * - the languages and the time zone are the identity's (`languages`/`locale`, `timezone`) or,
16
+ * without them, the system's.
17
+ *
18
+ * The platform and the Chrome version are never configurable. Measured with Chrome 157: no
19
+ * DevTools override reaches `navigator.platform` in a dedicated worker, and a popup's first
20
+ * request carries the real `Sec-CH-UA-Platform` and platform version, so another platform would
21
+ * be a partial override however it is applied (and WebGL, fonts and TLS would still say the real
22
+ * one). A typed user agent string is refused for the same reason.
23
+ *
24
+ * `proxy` sends the identity's traffic through a proxy. The credentials are never written in
25
+ * identity.json: `password` (and `username`, when it is one) is a `keychain:<item>` reference
26
+ * read from the secret store at launch, and both values join the redactor, so no tool result
27
+ * shows them. WebRTC is kept on the proxy (`disable_non_proxied_udp`), so it does not show the
28
+ * direct address.
29
+ */
30
+ /** The values of `userAgent`. */
31
+ declare const USER_AGENT_MODES: readonly ["coherent"];
32
+ export type UserAgentMode = (typeof USER_AGENT_MODES)[number];
33
+ /** identity.json `proxy`. */
34
+ export interface ProxySettings {
35
+ /** `http://`, `https://`, `socks4://` or `socks5://` with a host and an optional port. */
36
+ server: string;
37
+ /** A user name, or a `keychain:<item>` reference to one. */
38
+ username?: string;
39
+ /** Always a `keychain:<item>` reference. */
40
+ password?: string;
41
+ }
42
+ /** Problems with the format 11 keys alone (combinations with the engine keys: `networkEngineClash`). */
43
+ export declare function networkProblems(v: Record<string, unknown>, out: string[]): void;
44
+ /**
45
+ * Why an engine cannot apply these settings. Attach mode drives the user's own Chrome, whose
46
+ * user agent and network turno does not change; read mode is Lightpanda, which presents its
47
+ * own user agent and was not checked with a proxy; Camoufox is Firefox, which sends no client
48
+ * hints at all, so `userAgent` describes nothing there (a proxy works).
49
+ */
50
+ export declare function networkEngineClash(engine: string, settings: {
51
+ userAgent?: unknown;
52
+ proxy?: unknown;
53
+ }): string | undefined;
54
+ /** A proxy ready for Playwright's `proxy` launch option. */
55
+ export interface ResolvedProxy {
56
+ server: string;
57
+ username?: string;
58
+ password?: string;
59
+ }
60
+ /**
61
+ * Reads the proxy's credentials from the secret store. Every value read is handed to `secret`
62
+ * (the redactor) before anything else sees it, with the `Proxy-Authorization` form Chrome sends
63
+ * for a plain http:// request through the proxy. Throws without the value when an item is
64
+ * missing or the store cannot be read.
65
+ */
66
+ export declare function resolveProxy(proxy: ProxySettings, env: NodeJS.ProcessEnv, secret: (value: string, label: string) => void, store?: SecretStore | undefined): Promise<ResolvedProxy>;
67
+ /**
68
+ * Chrome switches that go with a proxy: WebRTC uses the proxy or no UDP at all, so a page
69
+ * cannot read the direct address through a peer connection.
70
+ */
71
+ export declare const CHROME_PROXY_ARGS: readonly string[];
72
+ /** The same for Firefox (Camoufox): ICE candidates only through the proxy. */
73
+ export declare const FIREFOX_PROXY_PREFS: Readonly<Record<string, boolean>>;
74
+ /**
75
+ * Chrome's own reduced user agent string for this OS and major version, as a headed Chrome
76
+ * sends it (the minor, build and patch are always 0 there).
77
+ */
78
+ export declare function reducedUserAgent(major: number, platform?: NodeJS.Platform): string;
79
+ /** What a page reads, for the launch check. */
80
+ export interface ObservedIdentity {
81
+ userAgent: string;
82
+ platform: string;
83
+ languages: string[];
84
+ timezone: string;
85
+ /** `Intl.DateTimeFormat().resolvedOptions().locale`. */
86
+ intlLocale: string;
87
+ uaData?: {
88
+ brands: {
89
+ brand: string;
90
+ version: string;
91
+ }[];
92
+ platform: string;
93
+ mobile: boolean;
94
+ /** The high entropy values (`getHighEntropyValues`), which a user agent override can blank. */
95
+ high?: HighEntropyValues;
96
+ } | null;
97
+ }
98
+ /** The client hints high entropy values the launch check reads. */
99
+ interface HighEntropyValues {
100
+ fullVersionList: {
101
+ brand: string;
102
+ version: string;
103
+ }[];
104
+ architecture: string;
105
+ platformVersion: string;
106
+ }
107
+ /**
108
+ * What the identity should present: `languages` and `timezone` are what was asked for, else
109
+ * unchecked; `high` is the metadata a headless Chrome was given, which every page must read back.
110
+ */
111
+ export interface ExpectedIdentity {
112
+ languages?: string[];
113
+ timezone?: string;
114
+ high?: HighEntropyValues;
115
+ }
116
+ /**
117
+ * Every contradiction between what a page reads and what the identity presents; empty when
118
+ * the set is coherent. Pure, so the bench and the unit tests use it too.
119
+ */
120
+ export declare function coherenceProblems(o: ObservedIdentity, expected?: ExpectedIdentity): string[];
121
+ /** Runs in a page: what `coherenceProblems` checks. */
122
+ export declare const OBSERVE_SCRIPT = "async () => {\n const d = navigator.userAgentData;\n const high = d ? await d.getHighEntropyValues([\"fullVersionList\", \"architecture\", \"platformVersion\"]) : null;\n return {\n userAgent: navigator.userAgent,\n platform: navigator.platform,\n languages: Array.from(navigator.languages || []),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n intlLocale: Intl.DateTimeFormat().resolvedOptions().locale,\n uaData: d\n ? {\n brands: d.brands.map((b) => ({ brand: b.brand, version: b.version })),\n platform: d.platform,\n mobile: d.mobile,\n high: {\n fullVersionList: (high.fullVersionList || []).map((b) => ({ brand: b.brand, version: b.version })),\n architecture: high.architecture || \"\",\n platformVersion: high.platformVersion || \"\",\n },\n }\n : null,\n };\n}";
123
+ /** The installed Chrome's major version from a version string like "157.0.8103.79". */
124
+ export declare function majorOf(version: string | undefined): number | undefined;
125
+ export {};