ant0-browser 0.1.1 → 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 (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
@@ -0,0 +1,736 @@
1
+ /**
2
+ * Transport for schema 4 personas: a private file next to the browser profile.
3
+ *
4
+ * A schema 4 persona is far larger than the command line allows and must not sit in `ps` output, so
5
+ * it goes through `--fingerprint-profile-file=<absolute path>` and never inline. The file holds the
6
+ * same text the inline `--fingerprint-profile` switch carries today (gzip, then base64, of the
7
+ * persona's JSON; see `encodeProfile`). The engine reads it once, at startup.
8
+ *
9
+ * The SDK sends schema 4 only to an engine that says it can read it. `--ant0-sdk-info` reports
10
+ * `persona.schemas`; an engine that reports `sdk_protocol` 1, prints nothing, or cannot be run is
11
+ * taken to read `[2]` only. A schema 4 persona is then refused (`sdk.persona_requires_engine`);
12
+ * it is never converted down.
13
+ *
14
+ * Permissions. POSIX: the file is created with mode 0600 (owner read/write) through an exclusive
15
+ * temporary file in the same directory and `fchmod`ed (by handle) to 0600 again, then renamed over the target, so
16
+ * a reader sees the old or the new file, never a partial one. Windows: the same temporary-file and
17
+ * rename sequence, but the empty temporary file is restricted BEFORE any content is written: its
18
+ * inherited ACL is removed and replaced with a single entry that grants the current user (by SID,
19
+ * from `whoami /user`) full control (`icacls <file> /inheritance:r /grant:r *<SID>:F`). If that
20
+ * fails the write fails: the persona is never left readable by others. Known window: the empty file is
21
+ * created with the inherited ACL and restricted an instant later (Node cannot create it restricted); it holds
22
+ * nothing until the restriction has succeeded, but in that instant a principal that the inherited ACL lets read
23
+ * could open the empty file and keep its handle. The Python SDK has the same window. Closing it would need
24
+ * the security descriptor set at creation, or a private parent directory; neither is done.
25
+ *
26
+ * Probing the engine (`--ant0-sdk-info`) is asynchronous and bounded: a 5 s limit enforced with
27
+ * SIGKILL, a cap on the output, and the answer is taken when the process exits. The probe child gets
28
+ * the private probe directory as its TMPDIR/TMP/TEMP, so whatever an engine without the switch
29
+ * creates (a Chromium singleton socket, for one) is removed with it. A probe that ran to completion
30
+ * is cached by executable path, size and mtime; a completed old-engine answer (no schema 4) is
31
+ * cached for 10 minutes and a timeout for 30 s only, so an old engine does not cost 5 s per launch, a
32
+ * slow first run is retried soon, and a replaced or fixed engine is picked up. A spawn error is never cached.
33
+ * A binary without the Ant0 capability marker is never run: it has no persona support (a completed answer,
34
+ * cached like an old engine). The probe runs with a dead proxy (`--proxy-server=127.0.0.1:9`), and a probe child
35
+ * does not outlive the process (see `killLiveProbesSync` and `sweepStaleProbeDirs`).
36
+ */
37
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
38
+ import { randomBytes } from "node:crypto";
39
+ import { closeSync, constants, existsSync, fchmodSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
40
+ import { tmpdir } from "node:os";
41
+ import { basename, dirname, join, resolve } from "node:path";
42
+ import { isAnt0Binary } from "./download.js";
43
+ import { SdkError } from "./errors.js";
44
+ import { encodeProfile } from "./fingerprint.js";
45
+ import { assertPersonaProfileV4, isPersonaV4 } from "./persona-profile-v4.js";
46
+ import { debugLog } from "./warnings.js";
47
+ export { PROFILE_FILE_SWITCH } from "./fingerprint.js";
48
+ /** Engine switch that prints the capability record. */
49
+ export const SDK_INFO_SWITCH = "--ant0-sdk-info";
50
+ /** File name inside the user data directory. */
51
+ export const PROFILE_FILE_NAME = "ant0-persona.profile";
52
+ /** The persona schema this module transports. */
53
+ export const PERSONA_SCHEMA_FILE = 4;
54
+ /** Limits of the `--ant0-sdk-info` probe. */
55
+ export const SDK_INFO_TIMEOUT_MS = 5000;
56
+ export const SDK_INFO_MAX_BYTES = 1 << 20;
57
+ /** After the process exits, how long to wait for its stdout to close before using what was read. */
58
+ export const SDK_INFO_DRAIN_MS = 200;
59
+ /** Arguments that keep a probe of an engine without `--ant0-sdk-info` away from the user's profile and the
60
+ * network: a build that is not an Ant0 engine (Chrome for Testing, say) would otherwise start normally, reach
61
+ * out to the vendor and write to the real profile and certificate store within the 5 s. */
62
+ export const PROBE_DEAD_PROXY = "--proxy-server=127.0.0.1:9";
63
+ export const SDK_INFO_ISOLATION_ARGS = (userDataDir) => [
64
+ `--user-data-dir=${userDataDir}`, "--headless=new", "--no-first-run", "--no-default-browser-check",
65
+ "--disable-background-networking", "--disable-component-update", "--disable-breakpad", "--disable-crash-reporter",
66
+ // A dead proxy: whatever a foreign build still tries to reach has nowhere to go (port 9 is "discard").
67
+ PROBE_DEAD_PROXY,
68
+ ];
69
+ /** The probe child's environment: everything that points at a home or data directory is the probe dir, so a
70
+ * stock browser writes nothing under the real user's home (~/.config, ~/.local/share/pki, %APPDATA%). */
71
+ export function sdkInfoProbeEnv(probeDir, base = process.env) {
72
+ const dirs = ["HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME",
73
+ "XDG_CACHE_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"];
74
+ return { ...base, ...Object.fromEntries(dirs.map((k) => [k, probeDir])) };
75
+ }
76
+ /** A fresh private probe directory with a short path: a long TMPDIR makes Chromium fail with "Socket path
77
+ * too long" (a unix socket path holds about 100 characters, and the profile's singleton socket lives in it). */
78
+ export const PROBE_DIR_MAX_LENGTH = 60;
79
+ /** Distinctive enough that no unrelated directory carries it; `mkdtemp` adds 6 characters of `[A-Za-z0-9]`, and a
80
+ * probe directory without a record is only recognised by exactly that shape. */
81
+ export const PROBE_DIR_PREFIX = "ant0sdk-probe-";
82
+ const PROBE_DIR_SHAPE = new RegExp(`^${PROBE_DIR_PREFIX}[A-Za-z0-9]{6}$`);
83
+ export function makeProbeDir() {
84
+ const prefix = PROBE_DIR_PREFIX;
85
+ const base = tmpdir();
86
+ // 6 random characters follow the prefix, and the socket file name adds about 20 more.
87
+ const fits = (b) => join(b, prefix).length + 6 <= PROBE_DIR_MAX_LENGTH;
88
+ const root = fits(base) ? base : process.platform !== "win32" && existsSync("/tmp") ? "/tmp" : base;
89
+ return mkdtempSync(join(root, prefix));
90
+ }
91
+ /** How long to wait for `taskkill /T` on Windows before going on. */
92
+ export const TASKKILL_BOUND_MS = 3000;
93
+ /**
94
+ * KNOWN LIMITATION (Windows, not verified on Windows): on the drain path the probe's leader has already
95
+ * exited (a descendant still holds the stdout pipe), so `taskkill /T /F /PID <leader>` names a process that is
96
+ * gone. `taskkill /T` walks the tree from a live process, so it may report "not found" and leave the orphaned
97
+ * descendant running; the pid may even have been reused. The probe dir is still removed (a still-open file in
98
+ * it can make that removal incomplete), and a later `sweepStaleProbeDirs` retries it. Needs a check on a
99
+ * Windows machine before the behaviour is relied on. POSIX is not affected: the group id outlives the leader.
100
+ * See docs/FINGERPRINT-MODES.md ("Known limitations").
101
+ */
102
+ /** Stop the probe and everything it started. POSIX: the child leads its own process group, so the whole
103
+ * group gets SIGKILL (synchronous). Windows: `taskkill /T /F` takes the tree; the returned promise settles
104
+ * when it has finished or after `boundMs`, whichever is first. Best effort, never rejects. */
105
+ export function killProbeTree(child, boundMs = TASKKILL_BOUND_MS) {
106
+ const pid = child.pid;
107
+ if (pid === undefined)
108
+ return Promise.resolve();
109
+ if (process.platform === "win32") {
110
+ // The tree first (taskkill, awaited with a bound), then the leader: killing the leader first would
111
+ // orphan the children taskkill walks the tree from.
112
+ return new Promise((done) => {
113
+ let over = false;
114
+ const end = () => {
115
+ if (over)
116
+ return;
117
+ over = true;
118
+ clearTimeout(bound);
119
+ try {
120
+ child.kill("SIGKILL");
121
+ }
122
+ catch { /* already gone */ }
123
+ done();
124
+ };
125
+ const bound = setTimeout(end, boundMs);
126
+ try {
127
+ const k = spawn("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
128
+ k.once("error", end);
129
+ k.once("exit", end);
130
+ }
131
+ catch {
132
+ end();
133
+ }
134
+ });
135
+ }
136
+ try {
137
+ process.kill(-pid, "SIGKILL");
138
+ }
139
+ catch {
140
+ try {
141
+ child.kill("SIGKILL");
142
+ }
143
+ catch { /* already gone */ }
144
+ }
145
+ return Promise.resolve();
146
+ }
147
+ // Probes that are running now (pid -> probe dir). A process exit or a terminate request kills them and
148
+ // removes their dirs, so a probe child never outlives the SDK process; a SIGKILL of the SDK cannot be
149
+ // caught, and `sweepStaleProbeDirs` handles what that leaves behind on the next run.
150
+ const liveProbes = new Map();
151
+ const PROBE_INFO_FILE = ".ant0-probe.json";
152
+ function killLiveProbesSync() {
153
+ for (const [pid, dir] of liveProbes) {
154
+ try {
155
+ if (process.platform === "win32") {
156
+ spawnSync("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore", windowsHide: true, timeout: TASKKILL_BOUND_MS });
157
+ }
158
+ else
159
+ process.kill(-pid, "SIGKILL");
160
+ }
161
+ catch { /* already gone */ }
162
+ try {
163
+ rmSync(dir, { recursive: true, force: true });
164
+ }
165
+ catch { /* best effort */ }
166
+ }
167
+ liveProbes.clear();
168
+ }
169
+ /** A probe dir older than this belongs to a process that is gone (a probe lasts 5 s). */
170
+ export const STALE_PROBE_DIR_MS = 60 * 1000;
171
+ let swept = false;
172
+ /** Whether `pid` still runs with exactly `--user-data-dir=<dir>` among its arguments (so a recycled pid is
173
+ * never signalled). */
174
+ function pidRunsProbe(pid, dir) {
175
+ const wanted = `--user-data-dir=${dir}`;
176
+ try {
177
+ if (process.platform === "linux")
178
+ return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").includes(wanted);
179
+ if (process.platform === "win32")
180
+ return false; // cannot be checked cheaply: the dir is removed, no kill
181
+ const out = execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }).trim();
182
+ return ` ${out} `.includes(` ${wanted} `);
183
+ }
184
+ catch {
185
+ return false;
186
+ }
187
+ }
188
+ /** Remove probe directories (and kill the probe left in them) that an earlier SDK process abandoned when
189
+ * it was killed. Only our own `ant0sdk-probe-*` directories, owned by this user, older than
190
+ * `STALE_PROBE_DIR_MS`; one without a record (`.ant0-probe.json`) must also have exactly the shape `mkdtemp`
191
+ * produces, so an unrelated directory that merely starts with the prefix is never touched. Directories of earlier
192
+ * SDKs (`ant0-probe-*`) are NOT swept, record or not: they are left to the OS temp sweeper. Best effort,
193
+ * never throws; returns the directories removed. `roots`, `now` and `uid` exist for tests. */
194
+ export function sweepStaleProbeDirs(roots = [...new Set([tmpdir(), ...(process.platform !== "win32" ? ["/tmp"] : [])])], now = Date.now(), uid = typeof process.getuid === "function" ? process.getuid() : undefined) {
195
+ const removed = [];
196
+ for (const root of roots) {
197
+ let names;
198
+ try {
199
+ names = readdirSync(root).filter((n) => n.startsWith(PROBE_DIR_PREFIX));
200
+ }
201
+ catch {
202
+ continue;
203
+ }
204
+ for (const name of names) {
205
+ const dir = join(root, name);
206
+ try {
207
+ const st = lstatSync(dir);
208
+ if (!st.isDirectory() || (uid !== undefined && st.uid !== uid))
209
+ continue;
210
+ let startedAt = st.mtimeMs;
211
+ let pid;
212
+ let recorded = false;
213
+ try {
214
+ const info = JSON.parse(readFileSync(join(dir, PROBE_INFO_FILE), "utf8"));
215
+ recorded = typeof info === "object" && info !== null;
216
+ // never 0 or negative: `process.kill(-pid)` of those would signal a whole group
217
+ if (recorded && Number.isInteger(info.pid) && info.pid > 0)
218
+ pid = info.pid;
219
+ if (recorded && Number.isFinite(info.startedAt))
220
+ startedAt = info.startedAt;
221
+ }
222
+ catch { /* no record: the directory age decides */ }
223
+ if (!recorded && !PROBE_DIR_SHAPE.test(name))
224
+ continue; // not a directory this module made
225
+ if (now - startedAt < STALE_PROBE_DIR_MS)
226
+ continue;
227
+ if (pid !== undefined && pidRunsProbe(pid, dir)) {
228
+ try {
229
+ process.kill(-pid, "SIGKILL");
230
+ }
231
+ catch { /* gone */ }
232
+ }
233
+ rmSync(dir, { recursive: true, force: true });
234
+ removed.push(dir);
235
+ }
236
+ catch { /* best effort */ }
237
+ }
238
+ }
239
+ return removed;
240
+ }
241
+ /** Run `executable --ant0-sdk-info` without blocking the event loop. Never rejects. */
242
+ export function probeSdkInfo(executable, limits = {}) {
243
+ const timeoutMs = limits.timeoutMs ?? SDK_INFO_TIMEOUT_MS;
244
+ const maxBytes = limits.maxBytes ?? SDK_INFO_MAX_BYTES;
245
+ const drainMs = limits.drainMs ?? SDK_INFO_DRAIN_MS;
246
+ // Every Ant0 engine answers --ant0-sdk-info and exits; only a foreign build (Chrome for Testing, say) would
247
+ // start up. The capability marker every Ant0 binary carries tells them apart without running anything, so a
248
+ // binary without it is never run: it has no persona support. A path that cannot be read goes on to the
249
+ // spawn below, which fails the usual way.
250
+ if (limits.requireAnt0 !== false && existsSync(executable)) {
251
+ let ant0 = true;
252
+ try {
253
+ ant0 = isAnt0Binary(executable);
254
+ }
255
+ catch { /* unreadable: let the spawn decide */ }
256
+ if (!ant0)
257
+ return Promise.resolve({ completed: true, notAnt0: true, stdout: "" });
258
+ }
259
+ if (!swept) {
260
+ swept = true;
261
+ sweepStaleProbeDirs();
262
+ }
263
+ return new Promise((resolvePromise) => {
264
+ // An engine that does not know --ant0-sdk-info may start a normal browser; the isolating arguments
265
+ // keep that off the user's profile (a private, throwaway profile dir; headless; no first-run UI).
266
+ // An engine that knows the switch exits before it reads any of them (patch 005).
267
+ let probeDir;
268
+ try {
269
+ probeDir = makeProbeDir();
270
+ }
271
+ catch {
272
+ resolvePromise({ completed: false, stdout: "" });
273
+ return;
274
+ }
275
+ const removeProbeDir = () => { try {
276
+ rmSync(probeDir, { recursive: true, force: true });
277
+ }
278
+ catch { /* best effort */ } };
279
+ let child;
280
+ try {
281
+ // Everything the child creates in its temp directory lands in the probe dir and goes with it.
282
+ child = spawn(executable, [...SDK_INFO_ISOLATION_ARGS(probeDir), SDK_INFO_SWITCH], { stdio: ["ignore", "pipe", "ignore"], windowsHide: true, detached: process.platform !== "win32",
283
+ env: sdkInfoProbeEnv(probeDir) });
284
+ }
285
+ catch {
286
+ removeProbeDir();
287
+ resolvePromise({ completed: false, stdout: "" });
288
+ return;
289
+ }
290
+ const chunks = [];
291
+ let size = 0;
292
+ let exitCode;
293
+ let settled = false;
294
+ let drainTimer;
295
+ if (child.pid !== undefined) {
296
+ liveProbes.set(child.pid, probeDir);
297
+ try {
298
+ writeFileSync(join(probeDir, PROBE_INFO_FILE), JSON.stringify({ pid: child.pid, startedAt: Date.now() }));
299
+ }
300
+ catch { /* best effort */ }
301
+ ensureProcessHooks();
302
+ }
303
+ const kill = () => killProbeTree(child);
304
+ const finish = (completed, timedOut = false, reapGroup = false) => {
305
+ if (settled)
306
+ return;
307
+ settled = true;
308
+ clearTimeout(timer);
309
+ if (drainTimer)
310
+ clearTimeout(drainTimer);
311
+ // A grandchild may still hold the pipe; stop reading it, and stop whatever the probe left running.
312
+ try {
313
+ child.stdout?.destroy();
314
+ }
315
+ catch { /* ignore */ }
316
+ // Only when something may still be running (the drain timer fired because a descendant holds the
317
+ // pipe): after a clean close the group is empty and its id may already belong to someone else.
318
+ const killed = reapGroup ? kill() : Promise.resolve();
319
+ const ok = completed && exitCode === 0;
320
+ const result = { completed, ...(timedOut ? { timedOut } : {}), stdout: ok ? Buffer.concat(chunks).toString("utf8") : "" };
321
+ // On Windows the tree must be gone (taskkill awaited, with a bound) before its directory is removed.
322
+ void killed.then(() => {
323
+ if (child.pid !== undefined)
324
+ liveProbes.delete(child.pid);
325
+ removeProbeDir();
326
+ releaseProcessHooks();
327
+ resolvePromise(result);
328
+ });
329
+ };
330
+ const timer = setTimeout(() => finish(false, true, true), timeoutMs);
331
+ child.stdout?.on("data", (chunk) => {
332
+ size += chunk.length;
333
+ if (size > maxBytes) {
334
+ finish(false, true, true);
335
+ return;
336
+ }
337
+ chunks.push(chunk);
338
+ });
339
+ child.once("error", () => finish(false));
340
+ child.once("exit", (code) => {
341
+ exitCode = code;
342
+ drainTimer = setTimeout(() => finish(true, false, true), drainMs);
343
+ });
344
+ child.once("close", (code) => { exitCode = code; finish(true); });
345
+ });
346
+ }
347
+ /** How long a completed old-engine answer is remembered. A schema 4 answer is kept for good (it is keyed
348
+ * by size and mtime, so a replaced binary is probed again). */
349
+ export const OLD_ENGINE_CACHE_MS = 10 * 60 * 1000;
350
+ /** How long a timed-out probe is remembered. Short, because a just-installed engine can be slow on its
351
+ * first run (cold disk, antivirus) and must not be treated as old for long. */
352
+ export const PROBE_TIMEOUT_CACHE_MS = 30 * 1000;
353
+ const infoCache = new Map();
354
+ const copyInfo = (i) => JSON.parse(JSON.stringify(i));
355
+ /** What the engine at `executable` says about persona support. Never throws: unknown means schemas
356
+ * `[2]` and nothing else. The answer is cached per executable path, size and modification time: an
357
+ * engine that serves schema 4 for good, a completed old-engine answer for `OLD_ENGINE_CACHE_MS`, a
358
+ * timeout for `PROBE_TIMEOUT_CACHE_MS`. A spawn error is not cached and is retried on the next call. `now` exists for tests. */
359
+ export async function enginePersonaInfo(executable, probe = probeSdkInfo, now = Date.now) {
360
+ let key = executable;
361
+ try {
362
+ const st = statSync(executable);
363
+ key = `${executable}\0${st.size}\0${st.mtimeMs}`;
364
+ }
365
+ catch { /* the probe below fails the same way */ }
366
+ const hit = infoCache.get(key);
367
+ if (hit && hit.expiresAt > now())
368
+ return copyInfo(hit.info);
369
+ if (hit)
370
+ infoCache.delete(key);
371
+ let result;
372
+ try {
373
+ result = await probe(executable);
374
+ }
375
+ catch {
376
+ return { schemas: [2] };
377
+ }
378
+ const info = result.completed ? parseSdkInfo(result.stdout) : { schemas: [2] };
379
+ if (result.completed || result.timedOut) {
380
+ const modern = result.completed && info.schemas.includes(4);
381
+ const ttl = modern ? Infinity : result.completed ? OLD_ENGINE_CACHE_MS : PROBE_TIMEOUT_CACHE_MS;
382
+ infoCache.set(key, { info, expiresAt: modern ? Infinity : now() + ttl });
383
+ }
384
+ return copyInfo(info);
385
+ }
386
+ /** Persona schemas the engine at `executable` can load. Never throws: unknown means `[2]`. */
387
+ export async function enginePersonaSchemas(executable, probe = probeSdkInfo, now = Date.now) {
388
+ return (await enginePersonaInfo(executable, probe, now)).schemas;
389
+ }
390
+ /** Test hook: forget every cached probe answer. */
391
+ export function resetEngineProbeCache() { infoCache.clear(); }
392
+ function parseInfoObject(text) {
393
+ try {
394
+ const v = JSON.parse(text);
395
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : undefined;
396
+ }
397
+ catch {
398
+ return undefined;
399
+ }
400
+ }
401
+ const stringList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
402
+ /** Read the persona member out of `--ant0-sdk-info` output. Protocol 1 or a missing `persona` block
403
+ * means schemas `[2]` and nothing else. The record is one JSON object: the whole trimmed output, else
404
+ * the last line that is a complete JSON object (an engine may print a banner first). `sdk_protocol`
405
+ * and the numbers must be integers; a string such as "2" does not count. Unknown fields are ignored. */
406
+ export function parseSdkInfo(output) {
407
+ // A leading byte order mark (a Windows tool that writes UTF-8 with one) is not part of the record.
408
+ const text = output.trim(); // trim() also strips a leading U+FEFF (byte order mark)
409
+ let info = parseInfoObject(text);
410
+ if (info === undefined) {
411
+ const lines = text.split(/\r?\n/);
412
+ for (let i = lines.length - 1; i >= 0 && info === undefined; i--) {
413
+ const line = lines[i].trim();
414
+ if (line.startsWith("{") && line.endsWith("}"))
415
+ info = parseInfoObject(line);
416
+ }
417
+ }
418
+ if (info === undefined)
419
+ return { schemas: [2] };
420
+ const protocol = info.sdk_protocol;
421
+ if (!Number.isInteger(protocol) || protocol < 2)
422
+ return { schemas: [2] };
423
+ const persona = info.persona;
424
+ if (persona === null || typeof persona !== "object" || !Array.isArray(persona.schemas))
425
+ return { schemas: [2] };
426
+ const ints = persona.schemas.filter((n) => Number.isInteger(n));
427
+ if (!ints.length)
428
+ return { schemas: [2] };
429
+ const out = { schemas: ints };
430
+ if (Number.isInteger(persona.revision))
431
+ out.revision = persona.revision;
432
+ if (typeof persona.engine_family === "string")
433
+ out.engineFamily = persona.engine_family;
434
+ if (Number.isInteger(persona.engine_major))
435
+ out.engineMajor = persona.engine_major;
436
+ for (const [wire, field] of [["os", "os"], ["arch", "arch"], ["brands", "brands"], ["capabilities", "capabilities"]]) {
437
+ const list = stringList(persona[wire]);
438
+ if (list !== undefined)
439
+ out[field] = list;
440
+ }
441
+ return out;
442
+ }
443
+ /** Read the accepted persona schemas out of `--ant0-sdk-info` output (see `parseSdkInfo`). */
444
+ export function parseSdkInfoSchemas(output) {
445
+ return parseSdkInfo(output).schemas;
446
+ }
447
+ /** Throw `sdk.persona_requires_engine` unless the engine at `executable` can load schema 4. Returns
448
+ * what the engine said, for the checks that follow. */
449
+ export async function assertEngineAcceptsSchema4(executable, probe = probeSdkInfo) {
450
+ const info = await enginePersonaInfo(executable, probe);
451
+ if (!info.schemas.includes(4)) {
452
+ throw new SdkError("sdk.persona_requires_engine", "this identity uses the new persona format (schema_version 4), which this engine does not " +
453
+ "advertise in --ant0-sdk-info (persona.schemas). Use an engine that supports it; the persona " +
454
+ "is not converted to the older format.");
455
+ }
456
+ return info;
457
+ }
458
+ /** Identity ids are implicit in the engine (`CapabilityIsKnown`, patch 937): `os:*`, `engine:*`, `brand:*`
459
+ * and `arch:*` are accepted when the value is one the engine supports, and are not listed in
460
+ * persona.capabilities. Checked against the identity support the engine advertises; accepted when it
461
+ * does not advertise that list. An empty value is never known. Anything else must be a listed capability. */
462
+ function requireIsServed(id, served, info) {
463
+ if (served.has(id))
464
+ return true;
465
+ const m = /^(os|engine|brand|arch):(.*)$/.exec(id);
466
+ if (!m || m[2] === "")
467
+ return false;
468
+ const advertised = m[1] === "os" ? info.os : m[1] === "arch" ? info.arch : m[1] === "brand" ? info.brands
469
+ : info.engineFamily === undefined ? undefined : [info.engineFamily];
470
+ return advertised === undefined || advertised.includes(m[2]);
471
+ }
472
+ /** Throw `sdk.persona_capability_missing` unless the engine serves every id the persona `requires`.
473
+ * An engine that takes schema 4 but lists no capabilities cannot be checked and is refused too: it
474
+ * would otherwise run without the profile and say so only in a log line. */
475
+ export function assertEngineServesRequires(requires, info) {
476
+ if (info.capabilities === undefined) {
477
+ throw new SdkError("sdk.persona_capability_missing", "this engine accepts the new persona format (schema_version 4) but does not list its capabilities " +
478
+ "in --ant0-sdk-info (persona.capabilities), so the persona's requirements cannot be checked. " +
479
+ "Use an engine that reports them.");
480
+ }
481
+ const served = new Set(info.capabilities);
482
+ const missing = requires.filter((id) => !requireIsServed(id, served, info));
483
+ if (missing.length > 0) {
484
+ throw new SdkError("sdk.persona_capability_missing", `this persona requires capabilities the engine does not serve: ${missing.join(", ")}. The engine would ` +
485
+ "run without the profile. Use an engine that serves them, or a persona that does not require them.");
486
+ }
487
+ }
488
+ /** The engine refuses a persona file larger than this (patch 937). */
489
+ export const PERSONA_FILE_MAX_BYTES = 1 << 20;
490
+ /** Throw `sdk.persona_too_large` when the encoded persona would not be accepted from a file. */
491
+ export function assertPersonaFileSize(text) {
492
+ const bytes = Buffer.byteLength(text, "utf8");
493
+ if (bytes > PERSONA_FILE_MAX_BYTES) {
494
+ throw new SdkError("sdk.persona_too_large", `the encoded persona is ${bytes} bytes; the engine accepts a persona file of at most ` +
495
+ `${PERSONA_FILE_MAX_BYTES} bytes (1 MiB) and would run without the profile.`);
496
+ }
497
+ }
498
+ /** Code and text of the brand-version warning (same in the Python SDK). */
499
+ export const BRAND_VERSION_MAJOR_CODE = "persona-brand-version-major";
500
+ export function brandVersionNotice(profile, info) {
501
+ const brand = profile?.identity?.brand;
502
+ const version = brand?.version;
503
+ // The engine compares the major for Chrome and Edge only; other brands carry their own version.
504
+ if (brand?.id !== "chrome" && brand?.id !== "edge")
505
+ return undefined;
506
+ if (typeof version !== "string" || info.engineMajor === undefined)
507
+ return undefined;
508
+ const major = version.split(".")[0];
509
+ if (major === String(info.engineMajor))
510
+ return undefined;
511
+ return {
512
+ code: BRAND_VERSION_MAJOR_CODE,
513
+ message: `the persona's brand version ${version} has major ${major}, but this engine's major is ` +
514
+ `${info.engineMajor}. For Chrome and Edge the engine presents the brand version only when the majors match, ` +
515
+ "so the page will not show it. Use a persona issued for this engine's major.",
516
+ };
517
+ }
518
+ const runCommand = (file, args) => new Promise((res, rej) => {
519
+ execFile(file, args, { windowsHide: true, timeout: 15000, encoding: "utf8" }, (error, stdout) => (error ? rej(error) : res(String(stdout))));
520
+ });
521
+ /** The current user's SID from `whoami /user /fo csv /nh` (one line: "DOMAIN\\user","S-1-5-..."). */
522
+ export async function currentUserSid(run = runCommand) {
523
+ const out = await run("whoami", ["/user", "/fo", "csv", "/nh"]);
524
+ const fields = out.trim().split(/\r?\n/)[0]?.match(/"([^"]*)"/g)?.map((f) => f.slice(1, -1)) ?? [];
525
+ const sid = fields[1];
526
+ if (!sid || !/^S-1-\d+(-\d+)+$/.test(sid))
527
+ throw new Error("whoami did not return a SID");
528
+ return sid;
529
+ }
530
+ /** Remove inherited access from `path` and grant the current user, by SID, full control. */
531
+ export async function restrictToCurrentUserWindows(path, run = runCommand) {
532
+ try {
533
+ const sid = await currentUserSid(run);
534
+ await run("icacls", [path, "/inheritance:r", "/grant:r", `*${sid}:F`]);
535
+ }
536
+ catch (cause) {
537
+ throw new SdkError("sdk.profile_file_unsafe", `cannot restrict the persona file to the current user: ${path}`, { cause });
538
+ }
539
+ }
540
+ async function restrictToCurrentUser(path, fd, run, platform) {
541
+ if (platform !== "win32") {
542
+ fchmodSync(fd, 0o600); // by handle: no second path lookup
543
+ return;
544
+ }
545
+ await restrictToCurrentUserWindows(path, run);
546
+ }
547
+ /** Write `text` to `target` through a private temporary file in the same directory, then rename.
548
+ * The temporary file is created exclusively (O_EXCL never follows or reuses a planted path) and
549
+ * restricted to the current user before any content is written. The content goes through the handle
550
+ * from that exclusive create: re-opening the path is not needed, and on Windows a second open with
551
+ * O_TRUNC failed (EINVAL). A permission change does not affect a handle that is already open. */
552
+ async function writePrivateAtomic(target, text, run = runCommand, platform = process.platform) {
553
+ const temp = join(dirname(target), `.${basename(target)}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
554
+ let created = false;
555
+ let fd;
556
+ try {
557
+ fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
558
+ created = true;
559
+ await restrictToCurrentUser(temp, fd, run, platform);
560
+ const data = Buffer.from(text, "utf8");
561
+ let off = 0;
562
+ while (off < data.length)
563
+ off += writeSync(fd, data, off, data.length - off);
564
+ fsyncSync(fd);
565
+ const done = fd; // clear first: if closeSync throws, the finally must not close this number again
566
+ fd = undefined;
567
+ closeSync(done);
568
+ renameSync(temp, target);
569
+ created = false;
570
+ }
571
+ finally {
572
+ if (fd !== undefined) {
573
+ try {
574
+ closeSync(fd);
575
+ }
576
+ catch { /* already closed */ }
577
+ }
578
+ if (created) {
579
+ try {
580
+ unlinkSync(temp);
581
+ }
582
+ catch { /* already gone */ }
583
+ }
584
+ }
585
+ }
586
+ /** Write a schema 4 persona to `<userDataDir>/ant0-persona.profile` and return its absolute path.
587
+ * `run` and `platform` exist for tests. */
588
+ export async function writePersonaProfileFile(userDataDir, profile, run = runCommand, platform = process.platform) {
589
+ assertPersonaProfileV4(profile);
590
+ const text = encodeProfile(profile);
591
+ assertPersonaFileSize(text); // before anything is created
592
+ const dir = resolve(userDataDir);
593
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
594
+ const path = join(dir, PROFILE_FILE_NAME);
595
+ await writePrivateAtomic(path, text, run, platform);
596
+ return path;
597
+ }
598
+ /** Remove a stale `ant0-persona.profile` from `userDataDir`: only that exact name, and a symlink is
599
+ * unlinked itself, never followed. Best effort; returns whether something was removed. */
600
+ export function removeStalePersonaFile(userDataDir) {
601
+ if (!userDataDir)
602
+ return false; // "" means "no profile dir" (Playwright uses a temp dir); never the cwd
603
+ const path = join(resolve(userDataDir), PROFILE_FILE_NAME);
604
+ try {
605
+ lstatSync(path);
606
+ unlinkSync(path);
607
+ return true;
608
+ }
609
+ catch {
610
+ return false;
611
+ }
612
+ }
613
+ // Temporary persona directories still alive; removed at process exit as a last resort.
614
+ const liveTemps = new Set();
615
+ let exitHandlerInstalled = false;
616
+ function removeLiveTemps() {
617
+ for (const d of liveTemps) {
618
+ try {
619
+ rmSync(d, { recursive: true, force: true });
620
+ }
621
+ catch { /* best effort */ }
622
+ }
623
+ liveTemps.clear();
624
+ }
625
+ function cleanupEverything() {
626
+ removeLiveTemps();
627
+ killLiveProbesSync();
628
+ }
629
+ // Signal handlers exist only while something needs cleaning (a temp persona dir or a running probe), so an
630
+ // idle SDK never changes how the host app reacts to SIGINT or SIGTERM. A handler cleans up and then:
631
+ // - other listeners exist: does nothing more; they run, the host decides (the signal is not swallowed: it
632
+ // was delivered to them);
633
+ // - none exist: re-raises the signal, so the process ends the way it would have.
634
+ // Either way the handlers are removed once nothing needs cleaning.
635
+ const signalHandlers = new Map();
636
+ function ensureProcessHooks() {
637
+ if (!exitHandlerInstalled) {
638
+ exitHandlerInstalled = true;
639
+ process.on("exit", cleanupEverything);
640
+ }
641
+ for (const signal of ["SIGINT", "SIGTERM"]) {
642
+ const installed = signalHandlers.get(signal);
643
+ if (installed && process.listeners(signal).includes(installed))
644
+ continue; // (a host may have cleared its listeners)
645
+ const handler = () => {
646
+ cleanupEverything();
647
+ const others = process.listeners(signal).filter((l) => l !== handler);
648
+ // Nothing is left to clean, so no handler of ours stays: the host's own listeners (if any) run on their own.
649
+ releaseProcessHooks();
650
+ if (others.length === 0) {
651
+ try {
652
+ process.kill(process.pid, signal);
653
+ }
654
+ catch { /* best effort */ }
655
+ }
656
+ };
657
+ try {
658
+ process.on(signal, handler);
659
+ signalHandlers.set(signal, handler);
660
+ }
661
+ catch { /* not supported on this platform */ }
662
+ }
663
+ }
664
+ function releaseProcessHooks() {
665
+ if (liveTemps.size > 0 || liveProbes.size > 0)
666
+ return;
667
+ for (const [signal, handler] of signalHandlers)
668
+ process.removeListener(signal, handler);
669
+ signalHandlers.clear();
670
+ }
671
+ function registerTemp(dir) {
672
+ liveTemps.add(dir);
673
+ ensureProcessHooks();
674
+ }
675
+ /** Throw unless the engine at `executable` can load the persona and serves what it requires (a schema 2 or
676
+ * absent persona passes). For the binary a launch plan actually spawns when it is not the one staged for. */
677
+ export async function assertPersonaFitsEngine(profile, executable, probe = probeSdkInfo) {
678
+ if (typeof profile !== "object" || profile === null || !isPersonaV4(profile))
679
+ return;
680
+ const info = await assertEngineAcceptsSchema4(executable, probe);
681
+ assertEngineServesRequires(profile.requires, info);
682
+ }
683
+ /** Prepare the persona transport for one launch. A schema 2 or absent persona is returned
684
+ * untouched, and a stale persona file in `userDataDir` is removed. A schema 4 persona is checked
685
+ * against the engine and written to a private file in `userDataDir`, or, when the launch has no
686
+ * profile directory of its own (an incognito launch), in a private temporary directory that
687
+ * `cleanup()` removes (an empty `userDataDir` counts as none; callers run it when the browser closes; a process-exit handler is the
688
+ * fallback). */
689
+ export async function stagePersonaProfile(fingerprint, executable, userDataDir, deps = {}) {
690
+ const profile = fingerprint.fingerprintProfile;
691
+ if (typeof profile !== "object" || profile === null || !isPersonaV4(profile)) {
692
+ if (userDataDir)
693
+ removeStalePersonaFile(userDataDir);
694
+ return { fingerprint, notices: [], cleanup() { }, removeFile() { } };
695
+ }
696
+ assertPersonaProfileV4(profile);
697
+ const info = await assertEngineAcceptsSchema4(executable, deps.probe);
698
+ assertEngineServesRequires(profile.requires, info);
699
+ const notice = brandVersionNotice(profile, info);
700
+ if (profile.provenance?.noise_key === undefined) {
701
+ debugLog("the persona has no provenance.noise_key; the engine derives one from the document");
702
+ }
703
+ let temp;
704
+ // An empty path means "no profile directory of its own" (as Playwright reads it), never the cwd.
705
+ if (!userDataDir) {
706
+ temp = mkdtempSync(join(tmpdir(), "ant0-persona-"));
707
+ registerTemp(temp);
708
+ }
709
+ const dir = userDataDir || temp;
710
+ const cleanup = () => {
711
+ if (!temp)
712
+ return;
713
+ const d = temp;
714
+ temp = undefined;
715
+ liveTemps.delete(d);
716
+ try {
717
+ rmSync(d, { recursive: true, force: true });
718
+ }
719
+ finally {
720
+ releaseProcessHooks();
721
+ }
722
+ };
723
+ try {
724
+ const path = await writePersonaProfileFile(dir, profile, deps.run, deps.platform);
725
+ const removeFile = () => { try {
726
+ unlinkSync(path);
727
+ }
728
+ catch { /* already gone */ } };
729
+ return { fingerprint: { ...fingerprint, fingerprintProfileFile: path }, notices: notice ? [notice] : [], cleanup, removeFile };
730
+ }
731
+ catch (error) {
732
+ cleanup();
733
+ throw error;
734
+ }
735
+ }
736
+ //# sourceMappingURL=profile-file.js.map