ant0-browser 0.1.1 → 0.2.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 (135) hide show
  1. package/README.md +112 -4
  2. package/dist/canvas.d.ts +55 -0
  3. package/dist/canvas.d.ts.map +1 -0
  4. package/dist/canvas.js +82 -0
  5. package/dist/canvas.js.map +1 -0
  6. package/dist/chromium-version.d.ts +3 -3
  7. package/dist/chromium-version.js +3 -3
  8. package/dist/claim-hints.d.ts +36 -0
  9. package/dist/claim-hints.d.ts.map +1 -0
  10. package/dist/claim-hints.js +9 -0
  11. package/dist/claim-hints.js.map +1 -0
  12. package/dist/cleanup.d.ts +35 -0
  13. package/dist/cleanup.d.ts.map +1 -0
  14. package/dist/cleanup.js +106 -0
  15. package/dist/cleanup.js.map +1 -0
  16. package/dist/content.d.ts +11 -0
  17. package/dist/content.d.ts.map +1 -0
  18. package/dist/content.js +52 -0
  19. package/dist/content.js.map +1 -0
  20. package/dist/download.d.ts +2 -0
  21. package/dist/download.d.ts.map +1 -1
  22. package/dist/download.js +14 -6
  23. package/dist/download.js.map +1 -1
  24. package/dist/errors.d.ts +49 -0
  25. package/dist/errors.d.ts.map +1 -0
  26. package/dist/errors.js +53 -0
  27. package/dist/errors.js.map +1 -0
  28. package/dist/fingerprint.d.ts +42 -37
  29. package/dist/fingerprint.d.ts.map +1 -1
  30. package/dist/fingerprint.js +124 -24
  31. package/dist/fingerprint.js.map +1 -1
  32. package/dist/fontpack.d.ts.map +1 -1
  33. package/dist/fontpack.js +2 -1
  34. package/dist/fontpack.js.map +1 -1
  35. package/dist/fonts.js +1 -1
  36. package/dist/fonts.js.map +1 -1
  37. package/dist/geoip.d.ts.map +1 -1
  38. package/dist/geoip.js +3 -2
  39. package/dist/geoip.js.map +1 -1
  40. package/dist/geometry.d.ts +4 -0
  41. package/dist/geometry.d.ts.map +1 -1
  42. package/dist/geometry.js +9 -3
  43. package/dist/geometry.js.map +1 -1
  44. package/dist/identity-persistence.d.ts +38 -1
  45. package/dist/identity-persistence.d.ts.map +1 -1
  46. package/dist/identity-persistence.js +90 -10
  47. package/dist/identity-persistence.js.map +1 -1
  48. package/dist/identity.d.ts +41 -3
  49. package/dist/identity.d.ts.map +1 -1
  50. package/dist/identity.js +199 -26
  51. package/dist/identity.js.map +1 -1
  52. package/dist/index.d.ts +69 -22
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +415 -218
  55. package/dist/index.js.map +1 -1
  56. package/dist/launch-ticket.d.ts +109 -5
  57. package/dist/launch-ticket.d.ts.map +1 -1
  58. package/dist/launch-ticket.js +327 -11
  59. package/dist/launch-ticket.js.map +1 -1
  60. package/dist/launchopts.d.ts +181 -48
  61. package/dist/launchopts.d.ts.map +1 -1
  62. package/dist/launchopts.js +470 -51
  63. package/dist/launchopts.js.map +1 -1
  64. package/dist/native/linux-x64/PRODUCT-LICENSE.txt +28 -0
  65. package/dist/native/linux-x64/ant0_runtime.node +0 -0
  66. package/dist/native/windows-x64/PRODUCT-LICENSE.txt +28 -0
  67. package/dist/native/windows-x64/ant0_runtime.node +0 -0
  68. package/dist/persona-migration.d.ts +3 -0
  69. package/dist/persona-migration.d.ts.map +1 -1
  70. package/dist/persona-migration.js +2 -0
  71. package/dist/persona-migration.js.map +1 -1
  72. package/dist/persona-profile-v2.d.ts +15 -1
  73. package/dist/persona-profile-v2.d.ts.map +1 -1
  74. package/dist/persona-profile-v2.js +35 -2
  75. package/dist/persona-profile-v2.js.map +1 -1
  76. package/dist/persona-profile-v4.d.ts +61 -0
  77. package/dist/persona-profile-v4.d.ts.map +1 -0
  78. package/dist/persona-profile-v4.js +79 -0
  79. package/dist/persona-profile-v4.js.map +1 -0
  80. package/dist/persona-rejected.d.ts +36 -0
  81. package/dist/persona-rejected.d.ts.map +1 -0
  82. package/dist/persona-rejected.js +40 -0
  83. package/dist/persona-rejected.js.map +1 -0
  84. package/dist/population-model.d.ts +3 -0
  85. package/dist/population-model.d.ts.map +1 -1
  86. package/dist/population-model.js +24 -3
  87. package/dist/population-model.js.map +1 -1
  88. package/dist/profile-file.d.ts +201 -0
  89. package/dist/profile-file.d.ts.map +1 -0
  90. package/dist/profile-file.js +736 -0
  91. package/dist/profile-file.js.map +1 -0
  92. package/dist/release-fetch.d.ts +4 -0
  93. package/dist/release-fetch.d.ts.map +1 -1
  94. package/dist/release-fetch.js +3 -0
  95. package/dist/release-fetch.js.map +1 -1
  96. package/dist/render.js +2 -2
  97. package/dist/render.js.map +1 -1
  98. package/dist/runtime-client.d.ts +47 -0
  99. package/dist/runtime-client.d.ts.map +1 -0
  100. package/dist/runtime-client.js +327 -0
  101. package/dist/runtime-client.js.map +1 -0
  102. package/dist/runtime-launch.d.ts +22 -0
  103. package/dist/runtime-launch.d.ts.map +1 -0
  104. package/dist/runtime-launch.js +92 -0
  105. package/dist/runtime-launch.js.map +1 -0
  106. package/dist/scale.d.ts +29 -0
  107. package/dist/scale.d.ts.map +1 -0
  108. package/dist/scale.js +105 -0
  109. package/dist/scale.js.map +1 -0
  110. package/dist/shaderdialect.d.ts.map +1 -1
  111. package/dist/shaderdialect.js +2 -1
  112. package/dist/shaderdialect.js.map +1 -1
  113. package/dist/speech-coherence.d.ts +52 -0
  114. package/dist/speech-coherence.d.ts.map +1 -0
  115. package/dist/speech-coherence.js +254 -0
  116. package/dist/speech-coherence.js.map +1 -0
  117. package/dist/template-selection.d.ts.map +1 -1
  118. package/dist/template-selection.js +8 -7
  119. package/dist/template-selection.js.map +1 -1
  120. package/dist/warnings.d.ts +35 -4
  121. package/dist/warnings.d.ts.map +1 -1
  122. package/dist/warnings.js +139 -25
  123. package/dist/warnings.js.map +1 -1
  124. package/dist/webgl-coherence.d.ts +30 -0
  125. package/dist/webgl-coherence.d.ts.map +1 -0
  126. package/dist/webgl-coherence.js +98 -0
  127. package/dist/webgl-coherence.js.map +1 -0
  128. package/dist/webgpu-override.d.ts +14 -0
  129. package/dist/webgpu-override.d.ts.map +1 -0
  130. package/dist/webgpu-override.js +82 -0
  131. package/dist/webgpu-override.js.map +1 -0
  132. package/dist/widevine.d.ts.map +1 -1
  133. package/dist/widevine.js +11 -10
  134. package/dist/widevine.js.map +1 -1
  135. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -14,33 +14,56 @@ import { spawn } from "node:child_process";
14
14
  import { createServer } from "node:net";
15
15
  import { tmpdir } from "node:os";
16
16
  import { join } from "node:path";
17
- import { checkInstall, ensureBinary } from "./download.js";
18
- import { fingerprintArgs, splitFingerprintOptions } from "./fingerprint.js";
17
+ import { fingerprintArgs, personaAvail, personaDpr, splitFingerprintOptions } from "./fingerprint.js";
18
+ import { scaleWindowArgs, withDeviceScale } from "./scale.js";
19
19
  import { prepareIdentityOptions } from "./identity.js";
20
20
  import { installHumanize, installHumanizeOnContext } from "./humanize.js";
21
- import { FIRST_RUN_HYGIENE_ARGS, defaultStartUrlArgs, extensionArgs, resolveProxy, mergeFeatureFlags, privacySandboxArgs, quicArgs, socks5UdpArgs, webBluetoothArgs, webrtcDefaultDenyArgs, } from "./launchopts.js";
21
+ import { FIRST_RUN_HYGIENE_ARGS, defaultStartUrlArgs, extensionArgs, resolveProxy, mergeFeatureFlags, privacySandboxArgs, domStorageBackendArgs, proxyBypassArgs, quicArgs, socks5UdpArgs, webBluetoothArgs, personaPlatformOf, withPlaywrightFeatureDefaults, mergeIgnoreDefaultArgs, gateWebrtcArgs, webrtcDefaultDenyArgs, assertNoReservedArgs, } from "./launchopts.js";
22
22
  import { RELEASE, platformRelease } from "./release.js";
23
23
  import { fetchWidevine, seedWidevine, widevineArgs } from "./widevine.js";
24
24
  import { emitCoherenceWarnings, gpuHostMissingFor } from "./warnings.js";
25
+ import { removeOwnDir, stopChild, track, untrack } from "./cleanup.js";
26
+ import { installedEngineVersion as readInstalledEngineVersion } from "./launch-ticket.js";
25
27
  import { fontLaunchEnv } from "./fonts.js";
26
28
  import { resolveFontPack } from "./fontpack.js";
27
29
  export { resolveFontPack, packFamilies, PACK_VERSION as FONT_PACK_VERSION } from "./fontpack.js";
28
30
  import { withShaderDialect } from "./shaderdialect.js";
29
- import { LaunchTicketRejectedError, resolveLaunchTicketArgs, rethrowIfTicketRejected, launchTicketRejection, LAUNCH_TICKET_EXIT_CODE, } from "./launch-ticket.js";
31
+ import { PersonaFileRejectedError, personaFileRejection } from "./persona-rejected.js";
32
+ import { LaunchTicketRejectedError, hasLaunchTicketArg, rethrowIfTicketRejected, launchTicketRejection, LAUNCH_TICKET_EXIT_CODE, redactError, redactLaunchSecrets, launchSecretValues, applyTicketEnv, argsForTicketDecision, callerEnvTicket, launchTicketArgValue, sdkFetchedTicket, withTicketRetry, dropPartialFirstLine, } from "./launch-ticket.js";
30
33
  import { applyHeadlessGeometry, initialWindowArgs, } from "./geometry.js";
34
+ import { manualBinary, withRuntimeLaunch } from "./runtime-launch.js";
35
+ import { assertPersonaFitsEngine, removeStalePersonaFile, stagePersonaProfile } from "./profile-file.js";
36
+ import { emitPersonaNotices } from "./warnings.js";
37
+ import { SdkError, SdkTypeError } from "./errors.js";
38
+ export { RuntimeError } from "./runtime-client.js";
39
+ export { SdkError, SdkInputError, SdkTypeError, SdkRangeError, reportFields } from "./errors.js";
31
40
  export { checkInstall, verifyInstall } from "./download.js";
32
41
  export { resolveGeo } from "./geoip.js";
42
+ // For callers that attach to an already-running browser (connectOverCDP) rather than launching
43
+ // one: humanize its existing context (current and future pages). Seed it from the identity's
44
+ // fingerprint so the motor persona matches the one a launch would have used.
45
+ export { installHumanizeOnContext } from "./humanize.js";
46
+ // The pure motor model behind humanized input (no page or browser access): seeded personas,
47
+ // mouse trajectories, click points and key/click timings. For callers that drive input over raw
48
+ // CDP themselves and want the same timing model as `humanize: true`.
49
+ export { mulberry32, hashSeed, gaussFrom, makePersona, clickHold, keyDwell, minJerk, planMove, dragDwell, clickPoint, planAmbient, } from "./motion.js";
33
50
  export { RELEASE, RELEASE_PUBLIC_KEY } from "./release.js";
34
51
  export { installRelease, installedRelease, verifyMinisign, ReleaseError, SignatureError } from "./release-fetch.js";
35
52
  export { fetchWidevine, seedWidevine } from "./widevine.js";
36
53
  export { checkRenderCoherence } from "./render.js";
37
- export { LaunchTicketRejectedError, LaunchTicketUnavailableError, launchTicketRejection, fetchLaunchTicket, discoverDaemon, resolveDaemonHome, inferEngineVersion, resolveLaunchTicketArgs, hasLaunchTicketArg, LAUNCH_TICKET_SWITCH, LAUNCH_TICKET_EXIT_CODE, LAUNCH_TICKET_REJECTED_CODE, ENGINE_VERSION_ENV, } from "./launch-ticket.js";
54
+ export { setContent } from "./content.js";
55
+ export { PersonaFileRejectedError, personaFileRejection, PERSONA_FILE_EXIT_CODE, PERSONA_FILE_REJECTED_CODE } from "./persona-rejected.js";
56
+ export { LaunchTicketRejectedError, LaunchTicketUnavailableError, launchTicketRejection, fetchLaunchTicket, discoverDaemon, resolveDaemonHome, inferEngineVersion, installedEngineVersion, resolveLaunchTicketArgs, hasLaunchTicketArg, LAUNCH_TICKET_SWITCH, LAUNCH_TICKET_ENV, LAUNCH_TICKET_EXIT_CODE, LAUNCH_TICKET_REJECTED_CODE, ENGINE_VERSION_ENV, } from "./launch-ticket.js";
38
57
  export { assertPersonaProfileV2, parsePersonaProfileV2, validatePersonaProfileV2, InvalidPersonaProfileV2Error, WEBGL_PARAMETER_NAMES, WEBGPU_LIMIT_NAMES, } from "./persona-profile-v2.js";
39
58
  export { CHROMIUM_VERSION, CHROMIUM_MAJOR, CHROMIUM_UA_VERSION } from "./chromium-version.js";
40
59
  export { migratePersonaBrowserMajor, needsMigration, personaBrowserMajor, PersonaMigrationError, MIGRATED_FIELDS, } from "./persona-migration.js";
41
60
  export { selectPersonaTemplate, } from "./template-selection.js";
42
61
  export { GENERATE_ALGORITHM, GENERATION_ORDER, PopulationModelError, loadPopulationModel, generatePersonaProfile, } from "./population-model.js";
43
- export { IDENTITY_WRAPPER_VERSION, GENERATED_IDENTITY_WRAPPER_VERSION, TEMPLATE_SELECTION_ALGORITHM, GENERATE_ALGORITHM as GENERATE_IDENTITY_ALGORITHM, IdentityPersistenceError, resolveIdentityDirectory, identityFilename, loadOrCreateDeviceKey, validatePersistedIdentity, loadPersistedIdentity, createOrLoadIdentity, createOrLoadGeneratedIdentity, } from "./identity-persistence.js";
62
+ export { IDENTITY_WRAPPER_VERSION, GENERATED_IDENTITY_WRAPPER_VERSION, TEMPLATE_SELECTION_ALGORITHM, GENERATE_ALGORITHM as GENERATE_IDENTITY_ALGORITHM, IdentityPersistenceError, resolveIdentityDirectory, identityFilename, loadOrCreateDeviceKey, validatePersistedIdentity, loadPersistedIdentity, createOrLoadIdentity, createOrLoadGeneratedIdentity, createOrLoadIssuedIdentity, ISSUED_IDENTITY_WRAPPER_VERSION, } from "./identity-persistence.js";
63
+ export { CANVAS_NOISE_KEY_SWITCH, CANVAS_NOISE_KEY_LENGTH, CANVAS_NOISE_KEY_DOMAIN, canvasMode, isCanvasNoiseKey, newCanvasNoiseKey, deriveCanvasNoiseKey, canvasNoiseKeyFor, } from "./canvas.js";
64
+ export { canvasNoiseKeyOfIdentity } from "./identity.js";
65
+ export { assertPersonaProfileV4, isPersonaV4, PersonaV4SchemaError } from "./persona-profile-v4.js";
66
+ export { PROFILE_FILE_SWITCH, SDK_INFO_SWITCH, PROFILE_FILE_NAME, enginePersonaInfo, enginePersonaSchemas, parseSdkInfoSchemas, writePersonaProfileFile, } from "./profile-file.js";
44
67
  export { loadTemplateDirectory, loadCapturedProfile, resolveIdentity, prepareIdentityOptions, } from "./identity.js";
45
68
  /** Resolve the real Windows font pack for a launch (Linux + persona only), else undefined. */
46
69
  async function fontPackForLaunch(identityMode, resolveFonts, quiet) {
@@ -52,34 +75,22 @@ async function fontPackForLaunch(identityMode, resolveFonts, quiet) {
52
75
  }
53
76
  function ensureRunnableHere(exe) {
54
77
  if (platformRelease() === undefined) {
55
- throw new Error(`Ant0 Browser ${RELEASE.version} ships Windows x64 and Linux x64 binaries — there is no build for '${process.platform}'.\n` +
78
+ throw new SdkError("sdk.environment_unsupported", `Ant0 Browser ${RELEASE.version} ships Windows x64 and Linux x64 binaries — there is no build for '${process.platform}'.\n` +
56
79
  `Run on Windows or Linux, or pass executablePath to a compatible binary.\n` +
57
80
  `(The resolved local binary is: ${exe})`);
58
81
  }
59
82
  }
60
- /**
61
- * Resolve the Ant0 Browser executable from an explicit path, `ANT0_BROWSER_BINARY`, or an existing
62
- * legacy local cache. This function never performs a network request.
63
- */
83
+ /** Resolve the installed default without fetching a ticket. The returned path is informational;
84
+ * launch/serve resolve again and retain native proof through their immediate spawn. */
64
85
  export async function executablePath(options = {}) {
65
- if (options.executablePath) {
66
- // Caller-supplied tree (often a browser bundled into a packaged app): we did not install it, so
67
- // validate it here — a half-copied tree otherwise CHECK-crashes during browser startup.
68
- checkInstall(options.executablePath);
69
- return options.executablePath;
70
- }
71
- if (process.env.ANT0_BROWSER_BINARY) {
72
- checkInstall(process.env.ANT0_BROWSER_BINARY);
73
- return process.env.ANT0_BROWSER_BINARY;
74
- }
75
- return ensureBinary({ cacheDir: options.cacheDir, quiet: options.quiet });
86
+ return withRuntimeLaunch({ ...options, launchTicket: false }, r => r.executable);
76
87
  }
77
88
  /** Headless context defaults ride on newPage/newContext because `chromium.launch()` takes none. */
78
- function installHeadlessGeometry(browser, geom) {
89
+ function installHeadlessGeometry(browser, geom, dpr) {
79
90
  const defaults = geom.mode === "native"
80
91
  ? { viewport: null }
81
92
  : { screen: geom.screen, viewport: geom.viewport };
82
- const merge = (o = {}) => "viewport" in o || "screen" in o ? o : { ...o, ...defaults };
93
+ const merge = (o = {}) => withDeviceScale("viewport" in o || "screen" in o ? o : { ...o, ...defaults }, dpr);
83
94
  const origNewPage = browser.newPage.bind(browser);
84
95
  const origNewContext = browser.newContext.bind(browser);
85
96
  browser.newPage =
@@ -91,27 +102,62 @@ function installHeadlessGeometry(browser, geom) {
91
102
  * makes window.innerWidth/Height disagree with the actual window — an impossible-window tell. For a
92
103
  * headed browser, default new pages/contexts to `viewport: null` (innerWidth tracks the real window)
93
104
  * unless the caller asked for a viewport. */
94
- function installHeadedViewport(browser) {
105
+ function installHeadedViewport(browser, dpr) {
106
+ const merge = (o) => withDeviceScale("viewport" in o || "screen" in o ? o : { ...o, viewport: null }, dpr);
95
107
  const origNewPage = browser.newPage.bind(browser);
96
- browser.newPage = (o = {}) => origNewPage("viewport" in o || "screen" in o ? o : { ...o, viewport: null });
108
+ browser.newPage = (o = {}) => origNewPage(merge(o));
97
109
  const origNewContext = browser.newContext.bind(browser);
98
- browser.newContext = (o = {}) => origNewContext("viewport" in o || "screen" in o ? o : { ...o, viewport: null });
110
+ browser.newContext = (o = {}) => origNewContext(merge(o));
111
+ }
112
+ /** The engine release is only known once the executable is resolved, so the `--webrtc-ip` gate
113
+ * (engines older than ant0.3 turn non-proxied UDP back on with it) is applied by each caller to
114
+ * the assembled list, with the version `withRuntimeLaunch` reports. */
115
+ function personaPlatformFor(fp) {
116
+ return personaPlatformOf(fp.platform, fp.fingerprintProfile);
99
117
  }
100
118
  /** Assemble the final engine args from all layers: identity + extensions + proxy, the
101
119
  * Privacy-Sandbox-disable default, the WebRTC leak-proof default, and the user's own args — then
102
120
  * collapse all --enable-features/--disable-features into one each (Chromium keeps only the last). */
103
- function assembleArgs(fpArgs, extArgs, proxyArgs, disablePrivacySandbox, webrtcIp, userArgs, proxyForQuic, socks5Udp) {
104
- // webBluetoothArgs: Linux hosts hide navigator.bluetooth while exposing usb/serial/hid, an
105
- // OS-origin tell on a Windows persona. No-op off Linux.
106
- const base = [...fpArgs, ...extArgs, ...proxyArgs, ...quicArgs(proxyForQuic), ...socks5UdpArgs(socks5Udp, proxyForQuic), ...webBluetoothArgs()];
121
+ function assembleArgs(fpArgs, extArgs, proxyArgs, disablePrivacySandbox, webrtcIp, userArgs, proxyForQuic, socks5Udp, personaPlatform, pinDomStorage = false) {
122
+ assertNoReservedArgs(userArgs);
123
+ // webBluetoothArgs: a Linux host hides navigator.bluetooth while exposing usb/serial/hid, an
124
+ // OS-origin tell on a Windows or macOS persona. Emitted only for such a persona; a Linux persona
125
+ // or a no-persona launch must not have it (real Linux Chrome lacks it).
126
+ const base = [...fpArgs, ...extArgs, ...proxyArgs, ...quicArgs(proxyForQuic), ...socks5UdpArgs(socks5Udp, proxyForQuic), ...webBluetoothArgs(personaPlatform ?? null)];
107
127
  // DEFAULT FLIPPED IN 0.23.0 — opt IN to disabling, rather than opt out.
108
128
  //
109
129
  // Keep these APIs enabled unless the caller explicitly requests the de-Googled policy.
110
130
  if (disablePrivacySandbox === true)
111
131
  base.push(...privacySandboxArgs());
132
+ // Sync captures only the leveldb DOM storage backend. Direct spawns (serve/launchPlan) pin here;
133
+ // the Playwright launch paths pin inside withPlaywrightFeatureDefaults, only when Playwright's own
134
+ // disabled list is known (else this --disable-features would replace the whole list).
135
+ if (pinDomStorage)
136
+ base.push(...domStorageBackendArgs());
112
137
  base.push(...webrtcDefaultDenyArgs([...base, ...userArgs], webrtcIp));
113
138
  return mergeFeatureFlags([...base, ...userArgs]);
114
139
  }
140
+ /** `widevine: true`: seed the CDM into the profile and fix the launch args so the engine registers it
141
+ * (un-suppress the component updater, force the startup scan on Windows). Best-effort: a failure
142
+ * leaves DRM off and the launch proceeds. Returns the adjusted `ignoreDefaultArgs` and args. */
143
+ async function applyWidevineLaunch(userDataDir, ignoreDefaultArgs, userArgs, quiet) {
144
+ try {
145
+ await seedWidevine(userDataDir, { quiet });
146
+ // The --component-updater=fast-update scan is Windows-only (on Linux the hint file registers
147
+ // the CDM). Only warn about a user-supplied non-fast-update mode where fast-update matters.
148
+ const cu = userArgs.filter((a) => a.includes("component-updater"));
149
+ if (process.platform !== "linux" && cu.length && !cu.some((a) => a.includes("fast-update")) && !quiet) {
150
+ process.stderr.write("[ant0-browser] [widevine] note: your --component-updater mode may not register the CDM; --component-updater=fast-update is needed to scan the pre-installed component\n");
151
+ }
152
+ const tweak = widevineArgs(ignoreDefaultArgs, userArgs);
153
+ return { ignoreDefaultArgs: tweak.ignoreDefaultArgs, args: tweak.args };
154
+ }
155
+ catch (e) {
156
+ if (!quiet)
157
+ process.stderr.write(`[ant0-browser] [widevine] setup failed (continuing without DRM): ${String(e)}\n`);
158
+ return { ignoreDefaultArgs, args: userArgs };
159
+ }
160
+ }
115
161
  function applyIdentityOption(options) {
116
162
  const prepared = prepareIdentityOptions(options);
117
163
  return { options: prepared.options, identityMode: prepared.identityMode };
@@ -217,11 +263,19 @@ export async function launch(options = {}) {
217
263
  }
218
264
  return launchIncognito(restOpts);
219
265
  }
266
+ /** The engine release to judge advisory warnings by: the trusted release record, else (for a
267
+ * development build) its `-ant0.dev` label. Never used for a gate. */
268
+ function advisoryEngineVersion(resolved, exe) {
269
+ return resolved ?? readInstalledEngineVersion(exe, true);
270
+ }
220
271
  /** The pre-0.23 incognito launch, reached via `ephemeralProfile: false`. */
221
272
  async function launchIncognito(options = {}) {
273
+ return withTicketRetry((note) => launchIncognitoOnce({ ...options }, note));
274
+ }
275
+ async function launchIncognitoOnce(options, note) {
222
276
  const identity = applyIdentityOption(options);
223
277
  options = identity.options;
224
- const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args, humanize, showCursor, cacheDir, quiet, resolveFonts, launchTicket, engineVersion, ...rest } = options;
278
+ const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args, humanize, showCursor, cacheDir, quiet, resolveFonts, launchTicket, engineVersion, runtime, ...rest } = options;
225
279
  const { fingerprint, rest: pwOptions } = splitFingerprintOptions(rest);
226
280
  const proxyOpt = pwOptions.proxy; // captured before resolveProxy runs
227
281
  // resolveProxy throws for a credentialed SOCKS proxy (nothing in the stack can authenticate to
@@ -229,65 +283,94 @@ async function launchIncognito(options = {}) {
229
283
  const { args: proxyArgs, proxy } = resolveProxy(pwOptions.proxy);
230
284
  if (proxy === undefined)
231
285
  delete pwOptions.proxy;
232
- emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless: pwOptions.headless, _userArgs: args ?? [],
233
- _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0]);
234
- const exe = await executablePath({ executablePath: exeOption, cacheDir, quiet });
235
- ensureRunnableHere(exe);
236
- const headed = pwOptions.headless === false;
237
- // On Linux, point FONTCONFIG_FILE at the bundled metric-compatible clones (Segoe UI, Arial, …).
238
- const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
239
- const launchEnv = withShaderDialect(shaderDialect, fontLaunchEnv(exe, pwOptions.env, packDir));
240
- let engineArgs = assembleArgs(fingerprintArgs(fingerprint, true), extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, args ?? [], proxyOpt, socks5Udp);
241
- // Headless: screen.* has to be handled alongside the viewport or the window reports a geometry no
242
- // real browser can (see ./geometry.ts). Probe a copy — viewport/screen are context options, which
243
- // chromium.launch() does not take — and carry the result to newPage/newContext.
244
- const geom = headed
245
- ? null
246
- : identity.identityMode === "native"
247
- ? { mode: "native" }
248
- : applyHeadlessGeometry({ ...pwOptions }, fingerprint.fingerprint, engineArgs);
249
- engineArgs = initialWindowArgs(engineArgs, geom);
250
- // Engine patch 0037: the caller's ticket, or one from the local daemon (see ./launch-ticket.ts).
251
- engineArgs = [...engineArgs, ...(await resolveLaunchTicketArgs({ launchTicket, engineVersion, executable: exe, args: engineArgs, quiet }))];
252
- let browser;
253
- try {
254
- browser = await chromium.launch({
255
- // Drop Playwright's default --enable-automation so the engine's AutomationControlled feature
256
- // stays off (it flips webdriver-adjacent tells). Caller can override via ignoreDefaultArgs.
257
- ignoreDefaultArgs: ["--enable-automation"],
258
- ...pwOptions,
259
- executablePath: exe,
260
- ...(launchEnv ? { env: launchEnv } : {}),
261
- args: engineArgs,
262
- });
263
- }
264
- catch (error) {
265
- rethrowIfTicketRejected(error); // exit 90 + stderr line -> LaunchTicketRejectedError
266
- }
267
- if (headed) {
268
- installHeadedViewport(browser); // launch() takes no viewport option -> wrap newPage/newContext
269
- }
270
- else if (geom)
271
- installHeadlessGeometry(browser, geom);
272
- installHumanize(browser, { humanize, showCursor, seed: fingerprint.fingerprint }); // seed => stable motor persona
273
- return browser;
286
+ else
287
+ pwOptions.proxy = proxy;
288
+ // Refused before the engine is resolved, probed or any persona file is written.
289
+ assertNoReservedArgs(args ?? []);
290
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket, engineVersion, args: argsForTicketDecision(args, pwOptions.env), quiet }, async ({ executable: exe, ticketArgs, engineVersion: resolvedEngine }) => {
291
+ note(sdkFetchedTicket(launchTicket, ticketArgs));
292
+ ensureRunnableHere(exe);
293
+ // Emitted here, not before the engine is resolved: the GPU/canvas gap warnings depend on the engine release.
294
+ emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless: pwOptions.headless, _userArgs: args ?? [], _cacheDirGiven: cacheDir !== undefined,
295
+ _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0], advisoryEngineVersion(resolvedEngine, exe));
296
+ const headed = pwOptions.headless === false;
297
+ // On Linux, point FONTCONFIG_FILE at the bundled metric-compatible clones (Segoe UI, Arial, …).
298
+ const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
299
+ const launchEnv = withShaderDialect(shaderDialect, fontLaunchEnv(exe, pwOptions.env, packDir));
300
+ const dpr = personaDpr(fingerprint);
301
+ // Schema 4 personas travel in a private file (no profile dir here, so a temp dir, removed when the browser closes).
302
+ const staged = await stagePersonaProfile(fingerprint, exe);
303
+ emitPersonaNotices(staged.notices, quiet);
304
+ let launched = false;
305
+ try {
306
+ const sdkArgs = scaleWindowArgs(fingerprintArgs(staged.fingerprint, true), dpr, headed, personaAvail(fingerprint), args ?? []);
307
+ let engineArgs = gateWebrtcArgs(assembleArgs(sdkArgs, extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, args ?? [], proxyOpt, socks5Udp, personaPlatformFor(fingerprint)), resolvedEngine, quiet, Boolean(proxyOpt?.server));
308
+ // Headless: screen.* has to be handled alongside the viewport or the window reports a geometry no
309
+ // real browser can (see ./geometry.ts). Probe a copy — viewport/screen are context options, which
310
+ // chromium.launch() does not take — and carry the result to newPage/newContext.
311
+ const geom = headed
312
+ ? null
313
+ : identity.identityMode === "native"
314
+ ? { mode: "native" }
315
+ : applyHeadlessGeometry({ ...pwOptions }, fingerprint.fingerprint, engineArgs);
316
+ engineArgs = initialWindowArgs(engineArgs, geom);
317
+ // Engine patch 0037: the caller's ticket, or one from the local daemon (see ./launch-ticket.ts).
318
+ engineArgs = [...engineArgs, ...ticketArgs];
319
+ // Engine patch 949: the same ticket in ANT0_LAUNCH of the engine child (a copy of the env; never process.env).
320
+ const ticketed = applyTicketEnv(engineArgs, launchEnv, pwOptions.env);
321
+ engineArgs = withPlaywrightFeatureDefaults(ticketed.args, mergeIgnoreDefaultArgs(pwOptions.ignoreDefaultArgs, args), quiet);
322
+ const childEnv = ticketed.env;
323
+ let browser;
324
+ try {
325
+ browser = await chromium.launch({
326
+ // Drop Playwright's default --enable-automation so the engine's AutomationControlled feature
327
+ // stays off (it flips webdriver-adjacent tells). Caller can override via ignoreDefaultArgs.
328
+ ...pwOptions,
329
+ ignoreDefaultArgs: mergeIgnoreDefaultArgs(pwOptions.ignoreDefaultArgs, args),
330
+ executablePath: exe,
331
+ ...(childEnv ? { env: childEnv } : {}),
332
+ args: engineArgs,
333
+ });
334
+ }
335
+ catch (error) {
336
+ rethrowIfTicketRejected(error, launchSecretValues(engineArgs, [], childEnv)); // exit 90 / 91 + stderr line -> LaunchTicketRejectedError / PersonaFileRejectedError
337
+ }
338
+ if (headed) {
339
+ installHeadedViewport(browser, dpr); // launch() takes no viewport option -> wrap newPage/newContext
340
+ }
341
+ else if (geom)
342
+ installHeadlessGeometry(browser, geom, dpr);
343
+ installHumanize(browser, { humanize, showCursor, seed: fingerprint.fingerprint }); // seed => stable motor persona
344
+ staged.removeFile(); // the engine read it at startup: the file does not stay until the browser closes
345
+ browser.once("disconnected", () => staged.cleanup()); // the temp dir goes when the browser does (process exit is the fallback)
346
+ launched = true;
347
+ return browser;
348
+ }
349
+ finally {
350
+ if (!launched)
351
+ staged.cleanup();
352
+ }
353
+ });
274
354
  }
275
355
  /**
276
356
  * Launch Ant0 Browser with a persistent profile directory and return a Playwright
277
357
  * {@link BrowserContext} (cookies, storage, etc. persist in `userDataDir`).
278
358
  */
279
359
  export async function launchPersistentContext(userDataDir, options = {}) {
360
+ return withTicketRetry((note) => launchPersistentContextOnce(userDataDir, { ...options }, note));
361
+ }
362
+ async function launchPersistentContextOnce(userDataDir, options, note) {
280
363
  const identity = applyIdentityOption(options);
281
364
  options = identity.options;
282
- const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args, humanize, showCursor, cacheDir, quiet, widevine, resolveFonts, launchTicket, engineVersion, ...rest } = options;
365
+ const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args, humanize, showCursor, cacheDir, quiet, widevine, resolveFonts, launchTicket, engineVersion, runtime, ...rest } = options;
283
366
  const { fingerprint, rest: pwOptions } = splitFingerprintOptions(rest);
284
367
  const proxyOpt = pwOptions.proxy; // captured before resolveProxy runs
285
368
  // Throws for a credentialed SOCKS proxy (see resolveProxy); other shapes pass through unchanged.
286
369
  const { args: proxyArgs, proxy } = resolveProxy(pwOptions.proxy);
287
370
  if (proxy === undefined)
288
371
  delete pwOptions.proxy;
289
- emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless: pwOptions.headless, _userArgs: args ?? [],
290
- _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0]);
372
+ else
373
+ pwOptions.proxy = proxy;
291
374
  const opts = pwOptions;
292
375
  // headed + no explicit viewport -> disable the emulated viewport (impossible-window tell)
293
376
  const headedNoViewport = opts.headless === false
@@ -298,60 +381,68 @@ export async function launchPersistentContext(userDataDir, options = {}) {
298
381
  // disables it by default) so the engine registers it. Failure -> DRM gracefully off, launch proceeds.
299
382
  // Default the automation strip BEFORE the Widevine helper so it appends --disable-component-update
300
383
  // to ['--enable-automation'] rather than clobbering it (losing the strip). Caller's own wins.
301
- let ignoreDefaultArgs = opts.ignoreDefaultArgs ?? ["--enable-automation"];
384
+ let ignoreDefaultArgs = mergeIgnoreDefaultArgs(opts.ignoreDefaultArgs, args);
385
+ assertNoReservedArgs(args ?? []); // before the profile directory is touched, the engine probed or a persona written
302
386
  let userArgs = args ?? [];
303
387
  if (widevine) {
388
+ const wv = await applyWidevineLaunch(userDataDir, ignoreDefaultArgs, userArgs, quiet);
389
+ ignoreDefaultArgs = wv.ignoreDefaultArgs;
390
+ userArgs = wv.args;
391
+ }
392
+ delete opts.ignoreDefaultArgs; // passed explicitly below
393
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket, engineVersion, args: argsForTicketDecision(userArgs, opts.env), quiet }, async ({ executable: exe, ticketArgs, engineVersion: resolvedEngine }) => {
394
+ note(sdkFetchedTicket(launchTicket, ticketArgs));
395
+ ensureRunnableHere(exe);
396
+ // Emitted here, not before the engine is resolved: the GPU/canvas gap warnings depend on the engine release.
397
+ emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless: pwOptions.headless, _userArgs: args ?? [], _cacheDirGiven: cacheDir !== undefined,
398
+ _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0], advisoryEngineVersion(resolvedEngine, exe));
399
+ const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
400
+ const ctxEnv = withShaderDialect(shaderDialect, fontLaunchEnv(exe, opts.env, packDir));
401
+ const dpr = personaDpr(fingerprint);
402
+ // Schema 4 personas travel in a private file inside the profile directory.
403
+ const stagedPersona = await stagePersonaProfile(fingerprint, exe, userDataDir);
404
+ emitPersonaNotices(stagedPersona.notices, quiet);
405
+ const sdkArgs = scaleWindowArgs(fingerprintArgs(stagedPersona.fingerprint, true), dpr, opts.headless === false, personaAvail(fingerprint), userArgs);
406
+ let engineArgs = gateWebrtcArgs(assembleArgs(sdkArgs, extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, userArgs, proxyOpt, socks5Udp, personaPlatformFor(fingerprint)), resolvedEngine, quiet, Boolean(proxyOpt?.server));
407
+ // Native persona/profile geometry only needs viewport:null. A seedless headless launch receives
408
+ // corpus context geometry. Headed mode already set viewport:null above.
409
+ const geom = opts.headless === false
410
+ ? null
411
+ : identity.identityMode === "native"
412
+ ? { mode: "native" }
413
+ : applyHeadlessGeometry(opts, fingerprint.fingerprint, engineArgs);
414
+ if (identity.identityMode === "native" && opts.headless !== false && opts.viewport === undefined) {
415
+ opts.viewport = null;
416
+ }
417
+ engineArgs = initialWindowArgs(engineArgs, geom);
418
+ // A caller's (or the corpus) viewport emulates scale 1; give it the persona's scale.
419
+ Object.assign(opts, withDeviceScale(opts, dpr));
420
+ // Engine patch 0037: the caller's ticket, or one from the local daemon (see ./launch-ticket.ts).
421
+ engineArgs = [...engineArgs, ...ticketArgs];
422
+ // Engine patch 949: the same ticket in ANT0_LAUNCH of the engine child (a copy of the env; never process.env).
423
+ const ticketed = applyTicketEnv(engineArgs, ctxEnv, opts.env);
424
+ engineArgs = withPlaywrightFeatureDefaults(ticketed.args, ignoreDefaultArgs, quiet);
425
+ const childEnv = ticketed.env;
426
+ let context;
304
427
  try {
305
- await seedWidevine(userDataDir, { quiet });
306
- // The --component-updater=fast-update scan is Windows-only (on Linux the hint file registers
307
- // the CDM). Only warn about a user-supplied non-fast-update mode where fast-update matters.
308
- const cu = userArgs.filter((a) => a.includes("component-updater"));
309
- if (process.platform !== "linux" && cu.length && !cu.some((a) => a.includes("fast-update")) && !quiet) {
310
- process.stderr.write("[ant0-browser] [widevine] note: your --component-updater mode may not register the CDM; --component-updater=fast-update is needed to scan the pre-installed component\n");
311
- }
312
- const tweak = widevineArgs(ignoreDefaultArgs, userArgs);
313
- ignoreDefaultArgs = tweak.ignoreDefaultArgs;
314
- userArgs = tweak.args;
428
+ context = await chromium.launchPersistentContext(userDataDir, {
429
+ ...opts,
430
+ ignoreDefaultArgs, // keep AutomationControlled off (+ component updater on when widevine)
431
+ executablePath: exe,
432
+ ...(childEnv ? { env: childEnv } : {}),
433
+ args: engineArgs,
434
+ });
315
435
  }
316
- catch (e) {
317
- if (!quiet)
318
- process.stderr.write(`[ant0-browser] [widevine] setup failed (continuing without DRM): ${String(e)}\n`);
436
+ catch (error) {
437
+ stagedPersona.removeFile();
438
+ stagedPersona.cleanup(); // a no-op unless userDataDir was "" (a temp persona dir was made)
439
+ rethrowIfTicketRejected(error, launchSecretValues(engineArgs, [userDataDir], childEnv)); // exit 90 / 91 + stderr line -> LaunchTicketRejectedError / PersonaFileRejectedError
319
440
  }
320
- }
321
- delete opts.ignoreDefaultArgs; // passed explicitly below
322
- const exe = await executablePath({ executablePath: exeOption, cacheDir, quiet });
323
- ensureRunnableHere(exe);
324
- const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
325
- const ctxEnv = withShaderDialect(shaderDialect, fontLaunchEnv(exe, opts.env, packDir));
326
- let engineArgs = assembleArgs(fingerprintArgs(fingerprint, true), extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, userArgs, proxyOpt, socks5Udp);
327
- // Native persona/profile geometry only needs viewport:null. A seedless headless launch receives
328
- // corpus context geometry. Headed mode already set viewport:null above.
329
- const geom = opts.headless === false
330
- ? null
331
- : identity.identityMode === "native"
332
- ? { mode: "native" }
333
- : applyHeadlessGeometry(opts, fingerprint.fingerprint, engineArgs);
334
- if (identity.identityMode === "native" && opts.headless !== false && opts.viewport === undefined) {
335
- opts.viewport = null;
336
- }
337
- engineArgs = initialWindowArgs(engineArgs, geom);
338
- // Engine patch 0037: the caller's ticket, or one from the local daemon (see ./launch-ticket.ts).
339
- engineArgs = [...engineArgs, ...(await resolveLaunchTicketArgs({ launchTicket, engineVersion, executable: exe, args: engineArgs, quiet }))];
340
- let context;
341
- try {
342
- context = await chromium.launchPersistentContext(userDataDir, {
343
- ...opts,
344
- ignoreDefaultArgs, // keep AutomationControlled off (+ component updater on when widevine)
345
- executablePath: exe,
346
- ...(ctxEnv ? { env: ctxEnv } : {}),
347
- args: engineArgs,
348
- });
349
- }
350
- catch (error) {
351
- rethrowIfTicketRejected(error); // exit 90 + stderr line -> LaunchTicketRejectedError
352
- }
353
- installHumanizeOnContext(context, { humanize, showCursor, seed: fingerprint.fingerprint }); // seed => stable motor persona
354
- return context;
441
+ stagedPersona.removeFile(); // the engine read it at startup; nothing may be left in the kept profile
442
+ context.once("close", () => stagedPersona.cleanup());
443
+ installHumanizeOnContext(context, { humanize, showCursor, seed: fingerprint.fingerprint }); // seed => stable motor persona
444
+ return context;
445
+ });
355
446
  }
356
447
  /** A free ephemeral TCP port on loopback. */
357
448
  function freePort() {
@@ -366,11 +457,18 @@ function freePort() {
366
457
  });
367
458
  }
368
459
  /**
460
+ * Stale tickets: unlike {@link serve}, a plan cannot retry for you. If your child exits 90 with `claim_expired` or
461
+ * `claim_stale` and the ticket was the SDK-fetched one (you passed no ticket of your own), build a fresh plan (or call
462
+ * `plan.spawn()` again, which fetches a new ticket) and respawn ONCE; do not retry any other reason.
463
+ *
369
464
  * Resolve a {@link LaunchPlan} from {@link ServeOptions} without launching anything. This is the
370
465
  * first half of {@link serve}; a supervisor spawns `plan.executable` with `plan.args` and
371
466
  * `plan.env`, polls `plan.cdpUrl + "/json/version"` for readiness, and removes `plan.userDataDir`
372
467
  * on exit when `plan.ownUserDataDir` is true. Side effects: may create the temp profile dir and,
373
468
  * on Linux with a persona, resolve (and on first run download) the font pack.
469
+ *
470
+ * Spawn window: the plan carries a launch ticket that engines from ant0.11 accept only for about 5 minutes after it
471
+ * was issued. Spawn the plan promptly, and call `launchPlan` again for every (re)spawn; never respawn from an old plan.
374
472
  */
375
473
  export async function launchPlan(options = {}) {
376
474
  const identity = applyIdentityOption(options);
@@ -379,74 +477,166 @@ export async function launchPlan(options = {}) {
379
477
  humanize: _humanize, // Playwright-only; not applicable to a direct launch
380
478
  showCursor: _showCursor, ...launchOpts } = options;
381
479
  // Build the same stealth arg set as launch(); the caller launches the binary directly.
382
- const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args: userArgs, cacheDir, quiet, resolveFonts, launchTicket, engineVersion, ...rest } = launchOpts;
480
+ const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args: callerArgs, cacheDir, quiet, widevine, resolveFonts, launchTicket, engineVersion, runtime, ...rest } = launchOpts;
383
481
  const { fingerprint, rest: pwOptions } = splitFingerprintOptions(rest);
384
- const proxyOpt = pwOptions.proxy;
385
- const { args: proxyArgs } = resolveProxy(proxyOpt);
386
- emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless, _userArgs: userArgs ?? [],
387
- _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0]);
388
- const exe = await executablePath({ executablePath: exeOption, cacheDir, quiet });
389
- ensureRunnableHere(exe);
390
- const engineArgs = assembleArgs(fingerprintArgs(fingerprint, true), extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, userArgs ?? [], proxyOpt, socks5Udp);
391
- // Env before the temp dir: withShaderDialect throws on a bad dialect, and nothing must leak then.
392
- const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
393
- const rawEnv = { ...process.env, ...(withShaderDialect(shaderDialect, fontLaunchEnv(exe, undefined, packDir)) ?? {}) };
394
- const env = {};
395
- for (const [k, v] of Object.entries(rawEnv))
482
+ // The resolved proxy (a socks5h:// server is sent as socks5://); throws for a credentialed SOCKS one.
483
+ const { args: proxyArgs, proxy: proxyOpt } = resolveProxy(pwOptions.proxy);
484
+ // Playwright adds --no-sandbox unless chromiumSandbox is true; a direct spawn keeps Chromium's
485
+ // sandbox on by default and drops it only for an explicit false.
486
+ const noSandbox = pwOptions.chromiumSandbox === false;
487
+ const callerEnv = pwOptions.env;
488
+ assertNoReservedArgs(callerArgs ?? []); // before any temp dir, probe or persona file
489
+ let userArgs = callerArgs;
490
+ if (typeof launchTicket === "string" && !hasLaunchTicketArg(userArgs ?? []) && launchTicket.split(".").length !== 5) {
491
+ throw new SdkTypeError("sdk.launch_ticket_invalid", "launchTicket must be the five-segment value the daemon issues");
492
+ }
493
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket: manualBinary({ executablePath: exeOption }) ? launchTicket : false, engineVersion, args: argsForTicketDecision(userArgs, callerEnv), quiet }, async ({ executable: exe, ticketArgs, engineVersion: resolvedEngine }) => {
494
+ ensureRunnableHere(exe);
495
+ // Emitted here, not before the engine is resolved: the GPU/canvas gap warnings depend on the engine release.
496
+ emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless, _userArgs: userArgs ?? [], _cacheDirGiven: cacheDir !== undefined,
497
+ _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0], advisoryEngineVersion(resolvedEngine, exe));
498
+ // Env before the temp dir: withShaderDialect throws on a bad dialect, and nothing must leak then.
499
+ // Layered as launch() does: process.env < font wiring < caller env, then the shader dialect.
500
+ const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
501
+ const planEnv = (exePath) => {
502
+ // Both helpers already start from process.env and drop what the caller removed; spreading
503
+ // process.env underneath would bring a caller-removed variable back.
504
+ const layered = withShaderDialect(shaderDialect, fontLaunchEnv(exePath, callerEnv, packDir)) ?? process.env;
505
+ const out = {};
506
+ // undefined and null values are dropped (as Python drops None); the rest are stringified.
507
+ for (const [k, v] of Object.entries(layered))
508
+ if (v !== undefined && v !== null)
509
+ out[k] = String(v);
510
+ return out;
511
+ };
512
+ const env = planEnv(exe);
513
+ const resolvedPort = port ?? (await freePort());
514
+ const ownUserDataDir = !uddOption;
515
+ const userDataDir = uddOption ?? mkdtempSync(join(tmpdir(), "ant0-browser-serve-"));
516
+ // From here the plan's own temp dir exists; the caller takes ownership only once the plan is
517
+ // returned, so a throw before that point must remove it (nothing can, otherwise).
518
+ try {
519
+ // widevine: true seeds the CDM into the served profile before the args are built, as
520
+ // launchPersistentContext does (the component-updater switch it may add lands in the args).
521
+ if (widevine)
522
+ userArgs = (await applyWidevineLaunch(userDataDir, undefined, userArgs ?? [], quiet)).args;
523
+ // Ungated on purpose: spawn() resolves the engine again, and the `--webrtc-ip` gate must use
524
+ // the version of the binary that actually starts.
525
+ const stagedServe = await stagePersonaProfile(fingerprint, exe, userDataDir);
526
+ emitPersonaNotices(stagedServe.notices, quiet);
527
+ const rawEngineArgs = assembleArgs(scaleWindowArgs(fingerprintArgs(stagedServe.fingerprint, true), personaDpr(fingerprint), headless === false, personaAvail(fingerprint), userArgs ?? []), extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, userArgs ?? [], proxyOpt, socks5Udp, personaPlatformFor(fingerprint), true);
528
+ const engineArgs = gateWebrtcArgs(rawEngineArgs, resolvedEngine, quiet, Boolean(proxyOpt?.server));
529
+ const origins = allowOrigins ?? `http://${host}:${resolvedPort},http://localhost:${resolvedPort}`;
530
+ // Playwright's launch() adds the first-run hygiene switches itself; a direct spawn must add
531
+ // them, or the first tab is chrome://ungoogled-first-run (see FIRST_RUN_HYGIENE_ARGS).
532
+ const cdpArgs = [
533
+ `--remote-debugging-port=${resolvedPort}`,
534
+ `--remote-debugging-address=${host}`,
535
+ `--remote-allow-origins=${origins}`,
536
+ `--user-data-dir=${userDataDir}`,
537
+ ...FIRST_RUN_HYGIENE_ARGS,
538
+ ];
539
+ if (headless)
540
+ cdpArgs.push("--headless=new");
541
+ if (proxyOpt?.server) {
542
+ cdpArgs.push(`--proxy-server=${proxyOpt.server}`);
543
+ // A caller's own --proxy-bypass-list wins, as it does under Playwright (args come last).
544
+ if (!(userArgs ?? []).some((a) => String(a).startsWith("--proxy-bypass-list")))
545
+ cdpArgs.push(...proxyBypassArgs(proxyOpt));
546
+ }
547
+ if (noSandbox && !(userArgs ?? []).includes("--no-sandbox"))
548
+ cdpArgs.push("--no-sandbox");
549
+ // Chromium opens every positional as a URL; with none from the caller, open about:blank so the
550
+ // first tab is neutral. Appended last so a caller's URL positionals (inside engineArgs) win.
551
+ const startUrlArgs = defaultStartUrlArgs(engineArgs);
552
+ // Engine patch 0037: the caller's ticket (ant0d passes its own in `args`, which wins), or one
553
+ // from the local daemon; the last switch before the start URLs, as the daemon does it.
554
+ let spawned = false;
555
+ // Engine patch 949: the ticket also goes in ANT0_LAUNCH of the engine's environment. The plan's env carries it
556
+ // (a copy; process.env is not touched), so a supervisor that spawns the plan itself passes it on.
557
+ const ticketedPlan = ticketedPlanFor([...engineArgs, ...cdpArgs, ...ticketArgs, ...startUrlArgs], env, callerEnv);
558
+ return {
559
+ executable: exe,
560
+ args: ticketedPlan.args,
561
+ env: ticketedPlan.env,
562
+ userDataDir,
563
+ ownUserDataDir,
564
+ host,
565
+ port: resolvedPort,
566
+ cdpUrl: `http://${host}:${resolvedPort}`,
567
+ identityMode: identity.identityMode,
568
+ headless,
569
+ personaFile: stagedServe.fingerprint.fingerprintProfileFile,
570
+ removePersonaFile: () => stagedServe.removeFile(),
571
+ async spawn(spawnOptions = {}) {
572
+ if (spawned)
573
+ throw new SdkError("sdk.launch_plan_used", "This launch plan has already been used; create a fresh plan");
574
+ spawned = true;
575
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket, engineVersion, args: argsForTicketDecision(userArgs, callerEnv), quiet }, async (fresh) => {
576
+ // The engine that starts is the one that was checked: spawn() resolves the binary again, and a
577
+ // different one has not been probed for the persona's format and requirements.
578
+ if (fresh.executable !== exe)
579
+ await assertPersonaFitsEngine(fingerprint.fingerprintProfile, fresh.executable);
580
+ const freshEnv = planEnv(fresh.executable);
581
+ return new Promise((resolve, reject) => {
582
+ const freshPlan = ticketedPlanFor([...gateWebrtcArgs(rawEngineArgs, fresh.engineVersion, true, Boolean(proxyOpt?.server)), ...cdpArgs, ...fresh.ticketArgs, ...startUrlArgs], freshEnv, callerEnv);
583
+ const child = spawn(fresh.executable, freshPlan.args, { ...spawnOptions, env: freshPlan.env, stdio: spawnOptions.stdio ?? ["ignore", "ignore", "pipe"] });
584
+ child.once("error", reject);
585
+ child.once("spawn", () => resolve(child));
586
+ });
587
+ });
588
+ },
589
+ };
590
+ }
591
+ catch (error) {
592
+ if (ownUserDataDir) {
593
+ try {
594
+ rmSync(userDataDir, { recursive: true, force: true });
595
+ }
596
+ catch { /* keep the original error */ }
597
+ }
598
+ else
599
+ removeStalePersonaFile(userDataDir); // the persona file of a plan that never came to be
600
+ throw error;
601
+ }
602
+ });
603
+ }
604
+ /** `applyTicketEnv` for a plan: the env stays a plain string map. */
605
+ function ticketedPlanFor(args, env, callerEnv) {
606
+ const t = applyTicketEnv(args, env, callerEnv);
607
+ const out = {};
608
+ for (const [k, v] of Object.entries(t.env))
396
609
  if (v !== undefined)
397
- env[k] = String(v);
398
- const resolvedPort = port ?? (await freePort());
399
- const ownUserDataDir = !uddOption;
400
- const userDataDir = uddOption ?? mkdtempSync(join(tmpdir(), "ant0-browser-serve-"));
401
- const origins = allowOrigins ?? `http://${host}:${resolvedPort},http://localhost:${resolvedPort}`;
402
- // Playwright's launch() adds the first-run hygiene switches itself; a direct spawn must add
403
- // them, or the first tab is chrome://ungoogled-first-run (see FIRST_RUN_HYGIENE_ARGS).
404
- const cdpArgs = [
405
- `--remote-debugging-port=${resolvedPort}`,
406
- `--remote-debugging-address=${host}`,
407
- `--remote-allow-origins=${origins}`,
408
- `--user-data-dir=${userDataDir}`,
409
- ...FIRST_RUN_HYGIENE_ARGS,
410
- ];
411
- if (headless)
412
- cdpArgs.push("--headless=new");
413
- if (proxyOpt?.server)
414
- cdpArgs.push(`--proxy-server=${proxyOpt.server}`);
415
- // Chromium opens every positional as a URL; with none from the caller, open about:blank so the
416
- // first tab is neutral. Appended last so a caller's URL positionals (inside engineArgs) win.
417
- const startUrlArgs = defaultStartUrlArgs(engineArgs);
418
- // Engine patch 0037: the caller's ticket (ant0d passes its own in `args`, which wins), or one
419
- // from the local daemon; the last switch before the start URLs, as the daemon does it.
420
- const ticketArgs = await resolveLaunchTicketArgs({ launchTicket, engineVersion, executable: exe, args: engineArgs, quiet });
421
- return {
422
- executable: exe,
423
- args: [...engineArgs, ...cdpArgs, ...ticketArgs, ...startUrlArgs],
424
- env,
425
- userDataDir,
426
- ownUserDataDir,
427
- host,
428
- port: resolvedPort,
429
- cdpUrl: `http://${host}:${resolvedPort}`,
430
- identityMode: identity.identityMode,
431
- headless,
432
- };
610
+ out[k] = String(v);
611
+ return { args: t.args, env: out };
433
612
  }
434
- /** Handle for a standing ant0-browser CDP endpoint. Use `.cdpUrl` with any CDP client. */
613
+ /** Handle for a standing ant0-browser CDP endpoint. Use `.cdpUrl` with any CDP client.
614
+ *
615
+ * Cleanup: call `close()`. Ctrl+C / SIGTERM cleanup is the application's job (the SDK installs no
616
+ * signal handlers). If the process exits without it, an exit hook stops the browser (SIGTERM) and
617
+ * removes the temp profile dir `serve()` created; a `userDataDir` you passed is never deleted. */
435
618
  export class Server {
436
619
  proc;
437
620
  host;
438
621
  port;
439
622
  userDataDir;
440
623
  ownUdd;
624
+ graceMs;
441
625
  /** OS process id of the browser (undefined only if the spawn never produced one). */
442
626
  pid;
443
- constructor(proc, host, port, userDataDir, ownUdd) {
627
+ closing;
628
+ entry;
629
+ constructor(proc, host, port, userDataDir, ownUdd,
630
+ /** @internal How long close() waits after SIGTERM before it falls back to SIGKILL. */
631
+ graceMs = 5000) {
444
632
  this.proc = proc;
445
633
  this.host = host;
446
634
  this.port = port;
447
635
  this.userDataDir = userDataDir;
448
636
  this.ownUdd = ownUdd;
637
+ this.graceMs = graceMs;
449
638
  this.pid = proc.pid;
639
+ this.entry = track(proc, ownUdd ? userDataDir : undefined);
450
640
  }
451
641
  /** HTTP CDP base — pass to `connectOverCDP` / `puppeteer.connect({ browserURL })`. */
452
642
  get cdpUrl() {
@@ -465,21 +655,17 @@ export class Server {
465
655
  isAlive() {
466
656
  return this.proc.exitCode === null && !this.proc.killed;
467
657
  }
468
- async close() {
469
- try {
470
- this.proc.kill("SIGTERM");
471
- }
472
- catch {
473
- /* ignore */
474
- }
475
- if (this.ownUdd) {
476
- try {
477
- rmSync(this.userDataDir, { recursive: true, force: true });
478
- }
479
- catch {
480
- /* ignore */
481
- }
482
- }
658
+ /** Stop the browser (SIGTERM, SIGKILL only after a timeout), wait for it to exit, then remove the
659
+ * temp profile dir if serve() created it. The server stays registered for the exit hook until all
660
+ * of that has finished, so `srv.close(); process.exit(0)` without await still cleans up. */
661
+ close() {
662
+ this.closing ??= (async () => {
663
+ await stopChild(this.proc, this.graceMs);
664
+ if (this.ownUdd)
665
+ await removeOwnDir(this.userDataDir);
666
+ untrack(this.entry);
667
+ })();
668
+ return this.closing;
483
669
  }
484
670
  }
485
671
  /**
@@ -494,9 +680,12 @@ export class Server {
494
680
  * ```
495
681
  * Stays stealthy: the binary is launched **directly** (not through Playwright/Puppeteer), so the
496
682
  * `--enable-automation` flag those frameworks add is never present and `navigator.webdriver` stays
497
- * `false`; the engine's `Runtime.enable` neutralization keeps the attached CDP client undetectable
498
- * to the page; the port binds to loopback with an origin allowlist; attaching over CDP adds no
499
- * launch flags, so the served persona is preserved end to end.
683
+ * `false`; the engine's `Runtime.enable` patch (110) stops `Runtime.enable` from running page code
684
+ * (no console-argument serialization, live or replayed, so no getter, Proxy trap or `toString`
685
+ * fires), which removes the best-known CDP tell. It does not make an attached client
686
+ * undetectable: whatever the client itself adds (init scripts, exposed bindings, emulation
687
+ * overrides, other CDP domains) is still its own to hide; the port binds to loopback with an origin
688
+ * allowlist; attaching over CDP adds no launch flags, so the served persona is preserved end to end.
500
689
  *
501
690
  * First-run hygiene: Playwright's `launch()` passes `--no-first-run`, `--no-default-browser-check`
502
691
  * and `--disable-search-engine-choice-screen` on its own; `serve()`/`launchPlan()` add the same
@@ -508,8 +697,14 @@ export class Server {
508
697
  * call {@link launchPlan} with the same options and spawn from the returned plan instead.
509
698
  */
510
699
  export async function serve(options = {}) {
700
+ return withTicketRetry((note) => serveOnce({ ...options }, note));
701
+ }
702
+ async function serveOnce(options, note) {
511
703
  const { readyTimeoutMs = 30000, quiet } = options;
512
704
  const plan = await launchPlan(options);
705
+ // A ticket the SDK fetched (none of the caller's own forms is present) may be retried once if the engine finds it stale.
706
+ note(typeof options.launchTicket !== "string" && options.launchTicket !== false && !hasLaunchTicketArg(options.args ?? [])
707
+ && !callerEnvTicket(options.env) && launchTicketArgValue(plan.args) !== undefined);
513
708
  const { host, port: resolvedPort, userDataDir, ownUserDataDir: ownUdd } = plan;
514
709
  const dropOwnUdd = () => {
515
710
  if (ownUdd) {
@@ -524,24 +719,24 @@ export async function serve(options = {}) {
524
719
  let proc;
525
720
  let stderrTail = "";
526
721
  try {
527
- proc = await new Promise((resolve, reject) => {
528
- let settled = false;
529
- const child = spawn(plan.executable, plan.args, { env: plan.env, stdio: ["ignore", "ignore", "pipe"] });
530
- child.stderr?.on("data", (chunk) => { stderrTail = (stderrTail + chunk.toString("utf8")).slice(-8192); });
531
- child.once("error", (err) => { if (!settled) {
532
- settled = true;
533
- reject(err);
534
- } });
535
- child.once("spawn", () => { if (!settled) {
536
- settled = true;
537
- resolve(child);
538
- } });
539
- });
722
+ proc = await plan.spawn();
723
+ proc.stderr?.on("data", (chunk) => { stderrTail = (stderrTail + chunk.toString("utf8")).slice(-8192); });
540
724
  }
541
725
  catch (error) {
726
+ plan.removePersonaFile();
542
727
  dropOwnUdd();
543
- throw error;
728
+ throw redactError(error, launchSecretValues(plan.args, [userDataDir], plan.env)); // a spawn error carries `spawnargs`: the whole command line
544
729
  }
730
+ // From here the child and its temp dir are covered by the exit hook (and by abort() below), also
731
+ // while we wait for readiness; the Server takes over the registration once it exists.
732
+ const launch = track(proc, ownUdd ? userDataDir : undefined);
733
+ const abort = async () => {
734
+ plan.removePersonaFile();
735
+ await stopChild(proc, 500);
736
+ if (ownUdd)
737
+ await removeOwnDir(userDataDir);
738
+ untrack(launch);
739
+ };
545
740
  const deadline = Date.now() + readyTimeoutMs;
546
741
  let ready = false;
547
742
  while (Date.now() < deadline) {
@@ -558,21 +753,23 @@ export async function serve(options = {}) {
558
753
  await new Promise((r) => setTimeout(r, 250));
559
754
  }
560
755
  if (!ready) {
561
- try {
562
- proc.kill();
563
- }
564
- catch { /* ignore */ }
565
- dropOwnUdd();
756
+ await abort();
757
+ const secrets = launchSecretValues(plan.args, [userDataDir], plan.env);
758
+ stderrTail = dropPartialFirstLine(stderrTail, stderrTail.length >= 8192);
566
759
  const reason = launchTicketRejection(stderrTail);
567
760
  if (reason || proc.exitCode === LAUNCH_TICKET_EXIT_CODE) {
568
- throw new LaunchTicketRejectedError(reason ?? "missing", stderrTail.trim());
761
+ throw new LaunchTicketRejectedError(reason ?? "missing", redactLaunchSecrets(stderrTail.trim(), secrets));
569
762
  }
570
- throw new Error(`ant0-browser serve: CDP endpoint at ${plan.cdpUrl} did not come up within ${readyTimeoutMs}ms` +
763
+ const persona = personaFileRejection(stderrTail, proc.exitCode);
764
+ if (persona)
765
+ throw new PersonaFileRejectedError(persona);
766
+ throw new SdkError("sdk.engine_not_ready", `ant0-browser serve: CDP endpoint at ${plan.cdpUrl} did not come up within ${readyTimeoutMs}ms` +
571
767
  (proc.exitCode !== null ? ` (engine exited with code ${proc.exitCode})` : "") +
572
- (stderrTail.trim() ? `\n${stderrTail.trim()}` : ""));
768
+ (stderrTail.trim() ? `\n${redactLaunchSecrets(stderrTail.trim(), secrets)}` : ""));
573
769
  }
770
+ plan.removePersonaFile(); // the engine read it at startup
574
771
  const srv = new Server(proc, host, resolvedPort, userDataDir, ownUdd);
575
- process.once("exit", () => { void srv.close(); });
772
+ untrack(launch);
576
773
  if (!quiet) {
577
774
  process.stderr.write(`[ant0-browser] CDP endpoint ready: ${srv.cdpUrl}\n` +
578
775
  ` attach any client: connectOverCDP(${JSON.stringify(srv.cdpUrl)}) / puppeteer.connect({ browserURL })\n`);