@phi-code-admin/camofox-browser 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/AGENTS.md +571 -571
  2. package/Dockerfile +86 -86
  3. package/LICENSE +21 -21
  4. package/README.md +691 -691
  5. package/camofox.config.json +10 -10
  6. package/lib/auth.js +134 -134
  7. package/lib/camoufox-executable.js +189 -189
  8. package/lib/config.js +153 -153
  9. package/lib/cookies.js +119 -119
  10. package/lib/downloads.js +168 -168
  11. package/lib/extract.js +74 -74
  12. package/lib/fly.js +54 -54
  13. package/lib/images.js +88 -88
  14. package/lib/inflight.js +16 -16
  15. package/lib/launcher.js +47 -47
  16. package/lib/macros.js +31 -31
  17. package/lib/metrics.js +184 -184
  18. package/lib/openapi.js +105 -105
  19. package/lib/persistence.js +89 -89
  20. package/lib/plugins.js +178 -175
  21. package/lib/proxy.js +277 -277
  22. package/lib/reporter.js +1102 -1102
  23. package/lib/request-utils.js +59 -59
  24. package/lib/resources.js +76 -76
  25. package/lib/snapshot.js +41 -41
  26. package/lib/tmp-cleanup.js +108 -108
  27. package/lib/tracing.js +137 -137
  28. package/openclaw.plugin.json +268 -268
  29. package/package.json +148 -148
  30. package/plugin.ts +758 -758
  31. package/plugins/persistence/AGENTS.md +37 -37
  32. package/plugins/persistence/README.md +48 -48
  33. package/plugins/persistence/index.js +124 -124
  34. package/plugins/vnc/AGENTS.md +42 -42
  35. package/plugins/vnc/README.md +165 -165
  36. package/plugins/vnc/apt.txt +7 -7
  37. package/plugins/vnc/index.js +142 -142
  38. package/plugins/vnc/spawn.js +8 -8
  39. package/plugins/vnc/vnc-launcher.js +64 -64
  40. package/plugins/vnc/vnc-watcher.sh +82 -82
  41. package/plugins/youtube/AGENTS.md +25 -25
  42. package/plugins/youtube/apt.txt +1 -1
  43. package/plugins/youtube/index.js +206 -206
  44. package/plugins/youtube/post-install.sh +5 -5
  45. package/plugins/youtube/youtube.js +301 -301
  46. package/run.sh +37 -37
  47. package/scripts/exec.js +8 -8
  48. package/scripts/generate-openapi.js +24 -24
  49. package/scripts/install-plugin-deps.sh +63 -63
  50. package/scripts/plugin.js +342 -342
  51. package/scripts/sync-version.js +25 -25
  52. package/server.js +6062 -6059
  53. package/tsconfig.json +12 -12
@@ -1,10 +1,10 @@
1
- {
2
- "id": "camofox-browser",
3
- "name": "Camofox Browser",
4
- "version": "1.6.0",
5
- "plugins": {
6
- "youtube": { "enabled": true },
7
- "persistence": { "enabled": true },
8
- "vnc": { "resolution": "1920x1080" }
9
- }
10
- }
1
+ {
2
+ "id": "camofox-browser",
3
+ "name": "Camofox Browser",
4
+ "version": "1.6.0",
5
+ "plugins": {
6
+ "youtube": { "enabled": true },
7
+ "persistence": { "enabled": true },
8
+ "vnc": { "resolution": "1920x1080" }
9
+ }
10
+ }
package/lib/auth.js CHANGED
@@ -1,134 +1,134 @@
1
- /**
2
- * Shared auth middleware for camofox-browser.
3
- *
4
- * Extracts the duplicated auth pattern from cookie/storage_state endpoints
5
- * into a reusable Express middleware factory.
6
- *
7
- * Policy (requireAuth / per-route):
8
- * - If CAMOFOX_API_KEY is set, require Bearer token match (timing-safe).
9
- * - If CAMOFOX_ACCESS_KEY is set, also accept it as an alternative (superkey).
10
- * - If neither key set and NODE_ENV !== production, allow loopback (127.0.0.1 / ::1).
11
- * - Otherwise, reject.
12
- *
13
- * Policy (accessKeyMiddleware / global):
14
- * - If CAMOFOX_ACCESS_KEY is set, require Bearer match on all routes except
15
- * /health, cookie import (when CAMOFOX_API_KEY set), and /stop (when CAMOFOX_ADMIN_KEY set).
16
- * - If not set, pass through (backward-compatible).
17
- */
18
-
19
- import crypto from 'crypto';
20
-
21
- /**
22
- * Timing-safe string comparison.
23
- */
24
- function timingSafeCompare(a, b) {
25
- if (typeof a !== 'string' || typeof b !== 'string') return false;
26
- const bufA = Buffer.from(a);
27
- const bufB = Buffer.from(b);
28
- if (bufA.length !== bufB.length) {
29
- // Compare against self to burn constant time, then return false
30
- crypto.timingSafeEqual(bufA, bufA);
31
- return false;
32
- }
33
- return crypto.timingSafeEqual(bufA, bufB);
34
- }
35
-
36
- /**
37
- * Check if an address is loopback.
38
- */
39
- function isLoopbackAddress(address) {
40
- if (!address) return false;
41
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
42
- }
43
-
44
- /**
45
- * Create an Express middleware that enforces API key auth.
46
- *
47
- * Accepts CAMOFOX_API_KEY as primary token. When CAMOFOX_ACCESS_KEY is also
48
- * configured, it is accepted as an alternative ("superkey") so that routes
49
- * gated by both the global access-key middleware AND this per-route middleware
50
- * don't require two different tokens in a single Authorization header.
51
- *
52
- * @param {object} config - Must have { apiKey, nodeEnv }; optionally { accessKey }
53
- * @param {object} [options]
54
- * @param {string} [options.errorMessage] - Custom error message when rejecting unauthenticated requests
55
- * @returns {function} Express middleware (req, res, next)
56
- */
57
- export function requireAuth(config, options = {}) {
58
- const errorMessage = options.errorMessage ||
59
- 'This endpoint requires CAMOFOX_API_KEY except for loopback requests in non-production environments.';
60
-
61
- return function requireAuthCheck(req, res, next) {
62
- const auth = String(req.headers['authorization'] || '');
63
- const match = auth.match(/^Bearer\s+(.+)$/i);
64
- const token = match ? match[1]?.trim() : null;
65
-
66
- // Accept API key
67
- if (config.apiKey && token && timingSafeCompare(token, config.apiKey)) {
68
- return next();
69
- }
70
-
71
- // Accept access key as alternative (superkey)
72
- if (config.accessKey && token && timingSafeCompare(token, config.accessKey)) {
73
- return next();
74
- }
75
-
76
- // If any key is configured, a valid token was required -- reject
77
- if (config.apiKey || config.accessKey) {
78
- return res.status(403).json({ error: 'Forbidden' });
79
- }
80
-
81
- // No keys configured -- allow loopback in non-production
82
- const remoteAddress = req.socket?.remoteAddress || '';
83
- const allowUnauthedLocal = config.nodeEnv !== 'production' && isLoopbackAddress(remoteAddress);
84
- if (!allowUnauthedLocal) {
85
- return res.status(403).json({ error: errorMessage });
86
- }
87
-
88
- next();
89
- };
90
- }
91
-
92
- /**
93
- * Global access-key middleware factory.
94
- *
95
- * When CAMOFOX_ACCESS_KEY is set, requires `Authorization: Bearer <key>` on
96
- * every route except:
97
- * - GET /health (Docker/Fly healthcheck)
98
- * - POST /sessions/:userId/cookies (only when CAMOFOX_API_KEY is also set -- has its own gate)
99
- * - POST /stop (only when CAMOFOX_ADMIN_KEY is also set -- has its own gate)
100
- *
101
- * When a route's dedicated key is NOT configured, the access-key middleware
102
- * does NOT exempt it -- defense-in-depth prevents unprotected endpoints.
103
- *
104
- * When CAMOFOX_ACCESS_KEY is not set, passes through (backward-compatible).
105
- *
106
- * @param {object} config - Must have { accessKey }; optionally { apiKey, adminKey }
107
- * @returns {function} Express middleware (req, res, next)
108
- */
109
- export function accessKeyMiddleware(config) {
110
- return function accessKeyCheck(req, res, next) {
111
- if (!config.accessKey) return next();
112
-
113
- // Exempt healthcheck
114
- if (req.path === '/health') return next();
115
-
116
- // Exempt routes with their own dedicated auth -- but only when their key is configured.
117
- // If the dedicated key is NOT set, the access key gates the route (defense-in-depth).
118
- if (config.apiKey && req.method === 'POST' && /^\/sessions\/[^/]+\/cookies$/.test(req.path)) return next();
119
- if (config.adminKey && req.method === 'POST' && req.path === '/stop') return next();
120
-
121
- const auth = String(req.headers['authorization'] || '');
122
- const match = auth.match(/^Bearer\s+(.+)$/i);
123
- const token = match ? match[1]?.trim() : null;
124
- if (!token || !timingSafeCompare(token, config.accessKey)) {
125
- return res.status(401)
126
- .set('WWW-Authenticate', 'Bearer realm="camofox"')
127
- .json({ error: 'Unauthorized' });
128
- }
129
- next();
130
- };
131
- }
132
-
133
- // Re-export utilities so server.js can still use them directly
134
- export { timingSafeCompare, isLoopbackAddress };
1
+ /**
2
+ * Shared auth middleware for camofox-browser.
3
+ *
4
+ * Extracts the duplicated auth pattern from cookie/storage_state endpoints
5
+ * into a reusable Express middleware factory.
6
+ *
7
+ * Policy (requireAuth / per-route):
8
+ * - If CAMOFOX_API_KEY is set, require Bearer token match (timing-safe).
9
+ * - If CAMOFOX_ACCESS_KEY is set, also accept it as an alternative (superkey).
10
+ * - If neither key set and NODE_ENV !== production, allow loopback (127.0.0.1 / ::1).
11
+ * - Otherwise, reject.
12
+ *
13
+ * Policy (accessKeyMiddleware / global):
14
+ * - If CAMOFOX_ACCESS_KEY is set, require Bearer match on all routes except
15
+ * /health, cookie import (when CAMOFOX_API_KEY set), and /stop (when CAMOFOX_ADMIN_KEY set).
16
+ * - If not set, pass through (backward-compatible).
17
+ */
18
+
19
+ import crypto from 'crypto';
20
+
21
+ /**
22
+ * Timing-safe string comparison.
23
+ */
24
+ function timingSafeCompare(a, b) {
25
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
26
+ const bufA = Buffer.from(a);
27
+ const bufB = Buffer.from(b);
28
+ if (bufA.length !== bufB.length) {
29
+ // Compare against self to burn constant time, then return false
30
+ crypto.timingSafeEqual(bufA, bufA);
31
+ return false;
32
+ }
33
+ return crypto.timingSafeEqual(bufA, bufB);
34
+ }
35
+
36
+ /**
37
+ * Check if an address is loopback.
38
+ */
39
+ function isLoopbackAddress(address) {
40
+ if (!address) return false;
41
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
42
+ }
43
+
44
+ /**
45
+ * Create an Express middleware that enforces API key auth.
46
+ *
47
+ * Accepts CAMOFOX_API_KEY as primary token. When CAMOFOX_ACCESS_KEY is also
48
+ * configured, it is accepted as an alternative ("superkey") so that routes
49
+ * gated by both the global access-key middleware AND this per-route middleware
50
+ * don't require two different tokens in a single Authorization header.
51
+ *
52
+ * @param {object} config - Must have { apiKey, nodeEnv }; optionally { accessKey }
53
+ * @param {object} [options]
54
+ * @param {string} [options.errorMessage] - Custom error message when rejecting unauthenticated requests
55
+ * @returns {function} Express middleware (req, res, next)
56
+ */
57
+ export function requireAuth(config, options = {}) {
58
+ const errorMessage = options.errorMessage ||
59
+ 'This endpoint requires CAMOFOX_API_KEY except for loopback requests in non-production environments.';
60
+
61
+ return function requireAuthCheck(req, res, next) {
62
+ const auth = String(req.headers['authorization'] || '');
63
+ const match = auth.match(/^Bearer\s+(.+)$/i);
64
+ const token = match ? match[1]?.trim() : null;
65
+
66
+ // Accept API key
67
+ if (config.apiKey && token && timingSafeCompare(token, config.apiKey)) {
68
+ return next();
69
+ }
70
+
71
+ // Accept access key as alternative (superkey)
72
+ if (config.accessKey && token && timingSafeCompare(token, config.accessKey)) {
73
+ return next();
74
+ }
75
+
76
+ // If any key is configured, a valid token was required -- reject
77
+ if (config.apiKey || config.accessKey) {
78
+ return res.status(403).json({ error: 'Forbidden' });
79
+ }
80
+
81
+ // No keys configured -- allow loopback in non-production
82
+ const remoteAddress = req.socket?.remoteAddress || '';
83
+ const allowUnauthedLocal = config.nodeEnv !== 'production' && isLoopbackAddress(remoteAddress);
84
+ if (!allowUnauthedLocal) {
85
+ return res.status(403).json({ error: errorMessage });
86
+ }
87
+
88
+ next();
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Global access-key middleware factory.
94
+ *
95
+ * When CAMOFOX_ACCESS_KEY is set, requires `Authorization: Bearer <key>` on
96
+ * every route except:
97
+ * - GET /health (Docker/Fly healthcheck)
98
+ * - POST /sessions/:userId/cookies (only when CAMOFOX_API_KEY is also set -- has its own gate)
99
+ * - POST /stop (only when CAMOFOX_ADMIN_KEY is also set -- has its own gate)
100
+ *
101
+ * When a route's dedicated key is NOT configured, the access-key middleware
102
+ * does NOT exempt it -- defense-in-depth prevents unprotected endpoints.
103
+ *
104
+ * When CAMOFOX_ACCESS_KEY is not set, passes through (backward-compatible).
105
+ *
106
+ * @param {object} config - Must have { accessKey }; optionally { apiKey, adminKey }
107
+ * @returns {function} Express middleware (req, res, next)
108
+ */
109
+ export function accessKeyMiddleware(config) {
110
+ return function accessKeyCheck(req, res, next) {
111
+ if (!config.accessKey) return next();
112
+
113
+ // Exempt healthcheck
114
+ if (req.path === '/health') return next();
115
+
116
+ // Exempt routes with their own dedicated auth -- but only when their key is configured.
117
+ // If the dedicated key is NOT set, the access key gates the route (defense-in-depth).
118
+ if (config.apiKey && req.method === 'POST' && /^\/sessions\/[^/]+\/cookies$/.test(req.path)) return next();
119
+ if (config.adminKey && req.method === 'POST' && req.path === '/stop') return next();
120
+
121
+ const auth = String(req.headers['authorization'] || '');
122
+ const match = auth.match(/^Bearer\s+(.+)$/i);
123
+ const token = match ? match[1]?.trim() : null;
124
+ if (!token || !timingSafeCompare(token, config.accessKey)) {
125
+ return res.status(401)
126
+ .set('WWW-Authenticate', 'Bearer realm="camofox"')
127
+ .json({ error: 'Unauthorized' });
128
+ }
129
+ next();
130
+ };
131
+ }
132
+
133
+ // Re-export utilities so server.js can still use them directly
134
+ export { timingSafeCompare, isLoopbackAddress };
@@ -1,189 +1,189 @@
1
- import crypto from 'crypto';
2
- import {
3
- accessSync,
4
- constants,
5
- existsSync,
6
- mkdirSync,
7
- readdirSync,
8
- readFileSync,
9
- realpathSync,
10
- rmSync,
11
- statSync,
12
- symlinkSync,
13
- writeFileSync,
14
- } from 'fs';
15
- import { dirname, join, resolve } from 'path';
16
- import { platform, tmpdir } from 'os';
17
-
18
- function assertExecutable(path) {
19
- const stat = statSync(path);
20
- if (!stat.isFile() && !stat.isSymbolicLink()) {
21
- throw new Error(`Camoufox executable is not a file: ${path}`);
22
- }
23
- if (platform() !== 'win32') accessSync(path, constants.X_OK);
24
- }
25
-
26
- function nixStoreRoot(path) {
27
- const match = path.match(/^\/nix\/store\/[^/]+/);
28
- return match?.[0] || null;
29
- }
30
-
31
- function collectDirs(root, maxDepth = 4) {
32
- const dirs = [];
33
- const queue = [{ dir: root, depth: 0 }];
34
- const seen = new Set();
35
-
36
- while (queue.length > 0) {
37
- const { dir, depth } = queue.shift();
38
- if (seen.has(dir)) continue;
39
- seen.add(dir);
40
- dirs.push(dir);
41
- if (depth >= maxDepth) continue;
42
-
43
- let entries = [];
44
- try {
45
- entries = readdirSync(dir, { withFileTypes: true });
46
- } catch {
47
- continue;
48
- }
49
- for (const entry of entries) {
50
- if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
51
- queue.push({ dir: join(dir, entry.name), depth: depth + 1 });
52
- }
53
- }
54
-
55
- return dirs;
56
- }
57
-
58
- function findResourceDir(executablePath) {
59
- const resolvedPath = realpathSync(executablePath);
60
- const directDirs = [
61
- dirname(executablePath),
62
- dirname(resolvedPath),
63
- ];
64
-
65
- const storeRoot = nixStoreRoot(resolvedPath) || nixStoreRoot(executablePath);
66
- const likelyDirs = storeRoot
67
- ? [
68
- storeRoot,
69
- join(storeRoot, 'lib', 'camoufox'),
70
- join(storeRoot, 'libexec', 'camoufox'),
71
- join(storeRoot, 'share', 'camoufox'),
72
- join(storeRoot, 'opt', 'camoufox'),
73
- ]
74
- : [];
75
-
76
- const allCandidates = [...directDirs, ...likelyDirs];
77
- for (const dir of allCandidates) {
78
- if (existsSync(join(dir, 'properties.json'))) return dir;
79
- }
80
-
81
- if (storeRoot) {
82
- for (const dir of collectDirs(storeRoot)) {
83
- if (existsSync(join(dir, 'properties.json'))) return dir;
84
- }
85
- }
86
-
87
- return null;
88
- }
89
-
90
- function ensureSymlink(target, linkPath, type = 'file') {
91
- rmSync(linkPath, { force: true, recursive: true });
92
- symlinkSync(target, linkPath, platform() === 'win32' && type === 'dir' ? 'junction' : type);
93
- }
94
-
95
- function shimRootFor(executablePath, resourceDir) {
96
- const key = crypto
97
- .createHash('sha256')
98
- .update(`${realpathSync(executablePath)}\n${realpathSync(resourceDir)}`)
99
- .digest('hex')
100
- .slice(0, 16);
101
- return join(tmpdir(), 'camofox-browser-external-camoufox', key);
102
- }
103
-
104
- function ensureLaunchShim(executablePath, resourceDir) {
105
- const shimRoot = shimRootFor(executablePath, resourceDir);
106
- mkdirSync(shimRoot, { recursive: true });
107
-
108
- const shimExecutable = join(shimRoot, platform() === 'win32' ? 'camoufox.exe' : 'camoufox-bin');
109
- ensureSymlink(realpathSync(executablePath), shimExecutable);
110
-
111
- for (const name of ['properties.json', 'version.json']) {
112
- const target = join(resourceDir, name);
113
- if (existsSync(target)) ensureSymlink(realpathSync(target), join(shimRoot, name));
114
- }
115
-
116
- const fontconfig = join(resourceDir, 'fontconfig');
117
- if (existsSync(fontconfig)) ensureSymlink(realpathSync(fontconfig), join(shimRoot, 'fontconfig'), 'dir');
118
-
119
- return shimExecutable;
120
- }
121
-
122
- function camoufoxLaunchFileName() {
123
- if (platform() === 'win32') return 'camoufox.exe';
124
- if (platform() === 'darwin') return join('Camoufox.app', 'Contents', 'MacOS', 'camoufox');
125
- return 'camoufox-bin';
126
- }
127
-
128
- function ensureCamoufoxJsCache(resourceDir, cacheDir, executablePath) {
129
- const cacheVersion = join(cacheDir, 'version.json');
130
- const cacheFontconfig = join(cacheDir, 'fontconfig');
131
- const cacheProperties = join(cacheDir, 'properties.json');
132
- const cacheExecutable = join(cacheDir, camoufoxLaunchFileName());
133
-
134
- if (
135
- existsSync(cacheVersion) &&
136
- existsSync(cacheFontconfig) &&
137
- existsSync(cacheProperties) &&
138
- existsSync(cacheExecutable)
139
- ) {
140
- return;
141
- }
142
-
143
- const versionFile = join(resourceDir, 'version.json');
144
- const propertiesFile = join(resourceDir, 'properties.json');
145
- const fontconfig = join(resourceDir, 'fontconfig');
146
- if (!existsSync(versionFile) || !existsSync(propertiesFile) || !existsSync(fontconfig)) {
147
- throw new Error(
148
- `External Camoufox bundle at ${resourceDir} must include properties.json, version.json, and fontconfig/ for camoufox-js compatibility`
149
- );
150
- }
151
-
152
- mkdirSync(cacheDir, { recursive: true });
153
- if (!existsSync(cacheVersion)) {
154
- writeFileSync(cacheVersion, readFileSync(versionFile));
155
- }
156
- if (!existsSync(cacheProperties)) {
157
- ensureSymlink(realpathSync(propertiesFile), cacheProperties);
158
- }
159
- if (!existsSync(cacheFontconfig)) {
160
- ensureSymlink(realpathSync(fontconfig), cacheFontconfig, 'dir');
161
- }
162
- if (!existsSync(cacheExecutable)) {
163
- mkdirSync(dirname(cacheExecutable), { recursive: true });
164
- ensureSymlink(realpathSync(executablePath), cacheExecutable);
165
- }
166
- }
167
-
168
- export function prepareExternalCamoufoxExecutable(executablePath, { cacheDir } = {}) {
169
- if (!executablePath) return null;
170
- if (!cacheDir) throw new Error('cacheDir is required for external Camoufox executable preparation');
171
-
172
- const resolvedExecutable = resolve(executablePath);
173
- assertExecutable(resolvedExecutable);
174
-
175
- const resourceDir = findResourceDir(resolvedExecutable);
176
- if (!resourceDir) {
177
- throw new Error(
178
- `Could not find Camoufox resources for ${resolvedExecutable}. ` +
179
- 'Point the executable override at a Camoufox bundle that includes properties.json.'
180
- );
181
- }
182
-
183
- ensureCamoufoxJsCache(resourceDir, cacheDir, resolvedExecutable);
184
-
185
- return {
186
- executablePath: ensureLaunchShim(resolvedExecutable, resourceDir),
187
- resourceDir,
188
- };
189
- }
1
+ import crypto from 'crypto';
2
+ import {
3
+ accessSync,
4
+ constants,
5
+ existsSync,
6
+ mkdirSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ realpathSync,
10
+ rmSync,
11
+ statSync,
12
+ symlinkSync,
13
+ writeFileSync,
14
+ } from 'fs';
15
+ import { dirname, join, resolve } from 'path';
16
+ import { platform, tmpdir } from 'os';
17
+
18
+ function assertExecutable(path) {
19
+ const stat = statSync(path);
20
+ if (!stat.isFile() && !stat.isSymbolicLink()) {
21
+ throw new Error(`Camoufox executable is not a file: ${path}`);
22
+ }
23
+ if (platform() !== 'win32') accessSync(path, constants.X_OK);
24
+ }
25
+
26
+ function nixStoreRoot(path) {
27
+ const match = path.match(/^\/nix\/store\/[^/]+/);
28
+ return match?.[0] || null;
29
+ }
30
+
31
+ function collectDirs(root, maxDepth = 4) {
32
+ const dirs = [];
33
+ const queue = [{ dir: root, depth: 0 }];
34
+ const seen = new Set();
35
+
36
+ while (queue.length > 0) {
37
+ const { dir, depth } = queue.shift();
38
+ if (seen.has(dir)) continue;
39
+ seen.add(dir);
40
+ dirs.push(dir);
41
+ if (depth >= maxDepth) continue;
42
+
43
+ let entries = [];
44
+ try {
45
+ entries = readdirSync(dir, { withFileTypes: true });
46
+ } catch {
47
+ continue;
48
+ }
49
+ for (const entry of entries) {
50
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
51
+ queue.push({ dir: join(dir, entry.name), depth: depth + 1 });
52
+ }
53
+ }
54
+
55
+ return dirs;
56
+ }
57
+
58
+ function findResourceDir(executablePath) {
59
+ const resolvedPath = realpathSync(executablePath);
60
+ const directDirs = [
61
+ dirname(executablePath),
62
+ dirname(resolvedPath),
63
+ ];
64
+
65
+ const storeRoot = nixStoreRoot(resolvedPath) || nixStoreRoot(executablePath);
66
+ const likelyDirs = storeRoot
67
+ ? [
68
+ storeRoot,
69
+ join(storeRoot, 'lib', 'camoufox'),
70
+ join(storeRoot, 'libexec', 'camoufox'),
71
+ join(storeRoot, 'share', 'camoufox'),
72
+ join(storeRoot, 'opt', 'camoufox'),
73
+ ]
74
+ : [];
75
+
76
+ const allCandidates = [...directDirs, ...likelyDirs];
77
+ for (const dir of allCandidates) {
78
+ if (existsSync(join(dir, 'properties.json'))) return dir;
79
+ }
80
+
81
+ if (storeRoot) {
82
+ for (const dir of collectDirs(storeRoot)) {
83
+ if (existsSync(join(dir, 'properties.json'))) return dir;
84
+ }
85
+ }
86
+
87
+ return null;
88
+ }
89
+
90
+ function ensureSymlink(target, linkPath, type = 'file') {
91
+ rmSync(linkPath, { force: true, recursive: true });
92
+ symlinkSync(target, linkPath, platform() === 'win32' && type === 'dir' ? 'junction' : type);
93
+ }
94
+
95
+ function shimRootFor(executablePath, resourceDir) {
96
+ const key = crypto
97
+ .createHash('sha256')
98
+ .update(`${realpathSync(executablePath)}\n${realpathSync(resourceDir)}`)
99
+ .digest('hex')
100
+ .slice(0, 16);
101
+ return join(tmpdir(), 'camofox-browser-external-camoufox', key);
102
+ }
103
+
104
+ function ensureLaunchShim(executablePath, resourceDir) {
105
+ const shimRoot = shimRootFor(executablePath, resourceDir);
106
+ mkdirSync(shimRoot, { recursive: true });
107
+
108
+ const shimExecutable = join(shimRoot, platform() === 'win32' ? 'camoufox.exe' : 'camoufox-bin');
109
+ ensureSymlink(realpathSync(executablePath), shimExecutable);
110
+
111
+ for (const name of ['properties.json', 'version.json']) {
112
+ const target = join(resourceDir, name);
113
+ if (existsSync(target)) ensureSymlink(realpathSync(target), join(shimRoot, name));
114
+ }
115
+
116
+ const fontconfig = join(resourceDir, 'fontconfig');
117
+ if (existsSync(fontconfig)) ensureSymlink(realpathSync(fontconfig), join(shimRoot, 'fontconfig'), 'dir');
118
+
119
+ return shimExecutable;
120
+ }
121
+
122
+ function camoufoxLaunchFileName() {
123
+ if (platform() === 'win32') return 'camoufox.exe';
124
+ if (platform() === 'darwin') return join('Camoufox.app', 'Contents', 'MacOS', 'camoufox');
125
+ return 'camoufox-bin';
126
+ }
127
+
128
+ function ensureCamoufoxJsCache(resourceDir, cacheDir, executablePath) {
129
+ const cacheVersion = join(cacheDir, 'version.json');
130
+ const cacheFontconfig = join(cacheDir, 'fontconfig');
131
+ const cacheProperties = join(cacheDir, 'properties.json');
132
+ const cacheExecutable = join(cacheDir, camoufoxLaunchFileName());
133
+
134
+ if (
135
+ existsSync(cacheVersion) &&
136
+ existsSync(cacheFontconfig) &&
137
+ existsSync(cacheProperties) &&
138
+ existsSync(cacheExecutable)
139
+ ) {
140
+ return;
141
+ }
142
+
143
+ const versionFile = join(resourceDir, 'version.json');
144
+ const propertiesFile = join(resourceDir, 'properties.json');
145
+ const fontconfig = join(resourceDir, 'fontconfig');
146
+ if (!existsSync(versionFile) || !existsSync(propertiesFile) || !existsSync(fontconfig)) {
147
+ throw new Error(
148
+ `External Camoufox bundle at ${resourceDir} must include properties.json, version.json, and fontconfig/ for camoufox-js compatibility`
149
+ );
150
+ }
151
+
152
+ mkdirSync(cacheDir, { recursive: true });
153
+ if (!existsSync(cacheVersion)) {
154
+ writeFileSync(cacheVersion, readFileSync(versionFile));
155
+ }
156
+ if (!existsSync(cacheProperties)) {
157
+ ensureSymlink(realpathSync(propertiesFile), cacheProperties);
158
+ }
159
+ if (!existsSync(cacheFontconfig)) {
160
+ ensureSymlink(realpathSync(fontconfig), cacheFontconfig, 'dir');
161
+ }
162
+ if (!existsSync(cacheExecutable)) {
163
+ mkdirSync(dirname(cacheExecutable), { recursive: true });
164
+ ensureSymlink(realpathSync(executablePath), cacheExecutable);
165
+ }
166
+ }
167
+
168
+ export function prepareExternalCamoufoxExecutable(executablePath, { cacheDir } = {}) {
169
+ if (!executablePath) return null;
170
+ if (!cacheDir) throw new Error('cacheDir is required for external Camoufox executable preparation');
171
+
172
+ const resolvedExecutable = resolve(executablePath);
173
+ assertExecutable(resolvedExecutable);
174
+
175
+ const resourceDir = findResourceDir(resolvedExecutable);
176
+ if (!resourceDir) {
177
+ throw new Error(
178
+ `Could not find Camoufox resources for ${resolvedExecutable}. ` +
179
+ 'Point the executable override at a Camoufox bundle that includes properties.json.'
180
+ );
181
+ }
182
+
183
+ ensureCamoufoxJsCache(resourceDir, cacheDir, resolvedExecutable);
184
+
185
+ return {
186
+ executablePath: ensureLaunchShim(resolvedExecutable, resourceDir),
187
+ resourceDir,
188
+ };
189
+ }