camoucore 0.3.0 → 0.6.1

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 (168) hide show
  1. package/LICENSE +4 -3
  2. package/dist/camoufox/__main__.d.ts +10 -0
  3. package/dist/camoufox/__main__.js +1175 -0
  4. package/dist/camoufox/__version__.d.ts +31 -0
  5. package/dist/camoufox/__version__.js +32 -0
  6. package/dist/camoufox/_humanize_playwright.d.ts +54 -0
  7. package/dist/camoufox/_humanize_playwright.js +429 -0
  8. package/dist/camoufox/addons.d.ts +21 -0
  9. package/dist/camoufox/addons.js +56 -0
  10. package/dist/camoufox/async_api.d.ts +9 -0
  11. package/dist/camoufox/async_api.js +9 -0
  12. package/dist/camoufox/browser-pin.d.ts +46 -0
  13. package/dist/camoufox/browser-pin.js +96 -0
  14. package/dist/camoufox/cli.d.ts +7 -0
  15. package/dist/camoufox/cli.js +20 -0
  16. package/dist/camoufox/coherence.d.ts +141 -0
  17. package/dist/camoufox/coherence.js +708 -0
  18. package/dist/camoufox/data-files/browser-pin.json +7 -0
  19. package/dist/camoufox/data-files/essential-fonts.json +5 -0
  20. package/dist/camoufox/data-files/fingerprint-presets-v150.json +14544 -0
  21. package/dist/camoufox/data-files/fingerprint-presets.json +5192 -0
  22. package/dist/camoufox/data-files/font-bases.json +1887 -0
  23. package/dist/camoufox/data-files/font-groups.json +716 -0
  24. package/dist/camoufox/data-files/fonts.json +240 -0
  25. package/dist/camoufox/data-files/fpgen.yml +44 -0
  26. package/dist/camoufox/data-files/launcher-constants.json +66 -0
  27. package/dist/camoufox/data-files/media-devices.json +148 -0
  28. package/dist/camoufox/data-files/repos.yml +40 -0
  29. package/dist/camoufox/data-files/voice-manifests.json +1864 -0
  30. package/dist/camoufox/data-files/voice-uris.json +188 -0
  31. package/dist/camoufox/data-files/warnings.yml +132 -0
  32. package/dist/camoufox/display_profile.d.ts +17 -0
  33. package/dist/camoufox/display_profile.js +72 -0
  34. package/dist/camoufox/driver_defaults.d.ts +25 -0
  35. package/dist/camoufox/driver_defaults.js +114 -0
  36. package/dist/camoufox/exceptions.d.ts +78 -0
  37. package/dist/camoufox/exceptions.js +135 -0
  38. package/dist/camoufox/fingerprints.d.ts +341 -0
  39. package/dist/camoufox/fingerprints.js +1682 -0
  40. package/dist/camoufox/gpudisplay.d.ts +158 -0
  41. package/dist/camoufox/gpudisplay.js +695 -0
  42. package/dist/camoufox/host_rendering.d.ts +38 -0
  43. package/dist/camoufox/host_rendering.js +180 -0
  44. package/dist/camoufox/humanize.d.ts +89 -0
  45. package/dist/camoufox/humanize.js +143 -0
  46. package/dist/camoufox/index.d.ts +21 -0
  47. package/dist/camoufox/index.js +21 -0
  48. package/dist/camoufox/ip.d.ts +45 -0
  49. package/dist/camoufox/ip.js +114 -0
  50. package/dist/camoufox/multiversion.d.ts +131 -0
  51. package/dist/camoufox/multiversion.js +489 -0
  52. package/dist/camoufox/node-floor.d.ts +5 -0
  53. package/dist/camoufox/node-floor.js +17 -0
  54. package/dist/camoufox/paths.d.ts +45 -0
  55. package/dist/camoufox/paths.js +59 -0
  56. package/dist/camoufox/pkgman.d.ts +331 -0
  57. package/dist/camoufox/pkgman.js +972 -0
  58. package/dist/camoufox/product.d.ts +8 -0
  59. package/dist/camoufox/product.js +8 -0
  60. package/dist/camoufox/pycompat.d.ts +97 -0
  61. package/dist/camoufox/pycompat.js +458 -0
  62. package/dist/camoufox/server.d.ts +36 -0
  63. package/dist/camoufox/server.js +82 -0
  64. package/dist/camoufox/sync_api.d.ts +77 -0
  65. package/dist/camoufox/sync_api.js +194 -0
  66. package/dist/camoufox/utils.d.ts +515 -0
  67. package/dist/camoufox/utils.js +1995 -0
  68. package/dist/camoufox/warnings.d.ts +16 -0
  69. package/dist/camoufox/warnings.js +65 -0
  70. package/dist/camoufox/webgl.d.ts +52 -0
  71. package/dist/camoufox/webgl.js +264 -0
  72. package/dist/camouwolf/__main__.d.ts +10 -0
  73. package/dist/camouwolf/__main__.js +1180 -0
  74. package/dist/camouwolf/__version__.d.ts +31 -0
  75. package/dist/camouwolf/__version__.js +32 -0
  76. package/dist/camouwolf/_humanize_playwright.d.ts +53 -0
  77. package/dist/camouwolf/_humanize_playwright.js +427 -0
  78. package/dist/camouwolf/addons.d.ts +42 -0
  79. package/dist/camouwolf/addons.js +113 -0
  80. package/dist/camouwolf/async_api.d.ts +9 -0
  81. package/dist/camouwolf/async_api.js +9 -0
  82. package/dist/camouwolf/browser-pin.d.ts +46 -0
  83. package/dist/camouwolf/browser-pin.js +96 -0
  84. package/dist/camouwolf/cli.d.ts +7 -0
  85. package/dist/camouwolf/cli.js +20 -0
  86. package/dist/camouwolf/clienthints.d.ts +61 -0
  87. package/dist/camouwolf/clienthints.js +176 -0
  88. package/dist/camouwolf/coherence.d.ts +152 -0
  89. package/dist/camouwolf/coherence.js +554 -0
  90. package/dist/camouwolf/data-files/browser-pin.json +7 -0
  91. package/dist/camouwolf/data-files/camouwolf.defaults.json +118 -0
  92. package/dist/camouwolf/data-files/data/bundle-fonts.json +1983 -0
  93. package/dist/camouwolf/data-files/data/chrome-languages.json +517 -0
  94. package/dist/camouwolf/data-files/data/properties.json +321 -0
  95. package/dist/camouwolf/data-files/data/system-colors.json +35 -0
  96. package/dist/camouwolf/data-files/data/ubo.json +6 -0
  97. package/dist/camouwolf/data-files/fpgen.yml +41 -0
  98. package/dist/camouwolf/data-files/launcher-constants.json +26 -0
  99. package/dist/camouwolf/data-files/repos.yml +23 -0
  100. package/dist/camouwolf/data-files/warnings.yml +96 -0
  101. package/dist/camouwolf/driver_defaults.d.ts +25 -0
  102. package/dist/camouwolf/driver_defaults.js +114 -0
  103. package/dist/camouwolf/exceptions.d.ts +95 -0
  104. package/dist/camouwolf/exceptions.js +150 -0
  105. package/dist/camouwolf/fingerprints.d.ts +227 -0
  106. package/dist/camouwolf/fingerprints.js +753 -0
  107. package/dist/camouwolf/gpudisplay.d.ts +171 -0
  108. package/dist/camouwolf/gpudisplay.js +711 -0
  109. package/dist/camouwolf/host_rendering.d.ts +18 -0
  110. package/dist/camouwolf/host_rendering.js +114 -0
  111. package/dist/camouwolf/humanize.d.ts +84 -0
  112. package/dist/camouwolf/humanize.js +128 -0
  113. package/dist/camouwolf/index.d.ts +22 -0
  114. package/dist/camouwolf/index.js +21 -0
  115. package/dist/camouwolf/multiversion.d.ts +131 -0
  116. package/dist/camouwolf/multiversion.js +491 -0
  117. package/dist/camouwolf/node-floor.d.ts +5 -0
  118. package/dist/camouwolf/node-floor.js +17 -0
  119. package/dist/camouwolf/paths.d.ts +34 -0
  120. package/dist/camouwolf/paths.js +58 -0
  121. package/dist/camouwolf/pkgman.d.ts +331 -0
  122. package/dist/camouwolf/pkgman.js +972 -0
  123. package/dist/camouwolf/product.d.ts +3 -0
  124. package/dist/camouwolf/product.js +3 -0
  125. package/dist/camouwolf/pycompat.d.ts +92 -0
  126. package/dist/camouwolf/pycompat.js +461 -0
  127. package/dist/camouwolf/server.d.ts +36 -0
  128. package/dist/camouwolf/server.js +81 -0
  129. package/dist/camouwolf/switches.d.ts +77 -0
  130. package/dist/camouwolf/switches.js +222 -0
  131. package/dist/camouwolf/sync_api.d.ts +84 -0
  132. package/dist/camouwolf/sync_api.js +173 -0
  133. package/dist/camouwolf/utils.d.ts +644 -0
  134. package/dist/camouwolf/utils.js +2057 -0
  135. package/dist/camouwolf/warnings.d.ts +14 -0
  136. package/dist/camouwolf/warnings.js +59 -0
  137. package/dist/camouwolf/webgl.d.ts +41 -0
  138. package/dist/camouwolf/webgl.js +198 -0
  139. package/dist/data.d.ts +1 -1
  140. package/dist/data.js +3 -3
  141. package/dist/download.js +1 -1
  142. package/dist/exceptions.d.ts +1 -1
  143. package/dist/exceptions.js +1 -1
  144. package/dist/geolocation.js +1 -1
  145. package/dist/host.js +1 -1
  146. package/dist/ip.js +1 -1
  147. package/dist/locales.js +1 -1
  148. package/dist/mcp/cli.d.ts +15 -0
  149. package/dist/mcp/cli.js +108 -0
  150. package/dist/mcp/index.d.ts +8 -0
  151. package/dist/mcp/index.js +8 -0
  152. package/dist/mcp/main.d.ts +2 -0
  153. package/dist/mcp/main.js +8 -0
  154. package/dist/mcp/secrets.d.ts +50 -0
  155. package/dist/mcp/secrets.js +193 -0
  156. package/dist/mcp/server.d.ts +48 -0
  157. package/dist/mcp/server.js +653 -0
  158. package/dist/mcp/tree.d.ts +10 -0
  159. package/dist/mcp/tree.js +36 -0
  160. package/dist/passthrough.d.ts +1 -1
  161. package/dist/product.js +1 -1
  162. package/dist/settings.js +1 -1
  163. package/dist/telemetry.d.ts +0 -1
  164. package/dist/telemetry.js +5 -4
  165. package/dist/virtdisplay.d.ts +1 -1
  166. package/dist/virtdisplay.js +1 -1
  167. package/dist/warnings.js +1 -1
  168. package/package.json +57 -13
@@ -0,0 +1,1682 @@
1
+ /**
2
+ * The identity layer: fpgen fingerprints and real presets turned into a
3
+ * Camoufox config, the per-identity draws (fonts, voices, media devices, GPU)
4
+ * and the geometry / arch corrections applied on top of both.
5
+ *
6
+ * TypeScript twin of python/camoucore/src/camoucore/camoufox/fingerprints.py. Every seeded draw is
7
+ * bit-for-bit the Python one -- `random.Random(seed)` is the python-random package, and
8
+ * identitySalt() hashes the same orjson bytes -- so one config and salt
9
+ * present one identity whichever launcher built it. Unseeded Python draws
10
+ * (`random.randint`, `random.choice`) go through python-random's
11
+ * module-level functions, the twin of Python's module-level generator.
12
+ */
13
+ import { createHash, randomBytes } from "node:crypto";
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import { generate, InvalidConstraints } from "fpgen-js";
17
+ import * as random from "python-random";
18
+ import { supported as cpuAffinitySupported, hostCoreCount, } from "../cpu_affinity.js";
19
+ import { validateIP, validIPv4 } from "../ip.js";
20
+ import { normalizeLocale } from "../locales.js";
21
+ import { hardwareCpu, intelMacCores } from "./coherence.js";
22
+ import { LAUNCHER_CONSTANTS, LOCAL_DATA, loadDataFile } from "./paths.js";
23
+ import { comparePyStr, crc32, isPlainObject, isPyError, KeyError, num, orjsonDumps, pyStr, pySum, pySumFloats, pyTruthy, ValueError, } from "./pycompat.js";
24
+ import { FallbackWarning, loadWarnings, warn } from "./warnings.js";
25
+ import { sampleWebglForScreen, webglForGpu } from "./webgl.js";
26
+ export const SUPPORTED_OS = ["linux", "macos", "windows"];
27
+ /** The fpgen -> Camoufox config mapping. */
28
+ export const FPGEN_DATA = loadDataFile("fpgen.yml");
29
+ // fpgen's OS names, from Camoufox's.
30
+ export const FPGEN_OS = {
31
+ lin: "Linux",
32
+ linux: "Linux",
33
+ mac: "macOS",
34
+ macos: "macOS",
35
+ win: "Windows",
36
+ windows: "Windows",
37
+ };
38
+ /** Python dict.get(key, default): the default only when the key is absent. */
39
+ function get(config, key, dflt = undefined) {
40
+ return Object.hasOwn(config, key) ? config[key] : dflt;
41
+ }
42
+ function isNone(value) {
43
+ return value === null || value === undefined;
44
+ }
45
+ /**
46
+ * A bound on the screen a generated fingerprint may claim (the twin of the
47
+ * Python dataclass that replaced browserforge's Screen).
48
+ */
49
+ export class Screen {
50
+ minWidth;
51
+ maxWidth;
52
+ minHeight;
53
+ maxHeight;
54
+ constructor({ minWidth = null, maxWidth = null, minHeight = null, maxHeight = null, } = {}) {
55
+ this.minWidth = minWidth;
56
+ this.maxWidth = maxWidth;
57
+ this.minHeight = minHeight;
58
+ this.maxHeight = maxHeight;
59
+ }
60
+ /**
61
+ * The bound as fpgen conditions: one predicate over the whole screen node.
62
+ * fpgen resolves screen.width and screen.height to that same node and each
63
+ * condition resets its evidence (build_evidence), so with one per field
64
+ * only the height bound held and 1280x1024 met a 1300 px minimum width.
65
+ */
66
+ asConditions() {
67
+ const { minWidth: loW, maxWidth: hiW, minHeight: loH, maxHeight: hiH, } = this;
68
+ if (loW === null && hiW === null && loH === null && hiH === null)
69
+ return {};
70
+ const within = (v, lo, hi) => typeof v === "number" &&
71
+ Number.isInteger(v) &&
72
+ (lo === null || v >= lo) &&
73
+ (hi === null || v <= hi);
74
+ return {
75
+ screen: (s) => {
76
+ if (typeof s !== "object" || s === null)
77
+ return false;
78
+ const { width, height } = s;
79
+ return within(width, loW, hiW) && within(height, loH, hiH);
80
+ },
81
+ };
82
+ }
83
+ /** dataclasses.asdict(), with the Python field names (for identitySalt). */
84
+ toPyDict() {
85
+ return {
86
+ min_width: this.minWidth,
87
+ max_width: this.maxWidth,
88
+ min_height: this.minHeight,
89
+ max_height: this.maxHeight,
90
+ };
91
+ }
92
+ }
93
+ export const PRESETS_FILE = path.join(LOCAL_DATA, "fingerprint-presets.json");
94
+ export const PRESETS_V150_FILE = path.join(LOCAL_DATA, "fingerprint-presets-v150.json");
95
+ /** Firefox major version at which the v150 preset bundle becomes preferred. */
96
+ export const PRESETS_V150_MIN_FF = 149;
97
+ const PRESETS_CACHE = new Map();
98
+ // ---------------------------------------------------------------------------
99
+ // Fonts
100
+ // ---------------------------------------------------------------------------
101
+ // CreepJS OS marker fonts used for OS detection (see fingerprints.py).
102
+ export const MACOS_MARKER_FONTS = LAUNCHER_CONSTANTS.markerFonts.mac;
103
+ export const LINUX_MARKER_FONTS = LAUNCHER_CONSTANTS.markerFonts.lin;
104
+ export const WINDOWS_MARKER_FONTS = LAUNCHER_CONSTANTS.markerFonts.win;
105
+ /** Add any missing marker fonts to the font list (in place). */
106
+ function ensureMarkerFonts(fonts, markers) {
107
+ const existing = new Set(fonts);
108
+ for (const m of markers) {
109
+ if (!existing.has(m))
110
+ fonts.push(m);
111
+ }
112
+ }
113
+ let osFontsCache = null;
114
+ /** The full OS font lists (fonts.json). */
115
+ export function loadOsFonts() {
116
+ osFontsCache ??= loadDataFile("fonts.json");
117
+ return osFontsCache;
118
+ }
119
+ // The OS BASE font sets that must always be reported: every family a real
120
+ // machine of that OS ships by default, intersected with fonts.json (see
121
+ // fingerprints.py for the sources). essential-fonts.json is the file
122
+ // pythonlib reads, so the two launchers cannot disagree on them.
123
+ const ESSENTIAL_FONTS = loadDataFile("essential-fonts.json");
124
+ export const ESSENTIAL_FONTS_MACOS = ESSENTIAL_FONTS.mac;
125
+ export const ESSENTIAL_FONTS_WINDOWS = ESSENTIAL_FONTS.win;
126
+ export const ESSENTIAL_FONTS_LINUX = ESSENTIAL_FONTS.lin;
127
+ /**
128
+ * Fonts only a Windows 11 base has: a Windows identity whose font list
129
+ * contains them presents Windows 11, and the rest of the identity must agree.
130
+ */
131
+ export const WINDOWS_11_MARKER_FONTS = new Set(LAUNCHER_CONSTANTS.windows11MarkerFonts);
132
+ /**
133
+ * The entropy that makes identitySeed() belong to ONE identity.
134
+ *
135
+ * Pass whatever the caller pinned the identity with -- an fpgen fingerprint,
136
+ * a preset, the caller's own config -- for a salt that is stable across
137
+ * launches of that identity; pass nothing for a fresh, random one. The salt
138
+ * is the first 8 bytes (big-endian) of the SHA-256 of the orjson
139
+ * serialization with sorted keys, exactly as Python computes it, so a pinned
140
+ * identity draws the same fonts, voices, GPU and noise seeds in both
141
+ * launchers. (Integral floats and integers above 2**53 only hash like
142
+ * Python's when they arrive as PyFloat / bigint -- see pycompat.parsePyJson.)
143
+ */
144
+ export function identitySalt(pinned) {
145
+ if (pinned === null || pinned === undefined) {
146
+ return randomBytes(8).readBigUInt64BE(0);
147
+ }
148
+ const blob = Buffer.from(orjsonDumps(pinned), "utf-8");
149
+ return createHash("sha256").update(blob).digest().readBigUInt64BE(0);
150
+ }
151
+ /** The browser's version in a UA: "rv:158.0" and "Firefox/158.0". */
152
+ const UA_VERSION = /(rv:|Firefox\/)[0-9][0-9.]*/g;
153
+ /**
154
+ * The UA with the browser's version taken out, for identitySeed(). A saved
155
+ * identity on a newer browser claims the new engine version and nothing else
156
+ * changes, so the seed must not move with it (Python: versionless_ua).
157
+ */
158
+ export function versionlessUa(userAgent) {
159
+ return userAgent.replace(UA_VERSION, "$1");
160
+ }
161
+ /**
162
+ * A seed for the per-identity draws: a pure function of the presented
163
+ * identity (UA without its version, platform, screen, cores) and its salt --
164
+ * zlib.crc32 of the values' Python str() joined by "|".
165
+ */
166
+ export function identitySeed(config, salt = 0) {
167
+ const parts = [
168
+ versionlessUa(pyStr(get(config, "navigator.userAgent", ""))),
169
+ pyStr(get(config, "navigator.platform", "")),
170
+ pyStr(get(config, "screen.width", "")),
171
+ pyStr(get(config, "screen.height", "")),
172
+ pyStr(get(config, "navigator.hardwareConcurrency", "")),
173
+ // not the GPU: it is sampled after the font draw in launchOptions
174
+ pyStr(salt),
175
+ ];
176
+ return crc32(parts.join("|"));
177
+ }
178
+ /**
179
+ * audio:seed is gone: the browser renders audio as stock Firefox does. A
180
+ * caller's seed is dropped with a warning rather than sent to a browser that
181
+ * would noise with it (a released one) or ignore it (this one).
182
+ */
183
+ export function dropAudioSeed(config) {
184
+ if ("audio:seed" in config) {
185
+ delete config["audio:seed"];
186
+ warn(loadWarnings().audio_seed_removed, "FutureWarning");
187
+ }
188
+ }
189
+ /** A seeded generator for a draw, or a fresh OS-seeded one when unseeded. */
190
+ function rng(seed) {
191
+ return new random.Random(seed ?? null);
192
+ }
193
+ let fontGroupsCache = null;
194
+ /** The addition units per OS (font-groups.json), each with its own probability. */
195
+ function loadFontGroups() {
196
+ if (!fontGroupsCache) {
197
+ try {
198
+ fontGroupsCache =
199
+ loadDataFile("font-groups.json");
200
+ }
201
+ catch (e) {
202
+ if (!isPyError(e, "OSError", "ValueError"))
203
+ throw e;
204
+ FallbackWarning.warn("Reading font-groups.json", "an OS-version base with no font additions", e);
205
+ fontGroupsCache = {};
206
+ }
207
+ }
208
+ return fontGroupsCache;
209
+ }
210
+ let fontBasesCache = null;
211
+ /** The OS-version bases per OS (font-bases.json), drawn entire by weight. */
212
+ function loadFontBases() {
213
+ if (!fontBasesCache) {
214
+ try {
215
+ fontBasesCache =
216
+ loadDataFile("font-bases.json");
217
+ }
218
+ catch (e) {
219
+ if (!isPyError(e, "OSError", "ValueError"))
220
+ throw e;
221
+ FallbackWarning.warn("Reading font-bases.json", "only the always-present core fonts as its OS base", e);
222
+ fontBasesCache = {};
223
+ }
224
+ }
225
+ return fontBasesCache;
226
+ }
227
+ /**
228
+ * Draw the OS version a machine runs (a font-bases.json entry) by its
229
+ * real-world weight (`_pick_release`). It is the identity's first draw, so the
230
+ * font list and the voice list, drawn from the same seed, land on the same
231
+ * version.
232
+ */
233
+ function pickRelease(osKey, r) {
234
+ const bases = loadFontBases()[osKey] ?? [];
235
+ if (!bases.length)
236
+ return null;
237
+ const roll = r.random();
238
+ let cumulative = 0.0;
239
+ for (const base of bases) {
240
+ cumulative += base.weight ?? 0.0;
241
+ if (roll < cumulative)
242
+ return base;
243
+ }
244
+ return bases[bases.length - 1];
245
+ }
246
+ function localeMatches(locale, required) {
247
+ return (locale ?? "").toLowerCase().startsWith(required.toLowerCase());
248
+ }
249
+ /** The additions this machine has, each unit judged on its own probability. */
250
+ function drawUnits(osKey, r, exclude, locale) {
251
+ const out = [];
252
+ for (const unit of loadFontGroups()[osKey] ?? []) {
253
+ const required = unit.requiresLocale;
254
+ if (required && !localeMatches(locale, required))
255
+ continue;
256
+ if (r.random() >= (unit.prob ?? 0.0))
257
+ continue;
258
+ let members = unit.fonts.filter((f) => !exclude.has(f));
259
+ if (!members.length)
260
+ continue;
261
+ if (unit.kind === "alacarte") {
262
+ const sizes = unit.sizes?.length
263
+ ? unit.sizes
264
+ : [{ n: members.length, w: 1.0 }];
265
+ const roll = r.random() * pySumFloats(sizes.map((s) => s.w));
266
+ let cumulative = 0.0;
267
+ let count = sizes[sizes.length - 1].n;
268
+ for (const size of sizes) {
269
+ cumulative += size.w;
270
+ if (roll < cumulative) {
271
+ count = size.n;
272
+ break;
273
+ }
274
+ }
275
+ count = Math.max(1, Math.min(count, members.length));
276
+ members = r.sample(members, count);
277
+ }
278
+ out.push(...members);
279
+ }
280
+ return out;
281
+ }
282
+ /** Whether the host itself ships the OS-version font variant (native identities only). */
283
+ function hostHasVariantFonts(targetOs) {
284
+ if (targetOs !== "windows")
285
+ return false;
286
+ const fontsDir = path.join(process.env.WINDIR || "C:\\Windows", "Fonts");
287
+ // SegUIVar.ttf is Segoe UI Variable: on every Windows 11 and on no Windows 10.
288
+ return fs.existsSync(path.join(fontsDir, "SegUIVar.ttf"));
289
+ }
290
+ const OS_TO_KEY = {
291
+ macos: "mac",
292
+ windows: "win",
293
+ linux: "lin",
294
+ };
295
+ function osKeyOf(targetOs) {
296
+ return OS_TO_KEY[targetOs] ?? "mac";
297
+ }
298
+ /**
299
+ * The font list of one plausible machine of the given OS
300
+ * (`_generate_random_font_subset`): one OS-version base by weight, never
301
+ * subsetted, then each addition unit at its own measured probability, then
302
+ * the marker fonts.
303
+ *
304
+ * @param locale gates the units the manifest marks `requiresLocale`.
305
+ * @param native the identity is the host's own OS (macOS / Windows), where the
306
+ * real system fonts are used: only the OS base is claimed.
307
+ */
308
+ export function generateRandomFontSubset(targetOs, seed, native = false, locale) {
309
+ const r = rng(seed);
310
+ const osFontsData = loadOsFonts();
311
+ const osKey = osKeyOf(targetOs);
312
+ const fullList = osFontsData[osKey] ?? osFontsData.mac ?? [];
313
+ let essential;
314
+ let markers;
315
+ if (targetOs === "windows") {
316
+ essential = new Set(ESSENTIAL_FONTS_WINDOWS);
317
+ markers = WINDOWS_MARKER_FONTS;
318
+ }
319
+ else if (targetOs === "linux") {
320
+ essential = new Set(ESSENTIAL_FONTS_LINUX);
321
+ markers = LINUX_MARKER_FONTS;
322
+ }
323
+ else {
324
+ essential = new Set(ESSENTIAL_FONTS_MACOS);
325
+ markers = MACOS_MARKER_FONTS;
326
+ }
327
+ if (native) {
328
+ let result = fullList.filter((f) => essential.has(f));
329
+ const full = new Set(fullList);
330
+ result.push(...[...essential].filter((f) => !full.has(f)).sort(comparePyStr));
331
+ // A native identity may run on a Windows 10 host, which cannot render
332
+ // the Windows 11 families the base carries.
333
+ if (targetOs === "windows" && !hostHasVariantFonts(targetOs)) {
334
+ result = result.filter((f) => !WINDOWS_11_MARKER_FONTS.has(f));
335
+ }
336
+ return result;
337
+ }
338
+ const release = pickRelease(osKey, r);
339
+ let base = release ? [...release.fonts] : [];
340
+ if (!base.length)
341
+ base = fullList.filter((f) => essential.has(f));
342
+ const result = [...base];
343
+ const chosen = new Set(result);
344
+ // The guaranteed floor underneath whichever base was drawn.
345
+ for (const font of fullList) {
346
+ if (essential.has(font) && !chosen.has(font)) {
347
+ result.push(font);
348
+ chosen.add(font);
349
+ }
350
+ }
351
+ // Every addition unit on its own real-world probability, atomically.
352
+ for (const font of drawUnits(osKey, r, chosen, locale)) {
353
+ if (!chosen.has(font)) {
354
+ result.push(font);
355
+ chosen.add(font);
356
+ }
357
+ }
358
+ ensureMarkerFonts(result, markers);
359
+ return result;
360
+ }
361
+ // Real Firefox speechSynthesis URI prefixes per backend.
362
+ const VOICE_URI_PREFIX = {
363
+ mac: "urn:moz-tts:osx:",
364
+ win: "urn:moz-tts:sapi:",
365
+ lin: "urn:moz-tts:speechd:",
366
+ };
367
+ export const MAC_NOVELTY_VOICES = new Set(LAUNCHER_CONSTANTS.macNoveltyVoices);
368
+ export const MAC_ELOQUENCE_VOICES = new Set(LAUNCHER_CONSTANTS.macEloquenceVoices);
369
+ let voiceUrisCache = null;
370
+ /** Real voiceURI per "Name|lang" as a stock browser reports it (voice-uris.json). */
371
+ function loadVoiceUris() {
372
+ if (!voiceUrisCache) {
373
+ try {
374
+ voiceUrisCache =
375
+ loadDataFile("voice-uris.json");
376
+ }
377
+ catch {
378
+ voiceUrisCache = {};
379
+ }
380
+ }
381
+ return voiceUrisCache;
382
+ }
383
+ let voiceManifestsCache = null;
384
+ /** The per-OS installed-voice model (voice-manifests.json). */
385
+ function loadVoiceManifests() {
386
+ voiceManifestsCache ??= loadDataFile("voice-manifests.json");
387
+ return voiceManifestsCache;
388
+ }
389
+ /** Stable dotted slug for mac/win URIs (shape-plausible, not catalog-exact). */
390
+ function voiceUriSlug(name) {
391
+ return name
392
+ .toLowerCase()
393
+ .replace(/[^a-z0-9]+/g, ".")
394
+ .replace(/^\.|\.$/g, "");
395
+ }
396
+ /** A voiceUri matching what real Firefox emits for the OS backend. */
397
+ export function voiceUri(osKey, name, lang) {
398
+ if (osKey === "lin") {
399
+ // SpeechDispatcherService.cpp: NS_EscapeURL(name, OnlyNonASCII|Spaces)
400
+ let escaped = "";
401
+ for (const ch of name) {
402
+ if (ch === " ")
403
+ escaped += "%20";
404
+ else if (ch.codePointAt(0) <= 0x7f)
405
+ escaped += ch;
406
+ else {
407
+ for (const b of Buffer.from(ch, "utf-8")) {
408
+ escaped += `%${b.toString(16).toUpperCase().padStart(2, "0")}`;
409
+ }
410
+ }
411
+ }
412
+ return `${VOICE_URI_PREFIX.lin}${escaped}?${lang}`;
413
+ }
414
+ if (osKey === "win") {
415
+ // SapiService.cpp: the name and lang, verbatim.
416
+ return `${VOICE_URI_PREFIX.win}${name}?${lang}`;
417
+ }
418
+ if (osKey === "mac") {
419
+ const uri = loadVoiceUris().mac?.[`${name}|${lang}`];
420
+ if (uri)
421
+ return uri;
422
+ const asciiName = name.normalize("NFKD").replace(/[^A-Za-z0-9]/g, "");
423
+ if (MAC_NOVELTY_VOICES.has(name)) {
424
+ return `${VOICE_URI_PREFIX.mac}com.apple.speech.synthesis.voice.${asciiName}`;
425
+ }
426
+ if (MAC_ELOQUENCE_VOICES.has(name)) {
427
+ return `${VOICE_URI_PREFIX.mac}com.apple.eloquence.${lang}.${asciiName}`;
428
+ }
429
+ return `${VOICE_URI_PREFIX.mac}com.apple.voice.compact.${lang}.${asciiName}`;
430
+ }
431
+ return `${VOICE_URI_PREFIX[osKey] ?? ""}${voiceUriSlug(name)}`;
432
+ }
433
+ /** "Name:lang:type" -> [name, lang, type] (str.rsplit(':', 2)). */
434
+ function splitVoiceEntry(entry) {
435
+ const last = entry.lastIndexOf(":");
436
+ const langsep = last < 0 ? -1 : entry.lastIndexOf(":", last - 1);
437
+ if (last < 0 || langsep < 0) {
438
+ throw new ValueError(`not enough values to unpack (voice entry ${JSON.stringify(entry)})`);
439
+ }
440
+ return [
441
+ entry.slice(0, langsep),
442
+ entry.slice(langsep + 1, last),
443
+ entry.slice(last + 1),
444
+ ];
445
+ }
446
+ function weightedPick(r, items, wkey = "w") {
447
+ const total = pySumFloats(items.map((i) => Number(i[wkey] ?? 0)));
448
+ let x = r.random() * total;
449
+ for (const i of items) {
450
+ x -= Number(i[wkey] ?? 0);
451
+ if (x <= 0)
452
+ return i;
453
+ }
454
+ return items[items.length - 1];
455
+ }
456
+ function weightedSample(r, items, k, weight) {
457
+ const pool = [...items];
458
+ const out = [];
459
+ while (pool.length && out.length < k) {
460
+ const total = pySumFloats(pool.map(weight));
461
+ let x = r.random() * total;
462
+ let picked = false;
463
+ for (const item of pool) {
464
+ x -= weight(item);
465
+ if (x <= 0) {
466
+ out.push(item);
467
+ pool.splice(pool.indexOf(item), 1);
468
+ picked = true;
469
+ break;
470
+ }
471
+ }
472
+ if (!picked)
473
+ out.push(pool.pop());
474
+ }
475
+ return out;
476
+ }
477
+ function resolveDisplayPack(packs, fallback, locale) {
478
+ const keys = Object.keys(packs);
479
+ if (locale) {
480
+ if (Object.hasOwn(packs, locale))
481
+ return locale;
482
+ const lang = locale.split("-")[0].toLowerCase();
483
+ for (const key of keys) {
484
+ if (key.split("-")[0].toLowerCase() === lang)
485
+ return key;
486
+ }
487
+ }
488
+ return Object.hasOwn(packs, fallback) ? fallback : keys[0];
489
+ }
490
+ function codePointGreater(a, b) {
491
+ return comparePyStr(a, b) > 0;
492
+ }
493
+ /**
494
+ * The speech-dispatcher voice grid of the Ubuntu release the identity runs
495
+ * (`_speechd_grid`).
496
+ */
497
+ function speechdGrid(seed) {
498
+ const release = pickRelease("lin", rng(seed));
499
+ const releases = loadVoiceManifests().lin.releases;
500
+ return release
501
+ ? releases[release.id].speechd
502
+ : Object.values(releases)[0].speechd;
503
+ }
504
+ /**
505
+ * (name, lang) per voice in speech-dispatcher's order (`_speechd_voices`):
506
+ * each language alone, then with every variant.
507
+ */
508
+ export function speechdVoices(grid) {
509
+ return grid.languages.flatMap(([name, lang]) => [
510
+ [name, lang],
511
+ ...grid.variants.map((v) => [`${name}+${v}`, lang]),
512
+ ]);
513
+ }
514
+ /**
515
+ * The identity's voices as the config keys the browser reads
516
+ * (`draw_voice_config`): `voices` on macOS and Windows, `voices:speechd` on
517
+ * Linux, whose ~15000 voices only fit in the environment as their grid.
518
+ */
519
+ export function drawVoiceConfig(targetOs, locale, seed) {
520
+ if (osKeyOf(targetOs) === "lin")
521
+ return { "voices:speechd": speechdGrid(seed) };
522
+ return { voices: generateRandomVoiceSubset(targetOs, locale, seed) };
523
+ }
524
+ /**
525
+ * The speech voice list for the given OS as MaskConfig voice objects
526
+ * (`_generate_random_voice_subset`), following the measured per-OS model in
527
+ * voice-manifests.json. Seeded by the identity so it always reports the same
528
+ * list. macOS marks its system voice default; Windows and Linux mark none.
529
+ */
530
+ export function generateRandomVoiceSubset(targetOs, locale, seed) {
531
+ const r = rng(seed);
532
+ const osKey = osKeyOf(targetOs);
533
+ if (osKey === "lin") {
534
+ return speechdVoices(speechdGrid(seed)).map(([name, lang]) => ({
535
+ name,
536
+ lang,
537
+ voiceUri: voiceUri("lin", name, lang),
538
+ isDefault: false,
539
+ // SpeechDispatcherService registers voices as local only when one
540
+ // is named "default"; espeak-ng has none.
541
+ isLocalService: false,
542
+ }));
543
+ }
544
+ const manifests = loadVoiceManifests();
545
+ const manifest = pyTruthy(manifests[osKey])
546
+ ? manifests[osKey]
547
+ : manifests.mac;
548
+ if (manifest === undefined)
549
+ throw new KeyError("'mac'");
550
+ const out = [];
551
+ const seen = new Set();
552
+ const add = (entries) => {
553
+ for (const e of entries ?? []) {
554
+ if (!seen.has(e)) {
555
+ seen.add(e);
556
+ out.push(e);
557
+ }
558
+ }
559
+ };
560
+ const legacy = [];
561
+ const packs = pyTruthy(manifest.langPacks)
562
+ ? manifest.langPacks
563
+ : {};
564
+ const takePack = (pack) => {
565
+ add(pack.oneCore);
566
+ if (pyTruthy(pack.desktop) &&
567
+ r.random() < Number(pyTruthy(pack.desktopProb) ? pack.desktopProb : 0)) {
568
+ for (const e of pack.desktop) {
569
+ if (!legacy.includes(e))
570
+ legacy.push(e);
571
+ }
572
+ }
573
+ };
574
+ add(manifest.base);
575
+ const chosen = new Set();
576
+ if (Object.keys(packs).length) {
577
+ const key = resolveDisplayPack(packs, pyTruthy(manifest.fallbackLocale) ? manifest.fallbackLocale : "en-US", locale);
578
+ chosen.add(key);
579
+ takePack(packs[key]);
580
+ }
581
+ for (const addition of manifest.additions ?? []) {
582
+ if (pyTruthy(addition.deferred))
583
+ continue;
584
+ const req = addition.requiresLocale;
585
+ if (pyTruthy(req) && !localeMatches(locale, req))
586
+ continue;
587
+ if (r.random() >= Number(pyTruthy(addition.prob) ? addition.prob : 0))
588
+ continue;
589
+ const kind = addition.kind;
590
+ if (kind === "bundle") {
591
+ add(addition.voices);
592
+ }
593
+ else if (kind === "alacarte") {
594
+ const sizes = pyTruthy(addition.sizes)
595
+ ? addition.sizes
596
+ : [{ n: 1, w: 1 }];
597
+ const k = Math.trunc(Number(weightedPick(r, sizes).n));
598
+ for (const e of weightedSample(r, addition.voices ?? [], k, () => 1.0)) {
599
+ if (!seen.has(e)) {
600
+ seen.add(e);
601
+ // a downloaded voice sits in its alphabetical place
602
+ const el = e.toLowerCase();
603
+ let idx = out.findIndex((v) => codePointGreater(v.toLowerCase(), el));
604
+ if (idx < 0)
605
+ idx = out.length;
606
+ out.splice(idx, 0, e);
607
+ }
608
+ }
609
+ }
610
+ else if (kind === "groups" && Object.keys(packs).length) {
611
+ const eligible = (addition.groups ?? []).filter((g) => Object.hasOwn(packs, g) && !chosen.has(g));
612
+ if (!eligible.length)
613
+ continue;
614
+ const k = pyTruthy(addition.sizes)
615
+ ? Math.trunc(Number(weightedPick(r, addition.sizes).n))
616
+ : eligible.length;
617
+ const weight = (g) => Number(pyTruthy(packs[g].weight) ? packs[g].weight : 0.01);
618
+ for (const g of weightedSample(r, eligible, k, weight)) {
619
+ chosen.add(g);
620
+ takePack(packs[g]);
621
+ }
622
+ }
623
+ }
624
+ const selected = [...out, ...legacy].map(splitVoiceEntry);
625
+ const voices = selected.map(([name, lang, vtype]) => ({
626
+ name,
627
+ lang,
628
+ voiceUri: voiceUri(osKey, name, lang),
629
+ isDefault: false,
630
+ isLocalService: vtype === "local",
631
+ }));
632
+ const systemVoice = manifest.systemVoice?.default;
633
+ const def = voices.find((v) => v.name === systemVoice);
634
+ if (def)
635
+ def.isDefault = true;
636
+ return voices;
637
+ }
638
+ /**
639
+ * Coerce a preset's `speechVoices` into MaskConfig voice objects: presets
640
+ * store "Name:lang:type" strings, which MaskConfig drops. Objects pass through.
641
+ */
642
+ export function normalizePresetVoices(voices, targetOs) {
643
+ const osKey = osKeyOf(targetOs);
644
+ const result = [];
645
+ for (const entry of voices) {
646
+ if (entry !== null && typeof entry === "object") {
647
+ result.push(entry);
648
+ continue;
649
+ }
650
+ const last = entry.lastIndexOf(":");
651
+ if (last < 0)
652
+ continue;
653
+ const vtype = entry.slice(last + 1);
654
+ const before = entry.slice(0, last);
655
+ const langsep = before.lastIndexOf(":");
656
+ if (langsep < 0)
657
+ continue;
658
+ const lang = before.slice(langsep + 1);
659
+ const name = before.slice(0, langsep);
660
+ if (!name || !lang)
661
+ continue;
662
+ result.push({
663
+ name,
664
+ lang,
665
+ voiceUri: voiceUri(osKey, name, lang),
666
+ isDefault: false,
667
+ isLocalService: vtype === "local",
668
+ });
669
+ }
670
+ if (result.length && !result.some((v) => v.isDefault))
671
+ result[0].isDefault = true;
672
+ return result;
673
+ }
674
+ // ---------------------------------------------------------------------------
675
+ // Hardware concurrency and navigator arch
676
+ // ---------------------------------------------------------------------------
677
+ /**
678
+ * Logical CPUs this process may run on (affinity aware), as they were before
679
+ * any launch pinned it: see cpu_affinity.hostCoreCount().
680
+ */
681
+ export function hostCpuCount() {
682
+ return hostCoreCount() || null;
683
+ }
684
+ /**
685
+ * Core counts real desktop machines ship with, from the recorded fingerprint
686
+ * corpus. 2 is excluded: no Apple Silicon part has 2 cores, and 85% of macOS
687
+ * identities draw an Apple GPU (see fingerprints.py).
688
+ */
689
+ export const PLAUSIBLE_CORE_COUNTS = LAUNCHER_CONSTANTS.plausibleCoreCounts;
690
+ /**
691
+ * navigator.hardwareConcurrency = the host's parallelism, snapped DOWN into
692
+ * PLAUSIBLE_CORE_COUNTS -- or the fingerprint's own value (snapped, capped by
693
+ * the host) when the browser can be pinned to that many cores.
694
+ *
695
+ * On an Intel Mac the count yields to the GPU: the GPU is read before this
696
+ * runs, and a count no Mac with it reports would drop it (#1090). Apple
697
+ * Silicon is snapped to its GPU by the apple-silicon-cores repair.
698
+ *
699
+ * @param canPin false when nothing will pin the browser (launchServer, or
700
+ * launchOptions used directly); undefined/null: whatever the host supports.
701
+ * @param host overrides for the host probes (tests).
702
+ * @param targetOs the launch's OS key; the GPU bound applies to "mac" only.
703
+ */
704
+ export function fixHardwareConcurrency(config, canPin, host = {}, targetOs) {
705
+ const machineCores = targetOs === "mac" ? intelMacCores(config["webGl:renderer"]) : null;
706
+ // Never empty: 4 is the plausible floor and every Intel Mac table has it.
707
+ const table = (cap) => {
708
+ const plausible = PLAUSIBLE_CORE_COUNTS.filter((c) => c <= cap);
709
+ if (!plausible.length)
710
+ plausible.push(PLAUSIBLE_CORE_COUNTS[0]);
711
+ return plausible.filter((c) => !machineCores || machineCores.has(c));
712
+ };
713
+ const n = "cpuCount" in host ? host.cpuCount : hostCpuCount();
714
+ if (!n)
715
+ return;
716
+ const pinnable = (host.canPinHost ?? cpuAffinitySupported()) && canPin !== false;
717
+ const cap = Math.trunc(n);
718
+ const hostAllowed = table(cap);
719
+ const hostValue = hostAllowed[hostAllowed.length - 1];
720
+ let drawn = config["navigator.hardwareConcurrency"];
721
+ if (typeof drawn === "boolean")
722
+ drawn = Number(drawn); // a Python bool is an int
723
+ if (pinnable &&
724
+ typeof drawn === "number" &&
725
+ Number.isInteger(drawn) &&
726
+ drawn >= 1) {
727
+ const allowed = table(Math.min(drawn, cap));
728
+ config["navigator.hardwareConcurrency"] = allowed[allowed.length - 1];
729
+ return;
730
+ }
731
+ config["navigator.hardwareConcurrency"] = hostValue;
732
+ }
733
+ /** Force navigator.platform AND navigator.oscpu to match the UA's arch (Linux). */
734
+ export function fixNavigatorArch(config, targetOs) {
735
+ if (targetOs !== "lin")
736
+ return;
737
+ const ua = config["navigator.userAgent"];
738
+ if (!pyTruthy(ua))
739
+ return;
740
+ let target = "";
741
+ if (ua.includes("Linux x86_64"))
742
+ target = "Linux x86_64";
743
+ else if (ua.includes("Linux i686"))
744
+ target = "Linux i686";
745
+ if (!target)
746
+ return;
747
+ if (config["navigator.platform"] !== target)
748
+ config["navigator.platform"] = target;
749
+ if (config["navigator.oscpu"] !== target)
750
+ config["navigator.oscpu"] = target;
751
+ }
752
+ // ---------------------------------------------------------------------------
753
+ // Screen / window geometry
754
+ // ---------------------------------------------------------------------------
755
+ // What Firefox's baseline fingerprinting protection, on by default, reports in
756
+ // place of the device's values (RFPTargetsDefaultBaseline.inc), and the browser
757
+ // applies it to the spoofed ones for the claimed OS: the available screen is
758
+ // the whole screen less a fixed taskbar (nsRFPService::GetSpoofedScreenAvailSize),
759
+ // and more than one touch point reads as 5 (CollapseMaxTouchPoints).
760
+ export const BASELINE_TASKBAR_HEIGHT = LAUNCHER_CONSTANTS.baselineTaskbarHeight;
761
+ export const BASELINE_MULTI_TOUCH_POINTS = LAUNCHER_CONSTANTS.baselineMultiTouchPoints;
762
+ /**
763
+ * Claim the available screen and touch points the browser will report.
764
+ * clampWindowDimensions then fits the window inside that screen.
765
+ */
766
+ export function followBaselineProtection(config, targetOs) {
767
+ const width = config["screen.width"];
768
+ const height = config["screen.height"];
769
+ if (pyTruthy(width) && pyTruthy(height)) {
770
+ config["screen.availWidth"] = width;
771
+ config["screen.availHeight"] =
772
+ num(height) - BASELINE_TASKBAR_HEIGHT[targetOs];
773
+ }
774
+ if (num(config["navigator.maxTouchPoints"] ?? 0) > 1) {
775
+ config["navigator.maxTouchPoints"] = BASELINE_MULTI_TOUCH_POINTS;
776
+ }
777
+ }
778
+ /** Enforce inner <= outer <= avail <= screen on both axes. */
779
+ export function clampWindowDimensions(config) {
780
+ for (const axis of ["Width", "Height"]) {
781
+ const screen = config[`screen.${axis.toLowerCase()}`];
782
+ const avail = config[`screen.avail${axis}`];
783
+ const outer = config[`window.outer${axis}`];
784
+ const inner = config[`window.inner${axis}`];
785
+ // avail must not exceed screen
786
+ if (pyTruthy(screen) && pyTruthy(avail) && num(avail) > num(screen)) {
787
+ config[`screen.avail${axis}`] = screen;
788
+ }
789
+ const availClamped = get(config, `screen.avail${axis}`, screen);
790
+ // outer must not exceed avail (or screen if avail is unknown)
791
+ const outerCap = !isNone(availClamped) ? availClamped : screen;
792
+ if (pyTruthy(outer) && pyTruthy(outerCap) && num(outer) > num(outerCap)) {
793
+ const chrome = pyTruthy(inner) ? Math.max(0, num(outer) - num(inner)) : 0;
794
+ config[`window.outer${axis}`] = outerCap;
795
+ if (pyTruthy(inner))
796
+ config[`window.inner${axis}`] = Math.max(1, num(outerCap) - chrome);
797
+ }
798
+ // inner must not exceed outer
799
+ const outerClamped = get(config, `window.outer${axis}`, outer);
800
+ const innerNow = config[`window.inner${axis}`];
801
+ if (pyTruthy(innerNow) &&
802
+ pyTruthy(outerClamped) &&
803
+ num(innerNow) > num(outerClamped)) {
804
+ config[`window.inner${axis}`] = outerClamped;
805
+ }
806
+ }
807
+ }
808
+ /**
809
+ * Shrink screen.width/height down to the bounds of the real display, keeping
810
+ * the taskbar delta. Run clampWindowDimensions afterwards.
811
+ */
812
+ export function clampScreenToDisplay(config, maxWidth, maxHeight) {
813
+ for (const [axis, cap] of [
814
+ ["width", maxWidth],
815
+ ["height", maxHeight],
816
+ ]) {
817
+ const screen = config[`screen.${axis}`];
818
+ if (!(pyTruthy(screen) && pyTruthy(cap)) || num(screen) <= cap)
819
+ continue;
820
+ const availKey = axis === "width" ? "screen.availWidth" : "screen.availHeight";
821
+ const avail = config[availKey];
822
+ config[`screen.${axis}`] = cap;
823
+ if (pyTruthy(avail)) {
824
+ config[availKey] = Math.max(1, cap - Math.max(0, num(screen) - num(avail)));
825
+ }
826
+ }
827
+ }
828
+ /**
829
+ * Keep the window box inside the available screen: 0 <= screenX/Y <= avail -
830
+ * outer. The available screen, not the whole one: pages are fitted to the
831
+ * window on screen.availHeight, and a window at y=2 whose outer
832
+ * height is the available height ran 2 px into the taskbar, so every new
833
+ * context drew a larger screen for it. Only `keys` are moved.
834
+ */
835
+ export function clampWindowPosition(config, keys = new Set(["window.screenX", "window.screenY"])) {
836
+ for (const [axis, posKey] of [
837
+ ["Width", "window.screenX"],
838
+ ["Height", "window.screenY"],
839
+ ]) {
840
+ const room = config[`screen.avail${axis}`] || config[`screen.${axis.toLowerCase()}`];
841
+ const outer = config[`window.outer${axis}`];
842
+ const pos = config[posKey];
843
+ if (!keys.has(posKey) ||
844
+ isNone(pos) ||
845
+ !(pyTruthy(room) && pyTruthy(outer)))
846
+ continue;
847
+ config[posKey] = Math.max(0, Math.min(num(pos), num(room) - num(outer)));
848
+ }
849
+ }
850
+ /** The smallest screen mainstream hardware still ships. */
851
+ export const MODERN_SCREEN_FLOOR = [1366, 768];
852
+ /**
853
+ * Lift netbook-era screen geometry to the modern floor, keeping the
854
+ * screen-to-avail gaps. Call BEFORE clampScreenToDisplay.
855
+ */
856
+ export function raiseScreenToModernFloor(config) {
857
+ const [minW, minH] = MODERN_SCREEN_FLOOR;
858
+ const sw = config["screen.width"];
859
+ const sh = config["screen.height"];
860
+ if (!(pyTruthy(sw) && pyTruthy(sh)) || (num(sw) >= minW && num(sh) >= minH))
861
+ return;
862
+ const aw = config["screen.availWidth"];
863
+ const ah = config["screen.availHeight"];
864
+ const gapW = pyTruthy(aw) ? num(sw) - num(aw) : null;
865
+ const gapH = pyTruthy(ah) ? num(sh) - num(ah) : null;
866
+ const newW = Math.max(num(sw), minW);
867
+ const newH = Math.max(num(sh), minH);
868
+ config["screen.width"] = newW;
869
+ config["screen.height"] = newH;
870
+ if (gapW !== null)
871
+ config["screen.availWidth"] = Math.max(1, newW - Math.max(0, gapW));
872
+ if (gapH !== null)
873
+ config["screen.availHeight"] = Math.max(1, newH - Math.max(0, gapH));
874
+ }
875
+ // ---------------------------------------------------------------------------
876
+ // Media devices
877
+ // ---------------------------------------------------------------------------
878
+ let mediaDevicesCache = null;
879
+ /** Per-OS catalogue of common sound cards / headsets / displays / cameras. */
880
+ function loadMediaDevices() {
881
+ mediaDevicesCache ??= loadDataFile("media-devices.json");
882
+ return mediaDevicesCache;
883
+ }
884
+ function weightedChoice(r, items) {
885
+ const w = (item) => (Object.hasOwn(item, "w") ? item.w : 1);
886
+ const total = Number(pySum(items.map(w)));
887
+ let x = r.random() * total;
888
+ for (const item of items) {
889
+ x -= w(item);
890
+ if (x < 0)
891
+ return item;
892
+ }
893
+ return items[items.length - 1];
894
+ }
895
+ // Share of machines with no microphone at all, and with a built-in camera.
896
+ const MEDIA_P_NO_MIC = {
897
+ win: 0.08,
898
+ mac: 0.0,
899
+ lin: 0.2,
900
+ };
901
+ const MEDIA_P_BUILTIN_CAM = {
902
+ win: 0.78,
903
+ mac: 0.0,
904
+ lin: 0.45,
905
+ };
906
+ /**
907
+ * Draw one machine's media devices for `osKey` ('win'|'mac'|'lin'): the
908
+ * mediaDevices:* config keys, counts plus aligned label and group lists.
909
+ */
910
+ export function drawMediaDevices(osKey, seed) {
911
+ const r = rng(seed);
912
+ const catalogue = loadMediaDevices();
913
+ const cat = pyTruthy(catalogue[osKey]) ? catalogue[osKey] : catalogue.win;
914
+ const mics = [];
915
+ const outs = [];
916
+ const cams = [];
917
+ let counter = 0;
918
+ const group = () => {
919
+ counter += 1;
920
+ return `hw-${counter}`;
921
+ };
922
+ const add = (item, grp) => {
923
+ for (const m of item.mics ?? [])
924
+ mics.push([m, grp]);
925
+ for (const o of item.outs ?? [])
926
+ outs.push([o, grp]);
927
+ if (pyTruthy(item.cam))
928
+ cams.push([item.cam, group()]);
929
+ };
930
+ // 1. the machine's own sound card (+ built-in camera on macOS models)
931
+ const card = weightedChoice(r, cat.cards);
932
+ const noMic = r.random() < (MEDIA_P_NO_MIC[osKey] ?? 0.0);
933
+ const cardGrp = group();
934
+ add(noMic ? { ...card, mics: [] } : card, cardGrp);
935
+ // 2. a built-in laptop camera (Windows/Linux); rare on a mic-less tower
936
+ const pCam = MEDIA_P_BUILTIN_CAM[osKey] ?? 0.0;
937
+ if (r.random() < (noMic ? pCam * 0.3 : pCam)) {
938
+ const builtin = cat.cameras.filter((c) => !pyTruthy(c.mic));
939
+ if (builtin.length)
940
+ cams.push([weightedChoice(r, builtin).cam, group()]);
941
+ }
942
+ // 3. a headset / USB microphone
943
+ if (r.random() < (cat.p_headset ?? 0.0))
944
+ add(weightedChoice(r, cat.headsets), group());
945
+ // 4. display audio (HDMI/DP)
946
+ if (r.random() < (cat.p_display ?? 0.0))
947
+ add(weightedChoice(r, cat.displays), group());
948
+ // 5. an external webcam, usually with its own microphone
949
+ if (r.random() < (cat.p_extra_camera ?? 0.0)) {
950
+ const withMic = cat.cameras.filter((c) => pyTruthy(c.mic));
951
+ const external = withMic.length ? withMic : cat.cameras;
952
+ const cam = weightedChoice(r, external);
953
+ const grp = group();
954
+ cams.push([cam.cam, grp]);
955
+ if (pyTruthy(cam.mic))
956
+ mics.push([cam.mic, grp]);
957
+ }
958
+ // 6. PulseAudio exposes a monitor source per output as a capture device
959
+ if (pyTruthy(cat.monitor_sources)) {
960
+ for (const [label, grp] of [...outs])
961
+ mics.push([`Monitor of ${label}`, grp]);
962
+ }
963
+ return {
964
+ "mediaDevices:enabled": true,
965
+ "mediaDevices:micros": mics.length,
966
+ "mediaDevices:webcams": cams.length,
967
+ "mediaDevices:speakers": outs.length,
968
+ "mediaDevices:microphoneLabels": mics.map(([m]) => m),
969
+ "mediaDevices:microphoneGroups": mics.map(([, g]) => g),
970
+ "mediaDevices:webcamLabels": cams.map(([c]) => c),
971
+ "mediaDevices:webcamGroups": cams.map(([, g]) => g),
972
+ "mediaDevices:speakerLabels": outs.map(([o]) => o),
973
+ "mediaDevices:speakerGroups": outs.map(([, g]) => g),
974
+ };
975
+ }
976
+ /**
977
+ * Give the identity a plausible set of media devices, drawn from the common
978
+ * desktop population for its OS and seeded by the identity. Nothing is drawn
979
+ * when the caller already set any mediaDevices: key.
980
+ */
981
+ export function setMediaDevicesDefaults(config, salt = 0) {
982
+ if (Object.keys(config).some((k) => k.startsWith("mediaDevices:")))
983
+ return;
984
+ const plat = pyStr(get(config, "navigator.platform", ""));
985
+ const osKey = plat.startsWith("Win")
986
+ ? "win"
987
+ : plat.startsWith("Mac")
988
+ ? "mac"
989
+ : "lin";
990
+ Object.assign(config, drawMediaDevices(osKey, identitySeed(config, salt)));
991
+ }
992
+ /**
993
+ * Intel's share of the x86 desktop CPUs running Firefox (Firefox Public Data
994
+ * Report, week of 2026-11-02: Intel 76.86%, AMD 17.61%); fingerprints.py.
995
+ */
996
+ export const X86_INTEL_SHARE = LAUNCHER_CONSTANTS.x86IntelShare;
997
+ /**
998
+ * Fill in the identity's CPU (cpu:arch, cpu:manufacturer), as
999
+ * fingerprints.set_cpu_default does. The GPU decides what it can (an Apple
1000
+ * GPU is an Apple ARM CPU, an Intel iGPU or Intel Mac an Intel one, a Radeon
1001
+ * iGPU an AMD one), then a core count only Intel ships; any other x86
1002
+ * identity's vendor is drawn at Firefox's own x86 split, seeded by the
1003
+ * identity. An ARM identity whose GPU names no single SoC maker keeps its
1004
+ * manufacturer unset: every ARM64 CPU computes alike. Run after the GPU and
1005
+ * navigator.hardwareConcurrency are final. Keys the caller set are kept.
1006
+ */
1007
+ export function setCpuDefault(config, targetOs, salt = 0) {
1008
+ let [arch, maker] = hardwareCpu(config, targetOs);
1009
+ arch =
1010
+ (pyTruthy(config["cpu:arch"]) ? config["cpu:arch"] : null) || arch || "x86";
1011
+ if (!("cpu:arch" in config))
1012
+ config["cpu:arch"] = arch;
1013
+ if ("cpu:manufacturer" in config || arch !== config["cpu:arch"])
1014
+ return;
1015
+ if (!maker && arch === "x86") {
1016
+ const draw = rng((identitySeed(config, salt) ^ 0xc9d0) >>> 0).random();
1017
+ maker = draw < X86_INTEL_SHARE ? "intel" : "amd";
1018
+ }
1019
+ if (maker)
1020
+ config["cpu:manufacturer"] = maker;
1021
+ }
1022
+ // ---------------------------------------------------------------------------
1023
+ // WebGL <-> screen coherence (#729)
1024
+ // ---------------------------------------------------------------------------
1025
+ /** Software rasterizers: never preferred, never screen-constrained. */
1026
+ const SOFTWARE_RENDERERS = [
1027
+ "llvmpipe",
1028
+ "Microsoft Basic Render Driver",
1029
+ "SwiftShader",
1030
+ "Generic Renderer",
1031
+ ];
1032
+ /** Gecko renderer buckets that are discrete GPUs (no netbook shipped one). */
1033
+ const DISCRETE_GPU_BUCKETS = new Set([
1034
+ "GeForce 8800 GTX",
1035
+ "GeForce GTX 480",
1036
+ "GeForce GTX 980",
1037
+ "Radeon R9 200 Series",
1038
+ ]);
1039
+ /** Netbook panels topped out at 1024x600; an area, not a per-axis floor. */
1040
+ const NETBOOK_MAX_PIXELS = 1024 * 600;
1041
+ const ANGLE_D3D_RE = /^ANGLE \([^,]*, (.*?) Direct3D.*\)$/s;
1042
+ const ANGLE_VULKAN_RE = /^ANGLE \((.*)\) on Vulkan$/s;
1043
+ const PCIE_SSE2_RE = /^(.*)\/PCIe?\/SSE2$/s;
1044
+ /** Reduce a reported renderer to Gecko's sanitized device bucket. */
1045
+ export function rendererBucket(renderer) {
1046
+ let core = renderer.endsWith(", or similar")
1047
+ ? renderer.slice(0, -", or similar".length)
1048
+ : renderer;
1049
+ let match = ANGLE_D3D_RE.exec(core) ?? ANGLE_VULKAN_RE.exec(core);
1050
+ if (match)
1051
+ core = match[1];
1052
+ match = PCIE_SSE2_RE.exec(core);
1053
+ if (match)
1054
+ core = match[1];
1055
+ return core.startsWith("NVIDIA ") ? core.slice("NVIDIA ".length) : core;
1056
+ }
1057
+ /** Whether `renderer` is a software rasterizer rather than real hardware. */
1058
+ export function isSoftwareRenderer(renderer) {
1059
+ return (!!renderer && SOFTWARE_RENDERERS.some((name) => renderer.includes(name)));
1060
+ }
1061
+ /** Whether `renderer` is a GPU that plausibly drives a `width` x `height` screen. */
1062
+ export function gpuScreenIsPlausible(renderer, width, height) {
1063
+ if (!renderer || !width || !height)
1064
+ return true;
1065
+ if (isSoftwareRenderer(renderer))
1066
+ return true;
1067
+ if (!DISCRETE_GPU_BUCKETS.has(rendererBucket(renderer)))
1068
+ return true;
1069
+ return width * height > NETBOOK_MAX_PIXELS;
1070
+ }
1071
+ // ---------------------------------------------------------------------------
1072
+ // Presets
1073
+ // ---------------------------------------------------------------------------
1074
+ /** The bundled-presets file for a Firefox version (v150 bundle from 149 up). */
1075
+ export function selectPresetsFile(ffVersion) {
1076
+ let major = 0;
1077
+ if (ffVersion) {
1078
+ const parsed = Number.parseInt(String(ffVersion).split(".", 1)[0].trim(), 10);
1079
+ major = /^\s*[+-]?\d+\s*$/.test(String(ffVersion).split(".", 1)[0])
1080
+ ? parsed
1081
+ : 0;
1082
+ }
1083
+ if (major >= PRESETS_V150_MIN_FF && fs.existsSync(PRESETS_V150_FILE))
1084
+ return PRESETS_V150_FILE;
1085
+ return PRESETS_FILE;
1086
+ }
1087
+ /** Load the bundled fingerprint presets. */
1088
+ export function loadPresets(ffVersion) {
1089
+ const file = selectPresetsFile(ffVersion);
1090
+ const cached = PRESETS_CACHE.get(file);
1091
+ if (cached)
1092
+ return cached;
1093
+ if (!fs.existsSync(file))
1094
+ return null;
1095
+ const bundle = JSON.parse(fs.readFileSync(file, "utf-8"));
1096
+ PRESETS_CACHE.set(file, bundle);
1097
+ return bundle;
1098
+ }
1099
+ const OS_TO_PRESET_KEY = {
1100
+ windows: "windows",
1101
+ macos: "macos",
1102
+ linux: "linux",
1103
+ win: "windows",
1104
+ mac: "macos",
1105
+ lin: "linux",
1106
+ };
1107
+ /**
1108
+ * A random preset for the given OS (or OSes), or null when none is bundled.
1109
+ * Draws from python-random's module-level `choice` (Python's random.choice).
1110
+ */
1111
+ export function getRandomPreset(os, ffVersion) {
1112
+ const presets = loadPresets(ffVersion);
1113
+ if (!pyTruthy(presets))
1114
+ return null;
1115
+ let osKeys;
1116
+ if (os?.length) {
1117
+ const names = typeof os === "string" ? [os] : [...os];
1118
+ osKeys = names.map((o) => OS_TO_PRESET_KEY[o] ?? o);
1119
+ }
1120
+ else {
1121
+ osKeys = ["macos", "windows", "linux"];
1122
+ }
1123
+ const candidates = [];
1124
+ for (const key of osKeys) {
1125
+ candidates.push(...(presets?.presets?.[key] ??
1126
+ []));
1127
+ }
1128
+ if (!candidates.length)
1129
+ return null;
1130
+ return random.choice(candidates);
1131
+ }
1132
+ // Tokens that name the machine rather than the platform.
1133
+ const APP_VERSION_DROPPED = new Set([
1134
+ "Win64",
1135
+ "x64",
1136
+ "Mobile",
1137
+ "Tablet",
1138
+ ]);
1139
+ /**
1140
+ * The appVersion Firefox reports for a browser sending this user agent:
1141
+ * "5.0 (<OS tokens>)" without the architecture, the Gecko revision, or the
1142
+ * Windows build number.
1143
+ */
1144
+ export function appVersionFromUserAgent(userAgent) {
1145
+ const block = /^Mozilla\/5\.0 \(([^)]*)\)/.exec(userAgent ?? "");
1146
+ if (!block)
1147
+ return null;
1148
+ const kept = [];
1149
+ for (const token of block[1].split(";").map((part) => part.trim())) {
1150
+ if (token.startsWith("rv:") ||
1151
+ APP_VERSION_DROPPED.has(token) ||
1152
+ token.startsWith("Linux ") ||
1153
+ token.startsWith("Intel Mac OS X")) {
1154
+ continue;
1155
+ }
1156
+ kept.push(token.startsWith("Windows") ? "Windows" : token);
1157
+ }
1158
+ return kept.length ? `5.0 (${kept.join("; ")})` : null;
1159
+ }
1160
+ /**
1161
+ * Sets navigator.appVersion the way Firefox computes it: from the userAgent.
1162
+ * Left unset it falls through to the HOST's value; taken from fpgen it is a
1163
+ * draw of its own, and fpgen pairs some Linux user agents with "5.0 (Windows)".
1164
+ */
1165
+ function setAppVersion(config) {
1166
+ const derived = appVersionFromUserAgent(config["navigator.userAgent"] ?? "");
1167
+ if (derived)
1168
+ config["navigator.appVersion"] = derived;
1169
+ }
1170
+ function oscpuFromPlatform(plat) {
1171
+ if (plat === "MacIntel")
1172
+ return "Intel Mac OS X 10.15";
1173
+ if (plat === "Win32")
1174
+ return "Windows NT 10.0; Win64; x64";
1175
+ if (plat.includes("Linux") || plat.includes("linux"))
1176
+ return "Linux x86_64";
1177
+ return null;
1178
+ }
1179
+ /**
1180
+ * Convert a real fingerprint preset to CAMOU_CONFIG format.
1181
+ *
1182
+ * `salt` (identitySalt) keys the font/voice draws; undefined draws a fresh
1183
+ * one, so two users of the same recorded device do not share its font list.
1184
+ */
1185
+ export function fromPreset(preset, ffVersion, salt) {
1186
+ const s = isNone(salt) ? identitySalt() : salt;
1187
+ const config = {};
1188
+ const nav = preset.navigator ?? {};
1189
+ if (pyTruthy(nav.userAgent)) {
1190
+ let ua = nav.userAgent;
1191
+ if (ffVersion) {
1192
+ ua = ua.replace(/Firefox\/\d+\.0/g, `Firefox/${ffVersion}.0`);
1193
+ ua = ua.replace(/rv:\d+\.0/g, `rv:${ffVersion}.0`);
1194
+ }
1195
+ config["navigator.userAgent"] = ua;
1196
+ }
1197
+ if (pyTruthy(nav.platform))
1198
+ config["navigator.platform"] = nav.platform;
1199
+ if (pyTruthy(nav.hardwareConcurrency))
1200
+ config["navigator.hardwareConcurrency"] = nav.hardwareConcurrency;
1201
+ if (pyTruthy(nav.oscpu)) {
1202
+ config["navigator.oscpu"] = nav.oscpu;
1203
+ }
1204
+ else if (pyTruthy(nav.platform)) {
1205
+ const oscpu = oscpuFromPlatform(nav.platform);
1206
+ if (oscpu)
1207
+ config["navigator.oscpu"] = oscpu;
1208
+ }
1209
+ setAppVersion(config);
1210
+ if (Object.hasOwn(nav, "maxTouchPoints"))
1211
+ config["navigator.maxTouchPoints"] = nav.maxTouchPoints;
1212
+ const screen = preset.screen ?? {};
1213
+ if (pyTruthy(screen.width))
1214
+ config["screen.width"] = screen.width;
1215
+ if (pyTruthy(screen.height))
1216
+ config["screen.height"] = screen.height;
1217
+ if (pyTruthy(screen.colorDepth)) {
1218
+ config["screen.colorDepth"] = screen.colorDepth;
1219
+ config["screen.pixelDepth"] = screen.colorDepth;
1220
+ }
1221
+ if (pyTruthy(screen.availWidth))
1222
+ config["screen.availWidth"] = screen.availWidth;
1223
+ if (pyTruthy(screen.availHeight))
1224
+ config["screen.availHeight"] = screen.availHeight;
1225
+ const webgl = preset.webgl ?? {};
1226
+ if (pyTruthy(webgl.unmaskedVendor))
1227
+ config["webGl:vendor"] = webgl.unmaskedVendor;
1228
+ if (pyTruthy(webgl.unmaskedRenderer))
1229
+ config["webGl:renderer"] = webgl.unmaskedRenderer;
1230
+ if (pyTruthy(preset.timezone))
1231
+ config.timezone = preset.timezone;
1232
+ const plat = nav.platform ?? "";
1233
+ let targetOs;
1234
+ if (plat === "MacIntel")
1235
+ targetOs = "macos";
1236
+ else if (plat === "Win32")
1237
+ targetOs = "windows";
1238
+ else if (plat.includes("Linux") || plat.includes("linux"))
1239
+ targetOs = "linux";
1240
+ else
1241
+ targetOs = "macos";
1242
+ const presetKey = `${pyStr(config["navigator.userAgent"])} / ${pyStr(config["webGl:renderer"])}`;
1243
+ try {
1244
+ config.fonts = generateRandomFontSubset(targetOs, identitySeed(config, s));
1245
+ }
1246
+ catch (e) {
1247
+ if (!isPyError(e, "OSError", "ValueError"))
1248
+ throw e;
1249
+ FallbackWarning.warn("Drawing the font list", pyTruthy(preset.fonts)
1250
+ ? "the preset's recorded fonts"
1251
+ : "the browser's own fonts", e, presetKey);
1252
+ if (pyTruthy(preset.fonts)) {
1253
+ const fonts = [...preset.fonts];
1254
+ ensureMarkerFonts(fonts, {
1255
+ macos: MACOS_MARKER_FONTS,
1256
+ windows: WINDOWS_MARKER_FONTS,
1257
+ linux: LINUX_MARKER_FONTS,
1258
+ }[targetOs] ?? MACOS_MARKER_FONTS);
1259
+ config.fonts = fonts;
1260
+ }
1261
+ }
1262
+ try {
1263
+ Object.assign(config, drawVoiceConfig(targetOs, null, identitySeed(config, s)));
1264
+ }
1265
+ catch (e) {
1266
+ if (!isPyError(e, "OSError", "ValueError", "KeyError"))
1267
+ throw e;
1268
+ FallbackWarning.warn("Drawing the speech voices", pyTruthy(preset.speechVoices)
1269
+ ? "the preset's recorded voices"
1270
+ : "the browser's own voices", e, presetKey);
1271
+ if (pyTruthy(preset.speechVoices)) {
1272
+ config.voices = normalizePresetVoices(preset.speechVoices, targetOs);
1273
+ }
1274
+ }
1275
+ return config;
1276
+ }
1277
+ /**
1278
+ * The JavaScript init script that calls the per-context window.setXxx()
1279
+ * functions. Those self-destruct after their first call, so they must run
1280
+ * via addInitScript.
1281
+ */
1282
+ export function buildInitScript(values) {
1283
+ const lines = ["(function(v) {", " var w = window;"];
1284
+ const setters = [
1285
+ ["navigatorPlatform", "setNavigatorPlatform"],
1286
+ ["navigatorOscpu", "setNavigatorOscpu"],
1287
+ ["navigatorUserAgent", "setNavigatorUserAgent"],
1288
+ ["navigatorAppVersion", "setNavigatorAppVersion"],
1289
+ ["hardwareConcurrency", "setNavigatorHardwareConcurrency"],
1290
+ ["webglVendor", "setWebGLVendor"],
1291
+ ["webglRenderer", "setWebGLRenderer"],
1292
+ ];
1293
+ for (const [key, fnName] of setters) {
1294
+ const val = values[key];
1295
+ if (!isNone(val)) {
1296
+ lines.push(` if (typeof w.${fnName} === "function") w.${fnName}(${pyJsonDumps(val)});`);
1297
+ }
1298
+ }
1299
+ // Screen dimensions (requires width + height together)
1300
+ const sw = values.screenWidth;
1301
+ const sh = values.screenHeight;
1302
+ if (pyTruthy(sw) && pyTruthy(sh)) {
1303
+ lines.push(` if (typeof w.setScreenDimensions === "function") w.setScreenDimensions(${sw}, ${sh});`);
1304
+ const scd = values.screenColorDepth;
1305
+ if (pyTruthy(scd)) {
1306
+ lines.push(` if (typeof w.setScreenColorDepth === "function") w.setScreenColorDepth(${scd});`);
1307
+ }
1308
+ }
1309
+ // Timezone -- only with an explicit value; MaskConfig handles the rest.
1310
+ const tz = values.timezone;
1311
+ if (pyTruthy(tz)) {
1312
+ lines.push(` if (typeof w.setTimezone === "function") w.setTimezone(${pyJsonDumps(tz)});`);
1313
+ }
1314
+ // WebRTC IP
1315
+ const ip = values.webrtcIP;
1316
+ if (pyTruthy(ip)) {
1317
+ validateIP(ip);
1318
+ const fnName = validIPv4(ip) ? "setWebRTCIPv4" : "setWebRTCIPv6";
1319
+ lines.push(` if (typeof w.${fnName} === "function") w.${fnName}(${pyJsonDumps(ip)});`);
1320
+ }
1321
+ else {
1322
+ lines.push(' if (typeof w.setWebRTCIPv4 === "function") w.setWebRTCIPv4("");');
1323
+ }
1324
+ // Font list (comma-separated)
1325
+ const fontList = values.fontList;
1326
+ if (fontList?.length) {
1327
+ lines.push(` if (typeof w.setFontList === "function") w.setFontList(${pyJsonDumps(fontList.join(","))});`);
1328
+ }
1329
+ // Speech voices: comma-separated names, or a Linux identity's
1330
+ // speech-dispatcher grid as JSON
1331
+ const voices = values.speechVoices;
1332
+ if (voices && !Array.isArray(voices)) {
1333
+ lines.push(` if (typeof w.setSpeechVoices === "function") w.setSpeechVoices(${pyJsonDumps(asciiJson(voices))});`);
1334
+ }
1335
+ else if (voices?.length) {
1336
+ const names = voices.map((v) => v !== null && typeof v === "object" ? v.name : v);
1337
+ lines.push(` if (typeof w.setSpeechVoices === "function") w.setSpeechVoices(${pyJsonDumps(names.join(","))});`);
1338
+ }
1339
+ lines.push("})();");
1340
+ return lines.join("\n");
1341
+ }
1342
+ /** Python's json.dumps(value, separators=(",", ":")) for plain JSON data. */
1343
+ function asciiJson(value) {
1344
+ return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
1345
+ }
1346
+ /** json.dumps() with its defaults (ASCII-escaped, ", " / ": " separators) for scalars. */
1347
+ function pyJsonDumps(value) {
1348
+ if (typeof value === "string") {
1349
+ return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
1350
+ }
1351
+ if (typeof value === "boolean")
1352
+ return value ? "true" : "false";
1353
+ if (isNone(value))
1354
+ return "null";
1355
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
1356
+ if (Number.isNaN(value))
1357
+ return "NaN";
1358
+ if (!Number.isFinite(value))
1359
+ return value > 0 ? "Infinity" : "-Infinity";
1360
+ return pyStr(value);
1361
+ }
1362
+ return String(value);
1363
+ }
1364
+ /** The OS a navigator.platform value presents, as a Camoufox OS name. */
1365
+ export function targetOsFromPlatform(plat) {
1366
+ if (plat === "Win32")
1367
+ return "windows";
1368
+ if (plat.includes("Linux") || plat.includes("linux"))
1369
+ return "linux";
1370
+ return "macos";
1371
+ }
1372
+ /**
1373
+ * Fingerprint values for a single per-context identity: the init script plus
1374
+ * the Playwright context options (camelCase, for playwright-core).
1375
+ *
1376
+ * By default an fpgen fingerprint is generated; pass a preset to use a real
1377
+ * recorded one instead.
1378
+ *
1379
+ * @param timezone IANA timezone; takes priority over the preset's.
1380
+ * @param locale BCP-47 locale; also sets context_options.locale.
1381
+ * @param config_overrides CAMOU_CONFIG keys applied after the config is built
1382
+ * and before the init script is rendered.
1383
+ * @param webgl_config The [vendor, renderer] a drawn identity claims, instead
1384
+ * of drawing one.
1385
+ */
1386
+ export function generateContextFingerprint({ preset, os, ff_version, webrtc_ip, timezone, locale, config_overrides, webgl_config, } = {}) {
1387
+ let config;
1388
+ let nav;
1389
+ let screen;
1390
+ let webgl;
1391
+ let resolvedPreset;
1392
+ if (!isNone(preset)) {
1393
+ const p = preset;
1394
+ config = fromPreset(p, ff_version);
1395
+ nav = p.navigator ?? {};
1396
+ screen = p.screen ?? {};
1397
+ webgl = p.webgl ?? {};
1398
+ resolvedPreset = p;
1399
+ }
1400
+ else {
1401
+ const fp = generateFingerprint({ os: os ?? undefined });
1402
+ config = fromFpgen(fp, ff_version);
1403
+ // fpgen's Linux pool now and then pairs the Linux UA with a Windows
1404
+ // platform and oscpu. launchOptions() corrects that; this path did not,
1405
+ // so ~1.6% of Linux contexts said Win32 -- and, since the OS below is
1406
+ // read from the platform, drew Windows fonts and voices as well.
1407
+ if (pyStr(get(config, "navigator.userAgent", "")).includes("Linux"))
1408
+ fixNavigatorArch(config, "lin");
1409
+ // A fresh identity: every seeded draw below gets its own salt.
1410
+ const salt = identitySalt();
1411
+ const osName = targetOsFromPlatform(pyStr(get(config, "navigator.platform", "")));
1412
+ if (!("fonts" in config)) {
1413
+ try {
1414
+ config.fonts = generateRandomFontSubset(osName, identitySeed(config, salt));
1415
+ }
1416
+ catch (e) {
1417
+ if (!isPyError(e, "OSError", "ValueError"))
1418
+ throw e;
1419
+ FallbackWarning.warn("Drawing the font list", "the browser's launch-time fonts", e, config["navigator.userAgent"]);
1420
+ }
1421
+ }
1422
+ if (!("voices" in config) && !("voices:speechd" in config)) {
1423
+ try {
1424
+ Object.assign(config, drawVoiceConfig(osName, null, identitySeed(config, salt)));
1425
+ }
1426
+ catch (e) {
1427
+ if (!isPyError(e, "OSError", "ValueError", "KeyError"))
1428
+ throw e;
1429
+ FallbackWarning.warn("Drawing the speech voices", "the browser's launch-time voices", e, config["navigator.userAgent"]);
1430
+ }
1431
+ }
1432
+ if (!("navigator.oscpu" in config)) {
1433
+ const oscpu = oscpuFromPlatform(pyStr(get(config, "navigator.platform", "")));
1434
+ if (oscpu)
1435
+ config["navigator.oscpu"] = oscpu;
1436
+ }
1437
+ if (!pyTruthy(config["webGl:vendor"]) ||
1438
+ !pyTruthy(config["webGl:renderer"])) {
1439
+ const osMap = {
1440
+ macos: "mac",
1441
+ linux: "lin",
1442
+ windows: "win",
1443
+ };
1444
+ let targetOs = osMap[os ?? ""];
1445
+ if (!targetOs) {
1446
+ const plat = pyStr(get(config, "navigator.platform", ""));
1447
+ targetOs =
1448
+ plat === "Win32"
1449
+ ? "win"
1450
+ : plat.includes("Linux") || plat.includes("linux")
1451
+ ? "lin"
1452
+ : "mac";
1453
+ }
1454
+ // Same coherence treatment launchOptions applies (#729): lift netbook
1455
+ // geometry, then keep the GPU consistent with the resulting screen.
1456
+ raiseScreenToModernFloor(config);
1457
+ const webglFp = webgl_config
1458
+ ? webglForGpu(targetOs, ...webgl_config)
1459
+ : sampleWebglForScreen(targetOs, config["screen.width"], config["screen.height"], undefined, config["navigator.hardwareConcurrency"]);
1460
+ delete webglFp.webGl2Enabled;
1461
+ Object.assign(config, webglFp);
1462
+ }
1463
+ nav = {
1464
+ platform: config["navigator.platform"],
1465
+ hardwareConcurrency: config["navigator.hardwareConcurrency"],
1466
+ };
1467
+ screen = {
1468
+ width: config["screen.width"],
1469
+ height: config["screen.height"],
1470
+ colorDepth: config["screen.colorDepth"],
1471
+ devicePixelRatio: null,
1472
+ };
1473
+ webgl = {
1474
+ unmaskedVendor: config["webGl:vendor"],
1475
+ unmaskedRenderer: config["webGl:renderer"],
1476
+ };
1477
+ resolvedPreset = { navigator: nav, screen, webgl };
1478
+ }
1479
+ if (timezone)
1480
+ config.timezone = timezone;
1481
+ if (locale) {
1482
+ const parsed = normalizeLocale(locale);
1483
+ config["locale:language"] = parsed.language;
1484
+ config["locale:region"] = parsed.region;
1485
+ config["navigator.language"] = parsed.asString;
1486
+ if (parsed.script)
1487
+ config["locale:script"] = parsed.script;
1488
+ }
1489
+ if (config_overrides) {
1490
+ const overrides = { ...config_overrides };
1491
+ dropAudioSeed(overrides);
1492
+ Object.assign(config, overrides);
1493
+ }
1494
+ const initValues = {
1495
+ navigatorPlatform: nav.platform,
1496
+ navigatorOscpu: config["navigator.oscpu"],
1497
+ navigatorUserAgent: config["navigator.userAgent"],
1498
+ navigatorAppVersion: config["navigator.appVersion"],
1499
+ hardwareConcurrency: pyTruthy(nav.hardwareConcurrency)
1500
+ ? nav.hardwareConcurrency
1501
+ : config["navigator.hardwareConcurrency"],
1502
+ webglVendor: webgl.unmaskedVendor,
1503
+ webglRenderer: webgl.unmaskedRenderer,
1504
+ screenWidth: screen.width,
1505
+ screenHeight: screen.height,
1506
+ screenColorDepth: screen.colorDepth,
1507
+ timezone: typeof resolvedPreset.timezone === "string"
1508
+ ? resolvedPreset.timezone
1509
+ : config.timezone,
1510
+ fontList: config.fonts,
1511
+ speechVoices: "voices:speechd" in config
1512
+ ? { speechd: config["voices:speechd"] }
1513
+ : config.voices,
1514
+ webrtcIP: webrtc_ip || "",
1515
+ };
1516
+ const initScript = buildInitScript(initValues);
1517
+ const contextOptions = {};
1518
+ const ua = config["navigator.userAgent"];
1519
+ if (pyTruthy(ua))
1520
+ contextOptions.userAgent = ua;
1521
+ const sw = screen.width;
1522
+ const sh = screen.height;
1523
+ if (pyTruthy(sw) && pyTruthy(sh))
1524
+ contextOptions.viewport = { width: sw, height: Math.max(sh - 28, 600) };
1525
+ const dpr = screen.devicePixelRatio;
1526
+ if (pyTruthy(dpr))
1527
+ contextOptions.deviceScaleFactor = dpr;
1528
+ let tz = config.timezone;
1529
+ if (!pyTruthy(tz))
1530
+ tz = resolvedPreset.timezone;
1531
+ if (pyTruthy(tz))
1532
+ contextOptions.timezoneId = tz;
1533
+ const navLang = config["navigator.language"];
1534
+ if (pyTruthy(navLang))
1535
+ contextOptions.locale = navLang;
1536
+ return {
1537
+ init_script: initScript,
1538
+ context_options: contextOptions,
1539
+ config,
1540
+ preset: resolvedPreset,
1541
+ };
1542
+ }
1543
+ // ---------------------------------------------------------------------------
1544
+ // fpgen fingerprints
1545
+ // ---------------------------------------------------------------------------
1546
+ /** Casts an fpgen fingerprint node onto Camoufox config properties. */
1547
+ function castToProperties(camoufoxData, castEnum, fpDict, ffVersion) {
1548
+ for (const [key, raw] of Object.entries(fpDict)) {
1549
+ // Ignore non-truthy values
1550
+ if (!pyTruthy(raw))
1551
+ continue;
1552
+ const typeKey = castEnum[key];
1553
+ if (!pyTruthy(typeKey))
1554
+ continue;
1555
+ if (isPlainObject(raw)) {
1556
+ castToProperties(camoufoxData, typeKey, raw, ffVersion);
1557
+ continue;
1558
+ }
1559
+ let data = raw;
1560
+ // fpgen carries header values as a list; a single string is the value.
1561
+ if (Array.isArray(data)) {
1562
+ if (data.length === 1 && typeof data[0] === "string")
1563
+ data = data[0];
1564
+ else
1565
+ continue;
1566
+ }
1567
+ if (typeof typeKey === "string" &&
1568
+ typeKey.startsWith("screen.") &&
1569
+ (typeof data === "boolean" ||
1570
+ (typeof data === "number" && Number.isInteger(data))) &&
1571
+ Number(data) < 0) {
1572
+ data = 0;
1573
+ }
1574
+ if (ffVersion && typeof data === "string") {
1575
+ data = data.replace(/(?<!\d)(1[0-9]{2})(\.0)(?!\d)/g, (_m, _v, dot) => `${ffVersion}${dot}`);
1576
+ }
1577
+ camoufoxData[typeKey] = data;
1578
+ }
1579
+ }
1580
+ /** Sets window.screenY from the generated screenX value. */
1581
+ function handleScreenXY(camoufoxData, fingerprint) {
1582
+ if ("window.screenY" in camoufoxData)
1583
+ return;
1584
+ const screen = pyTruthy(fingerprint.screen) ? fingerprint.screen : {};
1585
+ const window = pyTruthy(fingerprint.window) ? fingerprint.window : {};
1586
+ const screenX = window.screenX;
1587
+ if (!pyTruthy(screenX)) {
1588
+ camoufoxData["window.screenX"] = 0;
1589
+ camoufoxData["window.screenY"] = 0;
1590
+ return;
1591
+ }
1592
+ if (Number.isInteger(screenX) && screenX >= -50 && screenX <= 50) {
1593
+ camoufoxData["window.screenY"] = screenX;
1594
+ return;
1595
+ }
1596
+ // The generator thinks the browser is windowed. Randomly generate a screenY.
1597
+ const screenY = num(screen.availHeight || 0) - num(window.outerHeight || 0);
1598
+ if (screenY === 0)
1599
+ camoufoxData["window.screenY"] = 0;
1600
+ else if (screenY > 0)
1601
+ camoufoxData["window.screenY"] = random.randrange(0, screenY);
1602
+ else
1603
+ camoufoxData["window.screenY"] = random.randrange(screenY, 0);
1604
+ }
1605
+ /** Converts an fpgen fingerprint to a Camoufox config. */
1606
+ export function fromFpgen(fingerprint, ffVersion) {
1607
+ const camoufoxData = {};
1608
+ castToProperties(camoufoxData, FPGEN_DATA, fingerprint, ffVersion);
1609
+ handleScreenXY(camoufoxData, fingerprint);
1610
+ setAppVersion(camoufoxData);
1611
+ return camoufoxData;
1612
+ }
1613
+ /** Sets a custom outer window size and centers it in the screen (in place). */
1614
+ export function handleWindowSize(fp, outerWidth, outerHeight) {
1615
+ fp.screen ??= {};
1616
+ fp.window ??= {};
1617
+ const screen = fp.screen;
1618
+ const window = fp.window;
1619
+ window.screenX =
1620
+ (window.screenX || 0) +
1621
+ Math.floor(((screen.width || outerWidth) - outerWidth) / 2);
1622
+ window.screenY = Math.floor(((screen.height || outerHeight) - outerHeight) / 2);
1623
+ if (pyTruthy(window.innerWidth)) {
1624
+ window.innerWidth = Math.max(outerWidth - (window.outerWidth || 0) + window.innerWidth, 0);
1625
+ }
1626
+ if (pyTruthy(window.innerHeight)) {
1627
+ window.innerHeight = Math.max(outerHeight - (window.outerHeight || 0) + window.innerHeight, 0);
1628
+ }
1629
+ window.outerWidth = outerWidth;
1630
+ window.outerHeight = outerHeight;
1631
+ }
1632
+ /**
1633
+ * Generates a Firefox fingerprint with fpgen (the model must be installed:
1634
+ * `await ensureModel()` from fpgen).
1635
+ *
1636
+ * `screen` bounds the generated screen; `window` overrides the outer window
1637
+ * size afterwards; `os` is Camoufox's name for the platform; anything else is
1638
+ * passed to fpgen as a condition.
1639
+ */
1640
+ export function generateFingerprint({ window, screen, os, ...conditions } = {}) {
1641
+ if (os?.length) {
1642
+ const names = typeof os === "string" ? [os] : [...os];
1643
+ const resolved = names.map((n) => {
1644
+ const v = FPGEN_OS[String(n).toLowerCase()];
1645
+ if (!v)
1646
+ throw new Error(`Unknown OS for fingerprint generation: '${n}'`);
1647
+ return v;
1648
+ });
1649
+ // fpgen takes one value or a predicate, not a list of alternatives.
1650
+ // DIVERGENCE from Python: fpgen hands a predicate the CASEFOLDED value
1651
+ // ("linux"), so Python's `lambda v: v in set(resolved)` compares it with
1652
+ // "Linux" and never matches -- os=['linux', 'windows'] always raises
1653
+ // InvalidConstraints there. The comparison here is casefolded, so a
1654
+ // list of OSes works.
1655
+ const allowed = new Set(resolved.map((r) => r.toLowerCase()));
1656
+ conditions.os =
1657
+ resolved.length === 1
1658
+ ? resolved[0]
1659
+ : (v) => allowed.has(String(v).toLowerCase());
1660
+ }
1661
+ const screenConditions = screen ? screen.asConditions() : {};
1662
+ let fingerprint;
1663
+ try {
1664
+ fingerprint = generate({
1665
+ browser: "Firefox",
1666
+ ...conditions,
1667
+ ...screenConditions,
1668
+ });
1669
+ }
1670
+ catch (err) {
1671
+ if (!Object.keys(screenConditions).length ||
1672
+ !(err instanceof InvalidConstraints))
1673
+ throw err;
1674
+ // The screen bound is best-effort: a display the pool has nothing to fit
1675
+ // must not stop a fingerprint being generated. clampScreenToDisplay()
1676
+ // still bounds the result afterwards.
1677
+ fingerprint = generate({ browser: "Firefox", ...conditions });
1678
+ }
1679
+ if (window)
1680
+ handleWindowSize(fingerprint, window[0], window[1]);
1681
+ return fingerprint;
1682
+ }