@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,189 @@
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 { httpProber } from '../utils/http.js';
5
+
6
+ // Domains that Percy's infrastructure relies on
7
+ export const REQUIRED_DOMAINS = [{
8
+ label: 'Percy API',
9
+ url: 'https://percy.io'
10
+ }, {
11
+ label: 'BrowserStack API',
12
+ url: 'https://www.browserstack.com'
13
+ }, {
14
+ label: 'BrowserStack Automate',
15
+ url: 'https://hub.browserstack.com'
16
+ }, {
17
+ label: 'Chromium download CDN',
18
+ url: 'https://storage.googleapis.com',
19
+ optional: true,
20
+ onFail: ['Percy downloads Chromium from storage.googleapis.com for visual asset capture.', 'To fix: set PERCY_BROWSER_EXECUTABLE=/path/to/chrome to use an installed browser,', 'or mirror the Chromium CDN: export PERCY_CHROMIUM_BASE_URL=https://your-mirror/chromium/']
21
+ }];
22
+
23
+ /**
24
+ * Connectivity and SSL checker class.
25
+ * All probing, SSL analysis and result classification logic lives here.
26
+ */
27
+ var _ConnectivityChecker_brand = /*#__PURE__*/new WeakSet();
28
+ export class ConnectivityChecker {
29
+ constructor() {
30
+ /**
31
+ * Build SSL findings from a percy.io probe result.
32
+ * Mirrors the ssl.js checkSSL() logic, but reuses an existing probe result
33
+ * rather than issuing a new HTTP request.
34
+ */
35
+ _classPrivateMethodInitSpec(this, _ConnectivityChecker_brand);
36
+ }
37
+ /**
38
+ * Combined connectivity + SSL check.
39
+ *
40
+ * Runs all required-domain probes in parallel, then derives SSL findings from
41
+ * the same percy.io probe result — no duplicate HTTP roundtrip.
42
+ *
43
+ * @param {object} [options]
44
+ * @param {string} [options.proxyUrl] - Proxy to test alongside direct
45
+ * @param {number} [options.timeout] - Per-request timeout ms (default 10 000)
46
+ * @returns {Promise<{ connectivityFindings: Array, sslFindings: Array }>}
47
+ */
48
+ async checkConnectivityAndSSL(options = {}) {
49
+ const {
50
+ proxyUrl,
51
+ timeout = 10000
52
+ } = options;
53
+ const rawFindings = await Promise.all(REQUIRED_DOMAINS.map(async ({
54
+ label,
55
+ url,
56
+ optional,
57
+ onFail
58
+ }) => {
59
+ const finding = await _assertClassBrand(_ConnectivityChecker_brand, this, _probeTarget).call(this, label, url, proxyUrl, timeout);
60
+ if (optional && finding.status === 'fail') {
61
+ finding.status = 'warn';
62
+ if (onFail) {
63
+ finding.suggestions = onFail;
64
+ }
65
+ }
66
+ return finding;
67
+ }));
68
+
69
+ // Sort: failures first, then warnings, then passes
70
+ const order = {
71
+ fail: 0,
72
+ warn: 1,
73
+ pass: 2,
74
+ skip: 3
75
+ };
76
+ /* istanbul ignore next */
77
+ rawFindings.sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9));
78
+
79
+ // Reuse the percy.io connectivity probe result for the SSL check — no extra
80
+ // HTTP round-trip needed.
81
+ const percyFinding = rawFindings.find(f => f.url === 'https://percy.io');
82
+ const sslFindings = _assertClassBrand(_ConnectivityChecker_brand, this, _buildSSLFindings).call(this, percyFinding === null || percyFinding === void 0 ? void 0 : percyFinding.directResult);
83
+ return {
84
+ connectivityFindings: rawFindings,
85
+ sslFindings
86
+ };
87
+ }
88
+ }
89
+ function _buildSSLFindings(percyProbeResult) {
90
+ const findings = [];
91
+ if (process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0') {
92
+ findings.push({
93
+ status: 'warn',
94
+ message: 'NODE_TLS_REJECT_UNAUTHORIZED=0 is set — SSL certificate validation is DISABLED.',
95
+ suggestions: ['SSL check results may not reflect your actual certificate status.', 'This is typically a temporary workaround. Remove after diagnosing the underlying SSL issue.', 'Consider using NODE_EXTRA_CA_CERTS=/path/to/ca.crt instead for a permanent fix.']
96
+ });
97
+ }
98
+ if (!percyProbeResult) {
99
+ findings.push({
100
+ status: 'skip',
101
+ message: 'SSL check skipped — percy.io was not probed.'
102
+ });
103
+ return findings;
104
+ }
105
+ if (httpProber.isSslError(percyProbeResult)) {
106
+ findings.push({
107
+ status: 'fail',
108
+ message: `SSL error connecting to percy.io: ${percyProbeResult.error} [${percyProbeResult.errorCode}]`,
109
+ suggestions: ['Your network proxy or VPN may be intercepting HTTPS traffic with its own certificate.', 'Ask your network admin to add percy.io to the SSL inspection exclusion list.', 'Solution: 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']
110
+ });
111
+ } else if (!percyProbeResult.ok && percyProbeResult.errorCode !== 'ECONNREFUSED' && percyProbeResult.status === 0) {
112
+ findings.push({
113
+ status: 'skip',
114
+ message: `Could not reach percy.io over HTTPS (${percyProbeResult.errorCode ?? percyProbeResult.error}). SSL check skipped – see connectivity check.`
115
+ });
116
+ } else {
117
+ findings.push({
118
+ status: 'pass',
119
+ message: `SSL handshake with percy.io succeeded (${percyProbeResult.latencyMs}ms).`
120
+ });
121
+ }
122
+ return findings;
123
+ }
124
+ async function _probeTarget(label, url, proxyUrl, timeout) {
125
+ // Direct probe — Node honours NODE_TLS_REJECT_UNAUTHORIZED automatically
126
+ const direct = await httpProber.probeUrl(url, {
127
+ timeout
128
+ });
129
+
130
+ // Proxy probe (only if a proxy is configured)
131
+ const viaProxy = proxyUrl ? await httpProber.probeUrl(url, {
132
+ proxyUrl,
133
+ timeout
134
+ }) : null;
135
+
136
+ // ── classify ────────────────────────────────────────────────────────────
137
+
138
+ // SSL errors are surfaced here too so the user sees them in context
139
+ if (httpProber.isSslError(direct)) {
140
+ return {
141
+ status: 'fail',
142
+ label,
143
+ url,
144
+ directResult: direct,
145
+ proxyResult: viaProxy,
146
+ message: `SSL error for ${label} (${url}): ${direct.errorCode}`,
147
+ suggestions: ['See the SSL / TLS section above for remediation steps.', 'Ensure your network proxy is not performing SSL inspection on percy.io / browserstack.com.', 'Solution: export NODE_TLS_REJECT_UNAUTHORIZED=0']
148
+ };
149
+ }
150
+
151
+ // Any HTTP response (even 4xx/5xx) means the server is network-reachable.
152
+ // Endpoints like hub.browserstack.com return 401/403 without credentials — that is still reachable.
153
+ const directReachable = direct.ok || direct.status > 0 && !direct.errorCode;
154
+ const proxyReachable = viaProxy && (viaProxy.ok || viaProxy.status > 0 && !viaProxy.errorCode);
155
+ if (directReachable) {
156
+ return {
157
+ status: 'pass',
158
+ label,
159
+ url,
160
+ directResult: direct,
161
+ proxyResult: viaProxy,
162
+ message: `${label} is reachable directly (HTTP ${direct.status}, ${direct.latencyMs}ms).`
163
+ };
164
+ }
165
+
166
+ // Direct failed – check if proxy helps
167
+ if (proxyReachable) {
168
+ return {
169
+ status: 'warn',
170
+ label,
171
+ url,
172
+ directResult: direct,
173
+ proxyResult: viaProxy,
174
+ message: `${label} is reachable via proxy but NOT directly.`,
175
+ suggestions: [`Ensure the proxy server is configured: set HTTPS_PROXY=${proxyUrl}`, 'Add proxy settings to your Percy config file under the proxy key.', `Direct error: ${direct.errorCode ?? direct.error}`]
176
+ };
177
+ }
178
+
179
+ // Both direct and proxy failed (or no proxy configured)
180
+ return {
181
+ status: 'fail',
182
+ label,
183
+ url,
184
+ directResult: direct,
185
+ proxyResult: viaProxy,
186
+ message: `${label} (${url}) is NOT reachable.`,
187
+ suggestions: [`Ensure your network allows outbound HTTPS to ${new URL(url).hostname}.`, 'Contact your network/IT team to whitelist: percy.io, www.browserstack.com, hub.browserstack.com.', 'If behind a corporate proxy, set HTTPS_PROXY=http://proxy-host:port in your environment.']
188
+ };
189
+ }
@@ -0,0 +1,419 @@
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 fs from 'fs';
6
+ import path from 'path';
7
+ import os from 'os';
8
+ import vm from 'vm';
9
+ import { minimatch } from 'minimatch';
10
+
11
+ // Test URL used when evaluating PAC scripts
12
+ const PAC_TEST_URL = 'https://percy.io/';
13
+ const PAC_TEST_HOST = 'percy.io';
14
+
15
+ /**
16
+ * PAC detector class.
17
+ * All PAC discovery, fetching, and evaluation logic lives here as methods.
18
+ */
19
+ var _PACDetector_brand = /*#__PURE__*/new WeakSet();
20
+ export class PACDetector {
21
+ constructor() {
22
+ // ─── macOS ────────────────────────────────────────────────────────────────────
23
+ _classPrivateMethodInitSpec(this, _PACDetector_brand);
24
+ }
25
+ /**
26
+ * Check 4 – PAC (Proxy Auto-Configuration) File Detection
27
+ *
28
+ * @returns {Promise<PacFinding[]>}
29
+ */
30
+ async detectPAC() {
31
+ const findings = [];
32
+ const discovered = []; // { url, source }
33
+
34
+ if (process.env.PERCY_PAC_FILE_URL) {
35
+ discovered.push({
36
+ url: process.env.PERCY_PAC_FILE_URL,
37
+ source: 'env:PERCY_PAC_FILE_URL'
38
+ });
39
+ }
40
+ const platform = os.platform();
41
+ if (platform === 'darwin') discovered.push(..._assertClassBrand(_PACDetector_brand, this, _macOSPacUrls).call(this));else if (platform === 'linux') discovered.push(..._assertClassBrand(_PACDetector_brand, this, _linuxPacUrls).call(this));else if (platform === 'win32') discovered.push(..._assertClassBrand(_PACDetector_brand, this, _windowsPacUrls).call(this));
42
+ discovered.push(..._assertClassBrand(_PACDetector_brand, this, _chromePacUrls).call(this));
43
+ discovered.push(..._assertClassBrand(_PACDetector_brand, this, _firefoxPacUrls).call(this));
44
+ if (discovered.length === 0) {
45
+ findings.push({
46
+ status: 'info',
47
+ source: 'none',
48
+ message: 'No PAC (Proxy Auto-Configuration) file detected.',
49
+ pacUrl: null,
50
+ resolvedProxy: null,
51
+ suggestions: []
52
+ });
53
+ return findings;
54
+ }
55
+ for (const {
56
+ url: pacUrl,
57
+ source
58
+ } of discovered) {
59
+ const finding = await _assertClassBrand(_PACDetector_brand, this, _evaluatePac).call(this, pacUrl, source);
60
+ findings.push(finding);
61
+ }
62
+ return findings;
63
+ }
64
+ }
65
+
66
+ // ─── Standalone utility exports ───────────────────────────────────────────────
67
+ // Pure stateless functions exported for direct use and unit testing.
68
+
69
+ /** Recursively search an object for a key, return first value found. */
70
+ function _macOSPacUrls() {
71
+ const urls = [];
72
+ const interfaces = ['Wi-Fi', 'Ethernet', 'en0', 'en1'];
73
+ for (const iface of interfaces) {
74
+ try {
75
+ var _enabledMatch$;
76
+ const out = cp.execSync(`networksetup -getautoproxyurl "${iface}" 2>/dev/null`, {
77
+ timeout: 4000,
78
+ encoding: 'utf8'
79
+ });
80
+ const urlMatch = out.match(/URL:\s*(\S+)/);
81
+ const enabledMatch = out.match(/Enabled:\s*(\w+)/i);
82
+ if (urlMatch && (enabledMatch === null || enabledMatch === void 0 || (_enabledMatch$ = enabledMatch[1]) === null || _enabledMatch$ === void 0 ? void 0 : _enabledMatch$.toLowerCase()) === 'yes') {
83
+ const url = urlMatch[1].trim();
84
+ urls.push({
85
+ url,
86
+ source: `macOS:networksetup(${iface})`
87
+ });
88
+ break;
89
+ }
90
+ } catch {/* interface not available */}
91
+ }
92
+
93
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
94
+ const plistPaths = ['/Library/Preferences/SystemConfiguration/preferences.plist', path.join(os.homedir(), 'Library/Preferences/com.apple.systempreferences.plist')];
95
+ for (const p of plistPaths) {
96
+ if (!fs.existsSync(p)) continue;
97
+ try {
98
+ const json = cp.execSync(`plutil -convert json -o - "${p}" 2>/dev/null`, {
99
+ timeout: 4000,
100
+ encoding: 'utf8'
101
+ });
102
+ const data = JSON.parse(json);
103
+ const pacUrl = findInObject(data, 'ProxyAutoConfigURLString');
104
+ /* istanbul ignore next */
105
+ if (pacUrl) urls.push({
106
+ url: pacUrl,
107
+ source: 'macOS:plist'
108
+ });
109
+ } catch {/* ignore */}
110
+ }
111
+ return urls;
112
+ }
113
+ // ─── Linux ────────────────────────────────────────────────────────────────────
114
+ function _linuxPacUrls() {
115
+ const urls = [];
116
+ try {
117
+ const mode = cp.execSync('gsettings get org.gnome.system.proxy mode 2>/dev/null', {
118
+ timeout: 3000,
119
+ encoding: 'utf8'
120
+ }).trim().replace(/'/g, '');
121
+ if (mode === 'auto') {
122
+ const pacUrl = cp.execSync('gsettings get org.gnome.system.proxy autoconfig-url 2>/dev/null', {
123
+ timeout: 3000,
124
+ encoding: 'utf8'
125
+ }).trim().replace(/'/g, '');
126
+ if (pacUrl && pacUrl !== "''") urls.push({
127
+ url: pacUrl,
128
+ source: 'linux:gsettings'
129
+ });
130
+ }
131
+ } catch {/* gsettings not available */}
132
+ try {
133
+ const env = fs.readFileSync('/etc/environment', 'utf8');
134
+ const match = env.match(/(?:AUTO_PROXY|auto_proxy|WPAD_URL)\s*=\s*['"]?([^'"\s]+)/i);
135
+ if (match) urls.push({
136
+ url: match[1],
137
+ source: 'linux:/etc/environment'
138
+ });
139
+ } catch {/* ignore */}
140
+ return urls;
141
+ }
142
+ // ─── Windows ──────────────────────────────────────────────────────────────────
143
+ function _windowsPacUrls() {
144
+ const urls = [];
145
+ try {
146
+ const out = cp.execSync('reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v AutoConfigURL 2>nul', {
147
+ timeout: 5000,
148
+ encoding: 'utf8'
149
+ });
150
+ const match = out.match(/AutoConfigURL\s+REG_SZ\s+(\S+)/);
151
+ if (match) urls.push({
152
+ url: match[1].trim(),
153
+ source: 'windows:registry'
154
+ });
155
+ } catch {/* ignore */}
156
+ return urls;
157
+ }
158
+ // ─── Chrome / Chromium ────────────────────────────────────────────────────────
159
+ function _chromePacUrls() {
160
+ const urls = [];
161
+ const platform = os.platform();
162
+ const localStateLocations = {
163
+ darwin: [path.join(os.homedir(), 'Library/Application Support/Google/Chrome/Local State'), path.join(os.homedir(), 'Library/Application Support/Chromium/Local State')],
164
+ linux: [path.join(os.homedir(), '.config/google-chrome/Local State'), path.join(os.homedir(), '.config/chromium/Local State')],
165
+ win32: [path.join(os.homedir(), 'AppData/Local/Google/Chrome/User Data/Local State'), path.join(os.homedir(), 'AppData/Local/Chromium/User Data/Local State')]
166
+ }[platform] ?? [];
167
+ for (const localStatePath of localStateLocations) {
168
+ if (!fs.existsSync(localStatePath)) continue;
169
+ try {
170
+ const state = JSON.parse(fs.readFileSync(localStatePath, 'utf8'));
171
+ const prefsPath = path.join(path.dirname(localStatePath), 'Default/Preferences');
172
+ /* istanbul ignore if */
173
+ if (fs.existsSync(prefsPath)) {
174
+ var _prefs$proxy, _prefs$chromeos;
175
+ const prefs = JSON.parse(fs.readFileSync(prefsPath, 'utf8'));
176
+ const pacScript = (prefs === null || prefs === void 0 || (_prefs$proxy = prefs.proxy) === null || _prefs$proxy === void 0 ? void 0 : _prefs$proxy.pac_url) || (prefs === null || prefs === void 0 || (_prefs$chromeos = prefs.chromeos) === null || _prefs$chromeos === void 0 || (_prefs$chromeos = _prefs$chromeos.proxy) === null || _prefs$chromeos === void 0 ? void 0 : _prefs$chromeos.pac_url) || findInObject((prefs === null || prefs === void 0 ? void 0 : prefs.proxy) ?? {}, 'pac_url');
177
+ if (pacScript) {
178
+ urls.push({
179
+ url: pacScript,
180
+ source: `chrome:Preferences(${path.dirname(prefsPath)})`
181
+ });
182
+ }
183
+ }
184
+ const extProxies = findInObject(state, 'pac_url') ?? findInObject(state, 'pac_script');
185
+ if (extProxies) urls.push({
186
+ url: extProxies,
187
+ source: 'chrome:extension'
188
+ });
189
+ } catch {/* ignore parse errors */}
190
+ }
191
+ return urls;
192
+ }
193
+ // ─── Firefox ──────────────────────────────────────────────────────────────────
194
+ function _firefoxPacUrls() {
195
+ const urls = [];
196
+ const platform = os.platform();
197
+ const profileDirs = {
198
+ darwin: path.join(os.homedir(), 'Library/Application Support/Firefox/Profiles'),
199
+ linux: path.join(os.homedir(), '.mozilla/firefox'),
200
+ win32: path.join(os.homedir(), 'AppData/Roaming/Mozilla/Firefox/Profiles')
201
+ }[platform];
202
+ if (!profileDirs || !fs.existsSync(profileDirs)) return urls;
203
+ let profileEntries = [];
204
+ try {
205
+ profileEntries = fs.readdirSync(profileDirs, {
206
+ withFileTypes: true
207
+ }).filter(e => e.isDirectory())
208
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
209
+ .map(e => path.join(profileDirs, e.name));
210
+ } catch {
211
+ return urls;
212
+ }
213
+ for (const profileDir of profileEntries) {
214
+ const prefsPath = path.join(profileDir, 'prefs.js');
215
+ /* istanbul ignore if */
216
+ if (!fs.existsSync(prefsPath)) continue;
217
+ try {
218
+ const prefs = fs.readFileSync(prefsPath, 'utf8');
219
+ const typeMatch = prefs.match(/user_pref\s*\(\s*"network\.proxy\.type"\s*,\s*(\d+)\s*\)/);
220
+ const pacMatch = prefs.match(/user_pref\s*\(\s*"network\.proxy\.autoconfig_url"\s*,\s*"([^"]+)"\s*\)/);
221
+ /* istanbul ignore next */
222
+ if (typeMatch && ['2', '4'].includes(typeMatch[1]) && pacMatch) {
223
+ /* istanbul ignore next */
224
+ urls.push({
225
+ url: pacMatch[1],
226
+ source: `firefox:prefs.js(${profileDir})`
227
+ });
228
+ }
229
+ } catch {/* ignore */}
230
+ }
231
+ return urls;
232
+ }
233
+ // ─── PAC evaluation ──────────────────────────────────────────────────────────
234
+ async function _evaluatePac(pacUrl, source) {
235
+ const baseFinding = {
236
+ source,
237
+ pacUrl,
238
+ resolvedProxy: null,
239
+ suggestions: []
240
+ };
241
+ let pacScript;
242
+ try {
243
+ pacScript = await _assertClassBrand(_PACDetector_brand, this, _fetchText).call(this, pacUrl);
244
+ } catch (err) {
245
+ return {
246
+ ...baseFinding,
247
+ status: 'warn',
248
+ message: `PAC file detected at ${pacUrl} (source: ${source}) but could not be fetched: ${err.message}`,
249
+ suggestions: ['Ensure the PAC server is reachable from this machine.', `Manually inspect: curl -v "${pacUrl}"`, `Set PERCY_PAC_FILE_URL=${pacUrl} if this PAC file is accessible from your CI environment.`]
250
+ };
251
+ }
252
+ let resolvedProxy = 'UNKNOWN';
253
+ try {
254
+ resolvedProxy = runPacScript(pacScript, PAC_TEST_URL, PAC_TEST_HOST);
255
+ } catch (err) {
256
+ return {
257
+ ...baseFinding,
258
+ status: 'warn',
259
+ message: `PAC file at ${pacUrl} could not be evaluated: ${err.message}`,
260
+ suggestions: ['Manually evaluate the PAC file to confirm which proxy is used for percy.io.', `Inspect PAC content: curl "${pacUrl}"`]
261
+ };
262
+ }
263
+ const isDirect = resolvedProxy.trim().toUpperCase().startsWith('DIRECT');
264
+ const finding = {
265
+ ...baseFinding,
266
+ resolvedProxy,
267
+ status: isDirect ? 'info' : 'warn',
268
+ message: isDirect ? `PAC file (${source}) resolves percy.io as: DIRECT (no proxy needed).` : `PAC file (${source}) resolves percy.io proxy as: ${resolvedProxy}`
269
+ };
270
+ if (!isDirect) {
271
+ const proxyMatch = resolvedProxy.match(/PROXY\s+(\S+)/i);
272
+ if (proxyMatch) {
273
+ finding.detectedProxyUrl = `http://${proxyMatch[1]}`;
274
+ finding.suggestions = [`Set HTTPS_PROXY=http://${proxyMatch[1]} in your environment so Percy can route traffic.`, `Set PERCY_PAC_FILE_URL=${pacUrl} to have Percy automatically use this PAC file.`, `Add to your CI environment: HTTPS_PROXY=http://${proxyMatch[1]}`];
275
+ } else {
276
+ finding.suggestions = [`Set PERCY_PAC_FILE_URL=${pacUrl} to have Percy automatically use this PAC file.`];
277
+ }
278
+ }
279
+ return finding;
280
+ }
281
+ // ─── Private helper ───────────────────────────────────────────────────────────
282
+ async function _fetchText(url) {
283
+ const mod = url.startsWith('https') ? (await import('https')).default : (await import('http')).default;
284
+ return new Promise((resolve, reject) => {
285
+ const req = mod.get(url, {
286
+ timeout: 8000
287
+ }, res => {
288
+ let data = '';
289
+ res.on('data', c => data += c);
290
+ res.on('end', () => resolve(data));
291
+ res.on('error', reject);
292
+ });
293
+ req.on('error', reject);
294
+ req.on('timeout', () => {
295
+ req.destroy();
296
+ reject(new Error('PAC fetch timed out'));
297
+ });
298
+ });
299
+ }
300
+ export function findInObject(obj, key, depth = 0) {
301
+ if (depth > 6 || typeof obj !== 'object' || obj === null) return null;
302
+ if (key in obj) return obj[key];
303
+ for (const v of Object.values(obj)) {
304
+ const found = findInObject(v, key, depth + 1);
305
+ if (found) return found;
306
+ }
307
+ return null;
308
+ }
309
+
310
+ /**
311
+ * Evaluate a PAC script using Node's built-in `vm` module.
312
+ * Provides minimal shims for the standard PAC helper functions.
313
+ * Returns the string result of FindProxyForURL(url, host).
314
+ */
315
+ export function runPacScript(script, url, host) {
316
+ // 1) Size guard against oversized scripts
317
+ /* istanbul ignore next */
318
+ if (typeof script !== 'string') {
319
+ /* istanbul ignore next */
320
+ throw new Error('PAC script must be a string');
321
+ }
322
+ if (script.length > 100000) {
323
+ throw new Error('PAC script exceeds 100KB size limit');
324
+ }
325
+
326
+ // 2) Static guard against obvious Node.js API usage in untrusted PAC content
327
+ const dangerous = /require\s*\(|import\s+|process\.|child_process|fs\.|net\./;
328
+ if (dangerous.test(script)) {
329
+ throw new Error('PAC script contains disallowed Node.js API references');
330
+ }
331
+
332
+ // 3) Null-prototype sandbox (no prototype chain). PAC helpers are exposed as
333
+ // non-writable properties to reduce mutation surface.
334
+ const sandbox = Object.create(null);
335
+ Object.defineProperties(sandbox, {
336
+ isPlainHostName: {
337
+ value: h => !h.includes('.'),
338
+ enumerable: true
339
+ },
340
+ dnsDomainIs: {
341
+ value: (h, d) => h.endsWith(d),
342
+ enumerable: true
343
+ },
344
+ localHostOrDomainIs: {
345
+ value: (h, hd) => h === hd || h.split('.')[0] === hd.split('.')[0],
346
+ enumerable: true
347
+ },
348
+ isResolvable: {
349
+ value: () => true,
350
+ enumerable: true
351
+ },
352
+ isInNet: {
353
+ value: () => false,
354
+ enumerable: true
355
+ },
356
+ dnsResolve: {
357
+ value: h => h,
358
+ enumerable: true
359
+ },
360
+ myIpAddress: {
361
+ value: () => '127.0.0.1',
362
+ enumerable: true
363
+ },
364
+ dnsDomainLevels: {
365
+ value: h => (h.match(/\./g) || []).length,
366
+ enumerable: true
367
+ },
368
+ shExpMatch: {
369
+ value: (str, shexp) => {
370
+ if (typeof str !== 'string' || typeof shexp !== 'string') return false;
371
+ if (shexp.length > 256) return false;
372
+ // minimatch handles * and ? exactly as PAC shExpMatch requires.
373
+ return minimatch(str, shexp, {
374
+ dot: true,
375
+ nocase: false
376
+ });
377
+ },
378
+ enumerable: true
379
+ },
380
+ weekdayRange: {
381
+ value: () => true,
382
+ enumerable: true
383
+ },
384
+ dateRange: {
385
+ value: () => true,
386
+ enumerable: true
387
+ },
388
+ timeRange: {
389
+ value: () => true,
390
+ enumerable: true
391
+ }
392
+ });
393
+ const ctx = vm.createContext(sandbox);
394
+
395
+ // 4) Definition timeout (catches immediate infinite loops in top-level code)
396
+ try {
397
+ vm.runInContext(`"use strict";\n(function(){\n${script}\n; if (typeof FindProxyForURL !== 'function') throw new Error('PAC script does not define FindProxyForURL');\n})()`, ctx, {
398
+ timeout: 5000
399
+ });
400
+ } catch (err) {
401
+ /* istanbul ignore next */
402
+ if ((err === null || err === void 0 ? void 0 : err.code) === 'ERR_SCRIPT_EXECUTION_TIMEOUT') {
403
+ throw new Error('PAC script evaluation timed out after 5 seconds — possible infinite loop');
404
+ }
405
+ throw err;
406
+ }
407
+
408
+ // 5) Invocation timeout (catches loops inside FindProxyForURL itself)
409
+ try {
410
+ return vm.runInContext(`"use strict";\n(function(){\n${script}\n; if (typeof FindProxyForURL !== 'function') throw new Error('PAC script does not define FindProxyForURL');\nreturn String(FindProxyForURL(${JSON.stringify(url)}, ${JSON.stringify(host)}));\n})()`, ctx, {
411
+ timeout: 3000
412
+ });
413
+ } catch (err) {
414
+ if ((err === null || err === void 0 ? void 0 : err.code) === 'ERR_SCRIPT_EXECUTION_TIMEOUT') {
415
+ throw new Error('PAC script evaluation timed out after 3 seconds — possible infinite loop');
416
+ }
417
+ throw err;
418
+ }
419
+ }