ant0-browser 0.0.0-stage → 0.2.0-beta.2

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 (163) hide show
  1. package/LICENSE +35 -0
  2. package/README.md +208 -2
  3. package/dist/canvas.d.ts +55 -0
  4. package/dist/canvas.d.ts.map +1 -0
  5. package/dist/canvas.js +82 -0
  6. package/dist/canvas.js.map +1 -0
  7. package/dist/chromium-version.d.ts +22 -0
  8. package/dist/chromium-version.d.ts.map +1 -0
  9. package/dist/chromium-version.js +22 -0
  10. package/dist/chromium-version.js.map +1 -0
  11. package/dist/claim-hints.d.ts +36 -0
  12. package/dist/claim-hints.d.ts.map +1 -0
  13. package/dist/claim-hints.js +9 -0
  14. package/dist/claim-hints.js.map +1 -0
  15. package/dist/cleanup.d.ts +35 -0
  16. package/dist/cleanup.d.ts.map +1 -0
  17. package/dist/cleanup.js +106 -0
  18. package/dist/cleanup.js.map +1 -0
  19. package/dist/content.d.ts +11 -0
  20. package/dist/content.d.ts.map +1 -0
  21. package/dist/content.js +52 -0
  22. package/dist/content.js.map +1 -0
  23. package/dist/download.d.ts +24 -0
  24. package/dist/download.d.ts.map +1 -0
  25. package/dist/download.js +227 -0
  26. package/dist/download.js.map +1 -0
  27. package/dist/errors.d.ts +49 -0
  28. package/dist/errors.d.ts.map +1 -0
  29. package/dist/errors.js +53 -0
  30. package/dist/errors.js.map +1 -0
  31. package/dist/fingerprint.d.ts +218 -0
  32. package/dist/fingerprint.d.ts.map +1 -0
  33. package/dist/fingerprint.js +475 -0
  34. package/dist/fingerprint.js.map +1 -0
  35. package/dist/fontpack.d.ts +13 -0
  36. package/dist/fontpack.d.ts.map +1 -0
  37. package/dist/fontpack.js +150 -0
  38. package/dist/fontpack.js.map +1 -0
  39. package/dist/fonts.d.ts +15 -0
  40. package/dist/fonts.d.ts.map +1 -0
  41. package/dist/fonts.js +86 -0
  42. package/dist/fonts.js.map +1 -0
  43. package/dist/geoip.d.ts +45 -0
  44. package/dist/geoip.d.ts.map +1 -0
  45. package/dist/geoip.js +290 -0
  46. package/dist/geoip.js.map +1 -0
  47. package/dist/geometry.d.ts +32 -0
  48. package/dist/geometry.d.ts.map +1 -0
  49. package/dist/geometry.js +85 -0
  50. package/dist/geometry.js.map +1 -0
  51. package/dist/humanize.d.ts +20 -0
  52. package/dist/humanize.d.ts.map +1 -0
  53. package/dist/humanize.js +921 -0
  54. package/dist/humanize.js.map +1 -0
  55. package/dist/identity-persistence.d.ts +88 -0
  56. package/dist/identity-persistence.d.ts.map +1 -0
  57. package/dist/identity-persistence.js +381 -0
  58. package/dist/identity-persistence.js.map +1 -0
  59. package/dist/identity.d.ts +81 -0
  60. package/dist/identity.d.ts.map +1 -0
  61. package/dist/identity.js +370 -0
  62. package/dist/identity.js.map +1 -0
  63. package/dist/index.d.ts +281 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +790 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/launch-ticket.d.ts +191 -0
  68. package/dist/launch-ticket.d.ts.map +1 -0
  69. package/dist/launch-ticket.js +549 -0
  70. package/dist/launch-ticket.js.map +1 -0
  71. package/dist/launchopts.d.ts +266 -0
  72. package/dist/launchopts.d.ts.map +1 -0
  73. package/dist/launchopts.js +623 -0
  74. package/dist/launchopts.js.map +1 -0
  75. package/dist/motion.d.ts +106 -0
  76. package/dist/motion.d.ts.map +1 -0
  77. package/dist/motion.js +311 -0
  78. package/dist/motion.js.map +1 -0
  79. package/dist/motionscore.d.ts +57 -0
  80. package/dist/motionscore.d.ts.map +1 -0
  81. package/dist/motionscore.js +215 -0
  82. package/dist/motionscore.js.map +1 -0
  83. package/dist/native/linux-x64/PRODUCT-LICENSE.txt +28 -0
  84. package/dist/native/linux-x64/ant0_runtime.node +0 -0
  85. package/dist/native/windows-x64/PRODUCT-LICENSE.txt +28 -0
  86. package/dist/native/windows-x64/ant0_runtime.node +0 -0
  87. package/dist/persona-migration.d.ts +54 -0
  88. package/dist/persona-migration.d.ts.map +1 -0
  89. package/dist/persona-migration.js +97 -0
  90. package/dist/persona-migration.js.map +1 -0
  91. package/dist/persona-profile-v2.d.ts +169 -0
  92. package/dist/persona-profile-v2.d.ts.map +1 -0
  93. package/dist/persona-profile-v2.js +454 -0
  94. package/dist/persona-profile-v2.js.map +1 -0
  95. package/dist/persona-profile-v4.d.ts +61 -0
  96. package/dist/persona-profile-v4.d.ts.map +1 -0
  97. package/dist/persona-profile-v4.js +79 -0
  98. package/dist/persona-profile-v4.js.map +1 -0
  99. package/dist/persona-rejected.d.ts +36 -0
  100. package/dist/persona-rejected.d.ts.map +1 -0
  101. package/dist/persona-rejected.js +40 -0
  102. package/dist/persona-rejected.js.map +1 -0
  103. package/dist/population-model.d.ts +45 -0
  104. package/dist/population-model.d.ts.map +1 -0
  105. package/dist/population-model.js +245 -0
  106. package/dist/population-model.js.map +1 -0
  107. package/dist/profile-file.d.ts +201 -0
  108. package/dist/profile-file.d.ts.map +1 -0
  109. package/dist/profile-file.js +736 -0
  110. package/dist/profile-file.js.map +1 -0
  111. package/dist/release-fetch.d.ts +74 -0
  112. package/dist/release-fetch.d.ts.map +1 -0
  113. package/dist/release-fetch.js +395 -0
  114. package/dist/release-fetch.js.map +1 -0
  115. package/dist/release.d.ts +16 -0
  116. package/dist/release.d.ts.map +1 -0
  117. package/dist/release.js +26 -0
  118. package/dist/release.js.map +1 -0
  119. package/dist/render.d.ts +38 -0
  120. package/dist/render.d.ts.map +1 -0
  121. package/dist/render.js +104 -0
  122. package/dist/render.js.map +1 -0
  123. package/dist/runtime-client.d.ts +47 -0
  124. package/dist/runtime-client.d.ts.map +1 -0
  125. package/dist/runtime-client.js +327 -0
  126. package/dist/runtime-client.js.map +1 -0
  127. package/dist/runtime-launch.d.ts +22 -0
  128. package/dist/runtime-launch.d.ts.map +1 -0
  129. package/dist/runtime-launch.js +92 -0
  130. package/dist/runtime-launch.js.map +1 -0
  131. package/dist/scale.d.ts +29 -0
  132. package/dist/scale.d.ts.map +1 -0
  133. package/dist/scale.js +105 -0
  134. package/dist/scale.js.map +1 -0
  135. package/dist/shaderdialect.d.ts +33 -0
  136. package/dist/shaderdialect.d.ts.map +1 -0
  137. package/dist/shaderdialect.js +47 -0
  138. package/dist/shaderdialect.js.map +1 -0
  139. package/dist/speech-coherence.d.ts +52 -0
  140. package/dist/speech-coherence.d.ts.map +1 -0
  141. package/dist/speech-coherence.js +254 -0
  142. package/dist/speech-coherence.js.map +1 -0
  143. package/dist/template-selection.d.ts +14 -0
  144. package/dist/template-selection.d.ts.map +1 -0
  145. package/dist/template-selection.js +66 -0
  146. package/dist/template-selection.js.map +1 -0
  147. package/dist/warnings.d.ts +50 -0
  148. package/dist/warnings.d.ts.map +1 -0
  149. package/dist/warnings.js +273 -0
  150. package/dist/warnings.js.map +1 -0
  151. package/dist/webgl-coherence.d.ts +30 -0
  152. package/dist/webgl-coherence.d.ts.map +1 -0
  153. package/dist/webgl-coherence.js +98 -0
  154. package/dist/webgl-coherence.js.map +1 -0
  155. package/dist/webgpu-override.d.ts +14 -0
  156. package/dist/webgpu-override.d.ts.map +1 -0
  157. package/dist/webgpu-override.js +82 -0
  158. package/dist/webgpu-override.js.map +1 -0
  159. package/dist/widevine.d.ts +44 -0
  160. package/dist/widevine.d.ts.map +1 -0
  161. package/dist/widevine.js +203 -0
  162. package/dist/widevine.js.map +1 -0
  163. package/package.json +56 -4
@@ -0,0 +1,623 @@
1
+ // Launch-time option helpers that are NOT fingerprint switches: unpacked-extension loading and
2
+ // proxy resolution. Pure (input -> switches / cleaned proxy) so they're unit-testable and mirror
3
+ // the Python SDK exactly.
4
+ /** A Playwright proxy descriptor. */
5
+ import { readFileSync } from "node:fs";
6
+ import { createRequire } from "node:module";
7
+ import { isIP } from "node:net";
8
+ import { dirname, join } from "node:path";
9
+ import { SdkInputError } from "./errors.js";
10
+ /** Privacy Sandbox + intrusive web APIs a de-Googled stealth build should not expose (a build that
11
+ * claims de-Googled while still answering document.browsingTopics()/navigator.runAdAuction is a
12
+ * self-contradictory, pivotable fingerprint). All are runtime base::Features, so disabling needs
13
+ * no rebuild.
14
+ *
15
+ * WebUSB is deliberately NOT in this list. It is not a Privacy Sandbox feature - it is a device
16
+ * API that ships alongside Web Serial, WebHID and Web Bluetooth under identical secure-context
17
+ * gating. Disabling only WebUSB left navigator.usb absent while serial/hid/bluetooth stayed
18
+ * present, a combination no real Chromium produces; measured against stock Chrome on the same
19
+ * host, that split was the single flagged difference in the device-API family. Presence leaks
20
+ * nothing on its own - the API is permission-gated and enumerates no device without a user
21
+ * gesture - so exposing it costs no privacy and removes a hard coherence tell. */
22
+ export const PRIVACY_SANDBOX_FEATURES = [
23
+ "BrowsingTopics", "BrowsingTopicsDocumentAPI", "Fledge", "InterestGroupStorage",
24
+ "PrivateAggregationApi", "SharedStorageAPI", "FencedFrames",
25
+ ];
26
+ /** Chromium honors only the LAST --enable-features / --disable-features on the command line (they
27
+ * do NOT concatenate), so multiple occurrences clobber each other. Collapse all of each into a
28
+ * single flag (order-preserving, de-duped) so defaults from different layers + the user's own flags
29
+ * coexist. */
30
+ export function mergeFeatureFlags(args) {
31
+ const enabled = [];
32
+ const disabled = [];
33
+ const rest = [];
34
+ for (const a of args) {
35
+ if (a.startsWith("--enable-features="))
36
+ enabled.push(...a.slice(18).split(",").filter(Boolean));
37
+ else if (a.startsWith("--disable-features="))
38
+ disabled.push(...a.slice(19).split(",").filter(Boolean));
39
+ else
40
+ rest.push(a);
41
+ }
42
+ const dedupe = (xs) => [...new Set(xs)];
43
+ if (enabled.length)
44
+ rest.push(`--enable-features=${dedupe(enabled).join(",")}`);
45
+ if (disabled.length)
46
+ rest.push(`--disable-features=${dedupe(disabled).join(",")}`);
47
+ return rest;
48
+ }
49
+ /** Chromium 157+ can keep localStorage/sessionStorage in SQLite (`Default/LocalStorage`) instead of
50
+ * leveldb (`Default/Local Storage`). The features are off by default in 158 and our engine has no
51
+ * field trials, but Chrome for Testing turns them on through its field-trial testing config. Ant0
52
+ * sync only captures the leveldb store, and a migrated profile can't go back, so the SDK always pins
53
+ * the leveldb backend. */
54
+ export const DOM_STORAGE_SQLITE_FEATURES = [
55
+ "DomStorageSqlite", "DomStorageSqliteMigration", "DomStorageSqliteNewDatabases",
56
+ ];
57
+ /** Keep DOM storage on leveldb (always applied; merged by mergeFeatureFlags). */
58
+ export function domStorageBackendArgs() {
59
+ return [`--disable-features=${DOM_STORAGE_SQLITE_FEATURES.join(",")}`];
60
+ }
61
+ /** Disable Privacy Sandbox + intrusive APIs (runtime, no rebuild). */
62
+ export function privacySandboxArgs() {
63
+ return [`--disable-features=${PRIVACY_SANDBOX_FEATURES.join(",")}`];
64
+ }
65
+ /** Behind a proxy, real Chrome cannot use QUIC/HTTP3 (a SOCKS5/HTTP proxy carries only TCP), so it
66
+ * falls back to TCP. Disable QUIC when a proxy is configured so no HTTP/3 UDP is attempted —
67
+ * coherent with proxied Chrome, and a guarantee no UDP egresses around the proxy. No proxy -> leave
68
+ * QUIC on (real Chrome uses it). */
69
+ export function quicArgs(proxy) {
70
+ return proxy && proxy.server ? ["--disable-quic"] : [];
71
+ }
72
+ /** Emit `--socks5-udp` for a `socks5://` proxy when the caller asks for it.
73
+ *
74
+ * WARNING: the engine does NOT implement this switch today. Neither the patch series nor the
75
+ * Chromium tree it builds contains a `--socks5-udp` handler (two independent source reads), so
76
+ * Chromium ignores it: no UDP is relayed through the proxy, and the deny policy
77
+ * (`disable_non_proxied_udp`, see {@link webrtcDefaultDenyArgs}) still blocks peer-to-peer UDP.
78
+ * The option is kept so existing callers do not break and so engine support can land later; do not
79
+ * rely on it to make WebRTC UDP work through a proxy.
80
+ *
81
+ * Emitted only for a `socks5://` proxy (UDP ASSOCIATE, RFC 1928 section 7, is a SOCKS5 command; SOCKS4
82
+ * and HTTP proxies have no equivalent). Off by default. */
83
+ export function socks5UdpArgs(socks5Udp, proxy) {
84
+ if (socks5Udp !== true)
85
+ return [];
86
+ const server = (proxy?.server ?? "").trim();
87
+ return /^socks5/i.test(server) ? ["--socks5-udp"] : [];
88
+ }
89
+ /**
90
+ * Switches to expose `navigator.bluetooth` for a persona that is NOT Linux, on a Linux host.
91
+ *
92
+ * Web Bluetooth is compiled into the engine but runtime-disabled on Linux only:
93
+ * Chromium's runtime_enabled_features.json5 gives WebBluetooth status "stable" on Win/Mac/Android/
94
+ * ChromeOS and lets Linux fall through to "default": "experimental", and content_features.cc
95
+ * declares kWebBluetooth FEATURE_DISABLED_BY_DEFAULT. So a Linux host serving a Windows or macOS
96
+ * persona reports navigator.usb, navigator.serial and navigator.hid but NOT navigator.bluetooth -
97
+ * a combination no real Windows or macOS Chrome produces, and an OS-origin tell that survives every
98
+ * string spoof. One flag restores it on the shipped binary; no rebuild is involved.
99
+ *
100
+ * The flag depends on the persona, not on the host alone. Real Linux Chrome has NO
101
+ * navigator.bluetooth, so a Linux persona (and a launch with no persona, which presents the real
102
+ * host) must not get it: adding it there would itself be the tell. `personaPlatform` is the
103
+ * effective persona platform (`windows` | `macos` | `linux`); `null` or empty means no persona, so
104
+ * nothing is emitted; omitting the argument keeps the old public behaviour (flag on a Linux host). `hostPlatform` is injectable for tests.
105
+ *
106
+ * Verified against Chromium 150's bluetooth.idl: getDevices() is gated on WebBluetoothGetDevices
107
+ * and requestLEScan()/onadvertisementreceived on WebBluetoothScanning, both "experimental", so
108
+ * real stable Chrome exposes exactly {constructor, getAvailability, requestDevice} - which is what
109
+ * this flag produces. getAvailability() resolves false and requestDevice() rejects NotFoundError
110
+ * on a machine with no adapter, matching a real desktop without Bluetooth hardware.
111
+ */
112
+ export function webBluetoothArgs(personaPlatform, hostPlatform = process.platform) {
113
+ if (hostPlatform !== "linux")
114
+ return []; // Win/Mac ship it stable; the flag would be a no-op
115
+ // Called with no argument (the public pre-persona signature) the old contract holds: a Linux
116
+ // host gets the flag. Every SDK launch path passes a string, or null for "no persona".
117
+ if (personaPlatform === undefined)
118
+ return ["--enable-features=WebBluetooth"];
119
+ const persona = typeof personaPlatform === "string" ? personaPlatform.trim().toLowerCase() : "";
120
+ if (!persona || persona === "linux")
121
+ return []; // real Linux Chrome has no navigator.bluetooth
122
+ return ["--enable-features=WebBluetooth"];
123
+ }
124
+ /** Effective persona platform of a launch: the resolved `platform` option, else the captured
125
+ * profile's `compatibility.os_family`. Undefined when there is no persona (native identity). */
126
+ export function personaPlatformOf(platform, profile) {
127
+ if (typeof platform === "string" && platform.trim())
128
+ return platform.trim().toLowerCase();
129
+ const p = profile;
130
+ // A schema 4 persona names its OS in the identity block.
131
+ const os = p?.schema_version === 4 ? p.identity?.os?.family : p?.compatibility?.os_family;
132
+ return typeof os === "string" && os.trim() ? os.trim().toLowerCase() : undefined;
133
+ }
134
+ /** Playwright default launch args this SDK always removes (a caller's own `ignoreDefaultArgs` wins).
135
+ *
136
+ * - `--enable-automation` flips the AutomationControlled feature and webdriver-adjacent tells.
137
+ * - `--disable-ipc-flooding-protection` turns off Chromium's IPC flooding protection, which real
138
+ * Chrome keeps on (`ipcFloodingProtection` in the self-check). With it off, a burst of
139
+ * renderer-to-browser IPC is not throttled as it is in a real browser. */
140
+ export const IGNORED_PLAYWRIGHT_DEFAULTS = ["--enable-automation", "--disable-ipc-flooding-protection"];
141
+ /** Playwright testing switches `launch()` / `launchPersistentContext()` do not pass, because a page can
142
+ * observe them: `--hide-scrollbars` (`innerWidth - clientWidth` is 0 instead of the scrollbar width) and
143
+ * `--disable-popup-blocking` (`window.open()` without a user gesture returns a Window instead of null).
144
+ * Removing them breaks no Playwright automation (measured, tools/launch-switches). They go into
145
+ * `ignoreDefaultArgs` unless the caller passes the switch itself in `args`: Playwright's
146
+ * `ignoreDefaultArgs` also filters the caller's own `args`, so ignoring it then would drop the caller's
147
+ * switch. `serve()` / `launchPlan()` never had them. */
148
+ export const DROPPED_PLAYWRIGHT_SWITCHES = ["--hide-scrollbars", "--disable-popup-blocking"];
149
+ /** Playwright default disabled features the launch paths stop disabling, because a page can observe
150
+ * them: `HttpsUpgrades` (http: navigations upgrade to https: when TLS answers) and
151
+ * `BoundaryEventDispatchTracksNodeRemoval` (extra `mouseenter` events after the pointed-at node is
152
+ * removed). A caller's own `--disable-features` is merged after the defaults and keeps them. */
153
+ export const DROPPED_PLAYWRIGHT_DISABLED_FEATURES = ["HttpsUpgrades", "BoundaryEventDispatchTracksNodeRemoval"];
154
+ /** Kept disabled on every launch path. playwright-core 1.61 does not disable it (1.65 does), and with it
155
+ * on (and HttpsUpgrades off) `http://` fails `ERR_BLOCKED_BY_CLIENT` on a host without TLS. Off, http:
156
+ * upgrades to https: when TLS works and falls back to http: when it does not, as in a normal Chrome. */
157
+ export const PLAYWRIGHT_KEPT_DISABLED_FEATURE = "HttpsFirstBalancedModeAutoEnable";
158
+ /** The one feature Playwright disables by default that real Chrome does not. Disabling it makes a
159
+ * cross-site iframe's `localStorage` read back UNPARTITIONED (a site can track across top-level
160
+ * sites inside one profile) or throw `SecurityError`, where real Chrome reads a partitioned `null`.
161
+ * It is not in this SDK's own lists and never was (git history): it comes from Playwright's defaults. */
162
+ export const PLAYWRIGHT_UNWANTED_DISABLED_FEATURE = "ThirdPartyStoragePartitioning";
163
+ // The enabled list is read only from the place Playwright builds its --enable-features switch:
164
+ // - current layout: the switch is `"--enable-features=" + NAME().join(",")` (or `NAME.join`), and NAME is
165
+ // assigned exactly once, to `() => [ ... ]` (or `[ ... ]`) holding plain quoted names or
166
+ // `process.env.X ? "" : "Name"` entries;
167
+ // - older layout: a single `[process.env.X ? "" :] "--enable-features=A,B"` entry directly after the
168
+ // `"--disable-features=" + disabledFeatures.join(",")` entry.
169
+ // Comments are removed first. An `--enable-features=...` string anywhere else in the bundle (an error
170
+ // message, say) is never read, and a bundle that has one this does not recognise gives undefined.
171
+ // Only comments that start after whitespace or punctuation (not the `//` of a URL or the `/*` of a glob
172
+ // inside a string), and block comments are capped, so a stray quote elsewhere in a large bundle cannot
173
+ // swallow code.
174
+ const JS_COMMENT_RE = /(?<![^\s,;(\[{])(?:\/\/[^\n]*|\/\*(?:(?!\*\/)[\s\S]){0,4000}\*\/)/g;
175
+ const ENABLED_EMIT_RE = /"--enable-features="\s*\+\s*([A-Za-z_$][\w$]*)\s*(\(\s*\))?\s*\.join\(\s*","\s*\)/;
176
+ const ENABLED_ITEM_SRC = '(?:process\\.env\\.([A-Za-z0-9_]+)\\s*\\?\\s*""\\s*:\\s*)?"([A-Za-z0-9_]+)"';
177
+ const ARRAY_END_RE = /^\s*(?:\.filter\(\s*Boolean\s*\)\s*)?(?:;|,|\n|$)/;
178
+ const DISABLED_EMIT_THEN_ENABLED_RE = /"--disable-features="\s*\+\s*disabledFeatures\.join\(\s*","\s*\)\s*,\s*(?:process\.env\.([A-Za-z0-9_]+)\s*\?\s*""\s*:\s*)?"--enable-features=([A-Za-z0-9_,]+)"/;
179
+ function stripJsComments(source) {
180
+ return source.replace(JS_COMMENT_RE, " ");
181
+ }
182
+ function escapeRe(s) {
183
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
184
+ }
185
+ function parseEnabledFeatures(source, env) {
186
+ const emit = ENABLED_EMIT_RE.exec(source);
187
+ if (emit) {
188
+ const name = escapeRe(emit[1]);
189
+ if ((source.match(new RegExp(`(?<![\\w$.])${name}\\s*=(?![=>])`, "g")) ?? []).length !== 1)
190
+ return undefined;
191
+ const arrow = emit[2] ? "\\(\\s*\\)\\s*=>\\s*" : "";
192
+ const arr = new RegExp(`(?<![\\w$.])${name}\\s*=\\s*${arrow}\\[([^\\]]*)\\]`).exec(source);
193
+ if (!arr || !ARRAY_END_RE.test(source.slice(arr.index + arr[0].length)))
194
+ return undefined;
195
+ const body = arr[1];
196
+ if (body.replace(new RegExp(ENABLED_ITEM_SRC, "g"), "").replace(/[\s,]/g, "") !== "")
197
+ return undefined;
198
+ return [...body.matchAll(new RegExp(ENABLED_ITEM_SRC, "g"))].filter((m) => !(m[1] && env[m[1]])).map((m) => m[2]);
199
+ }
200
+ const legacy = DISABLED_EMIT_THEN_ENABLED_RE.exec(source);
201
+ if (legacy) {
202
+ if (legacy[1] && env[legacy[1]])
203
+ return [];
204
+ return legacy[2].split(",").filter(Boolean);
205
+ }
206
+ if (source.includes("--enable-features=") || /\benabledFeatures\b/.test(source))
207
+ return undefined;
208
+ return [];
209
+ }
210
+ /** Read Playwright's default feature switches out of its source text. Undefined unless the
211
+ * `disabledFeatures` array is plain quoted names (comments allowed) and contains
212
+ * {@link PLAYWRIGHT_UNWANTED_DISABLED_FEATURE}, and the enabled list is found where Playwright builds
213
+ * its switch; anything else (another layout, conditional entries) is not guessed at. `env` resolves the
214
+ * `process.env.X ? "" : "Name"` entries (default `process.env`). */
215
+ export function parsePlaywrightFeatureDefaults(source, env = process.env) {
216
+ source = stripJsComments(source);
217
+ const m = /\bdisabledFeatures\s*=\s*\[([^\]]*)\]/.exec(source);
218
+ if (!m)
219
+ return undefined;
220
+ const body = m[1];
221
+ const names = [...body.matchAll(/"([A-Za-z0-9_]+)"/g)].map((x) => x[1]);
222
+ if (body.replace(/"[A-Za-z0-9_]+"/g, "").replace(/[\s,]/g, "") !== "")
223
+ return undefined;
224
+ if (!names.includes(PLAYWRIGHT_UNWANTED_DISABLED_FEATURE))
225
+ return undefined;
226
+ const enabled = parseEnabledFeatures(source, env);
227
+ if (enabled === undefined)
228
+ return undefined;
229
+ return {
230
+ disabledFull: names,
231
+ disabled: names.filter((n) => n !== PLAYWRIGHT_UNWANTED_DISABLED_FEATURE),
232
+ enabled,
233
+ };
234
+ }
235
+ /** Back-compat helper: the disabled list without the unwanted feature, or undefined. */
236
+ export function parsePlaywrightDisabledFeatures(source) {
237
+ return parsePlaywrightFeatureDefaults(source)?.disabled;
238
+ }
239
+ let resolvedDefaults = null;
240
+ /** Playwright's default feature switches derived from the Playwright that is actually installed (its
241
+ * source, `lib/coreBundle.js` or `lib/server/chromium/chromiumSwitches.js`), so a different resolved
242
+ * version cannot be silently replaced by a stale copy. Undefined when it cannot be derived. */
243
+ export function installedPlaywrightFeatureDefaults() {
244
+ if (resolvedDefaults !== null)
245
+ return resolvedDefaults;
246
+ resolvedDefaults = undefined;
247
+ try {
248
+ const dir = dirname(createRequire(import.meta.url).resolve("playwright-core/package.json"));
249
+ for (const rel of ["lib/coreBundle.js", "lib/server/chromium/chromiumSwitches.js"]) {
250
+ let text;
251
+ try {
252
+ text = readFileSync(join(dir, rel), "utf8");
253
+ }
254
+ catch {
255
+ continue;
256
+ }
257
+ const parsed = parsePlaywrightFeatureDefaults(text);
258
+ if (parsed) {
259
+ resolvedDefaults = parsed;
260
+ break;
261
+ }
262
+ }
263
+ }
264
+ catch { /* unresolvable */ }
265
+ return resolvedDefaults;
266
+ }
267
+ export function installedPlaywrightDisabledFeatures() {
268
+ return installedPlaywrightFeatureDefaults()?.disabled;
269
+ }
270
+ let warnedNoDefaults = false;
271
+ /** True when Playwright will still add its own `--disable-features=<list>`: not when every default
272
+ * is ignored, nor when the caller's `ignoreDefaultArgs` holds that exact default argument (Playwright
273
+ * filters by exact string, so a bare `--disable-features` entry ignores nothing). */
274
+ function playwrightKeepsFeatureDefaults(ignoreDefaultArgs, d) {
275
+ if (ignoreDefaultArgs === true)
276
+ return false;
277
+ if (Array.isArray(ignoreDefaultArgs) && ignoreDefaultArgs.includes(`--disable-features=${d.disabledFull.join(",")}`))
278
+ return false;
279
+ return true;
280
+ }
281
+ function callerEnabledFeatures(args) {
282
+ const out = [];
283
+ for (const x of parseSwitches(args)) {
284
+ if (x.name === "enable-features" && x.value)
285
+ out.push(...x.value.split(",").map((f) => f.trim()).filter(Boolean));
286
+ }
287
+ return out;
288
+ }
289
+ /** Playwright's `--disable-features` / `--enable-features` defaults, minus
290
+ * ThirdPartyStoragePartitioning, for a Playwright launch only (a direct spawn has no Playwright
291
+ * defaults). Put them in FRONT of the engine args and run {@link mergeFeatureFlags}: the SDK's own
292
+ * and the caller's flags then merge with Playwright's lists instead of replacing them (Chromium
293
+ * honours only the last of each). Empty when Playwright's defaults are ignored, or when they cannot
294
+ * be derived from the installed Playwright (warned once; Playwright's own list then stays, and an
295
+ * SDK or caller `--disable-features` replaces it, so the launch paths skip the DOM storage pin then). `defaults` is injectable for tests. */
296
+ export function playwrightFeatureArgs(args, ignoreDefaultArgs, defaults = installedPlaywrightFeatureDefaults(), quiet) {
297
+ const d = Array.isArray(defaults)
298
+ ? { disabledFull: [...defaults], disabled: defaults, enabled: [] }
299
+ : defaults;
300
+ if (ignoreDefaultArgs === true)
301
+ return [];
302
+ if (!d || d.disabled.length === 0) {
303
+ if (!warnedNoDefaults && !quiet && process.env.ANT0_BROWSER_NO_WARN === undefined) {
304
+ warnedNoDefaults = true;
305
+ process.stderr.write("[ant0-browser] [features] could not read the installed Playwright's default feature lists, so they are left " +
306
+ "as Playwright sets them. A --disable-features switch passed by the SDK or the caller replaces Playwright's " +
307
+ "whole disabled list (ThirdPartyStoragePartitioning and Playwright's other disabled features are then no " +
308
+ "longer disabled), and a --enable-features switch (for example WebBluetooth) replaces Playwright's own enabled " +
309
+ "features (CDPScreenshotNewSurface, SkipListAccountsWithoutGaiaCookies). With neither switch, Playwright's " +
310
+ "lists stay in effect\n");
311
+ }
312
+ return [];
313
+ }
314
+ if (!playwrightKeepsFeatureDefaults(ignoreDefaultArgs, d))
315
+ return [];
316
+ // Playwright's list minus the features the page can observe, plus HttpsFirstBalancedModeAutoEnable (see
317
+ // the constants). Only here, i.e. only when Playwright's defaults were read: when they cannot be
318
+ // (returned [] above) the feature lists are not touched at all, nothing added, nothing removed.
319
+ // A feature the caller enables explicitly (--enable-features) is taken OUT of this disabled list, whether
320
+ // Playwright's own list or our addition put it there, so it is never in both lists (disable would win).
321
+ const managed = [...DROPPED_PLAYWRIGHT_DISABLED_FEATURES, PLAYWRIGHT_KEPT_DISABLED_FEATURE];
322
+ let disabled = d.disabled.filter((n) => !DROPPED_PLAYWRIGHT_DISABLED_FEATURES.includes(n));
323
+ if (!disabled.includes(PLAYWRIGHT_KEPT_DISABLED_FEATURE))
324
+ disabled.push(PLAYWRIGHT_KEPT_DISABLED_FEATURE);
325
+ const callerEnabled = callerEnabledFeatures(args);
326
+ disabled = disabled.filter((n) => !(managed.includes(n) && callerEnabled.includes(n)));
327
+ const out = disabled.length ? [`--disable-features=${disabled.join(",")}`] : [];
328
+ if (d.enabled.length)
329
+ out.push(`--enable-features=${d.enabled.join(",")}`);
330
+ return out;
331
+ }
332
+ /** The engine args with Playwright's feature defaults merged in (see {@link playwrightFeatureArgs}). */
333
+ export function withPlaywrightFeatureDefaults(args, ignoreDefaultArgs, quiet, defaults = installedPlaywrightFeatureDefaults()) {
334
+ const lists = playwrightFeatureArgs(args, ignoreDefaultArgs, defaults, quiet);
335
+ // The leveldb DOM storage pin is skipped when Playwright's disabled list cannot be read (and is not
336
+ // ignored wholesale): the SDK's --disable-features would then replace that whole list, and the pin
337
+ // is a no-op on the current engine, so the launch keeps its args exactly as they were without it.
338
+ // serve()/launchPlan() always pin (no Playwright list to lose) from assembleArgs.
339
+ const found = Array.isArray(defaults) ? { disabled: defaults } : defaults;
340
+ const unreadable = ignoreDefaultArgs !== true && !(found && found.disabled.length > 0);
341
+ const pin = unreadable ? [] : domStorageBackendArgs();
342
+ return mergeFeatureFlags([...lists, ...args, ...pin]);
343
+ }
344
+ /** `--proxy-bypass-list` for a Playwright proxy's `bypass` (comma separated), for the direct
345
+ * `serve()` / `launchPlan()` spawn. Same rule translation Playwright applies (trim, leading `.` ->
346
+ * `*.`, `;` joined). Playwright also forces `<-loopback>` through the proxy; a direct spawn keeps
347
+ * Chromium's own loopback bypass, so that rule is deliberately not added. Empty without a proxy
348
+ * server or a bypass. */
349
+ export function proxyBypassArgs(proxy) {
350
+ if (!proxy || typeof proxy !== "object" || !proxy.server || !proxy.bypass)
351
+ return [];
352
+ const rules = String(proxy.bypass).split(",").map((t) => t.trim()).filter(Boolean)
353
+ .map((t) => (t.startsWith(".") ? "*" + t : t));
354
+ return rules.length ? [`--proxy-bypass-list=${rules.join(";")}`] : [];
355
+ }
356
+ /** The SDK's ignored Playwright defaults plus the caller's own, so a caller's `ignoreDefaultArgs`
357
+ * adds to them and can never bring `--enable-automation` or `--disable-ipc-flooding-protection` back.
358
+ * `true` (ignore every default) is kept as is. `--hide-scrollbars` and `--disable-popup-blocking` are added
359
+ * too (see {@link DROPPED_PLAYWRIGHT_SWITCHES}), except one the caller passes in `args` themselves. */
360
+ export function mergeIgnoreDefaultArgs(caller, args) {
361
+ if (caller === true)
362
+ return true;
363
+ const own = Array.isArray(caller) ? caller.map(String) : [];
364
+ const dropped = DROPPED_PLAYWRIGHT_SWITCHES.filter((sw) => !hasSwitch(args ?? [], sw.slice(2)));
365
+ return [...new Set([...IGNORED_PLAYWRIGHT_DEFAULTS, ...dropped, ...own])];
366
+ }
367
+ /** First engine release that holds `--webrtc-ip` without re-enabling non-proxied UDP. */
368
+ export const WEBRTC_IP_MIN_ENGINE = "158.0.8127.18-ant0.3";
369
+ const ENGINE_VERSION_RE = /^(\d+)\.(\d+)\.(\d+)\.(\d+)-ant0\.(\d+)$/;
370
+ function parseEngineVersion(v) {
371
+ if (typeof v !== "string")
372
+ return undefined;
373
+ const m = ENGINE_VERSION_RE.exec(v.trim());
374
+ return m ? m.slice(1).map(Number) : undefined;
375
+ }
376
+ /** True only for a parseable engine release at or after {@link WEBRTC_IP_MIN_ENGINE}, compared
377
+ * numerically field by field (the four-part Chromium version, then the `-ant0.N` build). Unknown,
378
+ * missing or unparseable counts as old: the safe path is to omit the flag. */
379
+ export function engineSupportsWebrtcIp(engineVersion) {
380
+ const have = parseEngineVersion(engineVersion);
381
+ if (!have)
382
+ return false;
383
+ const need = parseEngineVersion(WEBRTC_IP_MIN_ENGINE);
384
+ for (let i = 0; i < need.length; i++) {
385
+ if (have[i] !== need[i])
386
+ return have[i] > need[i];
387
+ }
388
+ return true;
389
+ }
390
+ /** True for a plain IPv4 or IPv6 address (no brackets, zone id, port or whitespace). */
391
+ export function isValidWebrtcIp(value) {
392
+ return typeof value === "string" && !/[\s%\[\]/]/.test(value) && isIP(value) !== 0;
393
+ }
394
+ const SAFE_POLICY = "disable_non_proxied_udp";
395
+ /** The switches Chromium would parse out of `args`, in order. Chromium accepts `--name`, `-name` and
396
+ * (Windows) `/name`, lowercases names on Windows, and stops at a bare `--`. Matching is deliberately
397
+ * a superset (every prefix, any case) so no spelling slips through on any host. */
398
+ function parseSwitches(args) {
399
+ const out = [];
400
+ for (const arg of args) {
401
+ if (arg === "--")
402
+ break;
403
+ const m = /^(?:--|-|\/)([^=\s\-/][^=]*)(?:=([\s\S]*))?$/.exec(arg);
404
+ if (m)
405
+ out.push({ name: m[1].toLowerCase(), value: m[2], arg });
406
+ }
407
+ return out;
408
+ }
409
+ function lastSwitchValue(args, name) {
410
+ const all = parseSwitches(args).filter((x) => x.name === name);
411
+ return all.length ? all[all.length - 1].value : undefined;
412
+ }
413
+ /** The WebRTC IP handling policy that is actually in force from the switches: the last non-empty
414
+ * `--force-webrtc-ip-handling-policy`, else the last non-empty `--webrtc-ip-handling-policy`
415
+ * (the force variant wins in Chromium). An empty or bare switch sets nothing. */
416
+ export function effectiveWebrtcPolicy(args) {
417
+ for (const name of ["force-webrtc-ip-handling-policy", "webrtc-ip-handling-policy"]) {
418
+ const nonEmpty = parseSwitches(args).filter((x) => x.name === name && (x.value ?? "").trim() !== "");
419
+ if (nonEmpty.length)
420
+ return nonEmpty[nonEmpty.length - 1].value.trim();
421
+ }
422
+ return undefined;
423
+ }
424
+ /** True only when the policy in force lets non-proxied UDP out (anything but
425
+ * `disable_non_proxied_udp`). They chose to leave the protection, so a dropped `--webrtc-ip` is not
426
+ * ours to enforce there: today's behaviour is kept. */
427
+ export function callerAllowsUdp(args) {
428
+ const policy = effectiveWebrtcPolicy(args);
429
+ return policy !== undefined && policy !== SAFE_POLICY;
430
+ }
431
+ /** True when the switches themselves configure a proxy (`--proxy-server=...`, any spelling) and no
432
+ * `--no-proxy-server` cancels it. `direct://` is no proxy. */
433
+ export function hasRawProxyServer(args) {
434
+ if (parseSwitches(args).some((x) => x.name === "no-proxy-server"))
435
+ return false;
436
+ const v = (lastSwitchValue(args, "proxy-server") ?? "").trim();
437
+ return v !== "" && !/^direct:\/\//i.test(v);
438
+ }
439
+ function hasSwitch(args, name) {
440
+ return parseSwitches(args).some((x) => x.name === name);
441
+ }
442
+ /**
443
+ * Drop `--webrtc-ip=...` from the final engine args when the engine is older than
444
+ * {@link WEBRTC_IP_MIN_ENGINE}.
445
+ *
446
+ * Why: engines through 158.0.8127.18-ant0.2 turn non-proxied UDP back on whenever `--webrtc-ip`
447
+ * is set, even with `--webrtc-ip-handling-policy=disable_non_proxied_udp`. A page that points ICE
448
+ * at its own TURN server or peer then gets UDP from the host's real public address (measured: 133
449
+ * packets to a test range with the flag, 0 without). ant0.3 fixes it in the engine.
450
+ *
451
+ * Applied to the final list, so it covers the option, a geo-derived value and a raw
452
+ * `--webrtc-ip=` in caller args alike. A caller policy that allows UDP opts out (see
453
+ * callerAllowsUdp). A warning is written when a value is dropped; it never contains the address.
454
+ */
455
+ export function gateWebrtcIpArgs(args, engineVersion, quiet) {
456
+ const warn = (msg) => {
457
+ if (!quiet && process.env.ANT0_BROWSER_NO_WARN === undefined)
458
+ process.stderr.write(`[ant0-browser] [webrtc-ip] ${msg}\n`);
459
+ };
460
+ // A value that is not an IP address (empty and bare included, any spelling or case of the switch)
461
+ // is dropped on every engine; the warning never repeats it.
462
+ const ipSwitches = new Set(parseSwitches(args).filter((x) => x.name === "webrtc-ip").map((x) => x.arg));
463
+ const valid = args.filter((a) => {
464
+ if (!ipSwitches.has(a))
465
+ return true;
466
+ const sw = parseSwitches([a])[0];
467
+ return sw !== undefined && isValidWebrtcIp(sw.value ?? "");
468
+ });
469
+ if (valid.length !== args.length)
470
+ warn("dropped webrtcIp: the value is not an IP address");
471
+ args = valid;
472
+ if (engineSupportsWebrtcIp(engineVersion))
473
+ return args;
474
+ if (callerAllowsUdp(args))
475
+ return args;
476
+ const remaining = new Set(parseSwitches(args).filter((x) => x.name === "webrtc-ip").map((x) => x.arg));
477
+ const kept = args.filter((a) => !remaining.has(a));
478
+ if (kept.length !== args.length && !quiet && process.env.ANT0_BROWSER_NO_WARN === undefined) {
479
+ const known = parseEngineVersion(engineVersion) ? String(engineVersion) : "version unknown";
480
+ process.stderr.write(`[ant0-browser] [webrtc-ip] dropped webrtcIp: this engine (${known}) would let real-IP UDP ` +
481
+ `out with it set; needs ${WEBRTC_IP_MIN_ENGINE} or later\n`);
482
+ }
483
+ return kept;
484
+ }
485
+ /** Switch (engine 158.0.8127.18-ant0.3 and later) that stops WebRTC looking up page-chosen hostnames
486
+ * (TURN/STUN servers, `.local` candidates) on the host's own resolver, which would otherwise happen
487
+ * outside the proxy. */
488
+ export const WEBRTC_NO_LOCAL_DNS = "--webrtc-no-local-dns";
489
+ /**
490
+ * {@link gateWebrtcIpArgs}, plus `--webrtc-no-local-dns` on every launch that has a proxy (the
491
+ * daemon's credential relay included) when the engine is at {@link WEBRTC_IP_MIN_ENGINE} or later
492
+ * (the same version check as `--webrtc-ip`; unknown counts as old). Not added without a proxy, or
493
+ * when the caller's own WebRTC policy allows UDP, or when it is already in the args, or in UDP
494
+ * relay mode (`--webrtc-udp-relay`; the engine ignores it there, see docs/SOCKS5-UDP-RELAY.md).
495
+ */
496
+ export function gateWebrtcArgs(args, engineVersion, quiet, hasProxy) {
497
+ const out = gateWebrtcIpArgs(args, engineVersion, quiet);
498
+ if (!(hasProxy || hasRawProxyServer(out)) || !engineSupportsWebrtcIp(engineVersion) || callerAllowsUdp(out) || hasSwitch(out, "webrtc-no-local-dns") || hasSwitch(out, "webrtc-udp-relay"))
499
+ return out;
500
+ return [...out, WEBRTC_NO_LOCAL_DNS];
501
+ }
502
+ /** Default WebRTC to disable_non_proxied_udp, so no UDP can egress around the proxy.
503
+ *
504
+ * This used to be skipped whenever `webrtcIp` was set, on the theory that the engine's srflx
505
+ * fabrication already covered WebRTC. It does not - the two defend different things:
506
+ *
507
+ * - fabrication rewrites what the browser *reports*, which beats a page that reads the candidate;
508
+ * - this policy stops UDP *leaving the machine*, which beats a server that watches where packets
509
+ * arrive from.
510
+ *
511
+ * A page that sets `iceTransportPolicy: "relay"` forces the browser to talk to its own TURN server.
512
+ * TURN prefers UDP and an HTTP/SOCKS proxy carries only TCP, so that UDP left on the host's own
513
+ * path and the TURN server read the real public address straight off the packet - no candidate
514
+ * involved, so fabricating one changed nothing.
515
+ *
516
+ * CAVEAT (measured): on engines older than 158.0.8127.18-ant0.3 this policy is NOT enough on its
517
+ * own. Setting `--webrtc-ip` makes those engines re-enable non-proxied UDP, overriding the policy.
518
+ * So the SDK omits `--webrtc-ip` for them (see gateWebrtcIpArgs) and the policy then holds.
519
+ * ant0.3 and later keep the policy in force with `--webrtc-ip` set.
520
+ *
521
+ * This is a real trade-off, not a free win: denying non-proxied UDP means peer connections that
522
+ * genuinely need UDP will not establish. Callers who need working WebRTC can set their own policy
523
+ * to opt out; a policy that allows UDP also keeps `--webrtc-ip` on any engine. */
524
+ export function webrtcDefaultDenyArgs(args, _webrtcIp) {
525
+ if (args.some((a) => a.startsWith("--webrtc-ip-handling-policy") || a.startsWith("--force-webrtc-ip-handling-policy"))) {
526
+ return [];
527
+ }
528
+ return ["--webrtc-ip-handling-policy=disable_non_proxied_udp"];
529
+ }
530
+ /** Switches to load unpacked extensions. Chromium needs BOTH --load-extension=<dirs> and
531
+ * --disable-extensions-except=<dirs> (the latter keeps the listed extensions enabled while
532
+ * everything else stays off). `paths` is a list of unpacked-extension directories. */
533
+ export function extensionArgs(paths) {
534
+ if (!paths || paths.length === 0)
535
+ return [];
536
+ const joined = paths.join(",");
537
+ return [`--load-extension=${joined}`, `--disable-extensions-except=${joined}`];
538
+ }
539
+ /** First-run/UX hygiene switches for a DIRECT launch (`serve()` / `launchPlan()`).
540
+ *
541
+ * Playwright adds these itself on `launch()`, so a Playwright-driven browser never shows the
542
+ * first-run UI. A direct spawn gets none of that, and the ungoogled-chromium base then opens
543
+ * `chrome://ungoogled-first-run` ("ungoogled-chromium first run page", empty body) in the first
544
+ * tab whenever the caller passes no start URL, plus the default-browser prompt and the search
545
+ * engine choice screen in headed mode. These are plain UI switches, not `base::Feature` toggles:
546
+ * they change nothing a page can observe, so the identity layer (which owns
547
+ * `--enable-features`/`--disable-features`) is not affected and the coherence checker does not
548
+ * flag them. */
549
+ export const FIRST_RUN_HYGIENE_ARGS = [
550
+ "--no-first-run",
551
+ "--no-default-browser-check",
552
+ "--disable-search-engine-choice-screen",
553
+ ];
554
+ /** True when `args` carries a positional (non-switch) argument, which Chromium opens as a URL.
555
+ * Everything after a literal `--` is positional by Chromium's command-line rules. */
556
+ export function hasUrlPositional(args) {
557
+ let afterSeparator = false;
558
+ for (const a of args) {
559
+ if (afterSeparator)
560
+ return true;
561
+ if (a === "--") {
562
+ afterSeparator = true;
563
+ continue;
564
+ }
565
+ if (!a.startsWith("-"))
566
+ return true;
567
+ }
568
+ return false;
569
+ }
570
+ /** The neutral start page for a direct launch with no caller URL: `about:blank` as the final
571
+ * positional, so the first tab is blank instead of the ungoogled first-run page. Empty when the
572
+ * caller already supplied a URL positional (Chromium would open both otherwise). */
573
+ export function defaultStartUrlArgs(args) {
574
+ return hasUrlPositional(args) ? [] : ["about:blank"];
575
+ }
576
+ /** Message thrown for a SOCKS proxy descriptor that carries `username`/`password`. Exported so the
577
+ * tests and the Python SDK's mirror can assert on the same wording. */
578
+ export const SOCKS_CREDENTIALS_UNSUPPORTED = "SOCKS proxy with username/password is not supported: the engine does not authenticate to " +
579
+ "SOCKS5 proxies (Chromium has no RFC 1929 username/password client), and Playwright rejects " +
580
+ "credentials in a SOCKS proxy descriptor. Either use an http(s):// proxy with credentials " +
581
+ "(Playwright handles those), a SOCKS5 proxy that allows this client's IP without credentials, " +
582
+ "or run a local relay (as ant0d does) that authenticates upstream and point `proxy.server` at " +
583
+ "it without credentials.";
584
+ /** Resolve a Playwright proxy descriptor into `{ args, proxy }`.
585
+ *
586
+ * Every proxy shape is left to Playwright unchanged, except a SOCKS proxy WITH credentials, which
587
+ * throws: neither Playwright (it rejects credentials in a SOCKS descriptor) nor the engine (stock
588
+ * Chromium has no RFC 1929 client, and no ant0-browser patch adds one) can authenticate to it, so
589
+ * a launch would silently produce a proxy that refuses every connection. Callers needing a
590
+ * credentialed SOCKS5 upstream run a local relay and hand the SDK its unauthenticated loopback
591
+ * address instead. Userinfo inside the URL (`socks5://user:pass@host:port`) counts as credentials
592
+ * too: Chromium would drop it silently. */
593
+ export function resolveProxy(proxy) {
594
+ if (!proxy || typeof proxy !== "object")
595
+ return { args: [], proxy };
596
+ const server = (proxy.server ?? "").trim();
597
+ // Credentials as fields, or as userinfo inside the URL: Chromium ignores the latter silently.
598
+ const hasCreds = !!(proxy.username || proxy.password) || /^[a-zA-Z0-9+.-]+:\/\/[^/@]*@/.test(server);
599
+ if (server && /^socks/i.test(server) && hasCreds) {
600
+ throw new SdkInputError("sdk.launch_option_unsupported", SOCKS_CREDENTIALS_UNSUPPORTED);
601
+ }
602
+ // The engine rejects socks5h:// (ERR_NO_SUPPORTED_PROXIES); its socks5:// already resolves hostnames
603
+ // at the proxy, which is what socks5h asks for. Only the scheme changes.
604
+ if (/^\s*socks5h:\/\//i.test(server)) {
605
+ return { args: [], proxy: { ...proxy, server: proxy.server.replace(/^(\s*)socks5h:\/\//i, "$1socks5://") } };
606
+ }
607
+ return { args: [], proxy };
608
+ }
609
+ /** Switches only the engine sets. `--ant0-persona-handle` carries the accepted persona to renderer
610
+ * processes (patch 937); a browser-process value would be ignored at best, so the SDK neither emits it
611
+ * nor lets a caller's own args do so. */
612
+ export const RESERVED_ENGINE_SWITCHES = ["--ant0-persona-handle"];
613
+ /** Throw `sdk.launch_option_unsupported` when `args` contains an engine-reserved switch, in any spelling
614
+ * Chromium parses: `--name`, `-name` or `/name` (any case), with or without `=value`. */
615
+ export function assertNoReservedArgs(args) {
616
+ const reserved = new Set(RESERVED_ENGINE_SWITCHES.map((n) => n.replace(/^--/, "")));
617
+ for (const sw of parseSwitches(args.map(String))) {
618
+ if (reserved.has(sw.name)) {
619
+ throw new SdkInputError("sdk.launch_option_unsupported", `--${sw.name} is set by the engine for its own processes and cannot be passed in args.`);
620
+ }
621
+ }
622
+ }
623
+ //# sourceMappingURL=launchopts.js.map