tokenusage-cli 0.1.0 → 0.2.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/CHANGELOG.md +46 -19
- package/LICENSE +22 -22
- package/README.md +123 -94
- package/THIRD_PARTY_NOTICES.md +140 -140
- package/bin/tokenusage.js +69 -69
- package/package.json +59 -59
- package/src/cli.js +146 -134
- package/src/commands/device-login.js +205 -205
- package/src/commands/diagnostics.js +38 -38
- package/src/commands/doctor.js +110 -110
- package/src/commands/init.js +2484 -2436
- package/src/commands/pause.js +77 -0
- package/src/commands/sessions.js +29 -29
- package/src/commands/status.js +1758 -1747
- package/src/commands/sync.js +8048 -7934
- package/src/commands/uninstall.js +322 -312
- package/src/lib/account-usage-dedup.js +267 -267
- package/src/lib/antigravity-paths.js +48 -48
- package/src/lib/ark-agent-plan-limits.js +438 -438
- package/src/lib/ark-coding-plan-limits.js +537 -537
- package/src/lib/async-queue-reader.js +138 -138
- package/src/lib/atomic-json.js +27 -27
- package/src/lib/bearer-token.js +11 -11
- package/src/lib/categorizer-utils.js +232 -232
- package/src/lib/claude-categorizer.js +1343 -1343
- package/src/lib/claude-config.js +279 -279
- package/src/lib/claude-user-identity.js +56 -56
- package/src/lib/cli-ui.js +179 -179
- package/src/lib/cloud-account.js +541 -541
- package/src/lib/cloud-device-token.js +141 -141
- package/src/lib/cloud-sync-prefs.js +14 -14
- package/src/lib/cloud-usage-reset.js +115 -115
- package/src/lib/codex-config.js +595 -595
- package/src/lib/codex-context-breakdown.js +806 -806
- package/src/lib/codex-model-attribution.js +128 -128
- package/src/lib/codex-rollout-parser.js +1471 -1471
- package/src/lib/codex-service-tier.js +49 -49
- package/src/lib/codex-token-refresh.js +140 -140
- package/src/lib/codex-token-usage.js +195 -195
- package/src/lib/codex-usage-record.js +195 -195
- package/src/lib/collection-pause.js +77 -0
- package/src/lib/command-runner.js +313 -313
- package/src/lib/commandcode-limits.js +317 -317
- package/src/lib/context-health.js +124 -124
- package/src/lib/cursor-config.js +605 -605
- package/src/lib/cursor-store.js +1918 -1918
- package/src/lib/debug-flags.js +7 -7
- package/src/lib/devin-limits.js +249 -249
- package/src/lib/devin-usage.js +212 -212
- package/src/lib/diagnostics.js +383 -383
- package/src/lib/doctor.js +385 -385
- package/src/lib/dumate.js +95 -95
- package/src/lib/fs.js +455 -455
- package/src/lib/function-url.js +14 -14
- package/src/lib/gemini-config.js +291 -291
- package/src/lib/git-outcomes.js +243 -243
- package/src/lib/grok-context-breakdown.js +890 -890
- package/src/lib/grok-hook.js +360 -360
- package/src/lib/grok-limits.js +865 -865
- package/src/lib/grok-usage.js +98 -98
- package/src/lib/heatmap-compact.js +114 -114
- package/src/lib/ingest-sanitize.js +41 -41
- package/src/lib/init-flow.js +42 -42
- package/src/lib/install-resolver.js +170 -170
- package/src/lib/jsonl-lines.js +134 -134
- package/src/lib/kimi-model-repair.js +173 -173
- package/src/lib/kimi-profile.js +61 -61
- package/src/lib/kimi-session.js +216 -216
- package/src/lib/local-api.js +3588 -3588
- package/src/lib/machine-id.js +238 -238
- package/src/lib/multi-install-parser.js +113 -113
- package/src/lib/notify-command.js +38 -38
- package/src/lib/omp-hook.js +589 -589
- package/src/lib/openclaw-cli.js +104 -104
- package/src/lib/openclaw-hook.js +375 -375
- package/src/lib/openclaw-session-plugin.js +560 -560
- package/src/lib/opencode-config.js +121 -121
- package/src/lib/opencode-go-limits.js +807 -807
- package/src/lib/outcomes-engine.js +253 -253
- package/src/lib/passive-mode.js +219 -219
- package/src/lib/pet-packages.js +722 -722
- package/src/lib/pricing/curated-overrides.json +822 -822
- package/src/lib/pricing/index.js +379 -379
- package/src/lib/pricing/litellm-fetcher.js +172 -172
- package/src/lib/pricing/matcher.js +456 -456
- package/src/lib/pricing/seed-snapshot.json +1 -1
- package/src/lib/progress.js +76 -76
- package/src/lib/project-usage-purge.js +117 -117
- package/src/lib/prompt.js +24 -24
- package/src/lib/provider-status.js +104 -104
- package/src/lib/proxy-env.js +489 -489
- package/src/lib/proxy-settings.js +163 -163
- package/src/lib/qoder-cn-cli-limits.js +119 -119
- package/src/lib/qoder-limits.js +880 -880
- package/src/lib/quiet-warnings.js +26 -26
- package/src/lib/rollout.js +26005 -25966
- package/src/lib/runtime-config.js +9 -4
- package/src/lib/scan-roots.js +277 -277
- package/src/lib/scheduled-task.js +145 -0
- package/src/lib/sentry.js +231 -231
- package/src/lib/session-analytics.js +2972 -2972
- package/src/lib/session-performance.js +237 -237
- package/src/lib/session-upload.js +379 -379
- package/src/lib/skill-usage.js +267 -267
- package/src/lib/skills-manager.js +1591 -1591
- package/src/lib/source-metadata.js +48 -48
- package/src/lib/sqlite-reader.js +215 -215
- package/src/lib/star-cta.js +73 -73
- package/src/lib/subscription-manager.js +293 -293
- package/src/lib/subscriptions.js +508 -508
- package/src/lib/sync-report.js +138 -0
- package/src/lib/telemetry.js +193 -193
- package/src/lib/tracker-paths.js +16 -16
- package/src/lib/trae-cn-config.js +548 -548
- package/src/lib/trae-db.js +127 -127
- package/src/lib/trae-snapshot.js +230 -230
- package/src/lib/trae-sqlite.js +143 -143
- package/src/lib/trae-usage.js +121 -121
- package/src/lib/upload-queue.js +134 -134
- package/src/lib/upload-throttle.js +171 -171
- package/src/lib/usage-limits.js +4552 -4552
- package/src/lib/wrapped-aggregator.js +236 -236
- package/src/lib/wsl-probe.js +281 -281
- package/src/lib/zcode-limits.js +1172 -1172
- package/src/lib/zcode-reset-credits.js +66 -66
- package/test/audit-fixes.test.js +200 -0
- package/test/cli-smoke.test.js +53 -53
- package/test/collection-controls.test.js +210 -0
- package/test/ingest-sanitize.test.js +162 -162
- package/test/quiet-warnings.test.js +53 -53
- package/test/session-upload.test.js +427 -427
package/src/lib/proxy-env.js
CHANGED
|
@@ -1,489 +1,489 @@
|
|
|
1
|
-
const cp = require("node:child_process");
|
|
2
|
-
const fs = require("node:fs");
|
|
3
|
-
const os = require("node:os");
|
|
4
|
-
const path = require("node:path");
|
|
5
|
-
const { normalizeProxyConfig, buildProxyUrl } = require("./proxy-settings");
|
|
6
|
-
|
|
7
|
-
// scutil --proxy is a sync spawn (2s timeout) that blocks the event loop.
|
|
8
|
-
// resolveEffectiveProxySource runs on GET /proxy-config, and
|
|
9
|
-
// applyUndiciProxyIfNeeded now uses the same probe on the system-mode path.
|
|
10
|
-
// A 30s TTL (including negative / null results) keeps the settings UI and
|
|
11
|
-
// the dispatcher aligned without re-spawning on every request.
|
|
12
|
-
const SYSTEM_PROXY_CACHE_TTL_MS = 30_000;
|
|
13
|
-
|
|
14
|
-
let systemProxyCache = { filled: false, at: 0, value: null };
|
|
15
|
-
|
|
16
|
-
function invalidateSystemProxyCache() {
|
|
17
|
-
systemProxyCache = { filled: false, at: 0, value: null };
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function resetSystemProxyCacheForTests() {
|
|
21
|
-
invalidateSystemProxyCache();
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function hasProxyEnv(env = process.env) {
|
|
25
|
-
return Boolean(
|
|
26
|
-
env.HTTPS_PROXY ||
|
|
27
|
-
env.https_proxy ||
|
|
28
|
-
env.HTTP_PROXY ||
|
|
29
|
-
env.http_proxy ||
|
|
30
|
-
env.ALL_PROXY ||
|
|
31
|
-
env.all_proxy,
|
|
32
|
-
);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function parseMacProxyOutput(output) {
|
|
36
|
-
const values = {};
|
|
37
|
-
for (const line of String(output || "").split(/\r?\n/)) {
|
|
38
|
-
const match = line.match(/^\s*([A-Za-z]+)\s*:\s*(.+?)\s*$/);
|
|
39
|
-
if (match) values[match[1]] = match[2];
|
|
40
|
-
}
|
|
41
|
-
if (values.HTTPSEnable !== "1" || !values.HTTPSProxy || !values.HTTPSPort) return null;
|
|
42
|
-
return `http://${values.HTTPSProxy}:${values.HTTPSPort}`;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function probeMacSystemProxyUrl(commandRunner) {
|
|
46
|
-
const result = commandRunner("scutil", ["--proxy"], {
|
|
47
|
-
encoding: "utf8",
|
|
48
|
-
timeout: 2000,
|
|
49
|
-
});
|
|
50
|
-
if (result?.error || result?.status !== 0) return null;
|
|
51
|
-
return parseMacProxyOutput(result.stdout);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function getCachedMacSystemProxyUrl({
|
|
55
|
-
platform = process.platform,
|
|
56
|
-
commandRunner = cp.spawnSync,
|
|
57
|
-
} = {}) {
|
|
58
|
-
if (platform !== "darwin") return null;
|
|
59
|
-
const now = Date.now();
|
|
60
|
-
if (systemProxyCache.filled && now - systemProxyCache.at < SYSTEM_PROXY_CACHE_TTL_MS) {
|
|
61
|
-
return systemProxyCache.value;
|
|
62
|
-
}
|
|
63
|
-
const value = probeMacSystemProxyUrl(commandRunner);
|
|
64
|
-
systemProxyCache = { filled: true, at: now, value };
|
|
65
|
-
return value;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
function isDeclaredManual(raw) {
|
|
69
|
-
if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return false;
|
|
70
|
-
return String(raw.mode || "").trim().toLowerCase() === "manual";
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function defaultConfigPath() {
|
|
74
|
-
return path.join(os.homedir(), ".tokenusage", "tracker", "config.json");
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function readPersistedProxyConfig({ configPath } = {}) {
|
|
78
|
-
const file = configPath || defaultConfigPath();
|
|
79
|
-
try {
|
|
80
|
-
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
81
|
-
return parsed && typeof parsed === "object" ? parsed.proxy : undefined;
|
|
82
|
-
} catch {
|
|
83
|
-
return undefined;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function pickProxyUrl(env = process.env) {
|
|
88
|
-
return (
|
|
89
|
-
env.HTTPS_PROXY ||
|
|
90
|
-
env.https_proxy ||
|
|
91
|
-
env.HTTP_PROXY ||
|
|
92
|
-
env.http_proxy ||
|
|
93
|
-
env.ALL_PROXY ||
|
|
94
|
-
env.all_proxy ||
|
|
95
|
-
null
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Shared resolution of the currently effective proxy URL.
|
|
101
|
-
* Used by both applyUndiciProxyIfNeeded (dispatcher) and
|
|
102
|
-
* resolveEffectiveProxySource (UI label) so the two cannot drift.
|
|
103
|
-
*
|
|
104
|
-
* System-mode order: process env (pickProxyUrl) → macOS scutil.
|
|
105
|
-
*/
|
|
106
|
-
function resolveEffectiveProxyUrl({
|
|
107
|
-
env = process.env,
|
|
108
|
-
proxyConfig,
|
|
109
|
-
platform = process.platform,
|
|
110
|
-
commandRunner = cp.spawnSync,
|
|
111
|
-
} = {}) {
|
|
112
|
-
const config = normalizeProxyConfig(proxyConfig);
|
|
113
|
-
if (config.mode === "off") {
|
|
114
|
-
return { source: "none", proxyUrl: null, config };
|
|
115
|
-
}
|
|
116
|
-
// Dirty persisted "manual" normalizes to system; do not pretend a system
|
|
117
|
-
// proxy is in effect. apply() fail-closes this case, so report "blocked"
|
|
118
|
-
// rather than "none" — the UI must not say "connecting directly" while
|
|
119
|
-
// outbound traffic is actually being refused.
|
|
120
|
-
if (isDeclaredManual(proxyConfig) && config.mode !== "manual") {
|
|
121
|
-
return { source: "blocked", proxyUrl: null, config };
|
|
122
|
-
}
|
|
123
|
-
if (config.mode === "manual") {
|
|
124
|
-
const proxyUrl = buildProxyUrl(config);
|
|
125
|
-
return { source: proxyUrl ? "manual" : "blocked", proxyUrl, config };
|
|
126
|
-
}
|
|
127
|
-
const envUrl = pickProxyUrl(env);
|
|
128
|
-
if (envUrl) return { source: "env", proxyUrl: envUrl, config };
|
|
129
|
-
const systemUrl = getCachedMacSystemProxyUrl({ platform, commandRunner });
|
|
130
|
-
if (systemUrl) return { source: "system", proxyUrl: systemUrl, config };
|
|
131
|
-
return { source: "none", proxyUrl: null, config };
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Display-only resolution of the currently effective proxy source.
|
|
136
|
-
* Includes macOS scutil so the settings UI can label "system".
|
|
137
|
-
*/
|
|
138
|
-
function resolveEffectiveProxySource(opts) {
|
|
139
|
-
return resolveEffectiveProxyUrl(opts);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function resolveSystemProxyEnv({
|
|
143
|
-
env = process.env,
|
|
144
|
-
platform = process.platform,
|
|
145
|
-
commandRunner = cp.spawnSync,
|
|
146
|
-
proxyConfig,
|
|
147
|
-
} = {}) {
|
|
148
|
-
const normalized = normalizeProxyConfig(proxyConfig);
|
|
149
|
-
// Manual mode is applied only via applyUndiciProxyIfNeeded's ProxyAgent.
|
|
150
|
-
// Injecting HTTPS_PROXY here would relaunch serve and leak the URL into
|
|
151
|
-
// process.env, so a later switch back to system still picks the old proxy.
|
|
152
|
-
// Invalid persisted "manual" still counts as declared-manual so we do not
|
|
153
|
-
// relaunch into a system-proxy env while apply() is about to fail-closed.
|
|
154
|
-
if (normalized.mode === "off" || normalized.mode === "manual" || isDeclaredManual(proxyConfig)) {
|
|
155
|
-
return null;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const resolved = resolveEffectiveProxyUrl({ env, proxyConfig, platform, commandRunner });
|
|
159
|
-
if (resolved.source === "env") {
|
|
160
|
-
return { NODE_USE_ENV_PROXY: env.NODE_USE_ENV_PROXY || "1" };
|
|
161
|
-
}
|
|
162
|
-
if (resolved.source === "system" && resolved.proxyUrl) {
|
|
163
|
-
return {
|
|
164
|
-
NODE_USE_ENV_PROXY: "1",
|
|
165
|
-
HTTPS_PROXY: resolved.proxyUrl,
|
|
166
|
-
HTTP_PROXY: resolved.proxyUrl,
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
return null;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function shouldRelaunchForProxy(argv, env = process.env) {
|
|
173
|
-
if (env.TOKENUSAGE_PROXY_ENV_APPLIED === "1") return false;
|
|
174
|
-
const command = Array.isArray(argv) ? argv[0] : null;
|
|
175
|
-
return !command || command === "serve";
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
function relaunchWithProxyEnvIfNeeded({
|
|
179
|
-
argv,
|
|
180
|
-
originalArgv,
|
|
181
|
-
env = process.env,
|
|
182
|
-
platform = process.platform,
|
|
183
|
-
commandRunner = cp.spawnSync,
|
|
184
|
-
nodePath = process.execPath,
|
|
185
|
-
proxyConfig,
|
|
186
|
-
} = {}) {
|
|
187
|
-
if (!shouldRelaunchForProxy(argv, env)) return null;
|
|
188
|
-
const proxyEnv = resolveSystemProxyEnv({ env, platform, commandRunner, proxyConfig });
|
|
189
|
-
if (!proxyEnv || proxyEnv.NODE_USE_ENV_PROXY === env.NODE_USE_ENV_PROXY) return null;
|
|
190
|
-
|
|
191
|
-
const childEnv = {
|
|
192
|
-
...env,
|
|
193
|
-
...proxyEnv,
|
|
194
|
-
TOKENUSAGE_PROXY_ENV_APPLIED: "1",
|
|
195
|
-
};
|
|
196
|
-
return commandRunner(nodePath, originalArgv, {
|
|
197
|
-
stdio: "inherit",
|
|
198
|
-
env: childEnv,
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// Dispatchers created by this module. setGlobalDispatcher only swaps the
|
|
203
|
-
// global symbol and does not recycle the previous agent, so we keep our own
|
|
204
|
-
// handle and close() it after a successful replacement.
|
|
205
|
-
let ownedDispatcher = null;
|
|
206
|
-
let lastManualApplyError = null;
|
|
207
|
-
|
|
208
|
-
function getLastProxyApplyError() {
|
|
209
|
-
return lastManualApplyError;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function resetProxyApplyStateForTests() {
|
|
213
|
-
ownedDispatcher = null;
|
|
214
|
-
lastManualApplyError = null;
|
|
215
|
-
resetSystemProxyCacheForTests();
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
function closeDispatcherQuietly(dispatcher) {
|
|
219
|
-
if (!dispatcher || typeof dispatcher.close !== "function") return;
|
|
220
|
-
Promise.resolve()
|
|
221
|
-
.then(() => dispatcher.close())
|
|
222
|
-
.catch(() => {});
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function warnManualApplyFailure(message, warn) {
|
|
226
|
-
const text = `[proxy] Failed to apply manual proxy; outbound traffic is blocked: ${message}`;
|
|
227
|
-
if (typeof warn === "function") {
|
|
228
|
-
warn(text);
|
|
229
|
-
return;
|
|
230
|
-
}
|
|
231
|
-
console.error(text);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
const FAIL_CLOSED_MESSAGE = "manual proxy is not applied; outbound traffic is blocked";
|
|
235
|
-
|
|
236
|
-
function createFailClosedDispatcher(reason) {
|
|
237
|
-
const message = reason ? `${FAIL_CLOSED_MESSAGE}: ${reason}` : FAIL_CLOSED_MESSAGE;
|
|
238
|
-
const error = () => Object.assign(new Error(message), { code: "PROXY_FAIL_CLOSED" });
|
|
239
|
-
try {
|
|
240
|
-
// eslint-disable-next-line global-require
|
|
241
|
-
const undici = require("undici");
|
|
242
|
-
if (typeof undici.Agent === "function") {
|
|
243
|
-
return new undici.Agent({
|
|
244
|
-
connect(_options, callback) {
|
|
245
|
-
if (typeof callback === "function") callback(error(), null);
|
|
246
|
-
},
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
} catch (_e) {
|
|
250
|
-
/* fall through to a minimal dispatcher */
|
|
251
|
-
}
|
|
252
|
-
return {
|
|
253
|
-
dispatch(_options, handler) {
|
|
254
|
-
if (handler && typeof handler.onError === "function") {
|
|
255
|
-
queueMicrotask(() => handler.onError(error()));
|
|
256
|
-
}
|
|
257
|
-
return true;
|
|
258
|
-
},
|
|
259
|
-
close() {
|
|
260
|
-
return Promise.resolve();
|
|
261
|
-
},
|
|
262
|
-
destroy() {
|
|
263
|
-
return Promise.resolve();
|
|
264
|
-
},
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
function installFailClosedDispatcher(parts, reason) {
|
|
269
|
-
if (!parts || typeof parts.setter !== "function") return false;
|
|
270
|
-
const next = createFailClosedDispatcher(reason);
|
|
271
|
-
try {
|
|
272
|
-
swapOwnedDispatcher(parts.setter, next);
|
|
273
|
-
return true;
|
|
274
|
-
} catch (_e) {
|
|
275
|
-
closeDispatcherQuietly(next);
|
|
276
|
-
return false;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/**
|
|
281
|
-
* Build an undici ProxyAgent for a user-configured proxy URL.
|
|
282
|
-
*
|
|
283
|
-
* CodeQL "Outbound network request depends on file data"
|
|
284
|
-
* (security/code-scanning/227): proxyUrl is the hop the user explicitly
|
|
285
|
-
* configured in Settings / config.json `proxy` (or HTTPS_PROXY / scutil).
|
|
286
|
-
* It reaches this function only after parseProxyPayload or
|
|
287
|
-
* normalizeProxyConfig + buildProxyUrl (manual) or pickProxyUrl /
|
|
288
|
-
* parseMacProxyOutput (system). This is the intended CONNECT/SOCKS target,
|
|
289
|
-
* not an unsanitized server-side request URL.
|
|
290
|
-
*/
|
|
291
|
-
function createProxyDispatcher(proxyUrl, { ProxyAgent } = {}) {
|
|
292
|
-
if (!proxyUrl) return null;
|
|
293
|
-
if (typeof ProxyAgent !== "function") return null;
|
|
294
|
-
return new ProxyAgent(proxyUrl);
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
function loadUndiciParts({ setGlobalDispatcher, ProxyAgent, Agent } = {}) {
|
|
298
|
-
let setter = setGlobalDispatcher;
|
|
299
|
-
let Proxy = ProxyAgent;
|
|
300
|
-
let Direct = Agent;
|
|
301
|
-
if (!setter || !Proxy || !Direct) {
|
|
302
|
-
try {
|
|
303
|
-
// eslint-disable-next-line global-require
|
|
304
|
-
const undici = require("undici");
|
|
305
|
-
setter = setter || undici.setGlobalDispatcher;
|
|
306
|
-
Proxy = Proxy || undici.ProxyAgent;
|
|
307
|
-
Direct = Direct || undici.Agent;
|
|
308
|
-
} catch (_e) {
|
|
309
|
-
return { setter: null, ProxyAgent: null, Agent: null };
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
return { setter, ProxyAgent: Proxy, Agent: Direct };
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
function resolveFetchImpl(fetchImpl) {
|
|
316
|
-
if (typeof fetchImpl === "function") return fetchImpl;
|
|
317
|
-
try {
|
|
318
|
-
// eslint-disable-next-line global-require
|
|
319
|
-
const undiciFetch = require("undici").fetch;
|
|
320
|
-
if (typeof undiciFetch === "function") return undiciFetch;
|
|
321
|
-
} catch (_e) {
|
|
322
|
-
/* fall through to the global */
|
|
323
|
-
}
|
|
324
|
-
return fetch;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
const PROXY_TEST_TIMEOUT_MS = 5000;
|
|
328
|
-
|
|
329
|
-
function proxyErrorMessage(error, fallback) {
|
|
330
|
-
const message = typeof error?.message === "string" ? error.message.split(/[\r\n]/)[0].trim() : "";
|
|
331
|
-
return message.slice(0, 500) || fallback;
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
async function runProxyConnectivityTest({
|
|
335
|
-
proxyUrl,
|
|
336
|
-
targetUrl,
|
|
337
|
-
timeoutMs = PROXY_TEST_TIMEOUT_MS,
|
|
338
|
-
fetchImpl,
|
|
339
|
-
ProxyAgent,
|
|
340
|
-
Agent,
|
|
341
|
-
setGlobalDispatcher,
|
|
342
|
-
} = {}) {
|
|
343
|
-
const started = Date.now();
|
|
344
|
-
const latency = () => Date.now() - started;
|
|
345
|
-
if (!proxyUrl) return { ok: false, error: "no proxy url", latencyMs: latency() };
|
|
346
|
-
if (!targetUrl) return { ok: false, error: "no test target", latencyMs: latency() };
|
|
347
|
-
|
|
348
|
-
let dispatcher = null;
|
|
349
|
-
try {
|
|
350
|
-
const parts = loadUndiciParts({ ProxyAgent, Agent, setGlobalDispatcher });
|
|
351
|
-
dispatcher = createProxyDispatcher(proxyUrl, parts);
|
|
352
|
-
if (!dispatcher) {
|
|
353
|
-
return { ok: false, error: "unsupported proxy protocol", latencyMs: latency() };
|
|
354
|
-
}
|
|
355
|
-
// Prefer undici.fetch: global fetch on some Node versions ignores the
|
|
356
|
-
// `dispatcher` option and would probe via the process-global agent.
|
|
357
|
-
const doFetch = resolveFetchImpl(fetchImpl);
|
|
358
|
-
const res = await doFetch(targetUrl, {
|
|
359
|
-
method: "GET",
|
|
360
|
-
dispatcher,
|
|
361
|
-
signal: AbortSignal.timeout(Math.min(timeoutMs, PROXY_TEST_TIMEOUT_MS)),
|
|
362
|
-
});
|
|
363
|
-
return { ok: true, status: res.status, latencyMs: latency() };
|
|
364
|
-
} catch (error) {
|
|
365
|
-
return { ok: false, error: proxyErrorMessage(error, "Proxy request failed"), latencyMs: latency() };
|
|
366
|
-
} finally {
|
|
367
|
-
closeDispatcherQuietly(dispatcher);
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
// Node's built-in NODE_USE_ENV_PROXY support only landed in v22.21 / v24.5.
|
|
372
|
-
// For older runtimes (including the v22.14 we historically embedded in the
|
|
373
|
-
// macOS app, and the v22.16 a community user hit on Discussion #68) the env
|
|
374
|
-
// var is silently ignored and fetch() bypasses the proxy. Setting an undici
|
|
375
|
-
// ProxyAgent dispatcher at startup gives us proxy support on every Node ≥ 18
|
|
376
|
-
// regardless of the env-proxy flag.
|
|
377
|
-
function swapOwnedDispatcher(setter, next) {
|
|
378
|
-
setter(next);
|
|
379
|
-
const previous = ownedDispatcher;
|
|
380
|
-
ownedDispatcher = next;
|
|
381
|
-
closeDispatcherQuietly(previous);
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
function installDirectAgent(parts) {
|
|
385
|
-
if (typeof parts.Agent !== "function" || typeof parts.setter !== "function") return false;
|
|
386
|
-
let next;
|
|
387
|
-
try {
|
|
388
|
-
next = new parts.Agent();
|
|
389
|
-
} catch (_e) {
|
|
390
|
-
return false;
|
|
391
|
-
}
|
|
392
|
-
try {
|
|
393
|
-
swapOwnedDispatcher(parts.setter, next);
|
|
394
|
-
} catch (_e) {
|
|
395
|
-
closeDispatcherQuietly(next);
|
|
396
|
-
return false;
|
|
397
|
-
}
|
|
398
|
-
return true;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
function failManual(message, warn, parts) {
|
|
402
|
-
lastManualApplyError = message;
|
|
403
|
-
const installed = installFailClosedDispatcher(parts, message);
|
|
404
|
-
warnManualApplyFailure(message, warn);
|
|
405
|
-
if (!installed) return { ok: false, error: message, unprotected: true };
|
|
406
|
-
return { ok: false, error: message };
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
function applyUndiciProxyIfNeeded({
|
|
410
|
-
env = process.env,
|
|
411
|
-
setGlobalDispatcher,
|
|
412
|
-
ProxyAgent,
|
|
413
|
-
Agent,
|
|
414
|
-
proxyConfig,
|
|
415
|
-
warn,
|
|
416
|
-
platform = process.platform,
|
|
417
|
-
commandRunner = cp.spawnSync,
|
|
418
|
-
} = {}) {
|
|
419
|
-
const normalized = normalizeProxyConfig(proxyConfig);
|
|
420
|
-
const parts = loadUndiciParts({ setGlobalDispatcher, ProxyAgent, Agent });
|
|
421
|
-
|
|
422
|
-
if (isDeclaredManual(proxyConfig) && normalized.mode !== "manual") {
|
|
423
|
-
return failManual(normalized.reason || "invalid manual proxy config", warn, parts);
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
if (normalized.mode === "off") {
|
|
427
|
-
if (typeof parts.setter !== "function") return null;
|
|
428
|
-
installDirectAgent(parts);
|
|
429
|
-
lastManualApplyError = null;
|
|
430
|
-
return null;
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
const resolved = resolveEffectiveProxyUrl({ env, proxyConfig, platform, commandRunner });
|
|
434
|
-
const proxyUrl = resolved.proxyUrl;
|
|
435
|
-
const manual = normalized.mode === "manual";
|
|
436
|
-
|
|
437
|
-
if (manual && !proxyUrl) {
|
|
438
|
-
return failManual("invalid manual proxy config", warn, parts);
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
if (!proxyUrl) {
|
|
442
|
-
if (ownedDispatcher) installDirectAgent(parts);
|
|
443
|
-
lastManualApplyError = null;
|
|
444
|
-
return null;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
if (typeof parts.setter !== "function") {
|
|
448
|
-
return manual ? failManual("undici dispatcher is unavailable", warn, parts) : null;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
let dispatcher;
|
|
452
|
-
try {
|
|
453
|
-
dispatcher = createProxyDispatcher(proxyUrl, parts);
|
|
454
|
-
} catch (error) {
|
|
455
|
-
const message = proxyErrorMessage(error, "Could not construct the proxy dispatcher");
|
|
456
|
-
return manual ? failManual(message, warn, parts) : null;
|
|
457
|
-
}
|
|
458
|
-
if (!dispatcher) {
|
|
459
|
-
return manual ? failManual("failed to construct proxy dispatcher", warn, parts) : null;
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
try {
|
|
463
|
-
swapOwnedDispatcher(parts.setter, dispatcher);
|
|
464
|
-
} catch (error) {
|
|
465
|
-
closeDispatcherQuietly(dispatcher);
|
|
466
|
-
const message = proxyErrorMessage(error, "Could not install the proxy dispatcher");
|
|
467
|
-
return manual ? failManual(message, warn, parts) : null;
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
lastManualApplyError = null;
|
|
471
|
-
return { ok: true, proxyUrl };
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
module.exports = {
|
|
475
|
-
hasProxyEnv,
|
|
476
|
-
parseMacProxyOutput,
|
|
477
|
-
pickProxyUrl,
|
|
478
|
-
resolveSystemProxyEnv,
|
|
479
|
-
relaunchWithProxyEnvIfNeeded,
|
|
480
|
-
applyUndiciProxyIfNeeded,
|
|
481
|
-
createProxyDispatcher,
|
|
482
|
-
readPersistedProxyConfig,
|
|
483
|
-
resolveEffectiveProxySource,
|
|
484
|
-
runProxyConnectivityTest,
|
|
485
|
-
getLastProxyApplyError,
|
|
486
|
-
resetProxyApplyStateForTests,
|
|
487
|
-
invalidateSystemProxyCache,
|
|
488
|
-
resetSystemProxyCacheForTests,
|
|
489
|
-
};
|
|
1
|
+
const cp = require("node:child_process");
|
|
2
|
+
const fs = require("node:fs");
|
|
3
|
+
const os = require("node:os");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { normalizeProxyConfig, buildProxyUrl } = require("./proxy-settings");
|
|
6
|
+
|
|
7
|
+
// scutil --proxy is a sync spawn (2s timeout) that blocks the event loop.
|
|
8
|
+
// resolveEffectiveProxySource runs on GET /proxy-config, and
|
|
9
|
+
// applyUndiciProxyIfNeeded now uses the same probe on the system-mode path.
|
|
10
|
+
// A 30s TTL (including negative / null results) keeps the settings UI and
|
|
11
|
+
// the dispatcher aligned without re-spawning on every request.
|
|
12
|
+
const SYSTEM_PROXY_CACHE_TTL_MS = 30_000;
|
|
13
|
+
|
|
14
|
+
let systemProxyCache = { filled: false, at: 0, value: null };
|
|
15
|
+
|
|
16
|
+
function invalidateSystemProxyCache() {
|
|
17
|
+
systemProxyCache = { filled: false, at: 0, value: null };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function resetSystemProxyCacheForTests() {
|
|
21
|
+
invalidateSystemProxyCache();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function hasProxyEnv(env = process.env) {
|
|
25
|
+
return Boolean(
|
|
26
|
+
env.HTTPS_PROXY ||
|
|
27
|
+
env.https_proxy ||
|
|
28
|
+
env.HTTP_PROXY ||
|
|
29
|
+
env.http_proxy ||
|
|
30
|
+
env.ALL_PROXY ||
|
|
31
|
+
env.all_proxy,
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function parseMacProxyOutput(output) {
|
|
36
|
+
const values = {};
|
|
37
|
+
for (const line of String(output || "").split(/\r?\n/)) {
|
|
38
|
+
const match = line.match(/^\s*([A-Za-z]+)\s*:\s*(.+?)\s*$/);
|
|
39
|
+
if (match) values[match[1]] = match[2];
|
|
40
|
+
}
|
|
41
|
+
if (values.HTTPSEnable !== "1" || !values.HTTPSProxy || !values.HTTPSPort) return null;
|
|
42
|
+
return `http://${values.HTTPSProxy}:${values.HTTPSPort}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function probeMacSystemProxyUrl(commandRunner) {
|
|
46
|
+
const result = commandRunner("scutil", ["--proxy"], {
|
|
47
|
+
encoding: "utf8",
|
|
48
|
+
timeout: 2000,
|
|
49
|
+
});
|
|
50
|
+
if (result?.error || result?.status !== 0) return null;
|
|
51
|
+
return parseMacProxyOutput(result.stdout);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function getCachedMacSystemProxyUrl({
|
|
55
|
+
platform = process.platform,
|
|
56
|
+
commandRunner = cp.spawnSync,
|
|
57
|
+
} = {}) {
|
|
58
|
+
if (platform !== "darwin") return null;
|
|
59
|
+
const now = Date.now();
|
|
60
|
+
if (systemProxyCache.filled && now - systemProxyCache.at < SYSTEM_PROXY_CACHE_TTL_MS) {
|
|
61
|
+
return systemProxyCache.value;
|
|
62
|
+
}
|
|
63
|
+
const value = probeMacSystemProxyUrl(commandRunner);
|
|
64
|
+
systemProxyCache = { filled: true, at: now, value };
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isDeclaredManual(raw) {
|
|
69
|
+
if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return false;
|
|
70
|
+
return String(raw.mode || "").trim().toLowerCase() === "manual";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function defaultConfigPath() {
|
|
74
|
+
return path.join(os.homedir(), ".tokenusage", "tracker", "config.json");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function readPersistedProxyConfig({ configPath } = {}) {
|
|
78
|
+
const file = configPath || defaultConfigPath();
|
|
79
|
+
try {
|
|
80
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
81
|
+
return parsed && typeof parsed === "object" ? parsed.proxy : undefined;
|
|
82
|
+
} catch {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function pickProxyUrl(env = process.env) {
|
|
88
|
+
return (
|
|
89
|
+
env.HTTPS_PROXY ||
|
|
90
|
+
env.https_proxy ||
|
|
91
|
+
env.HTTP_PROXY ||
|
|
92
|
+
env.http_proxy ||
|
|
93
|
+
env.ALL_PROXY ||
|
|
94
|
+
env.all_proxy ||
|
|
95
|
+
null
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Shared resolution of the currently effective proxy URL.
|
|
101
|
+
* Used by both applyUndiciProxyIfNeeded (dispatcher) and
|
|
102
|
+
* resolveEffectiveProxySource (UI label) so the two cannot drift.
|
|
103
|
+
*
|
|
104
|
+
* System-mode order: process env (pickProxyUrl) → macOS scutil.
|
|
105
|
+
*/
|
|
106
|
+
function resolveEffectiveProxyUrl({
|
|
107
|
+
env = process.env,
|
|
108
|
+
proxyConfig,
|
|
109
|
+
platform = process.platform,
|
|
110
|
+
commandRunner = cp.spawnSync,
|
|
111
|
+
} = {}) {
|
|
112
|
+
const config = normalizeProxyConfig(proxyConfig);
|
|
113
|
+
if (config.mode === "off") {
|
|
114
|
+
return { source: "none", proxyUrl: null, config };
|
|
115
|
+
}
|
|
116
|
+
// Dirty persisted "manual" normalizes to system; do not pretend a system
|
|
117
|
+
// proxy is in effect. apply() fail-closes this case, so report "blocked"
|
|
118
|
+
// rather than "none" — the UI must not say "connecting directly" while
|
|
119
|
+
// outbound traffic is actually being refused.
|
|
120
|
+
if (isDeclaredManual(proxyConfig) && config.mode !== "manual") {
|
|
121
|
+
return { source: "blocked", proxyUrl: null, config };
|
|
122
|
+
}
|
|
123
|
+
if (config.mode === "manual") {
|
|
124
|
+
const proxyUrl = buildProxyUrl(config);
|
|
125
|
+
return { source: proxyUrl ? "manual" : "blocked", proxyUrl, config };
|
|
126
|
+
}
|
|
127
|
+
const envUrl = pickProxyUrl(env);
|
|
128
|
+
if (envUrl) return { source: "env", proxyUrl: envUrl, config };
|
|
129
|
+
const systemUrl = getCachedMacSystemProxyUrl({ platform, commandRunner });
|
|
130
|
+
if (systemUrl) return { source: "system", proxyUrl: systemUrl, config };
|
|
131
|
+
return { source: "none", proxyUrl: null, config };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Display-only resolution of the currently effective proxy source.
|
|
136
|
+
* Includes macOS scutil so the settings UI can label "system".
|
|
137
|
+
*/
|
|
138
|
+
function resolveEffectiveProxySource(opts) {
|
|
139
|
+
return resolveEffectiveProxyUrl(opts);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function resolveSystemProxyEnv({
|
|
143
|
+
env = process.env,
|
|
144
|
+
platform = process.platform,
|
|
145
|
+
commandRunner = cp.spawnSync,
|
|
146
|
+
proxyConfig,
|
|
147
|
+
} = {}) {
|
|
148
|
+
const normalized = normalizeProxyConfig(proxyConfig);
|
|
149
|
+
// Manual mode is applied only via applyUndiciProxyIfNeeded's ProxyAgent.
|
|
150
|
+
// Injecting HTTPS_PROXY here would relaunch serve and leak the URL into
|
|
151
|
+
// process.env, so a later switch back to system still picks the old proxy.
|
|
152
|
+
// Invalid persisted "manual" still counts as declared-manual so we do not
|
|
153
|
+
// relaunch into a system-proxy env while apply() is about to fail-closed.
|
|
154
|
+
if (normalized.mode === "off" || normalized.mode === "manual" || isDeclaredManual(proxyConfig)) {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const resolved = resolveEffectiveProxyUrl({ env, proxyConfig, platform, commandRunner });
|
|
159
|
+
if (resolved.source === "env") {
|
|
160
|
+
return { NODE_USE_ENV_PROXY: env.NODE_USE_ENV_PROXY || "1" };
|
|
161
|
+
}
|
|
162
|
+
if (resolved.source === "system" && resolved.proxyUrl) {
|
|
163
|
+
return {
|
|
164
|
+
NODE_USE_ENV_PROXY: "1",
|
|
165
|
+
HTTPS_PROXY: resolved.proxyUrl,
|
|
166
|
+
HTTP_PROXY: resolved.proxyUrl,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function shouldRelaunchForProxy(argv, env = process.env) {
|
|
173
|
+
if (env.TOKENUSAGE_PROXY_ENV_APPLIED === "1") return false;
|
|
174
|
+
const command = Array.isArray(argv) ? argv[0] : null;
|
|
175
|
+
return !command || command === "serve";
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function relaunchWithProxyEnvIfNeeded({
|
|
179
|
+
argv,
|
|
180
|
+
originalArgv,
|
|
181
|
+
env = process.env,
|
|
182
|
+
platform = process.platform,
|
|
183
|
+
commandRunner = cp.spawnSync,
|
|
184
|
+
nodePath = process.execPath,
|
|
185
|
+
proxyConfig,
|
|
186
|
+
} = {}) {
|
|
187
|
+
if (!shouldRelaunchForProxy(argv, env)) return null;
|
|
188
|
+
const proxyEnv = resolveSystemProxyEnv({ env, platform, commandRunner, proxyConfig });
|
|
189
|
+
if (!proxyEnv || proxyEnv.NODE_USE_ENV_PROXY === env.NODE_USE_ENV_PROXY) return null;
|
|
190
|
+
|
|
191
|
+
const childEnv = {
|
|
192
|
+
...env,
|
|
193
|
+
...proxyEnv,
|
|
194
|
+
TOKENUSAGE_PROXY_ENV_APPLIED: "1",
|
|
195
|
+
};
|
|
196
|
+
return commandRunner(nodePath, originalArgv, {
|
|
197
|
+
stdio: "inherit",
|
|
198
|
+
env: childEnv,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Dispatchers created by this module. setGlobalDispatcher only swaps the
|
|
203
|
+
// global symbol and does not recycle the previous agent, so we keep our own
|
|
204
|
+
// handle and close() it after a successful replacement.
|
|
205
|
+
let ownedDispatcher = null;
|
|
206
|
+
let lastManualApplyError = null;
|
|
207
|
+
|
|
208
|
+
function getLastProxyApplyError() {
|
|
209
|
+
return lastManualApplyError;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function resetProxyApplyStateForTests() {
|
|
213
|
+
ownedDispatcher = null;
|
|
214
|
+
lastManualApplyError = null;
|
|
215
|
+
resetSystemProxyCacheForTests();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function closeDispatcherQuietly(dispatcher) {
|
|
219
|
+
if (!dispatcher || typeof dispatcher.close !== "function") return;
|
|
220
|
+
Promise.resolve()
|
|
221
|
+
.then(() => dispatcher.close())
|
|
222
|
+
.catch(() => {});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function warnManualApplyFailure(message, warn) {
|
|
226
|
+
const text = `[proxy] Failed to apply manual proxy; outbound traffic is blocked: ${message}`;
|
|
227
|
+
if (typeof warn === "function") {
|
|
228
|
+
warn(text);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
console.error(text);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const FAIL_CLOSED_MESSAGE = "manual proxy is not applied; outbound traffic is blocked";
|
|
235
|
+
|
|
236
|
+
function createFailClosedDispatcher(reason) {
|
|
237
|
+
const message = reason ? `${FAIL_CLOSED_MESSAGE}: ${reason}` : FAIL_CLOSED_MESSAGE;
|
|
238
|
+
const error = () => Object.assign(new Error(message), { code: "PROXY_FAIL_CLOSED" });
|
|
239
|
+
try {
|
|
240
|
+
// eslint-disable-next-line global-require
|
|
241
|
+
const undici = require("undici");
|
|
242
|
+
if (typeof undici.Agent === "function") {
|
|
243
|
+
return new undici.Agent({
|
|
244
|
+
connect(_options, callback) {
|
|
245
|
+
if (typeof callback === "function") callback(error(), null);
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
} catch (_e) {
|
|
250
|
+
/* fall through to a minimal dispatcher */
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
dispatch(_options, handler) {
|
|
254
|
+
if (handler && typeof handler.onError === "function") {
|
|
255
|
+
queueMicrotask(() => handler.onError(error()));
|
|
256
|
+
}
|
|
257
|
+
return true;
|
|
258
|
+
},
|
|
259
|
+
close() {
|
|
260
|
+
return Promise.resolve();
|
|
261
|
+
},
|
|
262
|
+
destroy() {
|
|
263
|
+
return Promise.resolve();
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function installFailClosedDispatcher(parts, reason) {
|
|
269
|
+
if (!parts || typeof parts.setter !== "function") return false;
|
|
270
|
+
const next = createFailClosedDispatcher(reason);
|
|
271
|
+
try {
|
|
272
|
+
swapOwnedDispatcher(parts.setter, next);
|
|
273
|
+
return true;
|
|
274
|
+
} catch (_e) {
|
|
275
|
+
closeDispatcherQuietly(next);
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Build an undici ProxyAgent for a user-configured proxy URL.
|
|
282
|
+
*
|
|
283
|
+
* CodeQL "Outbound network request depends on file data"
|
|
284
|
+
* (security/code-scanning/227): proxyUrl is the hop the user explicitly
|
|
285
|
+
* configured in Settings / config.json `proxy` (or HTTPS_PROXY / scutil).
|
|
286
|
+
* It reaches this function only after parseProxyPayload or
|
|
287
|
+
* normalizeProxyConfig + buildProxyUrl (manual) or pickProxyUrl /
|
|
288
|
+
* parseMacProxyOutput (system). This is the intended CONNECT/SOCKS target,
|
|
289
|
+
* not an unsanitized server-side request URL.
|
|
290
|
+
*/
|
|
291
|
+
function createProxyDispatcher(proxyUrl, { ProxyAgent } = {}) {
|
|
292
|
+
if (!proxyUrl) return null;
|
|
293
|
+
if (typeof ProxyAgent !== "function") return null;
|
|
294
|
+
return new ProxyAgent(proxyUrl);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function loadUndiciParts({ setGlobalDispatcher, ProxyAgent, Agent } = {}) {
|
|
298
|
+
let setter = setGlobalDispatcher;
|
|
299
|
+
let Proxy = ProxyAgent;
|
|
300
|
+
let Direct = Agent;
|
|
301
|
+
if (!setter || !Proxy || !Direct) {
|
|
302
|
+
try {
|
|
303
|
+
// eslint-disable-next-line global-require
|
|
304
|
+
const undici = require("undici");
|
|
305
|
+
setter = setter || undici.setGlobalDispatcher;
|
|
306
|
+
Proxy = Proxy || undici.ProxyAgent;
|
|
307
|
+
Direct = Direct || undici.Agent;
|
|
308
|
+
} catch (_e) {
|
|
309
|
+
return { setter: null, ProxyAgent: null, Agent: null };
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return { setter, ProxyAgent: Proxy, Agent: Direct };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function resolveFetchImpl(fetchImpl) {
|
|
316
|
+
if (typeof fetchImpl === "function") return fetchImpl;
|
|
317
|
+
try {
|
|
318
|
+
// eslint-disable-next-line global-require
|
|
319
|
+
const undiciFetch = require("undici").fetch;
|
|
320
|
+
if (typeof undiciFetch === "function") return undiciFetch;
|
|
321
|
+
} catch (_e) {
|
|
322
|
+
/* fall through to the global */
|
|
323
|
+
}
|
|
324
|
+
return fetch;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const PROXY_TEST_TIMEOUT_MS = 5000;
|
|
328
|
+
|
|
329
|
+
function proxyErrorMessage(error, fallback) {
|
|
330
|
+
const message = typeof error?.message === "string" ? error.message.split(/[\r\n]/)[0].trim() : "";
|
|
331
|
+
return message.slice(0, 500) || fallback;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function runProxyConnectivityTest({
|
|
335
|
+
proxyUrl,
|
|
336
|
+
targetUrl,
|
|
337
|
+
timeoutMs = PROXY_TEST_TIMEOUT_MS,
|
|
338
|
+
fetchImpl,
|
|
339
|
+
ProxyAgent,
|
|
340
|
+
Agent,
|
|
341
|
+
setGlobalDispatcher,
|
|
342
|
+
} = {}) {
|
|
343
|
+
const started = Date.now();
|
|
344
|
+
const latency = () => Date.now() - started;
|
|
345
|
+
if (!proxyUrl) return { ok: false, error: "no proxy url", latencyMs: latency() };
|
|
346
|
+
if (!targetUrl) return { ok: false, error: "no test target", latencyMs: latency() };
|
|
347
|
+
|
|
348
|
+
let dispatcher = null;
|
|
349
|
+
try {
|
|
350
|
+
const parts = loadUndiciParts({ ProxyAgent, Agent, setGlobalDispatcher });
|
|
351
|
+
dispatcher = createProxyDispatcher(proxyUrl, parts);
|
|
352
|
+
if (!dispatcher) {
|
|
353
|
+
return { ok: false, error: "unsupported proxy protocol", latencyMs: latency() };
|
|
354
|
+
}
|
|
355
|
+
// Prefer undici.fetch: global fetch on some Node versions ignores the
|
|
356
|
+
// `dispatcher` option and would probe via the process-global agent.
|
|
357
|
+
const doFetch = resolveFetchImpl(fetchImpl);
|
|
358
|
+
const res = await doFetch(targetUrl, {
|
|
359
|
+
method: "GET",
|
|
360
|
+
dispatcher,
|
|
361
|
+
signal: AbortSignal.timeout(Math.min(timeoutMs, PROXY_TEST_TIMEOUT_MS)),
|
|
362
|
+
});
|
|
363
|
+
return { ok: true, status: res.status, latencyMs: latency() };
|
|
364
|
+
} catch (error) {
|
|
365
|
+
return { ok: false, error: proxyErrorMessage(error, "Proxy request failed"), latencyMs: latency() };
|
|
366
|
+
} finally {
|
|
367
|
+
closeDispatcherQuietly(dispatcher);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Node's built-in NODE_USE_ENV_PROXY support only landed in v22.21 / v24.5.
|
|
372
|
+
// For older runtimes (including the v22.14 we historically embedded in the
|
|
373
|
+
// macOS app, and the v22.16 a community user hit on Discussion #68) the env
|
|
374
|
+
// var is silently ignored and fetch() bypasses the proxy. Setting an undici
|
|
375
|
+
// ProxyAgent dispatcher at startup gives us proxy support on every Node ≥ 18
|
|
376
|
+
// regardless of the env-proxy flag.
|
|
377
|
+
function swapOwnedDispatcher(setter, next) {
|
|
378
|
+
setter(next);
|
|
379
|
+
const previous = ownedDispatcher;
|
|
380
|
+
ownedDispatcher = next;
|
|
381
|
+
closeDispatcherQuietly(previous);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function installDirectAgent(parts) {
|
|
385
|
+
if (typeof parts.Agent !== "function" || typeof parts.setter !== "function") return false;
|
|
386
|
+
let next;
|
|
387
|
+
try {
|
|
388
|
+
next = new parts.Agent();
|
|
389
|
+
} catch (_e) {
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
try {
|
|
393
|
+
swapOwnedDispatcher(parts.setter, next);
|
|
394
|
+
} catch (_e) {
|
|
395
|
+
closeDispatcherQuietly(next);
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
return true;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function failManual(message, warn, parts) {
|
|
402
|
+
lastManualApplyError = message;
|
|
403
|
+
const installed = installFailClosedDispatcher(parts, message);
|
|
404
|
+
warnManualApplyFailure(message, warn);
|
|
405
|
+
if (!installed) return { ok: false, error: message, unprotected: true };
|
|
406
|
+
return { ok: false, error: message };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function applyUndiciProxyIfNeeded({
|
|
410
|
+
env = process.env,
|
|
411
|
+
setGlobalDispatcher,
|
|
412
|
+
ProxyAgent,
|
|
413
|
+
Agent,
|
|
414
|
+
proxyConfig,
|
|
415
|
+
warn,
|
|
416
|
+
platform = process.platform,
|
|
417
|
+
commandRunner = cp.spawnSync,
|
|
418
|
+
} = {}) {
|
|
419
|
+
const normalized = normalizeProxyConfig(proxyConfig);
|
|
420
|
+
const parts = loadUndiciParts({ setGlobalDispatcher, ProxyAgent, Agent });
|
|
421
|
+
|
|
422
|
+
if (isDeclaredManual(proxyConfig) && normalized.mode !== "manual") {
|
|
423
|
+
return failManual(normalized.reason || "invalid manual proxy config", warn, parts);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
if (normalized.mode === "off") {
|
|
427
|
+
if (typeof parts.setter !== "function") return null;
|
|
428
|
+
installDirectAgent(parts);
|
|
429
|
+
lastManualApplyError = null;
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const resolved = resolveEffectiveProxyUrl({ env, proxyConfig, platform, commandRunner });
|
|
434
|
+
const proxyUrl = resolved.proxyUrl;
|
|
435
|
+
const manual = normalized.mode === "manual";
|
|
436
|
+
|
|
437
|
+
if (manual && !proxyUrl) {
|
|
438
|
+
return failManual("invalid manual proxy config", warn, parts);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
if (!proxyUrl) {
|
|
442
|
+
if (ownedDispatcher) installDirectAgent(parts);
|
|
443
|
+
lastManualApplyError = null;
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (typeof parts.setter !== "function") {
|
|
448
|
+
return manual ? failManual("undici dispatcher is unavailable", warn, parts) : null;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
let dispatcher;
|
|
452
|
+
try {
|
|
453
|
+
dispatcher = createProxyDispatcher(proxyUrl, parts);
|
|
454
|
+
} catch (error) {
|
|
455
|
+
const message = proxyErrorMessage(error, "Could not construct the proxy dispatcher");
|
|
456
|
+
return manual ? failManual(message, warn, parts) : null;
|
|
457
|
+
}
|
|
458
|
+
if (!dispatcher) {
|
|
459
|
+
return manual ? failManual("failed to construct proxy dispatcher", warn, parts) : null;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
try {
|
|
463
|
+
swapOwnedDispatcher(parts.setter, dispatcher);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
closeDispatcherQuietly(dispatcher);
|
|
466
|
+
const message = proxyErrorMessage(error, "Could not install the proxy dispatcher");
|
|
467
|
+
return manual ? failManual(message, warn, parts) : null;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
lastManualApplyError = null;
|
|
471
|
+
return { ok: true, proxyUrl };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
module.exports = {
|
|
475
|
+
hasProxyEnv,
|
|
476
|
+
parseMacProxyOutput,
|
|
477
|
+
pickProxyUrl,
|
|
478
|
+
resolveSystemProxyEnv,
|
|
479
|
+
relaunchWithProxyEnvIfNeeded,
|
|
480
|
+
applyUndiciProxyIfNeeded,
|
|
481
|
+
createProxyDispatcher,
|
|
482
|
+
readPersistedProxyConfig,
|
|
483
|
+
resolveEffectiveProxySource,
|
|
484
|
+
runProxyConnectivityTest,
|
|
485
|
+
getLastProxyApplyError,
|
|
486
|
+
resetProxyApplyStateForTests,
|
|
487
|
+
invalidateSystemProxyCache,
|
|
488
|
+
resetSystemProxyCacheForTests,
|
|
489
|
+
};
|