camoucore 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,14 +5,11 @@
5
5
  * TypeScript twin of python/camoucore/src/camoucore/camoufox/pkgman.py.
6
6
  */
7
7
  import { execFileSync } from "node:child_process";
8
- import { once } from "node:events";
9
8
  import * as fs from "node:fs";
10
9
  import { createRequire } from "node:module";
11
10
  import * as os from "node:os";
12
11
  import * as path from "node:path";
13
- import cliProgress from "cli-progress";
14
- import prettyBytes from "pretty-bytes";
15
- import { githubHeaders, raiseForStatus, request, } from "../download.js";
12
+ import { githubHeaders, raiseForStatus, request, webdl } from "../download.js";
16
13
  import { CONSTRAINTS, LIBRARY_VERSION } from "./__version__.js";
17
14
  import { effectivePin, pinMatches, pinSpec, warnIfUnpaired, } from "./browser-pin.js";
18
15
  import { CamoufoxNotInstalled, FileNotFoundError, MissingRelease, ProfileDirectoryError, UnsupportedArchitecture, UnsupportedOS, UnsupportedVersion, } from "./exceptions.js";
@@ -23,7 +20,7 @@ import { COMPAT_FLAG, findInstalledVersion, getActivePath, getDefaultChannel, in
23
20
  import { ARCH_MAP, INSTALL_DIR, LAUNCH_FILE, loadDataFile, OS_ARCH_MATRIX, OS_MAP, OS_NAME, rprint, } from "./paths.js";
24
21
  import { comparePyStr, ValueError } from "./pycompat.js";
25
22
  import { warn } from "./warnings.js";
26
- export { GITHUB_TOKEN, unzip, verifySha256, } from "../download.js";
23
+ export { GITHUB_TOKEN, unzip, verifySha256, webdl, } from "../download.js";
27
24
  /**
28
25
  * Ensure Firefox's Linux application directory exists before startup.
29
26
  *
@@ -499,11 +496,6 @@ export class CamoufoxFetcher {
499
496
  _versionObj;
500
497
  _selectedVersion;
501
498
  _url;
502
- /**
503
- * Where the download is kept between runs, so that a later fetch resumes
504
- * it; unset downloads into a temporary file.
505
- */
506
- partial;
507
499
  constructor(repoConfig, selectedVersion) {
508
500
  this.repoConfig = repoConfig ?? RepoConfig.getDefault();
509
501
  this.githubRepos = this.repoConfig.repos;
@@ -627,13 +619,6 @@ export class CamoufoxFetcher {
627
619
  rprint(`Downloading package: ${url}`);
628
620
  await webdl(url, undefined, true, file);
629
621
  }
630
- /**
631
- * Download this build's archive into `file`. Through the instance's class,
632
- * as Python's fetcher.download_file(), so a subclass can override either.
633
- */
634
- download(file) {
635
- return this.constructor.downloadFile(file, this.url);
636
- }
637
622
  /**
638
623
  * Download and install camoufox to a versioned subdirectory.
639
624
  */
@@ -955,85 +940,6 @@ export function selectedLaunchPath(specifier) {
955
940
  warnIfUnpaired(path.basename(path.dirname(installPath)), version.version ?? "", version.build);
956
941
  return launchPath(installPath);
957
942
  }
958
- const formatBytes = (v, _, type) => type === "total" || type === "value" ? prettyBytes(v) : String(v);
959
- /**
960
- * camoucore.download.webdl cannot resume (no `offset`, `restart`); this stays
961
- * until it can.
962
- *
963
- * Download a file from the given URL. Streams into `buffer` when one is given,
964
- * otherwise accumulates and returns the bytes.
965
- *
966
- * An HTTP error raises requests' "<status> Client Error: ... for url: ..."
967
- * message, like the Python twin; see request() for network failures.
968
- *
969
- * `offset` resumes a download whose first `offset` bytes `buffer` already
970
- * appends to. `restart` empties what `buffer` writes to: it is called when the
971
- * server sends the whole file, not the rest of it.
972
- */
973
- export async function webdl(url, desc, bar = true, buffer = null, { progressCallback, offset = 0, restart, } = {}) {
974
- const headers = githubHeaders(url);
975
- if (offset)
976
- headers.Range = `bytes=${offset}-`;
977
- const response = await request(url, { headers });
978
- raiseForStatus(response, url);
979
- if (offset && response.status !== 206) {
980
- restart?.();
981
- offset = 0;
982
- }
983
- const totalSize = offset + Number.parseInt(response.headers.get("content-length") || "0", 10);
984
- let progressBar = null;
985
- if (!progressCallback && bar) {
986
- progressBar = new cliProgress.SingleBar({
987
- format: `${desc || "Downloading"} [{bar}] {percentage}% | ETA: {eta_formatted} | {value}/{total}`,
988
- formatValue: formatBytes,
989
- noTTYOutput: true,
990
- }, cliProgress.Presets.shades_classic);
991
- progressBar.start(totalSize, offset);
992
- }
993
- const chunks = [];
994
- let downloaded = offset;
995
- let lastUpdate = offset;
996
- try {
997
- if (!response.body) {
998
- throw new Error(`Response from ${url} had no body`);
999
- }
1000
- for await (const chunk of response.body) {
1001
- if (buffer) {
1002
- // A stream that already failed (disk full) never drains: surface
1003
- // its error instead of waiting on it. When it is merely slow,
1004
- // wait for it, or the whole archive ends up queued in memory.
1005
- if (buffer.errored)
1006
- throw buffer.errored;
1007
- if (!buffer.write(chunk))
1008
- await once(buffer, "drain");
1009
- }
1010
- else {
1011
- chunks.push(chunk);
1012
- }
1013
- downloaded += chunk.length;
1014
- if (progressCallback) {
1015
- if (downloaded - lastUpdate >= 65536 || downloaded === totalSize) {
1016
- progressCallback(downloaded, totalSize);
1017
- lastUpdate = downloaded;
1018
- }
1019
- }
1020
- else if (progressBar) {
1021
- progressBar.increment(chunk.length);
1022
- }
1023
- else if (totalSize) {
1024
- const pct = (downloaded / totalSize) * 100;
1025
- process.stdout.write(`\r${desc}: ${pct.toFixed(0)}%`);
1026
- }
1027
- }
1028
- }
1029
- finally {
1030
- progressBar?.stop();
1031
- }
1032
- if (!progressCallback && !bar) {
1033
- process.stdout.write(desc ? `\r${desc}: Complete\n` : "\n");
1034
- }
1035
- return Buffer.concat(chunks);
1036
- }
1037
943
  /**
1038
944
  * chmod -R 755 on POSIX so the freshly-extracted binaries are executable.
1039
945
  * (The zip does not carry usable permission bits on every platform.)
@@ -17,7 +17,7 @@ import { attach } from "./_humanize_playwright.js";
17
17
  import { attachDriverDefaults } from "./driver_defaults.js";
18
18
  import { generateContextFingerprint } from "./fingerprints.js";
19
19
  import { normalize } from "./humanize.js";
20
- import { applyNoViewport, attachDesktopOnlyWarning, attachNoViewportDefault, attachPersistentGeometry, attachSharedTrafficWarning, attachSocks5Auth, attachStockMediaDefaults, attachViewportFit, attachVirtualDisplay, contextIdentity, contextScreenBound, driverPid, handOverContextGeometry, hostIdentity, launchGeometry, launchOptions, launchOs, pinnedCoreCount, STOCK_MEDIA_DEFAULTS, spoofsWindowDimensions, startVirtualDisplay, takeBackContextGeometry, } from "./utils.js";
20
+ import { applyNoViewport, attachDesktopOnlyWarning, attachNoViewportDefault, attachSharedTrafficWarning, attachSocks5Auth, attachStockMediaDefaults, attachVirtualDisplay, contextIdentity, driverPid, hostIdentity, launchOptions, launchOs, pinnedCoreCount, STOCK_MEDIA_DEFAULTS, spoofsWindowDimensions, startVirtualDisplay, } from "./utils.js";
21
21
  export async function Camoufox(options = {}) {
22
22
  return NewBrowser(firefox, options);
23
23
  }
@@ -103,7 +103,6 @@ async function launchWith(playwright, fromOptions, persistentContext, noViewport
103
103
  }
104
104
  const context = await playwright.launchPersistentContext(userDataDir ?? "", options);
105
105
  attachDriverDefaults(context);
106
- attachPersistentGeometry(context, fromOptions);
107
106
  return attachVirtualDisplay(context, virtualDisplay);
108
107
  }
109
108
  // Browser
@@ -112,7 +111,6 @@ async function launchWith(playwright, fromOptions, persistentContext, noViewport
112
111
  attachSocks5Auth(browser);
113
112
  if (!fromOptions.proxy)
114
113
  attachSharedTrafficWarning(browser);
115
- attachViewportFit(browser, launchGeometry(fromOptions));
116
114
  if (noViewportDefault) {
117
115
  attachNoViewportDefault(browser);
118
116
  }
@@ -173,7 +171,6 @@ export async function NewContext(browser, { preset, os, ff_version, webrtc_ip, p
173
171
  ff_version: ffVersion,
174
172
  webrtc_ip: webrtcIp,
175
173
  webgl_config: webglConfig,
176
- screen_bound: contextScreenBound(browser, contextOs, contextOptions),
177
174
  });
178
175
  // Merge the generated context options with user overrides (user wins). They
179
176
  // are already Playwright's JS names (userAgent, deviceScaleFactor,
@@ -189,19 +186,9 @@ export async function NewContext(browser, { preset, os, ff_version, webrtc_ip, p
189
186
  opts.geolocation = position;
190
187
  opts.permissions ??= ["geolocation"];
191
188
  }
192
- // A browser launched elsewhere takes SOCKS5 credentials too, and its
193
- // contexts are fitted to their screens as well. The hand-over is read by
194
- // the newContext() call below before it first awaits.
189
+ // A browser launched elsewhere takes SOCKS5 credentials too.
195
190
  attachSocks5Auth(browser);
196
- attachViewportFit(browser);
197
- handOverContextGeometry(browser, fp);
198
- let context;
199
- try {
200
- context = await browser.newContext(opts);
201
- }
202
- finally {
203
- takeBackContextGeometry(browser);
204
- }
191
+ const context = await browser.newContext(opts);
205
192
  await context.addInitScript(fp.init_script);
206
193
  return context;
207
194
  }
@@ -4,7 +4,7 @@ import { type ProxyConfig, publicIP } from "../ip.js";
4
4
  import { VirtualDisplay } from "../virtdisplay.js";
5
5
  import { addDefaultAddons, confirmPaths, type DefaultAddon } from "./addons.js";
6
6
  import { type DisplayProfileOption } from "./display_profile.js";
7
- import { type Box, clampScreenToDisplay, clampWindowDimensions, clampWindowPosition, drawVoiceConfig, fixHardwareConcurrency, fixNavigatorArch, followBaselineProtection, fromFpgen, fromPreset, generateFingerprint, generateRandomFontSubset, generateRandomVoiceSubset, getRandomPreset, identitySalt, identitySeed, raiseScreenToModernFloor, Screen, setMediaDevicesDefaults } from "./fingerprints.js";
7
+ import { clampScreenToDisplay, clampWindowDimensions, clampWindowPosition, drawVoiceConfig, fixHardwareConcurrency, fixNavigatorArch, followBaselineProtection, fromFpgen, fromPreset, generateFingerprint, generateRandomFontSubset, generateRandomVoiceSubset, getRandomPreset, identitySalt, identitySeed, raiseScreenToModernFloor, Screen, setMediaDevicesDefaults } from "./fingerprints.js";
8
8
  import { selectGpu } from "./gpudisplay.js";
9
9
  import { type Gpu, hostGpu } from "./host_rendering.js";
10
10
  import { type HumanizeSetting } from "./humanize.js";
@@ -26,7 +26,6 @@ declare const OS_NAMES: {
26
26
  export type OsName = (typeof OS_NAMES)[TargetOS];
27
27
  export declare const CACHE_PREFS: Record<string, any>;
28
28
  export declare const PROXY_DOH_PREFS: Record<string, any>;
29
- export declare const WINDOWS_UI_COLORS: Readonly<Record<string, string>>;
30
29
  export declare const WINDOWS_BEHAVIOUR_PREFS: Record<string, any>;
31
30
  /** The host OS in fonts.json / target_os terms ('mac', 'win', 'lin'). */
32
31
  declare function hostOsKey(): TargetOS | null;
@@ -136,34 +135,18 @@ export declare function getPrefEnvVars(prefs: Record<string, any>): Record<strin
136
135
  * managed install, the same way loadProperties() treats properties.json.
137
136
  */
138
137
  export declare function getEnvVars(configMap: Record<string, any>, userAgentOs: string, executablePath?: string | null): EnvVars;
138
+ /** True when CAMOUFOX_STRICT_CONFIG asks validateConfig to reject unknown keys. */
139
+ export declare function strictConfig(): boolean;
139
140
  /**
140
141
  * Validates the config map against the build's properties.json, and lifts a
141
142
  * numeric value below its declared `min` up to it.
142
- */
143
- export declare function validateConfig(configMap: Record<string, any>, executablePath?: string | null): void;
144
- /**
145
- * Applies the prefs and environment variables the build declares in its
146
- * launch.json. A build that needs a pref or variable set at launch for a
147
- * feature it compiles in says so there, so the launcher needs no knowledge of
148
- * any particular build. Most builds ship no launch.json.
149
143
  *
150
- * Each rule may restrict itself to identity OSes (`target`) and host OSes
151
- * (`host`), both in 'win'/'mac'/'lin' terms. `env` sets variables verbatim,
152
- * `envPaths` to a file relative to the build's directory, which must exist,
153
- * `envPathsOptional` likewise but only when the file exists, and
154
- * `envFromConfig` to the value of a config key when the identity has one.
155
- * `config` sets config keys. `ldPreload` appends each build-relative
156
- * library that exists to LD_PRELOAD (appended, never replacing one the
157
- * caller has), and `envCacheDirs` points each variable at a per-user cache
158
- * directory of that name, created on demand. A pref or config key the caller
159
- * set, or a variable already in the environment, is never replaced.
160
- *
161
- * An `exclusive` rule owns its variables: where it does not apply they are
162
- * removed from the environment, the caller's included, so a feature meant for
163
- * one target/host pairing cannot leak into another through an inherited
164
- * variable. A rule's `warn` is emitted as a RuntimeWarning when it applies.
144
+ * A key the build does not declare is reported and skipped, so a newer library
145
+ * still launches an older build. With CAMOUFOX_STRICT_CONFIG=1 it throws
146
+ * UnknownProperty instead: CI sets it against the newest release, so the
147
+ * launcher cannot ship a writer for a key no released browser reads.
165
148
  */
166
- export declare function applyLaunchRules(targetOs: string, config: Record<string, any>, firefoxUserPrefs: Record<string, any>, userPrefKeys: Set<string>, env: Record<string, any>, executablePath?: string | null): void;
149
+ export declare function validateConfig(configMap: Record<string, any>, executablePath?: string | null): void;
167
150
  /**
168
151
  * Validates the type of the value. (Python's bool is an int, so a boolean
169
152
  * passes the numeric checks there, and here.)
@@ -237,19 +220,14 @@ export declare function socks5Host(proxy: ProxyConfig | undefined | null): strin
237
220
  /**
238
221
  * Who resolves the names a proxied browser visits (docs/proxy-dns.md).
239
222
  *
240
- * "doh", the default behind a SOCKS5 proxy: the browser, by DoH through the
241
- * proxy, as a Firefox at the exit resolves its own. It gets HTTPS records, so
242
- * it sends ECH and starts HTTP/3 where that Firefox does, and the proxy is
243
- * given addresses. "exit": the proxy is given names. An HTTP proxy is always
244
- * given names.
223
+ * "exit", the default: the proxy is given names. "doh", behind a SOCKS5 proxy
224
+ * only: the browser, by DoH through the proxy, as a Firefox at the exit
225
+ * resolves its own; it gets HTTPS records, so it sends ECH where that Firefox
226
+ * does, and the proxy is given addresses. Starting HTTP/3 on them also needs
227
+ * the browser half that carries HTTP/3 over SOCKS5, which no released
228
+ * Camoufox has yet. An HTTP proxy is always given names.
245
229
  */
246
230
  export declare function applyProxyDns(proxyDns: string | undefined | null, proxy: ProxyConfig | undefined | null, config: Record<string, any>, firefoxUserPrefs: Record<string, any>, exitLookedUp: boolean): Promise<void>;
247
- /**
248
- * Send a connection's TLS ClientHello behind its SOCKS5 CONNECT request,
249
- * before the proxy's reply. Only for a proxy that forwards what it has
250
- * received once it has connected (docs/proxy-dns.md).
251
- */
252
- export declare function applyProxyOptimisticData(enabled: boolean | undefined | null, proxy: ProxyConfig | undefined | null, firefoxUserPrefs: Record<string, any>): void;
253
231
  /** The CAMOU_CONFIG chunks of a set of launch options, reassembled in order. */
254
232
  export declare function camouConfigBlob(fromOptions: Record<string, any>): string;
255
233
  /** The OS of the identity these launch options claim, the host's when they
@@ -306,100 +284,6 @@ export declare function attachStockMediaDefaults<T>(target: T): T;
306
284
  * through newContext(), so it is covered too.
307
285
  */
308
286
  export declare function attachSocks5Auth<T>(target: T): T;
309
- /** The viewport Playwright gives a context that asks for neither a viewport nor none. */
310
- export declare const PLAYWRIGHT_DEFAULT_VIEWPORT: {
311
- width: number;
312
- height: number;
313
- };
314
- /** What an identity claims around its pages (launchGeometry). */
315
- export interface Geometry {
316
- os: TargetOS;
317
- screen: [number, number];
318
- window: Box | null;
319
- }
320
- /**
321
- * What a launch's identity claims around its pages, from the CAMOU_CONFIG in
322
- * the launch options; null when the identity claims no screen
323
- * (python/camoucore/src/camoucore/camoufox/utils.py launch_geometry).
324
- *
325
- * The window is where CamoufoxWindow.sys.mjs puts the browser's real window,
326
- * which every page reports in outerWidth/outerHeight: the identity's outer
327
- * size, or, where the identity sets the content area instead, that with the
328
- * recorded chrome around it.
329
- */
330
- export declare function launchGeometry(fromOptions: Record<string, any>): Geometry | null;
331
- /**
332
- * The screen a new context must claim so that its pages fit on it, or null
333
- * when the identity's own already holds them
334
- * (python/camoucore/src/camoucore/camoufox/utils.py fit_context_screen).
335
- *
336
- * A viewport sits in a window the recorded chrome larger (screenFloor), and
337
- * the pages report the browser's window as theirs, so the screen holds both;
338
- * one that does not is replaced with a recorded screen that does
339
- * (drawScreen). Playwright's own `screen` option, which Juggler does not
340
- * apply, is the screen the caller chose: it is claimed as given. The caller's
341
- * viewport is never changed, so where no screen or no window can hold it,
342
- * this warns.
343
- */
344
- export declare function fitContextScreen(geometry: Geometry, options: Record<string, any>): [number, number] | null;
345
- /**
346
- * The init script that makes a context claim a `width` x `height` screen
347
- * (screen-spoofing.patch; the available rect follows it).
348
- */
349
- export declare function screenInitScript(width: number, height: number): string;
350
- /**
351
- * Make every newContext()/newPage() of `target` claim a screen its pages fit
352
- * on (python/camoucore/src/camoucore/camoufox/utils.py attach_viewport_fit).
353
- *
354
- * `geometry` is what the launch's identity claims (launchGeometry). A context
355
- * claims that, or the identity NewContext() hands over, with the screen
356
- * fitContextScreen() decides set through the per-context screen setter. The
357
- * context keeps what it claims, for setViewportSize().
358
- */
359
- export declare function attachViewportFit<T>(target: T, geometry?: Geometry | null): T;
360
- /**
361
- * Warn when page.setViewportSize() asks for a page its context's screen or
362
- * window cannot hold. The screen setter is sealed once a page has loaded, so
363
- * a context keeps the screen it started with.
364
- */
365
- export declare function checkViewportSize(geometry: Geometry | null | undefined, size: any, reason?: string): void;
366
- /**
367
- * A persistent context's pages claim the launch's identity: keep it for
368
- * setViewportSize(), and warn when the launch's own viewport does not fit it.
369
- * launchOptions() draws the identity around a viewport it is given, so this
370
- * only catches one the options were built without.
371
- */
372
- export declare function attachPersistentGeometry<T>(context: T, fromOptions: Record<string, any>): T;
373
- /**
374
- * The bound on a launch identity's screen that holds a `viewport` page in its
375
- * window (the caller's `window`, or one the recorded chrome larger), for
376
- * whichever OS the draw picks, within the caller's or the display's `screen`
377
- * bound (python/camoucore/src/camoucore/camoufox/utils.py viewport_screen_bound).
378
- */
379
- export declare function viewportScreenBound(viewport: [number, number], os: string | readonly string[] | null | undefined, screen: Screen | null, window: readonly [number, number] | null | undefined): Screen;
380
- /**
381
- * A bound on the screen a NewContext() identity draws, so that it holds the
382
- * context's pages: the viewport the caller asks for, with the recorded chrome
383
- * around it, and the browser's window, which the pages report as theirs
384
- * (screenFloor). Without a known OS, the bound holds them for any.
385
- */
386
- export declare function contextScreenBound(browser: any, os: string | null | undefined, contextOptions: Record<string, any>): Screen | null;
387
- /**
388
- * Tell attachViewportFit() what the next context of `browser` claims: the
389
- * NewContext() identity in `fingerprint`, in the browser's window.
390
- */
391
- export declare function handOverContextGeometry(browser: any, fingerprint: {
392
- config: Record<string, any>;
393
- preset: Record<string, any>;
394
- }): void;
395
- /** Drop a handOverContextGeometry() that no newContext() took. */
396
- export declare function takeBackContextGeometry(browser: any): void;
397
- /**
398
- * page.setViewportSize() on a page of a Camoufox launch: checkViewportSize()
399
- * against what the page's context claims (attachDriverDefaults in
400
- * driver_defaults.ts calls it where the client sends the request).
401
- */
402
- export declare function checkPageViewportSize(page: any, size: any): void;
403
287
  /**
404
288
  * Warn when newPage()/newContext() asks for isMobile: Camoufox only has desktop
405
289
  * identities, and Juggler ignores the option (TargetRegistry.js).
@@ -584,16 +468,12 @@ export interface LaunchOptions {
584
468
  /** Proxy to use for the browser. */
585
469
  proxy?: ProxyConfig;
586
470
  /**
587
- * Who resolves names behind a SOCKS5 proxy: "doh" (default), the browser,
588
- * by DoH through the proxy; "exit", the proxy. See docs/proxy-dns.md.
471
+ * Who resolves names behind a SOCKS5 proxy: "exit" (default), the proxy;
472
+ * "doh", the browser, by DoH through the proxy. "doh" needs a browser that
473
+ * carries HTTP/3 over SOCKS5, which no released Camoufox does yet. See
474
+ * docs/proxy-dns.md.
589
475
  */
590
476
  proxy_dns?: "doh" | "exit";
591
- /**
592
- * Send the TLS ClientHello behind the SOCKS5 CONNECT request, before the
593
- * proxy's reply. Only for a proxy that forwards those bytes; behind one
594
- * that discards them every HTTPS connection hangs. See docs/proxy-dns.md.
595
- */
596
- proxy_optimistic_data?: boolean;
597
477
  /** Cache previous pages, requests, etc (uses more memory). */
598
478
  enable_cache?: boolean;
599
479
  /** Arguments to pass to the browser. */
@@ -619,11 +499,8 @@ export interface LaunchOptions {
619
499
  canvas_noise?: boolean | null;
620
500
  /** The display's ICC colour profile, which ICC-tagged images are converted
621
501
  * to (a page reads it from their decoded pixels): ICC bytes or a path, e.g.
622
- * one recorded with GetICMProfileW on the machine the identity presents.
623
- * `false` keeps the browser's own (built-in sRGB on a host without one).
624
- * Default: an identity of another OS draws one from display-profiles.json
625
- * for its OS and screen; an identity of the host's OS uses the host
626
- * display's, as stock does. */
502
+ * one recorded with GetICMProfileW on a real machine. Default (undefined or
503
+ * false): the browser's own, the host display's as stock Firefox uses. */
627
504
  display_profile?: DisplayProfileOption;
628
505
  /** Additional Firefox launch options, passed straight through to Playwright. */
629
506
  [key: string]: any;