camoucore 0.3.0 → 0.6.0

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