@cbxss/eoka 0.0.0-stage → 0.1.0-beta.10

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 (48) hide show
  1. package/README.md +170 -2
  2. package/dist/LICENSE +21 -0
  3. package/dist/browser-install-diagnostics.d.ts +1 -0
  4. package/dist/browser-install-diagnostics.js +21 -0
  5. package/dist/browser-install-engine.d.ts +10 -0
  6. package/dist/browser-install-engine.js +286 -0
  7. package/dist/browser-install-inventory.d.ts +34 -0
  8. package/dist/browser-install-inventory.js +107 -0
  9. package/dist/browser-install-worker.d.ts +21 -0
  10. package/dist/browser-install-worker.js +65 -0
  11. package/dist/browser-install.d.ts +22 -0
  12. package/dist/browser-install.js +7 -0
  13. package/dist/browser.d.ts +62 -0
  14. package/dist/browser.js +452 -0
  15. package/dist/client.d.ts +11 -0
  16. package/dist/client.js +1 -0
  17. package/dist/cloudflare.d.ts +12 -0
  18. package/dist/cloudflare.js +19 -0
  19. package/dist/errors.d.ts +33 -0
  20. package/dist/errors.js +44 -0
  21. package/dist/generated/protocol.d.ts +4878 -0
  22. package/dist/generated/protocol.js +2 -0
  23. package/dist/generated/schema-bundle.json +23846 -0
  24. package/dist/index.d.ts +22 -0
  25. package/dist/index.js +11 -0
  26. package/dist/install-errors.d.ts +4 -0
  27. package/dist/install-errors.js +6 -0
  28. package/dist/operations.d.ts +22 -0
  29. package/dist/operations.js +87 -0
  30. package/dist/page.d.ts +107 -0
  31. package/dist/page.js +299 -0
  32. package/dist/platform.d.ts +4 -0
  33. package/dist/platform.js +27 -0
  34. package/dist/recording.d.ts +27 -0
  35. package/dist/recording.js +124 -0
  36. package/dist/release-manifest.json +101 -0
  37. package/dist/release.d.ts +36 -0
  38. package/dist/release.js +76 -0
  39. package/dist/server-binary.d.ts +12 -0
  40. package/dist/server-binary.js +130 -0
  41. package/dist/transport.d.ts +89 -0
  42. package/dist/transport.js +737 -0
  43. package/examples/capture.mjs +36 -0
  44. package/examples/consume-schema.mjs +7 -0
  45. package/examples/explicit-paths.mjs +42 -0
  46. package/examples/install-browser.mjs +20 -0
  47. package/examples/offline.mjs +20 -0
  48. package/package.json +70 -4
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # @cbxss/eoka
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js SDK for eoka, a stealth Chrome automation sidecar.
4
+
5
+ ```sh
6
+ npm install @cbxss/eoka@latest
7
+ ```
8
+
9
+ Requires Node.js 24.21+ (ESM only). Supported platforms: Linux x64/arm64 (glibc 2.35+), macOS x64/arm64, Windows x64.
10
+
11
+ ## Quick start
12
+
13
+ ```js
14
+ import { Browser } from "@cbxss/eoka";
15
+
16
+ const browser = await Browser.launch();
17
+ try {
18
+ const page = await browser.newPage("https://example.com");
19
+ console.log(await page.title());
20
+ await page.screenshotToFile({ path: "./example.png" });
21
+ } finally {
22
+ await browser.close();
23
+ }
24
+ ```
25
+
26
+ The first launch downloads a pinned Chrome for Testing build (about 200 MB) into a per-user cache. Later launches reuse it.
27
+
28
+ ## Pages
29
+
30
+ ```js
31
+ await page.goto("https://example.com/login");
32
+ await page.fill("#email", "ada@example.com");
33
+ await page.click("button[type=submit]", {
34
+ actionOptions: { expect: { kind: "url", value: "/home", contains: true } },
35
+ });
36
+
37
+ await page.waitForText("Welcome");
38
+ const heading = await page.getText("h1");
39
+ const count = await page.evaluate("()=>document.querySelectorAll('li').length");
40
+ ```
41
+
42
+ String targets are CSS selectors. An action resolves only after its result is verified. `click`, `type`, `pressKey`, `submit` and `drag` need an `expect` that describes the result.
43
+
44
+ - **Reads:** `text`, `content`, `title`, `url`, `getText`, `getAttribute`, `exists`, `evaluate`
45
+ - **Waits:** `waitFor`, `waitForVisible`, `waitForText`
46
+ - **Actions:** `goto`, `fill`, `select`, `hover`, `click`, `type`, `pressKey`, `submit`, `drag`
47
+
48
+ ## Shadow DOM and Turnstile
49
+
50
+ `page.frames()` lists every frame, including cross-origin OOPIFs. `page.clickShadow(selector, { frameId?, resolveTimeoutMs? })` searches the frame's light DOM and every shadow root (closed roots included), maps the matched node's center to viewport coordinates, and clicks with human-like movement. `resolveTimeoutMs` bounds the server-side resolution; `CallOptions.timeoutMs` remains the RPC deadline and defaults to the resolution deadline plus 10 seconds when omitted:
51
+
52
+ ```js
53
+ const challenge = (await page.frames()).find(frame =>
54
+ frame.url.includes("challenges.cloudflare.com"));
55
+ if (challenge) {
56
+ await page.clickShadow('input[type="checkbox"]', { frameId: challenge.id });
57
+ }
58
+ ```
59
+
60
+ `page.solveTurnstile({ timeoutMs })` is a best-effort helper for interactive Cloudflare challenge pages. The server finds the challenge frame, clicks the checkbox, and waits for the page to leave the challenge state, then resolves with `{ clicks, elapsedMs }` (zero clicks on a normal page). It is not a general CAPTCHA solver.
61
+
62
+ ### Automatic challenge handling
63
+
64
+ `Browser.launch({ autoSolveCloudflare: true })` (and `Browser.connect`) has the server watch every tab and solve full-page Cloudflare challenges as they appear. It does not click Turnstile widgets embedded in normal forms. The Go SDK, CLI (`--auto-solve-cloudflare`) and MCP server (`EOKA_AUTO_SOLVE_CLOUDFLARE=1`) use the same server watcher.
65
+
66
+ ```js
67
+ const browser = await Browser.launch({ autoSolveCloudflare: true });
68
+ try {
69
+ const page = await browser.newPage("https://1337x.to/");
70
+ console.log(await page.title()); // Torrent Search Engine | 1337x.to
71
+ } finally {
72
+ await browser.close();
73
+ }
74
+ ```
75
+
76
+ Tune it with `{ intervalMs, timeoutMs }` (defaults 500 and 30000). The server logs each challenge and result to its stderr. The watcher stops with `browser.close()`.
77
+
78
+ ## Screenshots and recording
79
+
80
+ ```js
81
+ const png = await page.screenshot(); // Buffer
82
+ await page.screenshot({ format: "webp", quality: 80 });
83
+ await page.screenshotToFile({ path: "./full.png", fullPage: true });
84
+
85
+ const recording = await page.record({ path: "./session.mp4" });
86
+ // ...
87
+ await recording.stop();
88
+ ```
89
+
90
+ File output never overwrites an existing file, and the directory must already exist. Recordings are silent MP4s. For screenshots larger than 16 MiB, use `screenshotToFile`.
91
+
92
+ ## Options
93
+
94
+ ```js
95
+ await Browser.launch({
96
+ headless: true, // default
97
+ sandbox: true, // default; leave it on
98
+ download: "auto", // "never" fails when Chrome isn't cached
99
+ browserCacheDir: "/opt/eoka/cache",
100
+ viewport: { width: 1280, height: 720, deviceScaleFactor: 1 },
101
+ timeoutMs: 30000,
102
+ });
103
+ ```
104
+
105
+ To install Chrome ahead of time, for example while building a Docker image:
106
+
107
+ ```js
108
+ import { installBrowser } from "@cbxss/eoka";
109
+ await installBrowser({ browserCacheDir: "/opt/eoka/cache" });
110
+ ```
111
+
112
+ To drive a Chrome you already run, use `Browser.connect({ browserWSEndpoint })`. Closing the SDK leaves that browser running.
113
+
114
+ | Environment variable | Purpose |
115
+ | --- | --- |
116
+ | `EOKA_BROWSER_CACHE_DIR` | Where Chrome is cached |
117
+ | `EOKA_RUNTIME_DIR` | Scratch directory for sessions |
118
+ | `EOKA_CHROME_PATH` | Use your own Chrome binary |
119
+ | `EOKA_SERVER_BIN` | Use your own `eoka-server` binary |
120
+ | `HTTPS_PROXY`, `NO_PROXY` | Proxy for the Chrome download |
121
+
122
+ ## Errors
123
+
124
+ Every SDK error extends `EokaError` and has a stable `code`:
125
+
126
+ ```js
127
+ import { EokaError } from "@cbxss/eoka";
128
+
129
+ try {
130
+ await page.fill("#name", "Ada");
131
+ } catch (error) {
132
+ if (error instanceof EokaError) console.error(error.code, error.message);
133
+ throw error;
134
+ }
135
+ ```
136
+
137
+ ## Linux and Docker
138
+
139
+ Chrome needs its usual system libraries even in headless mode. On Debian:
140
+
141
+ ```dockerfile
142
+ FROM node:24-trixie
143
+ RUN apt-get update && apt-get install -y --no-install-recommends \
144
+ ca-certificates fonts-liberation libasound2t64 libatk-bridge2.0-0t64 libatk1.0-0t64 \
145
+ libcairo2 libcups2t64 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0t64 libnspr4 \
146
+ libnss3 libpango-1.0-0 libssl3t64 libx11-6 libxcb1 libxcomposite1 libxdamage1 \
147
+ libxext6 libxfixes3 libxkbcommon0 libxrandr2 \
148
+ && rm -rf /var/lib/apt/lists/*
149
+ USER node
150
+ ```
151
+
152
+ Run as a non-root user. On Ubuntu 23.10 and later, AppArmor may block Chrome's sandbox; see [Chromium's AppArmor notes](https://chromium.googlesource.com/chromium/src/+/main/docs/security/apparmor-userns-restrictions.md). Alpine (musl) isn't supported.
153
+
154
+ ## Examples
155
+
156
+ ```sh
157
+ node node_modules/@cbxss/eoka/examples/install-browser.mjs
158
+ node node_modules/@cbxss/eoka/examples/offline.mjs
159
+ node node_modules/@cbxss/eoka/examples/capture.mjs ./captures
160
+ ```
161
+
162
+ ## Development
163
+
164
+ ```sh
165
+ mise install
166
+ npm ci --ignore-scripts --omit=optional
167
+ npm run build
168
+ npm test
169
+ ```
170
+
171
+ Releases are automatic: merge a version bump to `main` and approve the `npm-prerelease` deployment.
package/dist/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shrimp Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ export declare function sanitizeInstallationDiagnostic(message: string, env: NodeJS.ProcessEnv): string;
@@ -0,0 +1,21 @@
1
+ export function sanitizeInstallationDiagnostic(message, env) {
2
+ for (const [key, value] of Object.entries(env)) {
3
+ if (!/proxy/i.test(key) || !value)
4
+ continue;
5
+ message = message.replaceAll(value, '[redacted proxy]');
6
+ try {
7
+ const proxy = new URL(value);
8
+ if (proxy.username || proxy.password) {
9
+ const username = decodeURIComponent(proxy.username);
10
+ const password = decodeURIComponent(proxy.password);
11
+ const credentials = [proxy.username, proxy.password, username, password, Buffer.from(`${username}:${password}`).toString('base64')];
12
+ for (const credential of credentials) {
13
+ if (credential)
14
+ message = message.replaceAll(credential, '[redacted]');
15
+ }
16
+ }
17
+ }
18
+ catch { }
19
+ }
20
+ return message.replace(/(https?:\/\/)[^/\s@]+@/gi, '$1[redacted]@');
21
+ }
@@ -0,0 +1,10 @@
1
+ import type { ChromePlatformRelease } from './release.js';
2
+ import type { PlatformId } from './platform.js';
3
+ import type { BrowserInstallation, InstallBrowserOptions } from './browser-install.js';
4
+ export interface InstallerRelease {
5
+ platform: PlatformId;
6
+ buildId: string;
7
+ pin: ChromePlatformRelease;
8
+ }
9
+ export declare function browserCacheDirectory(options: InstallBrowserOptions): string;
10
+ export declare function createBrowserInstaller(release: InstallerRelease): (options?: InstallBrowserOptions) => Promise<BrowserInstallation>;
@@ -0,0 +1,286 @@
1
+ import { fork, spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { hostname, homedir } from 'node:os';
4
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { InstallationError } from './install-errors.js';
8
+ import { sanitizeInstallationDiagnostic } from './browser-install-diagnostics.js';
9
+ export function browserCacheDirectory(options) {
10
+ const env = options.env ?? process.env;
11
+ if (options.browserCacheDir !== undefined) {
12
+ if (!options.browserCacheDir.trim())
13
+ throw new InstallationError('InstallationFailed', 'browserCacheDir must not be empty');
14
+ return path.resolve(options.browserCacheDir);
15
+ }
16
+ if (env.EOKA_BROWSER_CACHE_DIR)
17
+ return path.resolve(env.EOKA_BROWSER_CACHE_DIR);
18
+ if (process.platform === 'darwin')
19
+ return path.join(homedir(), 'Library', 'Caches', 'eoka');
20
+ if (process.platform === 'win32')
21
+ return path.join(env.LOCALAPPDATA || path.join(homedir(), 'AppData', 'Local'), 'eoka', 'Cache');
22
+ return path.join(env.XDG_CACHE_HOME || path.join(homedir(), '.cache'), 'eoka');
23
+ }
24
+ async function processStart(pid) {
25
+ if (process.platform !== 'linux')
26
+ return null;
27
+ try {
28
+ const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
29
+ return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19] ?? null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ async function alive(pid, start) {
36
+ try {
37
+ process.kill(pid, 0);
38
+ }
39
+ catch (error) {
40
+ return error.code !== 'ESRCH';
41
+ }
42
+ if (process.platform !== 'linux')
43
+ return true;
44
+ try {
45
+ const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
46
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
47
+ return fields[0] !== 'Z' && fields[0] !== 'X' && (start === null || fields[19] === start);
48
+ }
49
+ catch (error) {
50
+ return error.code !== 'ENOENT';
51
+ }
52
+ }
53
+ async function stopWorker(child) {
54
+ if (!child.pid)
55
+ return;
56
+ if (process.platform === 'win32' && (child.exitCode !== null || child.signalCode !== null))
57
+ return;
58
+ if (process.platform === 'win32') {
59
+ await new Promise((resolve, reject) => {
60
+ const killer = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
61
+ killer.once('error', reject);
62
+ killer.once('close', code => code === 0 || child.exitCode !== null ? resolve() : reject(new Error(`taskkill failed with code ${code}`)));
63
+ });
64
+ }
65
+ else {
66
+ try {
67
+ process.kill(-child.pid, 'SIGKILL');
68
+ }
69
+ catch (error) {
70
+ if (error.code !== 'ESRCH')
71
+ throw error;
72
+ }
73
+ }
74
+ }
75
+ async function runWorker(request, options, signal, onStarted) {
76
+ signal.throwIfAborted();
77
+ const child = fork(new URL('./browser-install-worker.js', import.meta.url), [], {
78
+ env: { ...(options.env ?? process.env) },
79
+ stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
80
+ execArgv: [],
81
+ detached: process.platform !== 'win32',
82
+ });
83
+ return await new Promise((resolve, reject) => {
84
+ let result;
85
+ let failure;
86
+ let stderr = '';
87
+ let diagnosed = false;
88
+ let stopping;
89
+ let starting;
90
+ const stop = (error) => {
91
+ failure ??= error;
92
+ stopping ??= stopWorker(child).catch(cause => { failure = new InstallationError('InstallationFailed', 'Could not terminate browser installation worker', { cause }); });
93
+ };
94
+ const onAbort = () => stop(signal.reason);
95
+ signal.addEventListener('abort', onAbort, { once: true });
96
+ child.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-8192); });
97
+ child.on('message', (message) => {
98
+ if (message.type === 'progress') {
99
+ try {
100
+ if (options.onProgress)
101
+ options.onProgress({ downloadedBytes: message.downloadedBytes, totalBytes: message.totalBytes, buildId: request.buildId });
102
+ else if (!diagnosed) {
103
+ diagnosed = true;
104
+ process.stderr.write(`Downloading pinned Chrome ${request.buildId} to ${browserCacheDirectory(options)}\n`);
105
+ }
106
+ }
107
+ catch (cause) {
108
+ stop(new InstallationError('InstallationFailed', 'Browser installation progress callback failed', { cause }));
109
+ }
110
+ }
111
+ else if (message.type === 'error') {
112
+ failure ??= new InstallationError(message.code, sanitizeInstallationDiagnostic(message.message, options.env ?? process.env), { stderr: sanitizeInstallationDiagnostic(stderr, options.env ?? process.env) });
113
+ }
114
+ else if (message.type === 'result')
115
+ result = message.verified;
116
+ });
117
+ child.once('error', cause => stop(new InstallationError('InstallationFailed', 'Could not start browser installation worker', { cause })));
118
+ child.once('close', async (code) => {
119
+ signal.removeEventListener('abort', onAbort);
120
+ if (starting)
121
+ await starting;
122
+ if (stopping)
123
+ await stopping;
124
+ if (code !== 0 && !stopping) {
125
+ try {
126
+ await stopWorker(child);
127
+ }
128
+ catch (cause) {
129
+ failure ??= cause;
130
+ }
131
+ }
132
+ if (failure !== undefined)
133
+ reject(failure);
134
+ else if (code !== 0 || result === undefined)
135
+ reject(new InstallationError('InstallationFailed', `Browser installation worker exited unexpectedly (${code})`, { stderr: sanitizeInstallationDiagnostic(stderr, options.env ?? process.env) }));
136
+ else
137
+ resolve(result);
138
+ });
139
+ starting = (async () => {
140
+ try {
141
+ if (child.pid && onStarted)
142
+ await onStarted(child.pid);
143
+ signal.throwIfAborted();
144
+ child.send(request, error => { if (error)
145
+ stop(error); });
146
+ }
147
+ catch (error) {
148
+ stop(error);
149
+ }
150
+ })();
151
+ if (signal.aborted)
152
+ onAbort();
153
+ });
154
+ }
155
+ async function readOwner(file) {
156
+ try {
157
+ const value = JSON.parse(await readFile(file, 'utf8'));
158
+ if (typeof value.token !== 'string' || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.host !== 'string' || (value.ticket !== null && (!Number.isSafeInteger(value.ticket) || value.ticket <= 0)))
159
+ throw new InstallationError('InstallationFailed', `Invalid browser lock owner: ${file}`);
160
+ return value;
161
+ }
162
+ catch (error) {
163
+ if (error.code === 'ENOENT')
164
+ return null;
165
+ throw error;
166
+ }
167
+ }
168
+ async function writeOwner(lock, owner) {
169
+ const temporary = path.join(lock, `${owner.token}.tmp`);
170
+ await writeFile(temporary, JSON.stringify(owner), { flag: 'wx', mode: 0o600 });
171
+ await rename(temporary, path.join(lock, `${owner.token}.json`));
172
+ }
173
+ async function contenders(lock) {
174
+ const result = [];
175
+ const host = hostname();
176
+ for (const name of await readdir(lock)) {
177
+ if (!name.endsWith('.json'))
178
+ continue;
179
+ const file = path.join(lock, name);
180
+ const owner = await readOwner(file);
181
+ if (!owner)
182
+ continue;
183
+ if (owner.host === host && !await alive(owner.pid, owner.processStart) && (owner.workerPid === null || !await alive(owner.workerPid, owner.workerStart))) {
184
+ await rm(file, { force: true });
185
+ }
186
+ else
187
+ result.push(owner);
188
+ }
189
+ return result;
190
+ }
191
+ async function acquireLock(lock, owner, signal) {
192
+ await mkdir(lock, { recursive: true, mode: 0o700 });
193
+ signal.throwIfAborted();
194
+ await writeOwner(lock, owner);
195
+ let maximum = 0;
196
+ for (const contender of await contenders(lock))
197
+ maximum = Math.max(maximum, contender.ticket ?? 0);
198
+ if (maximum >= Number.MAX_SAFE_INTEGER)
199
+ throw new InstallationError('InstallationFailed', 'Browser lock ticket space is exhausted');
200
+ const ticket = maximum + 1;
201
+ owner.ticket = ticket;
202
+ await writeOwner(lock, owner);
203
+ while (true) {
204
+ signal.throwIfAborted();
205
+ const waiting = (await contenders(lock)).some(other => other.token !== owner.token && (other.ticket === null || other.ticket < ticket || (other.ticket === ticket && other.token < owner.token)));
206
+ if (!waiting)
207
+ return;
208
+ await delay(100, undefined, { signal });
209
+ }
210
+ }
211
+ export function createBrowserInstaller(release) {
212
+ return async (options = {}) => {
213
+ if (!release.pin.sha256 || !/^[a-f0-9]{64}$/.test(release.pin.sha256))
214
+ throw new InstallationError('ReleaseNotPrepared', 'The managed Chrome release has no reviewed archive checksum');
215
+ if (!/^[0-9]+(?:\.[0-9]+){3}$/.test(release.buildId))
216
+ throw new InstallationError('ReleaseNotPrepared', 'Invalid managed Chrome build identifier');
217
+ if (options.download !== undefined && options.download !== 'auto' && options.download !== 'never')
218
+ throw new InstallationError('InstallationFailed', 'download must be auto or never');
219
+ const timeoutMs = options.timeoutMs ?? 300_000;
220
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
221
+ throw new InstallationError('InstallationFailed', 'timeoutMs must be a positive finite duration no greater than 2147483647');
222
+ const cacheDir = browserCacheDirectory(options);
223
+ const controller = new AbortController();
224
+ const abort = () => controller.abort(new InstallationError('InstallationAborted', 'Browser installation was aborted', { cause: options.signal?.reason }));
225
+ options.signal?.addEventListener('abort', abort, { once: true });
226
+ if (options.signal?.aborted)
227
+ abort();
228
+ const timer = setTimeout(() => controller.abort(new InstallationError('InstallationTimeout', `Browser installation exceeded ${timeoutMs}ms`)), timeoutMs);
229
+ timer.unref();
230
+ const signal = controller.signal;
231
+ const key = `chrome-${release.platform}-${release.buildId}-${release.pin.sha256}`;
232
+ const root = path.join(cacheDir, key);
233
+ const executablePath = `chrome/${release.pin.platform}-${release.buildId}/${release.pin.executablePath}`;
234
+ const request = { action: 'verify', root, ...release, executablePath };
235
+ const lock = path.join(cacheDir, '.locks', key);
236
+ const token = randomUUID();
237
+ const stage = path.join(cacheDir, '.staging', `${key}-${token}`);
238
+ let owner;
239
+ let staged = false;
240
+ try {
241
+ if (await runWorker(request, options, signal))
242
+ return { executablePath: path.join(root, executablePath), cacheDir, buildId: release.buildId, platform: release.platform, source: 'cache' };
243
+ signal.throwIfAborted();
244
+ if (options.download === 'never')
245
+ throw new InstallationError('BrowserNotInstalled', `Pinned Chrome ${release.buildId} is not installed in ${cacheDir}; run installBrowser() with downloads enabled before using offline mode`);
246
+ const lockOwner = { token, pid: process.pid, host: hostname(), processStart: await processStart(process.pid), workerPid: null, workerStart: null, ticket: null };
247
+ owner = lockOwner;
248
+ await acquireLock(lock, lockOwner, signal);
249
+ if (await runWorker(request, options, signal))
250
+ return { executablePath: path.join(root, executablePath), cacheDir, buildId: release.buildId, platform: release.platform, source: 'cache' };
251
+ await mkdir(stage, { recursive: true, mode: 0o700 });
252
+ staged = true;
253
+ await runWorker({ ...request, action: 'install', root: stage }, options, signal, async (pid) => {
254
+ lockOwner.workerPid = pid;
255
+ lockOwner.workerStart = await processStart(pid);
256
+ await writeOwner(lock, lockOwner);
257
+ });
258
+ signal.throwIfAborted();
259
+ await rename(stage, root);
260
+ staged = false;
261
+ return { executablePath: path.join(root, executablePath), cacheDir, buildId: release.buildId, platform: release.platform, source: 'download' };
262
+ }
263
+ catch (cause) {
264
+ if (signal.aborted)
265
+ throw signal.reason;
266
+ if (cause instanceof InstallationError)
267
+ throw cause;
268
+ throw new InstallationError('InstallationFailed', `Could not install pinned Chrome ${release.buildId}`, { cause });
269
+ }
270
+ finally {
271
+ clearTimeout(timer);
272
+ options.signal?.removeEventListener('abort', abort);
273
+ try {
274
+ if (staged)
275
+ await rm(stage, { recursive: true, force: true });
276
+ if (owner) {
277
+ await rm(path.join(lock, `${token}.json`), { force: true });
278
+ await rm(path.join(lock, `${token}.tmp`), { force: true });
279
+ }
280
+ }
281
+ catch (cause) {
282
+ throw new InstallationError('InstallationFailed', 'Could not clean up the owned browser installation stage or lock', { cause });
283
+ }
284
+ }
285
+ };
286
+ }
@@ -0,0 +1,34 @@
1
+ import type { ChromePlatformRelease } from './release.js';
2
+ export declare const markerName = ".eoka-installation.json";
3
+ export interface InventoryEntry {
4
+ path: string;
5
+ type: 'file' | 'directory' | 'link';
6
+ mode: number;
7
+ size?: number;
8
+ sha256?: string;
9
+ target?: string;
10
+ }
11
+ export interface InstallationMarker {
12
+ schema: 1;
13
+ buildId: string;
14
+ platform: string;
15
+ archiveSha256: string;
16
+ archiveUrl: string;
17
+ executablePath: string;
18
+ inventorySha256: string;
19
+ inventory: InventoryEntry[];
20
+ }
21
+ export declare function fingerprint(entries: InventoryEntry[]): string;
22
+ export interface InventoryOptions {
23
+ /**
24
+ * Root-relative, `/`-separated directory to skip while it is empty. Chrome
25
+ * creates `extensions/` next to its executable on every startup
26
+ * (component-extension staging) even with `--disable-component-update`; it
27
+ * is not part of the pinned archive, so it must not read as tampering.
28
+ */
29
+ ignoreEmptyDirectory?: string;
30
+ }
31
+ export declare function inventoryTree(root: string, options?: InventoryOptions): Promise<InventoryEntry[]>;
32
+ export declare function validateExecutable(root: string, relative: string): Promise<void>;
33
+ export declare function createMarker(root: string, buildId: string, platform: string, pin: ChromePlatformRelease, executablePath: string): Promise<void>;
34
+ export declare function verifyInstallation(root: string, buildId: string, platform: string, pin: ChromePlatformRelease, executablePath: string): Promise<boolean>;
@@ -0,0 +1,107 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream, constants } from 'node:fs';
3
+ import { access, lstat, readFile, readdir, readlink, realpath, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { InstallationError } from './install-errors.js';
6
+ export const markerName = '.eoka-installation.json';
7
+ export function fingerprint(entries) {
8
+ return createHash('sha256').update(JSON.stringify(entries)).digest('hex');
9
+ }
10
+ function inside(root, target) {
11
+ const relative = path.relative(root, target);
12
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
13
+ }
14
+ export async function inventoryTree(root, options = {}) {
15
+ const rootInfo = await lstat(root);
16
+ if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink())
17
+ throw new InstallationError('IntegrityMismatch', 'Browser installation root is not a regular directory');
18
+ const resolvedRoot = await realpath(root);
19
+ const entries = [];
20
+ async function visit(directory, prefix) {
21
+ const names = (await readdir(directory)).sort();
22
+ for (const name of names) {
23
+ if (!prefix && name === markerName)
24
+ continue;
25
+ const relative = prefix ? `${prefix}/${name}` : name;
26
+ const absolute = path.join(directory, name);
27
+ const info = await lstat(absolute);
28
+ const mode = info.mode & 0o555;
29
+ if (relative === options.ignoreEmptyDirectory && info.isDirectory() && (await readdir(absolute)).length === 0)
30
+ continue;
31
+ if (info.isSymbolicLink()) {
32
+ const target = await readlink(absolute);
33
+ try {
34
+ if (path.isAbsolute(target) || !inside(resolvedRoot, await realpath(absolute)))
35
+ throw new Error('Link escapes browser distribution');
36
+ }
37
+ catch (cause) {
38
+ throw new InstallationError('IntegrityMismatch', `Unsafe or broken browser link: ${relative}`, { cause });
39
+ }
40
+ entries.push({ path: relative, type: 'link', mode, target });
41
+ }
42
+ else if (info.isDirectory()) {
43
+ entries.push({ path: relative, type: 'directory', mode });
44
+ await visit(absolute, relative);
45
+ }
46
+ else if (info.isFile()) {
47
+ const hash = createHash('sha256');
48
+ for await (const chunk of createReadStream(absolute))
49
+ hash.update(chunk);
50
+ entries.push({ path: relative, type: 'file', mode, size: info.size, sha256: hash.digest('hex') });
51
+ }
52
+ else {
53
+ throw new InstallationError('IntegrityMismatch', `Unsupported browser resource: ${relative}`);
54
+ }
55
+ }
56
+ }
57
+ await visit(root, '');
58
+ return entries;
59
+ }
60
+ export async function validateExecutable(root, relative) {
61
+ const absolute = path.resolve(root, relative);
62
+ if (!inside(root, absolute))
63
+ throw new InstallationError('IntegrityMismatch', 'Browser executable escapes the installation');
64
+ const info = await lstat(absolute);
65
+ if (!info.isFile() || info.isSymbolicLink() || info.size === 0)
66
+ throw new InstallationError('IntegrityMismatch', 'Browser executable is missing or unsafe');
67
+ await access(absolute, process.platform === 'win32' ? constants.R_OK : constants.R_OK | constants.X_OK);
68
+ }
69
+ export async function createMarker(root, buildId, platform, pin, executablePath) {
70
+ await validateExecutable(root, executablePath);
71
+ const inventory = await inventoryTree(root);
72
+ const marker = { schema: 1, buildId, platform, archiveSha256: pin.sha256, archiveUrl: pin.url, executablePath, inventorySha256: fingerprint(inventory), inventory };
73
+ await writeFile(path.join(root, markerName), JSON.stringify(marker), { flag: 'wx', mode: 0o600 });
74
+ }
75
+ export async function verifyInstallation(root, buildId, platform, pin, executablePath) {
76
+ try {
77
+ await lstat(root);
78
+ }
79
+ catch (error) {
80
+ if (error.code === 'ENOENT')
81
+ return false;
82
+ throw error;
83
+ }
84
+ try {
85
+ const markerPath = path.join(root, markerName);
86
+ const markerInfo = await lstat(markerPath);
87
+ if (!markerInfo.isFile() || markerInfo.isSymbolicLink() || markerInfo.size > 64 * 1024 * 1024)
88
+ throw new Error('Invalid installation inventory');
89
+ const marker = JSON.parse(await readFile(markerPath, 'utf8'));
90
+ if (marker.schema !== 1 || marker.buildId !== buildId || marker.platform !== platform || marker.archiveSha256 !== pin.sha256 || marker.archiveUrl !== pin.url || marker.executablePath !== executablePath || !Array.isArray(marker.inventory) || marker.inventorySha256 !== fingerprint(marker.inventory))
91
+ throw new Error('Installation inventory does not match the pinned release');
92
+ await validateExecutable(root, executablePath);
93
+ // The marker is always written from a strict inventory (createMarker).
94
+ // Chrome's archive never ships `extensions/`; the leniency only covers the
95
+ // empty directory it creates beside the executable after the first launch.
96
+ const runtimeExtensions = path.posix.join(path.posix.dirname(executablePath), 'extensions');
97
+ const actual = await inventoryTree(root, { ignoreEmptyDirectory: runtimeExtensions });
98
+ if (fingerprint(actual) !== marker.inventorySha256)
99
+ throw new Error('Browser distribution resources have changed');
100
+ return true;
101
+ }
102
+ catch (cause) {
103
+ if (cause instanceof InstallationError)
104
+ throw cause;
105
+ throw new InstallationError('IntegrityMismatch', `Browser cache failed integrity verification: ${root}`, { cause });
106
+ }
107
+ }