@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,451 @@
1
+ function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
2
+ function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
3
+ 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"); }
4
+ import cp from 'child_process';
5
+ import { promisify } from 'util';
6
+ import dns from 'dns';
7
+ import fs from 'fs';
8
+ import os from 'os';
9
+ import { httpProber } from '../utils/http.js';
10
+
11
+ // Wrap lazily so that spyOn(cp, 'exec') in tests can intercept the call.
12
+ const exec = (...args) => promisify(cp.exec)(...args);
13
+
14
+ // ─── Proxy environment variable names (case-insensitive handled below) ───────
15
+ const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy'];
16
+ const NO_PROXY_KEYS = ['NO_PROXY', 'no_proxy'];
17
+
18
+ // Process names that indicate a proxy or security agent
19
+ const PROXY_PROCESS_PATTERNS = ['zscaler', 'zsatunnel', 'zsaservice', 'netskope', 'nssvc', 'symantec', 'bluecoat', 'proxysg', 'crowdstrike', 'falcon', 'squid', 'tinyproxy', 'privoxy', 'charles', 'fiddler', 'mitmproxy', 'proxyman', 'burp', 'owasp', 'forticlient', 'anyconnect', 'globalprotect', 'pangps', 'networkserviceproxy', 'iboss', 'mcafee web gateway'];
20
+
21
+ // Response-header names that indicate a proxy is in the path
22
+ const PROXY_HEADER_INDICATORS = ['via', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip', 'forwarded', 'x-proxy-id', 'x-bluecoat-via', 'x-egress-zone', 'x-zscaler-request-id', 'x-netskope-user', 'x-proxyuser-ip', 'proxy-connection'];
23
+
24
+ /**
25
+ * Proxy detector class.
26
+ * All detection layers, validation, and helper logic live here as methods.
27
+ */
28
+ var _ProxyDetector_brand = /*#__PURE__*/new WeakSet();
29
+ export class ProxyDetector {
30
+ constructor() {
31
+ // ─── Layer 2: System-level ─────────────────────────────────────────────────
32
+ _classPrivateMethodInitSpec(this, _ProxyDetector_brand);
33
+ }
34
+ /**
35
+ * Check 3 – Thorough Proxy Detection
36
+ *
37
+ * Detection layers:
38
+ * 1. Environment variables (HTTPS_PROXY, HTTP_PROXY, ALL_PROXY, NO_PROXY)
39
+ * 2. System-level settings (macOS scutil, Linux gsettings, Windows registry)
40
+ * 3. Response-header fingerprinting (Via, X-Forwarded-For, Proxy-* etc.)
41
+ * 4. System process inspection for known proxy/security agents
42
+ * 5. WPAD / DNS auto-discovery
43
+ *
44
+ * @param {object} [options]
45
+ * @param {number} [options.timeout] Request timeout ms
46
+ * @param {boolean} [options.testProxy] Validate discovered proxies
47
+ * @param {boolean} [options.checkHeaders] Fingerprint via HTTP response headers
48
+ * @param {boolean} [options.scanProcesses] Inspect running process list
49
+ * @param {boolean} [options.checkWpad] Test WPAD DNS resolution
50
+ * @returns {Promise<ProxyFinding[]>}
51
+ */
52
+ async detectProxy(options = {}) {
53
+ const {
54
+ timeout = 10000,
55
+ testProxy = true,
56
+ checkHeaders = true,
57
+ scanProcesses = true,
58
+ checkWpad = true
59
+ } = options;
60
+ const findings = [];
61
+ const discovered = new Map(); // proxyUrl → { source }
62
+
63
+ // ── Layer 1: Environment variables ──────────────────────────────────────
64
+ // Use first-write-wins so that on case-insensitive systems (Windows) where
65
+ // HTTPS_PROXY and https_proxy resolve to the same value, the uppercase
66
+ // variant (which comes first in PROXY_ENV_KEYS) keeps the source credit.
67
+ for (const key of PROXY_ENV_KEYS) {
68
+ const val = process.env[key];
69
+ if (val && !discovered.has(val)) discovered.set(val, {
70
+ source: `env:${key}`
71
+ });
72
+ }
73
+ const noProxy = NO_PROXY_KEYS.map(k => process.env[k]).filter(Boolean).join(',');
74
+ if (noProxy) {
75
+ findings.push({
76
+ status: 'info',
77
+ layer: 'environment',
78
+ source: 'env:NO_PROXY',
79
+ message: `NO_PROXY / no_proxy is set: ${noProxy}`,
80
+ proxyUrl: null,
81
+ suggestions: ['Ensure percy.io and browserstack.com are NOT in NO_PROXY if you need the proxy to reach them.']
82
+ });
83
+ }
84
+
85
+ // ── Layer 2: System-level proxy config ──────────────────────────────────
86
+ const platform = os.platform();
87
+ if (platform === 'darwin') {
88
+ const sys = _assertClassBrand(_ProxyDetector_brand, this, _detectMacOSProxy).call(this);
89
+ if (sys) discovered.set(sys.url, {
90
+ source: sys.source
91
+ });
92
+ } else if (platform === 'linux') {
93
+ const sys = _assertClassBrand(_ProxyDetector_brand, this, _detectLinuxProxy).call(this);
94
+ if (sys) discovered.set(sys.url, {
95
+ source: sys.source
96
+ });
97
+ } else if (platform === 'win32') {
98
+ const sys = _assertClassBrand(_ProxyDetector_brand, this, _detectWindowsProxy).call(this);
99
+ if (sys) discovered.set(sys.url, {
100
+ source: sys.source
101
+ });
102
+ }
103
+
104
+ // ── Layer 3: Response-header fingerprinting ──────────────────────────────
105
+ const headerFindings = checkHeaders ? await _assertClassBrand(_ProxyDetector_brand, this, _detectViaHeaders).call(this, timeout) : [];
106
+ for (const hf of headerFindings) {
107
+ findings.push(hf);
108
+ if (hf.detectedProxyUrl) {
109
+ discovered.set(hf.detectedProxyUrl, {
110
+ source: 'header-fingerprint'
111
+ });
112
+ }
113
+ }
114
+
115
+ // ── Layer 4: Process inspection ─────────────────────────────────────────
116
+ const procFindings = scanProcesses ? await _assertClassBrand(_ProxyDetector_brand, this, _detectProxyProcesses).call(this) : [];
117
+ for (const pf of procFindings) findings.push(pf);
118
+
119
+ // ── Layer 5: WPAD / DNS auto-discovery ───────────────────────────────────
120
+ const wpadFindings = checkWpad ? await _assertClassBrand(_ProxyDetector_brand, this, _detectWpad).call(this) : [];
121
+ for (const wf of wpadFindings) findings.push(wf);
122
+
123
+ // ── Emit findings for each discovered proxy URL ──────────────────────────
124
+ const anyDetected = discovered.size > 0 || headerFindings.some(f => f.status !== 'info') || procFindings.some(f => f.status !== 'info');
125
+ if (!anyDetected) {
126
+ findings.push({
127
+ status: 'info',
128
+ layer: 'summary',
129
+ source: 'none',
130
+ message: 'No proxy configuration detected from any detection layer.',
131
+ proxyUrl: null,
132
+ suggestions: ['If you are behind a corporate proxy, set HTTPS_PROXY=https://proxy-host:port.', 'Alternatively add proxy settings to your Percy config file.']
133
+ });
134
+ }
135
+ for (const [proxyUrl, {
136
+ source
137
+ }] of discovered) {
138
+ const finding = {
139
+ layer: 'configuration',
140
+ source,
141
+ proxyUrl,
142
+ message: `Proxy ${proxyUrl} (${source})`
143
+ };
144
+ if (testProxy) {
145
+ const validation = await this.validateProxy(proxyUrl, timeout);
146
+ finding.status = validation.status;
147
+ finding.message += ` — ${validation.message}`;
148
+ finding.suggestions = validation.suggestions;
149
+ finding.proxyValidation = validation;
150
+ } else {
151
+ finding.status = 'info';
152
+ }
153
+ findings.push(finding);
154
+ }
155
+ return findings;
156
+ }
157
+ // ─── Proxy validation ───────────────────────────────────────────────────────
158
+
159
+ async validateProxy(proxyUrl, timeout) {
160
+ const TEST_URLS = ['https://percy.io', 'https://www.browserstack.com'];
161
+ const results = await Promise.all(TEST_URLS.map(u => httpProber.probeUrl(u, {
162
+ proxyUrl,
163
+ timeout
164
+ })));
165
+ const allOk = results.every(r => r.ok);
166
+ const anyOk = results.some(r => r.ok);
167
+ if (allOk) {
168
+ return {
169
+ status: 'pass',
170
+ message: 'proxy connectivity OK for percy.io and browserstack.com',
171
+ suggestions: []
172
+ };
173
+ }
174
+ if (anyOk) {
175
+ const failed = TEST_URLS.filter((_, i) => !results[i].ok);
176
+ return {
177
+ status: 'warn',
178
+ message: `proxy reachable but could not connect to: ${failed.join(', ')}`,
179
+ suggestions: ['Whitelist the unreachable domains on your proxy server.', 'Check if proxy authentication is required (HTTPS_PROXY=http://user:pass@host:port).']
180
+ };
181
+ }
182
+
183
+ /* istanbul ignore next */
184
+ const errors = results.map((r, i) => `${new URL(TEST_URLS[i]).hostname}: ${r.errorCode ?? r.error}`).join(', ');
185
+ const hasSslError = results.some(r => httpProber.isSslError(r));
186
+ const suggestions = ['Verify the proxy is running and allows outbound HTTPS to percy.io.', 'If credentials needed: HTTPS_PROXY=http://user:pass@host:port'];
187
+ if (hasSslError) {
188
+ suggestions.push('The proxy is intercepting HTTPS with its own certificate (SSL inspection).', 'Temporary bypass: export NODE_TLS_REJECT_UNAUTHORIZED=0 (re-run percy doctor to verify)', 'Or trust the proxy CA: export NODE_EXTRA_CA_CERTS=/path/to/proxy-ca.crt');
189
+ }
190
+ return {
191
+ status: 'fail',
192
+ message: `proxy cannot reach Percy/BrowserStack — ${errors}`,
193
+ suggestions
194
+ };
195
+ }
196
+ }
197
+ function _detectMacOSProxy() {
198
+ try {
199
+ const out = cp.execSync('scutil --proxy', {
200
+ timeout: 5000,
201
+ encoding: 'utf8'
202
+ });
203
+
204
+ // HTTPS proxy takes priority, fall back to HTTP
205
+ const httpsEnabled = /HTTPSEnable\s*:\s*1/i.test(out);
206
+ const httpEnabled = /HTTPEnable\s*:\s*1/i.test(out);
207
+ if (httpsEnabled) {
208
+ var _out$match, _out$match2;
209
+ const host = (_out$match = out.match(/HTTPSProxy\s*:\s*(\S+)/i)) === null || _out$match === void 0 ? void 0 : _out$match[1];
210
+ /* istanbul ignore next */
211
+ const port = ((_out$match2 = out.match(/HTTPSPort\s*:\s*(\d+)/i)) === null || _out$match2 === void 0 ? void 0 : _out$match2[1]) ?? '8080';
212
+ /* istanbul ignore next */
213
+ if (host) return {
214
+ url: `http://${host}:${port}`,
215
+ source: 'macOS:scutil(HTTPS)'
216
+ };
217
+ }
218
+ if (httpEnabled) {
219
+ var _out$match3, _out$match4;
220
+ const host = (_out$match3 = out.match(/HTTPProxy\s*:\s*(\S+)/i)) === null || _out$match3 === void 0 ? void 0 : _out$match3[1];
221
+ /* istanbul ignore next */
222
+ const port = ((_out$match4 = out.match(/HTTPPort\s*:\s*(\d+)/i)) === null || _out$match4 === void 0 ? void 0 : _out$match4[1]) ?? '8080';
223
+ /* istanbul ignore next */
224
+ if (host) return {
225
+ url: `http://${host}:${port}`,
226
+ source: 'macOS:scutil(HTTP)'
227
+ };
228
+ }
229
+ } catch {/* ignore */}
230
+ return null;
231
+ }
232
+ function _detectLinuxProxy() {
233
+ // Try GNOME gsettings
234
+ try {
235
+ const mode = cp.execSync('gsettings get org.gnome.system.proxy mode 2>/dev/null', {
236
+ timeout: 3000,
237
+ encoding: 'utf8'
238
+ }).trim().replace(/'/g, '');
239
+ if (mode === 'manual') {
240
+ const host = cp.execSync('gsettings get org.gnome.system.proxy.https host 2>/dev/null', {
241
+ timeout: 3000,
242
+ encoding: 'utf8'
243
+ }).trim().replace(/'/g, '');
244
+ const port = cp.execSync('gsettings get org.gnome.system.proxy.https port 2>/dev/null', {
245
+ timeout: 3000,
246
+ encoding: 'utf8'
247
+ }).trim();
248
+ /* istanbul ignore next */
249
+ if (host && host !== "''") {
250
+ return {
251
+ url: `http://${host}:${port}`,
252
+ source: 'linux:gsettings'
253
+ };
254
+ }
255
+ }
256
+ } catch {/* ignore */}
257
+
258
+ // Try /etc/environment
259
+ try {
260
+ const env = fs.readFileSync('/etc/environment', 'utf8');
261
+ const match = env.match(/(?:HTTPS?_PROXY|https?_proxy)\s*=\s*['"]?([^'"\s]+)/i);
262
+ /* istanbul ignore next */
263
+ if (match) return {
264
+ url: match[1],
265
+ source: 'linux:/etc/environment'
266
+ };
267
+ } catch {/* ignore */}
268
+
269
+ // Try /etc/profile.d/ scripts
270
+ try {
271
+ const dir = '/etc/profile.d';
272
+ if (fs.existsSync(dir)) {
273
+ for (const file of fs.readdirSync(dir)) {
274
+ try {
275
+ const content = fs.readFileSync(`${dir}/${file}`, 'utf8');
276
+ const m = content.match(/export\s+(?:HTTPS?_PROXY|https?_proxy)\s*=\s*['"]?([^'"\s'"]+)/i);
277
+ /* istanbul ignore next */
278
+ if (m) return {
279
+ url: m[1],
280
+ source: `linux:${dir}/${file}`
281
+ };
282
+ } catch {/* ignore */}
283
+ }
284
+ }
285
+ } catch {/* ignore */}
286
+ return null;
287
+ }
288
+ function _detectWindowsProxy() {
289
+ try {
290
+ const enableOut = cp.execSync('reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable 2>nul', {
291
+ timeout: 5000,
292
+ encoding: 'utf8'
293
+ });
294
+ if (!enableOut.includes('0x1')) return null;
295
+ const serverOut = cp.execSync('reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer 2>nul', {
296
+ timeout: 5000,
297
+ encoding: 'utf8'
298
+ });
299
+ const m = serverOut.match(/ProxyServer\s+REG_SZ\s+(\S+)/);
300
+ /* istanbul ignore next */
301
+ if (!m) return null;
302
+ let url = m[1].trim();
303
+ /* istanbul ignore next */
304
+ if (!url.startsWith('http')) url = `http://${url}`;
305
+ return {
306
+ url,
307
+ source: 'windows:registry'
308
+ };
309
+ } catch {
310
+ return null;
311
+ }
312
+ }
313
+ // ─── Layer 3: HTTP response-header fingerprinting ──────────────────────────
314
+ async function _detectViaHeaders(timeout) {
315
+ // Probe a few endpoints and check response headers for proxy indicators
316
+ const PROBE_TARGETS = ['https://percy.io', 'http://percy.io' // plain HTTP — proxy headers are more visible
317
+ ];
318
+ const findings = [];
319
+ for (const target of PROBE_TARGETS) {
320
+ try {
321
+ const result = await httpProber.probeUrl(target, {
322
+ timeout
323
+ });
324
+ /* istanbul ignore next */
325
+ if (!result.responseHeaders) continue;
326
+ const found = {};
327
+ for (const [key, value] of Object.entries(result.responseHeaders)) {
328
+ const lk = key.toLowerCase();
329
+ if (PROXY_HEADER_INDICATORS.some(h => lk === h || lk.startsWith(h))) {
330
+ found[key] = value;
331
+ }
332
+ }
333
+ if (Object.keys(found).length > 0) {
334
+ var _Object$entries$find;
335
+ // Extract proxy address from Via header if present
336
+ let detectedProxyUrl = null;
337
+ const viaVal = (_Object$entries$find = Object.entries(found).find(([k]) => k.toLowerCase() === 'via')) === null || _Object$entries$find === void 0 ? void 0 : _Object$entries$find[1];
338
+ if (viaVal) {
339
+ // Via: 1.1 proxy.corp.example.com:8080 (Squid/4.1)
340
+ const m = viaVal.match(/\d+\.\d+\s+([^:,\s(]+)(?::(\d+))?/);
341
+ /* istanbul ignore next */
342
+ if (m && m[1] && !m[1].match(/^\d+\.\d+\.\d+\.\d+$/)) {
343
+ detectedProxyUrl = `http://${m[1].trim()}:${m[2] ?? '8080'}`;
344
+ }
345
+ }
346
+ findings.push({
347
+ status: 'warn',
348
+ layer: 'header-fingerprint',
349
+ source: target,
350
+ message: `Proxy-indicating headers detected in response from ${target}`,
351
+ headers: found,
352
+ detectedProxyUrl,
353
+ suggestions: ['Your HTTP traffic is being intercepted by a proxy or security appliance.', detectedProxyUrl ? `Possible proxy address from Via header: set HTTPS_PROXY=${detectedProxyUrl}` : 'Set HTTPS_PROXY to your corporate proxy address.', 'Check with your network team for the correct proxy endpoint.']
354
+ });
355
+ }
356
+ } catch {/* probe failed, skip */}
357
+ }
358
+ if (findings.length === 0) {
359
+ findings.push({
360
+ status: 'info',
361
+ layer: 'header-fingerprint',
362
+ source: 'header-scan',
363
+ message: 'No proxy-indicating headers detected in HTTP responses.',
364
+ headers: {}
365
+ });
366
+ }
367
+ return findings;
368
+ }
369
+ // ─── Layer 4: Process inspection ───────────────────────────────────────────
370
+ async function _detectProxyProcesses() {
371
+ const findings = [];
372
+ let processList = '';
373
+ try {
374
+ const platform = os.platform();
375
+ if (platform === 'win32') {
376
+ const {
377
+ stdout
378
+ } = await exec('tasklist /fo csv /nh 2>nul', {
379
+ timeout: 5000
380
+ });
381
+ processList = stdout.toLowerCase();
382
+ } else {
383
+ const {
384
+ stdout
385
+ } = await exec('ps aux 2>/dev/null || ps -ef 2>/dev/null', {
386
+ timeout: 5000
387
+ });
388
+ processList = stdout.toLowerCase();
389
+ }
390
+ } catch {/* ignore */}
391
+ const matched = PROXY_PROCESS_PATTERNS.filter(p => processList.includes(p.toLowerCase()));
392
+ if (matched.length > 0) {
393
+ findings.push({
394
+ status: 'warn',
395
+ layer: 'process-inspection',
396
+ source: 'process-scan',
397
+ message: `Security agent(s) detected: ${matched.join(', ')} — may intercept HTTPS`,
398
+ processes: matched,
399
+ suggestions: ['Set HTTPS_PROXY to your proxy endpoint, or add its root CA to NODE_EXTRA_CA_CERTS.', 'Zscaler: set HTTPS_PROXY to ZIA gateway. Netskope: HTTPS_PROXY=http://localhost:8080.']
400
+ });
401
+ } else {
402
+ findings.push({
403
+ status: 'info',
404
+ layer: 'process-inspection',
405
+ source: 'process-scan',
406
+ message: 'No known proxy/security agent processes detected.'
407
+ });
408
+ }
409
+ return findings;
410
+ }
411
+ // ─── Layer 5: WPAD / DNS auto-discovery ────────────────────────────────────
412
+ async function _detectWpad() {
413
+ const findings = [];
414
+ const wpadHosts = ['wpad'];
415
+ try {
416
+ const hostname = os.hostname();
417
+ const parts = hostname.split('.');
418
+ if (parts.length > 1) wpadHosts.push(`wpad.${parts.slice(1).join('.')}`);
419
+ } catch {/* ignore */}
420
+ for (const wpadHost of wpadHosts) {
421
+ try {
422
+ const addresses = await new Promise((resolve, reject) => {
423
+ dns.resolve4(wpadHost, (err, addrs) => err ? reject(err) : resolve(addrs));
424
+ });
425
+ if (addresses.length > 0) {
426
+ const wpadUrl = `http://${wpadHost}/wpad.dat`;
427
+ findings.push({
428
+ status: 'warn',
429
+ layer: 'wpad-discovery',
430
+ source: `dns:${wpadHost}`,
431
+ wpadHost,
432
+ wpadUrl,
433
+ resolvedIPs: addresses,
434
+ message: `WPAD host "${wpadHost}" resolves to ${addresses[0]} — auto-proxy may be active`,
435
+ suggestions: [`Inspect the PAC file: curl "${wpadUrl}"`, 'See the PAC Detection section above for details on the resolved proxy.', 'If WPAD routes percy.io via a proxy, set HTTPS_PROXY accordingly.']
436
+ });
437
+ }
438
+ } catch (err) {
439
+ /* NXDOMAIN — no WPAD on this host */
440
+ }
441
+ }
442
+ if (findings.length === 0) {
443
+ findings.push({
444
+ status: 'info',
445
+ layer: 'wpad-discovery',
446
+ source: 'wpad-dns',
447
+ message: 'No WPAD host found via DNS auto-discovery.'
448
+ });
449
+ }
450
+ return findings;
451
+ }
package/dist/doctor.js ADDED
@@ -0,0 +1,100 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import command from '@percy/cli-command';
5
+ import { captureProxyEnv, redactProxyUrl, runConnectivityAndSSL, runProxyCheck, runPACCheck, runBrowserCheck } from './utils/helpers.js';
6
+ import { checkLine, print } from './utils/reporter.js';
7
+ import { getPackageJSON } from '@percy/cli-command/utils';
8
+ const pkg = getPackageJSON(import.meta.url);
9
+ export const doctor = command('doctor', {
10
+ description: 'Diagnose network connectivity and configuration for Percy builds',
11
+ examples: ['$0', '$0 --proxy-server http://proxy.corp.example.com:8080', '$0 --url https://my-staging.example.com', '$0 --output-json ./percy-doctor.json'],
12
+ flags: [{
13
+ name: 'proxy-server',
14
+ description: 'Proxy server URL to test alongside direct connectivity (e.g. http://proxy:8080)',
15
+ type: 'string',
16
+ attribute: 'proxyServer'
17
+ }, {
18
+ name: 'url',
19
+ description: 'URL to open in Chrome for network activity analysis (default: https://percy.io)',
20
+ type: 'string'
21
+ }, {
22
+ name: 'timeout',
23
+ description: 'Per-request timeout in milliseconds (default: 10000)',
24
+ type: 'string',
25
+ default: '10000'
26
+ }, {
27
+ name: 'output-json',
28
+ description: 'Write the full diagnostic report to a JSON file',
29
+ type: 'string',
30
+ attribute: 'outputJson'
31
+ }]
32
+ }, async ({
33
+ flags,
34
+ log,
35
+ exit
36
+ }) => {
37
+ var _flags$url;
38
+ const proxyUrl = flags.proxyServer || process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null;
39
+ const timeout = parseInt(flags.timeout ?? '10000', 10);
40
+ if (isNaN(timeout) || timeout <= 0) {
41
+ log.error('--timeout must be a positive integer (milliseconds)');
42
+ return exit(1, '--timeout must be a positive integer', false);
43
+ }
44
+ const targetUrl = ((_flags$url = flags.url) === null || _flags$url === void 0 ? void 0 : _flags$url.trim()) || 'https://percy.io';
45
+ const jsonOutputPath = flags.outputJson ?? null;
46
+ const report = {
47
+ timestamp: new Date().toISOString(),
48
+ environment: {
49
+ percyCLIVersion: pkg.version,
50
+ platform: process.platform,
51
+ arch: process.arch,
52
+ nodeVersion: process.version,
53
+ hostname: os.hostname(),
54
+ proxyEnv: captureProxyEnv()
55
+ },
56
+ checks: {}
57
+ };
58
+ print(log, '\n Percy Doctor — network readiness check\n');
59
+ if (proxyUrl) {
60
+ print(log, checkLine('info', `Proxy in use: ${redactProxyUrl(proxyUrl)}`));
61
+ print(log, '');
62
+ }
63
+ const {
64
+ connectivity,
65
+ ssl
66
+ } = await runConnectivityAndSSL(proxyUrl, timeout);
67
+ report.checks.connectivity = connectivity;
68
+ report.checks.ssl = ssl;
69
+ const {
70
+ proxy
71
+ } = await runProxyCheck(timeout);
72
+ report.checks.proxy = proxy;
73
+ const {
74
+ pac
75
+ } = await runPACCheck();
76
+ report.checks.pac = pac;
77
+ const {
78
+ browser
79
+ } = await runBrowserCheck(targetUrl, proxyUrl, timeout);
80
+ report.checks.browser = browser;
81
+ report.summary = {
82
+ overall: Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'fail') ? 'fail' : Object.values(report.checks).some(c => (c === null || c === void 0 ? void 0 : c.status) === 'warn') ? 'warn' : 'pass'
83
+ };
84
+ if (jsonOutputPath) {
85
+ try {
86
+ // cli-doctor runs inside the customer's own CI environment; jsonOutputPath is a
87
+ // CLI flag value supplied by the operator, not arbitrary remote user input.
88
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
89
+ const absPath = path.resolve(process.cwd(), jsonOutputPath);
90
+ fs.writeFileSync(absPath, JSON.stringify(report, null, 2), 'utf8');
91
+ print(log, checkLine('info', `Full report saved to: ${absPath}`));
92
+ } catch (err) {
93
+ log.warn(`Could not write JSON report: ${err.message}`);
94
+ }
95
+ }
96
+ if (report.summary.overall === 'fail') {
97
+ exit(1, '', false);
98
+ }
99
+ });
100
+ export default doctor;
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { default, doctor } from './doctor.js';
2
+ export { ConnectivityChecker, REQUIRED_DOMAINS } from './checks/connectivity.js';
3
+ export { ProxyDetector } from './checks/proxy.js';
4
+ export { PACDetector, runPacScript, findInObject } from './checks/pac.js';
5
+ export { BrowserChecker, NetworkCapture, analyseCapture, sanitizeExecutablePath, safeEnvPath, safeHostname } from './checks/browser.js';
6
+ export { runDiagnostics, redactProxyUrl, captureProxyEnv, PERCY_DOMAINS } from './utils/helpers.js';