camoufox-js 0.12.0 → 0.13.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/README.md CHANGED
@@ -9,7 +9,7 @@ npm install camoufox-js
9
9
  ```
10
10
 
11
11
  The Camoufox browser itself is downloaded with `npx camoufox-js fetch` into the
12
- per-user cache directory (`~/.cache/camoufox` on Linux). Set the
12
+ per-user cache directory (`$XDG_CACHE_HOME/camoufox` or `~/.cache/camoufox` on Linux). Set the
13
13
  `CAMOUFOX_INSTALL_DIR` environment variable to install and resolve it from a
14
14
  custom location instead — useful in containers and CI images where the home
15
15
  directory is ephemeral or persisted separately (similar to Playwright's
@@ -19,6 +19,11 @@ directory is ephemeral or persisted separately (similar to Playwright's
19
19
  CAMOUFOX_INSTALL_DIR=/opt/camoufox npx camoufox-js fetch
20
20
  ```
21
21
 
22
+ Each camoufox-js release is tested with one Camoufox build (`src/data-files/browser-pin.json`), and `fetch` installs
23
+ exactly that build into `browsers/<repo>/<version>-<build>/` inside that directory. This is the layout the Python
24
+ library uses, so both can share one cache. If the build is missing, the first launch downloads it, unless
25
+ `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` is set.
26
+
22
27
  ## Usage
23
28
 
24
29
  You can launch Playwright-controlled Camoufox using this package like this:
@@ -6,6 +6,12 @@ export declare class CONSTRAINTS {
6
6
  * The minimum and maximum supported versions of the Camoufox browser.
7
7
  */
8
8
  static readonly MIN_VERSION: string;
9
+ /**
10
+ * Exclusive. The Firefox 156 builds (beta.32+) dropped properties this library still generates.
11
+ */
9
12
  static readonly MAX_VERSION: string;
10
- static asRange(): string;
13
+ /**
14
+ * Minimum version with Playwright 1.61+, which sends viewport fields that older builds reject.
15
+ */
16
+ static readonly PLAYWRIGHT_1_61_MIN_VERSION: string;
11
17
  }
@@ -6,11 +6,12 @@ export class CONSTRAINTS {
6
6
  * The minimum and maximum supported versions of the Camoufox browser.
7
7
  */
8
8
  static MIN_VERSION = "alpha.1";
9
- static MAX_VERSION = "1";
10
- static asRange() {
11
- /**
12
- * Returns the version range as a string.
13
- */
14
- return `>=${CONSTRAINTS.MIN_VERSION}, <${CONSTRAINTS.MAX_VERSION}`;
15
- }
9
+ /**
10
+ * Exclusive. The Firefox 156 builds (beta.32+) dropped properties this library still generates.
11
+ */
12
+ static MAX_VERSION = "beta.32";
13
+ /**
14
+ * Minimum version with Playwright 1.61+, which sends viewport fields that older builds reject.
15
+ */
16
+ static PLAYWRIGHT_1_61_MIN_VERSION = "beta.30";
16
17
  }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The browser build this library is tested with, in the same format as the
3
+ * Python library's browser-pin.json. `camoufox fetch` installs and launches
4
+ * exactly this build unless the user explicitly chose another one.
5
+ */
6
+ export declare const PIN_FILE: string;
7
+ export interface BrowserPin {
8
+ tag: string;
9
+ repo: string;
10
+ repoName: string;
11
+ version: string;
12
+ build: string;
13
+ }
14
+ export declare function pinSpec(pin: BrowserPin): string;
15
+ export declare function loadPin(file?: string): BrowserPin | null;
16
+ /**
17
+ * The pin, unless the user chose a channel or a build themselves.
18
+ */
19
+ export declare function effectivePin(config: {
20
+ channel?: string;
21
+ pinned?: string;
22
+ }): BrowserPin | null;
23
+ export declare function pinMatches(pin: BrowserPin, repoName: string, version: string, build: string): boolean;
@@ -0,0 +1,42 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const currentDir = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
5
+ /**
6
+ * The browser build this library is tested with, in the same format as the
7
+ * Python library's browser-pin.json. `camoufox fetch` installs and launches
8
+ * exactly this build unless the user explicitly chose another one.
9
+ */
10
+ export const PIN_FILE = path.join(currentDir, "data-files", "browser-pin.json");
11
+ export function pinSpec(pin) {
12
+ return `${pin.version}-${pin.build}`;
13
+ }
14
+ export function loadPin(file = PIN_FILE) {
15
+ let data;
16
+ try {
17
+ data = JSON.parse(fs.readFileSync(file, "utf-8"));
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ if (!data?.tag)
23
+ return null;
24
+ return {
25
+ tag: data.tag,
26
+ repo: String(data.repo),
27
+ repoName: String(data.repo_name).toLowerCase(),
28
+ version: String(data.version),
29
+ build: String(data.build),
30
+ };
31
+ }
32
+ /**
33
+ * The pin, unless the user chose a channel or a build themselves.
34
+ */
35
+ export function effectivePin(config) {
36
+ return config.channel || config.pinned ? null : loadPin();
37
+ }
38
+ export function pinMatches(pin, repoName, version, build) {
39
+ return (repoName.toLowerCase() === pin.repoName &&
40
+ version === pin.version &&
41
+ build === pin.build);
42
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "tag": "v152.0.4-beta.30",
3
+ "repo": "daijro/camoufox",
4
+ "repo_name": "Official",
5
+ "version": "152.0.4",
6
+ "build": "beta.30"
7
+ }
@@ -71,6 +71,9 @@ export declare class VirtualDisplayNotSupported extends VirtualDisplayError {
71
71
  export declare class CamoufoxNotInstalled extends Error {
72
72
  constructor(message?: string);
73
73
  }
74
+ export declare class CorruptedDownload extends Error {
75
+ constructor(message?: string);
76
+ }
74
77
  export declare class FileNotFoundError extends Error {
75
78
  constructor(message?: string);
76
79
  }
@@ -145,6 +145,12 @@ export class CamoufoxNotInstalled extends Error {
145
145
  this.name = "CamoufoxNotInstalled";
146
146
  }
147
147
  }
148
+ export class CorruptedDownload extends Error {
149
+ constructor(message) {
150
+ super(message ?? "The download is corrupted.");
151
+ this.name = "CorruptedDownload";
152
+ }
153
+ }
148
154
  export class FileNotFoundError extends Error {
149
155
  constructor(message) {
150
156
  super(message ?? "File couldn't be found.");
@@ -0,0 +1,40 @@
1
+ import { Version } from "./pkgman.js";
2
+ /**
3
+ * The Python library's multi-version layout (multiversion.py), shared with it: builds live in
4
+ * INSTALL_DIR/browsers/<repo>/<version>-<build>[-<sha8>]/ and config.json records the active
5
+ * one and whether the user chose a channel or a build.
6
+ */
7
+ export declare const browsersDir: () => string;
8
+ export declare const configFile: () => string;
9
+ export declare const compatFlag: () => string;
10
+ export interface CamoufoxConfig {
11
+ active_version?: string | null;
12
+ channel?: string;
13
+ pinned?: string;
14
+ pinned_sha?: string;
15
+ [key: string]: unknown;
16
+ }
17
+ export declare function loadConfig(): CamoufoxConfig;
18
+ export declare function saveConfig(config: CamoufoxConfig): void;
19
+ export declare function setActive(relativePath: string): void;
20
+ export declare function getRepoName(githubRepo: string): string;
21
+ export declare function versionFolderName(version: string, build: string, sha256?: string): string;
22
+ export interface InstalledVersion {
23
+ repoName: string;
24
+ version: Version;
25
+ path: string;
26
+ relativePath: string;
27
+ isActive: boolean;
28
+ isPrerelease: boolean;
29
+ sha256?: string;
30
+ }
31
+ /**
32
+ * Builds in browsers/, sorted by repo, then newest first.
33
+ */
34
+ export declare function listInstalled(): InstalledVersion[];
35
+ /**
36
+ * The build to launch: the pinned one unless the user explicitly chose another, else the
37
+ * active one. Null when that build isn't installed. Unlike the Python library, it doesn't
38
+ * record the result in config.json, as launches may run concurrently or from a read-only dir.
39
+ */
40
+ export declare function getActivePath(): string | null;
@@ -0,0 +1,105 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { effectivePin, pinMatches } from "./browser-pin.js";
4
+ import { INSTALL_DIR, Version } from "./pkgman.js";
5
+ /**
6
+ * The Python library's multi-version layout (multiversion.py), shared with it: builds live in
7
+ * INSTALL_DIR/browsers/<repo>/<version>-<build>[-<sha8>]/ and config.json records the active
8
+ * one and whether the user chose a channel or a build.
9
+ */
10
+ // pkgman imports this module too, so paths are resolved on use rather than at load.
11
+ export const browsersDir = () => path.join(INSTALL_DIR.toString(), "browsers");
12
+ export const configFile = () => path.join(INSTALL_DIR.toString(), "config.json");
13
+ export const compatFlag = () => path.join(INSTALL_DIR.toString(), ".0.5_FLAG");
14
+ export function loadConfig() {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(configFile(), "utf-8"));
17
+ }
18
+ catch {
19
+ return {};
20
+ }
21
+ }
22
+ export function saveConfig(config) {
23
+ fs.mkdirSync(INSTALL_DIR, { recursive: true });
24
+ // Through a rename, so a concurrent reader never sees a half-written file.
25
+ const tmp = `${configFile()}.${process.pid}.tmp`;
26
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2));
27
+ fs.renameSync(tmp, configFile());
28
+ }
29
+ export function setActive(relativePath) {
30
+ saveConfig({ ...loadConfig(), active_version: relativePath });
31
+ }
32
+ // Folder names of the Python library's repos.yml entries.
33
+ const REPO_NAMES = { "daijro/camoufox": "official" };
34
+ export function getRepoName(githubRepo) {
35
+ return REPO_NAMES[githubRepo] ?? githubRepo.split("/")[0].toLowerCase();
36
+ }
37
+ export function versionFolderName(version, build, sha256) {
38
+ const base = `${version}-${build}`;
39
+ return sha256 ? `${base}-${sha256.slice(0, 8)}` : base;
40
+ }
41
+ /**
42
+ * Builds in browsers/, sorted by repo, then newest first.
43
+ */
44
+ export function listInstalled() {
45
+ const installed = [];
46
+ if (!fs.existsSync(browsersDir()))
47
+ return installed;
48
+ const active = loadConfig().active_version;
49
+ for (const repo of fs.readdirSync(browsersDir(), { withFileTypes: true })) {
50
+ if (!repo.isDirectory() || repo.name.startsWith("."))
51
+ continue;
52
+ const repoDir = path.join(browsersDir(), repo.name);
53
+ for (const folder of fs.readdirSync(repoDir, { withFileTypes: true })) {
54
+ const dir = path.join(repoDir, folder.name);
55
+ const versionJson = path.join(dir, "version.json");
56
+ if (!folder.isDirectory() || !fs.existsSync(versionJson))
57
+ continue;
58
+ try {
59
+ const data = JSON.parse(fs.readFileSync(versionJson, "utf-8"));
60
+ const relativePath = `browsers/${repo.name}/${folder.name}`;
61
+ installed.push({
62
+ repoName: repo.name,
63
+ version: Version.fromPath(dir),
64
+ path: dir,
65
+ relativePath,
66
+ isActive: relativePath === active,
67
+ isPrerelease: data.prerelease ?? false,
68
+ sha256: data.sha256 ?? undefined,
69
+ });
70
+ }
71
+ catch {
72
+ // A corrupt version.json is not a usable install.
73
+ }
74
+ }
75
+ }
76
+ const compare = (a, b) => a.lessThan(b) ? -1 : b.lessThan(a) ? 1 : 0;
77
+ return installed.sort((a, b) => (a.repoName < b.repoName ? 1 : a.repoName > b.repoName ? -1 : 0) ||
78
+ compare(b.version, a.version));
79
+ }
80
+ /**
81
+ * The build to launch: the pinned one unless the user explicitly chose another, else the
82
+ * active one. Null when that build isn't installed. Unlike the Python library, it doesn't
83
+ * record the result in config.json, as launches may run concurrently or from a read-only dir.
84
+ */
85
+ export function getActivePath() {
86
+ const config = loadConfig();
87
+ const active = config.active_version;
88
+ const pin = effectivePin(config);
89
+ if (pin) {
90
+ const inst = listInstalled().find((v) => pinMatches(pin, v.repoName, v.version.version ?? "", v.version.release));
91
+ return inst?.path ?? null;
92
+ }
93
+ if (active) {
94
+ const activePath = path.join(INSTALL_DIR.toString(), active);
95
+ if (fs.existsSync(path.join(activePath, "version.json"))) {
96
+ return activePath;
97
+ }
98
+ }
99
+ if (!config.channel && !config.pinned) {
100
+ const [newest] = listInstalled();
101
+ if (newest)
102
+ return newest.path;
103
+ }
104
+ return null;
105
+ }
package/dist/pkgman.d.ts CHANGED
@@ -12,7 +12,7 @@ export declare const LOCAL_DATA: PathLike;
12
12
  export declare const OS_ARCH_MATRIX: {
13
13
  [key: string]: string[];
14
14
  };
15
- declare class Version {
15
+ export declare class Version {
16
16
  release: string;
17
17
  version?: string;
18
18
  sorted_rel: number[];
@@ -30,7 +30,8 @@ export declare class GitHubDownloader {
30
30
  githubRepo: string;
31
31
  apiUrl: string;
32
32
  constructor(githubRepo: string);
33
- checkAsset(asset: any): any;
33
+ checkAsset(asset: any, _release?: any): any;
34
+ releasesUrl(): string;
34
35
  missingAssetError(): void;
35
36
  getAsset({ retries }?: {
36
37
  retries: number;
@@ -41,16 +42,22 @@ export declare class CamoufoxFetcher extends GitHubDownloader {
41
42
  _version_obj?: Version;
42
43
  pattern: RegExp;
43
44
  _url?: string;
45
+ isPrerelease: boolean;
46
+ sha256?: string;
47
+ createdAt?: string;
44
48
  constructor();
45
49
  init(): Promise<void>;
46
- checkAsset(asset: any): [Version, string] | null;
50
+ releasesUrl(): string;
51
+ checkAsset(asset: any, release?: any): [Version, string] | null;
47
52
  missingAssetError(): void;
48
53
  static getPlatformArch(): string;
49
54
  fetchLatest(): Promise<void>;
50
55
  static downloadFile(url: string): Promise<Buffer>;
51
- extractZip(zipFile: string | Buffer): Promise<void>;
56
+ extractZip(zipFile: string | Buffer, destDir?: string): Promise<void>;
52
57
  static cleanup(): boolean;
53
- setVersion(): void;
58
+ setVersion(destDir?: string): void;
59
+ private static removeLeftovers;
60
+ private static activate;
54
61
  install(): Promise<void>;
55
62
  get url(): string;
56
63
  get version(): string;
@@ -58,11 +65,18 @@ export declare class CamoufoxFetcher extends GitHubDownloader {
58
65
  get verstr(): string;
59
66
  }
60
67
  export declare function installedVerStr(): string;
61
- export declare function camoufoxPath(downloadIfMissing?: boolean): PathLike;
68
+ /**
69
+ * @param _downloadIfMissing Ignored, downloads happen in {@link ensureCamoufoxInstalled}.
70
+ */
71
+ export declare function camoufoxPath(_downloadIfMissing?: boolean): PathLike;
72
+ /**
73
+ * Installs the pinned build when no supported install is available, as the Python
74
+ * library does on launch. An explicitly chosen build is never replaced.
75
+ */
76
+ export declare function ensureCamoufoxInstalled(): Promise<void>;
62
77
  export declare function getPath(file: string): string;
63
78
  export declare function launchPath(): string;
64
79
  export declare function webdl(url: string, desc?: string, bar?: boolean, buffer?: Writable | null, { retries }?: {
65
80
  retries: number;
66
81
  }): Promise<Buffer>;
67
82
  export declare function unzip(zipFile: Buffer, extractPath: string, desc?: string, bar?: boolean): Promise<void>;
68
- export {};
package/dist/pkgman.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
2
3
  import * as fs from "node:fs";
4
+ import { createRequire } from "node:module";
3
5
  import * as os from "node:os";
4
6
  import * as path from "node:path";
5
7
  import { setTimeout } from "node:timers/promises";
@@ -8,7 +10,9 @@ import AdmZip from "adm-zip";
8
10
  import cliProgress from "cli-progress";
9
11
  import prettyBytes from "pretty-bytes";
10
12
  import { CONSTRAINTS } from "./__version__.js";
11
- import { CamoufoxNotInstalled, FileNotFoundError, MissingRelease, UnsupportedArchitecture, UnsupportedOS, UnsupportedVersion, } from "./exceptions.js";
13
+ import { effectivePin, pinMatches, pinSpec } from "./browser-pin.js";
14
+ import { CamoufoxNotInstalled, CorruptedDownload, FileNotFoundError, MissingRelease, UnsupportedArchitecture, UnsupportedOS, UnsupportedVersion, } from "./exceptions.js";
15
+ import { browsersDir, compatFlag, getActivePath, getRepoName, loadConfig, setActive, versionFolderName, } from "./multiversion.js";
12
16
  const ARCH_MAP = {
13
17
  x64: "x86_64",
14
18
  ia32: "i686",
@@ -56,7 +60,17 @@ const LAUNCH_FILE = {
56
60
  mac: "../MacOS/camoufox",
57
61
  lin: "camoufox-bin",
58
62
  };
59
- class Version {
63
+ function isPlaywright161OrNewer() {
64
+ try {
65
+ const { version } = createRequire(import.meta.url)("playwright-core/package.json");
66
+ const [major, minor] = version.split(".").map(Number);
67
+ return major > 1 || (major === 1 && minor >= 61);
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ export class Version {
60
74
  release;
61
75
  version;
62
76
  sorted_rel;
@@ -90,7 +104,7 @@ class Version {
90
104
  return false;
91
105
  }
92
106
  isSupported() {
93
- return VERSION_MIN.lessThan(this) && this.lessThan(VERSION_MAX);
107
+ return !this.lessThan(VERSION_MIN) && this.lessThan(VERSION_MAX);
94
108
  }
95
109
  static fromPath(filePath = INSTALL_DIR) {
96
110
  const versionPath = path.join(filePath.toString(), "version.json");
@@ -98,19 +112,23 @@ class Version {
98
112
  throw new FileNotFoundError(`Version information not found at ${versionPath}. Please run \`camoufox fetch\` to install.`);
99
113
  }
100
114
  const versionData = JSON.parse(fs.readFileSync(versionPath, "utf-8"));
101
- return new Version(versionData.release, versionData.version);
115
+ // The flat layout wrote `release`, the versioned one (shared with the Python library) writes `build`.
116
+ return new Version(versionData.build ?? versionData.release, versionData.version);
102
117
  }
103
118
  static isSupportedPath(path) {
104
119
  return Version.fromPath(path).isSupported();
105
120
  }
106
121
  static buildMinMax() {
107
122
  return [
108
- new Version(CONSTRAINTS.MIN_VERSION),
123
+ new Version(isPlaywright161OrNewer()
124
+ ? CONSTRAINTS.PLAYWRIGHT_1_61_MIN_VERSION
125
+ : CONSTRAINTS.MIN_VERSION),
109
126
  new Version(CONSTRAINTS.MAX_VERSION),
110
127
  ];
111
128
  }
112
129
  }
113
130
  const [VERSION_MIN, VERSION_MAX] = Version.buildMinMax();
131
+ const SUPPORTED_RANGE = `>=${VERSION_MIN.release}, <${VERSION_MAX.release}`;
114
132
  export class GitHubDownloader {
115
133
  githubRepo;
116
134
  apiUrl;
@@ -118,19 +136,23 @@ export class GitHubDownloader {
118
136
  this.githubRepo = githubRepo;
119
137
  this.apiUrl = `https://api.github.com/repos/${githubRepo}/releases`;
120
138
  }
121
- checkAsset(asset) {
139
+ checkAsset(asset, _release) {
122
140
  return asset.browser_download_url;
123
141
  }
142
+ releasesUrl() {
143
+ return this.apiUrl;
144
+ }
124
145
  missingAssetError() {
125
146
  throw new MissingRelease(`Could not find a release asset in ${this.githubRepo}.`);
126
147
  }
127
148
  async getAsset({ retries } = { retries: 5 }) {
128
149
  let attempts = 0;
129
150
  let response;
151
+ const url = this.releasesUrl();
130
152
  while (attempts < retries) {
131
153
  try {
132
- response = await fetch(this.apiUrl, {
133
- headers: getAuthorizationHeaders(this.apiUrl),
154
+ response = await fetch(url, {
155
+ headers: getAuthorizationHeaders(url),
134
156
  });
135
157
  if (response.ok)
136
158
  break;
@@ -142,14 +164,15 @@ export class GitHubDownloader {
142
164
  attempts++;
143
165
  }
144
166
  if (!response || !response.ok) {
145
- throw new Error(`Failed to fetch releases from ${this.apiUrl} after ${retries} attempts`);
167
+ throw new Error(`Failed to fetch releases from ${url} after ${retries} attempts`);
146
168
  }
147
- const releases = await response.json();
169
+ const data = await response.json();
170
+ const releases = Array.isArray(data) ? data : [data];
148
171
  for (const release of releases) {
149
172
  if (release.prerelease || release.draft)
150
173
  continue;
151
174
  for (const asset of release.assets) {
152
- const data = this.checkAsset(asset);
175
+ const data = this.checkAsset(asset, release);
153
176
  if (data) {
154
177
  return data;
155
178
  }
@@ -163,6 +186,9 @@ export class CamoufoxFetcher extends GitHubDownloader {
163
186
  _version_obj;
164
187
  pattern;
165
188
  _url;
189
+ isPrerelease = false;
190
+ sha256;
191
+ createdAt;
166
192
  constructor() {
167
193
  super("daijro/camoufox");
168
194
  this.arch = CamoufoxFetcher.getPlatformArch();
@@ -171,17 +197,34 @@ export class CamoufoxFetcher extends GitHubDownloader {
171
197
  async init() {
172
198
  await this.fetchLatest();
173
199
  }
174
- checkAsset(asset) {
200
+ releasesUrl() {
201
+ const pin = effectivePin(loadConfig());
202
+ return pin && getRepoName(this.githubRepo) === pin.repoName
203
+ ? `${this.apiUrl}/tags/${pin.tag}`
204
+ : this.apiUrl;
205
+ }
206
+ checkAsset(asset, release) {
175
207
  const match = asset.name.match(this.pattern);
176
208
  if (!match)
177
209
  return null;
178
210
  const version = new Version(match[2], match[1]);
179
211
  if (!version.isSupported())
180
212
  return null;
213
+ // Install exactly the tested build, unless the user explicitly chose another one.
214
+ const pin = effectivePin(loadConfig());
215
+ if (pin &&
216
+ !pinMatches(pin, getRepoName(this.githubRepo), match[1], match[2])) {
217
+ return null;
218
+ }
219
+ this.isPrerelease = Boolean(release?.prerelease);
220
+ this.sha256 = asset.digest?.startsWith("sha256:")
221
+ ? asset.digest.slice("sha256:".length)
222
+ : undefined;
223
+ this.createdAt = asset.created_at;
181
224
  return [version, asset.browser_download_url];
182
225
  }
183
226
  missingAssetError() {
184
- throw new MissingRelease(`No matching release found for ${OS_NAME} ${this.arch} in the supported range: (${CONSTRAINTS.asRange()}). Please update the library.`);
227
+ throw new MissingRelease(`No matching release found for ${OS_NAME} ${this.arch} in the supported range: (${SUPPORTED_RANGE}). Please update the library.`);
185
228
  }
186
229
  static getPlatformArch() {
187
230
  const platArch = os.arch().toLowerCase();
@@ -207,9 +250,9 @@ export class CamoufoxFetcher extends GitHubDownloader {
207
250
  });
208
251
  return Buffer.from(await response.arrayBuffer());
209
252
  }
210
- async extractZip(zipFile) {
253
+ async extractZip(zipFile, destDir = INSTALL_DIR.toString()) {
211
254
  const zip = new AdmZip(zipFile);
212
- zip.extractAllTo(INSTALL_DIR.toString(), true);
255
+ zip.extractAllTo(destDir, true);
213
256
  }
214
257
  static cleanup() {
215
258
  if (fs.existsSync(INSTALL_DIR)) {
@@ -218,30 +261,83 @@ export class CamoufoxFetcher extends GitHubDownloader {
218
261
  }
219
262
  return false;
220
263
  }
221
- setVersion() {
222
- fs.writeFileSync(path.join(INSTALL_DIR.toString(), "version.json"), JSON.stringify({ version: this.version, release: this.release }));
264
+ setVersion(destDir = INSTALL_DIR.toString()) {
265
+ fs.writeFileSync(path.join(destDir, "version.json"), JSON.stringify({
266
+ version: this.version,
267
+ build: this.release,
268
+ prerelease: this.isPrerelease,
269
+ sha256: this.sha256 ?? null,
270
+ created_at: this.createdAt ?? null,
271
+ }));
272
+ }
273
+ // Remove staging dirs left behind by an interrupted install.
274
+ static removeLeftovers(dir, prefix) {
275
+ for (const name of fs.readdirSync(dir)) {
276
+ // Fresh ones may belong to an install still running in another process.
277
+ if (name.startsWith(prefix) && isStale(path.join(dir, name))) {
278
+ fs.rmSync(path.join(dir, name), { recursive: true, force: true });
279
+ }
280
+ }
281
+ }
282
+ static activate(installDir, relativePath) {
283
+ setActive(relativePath);
284
+ removeLegacyInstall(installDir);
223
285
  }
224
286
  async install() {
225
287
  await this.init();
226
- await CamoufoxFetcher.cleanup();
227
- // Set up outside the try so finally can always tear down the ~600MB staging dir.
288
+ const folder = versionFolderName(this.version, this.release, this.sha256);
289
+ const relativePath = `browsers/${getRepoName(this.githubRepo)}/${folder}`;
290
+ const installDir = path.join(INSTALL_DIR.toString(), relativePath);
291
+ fs.mkdirSync(browsersDir(), { recursive: true });
292
+ // Tells the Python library this directory uses its layout, so it doesn't wipe it.
293
+ fs.writeFileSync(compatFlag(), "");
294
+ if (fs.existsSync(path.join(installDir, "version.json"))) {
295
+ console.log(`Camoufox v${this.verstr} is already installed.`);
296
+ CamoufoxFetcher.activate(installDir, relativePath);
297
+ return;
298
+ }
299
+ // Older releases staged next to the (symlink-resolved) install dir.
300
+ const root = fs.realpathSync(INSTALL_DIR);
301
+ CamoufoxFetcher.removeLeftovers(path.dirname(root), `${path.basename(root)}.staging-`);
302
+ CamoufoxFetcher.removeLeftovers(browsersDir(), ".staging-");
303
+ // Staged inside browsers/ so the final rename stays on one filesystem. Dot-prefixed
304
+ // entries are skipped by install listings, including the Python library's.
305
+ // Set up outside the try so finally can always tear down the ~600MB staging dirs.
306
+ const stagingDir = fs.mkdtempSync(path.join(browsersDir(), ".staging-"));
228
307
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "camoufox-"));
229
308
  const tempFilePath = path.join(tempDir, "camoufox.zip");
230
309
  const tempFileStream = fs.createWriteStream(tempFilePath);
231
310
  try {
232
- fs.mkdirSync(INSTALL_DIR, { recursive: true });
233
311
  await webdl(this.url, "Downloading Camoufox...", true, tempFileStream);
234
312
  await new Promise((r) => tempFileStream.close(r));
235
- await this.extractZip(tempFilePath);
236
- this.setVersion();
313
+ await verifySha256(tempFilePath, this.sha256, `Camoufox v${this.verstr}`);
314
+ await this.extractZip(tempFilePath, stagingDir);
315
+ this.setVersion(stagingDir);
237
316
  if (OS_NAME !== "win") {
238
- execFileSync("chmod", ["-R", "755", INSTALL_DIR.toString()]);
317
+ execFileSync("chmod", ["-R", "755", stagingDir]);
318
+ }
319
+ fs.mkdirSync(path.dirname(installDir), { recursive: true });
320
+ try {
321
+ fs.renameSync(stagingDir, installDir);
239
322
  }
240
- console.log("Camoufox successfully installed.");
323
+ catch (e) {
324
+ // Unless another process finished the same install in the meantime, the target is
325
+ // an install in progress (the Python library extracts in place) or an abandoned one.
326
+ if (!fs.existsSync(path.join(installDir, "version.json"))) {
327
+ if (!fs.existsSync(installDir))
328
+ throw e;
329
+ if (!isStale(installDir)) {
330
+ throw new Error(`Another process is installing Camoufox into ${installDir}, try again once it finishes.`);
331
+ }
332
+ fs.rmSync(installDir, { recursive: true, force: true });
333
+ fs.renameSync(stagingDir, installDir);
334
+ }
335
+ }
336
+ CamoufoxFetcher.activate(installDir, relativePath);
337
+ console.log(`Camoufox successfully installed to ${installDir}.`);
241
338
  }
242
339
  catch (e) {
243
340
  console.error(`Error installing Camoufox: ${e}`);
244
- await CamoufoxFetcher.cleanup();
245
341
  throw e;
246
342
  }
247
343
  finally {
@@ -252,9 +348,10 @@ export class CamoufoxFetcher extends GitHubDownloader {
252
348
  await new Promise((resolve) => tempFileStream.close(() => resolve()));
253
349
  }
254
350
  fs.rmSync(tempDir, { recursive: true, force: true });
351
+ fs.rmSync(stagingDir, { recursive: true, force: true });
255
352
  }
256
353
  catch (cleanupErr) {
257
- console.error(`Failed to remove staging dir ${tempDir}: ${cleanupErr}`);
354
+ console.error(`Failed to remove staging dir: ${cleanupErr}`);
258
355
  }
259
356
  }
260
357
  }
@@ -291,32 +388,91 @@ function userCacheDir(appName) {
291
388
  return path.join(os.homedir(), "Library", "Caches", appName);
292
389
  }
293
390
  else {
294
- return path.join(os.homedir(), ".cache", appName);
391
+ // Per the XDG spec a relative XDG_CACHE_HOME is invalid and ignored.
392
+ const xdg = process.env.XDG_CACHE_HOME;
393
+ return path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), ".cache"), appName);
295
394
  }
296
395
  }
297
- export function installedVerStr() {
298
- return Version.fromPath().fullString;
396
+ // Root entries of the layout shared with the Python library, never part of a flat install.
397
+ const SHARED_ENTRIES = new Set([
398
+ ".0.5_FLAG",
399
+ "addons",
400
+ "browsers",
401
+ "config.json",
402
+ "fontconfig",
403
+ "geoip",
404
+ "repo_cache.json",
405
+ ]);
406
+ // Older than any download or extraction still in progress.
407
+ function isStale(p) {
408
+ try {
409
+ return Date.now() - fs.statSync(p).mtimeMs > 24 * 60 * 60 * 1000;
410
+ }
411
+ catch {
412
+ return false;
413
+ }
299
414
  }
300
- export function camoufoxPath(downloadIfMissing = true) {
301
- // Ensure the directory exists and is not empty
302
- if (!fs.existsSync(INSTALL_DIR) || fs.readdirSync(INSTALL_DIR).length === 0) {
303
- if (!downloadIfMissing) {
304
- throw new Error(`Camoufox executable not found at ${INSTALL_DIR}`);
415
+ /**
416
+ * Removes a flat install of an older release from the root of INSTALL_DIR. It holds the
417
+ * same top-level entries as the build just installed into `installDir`.
418
+ */
419
+ function removeLegacyInstall(installDir) {
420
+ const root = INSTALL_DIR.toString();
421
+ if (!fs.existsSync(path.join(root, "version.json")))
422
+ return;
423
+ try {
424
+ for (const name of fs.readdirSync(installDir)) {
425
+ if (!SHARED_ENTRIES.has(name)) {
426
+ fs.rmSync(path.join(root, name), { recursive: true, force: true });
427
+ }
305
428
  }
306
429
  }
307
- else if (fs.existsSync(INSTALL_DIR) &&
308
- Version.isSupportedPath(INSTALL_DIR)) {
309
- return INSTALL_DIR;
430
+ catch (e) {
431
+ // The new install is complete; a leftover (e.g. a file still in use on Windows) must not fail it.
432
+ console.warn(`Failed to remove the previous install at ${root}: ${e}`);
310
433
  }
311
- else {
312
- if (!downloadIfMissing) {
313
- throw new UnsupportedVersion("Camoufox executable is outdated.");
314
- }
434
+ }
435
+ /**
436
+ * The install a launch uses: the pinned (or explicitly chosen) build from browsers/,
437
+ * else a flat install of an older release at the root of INSTALL_DIR.
438
+ */
439
+ function activeInstallDir() {
440
+ return getActivePath() ?? INSTALL_DIR.toString();
441
+ }
442
+ export function installedVerStr() {
443
+ return Version.fromPath(activeInstallDir()).fullString;
444
+ }
445
+ /**
446
+ * @param _downloadIfMissing Ignored, downloads happen in {@link ensureCamoufoxInstalled}.
447
+ */
448
+ export function camoufoxPath(_downloadIfMissing = true) {
449
+ const installDir = activeInstallDir();
450
+ if (!fs.existsSync(path.join(installDir, "version.json"))) {
451
+ const pin = effectivePin(loadConfig());
452
+ throw new CamoufoxNotInstalled(`Camoufox${pin ? ` v${pinSpec(pin)}` : ""} is not installed at ${INSTALL_DIR}. Please run \`camoufox fetch\` to install.`);
315
453
  }
316
- // Install and recheck
317
- const fetcher = new CamoufoxFetcher();
318
- fetcher.install().then(() => camoufoxPath());
319
- return INSTALL_DIR;
454
+ if (!Version.isSupportedPath(installDir)) {
455
+ throw new UnsupportedVersion(`Camoufox v${installedVerStr()} is not supported by this library (supported range: ${SUPPORTED_RANGE}). Please run \`camoufox fetch\` to install a supported version.`);
456
+ }
457
+ return installDir;
458
+ }
459
+ let pendingInstall;
460
+ /**
461
+ * Installs the pinned build when no supported install is available, as the Python
462
+ * library does on launch. An explicitly chosen build is never replaced.
463
+ */
464
+ export async function ensureCamoufoxInstalled() {
465
+ if (!effectivePin(loadConfig()))
466
+ return;
467
+ const installDir = activeInstallDir();
468
+ if (fs.existsSync(path.join(installDir, "version.json")) &&
469
+ Version.isSupportedPath(installDir)) {
470
+ return;
471
+ }
472
+ pendingInstall ??= new CamoufoxFetcher().install().finally(() => {
473
+ pendingInstall = undefined;
474
+ });
475
+ await pendingInstall;
320
476
  }
321
477
  export function getPath(file) {
322
478
  if (OS_NAME === "mac") {
@@ -378,6 +534,20 @@ export async function webdl(url, desc = "", bar = true, buffer = null, { retries
378
534
  }
379
535
  return Buffer.concat(chunks);
380
536
  }
537
+ async function verifySha256(file, expected, desc) {
538
+ if (!expected) {
539
+ console.warn(`No sha256 published for ${desc}, skipping verification.`);
540
+ return;
541
+ }
542
+ const hash = createHash("sha256");
543
+ for await (const chunk of fs.createReadStream(file)) {
544
+ hash.update(chunk);
545
+ }
546
+ const actual = hash.digest("hex");
547
+ if (actual !== expected.toLowerCase()) {
548
+ throw new CorruptedDownload(`Checksum mismatch for ${desc}: expected sha256 ${expected.toLowerCase()}, got ${actual}.`);
549
+ }
550
+ }
381
551
  export async function unzip(zipFile, extractPath, desc, bar = true) {
382
552
  const zip = new AdmZip(zipFile);
383
553
  const zipEntries = zip.getEntries();
package/dist/utils.js CHANGED
@@ -10,7 +10,7 @@ import { fromBrowserforge, generateFingerprint, SUPPORTED_OS, } from "./fingerpr
10
10
  import { publicIP, validIPv4, validIPv6 } from "./ip.js";
11
11
  import { geoipAllowed, getGeolocation, handleLocales } from "./locale.js";
12
12
  import FONTS from "./mappings/fonts.config.js";
13
- import { getPath, installedVerStr, launchPath, OS_NAME } from "./pkgman.js";
13
+ import { ensureCamoufoxInstalled, getPath, installedVerStr, launchPath, OS_NAME, } from "./pkgman.js";
14
14
  import { LeakWarning } from "./warnings.js";
15
15
  import { sampleWebGL } from "./webgl/sample.js";
16
16
  // Camoufox preferences to cache previous pages and requests
@@ -381,6 +381,10 @@ export async function launchOptions({ config, os, block_images, block_webrtc, bl
381
381
  if (!operatingSystems && webgl_config) {
382
382
  throw new Error("OS must be set when using webgl_config");
383
383
  }
384
+ if (!executable_path &&
385
+ !getAsBooleanFromENV("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", false)) {
386
+ await ensureCamoufoxInstalled();
387
+ }
384
388
  // Add the default addons
385
389
  await addDefaultAddons(addons, exclude_addons);
386
390
  // Confirm all addon paths are valid
@@ -454,8 +458,10 @@ export async function launchOptions({ config, os, block_images, block_webrtc, bl
454
458
  // Set geolocation
455
459
  if (geoip) {
456
460
  geoipAllowed();
457
- // Find the user's IP address
458
- geoip = await publicIP(proxyUrl?.href);
461
+ // Use provided IP directly, or resolve the public IP via the proxy if provided
462
+ if (typeof geoip !== "string") {
463
+ geoip = await publicIP(proxyUrl?.href);
464
+ }
459
465
  // Spoof WebRTC if not blocked
460
466
  if (!block_webrtc) {
461
467
  if (validIPv4(geoip)) {
@@ -1,5 +1,5 @@
1
1
  import { execFileSync, spawn } from "node:child_process";
2
- import { accessSync, constants as fsConstants } from "node:fs";
2
+ import { accessSync, constants as fsConstants, unlinkSync } from "node:fs";
3
3
  import { CannotExecuteXvfb, CannotFindXvfb, VirtualDisplayNotSupported, } from "./exceptions.js";
4
4
  import { OS_NAME } from "./pkgman.js";
5
5
  // Safe timeout for xvfb writing display num, prevents infinite hang
@@ -116,12 +116,28 @@ export class VirtualDisplay {
116
116
  return `:${this._display}`;
117
117
  }
118
118
  kill() {
119
- if (this.proc && this.proc.exitCode === null && !this.proc.killed) {
120
- if (this.debug) {
121
- console.log("Terminating virtual display:", this._display);
122
- }
123
- this.proc.kill();
119
+ const proc = this.proc;
120
+ const display = this._display;
121
+ if (!proc || proc.exitCode !== null || proc.killed)
122
+ return;
123
+ if (this.debug) {
124
+ console.log("Terminating virtual display:", display);
124
125
  }
126
+ proc.once("exit", () => {
127
+ try {
128
+ unlinkSync(`/tmp/.X${display}-lock`);
129
+ }
130
+ catch {
131
+ // already gone
132
+ }
133
+ try {
134
+ unlinkSync(`/tmp/.X11-unix/X${display}`);
135
+ }
136
+ catch {
137
+ // already gone
138
+ }
139
+ });
140
+ proc.kill("SIGKILL");
125
141
  }
126
142
  static assert_linux() {
127
143
  if (OS_NAME !== "lin") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "camoufox-js",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "bin": "dist/__main__.js",
@@ -44,13 +44,13 @@
44
44
  "@types/language-tags": "^1.0.4",
45
45
  "@types/node": "^24.0.0",
46
46
  "@types/xml2js": "^0.4.14",
47
- "playwright-core": "<1.61.0",
47
+ "playwright-core": "<1.63.0",
48
48
  "rimraf": "^6.0.1",
49
49
  "typescript": "^5.8.3",
50
50
  "vitest": "^4.0.0"
51
51
  },
52
52
  "peerDependencies": {
53
- "playwright-core": "<1.61.0"
53
+ "playwright-core": "<1.63.0"
54
54
  },
55
55
  "devEngines": {
56
56
  "packageManager": {