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