@cbxss/eoka 0.0.0-stage → 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +539 -2
- package/dist/LICENSE +21 -0
- package/dist/browser-install-diagnostics.d.ts +1 -0
- package/dist/browser-install-diagnostics.js +21 -0
- package/dist/browser-install-engine.d.ts +10 -0
- package/dist/browser-install-engine.js +286 -0
- package/dist/browser-install-inventory.d.ts +25 -0
- package/dist/browser-install-inventory.js +101 -0
- package/dist/browser-install-worker.d.ts +21 -0
- package/dist/browser-install-worker.js +65 -0
- package/dist/browser-install.d.ts +22 -0
- package/dist/browser-install.js +7 -0
- package/dist/browser.d.ts +59 -0
- package/dist/browser.js +445 -0
- package/dist/client.d.ts +11 -0
- package/dist/client.js +1 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +44 -0
- package/dist/generated/protocol.d.ts +3901 -0
- package/dist/generated/protocol.js +2 -0
- package/dist/generated/schema-bundle.json +18868 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +11 -0
- package/dist/install-errors.d.ts +4 -0
- package/dist/install-errors.js +6 -0
- package/dist/operations.d.ts +22 -0
- package/dist/operations.js +87 -0
- package/dist/page.d.ts +77 -0
- package/dist/page.js +250 -0
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js +27 -0
- package/dist/recording.d.ts +27 -0
- package/dist/recording.js +124 -0
- package/dist/release-manifest.json +101 -0
- package/dist/release.d.ts +36 -0
- package/dist/release.js +76 -0
- package/dist/server-binary.d.ts +11 -0
- package/dist/server-binary.js +107 -0
- package/dist/transport.d.ts +89 -0
- package/dist/transport.js +737 -0
- package/examples/capture.mjs +36 -0
- package/examples/consume-schema.mjs +7 -0
- package/examples/explicit-paths.mjs +42 -0
- package/examples/install-browser.mjs +20 -0
- package/examples/offline.mjs +20 -0
- package/package.json +70 -4
|
@@ -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,25 @@
|
|
|
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 declare function inventoryTree(root: string): Promise<InventoryEntry[]>;
|
|
23
|
+
export declare function validateExecutable(root: string, relative: string): Promise<void>;
|
|
24
|
+
export declare function createMarker(root: string, buildId: string, platform: string, pin: ChromePlatformRelease, executablePath: string): Promise<void>;
|
|
25
|
+
export declare function verifyInstallation(root: string, buildId: string, platform: string, pin: ChromePlatformRelease, executablePath: string): Promise<boolean>;
|
|
@@ -0,0 +1,101 @@
|
|
|
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) {
|
|
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 (info.isSymbolicLink()) {
|
|
30
|
+
const target = await readlink(absolute);
|
|
31
|
+
try {
|
|
32
|
+
if (path.isAbsolute(target) || !inside(resolvedRoot, await realpath(absolute)))
|
|
33
|
+
throw new Error('Link escapes browser distribution');
|
|
34
|
+
}
|
|
35
|
+
catch (cause) {
|
|
36
|
+
throw new InstallationError('IntegrityMismatch', `Unsafe or broken browser link: ${relative}`, { cause });
|
|
37
|
+
}
|
|
38
|
+
entries.push({ path: relative, type: 'link', mode, target });
|
|
39
|
+
}
|
|
40
|
+
else if (info.isDirectory()) {
|
|
41
|
+
entries.push({ path: relative, type: 'directory', mode });
|
|
42
|
+
await visit(absolute, relative);
|
|
43
|
+
}
|
|
44
|
+
else if (info.isFile()) {
|
|
45
|
+
const hash = createHash('sha256');
|
|
46
|
+
for await (const chunk of createReadStream(absolute))
|
|
47
|
+
hash.update(chunk);
|
|
48
|
+
entries.push({ path: relative, type: 'file', mode, size: info.size, sha256: hash.digest('hex') });
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
throw new InstallationError('IntegrityMismatch', `Unsupported browser resource: ${relative}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
await visit(root, '');
|
|
56
|
+
return entries;
|
|
57
|
+
}
|
|
58
|
+
export async function validateExecutable(root, relative) {
|
|
59
|
+
const absolute = path.resolve(root, relative);
|
|
60
|
+
if (!inside(root, absolute))
|
|
61
|
+
throw new InstallationError('IntegrityMismatch', 'Browser executable escapes the installation');
|
|
62
|
+
const info = await lstat(absolute);
|
|
63
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size === 0)
|
|
64
|
+
throw new InstallationError('IntegrityMismatch', 'Browser executable is missing or unsafe');
|
|
65
|
+
await access(absolute, process.platform === 'win32' ? constants.R_OK : constants.R_OK | constants.X_OK);
|
|
66
|
+
}
|
|
67
|
+
export async function createMarker(root, buildId, platform, pin, executablePath) {
|
|
68
|
+
await validateExecutable(root, executablePath);
|
|
69
|
+
const inventory = await inventoryTree(root);
|
|
70
|
+
const marker = { schema: 1, buildId, platform, archiveSha256: pin.sha256, archiveUrl: pin.url, executablePath, inventorySha256: fingerprint(inventory), inventory };
|
|
71
|
+
await writeFile(path.join(root, markerName), JSON.stringify(marker), { flag: 'wx', mode: 0o600 });
|
|
72
|
+
}
|
|
73
|
+
export async function verifyInstallation(root, buildId, platform, pin, executablePath) {
|
|
74
|
+
try {
|
|
75
|
+
await lstat(root);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error.code === 'ENOENT')
|
|
79
|
+
return false;
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
const markerPath = path.join(root, markerName);
|
|
84
|
+
const markerInfo = await lstat(markerPath);
|
|
85
|
+
if (!markerInfo.isFile() || markerInfo.isSymbolicLink() || markerInfo.size > 64 * 1024 * 1024)
|
|
86
|
+
throw new Error('Invalid installation inventory');
|
|
87
|
+
const marker = JSON.parse(await readFile(markerPath, 'utf8'));
|
|
88
|
+
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))
|
|
89
|
+
throw new Error('Installation inventory does not match the pinned release');
|
|
90
|
+
await validateExecutable(root, executablePath);
|
|
91
|
+
const actual = await inventoryTree(root);
|
|
92
|
+
if (fingerprint(actual) !== marker.inventorySha256)
|
|
93
|
+
throw new Error('Browser distribution resources have changed');
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
catch (cause) {
|
|
97
|
+
if (cause instanceof InstallationError)
|
|
98
|
+
throw cause;
|
|
99
|
+
throw new InstallationError('IntegrityMismatch', `Browser cache failed integrity verification: ${root}`, { cause });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ChromePlatformRelease } from './release.js';
|
|
2
|
+
export interface WorkerRequest {
|
|
3
|
+
action: 'verify' | 'install';
|
|
4
|
+
root: string;
|
|
5
|
+
buildId: string;
|
|
6
|
+
platform: string;
|
|
7
|
+
pin: ChromePlatformRelease;
|
|
8
|
+
executablePath: string;
|
|
9
|
+
}
|
|
10
|
+
export type WorkerMessage = {
|
|
11
|
+
type: 'result';
|
|
12
|
+
verified: boolean;
|
|
13
|
+
} | {
|
|
14
|
+
type: 'progress';
|
|
15
|
+
downloadedBytes: number;
|
|
16
|
+
totalBytes: number;
|
|
17
|
+
} | {
|
|
18
|
+
type: 'error';
|
|
19
|
+
code: string;
|
|
20
|
+
message: string;
|
|
21
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { Browser, install, getDownloadUrl } from '@puppeteer/browsers';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createMarker, verifyInstallation } from './browser-install-inventory.js';
|
|
5
|
+
import { sanitizeInstallationDiagnostic } from './browser-install-diagnostics.js';
|
|
6
|
+
process.once('disconnect', () => {
|
|
7
|
+
if (process.platform === 'win32') {
|
|
8
|
+
spawn('taskkill', ['/PID', String(process.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).once('error', () => process.exit(1));
|
|
9
|
+
}
|
|
10
|
+
else {
|
|
11
|
+
try {
|
|
12
|
+
process.kill(-process.pid, 'SIGKILL');
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
process.exit(1);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
process.once('message', async (request) => {
|
|
20
|
+
try {
|
|
21
|
+
if (request.action === 'verify') {
|
|
22
|
+
const verified = await verifyInstallation(request.root, request.buildId, request.platform, request.pin, request.executablePath);
|
|
23
|
+
process.send?.({ type: 'result', verified });
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
if (process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0')
|
|
27
|
+
throw new Error('Browser downloads require TLS certificate verification; remove NODE_TLS_REJECT_UNAUTHORIZED=0');
|
|
28
|
+
if (!request.pin.sha256 || !/^[a-f0-9]{64}$/.test(request.pin.sha256))
|
|
29
|
+
throw new Error('Missing archive checksum');
|
|
30
|
+
const platform = request.pin.platform;
|
|
31
|
+
const url = new URL(request.pin.url);
|
|
32
|
+
const baseUrl = new URL('../../', url).href.replace(/\/$/, '');
|
|
33
|
+
if (getDownloadUrl(Browser.CHROME, platform, request.buildId, baseUrl).href !== url.href)
|
|
34
|
+
throw new Error('Pinned URL does not match the Chrome distribution');
|
|
35
|
+
const browser = await install({
|
|
36
|
+
browser: Browser.CHROME,
|
|
37
|
+
buildId: request.buildId,
|
|
38
|
+
platform,
|
|
39
|
+
cacheDir: request.root,
|
|
40
|
+
baseUrl,
|
|
41
|
+
expectedHash: request.pin.sha256,
|
|
42
|
+
installDeps: false,
|
|
43
|
+
downloadProgressCallback: (downloadedBytes, totalBytes) => {
|
|
44
|
+
process.send?.({ type: 'progress', downloadedBytes, totalBytes });
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
if (path.relative(request.root, browser.executablePath).replaceAll(path.sep, '/') !== request.executablePath)
|
|
48
|
+
throw new Error('Installer returned an unexpected executable path');
|
|
49
|
+
await createMarker(request.root, request.buildId, request.platform, request.pin, request.executablePath);
|
|
50
|
+
process.send?.({ type: 'result', verified: true });
|
|
51
|
+
}
|
|
52
|
+
process.exitCode = 0;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
56
|
+
const message = sanitizeInstallationDiagnostic(rawMessage, process.env);
|
|
57
|
+
const code = error && typeof error === 'object' && 'name' in error && error.name === 'InstallationError' && 'code' in error && typeof error.code === 'string' ? error.code : /integrity check failed/i.test(rawMessage) ? 'IntegrityMismatch' : 'InstallationFailed';
|
|
58
|
+
process.send?.({ type: 'error', code, message });
|
|
59
|
+
process.exitCode = 1;
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
process.removeAllListeners('disconnect');
|
|
63
|
+
process.disconnect?.();
|
|
64
|
+
}
|
|
65
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type PlatformId } from './platform.js';
|
|
2
|
+
export interface InstallProgress {
|
|
3
|
+
downloadedBytes: number;
|
|
4
|
+
totalBytes: number;
|
|
5
|
+
buildId: string;
|
|
6
|
+
}
|
|
7
|
+
export interface InstallBrowserOptions {
|
|
8
|
+
browserCacheDir?: string;
|
|
9
|
+
download?: 'auto' | 'never';
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
onProgress?: (progress: InstallProgress) => void;
|
|
13
|
+
env?: NodeJS.ProcessEnv;
|
|
14
|
+
}
|
|
15
|
+
export interface BrowserInstallation {
|
|
16
|
+
executablePath: string;
|
|
17
|
+
cacheDir: string;
|
|
18
|
+
buildId: string;
|
|
19
|
+
platform: PlatformId;
|
|
20
|
+
source: 'cache' | 'download';
|
|
21
|
+
}
|
|
22
|
+
export declare function installBrowser(options?: InstallBrowserOptions): Promise<BrowserInstallation>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createBrowserInstaller } from './browser-install-engine.js';
|
|
2
|
+
import { detectPlatform } from './platform.js';
|
|
3
|
+
import { releaseManifest } from './release.js';
|
|
4
|
+
export async function installBrowser(options = {}) {
|
|
5
|
+
const platform = detectPlatform();
|
|
6
|
+
return await createBrowserInstaller({ platform, buildId: releaseManifest.chrome.buildId, pin: releaseManifest.chrome.platforms[platform] })(options);
|
|
7
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { CallOptions, InvokeClient } from './client.js';
|
|
2
|
+
import type { MethodName, MethodParams, MethodResults } from './generated/protocol.js';
|
|
3
|
+
import { Operation } from './operations.js';
|
|
4
|
+
import { Page, type PerformOptions } from './page.js';
|
|
5
|
+
import { Recording } from './recording.js';
|
|
6
|
+
import { type InstallProgress } from './browser-install.js';
|
|
7
|
+
export interface BrowserOptions {
|
|
8
|
+
serverPath?: string;
|
|
9
|
+
serverEnv?: NodeJS.ProcessEnv;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
shutdownTimeoutMs?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface LaunchOptions extends BrowserOptions {
|
|
15
|
+
executablePath?: string;
|
|
16
|
+
headless?: boolean;
|
|
17
|
+
sandbox?: boolean;
|
|
18
|
+
viewport?: {
|
|
19
|
+
width: number;
|
|
20
|
+
height: number;
|
|
21
|
+
deviceScaleFactor?: number;
|
|
22
|
+
};
|
|
23
|
+
runtimeDir?: string;
|
|
24
|
+
userDataDir?: string;
|
|
25
|
+
browserCacheDir?: string;
|
|
26
|
+
download?: 'auto' | 'never';
|
|
27
|
+
onProgress?: (progress: InstallProgress) => void;
|
|
28
|
+
userAgent?: string;
|
|
29
|
+
timezone?: string;
|
|
30
|
+
proxy?: NonNullable<MethodParams['browser.launch']['proxy']>;
|
|
31
|
+
}
|
|
32
|
+
export interface ConnectOptions extends BrowserOptions {
|
|
33
|
+
browserWSEndpoint: string;
|
|
34
|
+
}
|
|
35
|
+
export declare class Browser implements InvokeClient {
|
|
36
|
+
#private;
|
|
37
|
+
private constructor();
|
|
38
|
+
static launch(options?: LaunchOptions): Promise<Browser>;
|
|
39
|
+
static connect(options: ConnectOptions): Promise<Browser>;
|
|
40
|
+
private static start;
|
|
41
|
+
get hello(): MethodResults['server.hello'];
|
|
42
|
+
get sessionInfo(): MethodResults['browser.launch'];
|
|
43
|
+
get ownership(): MethodResults['browser.launch']['ownership'];
|
|
44
|
+
get browserVersion(): string;
|
|
45
|
+
supports(method: string): boolean;
|
|
46
|
+
hasCapability(name: string): boolean;
|
|
47
|
+
invoke<M extends MethodName>(method: M, params: MethodParams[M], options?: CallOptions): Promise<MethodResults[M]>;
|
|
48
|
+
page(id: string): Page;
|
|
49
|
+
operation(id: string): Operation;
|
|
50
|
+
recording(id: string): Recording;
|
|
51
|
+
tabs(options?: CallOptions): Promise<MethodResults['browser.tabs']['tabs']>;
|
|
52
|
+
pages(options?: CallOptions): Promise<Page[]>;
|
|
53
|
+
operations(params?: MethodParams['operations.list'], options?: CallOptions): Promise<MethodResults['operations.list']>;
|
|
54
|
+
newPage(url?: string, options?: PerformOptions): Promise<Page>;
|
|
55
|
+
private createPage;
|
|
56
|
+
private cleanupAbandonedCreation;
|
|
57
|
+
close(): Promise<void>;
|
|
58
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
59
|
+
}
|