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,1995 @@
1
+ /**
2
+ * Launch-option assembly, the twin of utils.py: launchOptions() must return what
3
+ * launch_options() does (tests/launch-golden.test.ts). `utilsDeps` holds what the
4
+ * Python tests monkeypatch.
5
+ */
6
+ import { execFileSync } from "node:child_process";
7
+ import { createHash } from "node:crypto";
8
+ import * as fs from "node:fs";
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
11
+ import { inspect } from "node:util";
12
+ import { ensureModel } from "fpgen-js";
13
+ import { UAParser } from "ua-parser-js";
14
+ import * as cpuAffinity from "../cpu_affinity.js";
15
+ import { hasDisplay, largestDisplay } from "../display.js";
16
+ import { allowGeoip, geoipAllowed, getGeolocation } from "../geolocation.js";
17
+ import { ProxyHelper, publicIP, validIPv4, validIPv6, } from "../ip.js";
18
+ import { handleLocales } from "../locales.js";
19
+ import { VirtualDisplay } from "../virtdisplay.js";
20
+ import { addDefaultAddons, confirmPaths } from "./addons.js";
21
+ import * as coherence from "./coherence.js";
22
+ import { applyDisplayProfile, } from "./display_profile.js";
23
+ import { InvalidOS, InvalidPropertyType, NonFirefoxFingerprint, UnknownIPLocation, UnknownProperty, } from "./exceptions.js";
24
+ import { clampScreenToDisplay, clampWindowDimensions, clampWindowPosition, drawVoiceConfig, dropAudioSeed, fixHardwareConcurrency, fixNavigatorArch, followBaselineProtection, fromFpgen, fromPreset, generateFingerprint, generateRandomFontSubset, generateRandomVoiceSubset, getRandomPreset, identitySalt, identitySeed, loadOsFonts, raiseScreenToModernFloor, Screen, setCpuDefault, setMediaDevicesDefaults, targetOsFromPlatform, WINDOWS_11_MARKER_FONTS, } from "./fingerprints.js";
25
+ import { GPU_PREFS, GpuDisplay, proveGpu, selectGpu } from "./gpudisplay.js";
26
+ import { addCanvasPlaceholder, hasCanvasPlaceholder, hostGpu, setWebgpu, } from "./host_rendering.js";
27
+ import { normalize } from "./humanize.js";
28
+ import { proxyAuthEnv, proxyAuthInitScript, publicIPv6, socks5Auth, } from "./ip.js";
29
+ import { INSTALL_DIR, LAUNCHER_CONSTANTS, OS_NAME } from "./paths.js";
30
+ import { buildFile, effectiveVersionMin, ensureBrowserProfileDir, ensureCamoufoxInstalled, getPath, installedVerStr, launchPath, resolvedPlaywrightVersionStr, selectedLaunchPath, Version, warnIfPackageOutdated, } from "./pkgman.js";
31
+ import { PRODUCT } from "./product.js";
32
+ import { comparePyStr, formatPyFloatRepr, isPlainObject, isPyError, orjsonDumps, PyFloat, pyRepr, pyStr, pyTruthy, pyTypeName, ValueError, } from "./pycompat.js";
33
+ import { FallbackWarning, LeakWarning, loadWarnings, warn, } from "./warnings.js";
34
+ import { firefoxGpus, sampleWebglForScreen, webglForGpu } from "./webgl.js";
35
+ /** The value a persistent profile's prefs.js holds for `pref` (undefined when none). Mirrors Python's saved_pref. */
36
+ export function savedPref(profileDir, pref) {
37
+ if (!profileDir)
38
+ return undefined;
39
+ let text;
40
+ try {
41
+ text = fs.readFileSync(path.join(profileDir, "prefs.js"), "utf-8");
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ const escaped = pref.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
47
+ const m = new RegExp(`user_pref\\("${escaped}",\\s*(.+?)\\);`).exec(text);
48
+ if (!m)
49
+ return undefined;
50
+ try {
51
+ return JSON.parse(m[1]);
52
+ }
53
+ catch {
54
+ return m[1];
55
+ }
56
+ }
57
+ /** Write a toggle only when on, or to clear a persistent non-stock value. */
58
+ export function setTogglePref(prefs, pref, on, stock, toggled, profileDir) {
59
+ if (on) {
60
+ prefs[pref] ??= toggled;
61
+ return;
62
+ }
63
+ const saved = savedPref(profileDir, pref);
64
+ if (saved !== undefined && saved !== stock)
65
+ prefs[pref] ??= stock;
66
+ }
67
+ /** The OS names Camoufox takes, by target_os key. */
68
+ const OS_NAMES = { win: "windows", mac: "macos", lin: "linux" };
69
+ // Camoufox preferences to cache previous pages and requests
70
+ export const CACHE_PREFS = LAUNCHER_CONSTANTS.cachePrefs;
71
+ // Behind a SOCKS5 proxy with proxy_dns "doh": names are resolved by DoH alone,
72
+ // at the resolver Firefox's own DoH rollout uses (docs/proxy-dns.md).
73
+ export const PROXY_DOH_PREFS = LAUNCHER_CONSTANTS.proxyDohPrefs;
74
+ /**
75
+ * Whether the dynamic linker can find a system libavcodec, which Linux
76
+ * Firefox loads for H.264 (as Python's ctypes.util.find_library('avcodec')).
77
+ */
78
+ function hasSystemAvcodec() {
79
+ for (const ldconfig of ["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"]) {
80
+ try {
81
+ const out = execFileSync(ldconfig, ["-p"], {
82
+ encoding: "utf-8",
83
+ stdio: ["ignore", "pipe", "ignore"],
84
+ });
85
+ return /\blibavcodec\.so/.test(out);
86
+ }
87
+ catch { }
88
+ }
89
+ return true; // cannot tell: do not warn
90
+ }
91
+ // Prefs whose Firefox default differs between the Windows and Linux builds and
92
+ // that a page or the user can observe, at the Windows default (see
93
+ // WINDOWS_BEHAVIOUR_PREFS in the Python launcher for each one's reason).
94
+ export const WINDOWS_BEHAVIOUR_PREFS = LAUNCHER_CONSTANTS.windowsBehaviourPrefs;
95
+ /** Monitor pixels per CSS pixel of the window at the scale it renders at.
96
+ * Linux reports the monitor in pixels at scale 1. On Windows and macOS the
97
+ * host's own scaling is already in the bounds and is not known here, so 1. */
98
+ function physicalScale(config, prefs = {}) {
99
+ if (utilsDeps.osName() !== "lin")
100
+ return 1;
101
+ // -1 is Firefox's "the system's".
102
+ const pref = Number(prefs["layout.css.devPixelsPerPx"] ?? -1);
103
+ return pref > 0 ? pref : Number(config["window.devicePixelRatio"] || 1);
104
+ }
105
+ /** The host OS in fonts.json / target_os terms ('mac', 'win', 'lin'). */
106
+ function hostOsKey() {
107
+ return ({ darwin: "mac", win32: "win", linux: "lin" }[process.platform] ?? null);
108
+ }
109
+ // navigator.storage.estimate().quota is not a constant: Gecko derives it from
110
+ // the disk. GetTemporaryStorageLimit() (dom/quota/ActorsParent.cpp) takes
111
+ // nsIFile::GetDiskCapacity() of the storage directory and halves it, then
112
+ // QuotaManager::GetGroupLimitForLimit() reports min(that / 5, 10 GiB) to the
113
+ // page -- so any disk of 100 GB or more reads back as exactly 10 GiB, and a
114
+ // smaller one as its own capacity / 10.
115
+ const QUOTA_FIXED_LIMIT_PREF = "dom.quotaManager.temporaryStorage.fixedLimit";
116
+ // The pref is a signed 32-bit int in KB. Any value above 50 GiB already reports
117
+ // the 10 GiB group cap, so clamping a multi-terabyte disk changes nothing a page
118
+ // can see.
119
+ const INT32_MAX = 2 ** 31 - 1;
120
+ /** shutil.disk_usage(path).total */
121
+ function diskTotal(p) {
122
+ const st = fs.statfsSync(p);
123
+ return st.blocks * st.bsize;
124
+ }
125
+ /**
126
+ * Half the capacity of the disk a stock Firefox profile would live on, in KB.
127
+ *
128
+ * That is the number Gecko's own GetTemporaryStorageLimit() would compute on
129
+ * this machine, and it is what `dom.quotaManager.temporaryStorage.fixedLimit`
130
+ * takes. The disk a stock profile lives on, not the one Playwright's throwaway
131
+ * profile lands on: on a host whose temp directory is a tmpfs, that profile
132
+ * sits on a RAM-sized volume no real Firefox profile would.
133
+ */
134
+ function stockProfileDiskCapacityKb() {
135
+ const home = os.homedir();
136
+ let candidates;
137
+ const osName = utilsDeps.osName();
138
+ if (osName === "win") {
139
+ const appdata = process.env.APPDATA;
140
+ candidates = [appdata ? path.join(appdata, "Mozilla") : home, home];
141
+ }
142
+ else if (osName === "mac") {
143
+ candidates = [
144
+ path.join(home, "Library", "Application Support", "Firefox"),
145
+ home,
146
+ ];
147
+ }
148
+ else {
149
+ candidates = [path.join(home, ".mozilla"), home];
150
+ }
151
+ for (const candidate of candidates) {
152
+ // The directory only exists if Firefox has ever run here; walk up to the
153
+ // first path that does, which is on the same filesystem anyway.
154
+ let probe = candidate;
155
+ while (!fs.existsSync(probe) && probe !== path.dirname(probe)) {
156
+ probe = path.dirname(probe);
157
+ }
158
+ let total;
159
+ try {
160
+ total = utilsDeps.diskTotal(probe);
161
+ }
162
+ catch {
163
+ continue;
164
+ }
165
+ if (total > 0) {
166
+ return Math.min(Math.floor(Math.floor(total / 2) / 1024), INT32_MAX);
167
+ }
168
+ }
169
+ return null;
170
+ }
171
+ /**
172
+ * Injection points: everything launchOptions() reaches outside this module.
173
+ * Mirrors the names the Python tests monkeypatch on camoufox.utils.
174
+ */
175
+ export const utilsDeps = {
176
+ osName: () => OS_NAME,
177
+ installDir: () => INSTALL_DIR,
178
+ hostOsKey,
179
+ diskTotal,
180
+ stockProfileDiskCapacityKb,
181
+ hasDisplay,
182
+ largestDisplay,
183
+ getScreenCons: (headless) => getScreenCons(headless),
184
+ print: (line) => {
185
+ process.stdout.write(`${line}\n`);
186
+ },
187
+ ensureBrowserProfileDir,
188
+ ensureCamoufoxInstalled,
189
+ addDefaultAddons,
190
+ confirmPaths,
191
+ installedVerStr: () => installedVerStr(),
192
+ effectiveVersionMin,
193
+ resolvedPlaywrightVersionStr,
194
+ getPath,
195
+ launchPath,
196
+ selectedLaunchPath,
197
+ identitySalt,
198
+ identitySeed,
199
+ generateFingerprint: async (options) => {
200
+ // fpgen's model is fetched on first use, like Python's.
201
+ await ensureModel();
202
+ return generateFingerprint(options);
203
+ },
204
+ fromFpgen,
205
+ fromPreset,
206
+ getRandomPreset,
207
+ fixNavigatorArch,
208
+ fixHardwareConcurrency,
209
+ followBaselineProtection,
210
+ clampScreenToDisplay,
211
+ clampWindowDimensions,
212
+ clampWindowPosition,
213
+ raiseScreenToModernFloor,
214
+ generateRandomFontSubset,
215
+ generateRandomVoiceSubset,
216
+ drawVoiceConfig,
217
+ setMediaDevicesDefaults,
218
+ hostGpu,
219
+ selectGpu,
220
+ // The WebGL draws read fpgen's model, fetched on first use like Python's.
221
+ firefoxGpus: async (targetOs) => {
222
+ await ensureModel();
223
+ return firefoxGpus(targetOs);
224
+ },
225
+ webglForGpu: async (...args) => {
226
+ await ensureModel();
227
+ return webglForGpu(...args);
228
+ },
229
+ sampleWebglForScreen: async (...args) => {
230
+ await ensureModel();
231
+ return sampleWebglForScreen(...args);
232
+ },
233
+ publicIp: publicIP,
234
+ publicIpv6: publicIPv6,
235
+ getGeolocation,
236
+ validateConfig: (config, p) => validateConfig(config, p),
237
+ getEnvVars: (config, uaOs, p) => getEnvVars(config, uaOs, p),
238
+ };
239
+ /*
240
+ * Python-compatible serialisation helpers
241
+ */
242
+ /**
243
+ * json.dumps(value, ensure_ascii=True, separators=(',', ':')): compact, every
244
+ * non-ASCII (and DEL) character \u-escaped, floats in Python's repr.
245
+ */
246
+ export function pyJsonDumpsAscii(value) {
247
+ const encode = (v) => {
248
+ if (v === null || v === undefined)
249
+ return "null";
250
+ if (v === true)
251
+ return "true";
252
+ if (v === false)
253
+ return "false";
254
+ if (typeof v === "number") {
255
+ if (Number.isInteger(v))
256
+ return String(v);
257
+ if (Number.isNaN(v))
258
+ return "NaN";
259
+ if (!Number.isFinite(v))
260
+ return v > 0 ? "Infinity" : "-Infinity";
261
+ return formatPyFloatRepr(v);
262
+ }
263
+ if (typeof v === "bigint")
264
+ return v.toString();
265
+ if (v instanceof PyFloat)
266
+ return formatPyFloatRepr(v.value);
267
+ if (typeof v === "string") {
268
+ return JSON.stringify(v).replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
269
+ }
270
+ if (Array.isArray(v))
271
+ return `[${v.map(encode).join(",")}]`;
272
+ return `{${Object.entries(v)
273
+ .map(([k, x]) => `${encode(k)}:${encode(x)}`)
274
+ .join(",")}}`;
275
+ };
276
+ return encode(value);
277
+ }
278
+ /**
279
+ * orjson.dumps(config): compact, UTF-8, insertion order. JavaScript has one
280
+ * number type, so the Python int/float split is carried the way pycompat
281
+ * carries it: a safe-integer number is an int, a bigint is an int beyond
282
+ * 2**53, a PyFloat is an integral float, and any other number is a float.
283
+ */
284
+ export function configJson(value) {
285
+ return orjsonDumps(value, false);
286
+ }
287
+ /** Slice `s` into chunks of `size` code points (Python str slicing). */
288
+ function chunkCodePoints(s, size) {
289
+ // Fast path: no astral characters, so UTF-16 units == code points.
290
+ if (!/[\ud800-\udfff]/.test(s)) {
291
+ const out = [];
292
+ for (let i = 0; i < s.length; i += size)
293
+ out.push(s.slice(i, i + size));
294
+ return out;
295
+ }
296
+ const cps = Array.from(s);
297
+ const out = [];
298
+ for (let i = 0; i < cps.length; i += size) {
299
+ out.push(cps.slice(i, i + size).join(""));
300
+ }
301
+ return out;
302
+ }
303
+ /*
304
+ * Environment
305
+ */
306
+ /**
307
+ * Generates a runtime fontconfig that resolves bundled font paths absolutely.
308
+ * The bundled fonts.conf uses prefix="cwd" relative paths which break when
309
+ * Playwright's working directory differs from the browser install directory.
310
+ * Writes a patched copy to the platform cache dir (deterministic, only
311
+ * regenerated when content changes). This must not live inside the versioned
312
+ * browser bundle: the bundle is commonly baked into an image as root and run
313
+ * as a non-root user, so it is read-only at launch time.
314
+ */
315
+ function generateFontconfig(fontconfigPath, executablePath, osDir) {
316
+ // Beside the caller's own binary when they supplied one; see getEnvVars.
317
+ const fontsDir = executablePath
318
+ ? path.join(path.dirname(executablePath), "fonts")
319
+ : utilsDeps.getPath("fonts");
320
+ // Which directories this identity's OS may see.
321
+ //
322
+ // fontconfig scans <dir> RECURSIVELY, so the parent must never be named: it
323
+ // would make every other OS's files reachable by the renderer -- hidden by
324
+ // the allowlist for direct lookups, but still candidates for glyph fallback.
325
+ //
326
+ // The bundle stores each face ONCE, in a directory named for the set of
327
+ // OSes that use it (L, M, W, LM, LW, MW, LMW) -- see browser/bundle/fonts/groups.json
328
+ // and browser/scripts/gen-font-groups.py. An OS reads the groups its letter appears
329
+ // in, so nothing has to be hidden after the fact.
330
+ let scanDirs = [];
331
+ const groupsPath = path.join(fontsDir, "groups.json");
332
+ const osKey = { linux: "lin", macos: "mac", windows: "win" }[osDir ?? ""];
333
+ if (osKey && fs.existsSync(groupsPath)) {
334
+ try {
335
+ const parsed = JSON.parse(fs.readFileSync(groupsPath, "utf-8"));
336
+ const readBy = parsed?.readBy?.[osKey] ?? [];
337
+ scanDirs = readBy
338
+ .map((g) => path.join(fontsDir, g))
339
+ .filter((d) => isDir(d));
340
+ }
341
+ catch {
342
+ scanDirs = [];
343
+ }
344
+ }
345
+ if (!scanDirs.length) {
346
+ // Older bundles ship fonts/<os>/ with each OS's set duplicated in full.
347
+ if (osDir && isDir(path.join(fontsDir, osDir))) {
348
+ scanDirs = [path.join(fontsDir, osDir)];
349
+ }
350
+ else {
351
+ scanDirs = [fontsDir];
352
+ }
353
+ }
354
+ const fontsConfSrc = path.join(fontconfigPath, "fonts.conf");
355
+ let confContent = fs.readFileSync(fontsConfSrc, "utf-8");
356
+ confContent = confContent.replace('<dir prefix="cwd">fonts</dir>', scanDirs.map((d) => `<dir>${d}</dir>`).join("\n\t"));
357
+ // INSTALL_DIR is platformdirs' user_cache_dir("camoufox"); see paths.ts.
358
+ const cacheDir = path.join(utilsDeps.installDir(), "fontconfig");
359
+ fs.mkdirSync(cacheDir, { recursive: true });
360
+ const contentHash = createHash("sha256")
361
+ .update(confContent)
362
+ .digest("hex")
363
+ .slice(0, 12);
364
+ const runtimeConf = path.join(cacheDir, `fonts-${contentHash}.conf`);
365
+ if (!fs.existsSync(runtimeConf)) {
366
+ fs.writeFileSync(runtimeConf, confContent);
367
+ }
368
+ return runtimeConf;
369
+ }
370
+ function isDir(p) {
371
+ try {
372
+ return fs.statSync(p).isDirectory();
373
+ }
374
+ catch {
375
+ return false;
376
+ }
377
+ }
378
+ /**
379
+ * Warn when a caller's own binary is older than their Playwright needs.
380
+ *
381
+ * A managed install below the floor is simply upgraded (pkgman resolves it),
382
+ * but `executable_path` deliberately bypasses that. That leaves the one
383
+ * pairing nothing checks: an old build driven by Playwright >= 1.61, which
384
+ * sends viewport fields the older Juggler schema rejects. Warns rather than
385
+ * raises: the default no-viewport path still works on an old build. A build
386
+ * with no version.json beside it tells us nothing, so it is left alone.
387
+ */
388
+ export function warnIfExecutablePredatesPlaywright(executablePath) {
389
+ if (!executablePath)
390
+ return;
391
+ let installed;
392
+ try {
393
+ installed = Version.fromPath(path.dirname(executablePath));
394
+ }
395
+ catch {
396
+ return;
397
+ }
398
+ const required = utilsDeps.effectiveVersionMin();
399
+ if (!installed.lessThan(required))
400
+ return;
401
+ warn(`The Camoufox build at ${executablePath} is ${installed.build}, but Playwright ` +
402
+ `${utilsDeps.resolvedPlaywrightVersionStr()} needs at least ${required.build}. ` +
403
+ "Contexts created with an explicit viewport will fail with " +
404
+ '"Protocol error (Browser.setDefaultViewport)". Update the build, or pin ' +
405
+ "playwright<1.61.", "RuntimeWarning");
406
+ }
407
+ /**
408
+ * Pass the launcher's Firefox prefs to browser/settings/camoufox.cfg, which applies them
409
+ * at STARTUP (CAMOU_PREFS_1..N, chunked like CAMOU_CONFIG).
410
+ *
411
+ * Playwright's non-persistent launch writes no user.js: firefoxUserPrefs only
412
+ * reach the browser at runtime, through juggler's Browser.enable, after
413
+ * startup. Anything Gecko reads during startup therefore raced or never
414
+ * applied.
415
+ */
416
+ export function getPrefEnvVars(prefs) {
417
+ if (!prefs || !Object.keys(prefs).length)
418
+ return {};
419
+ // ASCII only: on Windows autoconfig's getenv() reads the environment through
420
+ // the ANSI code page, which would mangle a raw UTF-8 pref value (\u escapes
421
+ // survive it and JSON.parse restores them).
422
+ const data = pyJsonDumpsAscii(prefs);
423
+ const chunkSize = utilsDeps.osName() === "win" ? 2047 : 32767;
424
+ const out = {};
425
+ chunkCodePoints(data, chunkSize).forEach((chunk, i) => {
426
+ out[`CAMOU_PREFS_${i + 1}`] = chunk;
427
+ });
428
+ return out;
429
+ }
430
+ /**
431
+ * Gets the environment variables for Camoufox: the chunked CAMOU_CONFIG, plus
432
+ * the Linux fontconfig pointer.
433
+ *
434
+ * `executablePath` is the caller's own executable, when they supplied one. The
435
+ * bundled fontconfig is read from beside that binary rather than from the
436
+ * managed install, the same way loadProperties() treats properties.json.
437
+ */
438
+ export function getEnvVars(configMap, userAgentOs, executablePath) {
439
+ const envVars = {};
440
+ const configStr = configJson(configMap);
441
+ // Split the config into chunks
442
+ const osName = utilsDeps.osName();
443
+ const chunkSize = osName === "win" ? 2047 : 32767;
444
+ chunkCodePoints(configStr, chunkSize).forEach((chunk, i) => {
445
+ envVars[`CAMOU_CONFIG_${i + 1}`] = chunk;
446
+ });
447
+ if (osName === "lin") {
448
+ // https://github.com/coryking/camoufox/commit/f21eeb2850a74cc104fb57e17e0a2fa27b7a2a28
449
+ // Thanks @coryking
450
+ const directoryMap = {
451
+ lin: "linux",
452
+ mac: "macos",
453
+ win: "windows",
454
+ };
455
+ const osDir = directoryMap[userAgentOs] ?? userAgentOs;
456
+ // v150+ uses "fontconfig/" (matching the Go launcher); older bundles
457
+ // shipped "fontconfigs/".
458
+ const bundlePath = (...parts) => executablePath
459
+ ? path.join(path.dirname(executablePath), ...parts)
460
+ : utilsDeps.getPath(path.join(...parts));
461
+ let fontconfigPath = bundlePath("fontconfig", osDir);
462
+ if (!fs.existsSync(path.join(fontconfigPath, "fonts.conf"))) {
463
+ fontconfigPath = bundlePath("fontconfigs", osDir);
464
+ }
465
+ if (!fs.existsSync(path.join(fontconfigPath, "fonts.conf"))) {
466
+ const err = new Error(`fonts.conf not found in ${fontconfigPath}! Something ain't right with your camoufox bundle.`);
467
+ err.name = "FileNotFoundError";
468
+ throw err;
469
+ }
470
+ envVars.FONTCONFIG_FILE = generateFontconfig(fontconfigPath, executablePath, osDir);
471
+ }
472
+ return envVars;
473
+ }
474
+ /**
475
+ * Loads the properties.json file: property -> its entry. An entry with a
476
+ * "removed" field is a key the browser no longer reads; it stays declared so
477
+ * that older libraries, which reject undeclared keys, still launch.
478
+ */
479
+ function loadProperties(executablePath) {
480
+ const propFile = executablePath
481
+ ? buildFile(executablePath, "properties.json")
482
+ : utilsDeps.getPath("properties.json");
483
+ const propDict = JSON.parse(fs.readFileSync(propFile, "utf-8"));
484
+ const out = {};
485
+ for (const prop of propDict)
486
+ out[prop.property] = prop;
487
+ return out;
488
+ }
489
+ /** True when CAMOUFOX_STRICT_CONFIG asks validateConfig to reject unknown keys. */
490
+ export function strictConfig() {
491
+ const value = (PRODUCT.getenv("STRICT_CONFIG") ?? "").trim().toLowerCase();
492
+ return !["", "0", "false", "no"].includes(value);
493
+ }
494
+ /**
495
+ * Validates the config map against the build's properties.json, and lifts a
496
+ * numeric value below its declared `min` up to it.
497
+ *
498
+ * A key the build does not declare is reported and skipped, so a newer library
499
+ * still launches an older build. With CAMOUFOX_STRICT_CONFIG=1 it throws
500
+ * UnknownProperty instead: CI sets it against the newest release, so the
501
+ * launcher cannot ship a writer for a key no released browser reads.
502
+ */
503
+ export function validateConfig(configMap, executablePath) {
504
+ const properties = loadProperties(executablePath);
505
+ const strict = strictConfig();
506
+ for (const [key, value] of Object.entries(configMap)) {
507
+ const entry = properties[key];
508
+ if (!entry) {
509
+ if (strict) {
510
+ throw new UnknownProperty(`Unknown property '${key}': this Camoufox build reads no such config key ` +
511
+ `(${PRODUCT.envVar("STRICT_CONFIG")} is set).`);
512
+ }
513
+ if (key === "voices:speechd") {
514
+ LeakWarning.warn(loadWarnings().voices_unread);
515
+ }
516
+ utilsDeps.print(`Skipping unknown patch ${key} : ${pyStr(value)}`);
517
+ continue; // Property not supported by this browser version; skip silently
518
+ }
519
+ if (entry.removed !== undefined) {
520
+ utilsDeps.print(`Skipping ${key}: removed in ${entry.removed}, it has no effect`);
521
+ continue;
522
+ }
523
+ const expectedType = entry.type;
524
+ if (!validateType(value, expectedType)) {
525
+ throw new InvalidPropertyType(`Invalid type for property ${key}. Expected ${expectedType}, got ${pyTypeName(value)}`);
526
+ }
527
+ if (entry.min !== undefined) {
528
+ const n = value instanceof PyFloat ? value.value : Number(value);
529
+ if (n < entry.min)
530
+ configMap[key] = entry.min;
531
+ }
532
+ if (key === "voices:speechd") {
533
+ validateSpeechdVoices(value);
534
+ }
535
+ if (key === "voices") {
536
+ validateVoices(value);
537
+ }
538
+ }
539
+ }
540
+ /**
541
+ * Validates the type of the value. (Python's bool is an int, so a boolean
542
+ * passes the numeric checks there, and here.)
543
+ */
544
+ export function validateType(value, expectedType) {
545
+ if (value instanceof PyFloat) {
546
+ // A Python float: int/uint only when it is integral (float.is_integer()).
547
+ const v = value.value;
548
+ if (expectedType === "double")
549
+ return true;
550
+ if (expectedType === "int")
551
+ return Number.isInteger(v);
552
+ if (expectedType === "uint")
553
+ return Number.isInteger(v) && v >= 0;
554
+ return false;
555
+ }
556
+ const isInt = typeof value === "boolean" ||
557
+ typeof value === "bigint" ||
558
+ (typeof value === "number" && Number.isInteger(value));
559
+ switch (expectedType) {
560
+ case "str":
561
+ return typeof value === "string";
562
+ case "int":
563
+ return isInt;
564
+ case "uint":
565
+ return isInt && Number(value) >= 0;
566
+ case "double":
567
+ return typeof value === "number" || isInt;
568
+ case "bool":
569
+ return typeof value === "boolean";
570
+ case "array":
571
+ return Array.isArray(value);
572
+ case "dict":
573
+ return (typeof value === "object" && value !== null && !Array.isArray(value));
574
+ default:
575
+ return false;
576
+ }
577
+ }
578
+ // The five fields MaskConfig::MVoices() requires of every `voices` entry. It
579
+ // skips anything missing one of them, so a bare "Name:lang:type" string or a
580
+ // half-filled object registers nothing -- and a voice list that registers
581
+ // nothing leaves the host's native voices exposed (#731).
582
+ const VOICE_FIELDS = [
583
+ "lang",
584
+ "name",
585
+ "voiceUri",
586
+ "isDefault",
587
+ "isLocalService",
588
+ ];
589
+ /**
590
+ * Validates that every `voices` entry is a complete voice object.
591
+ */
592
+ export function validateVoices(voices) {
593
+ if (!Array.isArray(voices)) {
594
+ throw new InvalidPropertyType(`Invalid type for property voices. Expected array, got ${pyTypeName(voices)}`);
595
+ }
596
+ voices.forEach((voice, index) => {
597
+ if (typeof voice !== "object" || voice === null || Array.isArray(voice)) {
598
+ throw new InvalidPropertyType(`Invalid voices[${index}]: expected an object with ` +
599
+ `{${VOICE_FIELDS.join(", ")}}, got ${pyTypeName(voice)} ` +
600
+ `(${pyRepr(voice)}). Camoufox needs full voice objects, not names.`);
601
+ }
602
+ const missing = VOICE_FIELDS.filter((field) => !(field in voice));
603
+ if (missing.length) {
604
+ throw new InvalidPropertyType(`Invalid voices[${index}]: missing ${missing.join(", ")}. ` +
605
+ `Every voice needs {${VOICE_FIELDS.join(", ")}}.`);
606
+ }
607
+ });
608
+ }
609
+ /**
610
+ * Validates a `voices:speechd` grid: {"languages": [[name, lang], ...],
611
+ * "variants": [name, ...]}, the shape MaskConfig::MSpeechdVoices() expands.
612
+ */
613
+ export function validateSpeechdVoices(grid) {
614
+ const { languages, variants } = grid ?? {};
615
+ const ok = Array.isArray(languages) &&
616
+ languages.every((e) => Array.isArray(e) &&
617
+ e.length === 2 &&
618
+ e.every((x) => typeof x === "string")) &&
619
+ Array.isArray(variants) &&
620
+ variants.every((v) => typeof v === "string");
621
+ if (!ok) {
622
+ throw new InvalidPropertyType('Invalid voices:speechd: expected {"languages": [[name, lang], ...], "variants": [name, ...]}');
623
+ }
624
+ }
625
+ /**
626
+ * Gets the OS from the config if the user agent is set, otherwise returns the
627
+ * OS of the current system.
628
+ */
629
+ export function getTargetOs(config) {
630
+ if (config["navigator.userAgent"]) {
631
+ return determineUaOs(config["navigator.userAgent"]);
632
+ }
633
+ return utilsDeps.osName();
634
+ }
635
+ /**
636
+ * Determines the OS from the user agent string.
637
+ */
638
+ export function determineUaOs(userAgent) {
639
+ // Python's ua_parser answers "Other" rather than nothing for an
640
+ // unrecognised UA, so its `raise` never fires and "lin" is what runs.
641
+ const parsed = new UAParser(userAgent).getOS().name || "Other";
642
+ // ua-parser-js reports "macOS"; the Python ua_parser reports "Mac OS X".
643
+ if (parsed.startsWith("Mac") || parsed.startsWith("macOS"))
644
+ return "mac";
645
+ if (parsed.startsWith("Windows"))
646
+ return "win";
647
+ return "lin";
648
+ }
649
+ /**
650
+ * Determines a sane viewport size for Camoufox if being ran in headful mode.
651
+ *
652
+ * Bounds are CSS pixels, the unit Firefox lays its windows out in -- see
653
+ * display.ts for why that differs from the monitor's physical size.
654
+ */
655
+ export function getScreenCons(headless) {
656
+ if (headless === true) {
657
+ return null; // Skip if headless
658
+ }
659
+ const display = utilsDeps.largestDisplay();
660
+ if (display === null) {
661
+ return null; // Skip if the display can't be probed
662
+ }
663
+ return new Screen({ maxWidth: display.width, maxHeight: display.height });
664
+ }
665
+ /**
666
+ * Updates the fonts for the target OS.
667
+ */
668
+ function updateFonts(config, targetOs) {
669
+ const fonts = [...loadOsFonts()[targetOs]];
670
+ // Merge with existing fonts (np.unique sorts)
671
+ if ("fonts" in config) {
672
+ config.fonts = [...new Set([...fonts, ...config.fonts])].sort(comparePyStr);
673
+ }
674
+ else {
675
+ config.fonts = fonts;
676
+ }
677
+ }
678
+ /**
679
+ * Asserts that the passed fingerprint is a valid Firefox fingerprint, and
680
+ * warns that passing one is not recommended.
681
+ */
682
+ function checkCustomFingerprint(fingerprint) {
683
+ const userAgent = fingerprint?.navigator?.userAgent || "";
684
+ const browserName = parseUaFamily(userAgent);
685
+ if (browserName !== "Firefox") {
686
+ throw new NonFirefoxFingerprint(`"${browserName}" fingerprints are not supported in Camoufox. ` +
687
+ "Using fingerprints from a browser other than Firefox WILL lead to detection. " +
688
+ "If this is intentional, pass `i_know_what_im_doing=True`.");
689
+ }
690
+ LeakWarning.warn(loadWarnings().custom_fingerprint, false);
691
+ }
692
+ /** ua_parser.user_agent_parser.ParseUserAgent(ua)['family']. */
693
+ function parseUaFamily(userAgent) {
694
+ const name = new UAParser(userAgent).getBrowser().name;
695
+ if (!name)
696
+ return "Other";
697
+ // ua-parser-js and uap-core name a few browsers differently.
698
+ const map = {
699
+ "Mobile Firefox": "Firefox Mobile",
700
+ "Mobile Chrome": "Chrome Mobile",
701
+ "Mobile Safari": "Mobile Safari",
702
+ };
703
+ return map[name] ?? name;
704
+ }
705
+ /**
706
+ * general.cpu_identity for the identity's CPU: 0 compute as the host, 1 Intel
707
+ * x86, 2 AMD x86, 3 ARM64 (every ARM64 CPU computes alike).
708
+ */
709
+ export function cpuIdentityPref(config) {
710
+ const arch = config["cpu:arch"] ?? null;
711
+ const maker = config["cpu:manufacturer"] ?? null;
712
+ const table = LAUNCHER_CONSTANTS.cpuIdentityPref;
713
+ if (arch === "arm")
714
+ return table.arm;
715
+ if (arch !== "x86" && arch !== null)
716
+ return 0;
717
+ const key = `x86/${pyStr(maker)}`;
718
+ return Object.hasOwn(table, key) ? table[key] : 0;
719
+ }
720
+ /**
721
+ * media.libvpx.realtime_only: Firefox builds libvpx realtime-only for Windows
722
+ * and Linux on ARM64 (not macOS), which changes the WebCodecs VP8/VP9 encoders'
723
+ * output and rejects quality-mode VP8 outright.
724
+ */
725
+ export function vpxRealtimeOnly(config, targetOs) {
726
+ return (config["cpu:arch"] === "arm" && (targetOs === "win" || targetOs === "lin"));
727
+ }
728
+ const CPU_OS_NAMES = {
729
+ windows: "win",
730
+ macos: "mac",
731
+ linux: "lin",
732
+ };
733
+ /**
734
+ * The OSes a machine with this CPU can run, among those asked for, as
735
+ * utils._os_for_cpu. Throws ValueError when the CPU is malformed or none of
736
+ * them can. With no OS asked for, only OSes with a GPU fpgen recorded beside
737
+ * such a CPU are drawn: an ARM identity is a Mac, or Linux rendering with
738
+ * llvmpipe, until Windows-on-ARM or Linux-on-ARM GPUs are recorded.
739
+ */
740
+ export async function osForCpu(cpu, osValue) {
741
+ const asked = typeof osValue === "string"
742
+ ? [osValue]
743
+ : osValue?.length
744
+ ? [...osValue]
745
+ : Object.keys(CPU_OS_NAMES);
746
+ checkValidOs(asked);
747
+ const errors = [];
748
+ const fits = [];
749
+ for (const name of asked) {
750
+ let resolved;
751
+ try {
752
+ resolved = coherence.resolveCpu(cpu, CPU_OS_NAMES[name]);
753
+ }
754
+ catch (e) {
755
+ if (!(e instanceof ValueError))
756
+ throw e;
757
+ errors.push(e.message);
758
+ continue;
759
+ }
760
+ if (osValue === null || osValue === undefined) {
761
+ const gpus = await utilsDeps.firefoxGpus(CPU_OS_NAMES[name]);
762
+ if (!gpus.some(([, r]) => coherence.gpuFitsCpu(r, CPU_OS_NAMES[name], resolved["cpu:arch"], resolved["cpu:manufacturer"]))) {
763
+ errors.push(`fpgen has recorded no ${name} GPU beside that CPU`);
764
+ continue;
765
+ }
766
+ }
767
+ fits.push(name);
768
+ }
769
+ if (!fits.length) {
770
+ throw new ValueError(`cpu=${pyRepr(cpu)}: ${[...new Set(errors)].join("; ")}`);
771
+ }
772
+ return fits.length === 1 ? fits[0] : fits;
773
+ }
774
+ /**
775
+ * Checks if the target OS is valid.
776
+ */
777
+ export function checkValidOs(osValue) {
778
+ if (typeof osValue !== "string") {
779
+ for (const osName of osValue)
780
+ checkValidOs(osName);
781
+ return;
782
+ }
783
+ // Assert that the OS is lowercase (str.islower(): has a cased char, none upper)
784
+ if (!(osValue !== osValue.toUpperCase() && osValue === osValue.toLowerCase())) {
785
+ throw new InvalidOS(`OS values must be lowercase: '${osValue}'`);
786
+ }
787
+ // Assert that the OS is supported by Camoufox
788
+ if (!["windows", "macos", "linux"].includes(osValue)) {
789
+ throw new InvalidOS(`Camoufox does not support the OS: '${osValue}'`);
790
+ }
791
+ }
792
+ /**
793
+ * Merges new keys/values from the source into the target, given that the key
794
+ * does not exist in the target.
795
+ */
796
+ export function mergeInto(target, source) {
797
+ for (const [key, value] of Object.entries(source)) {
798
+ if (!(key in target))
799
+ target[key] = value;
800
+ }
801
+ }
802
+ /**
803
+ * Sets a new key/value into the target, given that the key does not exist.
804
+ */
805
+ export function setInto(target, key, value) {
806
+ if (!(key in target))
807
+ target[key] = value;
808
+ }
809
+ /**
810
+ * Checks if a domain is set in the config.
811
+ */
812
+ export function isDomainSet(config, ...properties) {
813
+ for (const prop of properties) {
814
+ // If the . prefix exists, check if the domain is a prefix of any key
815
+ if (prop.endsWith(".") || prop.endsWith(":")) {
816
+ if (Object.keys(config).some((key) => key.startsWith(prop)))
817
+ return true;
818
+ }
819
+ else if (prop in config) {
820
+ // Otherwise, check if the domain is a direct key in the config
821
+ return true;
822
+ }
823
+ }
824
+ return false;
825
+ }
826
+ /** The host of a SOCKS5 proxy, or null when `proxy` is not one. */
827
+ /** Whether a Playwright proxy server is an HTTP(S) proxy (a bare host:port is one), which carries no UDP. */
828
+ export function proxyCarriesNoUdp(server) {
829
+ const scheme = server.includes("://")
830
+ ? server.split("://", 1)[0].toLowerCase()
831
+ : "http";
832
+ return scheme === "http" || scheme === "https";
833
+ }
834
+ export function socks5Host(proxy) {
835
+ if (!proxy) {
836
+ return null;
837
+ }
838
+ let url;
839
+ try {
840
+ url = new URL(String(proxy.server ?? ""));
841
+ }
842
+ catch {
843
+ return null;
844
+ }
845
+ // URL keeps the brackets of an IPv6 host; Python's urlsplit drops them.
846
+ return url.protocol === "socks5:"
847
+ ? url.hostname.replace(/^\[|\]$/g, "")
848
+ : null;
849
+ }
850
+ /**
851
+ * Who resolves the names a proxied browser visits (docs/proxy-dns.md).
852
+ *
853
+ * "exit", the default: the proxy is given names. "doh", behind a SOCKS5 proxy
854
+ * only: the browser, by DoH through the proxy, as a Firefox at the exit
855
+ * resolves its own; it gets HTTPS records, so it sends ECH where that Firefox
856
+ * does, and the proxy is given addresses. Starting HTTP/3 on them also needs
857
+ * the browser half that carries HTTP/3 over SOCKS5, which no released
858
+ * Camoufox has yet. An HTTP proxy is always given names.
859
+ */
860
+ export async function applyProxyDns(proxyDns, proxy, config, firefoxUserPrefs, exitLookedUp) {
861
+ if (proxyDns != null && proxyDns !== "doh" && proxyDns !== "exit") {
862
+ throw new ValueError(`proxy_dns must be 'doh' or 'exit', not ${JSON.stringify(proxyDns)}.`);
863
+ }
864
+ const host = socks5Host(proxy);
865
+ if (host === null) {
866
+ if (proxyDns === "doh") {
867
+ throw new ValueError("proxy_dns='doh' needs a socks5:// proxy.");
868
+ }
869
+ return;
870
+ }
871
+ if (proxyDns !== "doh") {
872
+ return;
873
+ }
874
+ mergeInto(firefoxUserPrefs, PROXY_DOH_PREFS);
875
+ // The proxy's own name cannot be asked through the proxy.
876
+ if (!(validIPv4(host) || validIPv6(host))) {
877
+ setInto(firefoxUserPrefs, "network.trr.excluded-domains", host);
878
+ }
879
+ // The browser picks the address now, so it has to know whether the exit
880
+ // can reach an IPv6 one. Asked only of an exit the launch looks up (geoip).
881
+ if (exitLookedUp &&
882
+ !("network:ipv4Only" in config) &&
883
+ !("webrtc:ipv6" in config) &&
884
+ (await utilsDeps.publicIpv6(ProxyHelper.asString(proxy))) ===
885
+ null) {
886
+ config["network:ipv4Only"] = true;
887
+ }
888
+ }
889
+ /**
890
+ * Whether this host has a public IPv6 address that geolocates where the IPv4
891
+ * identity does. Warns when it has one that does not.
892
+ */
893
+ async function keepsIPv6(geoConfig, geoipDb, iKnowWhatImDoing) {
894
+ const ipv6 = await utilsDeps.publicIpv6();
895
+ if (ipv6 === null) {
896
+ return false;
897
+ }
898
+ let ipv6Config = {};
899
+ try {
900
+ ipv6Config = (await utilsDeps.getGeolocation(ipv6, geoipDb)).asConfig();
901
+ }
902
+ catch (error) {
903
+ if (!(error instanceof UnknownIPLocation)) {
904
+ throw error;
905
+ }
906
+ }
907
+ if (["timezone", "locale:region"].every((key) => ipv6Config[key] === geoConfig[key])) {
908
+ return true;
909
+ }
910
+ LeakWarning.warn(loadWarnings().ipv6_elsewhere, iKnowWhatImDoing);
911
+ return false;
912
+ }
913
+ /**
914
+ * Warns for each coherence violation the launch left in place because the
915
+ * caller set the values involved. Camoufox does not overwrite what the caller
916
+ * passed, but an identity no real machine presents is detectable, and a caller
917
+ * that records its identities needs to know that it holds one (#956).
918
+ */
919
+ function warnKeptIncoherent(violations) {
920
+ for (const violation of violations) {
921
+ if (!violation.kept?.length)
922
+ continue;
923
+ const keys = violation.kept.join(", ");
924
+ warn(loadWarnings()
925
+ .caller_value_incoherent.replaceAll("{keys}", keys)
926
+ .replace("{detail}", () => violation.detail), "LeakWarning");
927
+ }
928
+ }
929
+ /**
930
+ * Warns the user if they are manually setting properties that Camoufox already
931
+ * sets internally.
932
+ */
933
+ function warnManualConfig(config) {
934
+ // Manual locale setting
935
+ if (isDomainSet(config, "navigator.language", "headers.Accept-Language", "locale:")) {
936
+ LeakWarning.warn(loadWarnings().locale, false);
937
+ }
938
+ // Manual geolocation and timezone setting
939
+ if (isDomainSet(config, "geolocation:", "timezone")) {
940
+ LeakWarning.warn(loadWarnings().geolocation, false);
941
+ }
942
+ // Manual User-Agent setting
943
+ if (isDomainSet(config, "headers.User-Agent")) {
944
+ LeakWarning.warn(loadWarnings()["header-ua"], false);
945
+ }
946
+ // Manual navigator setting
947
+ if (isDomainSet(config, "navigator.")) {
948
+ LeakWarning.warn(loadWarnings().navigator, false);
949
+ }
950
+ // Touchscreen digitizer spoofing. Called out separately from the blanket
951
+ // navigator warning because the knock-on effects reach past navigator into
952
+ // CSS pointer media queries and the TouchEvent interfaces.
953
+ if (isDomainSet(config, "navigator.maxTouchPoints")) {
954
+ LeakWarning.warn(loadWarnings().max_touch_points, false);
955
+ }
956
+ if (pyTruthy(config.instantAnimations)) {
957
+ LeakWarning.warn(loadWarnings().instant_animations, false);
958
+ }
959
+ // Manual screen/window setting
960
+ if (isDomainSet(config, "screen.", "window.", "document.body.")) {
961
+ LeakWarning.warn(loadWarnings().viewport, false);
962
+ }
963
+ }
964
+ const WINDOW_DIM_KEYS = [
965
+ "window.outerWidth",
966
+ "window.outerHeight",
967
+ "window.innerWidth",
968
+ "window.innerHeight",
969
+ ];
970
+ /** The CAMOU_CONFIG chunks of a set of launch options, reassembled in order. */
971
+ export function camouConfigBlob(fromOptions) {
972
+ const env = fromOptions.env ?? {};
973
+ return Object.entries(env)
974
+ .filter(([k]) => k.startsWith("CAMOU_CONFIG_"))
975
+ .map(([k, v]) => [
976
+ Number.parseInt(k.slice(k.lastIndexOf("_") + 1), 10),
977
+ String(v),
978
+ ])
979
+ .sort((a, b) => a[0] - b[0])
980
+ .map(([, v]) => v)
981
+ .join("");
982
+ }
983
+ /** The OS of the identity these launch options claim, the host's when they
984
+ * claim no user agent. */
985
+ export function launchOs(fromOptions) {
986
+ const blob = camouConfigBlob(fromOptions);
987
+ return OS_NAMES[getTargetOs(blob ? JSON.parse(blob) : {})];
988
+ }
989
+ /**
990
+ * The core count the browser must be pinned to for these launch options, or
991
+ * null: the identity's navigator.hardwareConcurrency when this host can honour
992
+ * it (see cpu_affinity), so a page measuring parallelism sees the reported
993
+ * number.
994
+ */
995
+ export function pinnedCoreCount(fromOptions) {
996
+ const blob = camouConfigBlob(fromOptions);
997
+ if (!blob || !cpuAffinity.supported())
998
+ return null;
999
+ let value;
1000
+ try {
1001
+ const parsed = JSON.parse(blob);
1002
+ value =
1003
+ parsed && typeof parsed === "object" && !Array.isArray(parsed)
1004
+ ? parsed["navigator.hardwareConcurrency"]
1005
+ : undefined;
1006
+ }
1007
+ catch {
1008
+ return null;
1009
+ }
1010
+ // The host's count, not this process's live mask: a concurrent pinned
1011
+ // launch narrows that while its browser spawns.
1012
+ const cores = cpuAffinity.hostCoreCount();
1013
+ if (typeof value === "number" &&
1014
+ Number.isInteger(value) &&
1015
+ value >= 1 &&
1016
+ value < cores) {
1017
+ return value;
1018
+ }
1019
+ return null;
1020
+ }
1021
+ /**
1022
+ * PID of the process that will spawn the browser (its children inherit the
1023
+ * CPU affinity set on it). Python's driver is a separate Node process;
1024
+ * playwright-core runs in this one.
1025
+ */
1026
+ export function driverPid() {
1027
+ return process.pid;
1028
+ }
1029
+ /**
1030
+ * Whether the CAMOU_CONFIG in a set of launch options spoofs any window
1031
+ * dimension. The config is chunked across CAMOU_CONFIG_<n> env vars, so
1032
+ * reassemble it in index order before looking.
1033
+ */
1034
+ export function spoofsWindowDimensions(fromOptions) {
1035
+ const blob = camouConfigBlob(fromOptions);
1036
+ if (!blob)
1037
+ return false;
1038
+ return WINDOW_DIM_KEYS.some((key) => blob.includes(key));
1039
+ }
1040
+ /**
1041
+ * Playwright emulates four media features on every context it creates, whether
1042
+ * or not the caller asked: `colorScheme` defaults to "light" and reducedMotion /
1043
+ * forcedColors / contrast to their no-preference values. That is an override,
1044
+ * not a passthrough -- the page then reports it whatever the host is set to. The
1045
+ * JS API's `null` (Python's "no-override") is Playwright's own opt-out: it sends
1046
+ * no emulation at all and the browser answers from the host.
1047
+ */
1048
+ export const STOCK_MEDIA_DEFAULTS = {
1049
+ colorScheme: null,
1050
+ reducedMotion: null,
1051
+ forcedColors: null,
1052
+ contrast: null,
1053
+ };
1054
+ /** Fill STOCK_MEDIA_DEFAULTS into any media option the caller left unset. */
1055
+ function withStockMediaDefaults(opts) {
1056
+ const out = { ...opts };
1057
+ for (const [option, value] of Object.entries(STOCK_MEDIA_DEFAULTS)) {
1058
+ if (out[option] === undefined)
1059
+ out[option] = value;
1060
+ }
1061
+ return out;
1062
+ }
1063
+ /**
1064
+ * Default newPage()/newContext() to the host's own media features.
1065
+ *
1066
+ * Explicit colorScheme / reducedMotion / forcedColors / contrast from the caller
1067
+ * always wins; this only replaces Playwright's silent defaults.
1068
+ */
1069
+ export function attachStockMediaDefaults(target) {
1070
+ for (const name of ["newPage", "newContext"]) {
1071
+ const original = target[name];
1072
+ if (typeof original !== "function")
1073
+ continue;
1074
+ target[name] = (options, ...rest) => original.call(target, withStockMediaDefaults(options ?? {}), ...rest);
1075
+ }
1076
+ return target;
1077
+ }
1078
+ const CAMOUFOX_SOCKS5_AUTH = Symbol.for("camoufox.socks5Auth");
1079
+ /**
1080
+ * Let newContext()/newPage() of `target` take a SOCKS5 proxy with a username
1081
+ * and password (python/camoucore/src/camoucore/camoufox/utils.py attach_socks5_auth).
1082
+ *
1083
+ * Playwright refuses one ("Browser does not support socks5 proxy
1084
+ * authentication"). The context is made with the proxy alone, and an init
1085
+ * script hands Juggler the credentials before newContext() resolves
1086
+ * (socks5Auth, proxyAuthInitScript). Playwright's newPage() makes its context
1087
+ * through newContext(), so it is covered too.
1088
+ */
1089
+ export function attachSocks5Auth(target) {
1090
+ const owner = target;
1091
+ const original = owner?.newContext;
1092
+ if (typeof original !== "function" || original[CAMOUFOX_SOCKS5_AUTH])
1093
+ return target;
1094
+ const newContext = async (options, ...rest) => {
1095
+ const [proxy, auth] = socks5Auth(options?.proxy);
1096
+ const context = await original.call(target, options && auth ? { ...options, proxy } : options, ...rest);
1097
+ if (auth)
1098
+ await context.addInitScript(proxyAuthInitScript(auth));
1099
+ return context;
1100
+ };
1101
+ newContext[CAMOUFOX_SOCKS5_AUTH] = true;
1102
+ owner.newContext = newContext;
1103
+ return target;
1104
+ }
1105
+ /**
1106
+ * Warn when newPage()/newContext() asks for isMobile: Camoufox only has desktop
1107
+ * identities, and Juggler ignores the option (TargetRegistry.js).
1108
+ */
1109
+ export function attachDesktopOnlyWarning(target) {
1110
+ for (const name of ["newPage", "newContext"]) {
1111
+ const original = target[name];
1112
+ if (typeof original !== "function")
1113
+ continue;
1114
+ target[name] = (options, ...rest) => {
1115
+ if (options?.isMobile || options?.is_mobile)
1116
+ LeakWarning.warn(loadWarnings().is_mobile);
1117
+ return original.call(target, options, ...rest);
1118
+ };
1119
+ }
1120
+ return target;
1121
+ }
1122
+ /**
1123
+ * Warn when a browser launched without a proxy gets a context proxy: the
1124
+ * browser's own traffic (the push connection every context shares) then takes
1125
+ * the first proxied context's proxy for the browser's life
1126
+ * (TargetRegistry.getProxyInfo).
1127
+ */
1128
+ export function attachSharedTrafficWarning(target) {
1129
+ for (const name of ["newPage", "newContext"]) {
1130
+ const original = target[name];
1131
+ if (typeof original !== "function")
1132
+ continue;
1133
+ target[name] = (options, ...rest) => {
1134
+ if (options?.proxy)
1135
+ LeakWarning.warn(loadWarnings().context_proxy_without_launch_proxy);
1136
+ return original.call(target, options, ...rest);
1137
+ };
1138
+ }
1139
+ return target;
1140
+ }
1141
+ /**
1142
+ * Whether the canvas is covered, and the host GPU the identity claims.
1143
+ *
1144
+ * The canvas renders on the host, so the identity claims the host's GPU when it
1145
+ * can: on the host's OS, with no GPU named, a GPU or software renderer fpgen has
1146
+ * recorded there. With WebGL off no GPU is claimed. Any other identity
1147
+ * contradicts the pixels, so the canvas is covered unless the caller chose
1148
+ * canvas_noise: false.
1149
+ */
1150
+ export async function planRendering(targetOs, canvasNoise, namedGpu, webglDisabled, probe) {
1151
+ if (canvasNoise)
1152
+ return [true, null];
1153
+ if (targetOs && targetOs === utilsDeps.hostOsKey() && !namedGpu) {
1154
+ const host = webglDisabled ? null : await probe();
1155
+ if (host === null)
1156
+ return [false, null];
1157
+ const recorded = await utilsDeps.firefoxGpus(targetOs);
1158
+ if (recorded.some(([vendor, renderer]) => vendor === host[0] && renderer === host[1])) {
1159
+ return [false, host];
1160
+ }
1161
+ }
1162
+ return [canvasNoise == null, null];
1163
+ }
1164
+ /**
1165
+ * For a launch without the canvas placeholder, the machine its contexts must
1166
+ * claim: the host's OS, and the host GPU it claims (planRendering). Only for
1167
+ * the default `canvasNoise` (undefined); a caller who chose it, or built the
1168
+ * options, keeps their contexts as they ask. Read before the launch, so a
1169
+ * failed probe leaves no browser behind.
1170
+ */
1171
+ export async function hostIdentity(fromOptions, canvasNoise) {
1172
+ const prefs = fromOptions.firefoxUserPrefs ?? {};
1173
+ if (canvasNoise != null || hasCanvasPlaceholder(prefs))
1174
+ return null;
1175
+ // Without the placeholder, the launch claimed the host's OS and no named GPU.
1176
+ const hostOs = utilsDeps.hostOsKey();
1177
+ const [covered, gpu] = await planRendering(hostOs, undefined, false, Boolean(prefs["webgl.disabled"]), () => utilsDeps.hostGpu(fromOptions.executablePath, fromOptions.headless, fromOptions.env, prefs));
1178
+ return covered ? null : [hostOs, gpu];
1179
+ }
1180
+ /**
1181
+ * The OS and GPU a new context on `browser` claims (null: drawn).
1182
+ *
1183
+ * On a browser without the canvas placeholder they are the host's, since the
1184
+ * canvas renders there; asking for anything else throws.
1185
+ */
1186
+ export function contextIdentity(browser, os, preset) {
1187
+ const hostIdentity = browser._camoufoxHostIdentity;
1188
+ if (!hostIdentity)
1189
+ return [os, null];
1190
+ const [hostOs, gpu] = hostIdentity;
1191
+ const hostName = OS_NAMES[hostOs];
1192
+ const hasPreset = pyTruthy(preset);
1193
+ const presetGpu = preset?.webgl ?? {};
1194
+ if ((os || hostName) !== hostName ||
1195
+ (hasPreset &&
1196
+ targetOsFromPlatform(preset?.navigator?.platform ?? "") !== hostName) ||
1197
+ (gpu &&
1198
+ hasPreset &&
1199
+ (presetGpu.unmaskedVendor !== gpu[0] ||
1200
+ presetGpu.unmaskedRenderer !== gpu[1]))) {
1201
+ throw new ValueError(`This browser renders its canvas as this ${hostName} machine, so its contexts claim it` +
1202
+ `${gpu ? ` and its GPU ${JSON.stringify(gpu)}` : ""}. Launch it with canvas_noise: true ` +
1203
+ "to give a context another OS or GPU.");
1204
+ }
1205
+ return [hostName, gpu];
1206
+ }
1207
+ /**
1208
+ * Normalise a context-options object onto the JS API's `viewport: null`,
1209
+ * defaulting to it when the caller expressed no preference. Playwright-Python
1210
+ * takes `no_viewport=True`; a caller-supplied `noViewport` is accepted and
1211
+ * translated.
1212
+ */
1213
+ export function applyNoViewport(opts) {
1214
+ const out = { ...opts };
1215
+ if ("noViewport" in out) {
1216
+ const noViewport = out.noViewport;
1217
+ delete out.noViewport;
1218
+ if (noViewport && !("viewport" in out))
1219
+ out.viewport = null;
1220
+ return out;
1221
+ }
1222
+ if (!("viewport" in out))
1223
+ out.viewport = null;
1224
+ return out;
1225
+ }
1226
+ /**
1227
+ * Default newPage()/newContext() to no viewport.
1228
+ *
1229
+ * Playwright applies a 1280x720 viewport by default, which makes Juggler ask
1230
+ * the content window to become 1280x720 (TargetRegistry.updateViewportSize).
1231
+ * When Camoufox is pinning the window to a spoofed size, that request can
1232
+ * never be satisfied, and awaitViewportDimensions has no timeout -- so the
1233
+ * second newPage() hangs forever (daijro/camoufox#666). An explicit viewport
1234
+ * from the caller always wins.
1235
+ */
1236
+ export function attachNoViewportDefault(target) {
1237
+ for (const name of ["newPage", "newContext"]) {
1238
+ const original = target[name];
1239
+ if (typeof original !== "function")
1240
+ continue;
1241
+ target[name] = (options, ...rest) => original.call(target, applyNoViewport(options ?? {}), ...rest);
1242
+ }
1243
+ return target;
1244
+ }
1245
+ /**
1246
+ * Start the display headless="virtual" or "virtual-gpu" asks for.
1247
+ *
1248
+ * Takes the display's own options out of `options` and points the launch at
1249
+ * the display. Returns the display, or null, and the headless value to launch
1250
+ * with.
1251
+ */
1252
+ export async function startVirtualDisplay(headless, debug, options) {
1253
+ const { gpu, require_gpu } = options;
1254
+ delete options.gpu;
1255
+ delete options.require_gpu;
1256
+ let display;
1257
+ if (headless === "virtual-gpu") {
1258
+ display = new GpuDisplay(utilsDeps.selectGpu(gpu), debug ?? false, require_gpu !== false);
1259
+ options.firefox_user_prefs = {
1260
+ ...GPU_PREFS,
1261
+ ...options.firefox_user_prefs,
1262
+ };
1263
+ }
1264
+ else if (gpu !== undefined || require_gpu !== undefined) {
1265
+ throw new ValueError("gpu and require_gpu apply to headless='virtual-gpu' only");
1266
+ }
1267
+ else if (headless === "virtual") {
1268
+ display = new VirtualDisplay(PRODUCT, debug ?? false);
1269
+ }
1270
+ else {
1271
+ return [null, headless];
1272
+ }
1273
+ options.virtual_display = await display.get();
1274
+ return [display, false];
1275
+ }
1276
+ /**
1277
+ * Attaches the virtual display to the browser's cleanup, and on a GPU display
1278
+ * checks the browser renders on the GPU. (Python has an async and a sync
1279
+ * variant; playwright-core has one API.)
1280
+ */
1281
+ export async function attachVirtualDisplay(browser, virtualDisplay) {
1282
+ if (!virtualDisplay)
1283
+ return browser; // Skip if no virtual display is provided
1284
+ const target = browser;
1285
+ const originalClose = target.close.bind(target);
1286
+ target.close = async (...args) => {
1287
+ try {
1288
+ return await originalClose(...args);
1289
+ }
1290
+ finally {
1291
+ virtualDisplay.kill();
1292
+ }
1293
+ };
1294
+ // close() never runs on an unexpected disconnect/close, so wire teardown
1295
+ // directly too; kill() is idempotent.
1296
+ target.on?.(target.contexts ? "disconnected" : "close", () => virtualDisplay.kill());
1297
+ target._virtualDisplay = virtualDisplay;
1298
+ if (virtualDisplay instanceof GpuDisplay) {
1299
+ try {
1300
+ await proveGpu(target, virtualDisplay);
1301
+ }
1302
+ catch (error) {
1303
+ await target.close();
1304
+ throw error;
1305
+ }
1306
+ }
1307
+ return browser;
1308
+ }
1309
+ /**
1310
+ * The Firefox version of the build about to launch: the named executable's own
1311
+ * application.ini, or the installed release. A named executable without one
1312
+ * throws, since claiming another build's version would leak in the UA.
1313
+ */
1314
+ export function resolveVerstr(executablePath) {
1315
+ if (!executablePath)
1316
+ return utilsDeps.installedVerStr();
1317
+ const ini = buildFile(executablePath, "application.ini");
1318
+ for (const line of fs.readFileSync(ini, "utf-8").split(/\r\n|\r|\n/)) {
1319
+ if (line.startsWith("Version=")) {
1320
+ return line.slice("Version=".length).trim();
1321
+ }
1322
+ }
1323
+ throw new ValueError(`${ini} names no Version`);
1324
+ }
1325
+ function toScreen(screen) {
1326
+ if (screen instanceof Screen)
1327
+ return screen;
1328
+ const s = screen;
1329
+ return new Screen({
1330
+ minWidth: s.minWidth ?? s.min_width,
1331
+ maxWidth: s.maxWidth ?? s.max_width,
1332
+ minHeight: s.minHeight ?? s.min_height,
1333
+ maxHeight: s.maxHeight ?? s.max_height,
1334
+ });
1335
+ }
1336
+ /**
1337
+ * Builds the Playwright Firefox launch options for Camoufox.
1338
+ *
1339
+ * Accepts all Playwright Firefox launch options, along with the Camoufox ones
1340
+ * documented on {@link LaunchOptions}.
1341
+ */
1342
+ export async function launchOptions(options = {}) {
1343
+ return buildLaunchOptions(options);
1344
+ }
1345
+ async function buildLaunchOptions({ config, os: targetOsOption, block_images, block_webrtc, block_webgl, disable_coop, webgl_config, cpu, geoip, geoip_db, humanize, locale, addons, fonts, custom_fonts_only, exclude_addons, screen, window, fingerprint, fingerprint_preset, ff_version, headless, main_world_eval, allow_addon_new_tab, executable_path, browser, firefox_user_prefs, proxy, proxy_dns, enable_cache, args, env, i_know_what_im_doing, debug, virtual_display, pin_cpu_cores, canvas_noise, display_profile, ...passthrough }) {
1346
+ utilsDeps.ensureBrowserProfileDir(env);
1347
+ // The launch fills these in, so it works on copies: a caller's object
1348
+ // reused for a second launch would otherwise carry the first identity's
1349
+ // values in, as if the caller had set them.
1350
+ config = { ...config };
1351
+ addons = [...(addons ?? [])];
1352
+ args = [...(args ?? [])];
1353
+ firefox_user_prefs = { ...firefox_user_prefs };
1354
+ // Set default values for optional arguments
1355
+ headless ??= false;
1356
+ // The caller's own prefs, before the launcher adds any: a display profile
1357
+ // never replaces one of these.
1358
+ const userPrefKeys = new Set(Object.keys(firefox_user_prefs));
1359
+ custom_fonts_only ??= false;
1360
+ i_know_what_im_doing ??= false;
1361
+ // Keep per-launch overrides isolated from the process environment and from
1362
+ // mappings supplied by callers. In particular, DISPLAY must not outlive the
1363
+ // virtual display that owns it.
1364
+ env = env == null ? { ...process.env } : { ...env };
1365
+ // CAMOUFOX_EXECUTABLE_PATH points every launch at a specific build without
1366
+ // threading the path through each call site; the CI runners set it.
1367
+ const envExecutable = (process.env.CAMOUFOX_EXECUTABLE_PATH ?? "").trim();
1368
+ if (browser) {
1369
+ if (executable_path || envExecutable) {
1370
+ throw new ValueError(`browser '${browser}' selects an installed build, but ` +
1371
+ `${executable_path ? "executable_path" : "CAMOUFOX_EXECUTABLE_PATH"} ` +
1372
+ "names a binary too. Pass one of them.");
1373
+ }
1374
+ // A selected build is launched like a caller's own binary: its files
1375
+ // are read from beside it, and the paired build is neither used nor fetched.
1376
+ executable_path = utilsDeps.selectedLaunchPath(browser);
1377
+ }
1378
+ else if (executable_path == null && envExecutable) {
1379
+ executable_path = envExecutable;
1380
+ }
1381
+ if (typeof executable_path === "string") {
1382
+ executable_path = path.resolve(executable_path);
1383
+ }
1384
+ // The managed install is resolved lazily in Python (camoufox_path() may
1385
+ // download); here that download is async, so do it before any sync lookup.
1386
+ if (!executable_path) {
1387
+ await utilsDeps.ensureCamoufoxInstalled();
1388
+ }
1389
+ // The binary that will launch, whose files the launch reads.
1390
+ const resolvedExecutable = executable_path
1391
+ ? String(executable_path)
1392
+ : utilsDeps.launchPath();
1393
+ // Handle virtual display
1394
+ if (virtual_display) {
1395
+ env.DISPLAY = virtual_display;
1396
+ // Virtual display uses Xvfb (X11). If the host session forces Wayland via
1397
+ // env vars, GTK/Firefox may try Wayland and ignore DISPLAY.
1398
+ env.GDK_BACKEND = "x11";
1399
+ delete env.WAYLAND_DISPLAY;
1400
+ env.MOZ_ENABLE_WAYLAND = "0";
1401
+ }
1402
+ // Warn the user for manual config settings
1403
+ if (!i_know_what_im_doing) {
1404
+ warnManualConfig(config);
1405
+ }
1406
+ if (cpu !== undefined && cpu !== null) {
1407
+ targetOsOption = await osForCpu(cpu, targetOsOption);
1408
+ }
1409
+ const callerKeys = new Set(Object.keys(config));
1410
+ // Snapshot which domains the USER set before fingerprint generation fills in
1411
+ // the rest. The post-generation corrections below must only touch generated
1412
+ // values, never override what the user passed.
1413
+ const userSetNavigator = isDomainSet(config, "navigator.");
1414
+ const userSetArch = isDomainSet(config, "navigator.platform", "navigator.oscpu");
1415
+ const userSetScreenWindow = isDomainSet(config, "screen.", "window.");
1416
+ const userWindowPosition = new Set(["window.screenX", "window.screenY"].filter((k) => k in config));
1417
+ const userSetMediaDevices = isDomainSet(config, "mediaDevices:");
1418
+ const userSetFonts = Boolean(fonts?.length) || isDomainSet(config, "fonts");
1419
+ const userSetVoices = isDomainSet(config, "voices", "voices:speechd");
1420
+ const userSetDnt = "navigator.doNotTrack" in config;
1421
+ const userSetGpc = "navigator.globalPrivacyControl" in config;
1422
+ const userSetAcceptEncoding = "headers.Accept-Encoding" in config;
1423
+ dropAudioSeed(config);
1424
+ // The salt that makes every seeded draw belong to this identity (see
1425
+ // fingerprints.identitySalt): stable when the caller pinned the identity --
1426
+ // a fingerprint, a preset object, or their own config naming the UA -- and
1427
+ // fresh otherwise.
1428
+ let salt;
1429
+ if (fingerprint != null) {
1430
+ salt = utilsDeps.identitySalt(fingerprint);
1431
+ }
1432
+ else if (isPlainObject(fingerprint_preset)) {
1433
+ salt = utilsDeps.identitySalt(fingerprint_preset);
1434
+ }
1435
+ else if ("navigator.userAgent" in config) {
1436
+ salt = utilsDeps.identitySalt({ ...config });
1437
+ }
1438
+ else {
1439
+ salt = utilsDeps.identitySalt();
1440
+ }
1441
+ // Assert the target OS is valid
1442
+ if (pyTruthy(targetOsOption)) {
1443
+ checkValidOs(targetOsOption);
1444
+ }
1445
+ else if (pyTruthy(webgl_config)) {
1446
+ // webgl_config requires OS to be set
1447
+ throw new ValueError("OS must be set when using webgl_config");
1448
+ }
1449
+ // The managed install is resolved lazily in Python (camoufox_path() may
1450
+ // download); here that download is async, so do it before any sync lookup.
1451
+ if (!executable_path) {
1452
+ await utilsDeps.ensureCamoufoxInstalled();
1453
+ }
1454
+ warnIfPackageOutdated();
1455
+ // The default addons are the ones that build bundles, beside its binary
1456
+ await utilsDeps.addDefaultAddons(addons, exclude_addons, executable_path ? String(executable_path) : utilsDeps.launchPath());
1457
+ // Confirm all addon paths are valid
1458
+ if (addons.length) {
1459
+ utilsDeps.confirmPaths(addons);
1460
+ config.addons = addons;
1461
+ }
1462
+ // Get the Firefox version
1463
+ let ffVersionStr;
1464
+ if (ff_version) {
1465
+ ffVersionStr = String(ff_version);
1466
+ LeakWarning.warn(loadWarnings().ff_version, i_know_what_im_doing);
1467
+ }
1468
+ else {
1469
+ ffVersionStr = resolveVerstr(executable_path).split(".")[0];
1470
+ }
1471
+ // Generate a fingerprint
1472
+ let usedPreset = false;
1473
+ if (fingerprint != null) {
1474
+ // User passed a custom fingerprint
1475
+ if (!i_know_what_im_doing) {
1476
+ checkCustomFingerprint(fingerprint);
1477
+ }
1478
+ }
1479
+ else if (pyTruthy(fingerprint_preset)) {
1480
+ // User opted into real fingerprint presets
1481
+ const preset = isPlainObject(fingerprint_preset)
1482
+ ? fingerprint_preset
1483
+ : await utilsDeps.getRandomPreset(targetOsOption, ffVersionStr);
1484
+ if (pyTruthy(preset)) {
1485
+ mergeInto(config, await utilsDeps.fromPreset(preset, ffVersionStr, salt));
1486
+ usedPreset = true;
1487
+ }
1488
+ }
1489
+ // Bound the geometry to the real display. The generator only honours this
1490
+ // when its pool has a match, so it is re-applied after generation as well.
1491
+ // `headless` and "is there a display to probe" are separate questions.
1492
+ const screenCons = screen
1493
+ ? toScreen(screen)
1494
+ : utilsDeps.hasDisplay(env)
1495
+ ? utilsDeps.getScreenCons(headless)
1496
+ : null;
1497
+ if (!usedPreset && fingerprint == null) {
1498
+ // Default: synthetic generation via fpgen (infinite unique fingerprints)
1499
+ fingerprint = await utilsDeps.generateFingerprint({
1500
+ screen: screenCons ?? undefined,
1501
+ window,
1502
+ os: targetOsOption,
1503
+ });
1504
+ }
1505
+ if (!usedPreset && fingerprint != null) {
1506
+ // Inject the generated fingerprint into the config
1507
+ mergeInto(config, utilsDeps.fromFpgen(fingerprint, ffVersionStr));
1508
+ }
1509
+ const targetOs = getTargetOs(config);
1510
+ if (cpu !== undefined && cpu !== null) {
1511
+ Object.assign(config, coherence.resolveCpu(cpu, targetOs));
1512
+ }
1513
+ // fpgen.yml leaves devicePixelRatio unmapped, so the page reports the
1514
+ // rendering scale while the screen keeps fpgen's CSS sizes. A drawn ratio no
1515
+ // display offers is a browser zoom that shrank those sizes (1760x990 at
1516
+ // 1.0909 is a 1920x1080 monitor at 110%): it moves to the display's scale
1517
+ // with the geometry rescaled, so the screen is the display it was recorded
1518
+ // on. Here, before the display clamp and the available area are derived
1519
+ // from it.
1520
+ if (!usedPreset &&
1521
+ fingerprint != null &&
1522
+ typeof fingerprint === "object" &&
1523
+ !userSetScreenWindow) {
1524
+ const drawnDpr = fingerprint.window
1525
+ ?.devicePixelRatio;
1526
+ if (!("window.devicePixelRatio" in config) &&
1527
+ coherence.isZoomedRatio(drawnDpr, targetOs)) {
1528
+ // A caller's layout.css.devPixelsPerPx is the scale the page renders
1529
+ // at, so the ratio moves to that: otherwise the page reports one
1530
+ // devicePixelRatio and matches another in matchMedia('(resolution)').
1531
+ const callerScale = Number(firefox_user_prefs["layout.css.devPixelsPerPx"] ?? -1);
1532
+ config["window.devicePixelRatio"] = drawnDpr;
1533
+ coherence.repairDevicePixelRatio(config, targetOs, callerScale > 0 ? callerScale : undefined);
1534
+ }
1535
+ }
1536
+ // A preset whose screen is a phone viewport is not a real desktop device.
1537
+ if (!userSetScreenWindow && coherence.screenIsImplausible(config)) {
1538
+ coherence.repairScreenOrientation(config);
1539
+ utilsDeps.raiseScreenToModernFloor(config);
1540
+ }
1541
+ // Correct fingerprint inconsistencies that leak as headless /
1542
+ // impossible-geometry tells, unless the user is driving these themselves.
1543
+ if (!userSetArch)
1544
+ utilsDeps.fixNavigatorArch(config, targetOs);
1545
+ if (!userSetNavigator)
1546
+ utilsDeps.fixHardwareConcurrency(config, Boolean(pin_cpu_cores), {}, targetOs);
1547
+ if (!userSetScreenWindow) {
1548
+ // Lift netbook-era geometry to something current hardware reports,
1549
+ // before the display clamp below so a genuinely small real monitor still
1550
+ // wins (#729). Synthetic draws only: a preset is a real device.
1551
+ if (!usedPreset) {
1552
+ utilsDeps.raiseScreenToModernFloor(config);
1553
+ }
1554
+ // Headful on a real monitor only: this bound exists so the window fits
1555
+ // the screen it is drawn on. headless has no window to overflow, and
1556
+ // headless="virtual" reaches here as headless=false with a 1x1 Xvfb.
1557
+ if (headless === false && !virtual_display && screenCons) {
1558
+ const fit = physicalScale(config);
1559
+ utilsDeps.clampScreenToDisplay(config, (screenCons.maxWidth &&
1560
+ Math.trunc(screenCons.maxWidth / fit)), (screenCons.maxHeight &&
1561
+ Math.trunc(screenCons.maxHeight / fit)));
1562
+ }
1563
+ }
1564
+ // Every launch, a caller's screen and window included: the config claims the
1565
+ // avail rect the browser reports (baseline protection takes the taskbar out
1566
+ // of the screen whatever availHeight says), and the window is fitted inside
1567
+ // it, since the browser grows the screen to hold a window that does not fit
1568
+ // (2560x1408 against a caller's 1920x1080 read back as 7680x2160). Only a
1569
+ // position the caller did not set is moved: one drawn against the generated
1570
+ // screen is moved onto the caller's, or every new context drew another screen.
1571
+ utilsDeps.followBaselineProtection(config, targetOs);
1572
+ utilsDeps.clampWindowDimensions(config);
1573
+ utilsDeps.clampWindowPosition(config, new Set(["window.screenX", "window.screenY"].filter((k) => !userWindowPosition.has(k))));
1574
+ // Deliberately NOT setting window.history.length: browser/settings/camoufox.cfg runs
1575
+ // Firefox's stock max_entries, so the real value starts at 1 and grows with
1576
+ // each navigation; pinning it would contradict history.back().
1577
+ // Update fonts list
1578
+ if (fonts?.length) {
1579
+ config.fonts = fonts;
1580
+ }
1581
+ if (custom_fonts_only) {
1582
+ firefox_user_prefs["gfx.bundled-fonts.activate"] = 0;
1583
+ if (fonts?.length) {
1584
+ LeakWarning.warn(loadWarnings().custom_fonts_only, i_know_what_im_doing);
1585
+ }
1586
+ else {
1587
+ throw new ValueError("No custom fonts were passed, but `custom_fonts_only` is enabled.");
1588
+ }
1589
+ }
1590
+ else if (!userSetFonts || !pyTruthy(config.fonts)) {
1591
+ // Draw the font subset HERE, after every identity fix-up above, so the
1592
+ // seed sees the final UA/screen/cores/GPU: the same presented identity
1593
+ // always gets the same font list (#442/#765).
1594
+ const osName = OS_NAMES[targetOs] ?? "macos";
1595
+ try {
1596
+ config.fonts = utilsDeps.generateRandomFontSubset(osName, utilsDeps.identitySeed(config, salt),
1597
+ // host's own OS on macOS/Windows: the real system fonts are used
1598
+ // (font-hijacker.patch keeps the bundle inactive), so only the OS
1599
+ // base is claimed
1600
+ (targetOs === "mac" || targetOs === "win") &&
1601
+ utilsDeps.hostOsKey() === targetOs);
1602
+ }
1603
+ catch (e) {
1604
+ if (!isPyError(e, "OSError", "ValueError"))
1605
+ throw e;
1606
+ FallbackWarning.warn("Drawing the font list", `every font fonts.json lists for ${targetOs}`, e, config["navigator.userAgent"]);
1607
+ updateFonts(config, targetOs);
1608
+ }
1609
+ }
1610
+ // Draw the identity's media devices unless the caller set any mediaDevices:
1611
+ // key. An empty enumerateDevices() list is a headless tell; a wrong label
1612
+ // after a grant is a spoof tell.
1613
+ if (!userSetMediaDevices) {
1614
+ await utilsDeps.setMediaDevicesDefaults(config, salt);
1615
+ }
1616
+ // A caller's display ICC profile, which tagged images are converted to
1617
+ // (display_profile.ts).
1618
+ applyDisplayProfile(firefox_user_prefs, userPrefKeys, display_profile, utilsDeps.installDir());
1619
+ // Scrollbars: pin the look-and-feel to the claimed OS so headless == headed
1620
+ // == stock, and for Windows to the version the identity's font draw
1621
+ // presents (Win11 fonts with classic scrollbars is a pair no real machine
1622
+ // produces).
1623
+ if (targetOs === "win") {
1624
+ const presentedFonts = config.fonts || [];
1625
+ const windows11 = !presentedFonts.length ||
1626
+ presentedFonts.some((font) => WINDOWS_11_MARKER_FONTS.has(font));
1627
+ setInto(firefox_user_prefs, "ui.useOverlayScrollbars", windows11 ? 1 : 0);
1628
+ }
1629
+ else {
1630
+ setInto(firefox_user_prefs, "ui.useOverlayScrollbars", 1);
1631
+ }
1632
+ // Stock doubles a wheel's lines on Windows and Linux and never on macOS, and
1633
+ // a page reads the result in deltaY (docs/input-dispatch.md).
1634
+ setInto(firefox_user_prefs, "mousewheel.system_scroll_override.enabled", targetOs !== "mac");
1635
+ // A Windows identity on another host: answers that come from the host
1636
+ // build's platform code are set to what stock Windows Firefox gives.
1637
+ if (targetOs === "win" && utilsDeps.hostOsKey() !== "win") {
1638
+ // Math.sin/cos/tan/pow as the Windows CRT computes them, to the last bit
1639
+ // (windows-crt-math.patch).
1640
+ setInto(firefox_user_prefs, "javascript.options.use_ucrt_math", true);
1641
+ // Keyboard: Windows' shortcut tables instead of GTK's text bindings, and
1642
+ // AltGr as keyCode 18 rather than 225 (windows-keyboard.patch).
1643
+ setInto(config, "input:windowsKeyboard", true);
1644
+ for (const [pref, value] of Object.entries(WINDOWS_BEHAVIOUR_PREFS)) {
1645
+ setInto(firefox_user_prefs, pref, value);
1646
+ }
1647
+ // WebCodecs H.264 encoding: Windows always has Media Foundation's
1648
+ // encoder, Linux Firefox only the system FFmpeg's. Not faked; see
1649
+ // launch_options in the Python launcher.
1650
+ if (utilsDeps.hostOsKey() === "lin" && !hasSystemAvcodec()) {
1651
+ LeakWarning.warn(loadWarnings().no_h264_encoder, i_know_what_im_doing);
1652
+ }
1653
+ // The scrollbars pinned above are drawn by the host build's theme (GTK's
1654
+ // 12 px where Windows 10 draws 17): draw Windows' own, 4 Windows 10 or
1655
+ // 5 Windows 11 (17 px: only Windows' build reads a system metric).
1656
+ const overlay = firefox_user_prefs["ui.useOverlayScrollbars"];
1657
+ setInto(firefox_user_prefs, "widget.non-native-theme.scrollbar.style", overlay ? 5 : 4);
1658
+ }
1659
+ // Per-character font fallback, LINUX ONLY: with async fallback on, the
1660
+ // first measurement of a character only one bundled family provides returns
1661
+ // the primary family's .notdef. macOS must NOT get this.
1662
+ if (targetOs === "lin") {
1663
+ setInto(firefox_user_prefs, "gfx.font_rendering.fallback.async", false);
1664
+ }
1665
+ // Storage quota, from the host's own disk (see stockProfileDiskCapacityKb).
1666
+ const quotaLimitKb = utilsDeps.stockProfileDiskCapacityKb();
1667
+ if (quotaLimitKb) {
1668
+ setInto(firefox_user_prefs, QUOTA_FIXED_LIMIT_PREF, quotaLimitKb);
1669
+ }
1670
+ // navigator.doNotTrack and navigator.globalPrivacyControl are pref-backed in
1671
+ // Firefox; spoofing them anywhere else leaves the wire (or the worker)
1672
+ // contradicting the API (daijro/camoufox#760). A stock Firefox 152 reports
1673
+ // "unspecified" and false, so generated values are dropped unless the
1674
+ // caller set them explicitly. screen.colorDepth is left as drawn.
1675
+ if (!userSetDnt) {
1676
+ delete config["navigator.doNotTrack"];
1677
+ }
1678
+ if (!userSetGpc) {
1679
+ delete config["navigator.globalPrivacyControl"];
1680
+ }
1681
+ const dnt = config["navigator.doNotTrack"];
1682
+ firefox_user_prefs["privacy.donottrackheader.enabled"] =
1683
+ dnt != null && pyStr(dnt) === "1";
1684
+ const gpc = config["navigator.globalPrivacyControl"];
1685
+ firefox_user_prefs["privacy.globalprivacycontrol.enabled"] =
1686
+ gpc != null ? pyTruthy(gpc) : false;
1687
+ // Accept-Encoding: Firefox's own value is already what the identity claims,
1688
+ // so the generated header is dropped unless the caller set it.
1689
+ if (!userSetAcceptEncoding) {
1690
+ delete config["headers.Accept-Encoding"];
1691
+ }
1692
+ // A proxied identity is a machine at the exit: a real proxy resolves the
1693
+ // exit through itself whenever geoip is available (Python's launch_options).
1694
+ if (geoip == null &&
1695
+ allowGeoip() &&
1696
+ pyTruthy(proxy) &&
1697
+ !(proxy?.server ?? "").includes("localhost") &&
1698
+ !isDomainSet(config, "geolocation")) {
1699
+ geoip = true;
1700
+ }
1701
+ // Set geolocation
1702
+ if (pyTruthy(geoip)) {
1703
+ geoipAllowed(); // Assert that geoip is allowed
1704
+ let geoipIp;
1705
+ if (geoip === true) {
1706
+ // Find the user's IP address
1707
+ geoipIp = proxy
1708
+ ? await utilsDeps.publicIp(ProxyHelper.asString(proxy))
1709
+ : await utilsDeps.publicIp();
1710
+ }
1711
+ else {
1712
+ geoipIp = geoip;
1713
+ }
1714
+ // Spoof WebRTC if not blocked
1715
+ if (!block_webrtc) {
1716
+ if (validIPv4(geoipIp)) {
1717
+ setInto(config, "webrtc:ipv4", geoipIp);
1718
+ }
1719
+ else if (validIPv6(geoipIp)) {
1720
+ setInto(config, "webrtc:ipv6", geoipIp);
1721
+ }
1722
+ }
1723
+ const geolocation = await utilsDeps.getGeolocation(geoipIp, geoip_db);
1724
+ const geoConfig = geolocation.asConfig();
1725
+ for (const [key, value] of Object.entries(geoConfig)) {
1726
+ if ([
1727
+ "timezone",
1728
+ "locale:language",
1729
+ "locale:region",
1730
+ "locale:script",
1731
+ ].includes(key)) {
1732
+ setInto(config, key, value);
1733
+ }
1734
+ else {
1735
+ config[key] = value;
1736
+ }
1737
+ }
1738
+ // Without a proxy, a site that has an IPv6 address sees this host's,
1739
+ // not the IPv4 address the identity was drawn from. Keep IPv6 only when
1740
+ // it places the host where the identity does; otherwise the browser
1741
+ // behaves as on an IPv4-only network.
1742
+ if (!proxy &&
1743
+ validIPv4(geoipIp) &&
1744
+ !(await keepsIPv6(geoConfig, geoip_db, i_know_what_im_doing))) {
1745
+ config["network:ipv4Only"] = true;
1746
+ }
1747
+ }
1748
+ // A page that receives a position without a prompt must also see
1749
+ // permissions.query({name: 'geolocation'}) report "granted" (#769).
1750
+ if ("geolocation:latitude" in config && "geolocation:longitude" in config) {
1751
+ setInto(firefox_user_prefs, "permissions.default.geo", 1);
1752
+ }
1753
+ else if (
1754
+ // Raise a warning when a proxy is being used without spoofing
1755
+ // geolocation. This warning cannot be ignored with i_know_what_im_doing.
1756
+ pyTruthy(proxy) &&
1757
+ !(proxy?.server ?? "").includes("localhost") &&
1758
+ !isDomainSet(config, "geolocation")) {
1759
+ LeakWarning.warn(loadWarnings().proxy_without_geoip);
1760
+ }
1761
+ // An HTTP proxy carries no UDP: WebRTC and HTTP/3 then act as on a machine
1762
+ // whose firewall drops every datagram, which few people's does. A SOCKS5
1763
+ // proxy with UDP ASSOCIATE sends them from the exit.
1764
+ if (proxy && proxyCarriesNoUdp(String(proxy.server ?? ""))) {
1765
+ LeakWarning.warn(loadWarnings().proxy_http_no_udp, i_know_what_im_doing);
1766
+ }
1767
+ await applyProxyDns(proxy_dns, proxy, config, firefox_user_prefs, pyTruthy(geoip));
1768
+ // Set locale
1769
+ if (pyTruthy(locale)) {
1770
+ await handleLocales(locale, config);
1771
+ }
1772
+ // Select the browser's UI locale to match the Intl locale. Always set: an
1773
+ // EMPTY value would follow the host OS locale.
1774
+ let requested;
1775
+ if (pyTruthy(config["locale:language"])) {
1776
+ requested = [
1777
+ config["locale:language"],
1778
+ config["locale:script"],
1779
+ config["locale:region"],
1780
+ ]
1781
+ .filter((part) => pyTruthy(part))
1782
+ .join("-");
1783
+ }
1784
+ else {
1785
+ requested = "en-US";
1786
+ }
1787
+ setInto(firefox_user_prefs, "intl.locale.requested", requested);
1788
+ // Stock learns its home region from a network lookup this launch turns
1789
+ // off, and writes it here. Without it the search service offers the
1790
+ // region-less engine list and the DoH rollout never decides.
1791
+ if (pyTruthy(config["locale:region"])) {
1792
+ setInto(firefox_user_prefs, "browser.search.region", config["locale:region"]);
1793
+ }
1794
+ // Spoof the speech-synthesis voice list. This has to fail CLOSED: leaving
1795
+ // `voices` unset exposes every native voice on the box (#731). Drawn after
1796
+ // the locale is resolved: the Windows voice list is the display language's
1797
+ // pack.
1798
+ if (!userSetVoices ||
1799
+ (!("voices" in config) && !("voices:speechd" in config))) {
1800
+ const osNameV = OS_NAMES[targetOs] ?? "macos";
1801
+ let voiceLocale = config["navigator.language"];
1802
+ if (pyTruthy(config["locale:language"])) {
1803
+ voiceLocale = [config["locale:language"], config["locale:region"]]
1804
+ .filter((part) => pyTruthy(part))
1805
+ .join("-");
1806
+ }
1807
+ try {
1808
+ Object.assign(config, utilsDeps.drawVoiceConfig(osNameV, voiceLocale ?? null, utilsDeps.identitySeed(config, salt)));
1809
+ }
1810
+ catch (e) {
1811
+ if (!isPyError(e, "OSError", "ValueError", "KeyError"))
1812
+ throw e;
1813
+ // An empty list still blocks the host's voices (see below), so a
1814
+ // generation failure degrades to "no voices" rather than "all of
1815
+ // the host's".
1816
+ FallbackWarning.warn("Drawing the speech voices", "no speech voices", e, config["navigator.userAgent"]);
1817
+ config.voices = [];
1818
+ }
1819
+ }
1820
+ // Pin the block explicitly instead of relying on a non-empty list to imply
1821
+ // it. setInto leaves an explicit caller value alone.
1822
+ setInto(config, "voices:blockIfNotDefined", true);
1823
+ // humanize runs in the driver (_humanize_playwright.ts): checked here, and
1824
+ // nothing about it reaches the browser's config.
1825
+ normalize(humanize);
1826
+ // Enable the main world context creation
1827
+ if (main_world_eval) {
1828
+ setInto(config, "allowMainWorld", true);
1829
+ }
1830
+ // Allow addon open new tabs
1831
+ if (allow_addon_new_tab) {
1832
+ setInto(config, "allowAddonNewtab", true);
1833
+ }
1834
+ // Fresh profiles get a toggle's pref only when on. A persistent profile
1835
+ // may need the stock value written once to clear an earlier toggled value.
1836
+ if (block_images) {
1837
+ LeakWarning.warn(loadWarnings().block_images, i_know_what_im_doing);
1838
+ }
1839
+ if (disable_coop) {
1840
+ LeakWarning.warn(loadWarnings().disable_coop, i_know_what_im_doing);
1841
+ }
1842
+ const profileDir = (passthrough.user_data_dir ?? passthrough.userDataDir);
1843
+ for (const [on, pref, stock, toggled] of [
1844
+ [block_images, "permissions.default.image", 1, 2],
1845
+ [block_webrtc, "media.peerconnection.enabled", true, false],
1846
+ [
1847
+ disable_coop,
1848
+ "browser.tabs.remote.useCrossOriginOpenerPolicy",
1849
+ true,
1850
+ false,
1851
+ ],
1852
+ ]) {
1853
+ setTogglePref(firefox_user_prefs, pref, Boolean(on), stock, toggled, profileDir);
1854
+ }
1855
+ // A persistent context takes its context options here.
1856
+ if (passthrough.is_mobile || passthrough.isMobile) {
1857
+ LeakWarning.warn(loadWarnings().is_mobile, i_know_what_im_doing);
1858
+ }
1859
+ // Drop values the source supplied that this identity cannot keep, before the
1860
+ // WebGL pool below defers to them. Here, not earlier, because the check
1861
+ // reads the core count and the screen, which the launch replaces above.
1862
+ warnKeptIncoherent(coherence.dropIncoherentSourceValues(config, targetOs, callerKeys));
1863
+ const [coverCanvas, host] = await planRendering(targetOs, canvas_noise, pyTruthy(webgl_config) ||
1864
+ (pyTruthy(config["webGl:vendor"]) && pyTruthy(config["webGl:renderer"])), Boolean(block_webgl), () => utilsDeps.hostGpu(resolvedExecutable, headless, env, firefox_user_prefs));
1865
+ if (coverCanvas) {
1866
+ addCanvasPlaceholder(firefox_user_prefs);
1867
+ LeakWarning.warn(loadWarnings().canvas_noise, i_know_what_im_doing);
1868
+ }
1869
+ if (block_webgl) {
1870
+ firefox_user_prefs["webgl.disabled"] = true;
1871
+ LeakWarning.warn(loadWarnings().block_webgl, i_know_what_im_doing);
1872
+ }
1873
+ else {
1874
+ let webglFp;
1875
+ const seed = () => utilsDeps.identitySeed(config, salt);
1876
+ // A pair the caller named, or the preset's own GPU, keeps its name and
1877
+ // gets that device's recorded parameters. webglForGpu raises for a GPU
1878
+ // fpgen has never seen: the caller asked for something that does not exist.
1879
+ if (pyTruthy(webgl_config)) {
1880
+ const [vendor, renderer] = webgl_config;
1881
+ webglFp = await utilsDeps.webglForGpu(targetOs, vendor, renderer, seed());
1882
+ }
1883
+ else if (pyTruthy(config["webGl:vendor"]) &&
1884
+ pyTruthy(config["webGl:renderer"])) {
1885
+ webglFp = await utilsDeps.webglForGpu(targetOs, config["webGl:vendor"], config["webGl:renderer"], seed());
1886
+ }
1887
+ else if (host) {
1888
+ // Claim the GPU the canvas really renders on.
1889
+ webglFp = await utilsDeps.webglForGpu(targetOs, ...host, seed());
1890
+ }
1891
+ else {
1892
+ // Synthetic path: keep the GPU coherent with the screen fpgen already
1893
+ // picked. Sampling the two independently yields pairs no real machine
1894
+ // ships -- a discrete desktop GPU behind a 1024x600 panel (#729).
1895
+ webglFp = await utilsDeps.sampleWebglForScreen(targetOs, config["screen.width"], config["screen.height"], seed(), config["navigator.hardwareConcurrency"], config);
1896
+ }
1897
+ const enableWebgl2 = webglFp.webGl2Enabled;
1898
+ delete webglFp.webGl2Enabled;
1899
+ // Merge the WebGL fingerprint into the config
1900
+ mergeInto(config, webglFp);
1901
+ // Set the WebGL preferences
1902
+ mergeInto(firefox_user_prefs, {
1903
+ "webgl.enable-webgl2": enableWebgl2,
1904
+ "webgl.force-enabled": true,
1905
+ });
1906
+ }
1907
+ // The CPU follows the GPU, so it is drawn once the GPU is final. A CPU the
1908
+ // caller named that the GPU contradicts (a preset's, webgl_config's, the
1909
+ // host's) is no machine at all.
1910
+ if (cpu !== undefined && cpu !== null) {
1911
+ const conflict = coherence.cpuConflict(config, targetOs);
1912
+ if (conflict)
1913
+ throw new ValueError(`cpu=${pyRepr(cpu)}: ${conflict}`);
1914
+ }
1915
+ setCpuDefault(config, targetOs, salt);
1916
+ // Every identity passes the whole-identity checks, whatever built it. The
1917
+ // pools are sampled independently, so a machine that never existed can be
1918
+ // assembled from parts that are each fine on their own. See coherence.ts.
1919
+ const incoherent = coherence.apply(config, targetOs, callerKeys);
1920
+ warnKeptIncoherent(incoherent);
1921
+ if (incoherent.length && debug) {
1922
+ for (const violation of incoherent) {
1923
+ console.log(`Incoherent identity (${violation.rule}): ${violation.detail}`);
1924
+ }
1925
+ }
1926
+ // The browser computes canvas, audio, Opus, wasm and NaNs as the claimed
1927
+ // CPU does (cpu-identity.patch). A build without the patch ignores the pref
1928
+ // and computes as the host does.
1929
+ const cpuPref = cpuIdentityPref(config);
1930
+ if (cpuPref && !("general.cpu_identity" in firefox_user_prefs)) {
1931
+ firefox_user_prefs["general.cpu_identity"] = cpuPref;
1932
+ }
1933
+ if (vpxRealtimeOnly(config, targetOs) &&
1934
+ !("media.libvpx.realtime_only" in firefox_user_prefs)) {
1935
+ firefox_user_prefs["media.libvpx.realtime_only"] = true;
1936
+ }
1937
+ // Render at the claimed display scale, so (resolution) and the CSS geometry
1938
+ // agree with devicePixelRatio as on the real machine (#933). That includes 1:
1939
+ // on a HiDPI host the host's own scale would otherwise reach (resolution).
1940
+ const dpr = Number(config["window.devicePixelRatio"]);
1941
+ if (dpr && !("layout.css.devPixelsPerPx" in firefox_user_prefs)) {
1942
+ firefox_user_prefs["layout.css.devPixelsPerPx"] = String(dpr);
1943
+ }
1944
+ if (headless === false && !virtual_display && screenCons) {
1945
+ const fit = physicalScale(config, firefox_user_prefs);
1946
+ for (const [axis, cap] of [
1947
+ ["Width", screenCons.maxWidth],
1948
+ ["Height", screenCons.maxHeight],
1949
+ ]) {
1950
+ const size = config[`window.outer${axis}`];
1951
+ if (cap && size && size * fit > cap) {
1952
+ throw new Error(`window.outer${axis} ${size} at display scale ${fit} needs ${size * fit} pixels, ` +
1953
+ `but this monitor has ${cap}. Pass a smaller screen and window, or run headless.`);
1954
+ }
1955
+ }
1956
+ }
1957
+ setWebgpu(firefox_user_prefs, targetOs, [config["webGl:vendor"], config["webGl:renderer"]], host);
1958
+ // Cache previous pages, requests, etc (uses more memory)
1959
+ if (enable_cache) {
1960
+ mergeInto(firefox_user_prefs, CACHE_PREFS);
1961
+ }
1962
+ // Print the config if debug is enabled
1963
+ if (debug) {
1964
+ console.log("[DEBUG] Config:");
1965
+ console.log(inspect(config, { depth: null, sorted: true }));
1966
+ }
1967
+ // Validate the config
1968
+ warnIfExecutablePredatesPlaywright(executable_path);
1969
+ utilsDeps.validateConfig(config, executable_path);
1970
+ // A SOCKS5 proxy's credentials go to Juggler, not through Playwright, which
1971
+ // refuses them (socks5Auth).
1972
+ const [launchProxy, proxyAuth] = socks5Auth(proxy);
1973
+ // Prepare environment variables to pass to Camoufox
1974
+ const envVars = {
1975
+ ...utilsDeps.getEnvVars(config, targetOs, executable_path),
1976
+ ...getPrefEnvVars(firefox_user_prefs),
1977
+ ...(proxyAuth ? proxyAuthEnv(proxyAuth) : {}),
1978
+ ...env,
1979
+ };
1980
+ const result = {
1981
+ executablePath: resolvedExecutable,
1982
+ args,
1983
+ env: envVars,
1984
+ firefoxUserPrefs: firefox_user_prefs,
1985
+ headless,
1986
+ ...passthrough,
1987
+ };
1988
+ // Only include proxy if it's set (Playwright validates this)
1989
+ // https://github.com/coryking/camoufox/commit/1336e8e509e8c12a896a09d9ee51f131f739f106
1990
+ // Thanks @coryking
1991
+ if (launchProxy != null) {
1992
+ result.proxy = launchProxy;
1993
+ }
1994
+ return result;
1995
+ }