@percy/cli-doctor 1.31.10-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.
@@ -0,0 +1,704 @@
1
+ function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
2
+ function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
3
+ function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
4
+ function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
5
+ function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
6
+ import { spawn } from 'child_process';
7
+ import http from 'http';
8
+ import net from 'net';
9
+ import os from 'os';
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import { URL } from 'url';
13
+
14
+ // ─── Path-safety helpers ────────────────────────────────────────────────────
15
+
16
+ /**
17
+ * Validate and normalize an executable path that may come from user/env input.
18
+ * Returns the resolved absolute path, or null when the value looks unsafe.
19
+ * We intentionally avoid shell: true in spawn() but still sanitize here so
20
+ * that Semgrep can statically confirm chromePath is clean before it reaches
21
+ * the child-process call.
22
+ */
23
+ export function sanitizeExecutablePath(p) {
24
+ if (!p || typeof p !== 'string') return null;
25
+ // Reject anything containing shell metacharacters before resolving
26
+ if (/[;&|`$<>\n\r"']/.test(p)) return null;
27
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
28
+ const resolved = path.resolve(p);
29
+ if (!path.isAbsolute(resolved)) return null;
30
+ return resolved;
31
+ }
32
+
33
+ /**
34
+ * Validate an environment-variable directory path before using it in
35
+ * path.join(). Returns `val` (resolved) when it is an absolute path;
36
+ * falls back to `fallback` otherwise, preventing path-traversal via a
37
+ * tampered PROGRAMFILES env var.
38
+ */
39
+ export function safeEnvPath(val, fallback) {
40
+ if (!val || typeof val !== 'string') return fallback;
41
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
42
+ const resolved = path.resolve(val);
43
+ return path.isAbsolute(resolved) ? resolved : fallback;
44
+ }
45
+
46
+ // ─── Request lifecycle & network capture (mirrors @percy/core's network.js) ───
47
+
48
+ /**
49
+ * Tracks the two key lifecycle moments for a single CDP requestId so that
50
+ * async event handlers can await proper ordering — the same pattern used in
51
+ * @percy/core's RequestLifeCycleHandler.
52
+ */
53
+ class RequestLifecycle {
54
+ constructor() {
55
+ this.requestWillBeSent = new Promise(r => this.resolveRequestWillBeSent = r);
56
+ this.responseReceived = new Promise(r => this.resolveResponseReceived = r);
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Lightweight network-event aggregator modelled on @percy/core's Network class.
62
+ *
63
+ * Uses per-request Promise chains to guarantee event processing order:
64
+ * requestWillBeSent → responseReceived → loadingFailed
65
+ *
66
+ * This prevents response/failure data being stored before the corresponding
67
+ * request record exists, which can occur when Chrome emits events out of order.
68
+ */
69
+ var _lifecycles = /*#__PURE__*/new WeakMap();
70
+ var _requests = /*#__PURE__*/new WeakMap();
71
+ var _responses = /*#__PURE__*/new WeakMap();
72
+ var _failed = /*#__PURE__*/new WeakMap();
73
+ var _proxyHeaders = /*#__PURE__*/new WeakMap();
74
+ var _NetworkCapture_brand = /*#__PURE__*/new WeakSet();
75
+ export class NetworkCapture {
76
+ constructor() {
77
+ _classPrivateMethodInitSpec(this, _NetworkCapture_brand);
78
+ _classPrivateFieldInitSpec(this, _lifecycles, new Map());
79
+ _classPrivateFieldInitSpec(this, _requests, new Map());
80
+ _classPrivateFieldInitSpec(this, _responses, new Map());
81
+ _classPrivateFieldInitSpec(this, _failed, new Map());
82
+ _classPrivateFieldInitSpec(this, _proxyHeaders, new Set());
83
+ }
84
+ /** Network.requestWillBeSent — stores request info and releases lifecycle. */
85
+ onRequestWillBeSent({
86
+ requestId,
87
+ request,
88
+ type,
89
+ timestamp
90
+ }) {
91
+ var _request$initiator;
92
+ if (request.url.startsWith('data:')) return;
93
+ _classPrivateFieldGet(_requests, this).set(requestId, {
94
+ url: request.url,
95
+ hostname: safeHostname(request.url),
96
+ method: request.method,
97
+ type,
98
+ initiatorType: (_request$initiator = request.initiator) === null || _request$initiator === void 0 ? void 0 : _request$initiator.type,
99
+ timestamp
100
+ });
101
+ _assertClassBrand(_NetworkCapture_brand, this, _lifecycle).call(this, requestId).resolveRequestWillBeSent();
102
+ }
103
+
104
+ /** Network.responseReceived — awaits requestWillBeSent before storing response. */
105
+ async onResponseReceived({
106
+ requestId,
107
+ response
108
+ }) {
109
+ await _assertClassBrand(_NetworkCapture_brand, this, _lifecycle).call(this, requestId).requestWillBeSent;
110
+ _classPrivateFieldGet(_responses, this).set(requestId, {
111
+ status: response.status,
112
+ statusText: response.statusText,
113
+ fromCache: response.fromDiskCache || response.fromServiceWorker,
114
+ protocol: response.protocol,
115
+ remoteIPAddress: response.remoteIPAddress,
116
+ headers: response.headers
117
+ });
118
+ // Collect proxy-indicating headers
119
+ for (const h of Object.keys(response.headers ?? {})) {
120
+ const lh = h.toLowerCase();
121
+ if (lh.startsWith('x-proxy') || lh.startsWith('proxy-') || lh === 'via' || lh === 'x-forwarded-for' || lh === 'x-forwarded-host' || lh.includes('zscaler') || lh.includes('netskope') || lh.includes('bluecoat') || lh === 'x-cache' || lh === 'cf-ray') {
122
+ _classPrivateFieldGet(_proxyHeaders, this).add(`${h}: ${response.headers[h]}`);
123
+ }
124
+ }
125
+ _assertClassBrand(_NetworkCapture_brand, this, _lifecycle).call(this, requestId).resolveResponseReceived();
126
+ }
127
+
128
+ /** Network.loadingFailed — awaits requestWillBeSent before storing failure. */
129
+ async onLoadingFailed({
130
+ requestId,
131
+ errorText,
132
+ blockedReason,
133
+ corsErrorStatus
134
+ }) {
135
+ await _assertClassBrand(_NetworkCapture_brand, this, _lifecycle).call(this, requestId).requestWillBeSent;
136
+ _classPrivateFieldGet(_failed, this).set(requestId, {
137
+ errorText,
138
+ blockedReason,
139
+ corsErrorStatus
140
+ });
141
+ }
142
+
143
+ /** Merge all tracked maps into a flat request array. */
144
+ buildRequests() {
145
+ const result = [];
146
+ for (const [id, req] of _classPrivateFieldGet(_requests, this)) {
147
+ const res = _classPrivateFieldGet(_responses, this).get(id) ?? null;
148
+ const fail = _classPrivateFieldGet(_failed, this).get(id) ?? null;
149
+ result.push({
150
+ ...req,
151
+ response: res,
152
+ failure: fail,
153
+ reachable: res ? res.status >= 200 && res.status < 400 : false,
154
+ blocked: !!(fail !== null && fail !== void 0 && fail.blockedReason),
155
+ errorText: (fail === null || fail === void 0 ? void 0 : fail.errorText) ?? null
156
+ });
157
+ }
158
+ return result;
159
+ }
160
+ getProxyHeaders() {
161
+ return Array.from(_classPrivateFieldGet(_proxyHeaders, this));
162
+ }
163
+ }
164
+ function _lifecycle(requestId) {
165
+ if (!_classPrivateFieldGet(_lifecycles, this).has(requestId)) {
166
+ _classPrivateFieldGet(_lifecycles, this).set(requestId, new RequestLifecycle());
167
+ }
168
+ return _classPrivateFieldGet(_lifecycles, this).get(requestId);
169
+ }
170
+ export function safeHostname(rawUrl) {
171
+ try {
172
+ return new URL(rawUrl).hostname;
173
+ } catch {
174
+ return rawUrl;
175
+ }
176
+ }
177
+ export function sanitizeProxyForChrome(proxyUrl) {
178
+ if (!proxyUrl) return null;
179
+ try {
180
+ const p = new URL(proxyUrl);
181
+ p.username = '';
182
+ p.password = '';
183
+ return p.toString().replace(/\/$/, '');
184
+ } catch {
185
+ /* istanbul ignore next */
186
+ return proxyUrl;
187
+ }
188
+ }
189
+
190
+ // ─── Analyse & build findings ─────────────────────────────────────────────────
191
+
192
+ export function analyseCapture(capture) {
193
+ const byHostname = new Map();
194
+ for (const req of capture.requests) {
195
+ const h = req.hostname;
196
+ if (!byHostname.has(h)) {
197
+ byHostname.set(h, {
198
+ hostname: h,
199
+ requests: [],
200
+ reachable: false,
201
+ blocked: false,
202
+ errors: new Set()
203
+ });
204
+ }
205
+ const entry = byHostname.get(h);
206
+ entry.requests.push(req);
207
+ if (req.reachable) entry.reachable = true;
208
+ if (req.blocked) entry.blocked = true;
209
+ if (req.errorText && req.errorText !== 'net::ERR_ABORTED') {
210
+ entry.errors.add(req.errorText);
211
+ }
212
+ }
213
+
214
+ // Flatten errors set to array
215
+ for (const entry of byHostname.values()) {
216
+ entry.errors = Array.from(entry.errors);
217
+ }
218
+ return byHostname;
219
+ }
220
+
221
+ // ─── BrowserChecker ───────────────────────────────────────────────────────────
222
+
223
+ /**
224
+ * All Chrome browser-network analysis logic lives here as methods.
225
+ * Instantiate and call checkBrowserNetwork() to run Check 5.
226
+ */
227
+ var _BrowserChecker_brand = /*#__PURE__*/new WeakSet();
228
+ export class BrowserChecker {
229
+ constructor() {
230
+ // ─── Private: Chrome binary discovery ──────────────────────────────────────
231
+ /** Return platform-specific candidate Chrome binary paths in priority order. */
232
+ _classPrivateMethodInitSpec(this, _BrowserChecker_brand);
233
+ }
234
+ /**
235
+ * Poll Chrome's /json/list endpoint for a page-type target's WS URL.
236
+ * Network.enable and Page.enable are page-level CDP domains — they must be sent
237
+ * to a page target, not the browser-level target from /json/version.
238
+ */
239
+ _pollCDPPageTarget(port) {
240
+ return new Promise((resolve, reject) => {
241
+ const req = http.get(`http://127.0.0.1:${port}/json/list`, {
242
+ timeout: 1000
243
+ }, res => {
244
+ let body = '';
245
+ res.on('data', d => body += d);
246
+ res.on('end', () => {
247
+ try {
248
+ const targets = JSON.parse(body);
249
+ const page = targets.find(t => t.type === 'page' && t.webSocketDebuggerUrl);
250
+ if (page) resolve(page.webSocketDebuggerUrl);else reject(new Error('no page target ready'));
251
+ } catch {
252
+ reject(new Error('invalid CDP response'));
253
+ }
254
+ });
255
+ });
256
+ req.on('error', reject);
257
+ req.on('timeout', () => reject(new Error('CDP poll timeout')));
258
+ });
259
+ }
260
+
261
+ /** Wait until Chrome's CDP page target is ready and return its webSocketDebuggerUrl. */
262
+ /* istanbul ignore next */
263
+ async _waitForCDP(port, timeout = 30000) {
264
+ const deadline = Date.now() + timeout;
265
+ while (Date.now() < deadline) {
266
+ try {
267
+ const wsUrl = await this._pollCDPPageTarget(port);
268
+ if (wsUrl) return wsUrl;
269
+ } catch {/* not ready yet */}
270
+ await new Promise(r => setTimeout(r, 150));
271
+ }
272
+ throw new Error('Timed out waiting for Chrome CDP page target');
273
+ }
274
+
275
+ /**
276
+ * Minimal CDP client over WebSocket.
277
+ * Only depends on the `ws` package (transitive dep via @percy/core).
278
+ */
279
+ async _connectCDP(wsUrl) {
280
+ const {
281
+ default: WS
282
+ } = await import('ws');
283
+ const ws = new WS(wsUrl, {
284
+ perMessageDeflate: false
285
+ });
286
+ await new Promise((resolve, reject) => {
287
+ ws.once('open', resolve);
288
+ ws.once('error', reject);
289
+ });
290
+ let _id = 0;
291
+ const _pending = new Map();
292
+ const _listeners = new Map(); // event → Set<handler>
293
+
294
+ ws.on('message', raw => {
295
+ let msg;
296
+ /* istanbul ignore next */
297
+ try {
298
+ msg = JSON.parse(raw.toString());
299
+ } catch {
300
+ return;
301
+ }
302
+ if (msg.id && _pending.has(msg.id)) {
303
+ const {
304
+ resolve,
305
+ reject
306
+ } = _pending.get(msg.id);
307
+ _pending.delete(msg.id);
308
+ /* istanbul ignore next */
309
+ if (msg.error) {
310
+ reject(new Error(msg.error.message));
311
+ } else {
312
+ resolve(msg.result ?? {});
313
+ }
314
+ }
315
+ if (msg.method) {
316
+ /* istanbul ignore next */
317
+ for (const handler of _listeners.get(msg.method) ?? []) {
318
+ handler(msg.params);
319
+ }
320
+ }
321
+ });
322
+ return {
323
+ send(method, params = {}) {
324
+ const id = ++_id;
325
+ return new Promise((resolve, reject) => {
326
+ _pending.set(id, {
327
+ resolve,
328
+ reject
329
+ });
330
+ ws.send(JSON.stringify({
331
+ id,
332
+ method,
333
+ params
334
+ }));
335
+ });
336
+ },
337
+ on(event, handler) {
338
+ if (!_listeners.has(event)) _listeners.set(event, new Set());
339
+ _listeners.get(event).add(handler);
340
+ },
341
+ close() {
342
+ ws.close();
343
+ }
344
+ };
345
+ }
346
+
347
+ // ─── Private: capture ──────────────────────────────────────────────────────
348
+
349
+ /**
350
+ * Launch Chrome, capture network activity, and return raw results.
351
+ * Races the capture against a hard deadline (timeout + 15 s).
352
+ */
353
+ /* istanbul ignore next */
354
+ async _captureNetworkRequests(chromePath, targetUrl, opts = {}) {
355
+ const {
356
+ timeout = 30000,
357
+ proxyUrl
358
+ } = opts;
359
+ // Hard wall-clock cap: navigation timeout + 15 s for Chrome startup + CDP handshake.
360
+ // If Chrome hangs (e.g. frozen renderer, hung SIGTERM), this ensures we always
361
+ // return within a bounded time rather than blocking the whole doctor run.
362
+ const hardDeadline = timeout + 15000;
363
+ const timeoutResult = {
364
+ targetUrl,
365
+ proxyUrl: proxyUrl ?? null,
366
+ navMs: 0,
367
+ requests: [],
368
+ proxyHeaders: [],
369
+ error: `Browser capture timed out after ${hardDeadline / 1000}s`
370
+ };
371
+ return Promise.race([this._doCapture(chromePath, targetUrl, opts), new Promise(resolve => setTimeout(() => resolve(timeoutResult), hardDeadline))]);
372
+ }
373
+
374
+ /* istanbul ignore next */
375
+ async _doCapture(chromePath, targetUrl, opts = {}) {
376
+ var _proc$stderr;
377
+ const {
378
+ headless = true,
379
+ timeout = 30000,
380
+ proxyUrl
381
+ } = opts;
382
+ const chromeProxyUrl = sanitizeProxyForChrome(proxyUrl);
383
+
384
+ // Re-validate at the sink to keep the child_process usage safe even if this
385
+ // method is called directly in tests or from future code paths.
386
+ const safeChromePath = sanitizeExecutablePath(chromePath);
387
+ /* istanbul ignore next */
388
+ if (!safeChromePath || !fs.existsSync(safeChromePath)) {
389
+ throw new Error('Invalid Chrome executable path');
390
+ }
391
+
392
+ // When NODE_TLS_REJECT_UNAUTHORIZED=0 is set the Node process has already
393
+ // disabled SSL verification (e.g. for an SSL-intercepting proxy). Mirror that
394
+ // into Chrome via two mechanisms:
395
+ // 1. --ignore-certificate-errors CLI flag (broad bypass, works for most cases)
396
+ // 2. Security.setIgnoreCertificateErrors CDP command (per-session, more reliable
397
+ // for intercepting proxies — this is how Puppeteer/Playwright do it)
398
+ const ignoreCerts = process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0';
399
+ const port = await _assertClassBrand(_BrowserChecker_brand, this, _getFreePort).call(this);
400
+ const chromeArgs = [`--remote-debugging-port=${port}`, '--no-sandbox', '--disable-extensions', '--disable-background-networking', '--disable-default-apps', '--disable-sync', '--disable-translate', '--metrics-recording-only', '--no-first-run', '--safebrowsing-disable-auto-update', '--password-store=basic', '--use-mock-keychain', headless ? '--headless=new' : '', headless ? '--hide-scrollbars' : '', headless ? '--mute-audio' : '', chromeProxyUrl ? `--proxy-server=${chromeProxyUrl}` : '', 'about:blank'].filter(Boolean);
401
+
402
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process --- IGNORE
403
+ const proc = spawn(safeChromePath, chromeArgs, {
404
+ stdio: ['ignore', 'ignore', 'pipe'],
405
+ detached: false,
406
+ shell: false // args are always an array; never expand via shell
407
+ });
408
+ let chromeStderr = '';
409
+ (_proc$stderr = proc.stderr) === null || _proc$stderr === void 0 || _proc$stderr.on('data', chunk => {
410
+ const next = String(chunk ?? '');
411
+ if (!next) return;
412
+ chromeStderr = (chromeStderr + next).slice(0, 4000);
413
+ });
414
+ const capture = new NetworkCapture();
415
+ let captureError = null;
416
+ let navMs = 0;
417
+ try {
418
+ const wsUrl = await this._waitForCDP(port, Math.max(timeout, 30000));
419
+ const cdp = await this._connectCDP(wsUrl);
420
+
421
+ // Attach event handlers — mirrors the watch() pattern in @percy/core's Network class
422
+ cdp.on('Network.requestWillBeSent', p => capture.onRequestWillBeSent(p));
423
+ cdp.on('Network.responseReceived', p => capture.onResponseReceived(p));
424
+ cdp.on('Network.loadingFailed', p => capture.onLoadingFailed(p));
425
+ await Promise.all([cdp.send('Network.enable'), cdp.send('Page.enable')]);
426
+
427
+ // Per-session SSL bypass — more reliable than the CLI flag for intercepting
428
+ // proxies (the flag sometimes doesn't fire in headless=new for CONNECT tunnels).
429
+ if (ignoreCerts) {
430
+ await cdp.send('Security.setIgnoreCertificateErrors', {
431
+ ignore: true
432
+ });
433
+ }
434
+ const navStart = Date.now();
435
+ await cdp.send('Page.navigate', {
436
+ url: targetUrl
437
+ });
438
+ await Promise.race([new Promise(resolve => cdp.on('Page.loadEventFired', () => setTimeout(resolve, 2500))), new Promise(resolve => setTimeout(resolve, timeout))]);
439
+ navMs = Date.now() - navStart;
440
+ cdp.close();
441
+
442
+ // Allow any in-flight async lifecycle handlers (onResponseReceived,
443
+ // onLoadingFailed) to fully settle before collecting results
444
+ await new Promise(resolve => setImmediate(resolve));
445
+ } catch (err) {
446
+ captureError = err.message;
447
+ } finally {
448
+ try {
449
+ proc.kill('SIGTERM');
450
+ } catch {/* ignore */}
451
+ await this._killProcess(proc, 3000);
452
+ }
453
+ return {
454
+ targetUrl,
455
+ proxyUrl: proxyUrl ?? null,
456
+ navMs,
457
+ requests: capture.buildRequests(),
458
+ proxyHeaders: capture.getProxyHeaders(),
459
+ error: captureError ? `${captureError}${chromeStderr ? ` | Chrome stderr: ${chromeStderr.trim().slice(0, 500)}` : ''}` : null
460
+ };
461
+ }
462
+
463
+ /**
464
+ * Terminate a child process gracefully (SIGTERM), escalating to SIGKILL after
465
+ * `gracePeriodMs` if it hasn't exited. Handles the race where the process has
466
+ * already exited so `proc.once('exit')` would never fire.
467
+ */
468
+ _killProcess(proc, gracePeriodMs = 3000) {
469
+ return new Promise(resolve => {
470
+ // Already dead — nothing to do
471
+ if (proc.exitCode !== null || proc.killed) return resolve();
472
+ const escalate = setTimeout(() => {
473
+ try {
474
+ proc.kill('SIGKILL');
475
+ } catch {/* already gone */}
476
+ // One final wait; if it still doesn't fire we move on
477
+ const bail = setTimeout(resolve, 2000);
478
+ proc.once('exit', () => {
479
+ clearTimeout(bail);
480
+ resolve();
481
+ });
482
+ }, gracePeriodMs);
483
+
484
+ /* istanbul ignore next */
485
+ proc.once('exit', () => {
486
+ clearTimeout(escalate);
487
+ resolve();
488
+ });
489
+ });
490
+ }
491
+
492
+ // ─── Public API ─────────────────────────────────────────────────────────────
493
+
494
+ /**
495
+ * Check 5 – Browser Network Analysis
496
+ *
497
+ * Launches Chrome (bundled Chromium or system) and navigates to `targetUrl`.
498
+ * All network requests are captured and grouped by hostname into:
499
+ * reachable / blocked / errored
500
+ *
501
+ * If `proxyUrl` is provided the test is run twice (direct + via proxy) so the
502
+ * delta is visible.
503
+ *
504
+ * @param {object} [options]
505
+ * @param {string} [options.targetUrl] URL to open (default: https://percy.io)
506
+ * @param {string} [options.proxyUrl] Optional proxy server to test
507
+ * @param {number} [options.timeout] Navigation timeout ms (default: 30000)
508
+ * @param {boolean} [options.headless] Run headless (default: true)
509
+ * @returns {Promise<BrowserFinding>}
510
+ */
511
+ async checkBrowserNetwork(options = {}) {
512
+ var _directResult$reason, _proxyResult$reason;
513
+ const {
514
+ targetUrl = 'https://percy.io',
515
+ proxyUrl,
516
+ timeout = 30000,
517
+ headless = true
518
+ } = options;
519
+ const notes = [];
520
+ if (proxyUrl) {
521
+ try {
522
+ const p = new URL(proxyUrl);
523
+ /* istanbul ignore next */
524
+ if (p.username || p.password) {
525
+ /* istanbul ignore next */
526
+ notes.push({
527
+ status: 'info',
528
+ message: 'Proxy credentials detected but not passed to Chrome (security: not exposed in process args).',
529
+ suggestions: ['Chrome browser check runs without proxy auth. Results may differ from authenticated access.']
530
+ });
531
+ }
532
+ } catch {/* ignore malformed proxy URL */}
533
+ }
534
+
535
+ // ── 1. Find Chrome ───────────────────────────────────────────────────────
536
+ const chromePath = await _assertClassBrand(_BrowserChecker_brand, this, _findChrome).call(this);
537
+ if (!chromePath) {
538
+ return {
539
+ status: 'skip',
540
+ message: 'Chrome / Chromium not found. Install Google Chrome or set PERCY_BROWSER_EXECUTABLE.',
541
+ chromePath: null,
542
+ targetUrl,
543
+ directCapture: null,
544
+ proxyCapture: null,
545
+ domainSummary: [],
546
+ proxyHeaders: [],
547
+ suggestions: ['Install Google Chrome from https://www.google.com/chrome/', 'Or set PERCY_BROWSER_EXECUTABLE=/path/to/chrome in your environment.']
548
+ };
549
+ }
550
+
551
+ // ── 2 & 3. Direct + proxy captures in parallel ──────────────────────────
552
+ const errCapture = (url, pUrl, msg) => ({
553
+ targetUrl: url,
554
+ proxyUrl: pUrl,
555
+ navMs: 0,
556
+ requests: [],
557
+ proxyHeaders: [],
558
+ error: msg
559
+ });
560
+ const [directResult, proxyResult] = await Promise.allSettled([this._captureNetworkRequests(chromePath, targetUrl, {
561
+ headless,
562
+ timeout
563
+ }), proxyUrl ? this._captureNetworkRequests(chromePath, targetUrl, {
564
+ headless,
565
+ timeout,
566
+ proxyUrl
567
+ }) : Promise.resolve(null)]);
568
+ const directCapture = directResult.status === 'fulfilled' ? directResult.value : errCapture(targetUrl, null, ((_directResult$reason = directResult.reason) === null || _directResult$reason === void 0 ? void 0 : _directResult$reason.message) ?? 'capture failed');
569
+
570
+ /* istanbul ignore next */
571
+ const proxyCapture = proxyResult.status === 'fulfilled' ? proxyResult.value : proxyUrl ? errCapture(targetUrl, proxyUrl, ((_proxyResult$reason = proxyResult.reason) === null || _proxyResult$reason === void 0 ? void 0 : _proxyResult$reason.message) ?? 'capture failed') : null;
572
+
573
+ // ── 4. Build domain-level summary ────────────────────────────────────────
574
+ const directByHost = analyseCapture(directCapture);
575
+ const proxyByHost = proxyCapture ? analyseCapture(proxyCapture) : null;
576
+ const allHostnames = new Set([...directByHost.keys(), ...((proxyByHost === null || proxyByHost === void 0 ? void 0 : proxyByHost.keys()) ?? [])]);
577
+ const domainSummary = [];
578
+ for (const hostname of allHostnames) {
579
+ var _direct$requests$find, _viaProxy$requests$fi;
580
+ const direct = directByHost.get(hostname) ?? null;
581
+ const viaProxy = (proxyByHost === null || proxyByHost === void 0 ? void 0 : proxyByHost.get(hostname)) ?? null;
582
+ let status;
583
+ if (direct !== null && direct !== void 0 && direct.reachable) {
584
+ status = 'pass';
585
+ } else if (viaProxy !== null && viaProxy !== void 0 && viaProxy.reachable) {
586
+ status = 'warn'; // reachable via proxy only
587
+ } else {
588
+ status = direct ? 'fail' : 'skip';
589
+ }
590
+ const entry = {
591
+ hostname,
592
+ status,
593
+ direct: direct ? {
594
+ reachable: direct.reachable,
595
+ blocked: direct.blocked,
596
+ errors: direct.errors,
597
+ sampleStatus: ((_direct$requests$find = direct.requests.find(r => r.response)) === null || _direct$requests$find === void 0 || (_direct$requests$find = _direct$requests$find.response) === null || _direct$requests$find === void 0 ? void 0 : _direct$requests$find.status) ?? null
598
+ } : null,
599
+ viaProxy: viaProxy ? {
600
+ reachable: viaProxy.reachable,
601
+ blocked: viaProxy.blocked,
602
+ errors: viaProxy.errors,
603
+ sampleStatus: ((_viaProxy$requests$fi = viaProxy.requests.find(r => r.response)) === null || _viaProxy$requests$fi === void 0 || (_viaProxy$requests$fi = _viaProxy$requests$fi.response) === null || _viaProxy$requests$fi === void 0 ? void 0 : _viaProxy$requests$fi.status) ?? null
604
+ } : null
605
+ };
606
+ domainSummary.push(entry);
607
+ }
608
+
609
+ // Sort: failures first
610
+ const order = {
611
+ fail: 0,
612
+ warn: 1,
613
+ pass: 2,
614
+ skip: 3
615
+ };
616
+ /* istanbul ignore next */
617
+ domainSummary.sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9));
618
+
619
+ // ── 5. Aggregate proxy headers ───────────────────────────────────────────
620
+ const proxyHeaders = [...new Set([...directCapture.proxyHeaders, ...((proxyCapture === null || proxyCapture === void 0 ? void 0 : proxyCapture.proxyHeaders) ?? [])])];
621
+
622
+ // ── 6. Overall status ────────────────────────────────────────────────────
623
+ const hasFail = domainSummary.some(d => d.status === 'fail');
624
+ const hasWarn = domainSummary.some(d => d.status === 'warn');
625
+ const overallStatus = hasFail ? 'fail' : hasWarn ? 'warn' : 'pass';
626
+ return {
627
+ status: overallStatus,
628
+ chromePath,
629
+ targetUrl,
630
+ directCapture,
631
+ proxyCapture,
632
+ domainSummary,
633
+ proxyHeaders,
634
+ navMs: directCapture.navMs,
635
+ error: directCapture.error,
636
+ notes
637
+ };
638
+ }
639
+ }
640
+ function _systemChromePaths() {
641
+ const home = os.homedir();
642
+ const platform = os.platform();
643
+ if (platform === 'darwin') {
644
+ return ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium', '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary', path.join(home, 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome')];
645
+ }
646
+ if (platform === 'linux') {
647
+ return ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium-browser', '/usr/bin/chromium', '/snap/bin/chromium'];
648
+ }
649
+ if (platform === 'win32') {
650
+ const pf = safeEnvPath(process.env.PROGRAMFILES, 'C:\\Program Files');
651
+ const pf86 = safeEnvPath(process.env['PROGRAMFILES(X86)'], 'C:\\Program Files (x86)');
652
+ return [path.join(pf, 'Google\\Chrome\\Application\\chrome.exe'), path.join(pf86, 'Google\\Chrome\\Application\\chrome.exe'), path.join(home, 'AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')];
653
+ }
654
+ return [];
655
+ }
656
+ /**
657
+ * Locate a usable Chrome/Chromium binary.
658
+ *
659
+ * Search order:
660
+ * 1. PERCY_BROWSER_EXECUTABLE (user override)
661
+ * 2. Percy's bundled Chromium via @percy/core/src/install.js
662
+ * 3. System-installed Chrome/Chromium (fallback when install fails)
663
+ *
664
+ * @returns {Promise<string|null>}
665
+ */
666
+ async function _findChrome() {
667
+ // 1. User-supplied override — sanitize before use (resolves path-traversal
668
+ // and detect-child-process Semgrep findings: chromePath is always a
669
+ // resolved absolute path with no shell metacharacters by the time it
670
+ // reaches spawn()).
671
+ if (process.env.PERCY_BROWSER_EXECUTABLE) {
672
+ const p = sanitizeExecutablePath(process.env.PERCY_BROWSER_EXECUTABLE);
673
+ /* istanbul ignore next */
674
+ if (p && fs.existsSync(p)) return p;
675
+ }
676
+
677
+ // 2. Percy's bundled Chromium (managed by @percy/core, lazy import)
678
+ try {
679
+ const {
680
+ chromium: installChromium
681
+ } = await import('@percy/core/src/install.js');
682
+ /* istanbul ignore next */
683
+ return await installChromium();
684
+ } catch {/* fall through to system Chrome */}
685
+
686
+ // 3. System Chrome
687
+ for (const p of _assertClassBrand(_BrowserChecker_brand, this, _systemChromePaths).call(this)) {
688
+ /* istanbul ignore next */
689
+ if (fs.existsSync(p)) return p;
690
+ }
691
+ return null;
692
+ }
693
+ // ─── Private: CDP helpers ───────────────────────────────────────────────────
694
+ /** Find a free TCP port by letting the OS assign one. */
695
+ function _getFreePort() {
696
+ return new Promise((resolve, reject) => {
697
+ const srv = net.createServer();
698
+ srv.listen(0, '127.0.0.1', () => {
699
+ const port = srv.address().port;
700
+ srv.close(() => resolve(port));
701
+ });
702
+ srv.on('error', reject);
703
+ });
704
+ }