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,2057 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Launch-option assembly, the twin of python/camoucore/src/camoucore/camouwolf/utils.py:
|
|
3
|
+
* launchOptions() must return what launch_options() does
|
|
4
|
+
* (tests/launch-golden.test.ts). `utilsDeps` holds what the Python tests
|
|
5
|
+
* monkeypatch.
|
|
6
|
+
*/
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { createHash, randomInt } from "node:crypto";
|
|
9
|
+
import * as fs from "node:fs";
|
|
10
|
+
import * as path from "node:path";
|
|
11
|
+
import { inspect } from "node:util";
|
|
12
|
+
import { ensureModel } from "fpgen-js";
|
|
13
|
+
import * as cpuAffinity from "../cpu_affinity.js";
|
|
14
|
+
import { hasDisplay, largestDisplay } from "../display.js";
|
|
15
|
+
import { geoipAllowed, getGeolocation } from "../geolocation.js";
|
|
16
|
+
import { ProxyHelper, publicIP, publicIPv6, validIPv4, } from "../ip.js";
|
|
17
|
+
import { handleLocales } from "../locales.js";
|
|
18
|
+
import { checkPassthrough, warnPassthrough } from "../passthrough.js";
|
|
19
|
+
import { applyDefaults, loadDefaults } from "../settings.js";
|
|
20
|
+
import { Telemetry, telemetryEnabled } from "../telemetry.js";
|
|
21
|
+
import { VirtualDisplay } from "../virtdisplay.js";
|
|
22
|
+
import { LIBRARY_VERSION } from "./__version__.js";
|
|
23
|
+
import { addDefaultAddons, confirmPaths } from "./addons.js";
|
|
24
|
+
import * as clienthints from "./clienthints.js";
|
|
25
|
+
import * as coherence from "./coherence.js";
|
|
26
|
+
import { attachDriverDefaults } from "./driver_defaults.js";
|
|
27
|
+
import { IncoherentIdentity, InvalidOS, InvalidPropertyType, NonChromeFingerprint, NotImplementedError, UnknownIPLocation, UnknownProperty, UnsupportedOSSpoof, ValueError, } from "./exceptions.js";
|
|
28
|
+
import { clampScreenToDisplay, clampWindowDimensions, clampWindowPosition, DEFAULT_MEDIA_DEVICES, ESSENTIAL_FONTS, fingerprintOs, fixHardwareConcurrency, fixScreenNoTaskbar, fromFpgen, generateFingerprint, handleWindowSize, OS_KEYS, OS_NAMES, raiseScreenToModernFloor, Screen, snapWindowToDevicePixels, windowSwitchBounds, } from "./fingerprints.js";
|
|
29
|
+
import { GPU_SWITCHES, GpuDisplay, proveGpu, selectGpu } from "./gpudisplay.js";
|
|
30
|
+
import { normalize } from "./humanize.js";
|
|
31
|
+
import { DEFAULTS_FILE, INSTALL_DIR, loadDataFile, OS_NAME } from "./paths.js";
|
|
32
|
+
import { buildFile, ensureBrowserProfileDir, ensureCamouwolfInstalled, installedVerStr, launchPath, selectedLaunchPath, warnIfPackageOutdated, } from "./pkgman.js";
|
|
33
|
+
import { PRODUCT } from "./product.js";
|
|
34
|
+
import { comparePyStr, isPlainObject, num, orjsonDumps, PyFloat, pyRepr, pyStr, pyStrRepr, pyTruthy, pyTypeName, } from "./pycompat.js";
|
|
35
|
+
import { auditSwitches, IGNORED_DEFAULT_ARGS, LAUNCHER_DISABLED_FEATURES, mergeListSwitches, PLAYWRIGHT_DISABLED_FEATURES, PLAYWRIGHT_HEADLESS_BLINK_SETTINGS, } from "./switches.js";
|
|
36
|
+
import { LeakWarning, loadWarnings, warn } from "./warnings.js";
|
|
37
|
+
import { chromeGpus, readoutNames, usableGpu } from "./webgl.js";
|
|
38
|
+
/** System colours of each OS's default theme, by OS name. */
|
|
39
|
+
export const SYSTEM_COLORS = loadDataFile("data/system-colors.json");
|
|
40
|
+
/**
|
|
41
|
+
* What this host can pass for. A Linux build can render as Windows (the
|
|
42
|
+
* bundled Windows fonts, the UCRT math replica, patches 0019 and 0022);
|
|
43
|
+
* nothing makes a Linux or Windows host render as macOS, or a Windows or macOS
|
|
44
|
+
* host as Linux.
|
|
45
|
+
*/
|
|
46
|
+
export const ALLOWED_OS_TARGETS = {
|
|
47
|
+
win: ["windows"],
|
|
48
|
+
lin: ["linux", "windows"],
|
|
49
|
+
mac: ["macos"],
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* How many fingerprints to draw before giving up on one whose GPU the identity
|
|
53
|
+
* can claim. fpgen's GPU condition already excludes software renderers, so a
|
|
54
|
+
* redraw only happens for a record whose ANGLE backend its own OS never uses.
|
|
55
|
+
*/
|
|
56
|
+
export const MAX_FINGERPRINT_DRAWS = 20;
|
|
57
|
+
export const FONT_FILE_SUFFIXES = [
|
|
58
|
+
".ttf",
|
|
59
|
+
".otf",
|
|
60
|
+
".ttc",
|
|
61
|
+
".woff",
|
|
62
|
+
".woff2",
|
|
63
|
+
".pfb",
|
|
64
|
+
];
|
|
65
|
+
/** What the launch reads from the host; the tests replace these. */
|
|
66
|
+
export const utilsDeps = {
|
|
67
|
+
osName: () => OS_NAME,
|
|
68
|
+
installDir: () => INSTALL_DIR,
|
|
69
|
+
/** os.environ, for CAMOUWOLF_EXECUTABLE_PATH and the default `env`. */
|
|
70
|
+
environ: () => process.env,
|
|
71
|
+
hasDisplay,
|
|
72
|
+
largestDisplay,
|
|
73
|
+
/** Overrides for the host CPU probes of fixHardwareConcurrency. */
|
|
74
|
+
hostCpu: () => ({}),
|
|
75
|
+
print: (line) => {
|
|
76
|
+
process.stdout.write(`${line}\n`);
|
|
77
|
+
},
|
|
78
|
+
ensureBrowserProfileDir,
|
|
79
|
+
ensureCamouwolfInstalled,
|
|
80
|
+
warnIfPackageOutdated,
|
|
81
|
+
addDefaultAddons,
|
|
82
|
+
confirmPaths,
|
|
83
|
+
installedVerStr: () => installedVerStr(),
|
|
84
|
+
launchPath,
|
|
85
|
+
selectedLaunchPath,
|
|
86
|
+
/** fpgen's model is fetched on first use, like Python's. */
|
|
87
|
+
ensureModel: async () => {
|
|
88
|
+
await ensureModel();
|
|
89
|
+
},
|
|
90
|
+
generateFingerprint,
|
|
91
|
+
chromeGpus,
|
|
92
|
+
publicIp: publicIP,
|
|
93
|
+
publicIpv6: publicIPv6,
|
|
94
|
+
geoipAllowed,
|
|
95
|
+
getGeolocation,
|
|
96
|
+
selectGpu,
|
|
97
|
+
/** secrets.randbelow(2**32 - 1) + 1 */
|
|
98
|
+
canvasSeed: () => randomInt(0, 2 ** 32 - 1) + 1,
|
|
99
|
+
};
|
|
100
|
+
/*
|
|
101
|
+
* Environment: the identity travels in CAMOU_CONFIG_<n>, never in argv.
|
|
102
|
+
*/
|
|
103
|
+
/**
|
|
104
|
+
* orjson.dumps(config): compact, UTF-8, insertion order. JavaScript has one
|
|
105
|
+
* number type, so the Python int/float split is carried the way pycompat
|
|
106
|
+
* carries it: a safe-integer number is an int, a bigint is an int beyond
|
|
107
|
+
* 2**53, a PyFloat is an integral float, and any other number is a float.
|
|
108
|
+
*/
|
|
109
|
+
export function configJson(value) {
|
|
110
|
+
return orjsonDumps(value, false);
|
|
111
|
+
}
|
|
112
|
+
/** What orjson.dumps refuses, as its error text; null when serializable. */
|
|
113
|
+
function unserializable(value) {
|
|
114
|
+
if (value === undefined)
|
|
115
|
+
return "Type is not JSON serializable: undefined";
|
|
116
|
+
if (value === null)
|
|
117
|
+
return null;
|
|
118
|
+
if (typeof value === "function" || typeof value === "symbol")
|
|
119
|
+
return `Type is not JSON serializable: ${typeof value}`;
|
|
120
|
+
if (typeof value === "number" && !Number.isFinite(value))
|
|
121
|
+
return null;
|
|
122
|
+
if (typeof value !== "object" || value instanceof PyFloat)
|
|
123
|
+
return null;
|
|
124
|
+
if (Array.isArray(value)) {
|
|
125
|
+
for (const item of value) {
|
|
126
|
+
const problem = unserializable(item);
|
|
127
|
+
if (problem)
|
|
128
|
+
return problem;
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
if (!isPlainObject(value)) {
|
|
133
|
+
return `Type is not JSON serializable: ${value.constructor?.name ?? "object"}`;
|
|
134
|
+
}
|
|
135
|
+
for (const item of Object.values(value)) {
|
|
136
|
+
const problem = unserializable(item);
|
|
137
|
+
if (problem)
|
|
138
|
+
return problem;
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
/** Slice `s` into chunks of `size` code points (Python str slicing). */
|
|
143
|
+
function chunkCodePoints(s, size) {
|
|
144
|
+
// Fast path: no astral characters, so UTF-16 units == code points.
|
|
145
|
+
if (!/[\ud800-\udfff]/.test(s)) {
|
|
146
|
+
const out = [];
|
|
147
|
+
for (let i = 0; i < s.length; i += size)
|
|
148
|
+
out.push(s.slice(i, i + size));
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
const cps = Array.from(s);
|
|
152
|
+
const out = [];
|
|
153
|
+
for (let i = 0; i < cps.length; i += size) {
|
|
154
|
+
out.push(cps.slice(i, i + size).join(""));
|
|
155
|
+
}
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
function isDir(p) {
|
|
159
|
+
try {
|
|
160
|
+
return fs.statSync(p).isDirectory();
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* The bundled font directories an identity on `osDir` may see.
|
|
168
|
+
*
|
|
169
|
+
* fontconfig scans a <dir> recursively, so the parent is never named when the
|
|
170
|
+
* bundle is split by OS: it would make every other OS's files candidates for
|
|
171
|
+
* glyph fallback.
|
|
172
|
+
*/
|
|
173
|
+
function fontScanDirs(fontsDir, osDir) {
|
|
174
|
+
const groupsPath = path.join(fontsDir, "groups.json");
|
|
175
|
+
const osKey = Object.hasOwn(OS_KEYS, osDir) ? OS_KEYS[osDir] : undefined;
|
|
176
|
+
if (osKey && fs.existsSync(groupsPath)) {
|
|
177
|
+
let readBy = [];
|
|
178
|
+
try {
|
|
179
|
+
const parsed = JSON.parse(fs.readFileSync(groupsPath, "utf8"));
|
|
180
|
+
readBy = parsed?.readBy?.[osKey] ?? [];
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
readBy = [];
|
|
184
|
+
}
|
|
185
|
+
const dirs = readBy
|
|
186
|
+
.map((g) => path.join(fontsDir, String(g)))
|
|
187
|
+
.filter((d) => isDir(d));
|
|
188
|
+
if (dirs.length)
|
|
189
|
+
return dirs;
|
|
190
|
+
}
|
|
191
|
+
if (isDir(path.join(fontsDir, osDir)))
|
|
192
|
+
return [path.join(fontsDir, osDir)];
|
|
193
|
+
return [fontsDir];
|
|
194
|
+
}
|
|
195
|
+
/** os.walk(): symlinked directories are listed, not entered. */
|
|
196
|
+
function hasFonts(directories) {
|
|
197
|
+
const walk = (directory) => {
|
|
198
|
+
let entries;
|
|
199
|
+
try {
|
|
200
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
const subdirs = [];
|
|
206
|
+
for (const entry of entries) {
|
|
207
|
+
const full = path.join(directory, entry.name);
|
|
208
|
+
if (entry.isDirectory()) {
|
|
209
|
+
subdirs.push(full);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (entry.isSymbolicLink() && isDir(full))
|
|
213
|
+
continue;
|
|
214
|
+
const lowered = entry.name.toLowerCase();
|
|
215
|
+
if (FONT_FILE_SUFFIXES.some((suffix) => lowered.endsWith(suffix)))
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
return subdirs.some(walk);
|
|
219
|
+
};
|
|
220
|
+
return directories.some(walk);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* A runtime fontconfig for an identity on `osDir` ('linux', 'macos',
|
|
224
|
+
* 'windows'), from the bundle beside the binary; null when the bundle ships no
|
|
225
|
+
* fonts for that OS.
|
|
226
|
+
*
|
|
227
|
+
* The bundled fonts.conf names its font directory relative to the working
|
|
228
|
+
* directory, which breaks when the launcher runs anywhere else, so a copy with
|
|
229
|
+
* absolute paths is written to the cache directory (not into the bundle, which
|
|
230
|
+
* is commonly read-only at launch). Loaded through FONTCONFIG_FILE it is the
|
|
231
|
+
* only config: the host's /etc/fonts rules, and so the host's fonts, are not
|
|
232
|
+
* read.
|
|
233
|
+
*/
|
|
234
|
+
export function generateFontconfig(executablePath, osDir) {
|
|
235
|
+
const fontsConf = buildFile(executablePath, path.join("fontconfig", osDir, "fonts.conf"));
|
|
236
|
+
const fontsDir = buildFile(executablePath, "fonts");
|
|
237
|
+
if (!fs.existsSync(fontsConf))
|
|
238
|
+
return null;
|
|
239
|
+
const scanDirs = fontScanDirs(fontsDir, osDir);
|
|
240
|
+
// A bundle whose fonts were not restored still ships fonts.conf. Loading it
|
|
241
|
+
// would leave the browser with no fonts at all.
|
|
242
|
+
if (!hasFonts(scanDirs))
|
|
243
|
+
return null;
|
|
244
|
+
const content = fs
|
|
245
|
+
.readFileSync(fontsConf, "utf8")
|
|
246
|
+
.replaceAll('<dir prefix="cwd">fonts</dir>', () => scanDirs.map((d) => `<dir>${d}</dir>`).join("\n\t"));
|
|
247
|
+
const cacheDir = path.join(utilsDeps.installDir(), "fontconfig");
|
|
248
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
249
|
+
const digest = createHash("sha256")
|
|
250
|
+
.update(content)
|
|
251
|
+
.digest("hex")
|
|
252
|
+
.slice(0, 12);
|
|
253
|
+
const runtimeConf = path.join(cacheDir, `fonts-${digest}.conf`);
|
|
254
|
+
if (!fs.existsSync(runtimeConf))
|
|
255
|
+
fs.writeFileSync(runtimeConf, content);
|
|
256
|
+
return runtimeConf;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* The config as CAMOU_CONFIG_1..N environment variables.
|
|
260
|
+
*
|
|
261
|
+
* Windows limits one variable to 32767 characters and, through some launch
|
|
262
|
+
* paths, to 2047, so the JSON is split there; elsewhere at 32767.
|
|
263
|
+
*/
|
|
264
|
+
export function configEnvVars(configMap, chunkSize) {
|
|
265
|
+
const problem = unserializable(configMap);
|
|
266
|
+
if (problem) {
|
|
267
|
+
throw new InvalidPropertyType(`The config cannot be serialized to JSON: ${problem}`);
|
|
268
|
+
}
|
|
269
|
+
const configStr = configJson(configMap);
|
|
270
|
+
const size = chunkSize ?? (utilsDeps.osName() === "win" ? 2047 : 32767);
|
|
271
|
+
const out = {};
|
|
272
|
+
chunkCodePoints(configStr, size).forEach((chunk, i) => {
|
|
273
|
+
out[`CAMOU_CONFIG_${i + 1}`] = chunk;
|
|
274
|
+
});
|
|
275
|
+
return out;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Gets the environment variables for Camouwolf: the config, and what the
|
|
279
|
+
* identity's OS needs from the process environment.
|
|
280
|
+
*
|
|
281
|
+
* `executablePath` is the executable about to launch; its bundle's fontconfig
|
|
282
|
+
* is used.
|
|
283
|
+
*/
|
|
284
|
+
export function getEnvVars(configMap, userAgentOs, executablePath) {
|
|
285
|
+
const envVars = configEnvVars(configMap);
|
|
286
|
+
const osName = utilsDeps.osName();
|
|
287
|
+
// Windows resolves the sin/cos/atan2 behind DOMMatrix.rotate and canvas
|
|
288
|
+
// ctx.rotate to ucrtbase; every other host resolves them to its own libm,
|
|
289
|
+
// which disagrees by 1 ULP. The browser carries a bit-exact replica behind
|
|
290
|
+
// this variable (browser/patches/0018-ucrt-math.patch). An environment
|
|
291
|
+
// variable because every process needs the answer, before any config exists.
|
|
292
|
+
if (userAgentOs === "win" && osName !== "win") {
|
|
293
|
+
envVars.CAMOUWOLF_UCRT_MATH = "1";
|
|
294
|
+
}
|
|
295
|
+
// The browser installs `timezone` as its renderers' host zone (patch 0006).
|
|
296
|
+
// TZ says the same to every other process of the browser, and to ICU before
|
|
297
|
+
// any config is parsed, so no process can answer with the host's zone.
|
|
298
|
+
// Windows does not read TZ.
|
|
299
|
+
const timezone = configMap.timezone;
|
|
300
|
+
if (pyTruthy(timezone) && osName !== "win")
|
|
301
|
+
envVars.TZ = timezone;
|
|
302
|
+
if (osName === "lin" && executablePath) {
|
|
303
|
+
const fontconfig = generateFontconfig(executablePath, OS_NAMES[userAgentOs]);
|
|
304
|
+
if (fontconfig)
|
|
305
|
+
envVars.FONTCONFIG_FILE = fontconfig;
|
|
306
|
+
}
|
|
307
|
+
return envVars;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Loads the config schema: property -> its entry. A build that ships its own
|
|
311
|
+
* properties.json beside the binary is validated against that one; otherwise
|
|
312
|
+
* the schema packaged with this library is used.
|
|
313
|
+
*/
|
|
314
|
+
function loadProperties(executablePath) {
|
|
315
|
+
let propList;
|
|
316
|
+
if (executablePath) {
|
|
317
|
+
const shipped = buildFile(executablePath, "properties.json");
|
|
318
|
+
if (fs.existsSync(shipped))
|
|
319
|
+
propList = JSON.parse(fs.readFileSync(shipped, "utf8"));
|
|
320
|
+
}
|
|
321
|
+
propList ??= loadDataFile("data/properties.json");
|
|
322
|
+
const out = {};
|
|
323
|
+
for (const prop of propList)
|
|
324
|
+
out[prop.property] = prop;
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Validates the config map: every key must be one the browser reads, with a
|
|
329
|
+
* value of its type. An unknown key throws UnknownProperty.
|
|
330
|
+
*/
|
|
331
|
+
export function validateConfig(configMap, executablePath) {
|
|
332
|
+
const properties = loadProperties(executablePath);
|
|
333
|
+
for (const [key, value] of Object.entries(configMap)) {
|
|
334
|
+
const entry = Object.hasOwn(properties, key) ? properties[key] : undefined;
|
|
335
|
+
if (!entry) {
|
|
336
|
+
throw new UnknownProperty(`Unknown property '${key}': this Camouwolf build reads no such config key. ` +
|
|
337
|
+
`Known properties: ${Object.keys(properties).sort(comparePyStr).join(", ")}`);
|
|
338
|
+
}
|
|
339
|
+
const expectedType = entry.type;
|
|
340
|
+
if (!validateType(value, expectedType)) {
|
|
341
|
+
throw new InvalidPropertyType(`Invalid type for property ${key}. Expected ${expectedType}, got ${pyTypeName(value)}`);
|
|
342
|
+
}
|
|
343
|
+
if (expectedType === "array" &&
|
|
344
|
+
!value.every((item) => typeof item === "string")) {
|
|
345
|
+
throw new InvalidPropertyType(`Invalid type for property ${key}. Expected an array of strings.`);
|
|
346
|
+
}
|
|
347
|
+
if (key === "webGl:parameters" || key === "webGl2:parameters") {
|
|
348
|
+
validateWebglParameters(key, value);
|
|
349
|
+
}
|
|
350
|
+
if (key === "systemColors") {
|
|
351
|
+
const allInts = Object.values(value).every((v) => typeof v === "bigint" ||
|
|
352
|
+
(typeof v === "number" && Number.isInteger(v)));
|
|
353
|
+
if (!allInts) {
|
|
354
|
+
throw new InvalidPropertyType("Invalid systemColors: every value must be an 0xRRGGBB integer.");
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Every entry is a decimal pname and a scalar, or a list of 2 to 4 numbers
|
|
361
|
+
* (the typed arrays getParameter returns); the browser reads nothing else.
|
|
362
|
+
*/
|
|
363
|
+
export function validateWebglParameters(key, parameters) {
|
|
364
|
+
const isNumber = (v) => typeof v === "number" || typeof v === "bigint" || v instanceof PyFloat;
|
|
365
|
+
for (const [pname, value] of Object.entries(parameters)) {
|
|
366
|
+
if (!/^\p{Nd}+$/u.test(pname)) {
|
|
367
|
+
throw new InvalidPropertyType(`Invalid ${key} key ${pyStrRepr(pname)}: expected a decimal GLenum.`);
|
|
368
|
+
}
|
|
369
|
+
const scalar = typeof value === "boolean" ||
|
|
370
|
+
typeof value === "string" ||
|
|
371
|
+
isNumber(value);
|
|
372
|
+
const array = Array.isArray(value) &&
|
|
373
|
+
value.length >= 2 &&
|
|
374
|
+
value.length <= 4 &&
|
|
375
|
+
value.every(isNumber);
|
|
376
|
+
if (!scalar && !array) {
|
|
377
|
+
throw new InvalidPropertyType(`Invalid ${key}[${pname}]: expected a number, boolean, string or a list of 2 to 4 numbers, ` +
|
|
378
|
+
`got ${pyTypeName(value)}.`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/** Validates the type of the value. */
|
|
383
|
+
export function validateType(value, expectedType) {
|
|
384
|
+
if (expectedType === "bool")
|
|
385
|
+
return typeof value === "boolean";
|
|
386
|
+
if (typeof value === "boolean")
|
|
387
|
+
return false;
|
|
388
|
+
const isNumber = typeof value === "number" ||
|
|
389
|
+
typeof value === "bigint" ||
|
|
390
|
+
value instanceof PyFloat;
|
|
391
|
+
// isinstance(value, int) or (isinstance(value, float) and value.is_integer())
|
|
392
|
+
const integral = typeof value === "bigint" || (isNumber && Number.isInteger(num(value)));
|
|
393
|
+
switch (expectedType) {
|
|
394
|
+
case "str":
|
|
395
|
+
return typeof value === "string";
|
|
396
|
+
case "int":
|
|
397
|
+
return integral;
|
|
398
|
+
case "uint":
|
|
399
|
+
return integral && Number(num(value)) >= 0;
|
|
400
|
+
case "double":
|
|
401
|
+
return isNumber;
|
|
402
|
+
case "array":
|
|
403
|
+
return Array.isArray(value);
|
|
404
|
+
case "dict":
|
|
405
|
+
return isPlainObject(value);
|
|
406
|
+
default:
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
/*
|
|
411
|
+
* Identity helpers
|
|
412
|
+
*/
|
|
413
|
+
/**
|
|
414
|
+
* Gets the OS from the config if the user agent is set, otherwise returns the
|
|
415
|
+
* OS of the current system.
|
|
416
|
+
*/
|
|
417
|
+
export function getTargetOs(config) {
|
|
418
|
+
const userAgent = config["navigator.userAgent"];
|
|
419
|
+
if (pyTruthy(userAgent)) {
|
|
420
|
+
const target = clienthints.uaOs(pyStr(userAgent));
|
|
421
|
+
if (!target) {
|
|
422
|
+
throw new ValueError("Could not determine OS from user agent");
|
|
423
|
+
}
|
|
424
|
+
return target;
|
|
425
|
+
}
|
|
426
|
+
return utilsDeps.osName();
|
|
427
|
+
}
|
|
428
|
+
/** Checks if the target OS is valid. */
|
|
429
|
+
export function checkValidOs(osValue) {
|
|
430
|
+
if (typeof osValue !== "string") {
|
|
431
|
+
for (const osName of osValue)
|
|
432
|
+
checkValidOs(osName);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
// Assert that the OS is lowercase (str.islower(): has a cased char, none upper)
|
|
436
|
+
if (!(osValue !== osValue.toUpperCase() && osValue === osValue.toLowerCase())) {
|
|
437
|
+
throw new InvalidOS(`OS values must be lowercase: '${osValue}'`);
|
|
438
|
+
}
|
|
439
|
+
// Assert that the OS is supported by Camouwolf
|
|
440
|
+
if (!["windows", "macos", "linux"].includes(osValue)) {
|
|
441
|
+
throw new InvalidOS(`Camouwolf does not support the OS: '${osValue}'`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
/** Refuse an identity on an OS this host cannot pass for. */
|
|
445
|
+
export function checkOsPolicy(names, allowOsMismatch) {
|
|
446
|
+
if (allowOsMismatch)
|
|
447
|
+
return;
|
|
448
|
+
const host = utilsDeps.osName();
|
|
449
|
+
const allowed = ALLOWED_OS_TARGETS[host];
|
|
450
|
+
const bad = names.filter((name) => !allowed.includes(name));
|
|
451
|
+
if (bad.length) {
|
|
452
|
+
throw new UnsupportedOSSpoof(`Camouwolf cannot pass a ${OS_NAMES[host]} host off as: ${bad.join(", ")}. ` +
|
|
453
|
+
"Supported host -> identity pairs: windows -> windows, linux -> linux, " +
|
|
454
|
+
"linux -> windows, macos -> macos. Pass allow_os_mismatch=True to override.");
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Merges new keys/values from the source into the target, given that the key
|
|
459
|
+
* does not exist in the target.
|
|
460
|
+
*/
|
|
461
|
+
export function mergeInto(target, source) {
|
|
462
|
+
for (const [key, value] of Object.entries(source)) {
|
|
463
|
+
if (!(key in target))
|
|
464
|
+
target[key] = value;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
/** dict.setdefault() */
|
|
468
|
+
function setDefault(target, key, value) {
|
|
469
|
+
if (!(key in target))
|
|
470
|
+
target[key] = value;
|
|
471
|
+
}
|
|
472
|
+
/** Checks if a domain is set in the config. */
|
|
473
|
+
export function isDomainSet(config, ...properties) {
|
|
474
|
+
for (const prop of properties) {
|
|
475
|
+
// A trailing . or : makes it a prefix
|
|
476
|
+
if (prop.endsWith(".") || prop.endsWith(":")) {
|
|
477
|
+
if (Object.keys(config).some((key) => key.startsWith(prop)))
|
|
478
|
+
return true;
|
|
479
|
+
}
|
|
480
|
+
else if (prop in config) {
|
|
481
|
+
return true;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return false;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Warns for each coherence violation the launch left in place because the
|
|
488
|
+
* caller set the values involved. Camouwolf does not overwrite what the caller
|
|
489
|
+
* passed, but an identity no real machine presents is detectable.
|
|
490
|
+
*/
|
|
491
|
+
export function warnKeptIncoherent(violations) {
|
|
492
|
+
for (const violation of violations) {
|
|
493
|
+
if (!violation.kept.length)
|
|
494
|
+
continue;
|
|
495
|
+
const keys = violation.kept.join(", ");
|
|
496
|
+
warn(loadWarnings()
|
|
497
|
+
.caller_value_incoherent.replaceAll("{keys}", () => keys)
|
|
498
|
+
.replaceAll("{detail}", () => violation.detail), "LeakWarning");
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Warns the user if they are manually setting properties that Camouwolf
|
|
503
|
+
* already sets internally.
|
|
504
|
+
*/
|
|
505
|
+
export function warnManualConfig(config) {
|
|
506
|
+
if (isDomainSet(config, "navigator.languages"))
|
|
507
|
+
LeakWarning.warn(loadWarnings().locale, false);
|
|
508
|
+
if (isDomainSet(config, "geolocation:", "timezone"))
|
|
509
|
+
LeakWarning.warn(loadWarnings().geolocation, false);
|
|
510
|
+
if (Object.keys(config).some((key) => (key.startsWith("navigator.") || key.startsWith("userAgentData.")) &&
|
|
511
|
+
key !== "navigator.languages")) {
|
|
512
|
+
LeakWarning.warn(loadWarnings().navigator, false);
|
|
513
|
+
}
|
|
514
|
+
if (isDomainSet(config, "screen.", "window."))
|
|
515
|
+
LeakWarning.warn(loadWarnings().viewport, false);
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Asserts that the passed fingerprint is a Chrome fingerprint, and warns the
|
|
519
|
+
* user that passing their own fingerprint is not recommended.
|
|
520
|
+
*/
|
|
521
|
+
export function checkCustomFingerprint(fingerprint) {
|
|
522
|
+
const navigator = pyTruthy(fingerprint.navigator)
|
|
523
|
+
? fingerprint.navigator
|
|
524
|
+
: {};
|
|
525
|
+
const userAgent = pyTruthy(navigator.userAgent)
|
|
526
|
+
? pyStr(navigator.userAgent)
|
|
527
|
+
: "";
|
|
528
|
+
if (!userAgent.includes("Chrome/") ||
|
|
529
|
+
/Edg\/|OPR\/|Firefox\//.test(userAgent)) {
|
|
530
|
+
throw new NonChromeFingerprint("This fingerprint is not from Chrome " +
|
|
531
|
+
`(user agent: ${pyStrRepr(userAgent || "none")}). Camouwolf is Chromium; a fingerprint from another ` +
|
|
532
|
+
'browser WILL lead to detection. Generate one with fpgen and browser="Chrome".');
|
|
533
|
+
}
|
|
534
|
+
LeakWarning.warn(loadWarnings().custom_fingerprint, false);
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* The Chromium version ('152.0.7977.42') of the build about to launch.
|
|
538
|
+
*
|
|
539
|
+
* The named executable's own version.json, or what the binary answers to
|
|
540
|
+
* --version; the installed release when no executable is named. A build that
|
|
541
|
+
* states no version throws, since claiming another build's would leak in the
|
|
542
|
+
* user agent and the client hints.
|
|
543
|
+
*/
|
|
544
|
+
export function resolveVersion(executablePath) {
|
|
545
|
+
if (!executablePath)
|
|
546
|
+
return utilsDeps.installedVerStr().split("-", 1)[0];
|
|
547
|
+
const versionFile = buildFile(executablePath, "version.json");
|
|
548
|
+
if (fs.existsSync(versionFile)) {
|
|
549
|
+
const version = JSON.parse(fs.readFileSync(versionFile, "utf8"))?.version;
|
|
550
|
+
if (typeof version === "string" && /^\d+(\.\d+){1,3}$/.test(version))
|
|
551
|
+
return version;
|
|
552
|
+
}
|
|
553
|
+
const result = spawnSync(executablePath, ["--version"], {
|
|
554
|
+
encoding: "utf8",
|
|
555
|
+
timeout: 30_000,
|
|
556
|
+
});
|
|
557
|
+
if (result.error) {
|
|
558
|
+
throw new ValueError(`Could not read the Chromium version of ${executablePath}: ${result.error.message}`, { cause: result.error });
|
|
559
|
+
}
|
|
560
|
+
const match = /\d+\.\d+\.\d+\.\d+/.exec(result.stdout ?? "");
|
|
561
|
+
if (!match) {
|
|
562
|
+
throw new ValueError(`${executablePath} states no Chromium version: it has no version.json beside it and ` +
|
|
563
|
+
"answered --version with nothing recognisable.");
|
|
564
|
+
}
|
|
565
|
+
return match[0];
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* What the build claims to be: "chromium" for the public build, "chrome" for
|
|
569
|
+
* one built with Chrome emulation (version.json's `product`).
|
|
570
|
+
*/
|
|
571
|
+
export function buildProduct(executablePath) {
|
|
572
|
+
const versionFile = buildFile(executablePath, "version.json");
|
|
573
|
+
if (!fs.existsSync(versionFile))
|
|
574
|
+
return "chromium";
|
|
575
|
+
return (JSON.parse(fs.readFileSync(versionFile, "utf8"))?.product ?? "chromium");
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* The navigator.keyboard.getLayoutMap() of a US QWERTY keyboard on the target
|
|
579
|
+
* OS, as "code=key" entries. null on macOS, where the host's map is left as it
|
|
580
|
+
* is.
|
|
581
|
+
*/
|
|
582
|
+
export function keyboardLayoutMap(targetOs) {
|
|
583
|
+
if (targetOs === "mac")
|
|
584
|
+
return null;
|
|
585
|
+
return [
|
|
586
|
+
...Array.from("abcdefghijklmnopqrstuvwxyz", (c) => `Key${c.toUpperCase()}=${c}`),
|
|
587
|
+
...Array.from("0123456789", (d) => `Digit${d}=${d}`),
|
|
588
|
+
"Backquote=`",
|
|
589
|
+
"Minus=-",
|
|
590
|
+
"Equal==",
|
|
591
|
+
"BracketLeft=[",
|
|
592
|
+
"BracketRight=]",
|
|
593
|
+
"Backslash=\\",
|
|
594
|
+
"Semicolon=;",
|
|
595
|
+
"Quote='",
|
|
596
|
+
"Comma=,",
|
|
597
|
+
"Period=.",
|
|
598
|
+
"Slash=/",
|
|
599
|
+
targetOs === "win" ? "IntlBackslash=\\" : "IntlBackslash=<",
|
|
600
|
+
];
|
|
601
|
+
}
|
|
602
|
+
/** Chrome's default language list per first language (data/chrome-languages.json). */
|
|
603
|
+
export const CHROME_LANGUAGES = loadDataFile("data/chrome-languages.json");
|
|
604
|
+
/**
|
|
605
|
+
* The language list for a resolved locale: every listed locale, or Chrome's
|
|
606
|
+
* own default list for the primary one (data/chrome-languages.json).
|
|
607
|
+
*
|
|
608
|
+
* The default is the list an off-the-record profile serves whatever the user
|
|
609
|
+
* set, so a Playwright context and a persistent one claim the same list.
|
|
610
|
+
*/
|
|
611
|
+
export function languagesFor(localeConfig) {
|
|
612
|
+
const listed = localeConfig["locale:all"];
|
|
613
|
+
if (pyTruthy(listed)) {
|
|
614
|
+
return String(listed)
|
|
615
|
+
.split(",")
|
|
616
|
+
.map((tag) => tag.trim())
|
|
617
|
+
.filter((tag) => tag);
|
|
618
|
+
}
|
|
619
|
+
const language = localeConfig["locale:language"];
|
|
620
|
+
const region = localeConfig["locale:region"];
|
|
621
|
+
if (!pyTruthy(language))
|
|
622
|
+
return null;
|
|
623
|
+
const primary = pyTruthy(region) ? `${language}-${region}` : language;
|
|
624
|
+
// language_prefs.cc GetIncognitoLanguageList: a first language the table
|
|
625
|
+
// lacks is followed by the en-US list.
|
|
626
|
+
const known = CHROME_LANGUAGES.lists[primary];
|
|
627
|
+
return known
|
|
628
|
+
? [...known]
|
|
629
|
+
: [primary, ...CHROME_LANGUAGES.lists[CHROME_LANGUAGES.fallback]];
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Merge `prefs` into the profile's Default/Preferences file.
|
|
633
|
+
*
|
|
634
|
+
* Keys are Chromium's dotted pref paths ("credentials_enable_service",
|
|
635
|
+
* "profile.default_content_setting_values.notifications") or nested objects; a
|
|
636
|
+
* dotted key is expanded into the nested form Chromium stores.
|
|
637
|
+
*/
|
|
638
|
+
export function writeChromiumPrefs(userDataDir, prefs) {
|
|
639
|
+
const file = path.join(userDataDir, "Default", "Preferences");
|
|
640
|
+
let current;
|
|
641
|
+
try {
|
|
642
|
+
current = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
643
|
+
}
|
|
644
|
+
catch {
|
|
645
|
+
current = {};
|
|
646
|
+
}
|
|
647
|
+
const merge = (target, source) => {
|
|
648
|
+
for (const [key, value] of Object.entries(source)) {
|
|
649
|
+
if (isPlainObject(value) && isPlainObject(target[key]))
|
|
650
|
+
merge(target[key], value);
|
|
651
|
+
else
|
|
652
|
+
target[key] = value;
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
for (const [key, value] of Object.entries(prefs)) {
|
|
656
|
+
let nested = value;
|
|
657
|
+
for (const part of key.split(".").reverse())
|
|
658
|
+
nested = { [part]: nested };
|
|
659
|
+
merge(current, nested);
|
|
660
|
+
}
|
|
661
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
662
|
+
fs.writeFileSync(file, JSON.stringify(current));
|
|
663
|
+
return file;
|
|
664
|
+
}
|
|
665
|
+
/*
|
|
666
|
+
* What a set of launch options carries
|
|
667
|
+
*/
|
|
668
|
+
/** The CAMOU_CONFIG_<n> chunks of a set of launch options, joined in order. */
|
|
669
|
+
export function camouConfigBlob(fromOptions) {
|
|
670
|
+
const env = fromOptions.env ?? {};
|
|
671
|
+
return Object.entries(env)
|
|
672
|
+
.filter(([k]) => /^CAMOU_CONFIG_\d+$/.test(k))
|
|
673
|
+
.map(([k, v]) => [
|
|
674
|
+
Number.parseInt(k.slice(k.lastIndexOf("_") + 1), 10),
|
|
675
|
+
String(v),
|
|
676
|
+
])
|
|
677
|
+
.sort((a, b) => a[0] - b[0])
|
|
678
|
+
.map(([, v]) => v)
|
|
679
|
+
.join("");
|
|
680
|
+
}
|
|
681
|
+
/** The config a set of launch options carries in its environment. */
|
|
682
|
+
export function launchConfig(fromOptions) {
|
|
683
|
+
const blob = camouConfigBlob(fromOptions);
|
|
684
|
+
if (!blob)
|
|
685
|
+
return {};
|
|
686
|
+
try {
|
|
687
|
+
const config = JSON.parse(blob);
|
|
688
|
+
return isPlainObject(config) ? config : {};
|
|
689
|
+
}
|
|
690
|
+
catch {
|
|
691
|
+
return {};
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* The OS ('macos', 'windows' or 'linux') of the identity these launch options
|
|
696
|
+
* claim, the host's when they claim no user agent.
|
|
697
|
+
*/
|
|
698
|
+
export function launchOs(fromOptions) {
|
|
699
|
+
return OS_NAMES[getTargetOs(launchConfig(fromOptions))];
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Whether these launch options are a passthrough launch's: every drawn
|
|
703
|
+
* identity claims a user agent, and a passthrough launch draws none.
|
|
704
|
+
*/
|
|
705
|
+
export function launchIsPassthrough(fromOptions) {
|
|
706
|
+
return !("navigator.userAgent" in launchConfig(fromOptions));
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* The position these launch options place the browser at, as Playwright's
|
|
710
|
+
* `geolocation` option, or null.
|
|
711
|
+
*/
|
|
712
|
+
export function launchGeolocation(fromOptions) {
|
|
713
|
+
return geolocationOf(launchConfig(fromOptions));
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* The position an identity places its browser at, as Playwright's
|
|
717
|
+
* `geolocation` option, or null.
|
|
718
|
+
*/
|
|
719
|
+
export function geolocationOf(config) {
|
|
720
|
+
const latitude = config["geolocation:latitude"];
|
|
721
|
+
const longitude = config["geolocation:longitude"];
|
|
722
|
+
if (latitude === null ||
|
|
723
|
+
latitude === undefined ||
|
|
724
|
+
longitude === null ||
|
|
725
|
+
longitude === undefined) {
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
const geolocation = { latitude, longitude };
|
|
729
|
+
if (pyTruthy(config["geolocation:accuracy"]))
|
|
730
|
+
geolocation.accuracy = config["geolocation:accuracy"];
|
|
731
|
+
return geolocation;
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* The core count the browser must be pinned to for these launch options, or
|
|
735
|
+
* null: the identity's navigator.hardwareConcurrency when this host can honour
|
|
736
|
+
* it (see cpu_affinity), so a page measuring parallelism sees the reported
|
|
737
|
+
* number.
|
|
738
|
+
*/
|
|
739
|
+
export function pinnedCoreCount(fromOptions) {
|
|
740
|
+
if (!cpuAffinity.supported())
|
|
741
|
+
return null;
|
|
742
|
+
const value = launchConfig(fromOptions)["navigator.hardwareConcurrency"];
|
|
743
|
+
// The host's count, not this process's live mask: a concurrent pinned
|
|
744
|
+
// launch narrows that while its browser spawns.
|
|
745
|
+
const cores = cpuAffinity.hostCoreCount();
|
|
746
|
+
if (typeof value === "number" &&
|
|
747
|
+
Number.isInteger(value) &&
|
|
748
|
+
cores &&
|
|
749
|
+
value >= 1 &&
|
|
750
|
+
value < cores) {
|
|
751
|
+
return value;
|
|
752
|
+
}
|
|
753
|
+
return null;
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* PID of the process that will spawn the browser (its children inherit the
|
|
757
|
+
* CPU affinity set on it). Python's driver is a separate Node process;
|
|
758
|
+
* playwright-core runs in this one.
|
|
759
|
+
*/
|
|
760
|
+
export function driverPid() {
|
|
761
|
+
return process.pid;
|
|
762
|
+
}
|
|
763
|
+
/*
|
|
764
|
+
* Context defaults
|
|
765
|
+
*/
|
|
766
|
+
/**
|
|
767
|
+
* Playwright emulates four media features on every context it creates, whether
|
|
768
|
+
* or not the caller asked: `colorScheme` defaults to "light" and reducedMotion
|
|
769
|
+
* / forcedColors / contrast to their no-preference values. That is an
|
|
770
|
+
* override, not a passthrough: the page then reports it whatever the host is
|
|
771
|
+
* set to. `null` is Playwright's own opt-out (Python's "no-override"): it
|
|
772
|
+
* sends no emulation at all and the browser answers for itself.
|
|
773
|
+
*/
|
|
774
|
+
export const STOCK_MEDIA_DEFAULTS = {
|
|
775
|
+
colorScheme: null,
|
|
776
|
+
reducedMotion: null,
|
|
777
|
+
forcedColors: null,
|
|
778
|
+
contrast: null,
|
|
779
|
+
};
|
|
780
|
+
/**
|
|
781
|
+
* Playwright context options that would make one context's pages a different
|
|
782
|
+
* machine from its workers and request headers, which answer from the
|
|
783
|
+
* context's identity whatever Playwright emulates in a page. Named as Playwright's JS API names
|
|
784
|
+
* them (Python: user_agent, is_mobile, device_scale_factor, screen, has_touch).
|
|
785
|
+
*/
|
|
786
|
+
export const PER_CONTEXT_IDENTITY_OPTIONS = {
|
|
787
|
+
userAgent: "navigator.userAgent comes from the identity; NewContext draws a context's own",
|
|
788
|
+
isMobile: "Camouwolf only has desktop identities",
|
|
789
|
+
deviceScaleFactor: "it changes the device pixel ratio without the screen the identity claims",
|
|
790
|
+
screen: "the screen comes from the launch identity; use the `screen` launch option",
|
|
791
|
+
hasTouch: "the launch identity reports no touchscreen",
|
|
792
|
+
};
|
|
793
|
+
/**
|
|
794
|
+
* The context options in `options` that would make a context's pages disagree
|
|
795
|
+
* with its identity, each with the reason.
|
|
796
|
+
*/
|
|
797
|
+
export function perContextIdentityProblems(options) {
|
|
798
|
+
return Object.entries(PER_CONTEXT_IDENTITY_OPTIONS)
|
|
799
|
+
.filter(([option]) => options[option] !== null && options[option] !== undefined)
|
|
800
|
+
.map(([option, why]) => `${option}= cannot be set per context: ${why}`);
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Throw IncoherentIdentity for a context option that would make a context's
|
|
804
|
+
* pages disagree with its identity.
|
|
805
|
+
*/
|
|
806
|
+
export function refusePerContextIdentity(options) {
|
|
807
|
+
const problems = perContextIdentityProblems(options);
|
|
808
|
+
if (problems.length) {
|
|
809
|
+
throw new IncoherentIdentity(`${problems.join("; ")}. Workers and request headers would still answer as the context's ` +
|
|
810
|
+
"identity. NewContext draws a context its own.");
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* The adjustment every newPage()/newContext() of a Camouwolf browser gets.
|
|
815
|
+
*
|
|
816
|
+
* - no viewport: Playwright's default 1280x720 viewport is a device-metrics
|
|
817
|
+
* override, which replaces the window size the identity launched with and
|
|
818
|
+
* reports the viewport as the screen. Without it the page reads the real
|
|
819
|
+
* window. A caller's `viewport` wins.
|
|
820
|
+
* - the host's own media features instead of Playwright's emulated ones.
|
|
821
|
+
* - the launch's geolocation (geoip, or geolocation:* in config), granted, as
|
|
822
|
+
* a browser whose user chose "Always allow" has it.
|
|
823
|
+
* - a LeakWarning for an option its pages would answer with against the
|
|
824
|
+
* context's identity (NewContext refuses those outright), unless the
|
|
825
|
+
* launch is passthrough.
|
|
826
|
+
*
|
|
827
|
+
* Returns the adjusted copy of the options.
|
|
828
|
+
*/
|
|
829
|
+
export function contextDefaults(geolocation, passthrough = false) {
|
|
830
|
+
return (options) => {
|
|
831
|
+
const out = { ...options };
|
|
832
|
+
// A passthrough browser has no identity to contradict.
|
|
833
|
+
for (const problem of passthrough ? [] : perContextIdentityProblems(out)) {
|
|
834
|
+
warn(loadWarnings().per_context_identity.replaceAll("{problem}", () => problem), "LeakWarning");
|
|
835
|
+
}
|
|
836
|
+
// Python's no_viewport=True is `viewport: null` in Playwright's JS API.
|
|
837
|
+
if ("noViewport" in out) {
|
|
838
|
+
const noViewport = out.noViewport;
|
|
839
|
+
delete out.noViewport;
|
|
840
|
+
if (noViewport && !("viewport" in out))
|
|
841
|
+
out.viewport = null;
|
|
842
|
+
}
|
|
843
|
+
else if (!("viewport" in out)) {
|
|
844
|
+
out.viewport = null;
|
|
845
|
+
}
|
|
846
|
+
for (const [option, value] of Object.entries(STOCK_MEDIA_DEFAULTS)) {
|
|
847
|
+
if (!(option in out))
|
|
848
|
+
out[option] = value;
|
|
849
|
+
}
|
|
850
|
+
if (geolocation && !("geolocation" in out)) {
|
|
851
|
+
out.geolocation = { ...geolocation };
|
|
852
|
+
const permissions = [...(out.permissions ?? [])];
|
|
853
|
+
if (!permissions.includes("geolocation"))
|
|
854
|
+
permissions.push("geolocation");
|
|
855
|
+
out.permissions = permissions;
|
|
856
|
+
}
|
|
857
|
+
return out;
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Patch 0031 sends a proxied context's WebRTC through the proxy; this keeps it
|
|
862
|
+
* to TCP there, with no UDP at all.
|
|
863
|
+
*/
|
|
864
|
+
export const WEBRTC_BLOCK_SWITCH = "--force-webrtc-ip-handling-policy=disable_non_proxied_udp";
|
|
865
|
+
/**
|
|
866
|
+
* Camoufox's NewContext options that would name another browser build than the
|
|
867
|
+
* one running, which every context shares.
|
|
868
|
+
*/
|
|
869
|
+
export const OTHER_BUILD_OPTIONS = [
|
|
870
|
+
"preset",
|
|
871
|
+
"ff_version",
|
|
872
|
+
"chrome_version",
|
|
873
|
+
];
|
|
874
|
+
/**
|
|
875
|
+
* Whether this host has a public IPv6 address that geolocates where the IPv4
|
|
876
|
+
* identity does. Warns when it has one that does not.
|
|
877
|
+
*/
|
|
878
|
+
export async function keepsIpv6(geoConfig, geoipDb, iKnowWhatImDoing) {
|
|
879
|
+
const ipv6 = await utilsDeps.publicIpv6();
|
|
880
|
+
if (ipv6 === null)
|
|
881
|
+
return false;
|
|
882
|
+
let ipv6Config = {};
|
|
883
|
+
try {
|
|
884
|
+
ipv6Config = (await utilsDeps.getGeolocation(ipv6, geoipDb)).asConfig();
|
|
885
|
+
}
|
|
886
|
+
catch (error) {
|
|
887
|
+
if (!(error instanceof UnknownIPLocation))
|
|
888
|
+
throw error;
|
|
889
|
+
}
|
|
890
|
+
if (["timezone", "locale:region"].every((key) => ipv6Config[key] === geoConfig[key]))
|
|
891
|
+
return true;
|
|
892
|
+
LeakWarning.warn(loadWarnings().ipv6_elsewhere, iKnowWhatImDoing);
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* Throw for a NewContext option a context cannot take: NotImplementedError for
|
|
897
|
+
* a Camoufox one naming another browser build than the one every context runs
|
|
898
|
+
* in, IncoherentIdentity for one its pages would contradict.
|
|
899
|
+
*/
|
|
900
|
+
export function refuseContextOptions(contextOptions) {
|
|
901
|
+
for (const option of OTHER_BUILD_OPTIONS) {
|
|
902
|
+
if (contextOptions[option] !== null &&
|
|
903
|
+
contextOptions[option] !== undefined) {
|
|
904
|
+
throw new NotImplementedError(`NewContext(${option}=) is not implemented in Camouwolf: a context runs in the ` +
|
|
905
|
+
"browser's own Chromium build. Launch another browser for another build.");
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
refusePerContextIdentity(contextOptions);
|
|
909
|
+
}
|
|
910
|
+
/** The language list these launch options give the browser. */
|
|
911
|
+
export function launchLanguages(fromOptions) {
|
|
912
|
+
for (const arg of fromOptions.args ?? []) {
|
|
913
|
+
if (String(arg).startsWith("--accept-lang=")) {
|
|
914
|
+
return String(arg).split("=").slice(1).join("=").split(",");
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return null;
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* The Chromium version the launch's identity claims: the binary's, or the
|
|
921
|
+
* chrome_version milestone the launch was given.
|
|
922
|
+
*/
|
|
923
|
+
export function launchFullVersion(fromOptions) {
|
|
924
|
+
const fullVersion = resolveVersion(fromOptions.executablePath);
|
|
925
|
+
const claimed = /Chrome\/(\d+)/.exec(String(launchConfig(fromOptions)["navigator.userAgent"] ?? ""));
|
|
926
|
+
if (claimed &&
|
|
927
|
+
Number(claimed[1]) !== Number.parseInt(fullVersion.split(".", 1)[0], 10)) {
|
|
928
|
+
return `${Number(claimed[1])}.0.0.0`;
|
|
929
|
+
}
|
|
930
|
+
return fullVersion;
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Keys of the browser rather than of a machine, which a context keeps from the
|
|
934
|
+
* launch: its renderers read the context's config in place of the launch's.
|
|
935
|
+
*/
|
|
936
|
+
export const BROWSER_KEYS = [
|
|
937
|
+
"network:ipv4Only",
|
|
938
|
+
"allowAddonNewtab",
|
|
939
|
+
"instantAnimations",
|
|
940
|
+
"showcursor",
|
|
941
|
+
];
|
|
942
|
+
/**
|
|
943
|
+
* A context's own identity and language list, drawn for the browser that
|
|
944
|
+
* `fromOptions` launched.
|
|
945
|
+
*
|
|
946
|
+
* The machine is drawn afresh on the launch's OS, screen, window and core
|
|
947
|
+
* count, which one browser process cannot vary. A proxied context is placed
|
|
948
|
+
* where the proxy exits, looked up through it; any other leaves from the
|
|
949
|
+
* browser's address and so keeps the launch's place and languages.
|
|
950
|
+
*/
|
|
951
|
+
export async function contextIdentity(fromOptions, { proxy, os, fingerprint, config: callerConfig, webgl_config, webrtc_ip, fonts, custom_fonts_only, locale, timezoneId, i_know_what_im_doing, } = {}) {
|
|
952
|
+
const launch = launchConfig(fromOptions);
|
|
953
|
+
if (!Object.keys(launch).length) {
|
|
954
|
+
throw new ValueError("NewContext needs a browser launched by Camouwolf: a context identity is drawn to fit it");
|
|
955
|
+
}
|
|
956
|
+
if (launchIsPassthrough(fromOptions)) {
|
|
957
|
+
throw new ValueError("NewContext draws a context its own identity, and a passthrough browser injects none. " +
|
|
958
|
+
"Use browser.newContext(), whose pages are this machine as the rest of the browser is.");
|
|
959
|
+
}
|
|
960
|
+
const targetOs = launchOs(fromOptions);
|
|
961
|
+
if (os !== undefined && os !== null && os !== targetOs) {
|
|
962
|
+
throw new ValueError(`NewContext(os='${os}'): the browser launched as '${targetOs}', and its contexts share the ` +
|
|
963
|
+
"fonts and maths library it launched with. Launch another browser for another OS.");
|
|
964
|
+
}
|
|
965
|
+
const config = { ...(callerConfig ?? {}) };
|
|
966
|
+
if (!i_know_what_im_doing)
|
|
967
|
+
warnManualConfig(config);
|
|
968
|
+
if (timezoneId)
|
|
969
|
+
config.timezone = timezoneId;
|
|
970
|
+
if (webrtc_ip) {
|
|
971
|
+
config[validIPv4(webrtc_ip) ? "webrtc:ipv4" : "webrtc:ipv6"] = webrtc_ip;
|
|
972
|
+
}
|
|
973
|
+
let contextLocale = locale;
|
|
974
|
+
if (!proxy) {
|
|
975
|
+
for (const [key, value] of Object.entries(launch)) {
|
|
976
|
+
if (key === "timezone" ||
|
|
977
|
+
key.startsWith("geolocation:") ||
|
|
978
|
+
key.startsWith("webrtc:")) {
|
|
979
|
+
setDefault(config, key, value);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
contextLocale = pyTruthy(locale) ? locale : launchLanguages(fromOptions);
|
|
983
|
+
}
|
|
984
|
+
const { languages } = await drawIdentity(config, {
|
|
985
|
+
os: targetOs,
|
|
986
|
+
webgl_config,
|
|
987
|
+
geoip: Boolean(proxy),
|
|
988
|
+
proxy,
|
|
989
|
+
block_webrtc: (fromOptions.args ?? []).includes(WEBRTC_BLOCK_SWITCH),
|
|
990
|
+
locale: contextLocale,
|
|
991
|
+
fingerprint,
|
|
992
|
+
screen: null,
|
|
993
|
+
fonts,
|
|
994
|
+
custom_fonts_only,
|
|
995
|
+
canvas_noise: Boolean(launch["canvas:randomizeReadback"]),
|
|
996
|
+
fullVersion: launchFullVersion(fromOptions),
|
|
997
|
+
// The launch's OS already passed the policy.
|
|
998
|
+
allow_os_mismatch: true,
|
|
999
|
+
i_know_what_im_doing: Boolean(i_know_what_im_doing),
|
|
1000
|
+
browserBinary: fromOptions.executablePath,
|
|
1001
|
+
launch,
|
|
1002
|
+
});
|
|
1003
|
+
for (const key of BROWSER_KEYS) {
|
|
1004
|
+
if (key in launch)
|
|
1005
|
+
config[key] = launch[key];
|
|
1006
|
+
}
|
|
1007
|
+
// The browser serves navigator.languages from the context's language pref.
|
|
1008
|
+
delete config["navigator.languages"];
|
|
1009
|
+
if (!languages?.length) {
|
|
1010
|
+
throw new ValueError("NewContext needs a locale: neither it nor the launch names one");
|
|
1011
|
+
}
|
|
1012
|
+
return { identity: config, languages };
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* The newContext() options NewContext passes for a context with `identity`:
|
|
1016
|
+
* the caller's, placed where the identity is.
|
|
1017
|
+
*/
|
|
1018
|
+
export function newContextOptions(contextOptions, identity, proxy, geolocation) {
|
|
1019
|
+
let storageState = contextOptions.storageState;
|
|
1020
|
+
if (typeof storageState === "string") {
|
|
1021
|
+
storageState = JSON.parse(fs.readFileSync(storageState, "utf8"));
|
|
1022
|
+
}
|
|
1023
|
+
if (storageState?.origins?.length) {
|
|
1024
|
+
// Playwright writes them from a page, and a context takes its identity
|
|
1025
|
+
// before its first renderer.
|
|
1026
|
+
throw new ValueError("NewContext(storageState) with origins' localStorage is not supported: set it from a " +
|
|
1027
|
+
"page of the new context instead. Cookies alone are.");
|
|
1028
|
+
}
|
|
1029
|
+
const options = { ...contextOptions };
|
|
1030
|
+
if (proxy)
|
|
1031
|
+
options.proxy = proxy;
|
|
1032
|
+
const place = geolocation ?? geolocationOf(identity);
|
|
1033
|
+
if (place) {
|
|
1034
|
+
options.geolocation = place;
|
|
1035
|
+
const permissions = [...(options.permissions ?? [])];
|
|
1036
|
+
if (!permissions.includes("geolocation"))
|
|
1037
|
+
permissions.push("geolocation");
|
|
1038
|
+
options.permissions = permissions;
|
|
1039
|
+
}
|
|
1040
|
+
return options;
|
|
1041
|
+
}
|
|
1042
|
+
/** Target.setBrowserContextIdentity's parameters (patch 0034). */
|
|
1043
|
+
export function setContextIdentityParams(contextId, identity, languages) {
|
|
1044
|
+
return {
|
|
1045
|
+
browserContextId: contextId,
|
|
1046
|
+
identity: configJson(identity),
|
|
1047
|
+
languages,
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* The one browser context Target.getBrowserContexts lists in `after` and not
|
|
1052
|
+
* in `before`.
|
|
1053
|
+
*/
|
|
1054
|
+
export function createdContextId(before, after) {
|
|
1055
|
+
const known = new Set(before.browserContextIds);
|
|
1056
|
+
const created = after.browserContextIds.filter((id) => !known.has(id));
|
|
1057
|
+
if (created.length !== 1) {
|
|
1058
|
+
throw new Error(`Expected one new browser context, found ${created.length}: was another made at the same time?`);
|
|
1059
|
+
}
|
|
1060
|
+
return created[0];
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Launch options for launchPersistentContext(). The launch itself creates the
|
|
1064
|
+
* context, so the defaults newContext() would get go into the options.
|
|
1065
|
+
*/
|
|
1066
|
+
export function persistentContextOptions(fromOptions) {
|
|
1067
|
+
return contextDefaults(launchGeolocation(fromOptions), launchIsPassthrough(fromOptions))(fromOptions);
|
|
1068
|
+
}
|
|
1069
|
+
/**
|
|
1070
|
+
* Warn that a non-persistent launch carries extensions its contexts will not
|
|
1071
|
+
* run.
|
|
1072
|
+
*/
|
|
1073
|
+
export function warnAddonsWithoutProfile(fromOptions) {
|
|
1074
|
+
const args = fromOptions.args ?? [];
|
|
1075
|
+
if (args.some((arg) => String(arg).startsWith("--load-extension="))) {
|
|
1076
|
+
warn(loadWarnings().addons_need_persistent_context, "RuntimeWarning");
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
const LAUNCH_OPTIONS = Symbol("camouwolfLaunchOptions");
|
|
1080
|
+
/**
|
|
1081
|
+
* Give every newPage()/newContext() of `browser` Camouwolf's defaults, and keep
|
|
1082
|
+
* the launch options NewContext draws a context's identity to fit.
|
|
1083
|
+
*/
|
|
1084
|
+
export function attachContextDefaults(browser, fromOptions) {
|
|
1085
|
+
browser[LAUNCH_OPTIONS] = fromOptions;
|
|
1086
|
+
const adjust = contextDefaults(launchGeolocation(fromOptions), launchIsPassthrough(fromOptions));
|
|
1087
|
+
for (const name of ["newPage", "newContext"]) {
|
|
1088
|
+
const original = browser[name];
|
|
1089
|
+
if (typeof original !== "function")
|
|
1090
|
+
continue;
|
|
1091
|
+
browser[name] = (options, ...rest) => original.call(browser, adjust(options), ...rest);
|
|
1092
|
+
}
|
|
1093
|
+
attachDriverDefaults(browser);
|
|
1094
|
+
return browser;
|
|
1095
|
+
}
|
|
1096
|
+
/*
|
|
1097
|
+
* Defaults and telemetry
|
|
1098
|
+
*/
|
|
1099
|
+
/**
|
|
1100
|
+
* `options` with each one the caller left unset taken from the defaults file,
|
|
1101
|
+
* overlaid with the user's own.
|
|
1102
|
+
*/
|
|
1103
|
+
export function launchDefaults(options) {
|
|
1104
|
+
return applyDefaults(loadDefaults(PRODUCT, DEFAULTS_FILE), options);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Count anti-bot outcomes on every context of `target` (a Browser, or a
|
|
1108
|
+
* persistent BrowserContext) when telemetry is on; see camoucore's telemetry
|
|
1109
|
+
* for what is sent. Telemetry never fails a launch.
|
|
1110
|
+
*/
|
|
1111
|
+
export function startTelemetry(target, fromOptions, setting, persistent) {
|
|
1112
|
+
try {
|
|
1113
|
+
if (!telemetryEnabled(PRODUCT, setting))
|
|
1114
|
+
return;
|
|
1115
|
+
const passthrough = launchIsPassthrough(fromOptions);
|
|
1116
|
+
const telemetry = new Telemetry(PRODUCT, {
|
|
1117
|
+
version: LIBRARY_VERSION,
|
|
1118
|
+
browserVersion: resolveVersion(fromOptions.executablePath),
|
|
1119
|
+
crossOs: !passthrough && launchOs(fromOptions) !== OS_NAMES[utilsDeps.osName()],
|
|
1120
|
+
passthrough,
|
|
1121
|
+
proxy: fromOptions.proxy ?? null,
|
|
1122
|
+
});
|
|
1123
|
+
const watch = (context) => {
|
|
1124
|
+
try {
|
|
1125
|
+
telemetry.watch(context);
|
|
1126
|
+
}
|
|
1127
|
+
catch {
|
|
1128
|
+
// Telemetry never affects a launch.
|
|
1129
|
+
}
|
|
1130
|
+
};
|
|
1131
|
+
if (persistent) {
|
|
1132
|
+
watch(target);
|
|
1133
|
+
target.on("close", () => void telemetry.close());
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
for (const name of ["newPage", "newContext"]) {
|
|
1137
|
+
const original = target[name];
|
|
1138
|
+
if (typeof original !== "function")
|
|
1139
|
+
continue;
|
|
1140
|
+
target[name] = async (...args) => {
|
|
1141
|
+
const made = await original.apply(target, args);
|
|
1142
|
+
watch(name === "newPage" ? made.context() : made);
|
|
1143
|
+
return made;
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
telemetry.watchBrowser(target);
|
|
1147
|
+
}
|
|
1148
|
+
catch {
|
|
1149
|
+
// Telemetry never affects a launch.
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
/** The launch options a Camouwolf browser was launched with. */
|
|
1153
|
+
export function launchOptionsOf(browser) {
|
|
1154
|
+
const fromOptions = browser?.[LAUNCH_OPTIONS];
|
|
1155
|
+
if (!fromOptions) {
|
|
1156
|
+
throw new ValueError("NewContext needs a browser from NewBrowser or Camouwolf: a context identity is drawn to fit it");
|
|
1157
|
+
}
|
|
1158
|
+
return fromOptions;
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* Start the display headless="virtual" or "virtual-gpu" asks for.
|
|
1162
|
+
*
|
|
1163
|
+
* Takes the display's own options out of `options` and points the launch at
|
|
1164
|
+
* the display. Returns the display, or null, and the headless value to launch
|
|
1165
|
+
* with.
|
|
1166
|
+
*/
|
|
1167
|
+
export async function startVirtualDisplay(headless, debug, options) {
|
|
1168
|
+
const { gpu, require_gpu } = options;
|
|
1169
|
+
delete options.gpu;
|
|
1170
|
+
delete options.require_gpu;
|
|
1171
|
+
let display;
|
|
1172
|
+
if (headless === "virtual-gpu") {
|
|
1173
|
+
display = new GpuDisplay(utilsDeps.selectGpu(gpu), Boolean(debug), require_gpu !== false);
|
|
1174
|
+
// The caller's own switches come after, and win.
|
|
1175
|
+
options.args = [...GPU_SWITCHES, ...(options.args ?? [])];
|
|
1176
|
+
}
|
|
1177
|
+
else if ((gpu !== undefined && gpu !== null) ||
|
|
1178
|
+
(require_gpu !== undefined && require_gpu !== null)) {
|
|
1179
|
+
throw new ValueError("gpu and require_gpu apply to headless='virtual-gpu' only");
|
|
1180
|
+
}
|
|
1181
|
+
else if (headless === "virtual") {
|
|
1182
|
+
display = new VirtualDisplay(PRODUCT, Boolean(debug));
|
|
1183
|
+
}
|
|
1184
|
+
else {
|
|
1185
|
+
return [null, headless];
|
|
1186
|
+
}
|
|
1187
|
+
// launchOptions sizes the display to the identity and starts it.
|
|
1188
|
+
options.virtual_display = display;
|
|
1189
|
+
return [display, false];
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Attaches the virtual display to the browser's cleanup, and on a GPU display
|
|
1193
|
+
* checks the browser renders on the GPU. (Python has an async and a sync
|
|
1194
|
+
* variant; playwright-core has one API.)
|
|
1195
|
+
*/
|
|
1196
|
+
export async function attachVirtualDisplay(browser, virtualDisplay) {
|
|
1197
|
+
if (!virtualDisplay)
|
|
1198
|
+
return browser; // Skip if no virtual display is provided
|
|
1199
|
+
const target = browser;
|
|
1200
|
+
const originalClose = target.close.bind(target);
|
|
1201
|
+
target.close = async (...args) => {
|
|
1202
|
+
try {
|
|
1203
|
+
return await originalClose(...args);
|
|
1204
|
+
}
|
|
1205
|
+
finally {
|
|
1206
|
+
virtualDisplay.kill();
|
|
1207
|
+
}
|
|
1208
|
+
};
|
|
1209
|
+
// close() never runs on an unexpected disconnect/close, so wire teardown
|
|
1210
|
+
// directly too; kill() is idempotent.
|
|
1211
|
+
target.on?.(target.contexts ? "disconnected" : "close", () => virtualDisplay.kill());
|
|
1212
|
+
target._virtualDisplay = virtualDisplay;
|
|
1213
|
+
if (virtualDisplay instanceof GpuDisplay) {
|
|
1214
|
+
try {
|
|
1215
|
+
await proveGpu(target, virtualDisplay);
|
|
1216
|
+
}
|
|
1217
|
+
catch (error) {
|
|
1218
|
+
await target.close();
|
|
1219
|
+
throw error;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
return browser;
|
|
1223
|
+
}
|
|
1224
|
+
function toScreen(screen) {
|
|
1225
|
+
if (screen instanceof Screen)
|
|
1226
|
+
return screen;
|
|
1227
|
+
const s = screen;
|
|
1228
|
+
return new Screen({
|
|
1229
|
+
minWidth: s.minWidth ?? s.min_width,
|
|
1230
|
+
maxWidth: s.maxWidth ?? s.max_width,
|
|
1231
|
+
minHeight: s.minHeight ?? s.min_height,
|
|
1232
|
+
maxHeight: s.maxHeight ?? s.max_height,
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
/** repr() of a list of (vendor, renderer) tuples. */
|
|
1236
|
+
function reprPairs(pairs) {
|
|
1237
|
+
return `[${pairs.map(([v, r]) => `(${pyStrRepr(v)}, ${pyStrRepr(r)})`).join(", ")}]`;
|
|
1238
|
+
}
|
|
1239
|
+
// A preset's fields and the config keys they set; the rest of the identity is
|
|
1240
|
+
// drawn from an fpgen record of a machine with the preset's GPU.
|
|
1241
|
+
const PRESET_KEYS = {
|
|
1242
|
+
navigator: {
|
|
1243
|
+
hardwareConcurrency: "navigator.hardwareConcurrency",
|
|
1244
|
+
maxTouchPoints: "navigator.maxTouchPoints",
|
|
1245
|
+
},
|
|
1246
|
+
screen: {
|
|
1247
|
+
width: "screen.width",
|
|
1248
|
+
height: "screen.height",
|
|
1249
|
+
colorDepth: "screen.colorDepth",
|
|
1250
|
+
availWidth: "screen.availWidth",
|
|
1251
|
+
availHeight: "screen.availHeight",
|
|
1252
|
+
devicePixelRatio: "window.devicePixelRatio",
|
|
1253
|
+
},
|
|
1254
|
+
};
|
|
1255
|
+
/**
|
|
1256
|
+
* The OS, GPU and recorded values of a Camoufox-format preset recorded from
|
|
1257
|
+
* Chrome. Its user agent names only the OS: the version is the binary's.
|
|
1258
|
+
*/
|
|
1259
|
+
export function presetIdentity(preset) {
|
|
1260
|
+
if (!isPlainObject(preset)) {
|
|
1261
|
+
throw new ValueError(`fingerprint_preset must be a dict, not ${pyTypeName(preset)}`);
|
|
1262
|
+
}
|
|
1263
|
+
const userAgent = pyStr(preset.navigator?.userAgent || "");
|
|
1264
|
+
if (!userAgent.includes("Chrome/") || userAgent.includes("Firefox/")) {
|
|
1265
|
+
throw new NonChromeFingerprint(`fingerprint_preset was not recorded from Chrome (its user agent is ${pyRepr(userAgent)}); ` +
|
|
1266
|
+
"a Firefox preset describes a browser Camouwolf is not");
|
|
1267
|
+
}
|
|
1268
|
+
const targetOs = clienthints.uaOs(userAgent);
|
|
1269
|
+
if (targetOs === null) {
|
|
1270
|
+
throw new ValueError(`fingerprint_preset user agent ${pyRepr(userAgent)} names no desktop OS`);
|
|
1271
|
+
}
|
|
1272
|
+
const webgl = preset.webgl || {};
|
|
1273
|
+
if (!(webgl.unmaskedVendor && webgl.unmaskedRenderer)) {
|
|
1274
|
+
throw new ValueError("fingerprint_preset needs webgl.unmaskedVendor and webgl.unmaskedRenderer");
|
|
1275
|
+
}
|
|
1276
|
+
const config = {};
|
|
1277
|
+
for (const [section, fields] of Object.entries(PRESET_KEYS)) {
|
|
1278
|
+
for (const [field, key] of Object.entries(fields)) {
|
|
1279
|
+
const value = preset[section]?.[field];
|
|
1280
|
+
if (value !== undefined && value !== null)
|
|
1281
|
+
config[key] = value;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
if (pyTruthy(preset.timezone))
|
|
1285
|
+
config.timezone = preset.timezone;
|
|
1286
|
+
return {
|
|
1287
|
+
os: OS_NAMES[targetOs],
|
|
1288
|
+
webglConfig: [webgl.unmaskedVendor, webgl.unmaskedRenderer],
|
|
1289
|
+
config,
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
/** The OSes in `os` that have `cpu`; ValueError when none does. */
|
|
1293
|
+
export function osesForCpu(cpu, os) {
|
|
1294
|
+
const names = typeof os === "string" ? [os] : [...os];
|
|
1295
|
+
const fits = [];
|
|
1296
|
+
const errors = [];
|
|
1297
|
+
for (const name of names) {
|
|
1298
|
+
try {
|
|
1299
|
+
coherence.resolveCpu(cpu, OS_KEYS[name] ?? name);
|
|
1300
|
+
fits.push(name);
|
|
1301
|
+
}
|
|
1302
|
+
catch (err) {
|
|
1303
|
+
if (!(err instanceof ValueError))
|
|
1304
|
+
throw err;
|
|
1305
|
+
errors.push(err.message);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
if (!fits.length) {
|
|
1309
|
+
throw new ValueError(`cpu=${pyRepr(cpu)}: ${errors.join("; ")}`);
|
|
1310
|
+
}
|
|
1311
|
+
return typeof os === "string" ? os : fits;
|
|
1312
|
+
}
|
|
1313
|
+
export const SOCKS5_DEFAULT_PORT = 1080;
|
|
1314
|
+
/**
|
|
1315
|
+
* The "host:port" the browser looks a SOCKS5 proxy's credentials up by: the
|
|
1316
|
+
* proxy's canonical host and port, as net::HostPortPair prints them.
|
|
1317
|
+
*/
|
|
1318
|
+
export function socks5ProxyKey(server) {
|
|
1319
|
+
const { url, port } = ProxyHelper.parseServer(server);
|
|
1320
|
+
let host = url.replace(/^\[|\]$/g, "").toLowerCase();
|
|
1321
|
+
// The URL parser writes an IPv6 address in its one canonical form.
|
|
1322
|
+
if (host.includes(":"))
|
|
1323
|
+
host = new URL(`http://[${host}]`).hostname;
|
|
1324
|
+
return `${host}:${port || SOCKS5_DEFAULT_PORT}`;
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* A socks5 proxy without its credentials, for Playwright (which refuses them
|
|
1328
|
+
* for Chromium), and the credentials as proxy:socks5Credentials, which the
|
|
1329
|
+
* browser reads from its config rather than from argv.
|
|
1330
|
+
*/
|
|
1331
|
+
export function splitSocks5Credentials(proxy) {
|
|
1332
|
+
if (!proxy?.username ||
|
|
1333
|
+
ProxyHelper.parseServer(proxy.server).schema !== "socks5") {
|
|
1334
|
+
return [proxy, null];
|
|
1335
|
+
}
|
|
1336
|
+
const username = proxy.username;
|
|
1337
|
+
const password = proxy.password || "";
|
|
1338
|
+
for (const [field, value] of [
|
|
1339
|
+
["username", username],
|
|
1340
|
+
["password", password],
|
|
1341
|
+
]) {
|
|
1342
|
+
const bytes = Buffer.byteLength(value, "utf-8");
|
|
1343
|
+
if (bytes < 1 || bytes > 255) {
|
|
1344
|
+
throw new ValueError(`A SOCKS5 ${field} is 1 to 255 bytes (RFC 1929)`);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
const { username: _u, password: _p, ...stripped } = proxy;
|
|
1348
|
+
return [stripped, { [socks5ProxyKey(proxy.server)]: { username, password } }];
|
|
1349
|
+
}
|
|
1350
|
+
/** The config with proxy credentials masked, for printing. */
|
|
1351
|
+
export function maskedConfig(config) {
|
|
1352
|
+
const credentials = config["proxy:socks5Credentials"];
|
|
1353
|
+
if (!pyTruthy(credentials))
|
|
1354
|
+
return config;
|
|
1355
|
+
return {
|
|
1356
|
+
...config,
|
|
1357
|
+
"proxy:socks5Credentials": Object.fromEntries(Object.entries(credentials).map(([key, entry]) => [
|
|
1358
|
+
key,
|
|
1359
|
+
{ username: entry.username, password: "***" },
|
|
1360
|
+
])),
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
const PEM_CERTIFICATE = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g;
|
|
1364
|
+
/**
|
|
1365
|
+
* Move certificatePaths into certificates: each file's certificates, PEM or
|
|
1366
|
+
* DER, as the base64 DER the browser trusts.
|
|
1367
|
+
*/
|
|
1368
|
+
export function readCertificatePaths(config) {
|
|
1369
|
+
const paths = config.certificatePaths || [];
|
|
1370
|
+
delete config.certificatePaths;
|
|
1371
|
+
const certificates = (config.certificates || []).map((c) => c.replace(PEM_CERTIFICATE, "$1"));
|
|
1372
|
+
for (const file of paths) {
|
|
1373
|
+
const data = fs.readFileSync(file);
|
|
1374
|
+
const bodies = [...data.toString("latin1").matchAll(PEM_CERTIFICATE)].map((m) => m[1]);
|
|
1375
|
+
certificates.push(...(bodies.length ? bodies : [data.toString("base64")]));
|
|
1376
|
+
}
|
|
1377
|
+
if (certificates.length) {
|
|
1378
|
+
config.certificates = certificates.map((c) => c.replace(/\s+/g, ""));
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
export function speaks(language) {
|
|
1382
|
+
const wanted = language.split("-")[0].toLowerCase();
|
|
1383
|
+
return (value) => Array.isArray(value) &&
|
|
1384
|
+
value.length > 0 &&
|
|
1385
|
+
pyStr(value[0]).split("-")[0].toLowerCase() === wanted;
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Draw an fpgen Chrome fingerprint whose GPU the identity may claim.
|
|
1389
|
+
*
|
|
1390
|
+
* Without `webglConfig`, any recorded hardware GPU on a backend its OS uses.
|
|
1391
|
+
* With it, a record of exactly that device: its limits, screen and fonts are
|
|
1392
|
+
* then the ones a machine with that GPU reported.
|
|
1393
|
+
*
|
|
1394
|
+
* With `language`, a record of Chrome in that language where fpgen has one:
|
|
1395
|
+
* a machine's voices and fonts follow the language its OS was installed in.
|
|
1396
|
+
*/
|
|
1397
|
+
export async function drawFingerprint(os, screen, window, webglConfig, language, cpu) {
|
|
1398
|
+
await utilsDeps.ensureModel();
|
|
1399
|
+
const names = typeof os === "string" ? [os] : [...(os ?? [])];
|
|
1400
|
+
let gpu;
|
|
1401
|
+
if (webglConfig?.length) {
|
|
1402
|
+
const [vendor, renderer] = webglConfig;
|
|
1403
|
+
const has = (name) => utilsDeps
|
|
1404
|
+
.chromeGpus(name)
|
|
1405
|
+
.some(([v, r]) => v === vendor && r === renderer);
|
|
1406
|
+
if (!names.some(has)) {
|
|
1407
|
+
const possible = names
|
|
1408
|
+
.flatMap((name) => utilsDeps.chromeGpus(name))
|
|
1409
|
+
.sort((a, b) => comparePyStr(a[0], b[0]) || comparePyStr(a[1], b[1]));
|
|
1410
|
+
throw new ValueError(`No recorded Chrome device with vendor ${pyRepr(vendor)} and renderer ${pyRepr(renderer)} on ` +
|
|
1411
|
+
`${names.join(", ")}. Possible pairs: ${reprPairs(possible)}`);
|
|
1412
|
+
}
|
|
1413
|
+
// fpgen hands a predicate the recorded value lowercased.
|
|
1414
|
+
const wantedVendor = vendor.toLowerCase();
|
|
1415
|
+
const wantedRenderer = renderer.toLowerCase();
|
|
1416
|
+
gpu = (value) => isPlainObject(value) &&
|
|
1417
|
+
pyStr(value.vendor ?? null).toLowerCase() === wantedVendor &&
|
|
1418
|
+
pyStr(value.renderer ?? null).toLowerCase() === wantedRenderer;
|
|
1419
|
+
}
|
|
1420
|
+
else {
|
|
1421
|
+
gpu = (value) => usableGpu(value);
|
|
1422
|
+
}
|
|
1423
|
+
if (cpu !== undefined && cpu !== null) {
|
|
1424
|
+
const claims = names.map((name) => [OS_KEYS[name], coherence.resolveCpu(cpu, OS_KEYS[name])]);
|
|
1425
|
+
if (webglConfig?.length) {
|
|
1426
|
+
const misfits = claims.map(([osKey, claim]) => coherence.cpuMisfit(webglConfig[1], null, osKey, ...claim));
|
|
1427
|
+
if (misfits.every(Boolean)) {
|
|
1428
|
+
throw new ValueError(`cpu=${pyRepr(cpu)}: no machine has ${misfits[0]}`);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
const anyGpu = gpu;
|
|
1432
|
+
gpu = (value) => anyGpu(value) &&
|
|
1433
|
+
claims.some(([osKey, claim]) => !coherence.cpuMisfit(isPlainObject(value) ? value.renderer : null, null, osKey, ...claim));
|
|
1434
|
+
}
|
|
1435
|
+
const conditions = { gpu };
|
|
1436
|
+
if (language)
|
|
1437
|
+
conditions.languages = speaks(language);
|
|
1438
|
+
for (let i = 0; i < MAX_FINGERPRINT_DRAWS; i++) {
|
|
1439
|
+
let fingerprint;
|
|
1440
|
+
try {
|
|
1441
|
+
fingerprint = utilsDeps.generateFingerprint({
|
|
1442
|
+
window,
|
|
1443
|
+
screen,
|
|
1444
|
+
os: pyTruthy(os) ? os : null,
|
|
1445
|
+
...conditions,
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
catch (err) {
|
|
1449
|
+
if (!("languages" in conditions))
|
|
1450
|
+
throw err;
|
|
1451
|
+
// fpgen has no record of Chrome in this language on these machines
|
|
1452
|
+
// (its sampler throws a TypeError on a pairing it never recorded).
|
|
1453
|
+
// The draw is then a machine installed in another language.
|
|
1454
|
+
delete conditions.languages;
|
|
1455
|
+
continue;
|
|
1456
|
+
}
|
|
1457
|
+
const drawnOs = fingerprintOs(fingerprint);
|
|
1458
|
+
// Camouwolf builds are x86-64 desktops. fpgen also records Chrome on ARM
|
|
1459
|
+
// Linux ("Linux armv81", "Linux aarch64"), whose platform a build that
|
|
1460
|
+
// computes as x86-64 cannot back up.
|
|
1461
|
+
const navigator = pyTruthy(fingerprint.navigator)
|
|
1462
|
+
? fingerprint.navigator
|
|
1463
|
+
: {};
|
|
1464
|
+
const platform = navigator.platform ?? null;
|
|
1465
|
+
const expected = drawnOs ? clienthints.NAV_PLATFORM[drawnOs] : null;
|
|
1466
|
+
if (platform !== expected)
|
|
1467
|
+
continue;
|
|
1468
|
+
if (!usableGpu(fingerprint.gpu, drawnOs))
|
|
1469
|
+
continue;
|
|
1470
|
+
if (!readoutNames(fingerprint, fingerprint.gpu.renderer))
|
|
1471
|
+
continue;
|
|
1472
|
+
const drawnScreen = pyTruthy(fingerprint.screen) ? fingerprint.screen : {};
|
|
1473
|
+
if (coherence.machineMisfit(fingerprint.gpu.renderer, drawnOs ?? "", navigator.hardwareConcurrency, drawnScreen.width, drawnScreen.height))
|
|
1474
|
+
continue;
|
|
1475
|
+
if (cpu !== undefined &&
|
|
1476
|
+
cpu !== null &&
|
|
1477
|
+
coherence.cpuMisfit(fingerprint.gpu.renderer, navigator.hardwareConcurrency, drawnOs ?? "", ...coherence.resolveCpu(cpu, drawnOs)))
|
|
1478
|
+
continue;
|
|
1479
|
+
return fingerprint;
|
|
1480
|
+
}
|
|
1481
|
+
throw new Error(`fpgen drew no desktop Chrome fingerprint with a usable GPU for os=${pyRepr(os ?? null)} in ` +
|
|
1482
|
+
`${MAX_FINGERPRINT_DRAWS} draws`);
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* The keys a context's identity takes from the launch's. The window is one
|
|
1486
|
+
* window and its pixel ratio the display's, whichever context draws in it.
|
|
1487
|
+
*/
|
|
1488
|
+
function isLaunchGeometry(key) {
|
|
1489
|
+
return key.startsWith("screen.") || key.startsWith("window.");
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* A whole identity, drawn into `config`: its language list and its OS.
|
|
1493
|
+
*
|
|
1494
|
+
* `config` holds the caller's keys, which win over drawn ones. With `launch`
|
|
1495
|
+
* (the browser's own config) it is a context's identity: the screen, window
|
|
1496
|
+
* and core count are the launch's, which one browser process cannot vary.
|
|
1497
|
+
*/
|
|
1498
|
+
export async function drawIdentity(config, { os: osOption, webgl_config, geoip, geoip_db, proxy, block_webrtc, locale, fingerprint, screen, window, fonts, custom_fonts_only, canvas_noise, pin_cpu_cores, fullVersion, allow_os_mismatch, i_know_what_im_doing, browserBinary, displayBound = null, virtualDisplay = false, launch, cpu, recorded, }) {
|
|
1499
|
+
const callerKeys = new Set(Object.keys(config));
|
|
1500
|
+
let userSetScreenWindow = isDomainSet(config, "screen.", "window.");
|
|
1501
|
+
const milestone = Number.parseInt(fullVersion.split(".", 1)[0], 10);
|
|
1502
|
+
// ---- place: geoip, locale ---------------------------------------------
|
|
1503
|
+
let localeConfig = {};
|
|
1504
|
+
if (pyTruthy(geoip)) {
|
|
1505
|
+
utilsDeps.geoipAllowed(); // Assert that geoip is allowed
|
|
1506
|
+
let ip = geoip;
|
|
1507
|
+
if (ip === true) {
|
|
1508
|
+
ip = await utilsDeps.publicIp(proxy ? ProxyHelper.asString(proxy) : undefined);
|
|
1509
|
+
}
|
|
1510
|
+
const geoConfig = (await utilsDeps.getGeolocation(ip, geoip_db)).asConfig();
|
|
1511
|
+
for (const [key, value] of Object.entries(geoConfig)) {
|
|
1512
|
+
if (key.startsWith("locale:"))
|
|
1513
|
+
localeConfig[key] = value;
|
|
1514
|
+
else if (key === "timezone")
|
|
1515
|
+
setDefault(config, key, value);
|
|
1516
|
+
else
|
|
1517
|
+
config[key] = value;
|
|
1518
|
+
}
|
|
1519
|
+
// Without a proxy, a site that has an IPv6 address sees this host's,
|
|
1520
|
+
// not the IPv4 address the identity was drawn from. Keep IPv6 only when
|
|
1521
|
+
// it places the host where the identity does.
|
|
1522
|
+
if (!launch &&
|
|
1523
|
+
!proxy &&
|
|
1524
|
+
validIPv4(ip) &&
|
|
1525
|
+
!(await keepsIpv6(geoConfig, geoip_db, i_know_what_im_doing)))
|
|
1526
|
+
config["network:ipv4Only"] = true;
|
|
1527
|
+
// Behind a proxy, WebRTC sees the network of a machine at the exit
|
|
1528
|
+
// (patch 0031): its one adapter has the exit's address.
|
|
1529
|
+
if (pyTruthy(proxy) && !block_webrtc)
|
|
1530
|
+
setDefault(config, validIPv4(ip) ? "webrtc:ipv4" : "webrtc:ipv6", ip);
|
|
1531
|
+
}
|
|
1532
|
+
else if (pyTruthy(proxy) &&
|
|
1533
|
+
!String(proxy?.server ?? "").includes("localhost") &&
|
|
1534
|
+
!String(proxy?.server ?? "").includes("127.0.0.1") &&
|
|
1535
|
+
!isDomainSet(config, "geolocation:")) {
|
|
1536
|
+
// This is a very bad idea; the warning cannot be silenced.
|
|
1537
|
+
LeakWarning.warn(loadWarnings().proxy_without_geoip);
|
|
1538
|
+
}
|
|
1539
|
+
if (pyTruthy(locale)) {
|
|
1540
|
+
localeConfig = {};
|
|
1541
|
+
await handleLocales(locale, localeConfig);
|
|
1542
|
+
}
|
|
1543
|
+
// Chrome serves navigator.languages and Accept-Language from one pref, which
|
|
1544
|
+
// --accept-lang sets, so the config does not repeat it: an off-the-record
|
|
1545
|
+
// context swaps the pref's list, and a pinned copy would then disagree.
|
|
1546
|
+
const languages = pyTruthy(config["navigator.languages"])
|
|
1547
|
+
? config["navigator.languages"]
|
|
1548
|
+
: languagesFor(localeConfig);
|
|
1549
|
+
if (launch) {
|
|
1550
|
+
// The window, and so the screen it sits on, is the browser's: a
|
|
1551
|
+
// context's machine is drawn with the launch's screen.
|
|
1552
|
+
const width = launch["screen.width"];
|
|
1553
|
+
const height = launch["screen.height"];
|
|
1554
|
+
screen = new Screen({
|
|
1555
|
+
minWidth: width,
|
|
1556
|
+
maxWidth: width,
|
|
1557
|
+
minHeight: height,
|
|
1558
|
+
maxHeight: height,
|
|
1559
|
+
});
|
|
1560
|
+
window = undefined;
|
|
1561
|
+
}
|
|
1562
|
+
// A caller who names the user agent themselves has pinned the identity.
|
|
1563
|
+
if ((fingerprint === undefined || fingerprint === null) &&
|
|
1564
|
+
!("navigator.userAgent" in config)) {
|
|
1565
|
+
fingerprint = await drawFingerprint(osOption, screen ?? displayBound, window, webgl_config, languages?.[0], cpu);
|
|
1566
|
+
}
|
|
1567
|
+
else if (fingerprint !== undefined && fingerprint !== null) {
|
|
1568
|
+
if (pyTruthy(webgl_config)) {
|
|
1569
|
+
throw new ValueError("webgl_config draws the fingerprint; it cannot be combined with `fingerprint`");
|
|
1570
|
+
}
|
|
1571
|
+
if (!i_know_what_im_doing)
|
|
1572
|
+
checkCustomFingerprint(fingerprint);
|
|
1573
|
+
if (pyTruthy(window)) {
|
|
1574
|
+
fingerprint = {
|
|
1575
|
+
...fingerprint,
|
|
1576
|
+
screen: {
|
|
1577
|
+
...(pyTruthy(fingerprint.screen) ? fingerprint.screen : {}),
|
|
1578
|
+
},
|
|
1579
|
+
window: {
|
|
1580
|
+
...(pyTruthy(fingerprint.window) ? fingerprint.window : {}),
|
|
1581
|
+
},
|
|
1582
|
+
};
|
|
1583
|
+
const [width, height] = window;
|
|
1584
|
+
handleWindowSize(fingerprint, width, height);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
else if (pyTruthy(webgl_config)) {
|
|
1588
|
+
throw new ValueError("webgl_config draws the fingerprint; it cannot be combined with a user agent in `config`");
|
|
1589
|
+
}
|
|
1590
|
+
if (fingerprint !== undefined && fingerprint !== null) {
|
|
1591
|
+
mergeInto(config, fromFpgen(fingerprint, milestone, buildProduct(browserBinary) === "chrome"));
|
|
1592
|
+
}
|
|
1593
|
+
if (recorded) {
|
|
1594
|
+
const kept = Object.fromEntries(Object.entries(recorded).filter(([k]) => !callerKeys.has(k)));
|
|
1595
|
+
Object.assign(config, kept);
|
|
1596
|
+
for (const key of Object.keys(kept)) {
|
|
1597
|
+
if (key !== "navigator.hardwareConcurrency")
|
|
1598
|
+
callerKeys.add(key);
|
|
1599
|
+
}
|
|
1600
|
+
userSetScreenWindow ||= isDomainSet(kept, "screen.", "window.");
|
|
1601
|
+
}
|
|
1602
|
+
// Patch 0012 shows the host's voices only when the key is absent, so it is
|
|
1603
|
+
// always sent: the recorded list, or none, never the host's.
|
|
1604
|
+
if (!("voices" in config))
|
|
1605
|
+
config.voices = [];
|
|
1606
|
+
const targetOs = getTargetOs(config);
|
|
1607
|
+
checkOsPolicy([OS_NAMES[targetOs]], allow_os_mismatch);
|
|
1608
|
+
setDefault(config, "navigator.userAgent", clienthints.buildUserAgent({ milestone, fullVersion, os: targetOs }));
|
|
1609
|
+
setDefault(config, "navigator.platform", clienthints.NAV_PLATFORM[targetOs]);
|
|
1610
|
+
const cpuClaim = cpu !== undefined && cpu !== null
|
|
1611
|
+
? coherence.resolveCpu(cpu, targetOs)
|
|
1612
|
+
: null;
|
|
1613
|
+
if (cpuClaim)
|
|
1614
|
+
setDefault(config, "userAgentData.architecture", cpuClaim[0]);
|
|
1615
|
+
clienthints.fillClientHints(config, targetOs, fullVersion);
|
|
1616
|
+
// The core count a page can measure is the host's, unless the browser is
|
|
1617
|
+
// pinned to the drawn one.
|
|
1618
|
+
if (launch) {
|
|
1619
|
+
// Measurable parallelism is the process's, pinned or not.
|
|
1620
|
+
config["navigator.hardwareConcurrency"] =
|
|
1621
|
+
launch["navigator.hardwareConcurrency"];
|
|
1622
|
+
}
|
|
1623
|
+
else if (!callerKeys.has("navigator.hardwareConcurrency")) {
|
|
1624
|
+
fixHardwareConcurrency(config, Boolean(pin_cpu_cores), utilsDeps.hostCpu());
|
|
1625
|
+
}
|
|
1626
|
+
if (cpuClaim) {
|
|
1627
|
+
const misfit = coherence.cpuMisfit(config["webGl:renderer"], config["navigator.hardwareConcurrency"], targetOs, ...cpuClaim);
|
|
1628
|
+
if (misfit) {
|
|
1629
|
+
throw new ValueError(`cpu=${pyRepr(cpu)}: no machine has ${misfit}`);
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
// ---- fonts -------------------------------------------------------------
|
|
1633
|
+
if (custom_fonts_only) {
|
|
1634
|
+
if (!pyTruthy(fonts)) {
|
|
1635
|
+
throw new ValueError("custom_fonts_only=True needs `fonts`");
|
|
1636
|
+
}
|
|
1637
|
+
LeakWarning.warn(loadWarnings().custom_fonts_only, i_know_what_im_doing);
|
|
1638
|
+
config.fonts = [...new Set(fonts)];
|
|
1639
|
+
}
|
|
1640
|
+
else if (pyTruthy(fonts)) {
|
|
1641
|
+
const base = pyTruthy(config.fonts)
|
|
1642
|
+
? config.fonts
|
|
1643
|
+
: ESSENTIAL_FONTS[targetOs];
|
|
1644
|
+
config.fonts = [...new Set([...base, ...fonts])];
|
|
1645
|
+
}
|
|
1646
|
+
// ---- devices, keyboard, colours ---------------------------------------
|
|
1647
|
+
setDefault(config, "mediaDevices:enumerated", [
|
|
1648
|
+
...DEFAULT_MEDIA_DEVICES[targetOs],
|
|
1649
|
+
]);
|
|
1650
|
+
// A desktop on mains power, as Chrome reports one with no battery. A frozen
|
|
1651
|
+
// discharging level would be the tell; a caller can still claim one.
|
|
1652
|
+
setDefault(config, "battery:charging", true);
|
|
1653
|
+
setDefault(config, "battery:level", 1);
|
|
1654
|
+
const layout = keyboardLayoutMap(targetOs);
|
|
1655
|
+
if (layout)
|
|
1656
|
+
setDefault(config, "keyboard.layoutMap", layout);
|
|
1657
|
+
const colors = SYSTEM_COLORS[OS_NAMES[targetOs]];
|
|
1658
|
+
if (pyTruthy(colors))
|
|
1659
|
+
setDefault(config, "systemColors", { ...colors });
|
|
1660
|
+
// ---- canvas ------------------------------------------------------------
|
|
1661
|
+
if (canvas_noise) {
|
|
1662
|
+
LeakWarning.warn(loadWarnings().canvas_noise, i_know_what_im_doing);
|
|
1663
|
+
if (!("canvas:seed" in config))
|
|
1664
|
+
config["canvas:seed"] = utilsDeps.canvasSeed();
|
|
1665
|
+
setDefault(config, "canvas:randomizeReadback", true);
|
|
1666
|
+
}
|
|
1667
|
+
else {
|
|
1668
|
+
// Stock Chrome returns the pixels it drew.
|
|
1669
|
+
setDefault(config, "canvas:seed", 0);
|
|
1670
|
+
setDefault(config, "canvas:randomizeReadback", false);
|
|
1671
|
+
}
|
|
1672
|
+
setDefault(config, "canvas:quantizeTextMetrics", false);
|
|
1673
|
+
setDefault(config, "AudioContext:randomizeSamples", false);
|
|
1674
|
+
// ---- geometry ----------------------------------------------------------
|
|
1675
|
+
if (launch) {
|
|
1676
|
+
for (const key of Object.keys(config)) {
|
|
1677
|
+
if (isLaunchGeometry(key))
|
|
1678
|
+
delete config[key];
|
|
1679
|
+
}
|
|
1680
|
+
for (const [key, value] of Object.entries(launch)) {
|
|
1681
|
+
if (isLaunchGeometry(key))
|
|
1682
|
+
config[key] = value;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
else if (!userSetScreenWindow) {
|
|
1686
|
+
coherence.repairDevicePixelRatio(config, targetOs, window ? ["window.outerWidth", "window.outerHeight"] : []);
|
|
1687
|
+
raiseScreenToModernFloor(config);
|
|
1688
|
+
coherence.repairScreenOrientation(config);
|
|
1689
|
+
if (displayBound !== null) {
|
|
1690
|
+
// A virtual display is measured in device pixels, and the window
|
|
1691
|
+
// renders at the identity's ratio.
|
|
1692
|
+
const scale = virtualDisplay
|
|
1693
|
+
? num(config["window.devicePixelRatio"] || 1)
|
|
1694
|
+
: 1;
|
|
1695
|
+
clampScreenToDisplay(config, Math.trunc(num(displayBound.maxWidth) / scale), Math.trunc(num(displayBound.maxHeight) / scale));
|
|
1696
|
+
}
|
|
1697
|
+
fixScreenNoTaskbar(config, targetOs);
|
|
1698
|
+
clampWindowDimensions(config);
|
|
1699
|
+
clampWindowPosition(config);
|
|
1700
|
+
snapWindowToDevicePixels(config);
|
|
1701
|
+
}
|
|
1702
|
+
// ---- coherence ---------------------------------------------------------
|
|
1703
|
+
const kept = new Set(callerKeys);
|
|
1704
|
+
if (launch) {
|
|
1705
|
+
for (const key of Object.keys(config)) {
|
|
1706
|
+
if (isLaunchGeometry(key))
|
|
1707
|
+
kept.add(key);
|
|
1708
|
+
}
|
|
1709
|
+
kept.add("navigator.hardwareConcurrency");
|
|
1710
|
+
}
|
|
1711
|
+
const violations = coherence.apply(config, targetOs, kept);
|
|
1712
|
+
warnKeptIncoherent(violations);
|
|
1713
|
+
const fatal = violations.filter((v) => coherence.FATAL_RULES.has(v.rule));
|
|
1714
|
+
if (fatal.length && !i_know_what_im_doing) {
|
|
1715
|
+
throw new IncoherentIdentity("Camouwolf refuses to launch an identity that contradicts itself:\n - " +
|
|
1716
|
+
fatal.map((v) => v.detail).join("\n - ") +
|
|
1717
|
+
"\nFix `config`, or pass i_know_what_im_doing=True to launch anyway.");
|
|
1718
|
+
}
|
|
1719
|
+
validateConfig(config, browserBinary);
|
|
1720
|
+
return { languages, targetOs };
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Builds the Playwright launch options for a Camouwolf browser. Accepts all
|
|
1724
|
+
* Playwright Chromium launch options, along with those of LaunchOptions. An
|
|
1725
|
+
* option left unset takes its value from camouwolf.defaults.json and the
|
|
1726
|
+
* user's own defaults file (`camouwolf defaults`).
|
|
1727
|
+
*/
|
|
1728
|
+
export async function launchOptions(options = {}) {
|
|
1729
|
+
return buildLaunchOptions(launchDefaults(options));
|
|
1730
|
+
}
|
|
1731
|
+
async function buildLaunchOptions({ config, os, block_images, block_webrtc, block_webgl, disable_coop, instant_animations, show_cursor, webgl_config, cpu, geoip, geoip_db, humanize, locale, addons, fonts, custom_fonts_only, exclude_addons, screen, window, fingerprint, fingerprint_preset, chrome_version, ff_version, headless, main_world_eval: _main_world_eval, allow_addon_new_tab, executable_path, browser, chromium_prefs, firefox_user_prefs, proxy, enable_cache, args, env, i_know_what_im_doing, debug, virtual_display, virtual_display_size, pin_cpu_cores, canvas_noise, allow_os_mismatch, passthrough, telemetry: _telemetry, ...playwrightOptions }) {
|
|
1732
|
+
if (passthrough) {
|
|
1733
|
+
checkPassthrough(PRODUCT, {
|
|
1734
|
+
config,
|
|
1735
|
+
os,
|
|
1736
|
+
fingerprint,
|
|
1737
|
+
fingerprint_preset,
|
|
1738
|
+
webgl_config,
|
|
1739
|
+
cpu,
|
|
1740
|
+
screen,
|
|
1741
|
+
window,
|
|
1742
|
+
fonts,
|
|
1743
|
+
custom_fonts_only,
|
|
1744
|
+
locale,
|
|
1745
|
+
geoip,
|
|
1746
|
+
canvas_noise,
|
|
1747
|
+
pin_cpu_cores,
|
|
1748
|
+
allow_os_mismatch,
|
|
1749
|
+
ff_version,
|
|
1750
|
+
chrome_version,
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
// ---- options with no Chromium equivalent ------------------------------
|
|
1754
|
+
if (pyTruthy(firefox_user_prefs)) {
|
|
1755
|
+
throw new NotImplementedError("firefox_user_prefs has no Chromium equivalent. Pass command-line switches in `args`, or " +
|
|
1756
|
+
"Chromium preferences in `chromium_prefs` together with persistent_context=True and a user_data_dir.");
|
|
1757
|
+
}
|
|
1758
|
+
if (ff_version !== undefined && ff_version !== null) {
|
|
1759
|
+
throw new NotImplementedError("ff_version is Camoufox's option. Use chrome_version (a Chromium milestone).");
|
|
1760
|
+
}
|
|
1761
|
+
if (fingerprint_preset === true) {
|
|
1762
|
+
throw new ValueError("fingerprint_preset=True picks a bundled preset, and Camouwolf bundles none: Camoufox's " +
|
|
1763
|
+
"presets are recorded from Firefox. Pass a preset recorded from Chrome as a dict, or leave " +
|
|
1764
|
+
"it unset to draw an fpgen fingerprint.");
|
|
1765
|
+
}
|
|
1766
|
+
const preset = pyTruthy(fingerprint_preset)
|
|
1767
|
+
? presetIdentity(fingerprint_preset)
|
|
1768
|
+
: null;
|
|
1769
|
+
// main_world_eval: nothing to switch on. Playwright evaluates in the page's
|
|
1770
|
+
// main world on Chromium.
|
|
1771
|
+
// The launch fills these in, so it works on copies: a caller's object
|
|
1772
|
+
// reused for a second launch would otherwise carry the first identity's
|
|
1773
|
+
// values in, as if the caller had set them.
|
|
1774
|
+
config = { ...config };
|
|
1775
|
+
addons = [...(addons ?? [])];
|
|
1776
|
+
args = [...(args ?? [])];
|
|
1777
|
+
const [browserProxy, socks5Credentials] = splitSocks5Credentials(proxy);
|
|
1778
|
+
readCertificatePaths(config);
|
|
1779
|
+
headless ??= false;
|
|
1780
|
+
i_know_what_im_doing ??= false;
|
|
1781
|
+
normalize(humanize);
|
|
1782
|
+
// Keep per-launch overrides isolated from the process environment and from
|
|
1783
|
+
// mappings supplied by callers. In particular, DISPLAY must not outlive the
|
|
1784
|
+
// virtual display that owns it.
|
|
1785
|
+
const environ = utilsDeps.environ();
|
|
1786
|
+
env = env == null ? { ...environ } : { ...env };
|
|
1787
|
+
utilsDeps.ensureBrowserProfileDir(env);
|
|
1788
|
+
// ---- the binary --------------------------------------------------------
|
|
1789
|
+
// CAMOUWOLF_EXECUTABLE_PATH points every launch at a specific build without
|
|
1790
|
+
// threading the path through each call site.
|
|
1791
|
+
const envExecutable = (environ.CAMOUWOLF_EXECUTABLE_PATH ?? "").trim();
|
|
1792
|
+
if (browser) {
|
|
1793
|
+
if (executable_path || envExecutable) {
|
|
1794
|
+
throw new ValueError(`browser=${pyRepr(browser)} selects an installed build, but ` +
|
|
1795
|
+
`${executable_path ? "executable_path" : "CAMOUWOLF_EXECUTABLE_PATH"} ` +
|
|
1796
|
+
"names a binary too. Pass one of them.");
|
|
1797
|
+
}
|
|
1798
|
+
executable_path = utilsDeps.selectedLaunchPath(browser);
|
|
1799
|
+
}
|
|
1800
|
+
else if (executable_path == null && envExecutable) {
|
|
1801
|
+
executable_path = envExecutable;
|
|
1802
|
+
}
|
|
1803
|
+
let browserBinary;
|
|
1804
|
+
if (executable_path != null) {
|
|
1805
|
+
browserBinary = path.resolve(String(executable_path));
|
|
1806
|
+
}
|
|
1807
|
+
else {
|
|
1808
|
+
// Python's launch_path() downloads the browser when none is installed;
|
|
1809
|
+
// here that download is async, so it is awaited first.
|
|
1810
|
+
await utilsDeps.ensureCamouwolfInstalled();
|
|
1811
|
+
browserBinary = utilsDeps.launchPath();
|
|
1812
|
+
}
|
|
1813
|
+
utilsDeps.warnIfPackageOutdated();
|
|
1814
|
+
// ---- display -----------------------------------------------------------
|
|
1815
|
+
const ownedDisplay = virtual_display instanceof VirtualDisplay ? virtual_display : null;
|
|
1816
|
+
let displaySize = virtual_display_size;
|
|
1817
|
+
if (ownedDisplay?.fixed)
|
|
1818
|
+
displaySize = ownedDisplay.size;
|
|
1819
|
+
if (virtual_display) {
|
|
1820
|
+
if (!ownedDisplay)
|
|
1821
|
+
env.DISPLAY = virtual_display;
|
|
1822
|
+
// The virtual display is X11. A host session that exports
|
|
1823
|
+
// WAYLAND_DISPLAY would otherwise send the window to the real desktop.
|
|
1824
|
+
env.GDK_BACKEND = "x11";
|
|
1825
|
+
delete env.WAYLAND_DISPLAY;
|
|
1826
|
+
args.unshift("--ozone-platform=x11");
|
|
1827
|
+
}
|
|
1828
|
+
// ---- the identity ------------------------------------------------------
|
|
1829
|
+
let languages;
|
|
1830
|
+
let targetOs;
|
|
1831
|
+
if (passthrough) {
|
|
1832
|
+
// The host's own device: no identity, so nothing to place, size or name.
|
|
1833
|
+
warnPassthrough(PRODUCT, proxy, i_know_what_im_doing);
|
|
1834
|
+
targetOs = utilsDeps.osName();
|
|
1835
|
+
}
|
|
1836
|
+
else {
|
|
1837
|
+
if (!i_know_what_im_doing)
|
|
1838
|
+
warnManualConfig(config);
|
|
1839
|
+
let osOption = os;
|
|
1840
|
+
if (preset) {
|
|
1841
|
+
if (pyTruthy(os) ||
|
|
1842
|
+
pyTruthy(webgl_config) ||
|
|
1843
|
+
(fingerprint !== undefined && fingerprint !== null)) {
|
|
1844
|
+
throw new ValueError("fingerprint_preset names the OS and GPU; it cannot be combined with os, " +
|
|
1845
|
+
"webgl_config or fingerprint");
|
|
1846
|
+
}
|
|
1847
|
+
osOption = preset.os;
|
|
1848
|
+
webgl_config = preset.webglConfig;
|
|
1849
|
+
}
|
|
1850
|
+
if (cpu !== undefined && cpu !== null) {
|
|
1851
|
+
osOption = osesForCpu(cpu, pyTruthy(osOption)
|
|
1852
|
+
? osOption
|
|
1853
|
+
: [...ALLOWED_OS_TARGETS[utilsDeps.osName()]]);
|
|
1854
|
+
}
|
|
1855
|
+
if (pyTruthy(osOption)) {
|
|
1856
|
+
checkValidOs(osOption);
|
|
1857
|
+
checkOsPolicy(typeof osOption === "string" ? [osOption] : [...osOption], allow_os_mismatch);
|
|
1858
|
+
}
|
|
1859
|
+
else if (pyTruthy(webgl_config)) {
|
|
1860
|
+
throw new ValueError("OS must be set when using webgl_config");
|
|
1861
|
+
}
|
|
1862
|
+
else if (!allow_os_mismatch) {
|
|
1863
|
+
osOption = [...ALLOWED_OS_TARGETS[utilsDeps.osName()]];
|
|
1864
|
+
}
|
|
1865
|
+
// The identity has to match the Chromium that actually runs.
|
|
1866
|
+
let fullVersion = resolveVersion(browserBinary);
|
|
1867
|
+
const ownMilestone = Number.parseInt(fullVersion.split(".", 1)[0], 10);
|
|
1868
|
+
if (chrome_version !== undefined &&
|
|
1869
|
+
chrome_version !== null &&
|
|
1870
|
+
Math.trunc(Number(chrome_version)) !== ownMilestone) {
|
|
1871
|
+
LeakWarning.warn(loadWarnings().chrome_version, i_know_what_im_doing);
|
|
1872
|
+
fullVersion = `${Math.trunc(Number(chrome_version))}.0.0.0`;
|
|
1873
|
+
}
|
|
1874
|
+
// A real display bounds the screen the identity may claim; so does a
|
|
1875
|
+
// virtual one of fixed size, which the real window has to fit on. One the
|
|
1876
|
+
// launcher sizes is fitted to the identity instead.
|
|
1877
|
+
let displayBound = null;
|
|
1878
|
+
if (headless !== true) {
|
|
1879
|
+
if (pyTruthy(displaySize)) {
|
|
1880
|
+
const [width, height] = displaySize;
|
|
1881
|
+
displayBound = new Screen({ maxWidth: width, maxHeight: height });
|
|
1882
|
+
}
|
|
1883
|
+
else if (!virtual_display && utilsDeps.hasDisplay(env)) {
|
|
1884
|
+
const display = utilsDeps.largestDisplay();
|
|
1885
|
+
if (display) {
|
|
1886
|
+
displayBound = new Screen({
|
|
1887
|
+
maxWidth: display.width,
|
|
1888
|
+
maxHeight: display.height,
|
|
1889
|
+
});
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
({ languages, targetOs } = await drawIdentity(config, {
|
|
1894
|
+
os: osOption,
|
|
1895
|
+
webgl_config,
|
|
1896
|
+
geoip,
|
|
1897
|
+
geoip_db,
|
|
1898
|
+
proxy,
|
|
1899
|
+
block_webrtc,
|
|
1900
|
+
locale,
|
|
1901
|
+
fingerprint,
|
|
1902
|
+
screen: screen ? toScreen(screen) : null,
|
|
1903
|
+
window,
|
|
1904
|
+
fonts,
|
|
1905
|
+
custom_fonts_only,
|
|
1906
|
+
canvas_noise,
|
|
1907
|
+
pin_cpu_cores,
|
|
1908
|
+
fullVersion,
|
|
1909
|
+
allow_os_mismatch,
|
|
1910
|
+
i_know_what_im_doing,
|
|
1911
|
+
browserBinary,
|
|
1912
|
+
displayBound,
|
|
1913
|
+
virtualDisplay: Boolean(virtual_display),
|
|
1914
|
+
cpu,
|
|
1915
|
+
recorded: preset?.config,
|
|
1916
|
+
}));
|
|
1917
|
+
}
|
|
1918
|
+
// ---- browser behaviour ------------------------------------------------
|
|
1919
|
+
setDefault(config, "allowAddonNewtab", Boolean(allow_addon_new_tab));
|
|
1920
|
+
if (instant_animations) {
|
|
1921
|
+
LeakWarning.warn(loadWarnings().instant_animations, i_know_what_im_doing);
|
|
1922
|
+
config.instantAnimations = true;
|
|
1923
|
+
}
|
|
1924
|
+
if (show_cursor)
|
|
1925
|
+
config.showcursor = true;
|
|
1926
|
+
if (socks5Credentials)
|
|
1927
|
+
config["proxy:socks5Credentials"] = socks5Credentials;
|
|
1928
|
+
// ---- switches ----------------------------------------------------------
|
|
1929
|
+
if (block_images) {
|
|
1930
|
+
LeakWarning.warn(loadWarnings().block_images, i_know_what_im_doing);
|
|
1931
|
+
args.push("--blink-settings=imagesEnabled=false");
|
|
1932
|
+
}
|
|
1933
|
+
// A proxied context's WebRTC already leaves through the proxy (patch 0031);
|
|
1934
|
+
// this keeps it to TCP through the proxy, with no UDP at all.
|
|
1935
|
+
if (block_webrtc) {
|
|
1936
|
+
args.push(WEBRTC_BLOCK_SWITCH);
|
|
1937
|
+
}
|
|
1938
|
+
if (block_webgl) {
|
|
1939
|
+
LeakWarning.warn(loadWarnings().block_webgl, i_know_what_im_doing);
|
|
1940
|
+
args.push("--disable-webgl", "--disable-webgl2");
|
|
1941
|
+
}
|
|
1942
|
+
if (!enable_cache)
|
|
1943
|
+
args.push("--disk-cache-size=1");
|
|
1944
|
+
utilsDeps.addDefaultAddons(addons, exclude_addons);
|
|
1945
|
+
if (addons.length) {
|
|
1946
|
+
utilsDeps.confirmPaths(addons);
|
|
1947
|
+
args.push(`--load-extension=${addons.map((p) => path.resolve(p)).join(",")}`);
|
|
1948
|
+
}
|
|
1949
|
+
// A repeated --disable-features replaces Playwright's own list (Chromium
|
|
1950
|
+
// reads the last one), so that list is restated with the launcher's.
|
|
1951
|
+
const disabled = [
|
|
1952
|
+
...PLAYWRIGHT_DISABLED_FEATURES,
|
|
1953
|
+
...LAUNCHER_DISABLED_FEATURES,
|
|
1954
|
+
];
|
|
1955
|
+
if (disable_coop) {
|
|
1956
|
+
LeakWarning.warn(loadWarnings().disable_coop, i_know_what_im_doing);
|
|
1957
|
+
disabled.push("CrossOriginOpenerPolicy");
|
|
1958
|
+
}
|
|
1959
|
+
if (debug)
|
|
1960
|
+
args.push("--enable-logging=stderr");
|
|
1961
|
+
// Chrome 137+ ignores --load-extension unless this feature is off.
|
|
1962
|
+
if (addons.length)
|
|
1963
|
+
disabled.push("DisableLoadExtensionCommandLineSwitch");
|
|
1964
|
+
args.push(`--disable-features=${disabled.join(",")}`);
|
|
1965
|
+
const audit = auditSwitches(args, !i_know_what_im_doing);
|
|
1966
|
+
let launchArgs = audit.args;
|
|
1967
|
+
if (debug) {
|
|
1968
|
+
for (const [arg, reason] of audit.dropped) {
|
|
1969
|
+
utilsDeps.print(`[camouwolf] dropped ${arg}: ${reason}`);
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
// The switches the audit refuses from a caller are the ones the launcher
|
|
1973
|
+
// derives from the identity, so the window, the UI language and the
|
|
1974
|
+
// Accept-Language header cannot disagree with it.
|
|
1975
|
+
// Chrome rounds the window through device pixels, so the switches carry the
|
|
1976
|
+
// input it reads back as the claimed window.
|
|
1977
|
+
const dpr = num(config["window.devicePixelRatio"] || 1);
|
|
1978
|
+
const outerWidth = config["window.outerWidth"];
|
|
1979
|
+
const outerHeight = config["window.outerHeight"];
|
|
1980
|
+
const screenX = config["window.screenX"];
|
|
1981
|
+
const screenY = config["window.screenY"];
|
|
1982
|
+
const hasPosition = screenX !== null &&
|
|
1983
|
+
screenX !== undefined &&
|
|
1984
|
+
screenY !== null &&
|
|
1985
|
+
screenY !== undefined;
|
|
1986
|
+
if (pyTruthy(outerWidth) && pyTruthy(outerHeight)) {
|
|
1987
|
+
const [x, width] = windowSwitchBounds(Math.trunc(num(screenX || 0)), Math.trunc(num(outerWidth)), dpr);
|
|
1988
|
+
const [y, height] = windowSwitchBounds(Math.trunc(num(screenY || 0)), Math.trunc(num(outerHeight)), dpr);
|
|
1989
|
+
launchArgs.push(`--window-size=${width},${height}`);
|
|
1990
|
+
if (hasPosition)
|
|
1991
|
+
launchArgs.push(`--window-position=${x},${y}`);
|
|
1992
|
+
}
|
|
1993
|
+
else if (hasPosition) {
|
|
1994
|
+
launchArgs.push(`--window-position=${Math.trunc(num(screenX))},${Math.trunc(num(screenY))}`);
|
|
1995
|
+
}
|
|
1996
|
+
if (languages && pyTruthy(languages)) {
|
|
1997
|
+
launchArgs.push(`--lang=${languages[0]}`);
|
|
1998
|
+
launchArgs.push(`--accept-lang=${languages.join(",")}`);
|
|
1999
|
+
if (utilsDeps.osName() === "lin") {
|
|
2000
|
+
// Chromium on Linux takes its UI locale from the environment.
|
|
2001
|
+
env.LANGUAGE = languages[0].replaceAll("-", "_");
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
launchArgs = mergeListSwitches(launchArgs);
|
|
2005
|
+
// ---- chromium_prefs ----------------------------------------------------
|
|
2006
|
+
if (pyTruthy(chromium_prefs)) {
|
|
2007
|
+
const userDataDir = playwrightOptions.user_data_dir ?? playwrightOptions.userDataDir;
|
|
2008
|
+
if (!userDataDir) {
|
|
2009
|
+
throw new ValueError("chromium_prefs are written to the profile, so they need a persistent context: pass " +
|
|
2010
|
+
"persistent_context=True and user_data_dir=. For a non-persistent launch, use `args` " +
|
|
2011
|
+
"(command-line switches) instead.");
|
|
2012
|
+
}
|
|
2013
|
+
writeChromiumPrefs(String(userDataDir), chromium_prefs);
|
|
2014
|
+
}
|
|
2015
|
+
// ---- environment -------------------------------------------------------
|
|
2016
|
+
if (ownedDisplay) {
|
|
2017
|
+
const dpr = num(config["window.devicePixelRatio"] || 1);
|
|
2018
|
+
const width = config["screen.width"] || config["window.outerWidth"];
|
|
2019
|
+
const height = config["screen.height"] || config["window.outerHeight"];
|
|
2020
|
+
if (width && height)
|
|
2021
|
+
ownedDisplay.fit(Math.ceil(width * dpr), Math.ceil(height * dpr));
|
|
2022
|
+
env.DISPLAY = await ownedDisplay.get();
|
|
2023
|
+
}
|
|
2024
|
+
if (debug) {
|
|
2025
|
+
// Python pretty-prints with pprint(); the layout differs, the content
|
|
2026
|
+
// does not.
|
|
2027
|
+
utilsDeps.print("[DEBUG] Config:");
|
|
2028
|
+
utilsDeps.print(inspect(maskedConfig(config), { depth: null, sorted: true }));
|
|
2029
|
+
}
|
|
2030
|
+
// A passthrough launch keeps the host's fonts and timezone: only the
|
|
2031
|
+
// behaviour keys go to the browser.
|
|
2032
|
+
Object.assign(env, passthrough
|
|
2033
|
+
? configEnvVars(config)
|
|
2034
|
+
: getEnvVars(config, targetOs, browserBinary));
|
|
2035
|
+
const ignored = playwrightOptions.ignore_default_args ??
|
|
2036
|
+
playwrightOptions.ignoreDefaultArgs;
|
|
2037
|
+
delete playwrightOptions.ignore_default_args;
|
|
2038
|
+
delete playwrightOptions.ignoreDefaultArgs;
|
|
2039
|
+
const ignoreDefaultArgs = ignored === true
|
|
2040
|
+
? true
|
|
2041
|
+
: [
|
|
2042
|
+
...new Set([
|
|
2043
|
+
...IGNORED_DEFAULT_ARGS,
|
|
2044
|
+
...(headless === true ? [PLAYWRIGHT_HEADLESS_BLINK_SETTINGS] : []),
|
|
2045
|
+
...(ignored || []),
|
|
2046
|
+
]),
|
|
2047
|
+
];
|
|
2048
|
+
return {
|
|
2049
|
+
executablePath: browserBinary,
|
|
2050
|
+
args: launchArgs,
|
|
2051
|
+
env,
|
|
2052
|
+
headless,
|
|
2053
|
+
ignoreDefaultArgs,
|
|
2054
|
+
...(pyTruthy(browserProxy) ? { proxy: browserProxy } : {}),
|
|
2055
|
+
...playwrightOptions,
|
|
2056
|
+
};
|
|
2057
|
+
}
|