Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

macosSystemProxy.ts

160 lines5.6 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Effect from "effect/Effect";
3import { ChildProcess, ChildProcessSpawner } from "effect/process";
4​
5const PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy"];
6​
7// NO_PROXY has no portable IP range: curl and Go read CIDR, npm only matches dot-separated
8// suffixes. A bypassed range or loopback address must stay direct in both, so every IPv4
9// literal is: two /1 blocks (curl ignores /0) plus each possible last octet.
10const IPV4_DIRECT = [
11 "0.0.0.0/1",
12 "128.0.0.0/1",
13 ...Array.from({ length: 256 }, (_, octet) => `.${octet}`),
14];
15const LOOPBACK_DIRECT = ["localhost", "127.0.0.1", "::1", "[::1]"];
16​
17const IPV4_EXCEPTION = /^(?=.*\d)[\d.*]+(?:\/\d+)?$/;
18const IPV6_ADDRESS = /^[0-9a-f:.]+$/i;
19const HOST_NAME = /^[a-z0-9._-]+$/i;
20​
21function readScutilProxy(output: string) {
22 const fields = new Map<string, string>();
23 const exceptions: Array<string> = [];
24 let hasDomainProxies = false;
25 let depth = 0;
26 let block = "";
27 for (const line of output.split("\n")) {
28 const text = line.trim();
29 if (text === "}") {
30 depth -= 1;
31 if (depth <= 1) block = "";
32 continue;
33 }
34 hasDomainProxies ||= block === "__SUPPLEMENTAL__";
35 const separator = text.indexOf(" : ");
36 const key = separator === -1 ? "" : text.slice(0, separator);
37 const value = separator === -1 ? "" : text.slice(separator + 3).trim();
38 if (text.endsWith("{")) {
39 if (depth === 1) block = key;
40 depth += 1;
41 } else if (depth === 1 && key) {
42 fields.set(key, value);
43 } else if (block === "ExceptionsList" && value) {
44 exceptions.push(value);
45 }
46 }
47 return { fields, exceptions, hasDomainProxies };
49​
50/** One scheme's proxy URL, undefined when it is off, null when a variable cannot express it. */
51function proxyUrl(
52 fields: ReadonlyMap<string, string>,
53 scheme: "HTTP" | "HTTPS",
54): string | null | undefined {
55 if (fields.get(`${scheme}Enable`) !== "1") {
56 return undefined;
57 }
58 const host = fields.get(`${scheme}Proxy`) ?? "";
59 const port = fields.get(`${scheme}Port`) ?? "";
60 // The password of an authenticated proxy is in the keychain, out of reach.
61 if (fields.has(`${scheme}User`) || !/^\d+$/.test(port)) {
62 return null;
63 }
64 if (host.includes(":")) {
65 return IPV6_ADDRESS.test(host) ? `http://[${host}]:${port}` : null;
66 }
67 return HOST_NAME.test(host) ? `http://${host}:${port}` : null;
69​
70/** NO_PROXY entries for one macOS exception, or null when no entry can express it. */
71function noProxyEntries(exception: string): ReadonlyArray<string> | null {
72 if (IPV4_EXCEPTION.test(exception)) {
73 return [];
74 }
75 // npm compares entries with the lowercased URL hostname, case-sensitively.
76 const host = exception.toLowerCase();
77 if (host.includes(":")) {
78 return IPV6_ADDRESS.test(host) ? [host, `[${host}]`] : null;
79 }
80 const name = host.startsWith("*.") ? host.slice(1) : host;
81 return HOST_NAME.test(name) ? [name] : null;
83​
84/**
85 * Maps `scutil -d --proxy` output to proxy env vars, or to nothing when the env vars would proxy a
86 * request macOS sends directly. SOCKS is not used.
87 */
88export function macosSystemProxyEnv(
89 scutilOutput: string,
90 existingNoProxy: ReadonlyArray<string> = [],
91): Record<string, string> {
92 const { fields, exceptions, hasDomainProxies } = readScutilProxy(scutilOutput);
93 const http = proxyUrl(fields, "HTTP");
94 const https = proxyUrl(fields, "HTTPS");
95 const exceptionEntries = exceptions.map(noProxyEntries);
96 if (
97 (!http && !https) ||
98 http === null ||
99 https === null ||
100 fields.get("ProxyAutoConfigEnable") === "1" ||
101 fields.get("ProxyAutoDiscoveryEnable") === "1" ||
102 // A VPN's per-domain proxies; one set of variables cannot route by domain.
103 hasDomainProxies ||
104 // No NO_PROXY entry matches every dotless host.
105 fields.get("ExcludeSimpleHostnames") === "1" ||
106 exceptionEntries.includes(null)
107 ) {
108 return {};
109 }
110 const noProxy = [
111 ...new Set([
112 ...existingNoProxy,
113 ...LOOPBACK_DIRECT,
114 ...exceptionEntries.flatMap((entries) => entries ?? []),
115 ...IPV4_DIRECT,
116 ]),
117 ].join(",");
118 // Each scheme keeps its own proxy, except in npm, which sends http requests through https_proxy.
119 return {
120 ...(http ? { HTTP_PROXY: http, http_proxy: http } : {}),
121 ...(https ? { HTTPS_PROXY: https, https_proxy: https } : {}),
122 NO_PROXY: noProxy,
123 no_proxy: noProxy,
124 };
126​
127/** Proxy env vars for a command on macOS whose environment names no proxy of its own. */
128export const readMacosSystemProxyEnv = Effect.fn("MacosSystemProxy.readEnv")(function* (
129 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
130 commandEnv: NodeJS.ProcessEnv = {},
131) {
132 if ((yield* HostProcess.Platform) !== "darwin") {
133 return {};
134 }
135 const env = { ...(yield* HostProcess.Environment), ...commandEnv };
136 const noProxy = [env.no_proxy, env.NO_PROXY]
137 .flatMap((value) => (value ?? "").split(","))
138 .flatMap((entry) => entry.trim().toLowerCase() || []);
139 if (
140 PROXY_ENV_KEYS.some((key) => env[key] || env[key.toUpperCase()]) ||
141 // npm reads its own proxy settings from the environment too.
142 Object.keys(env).some((key) => /^npm_config_(https?[-_])?proxy$/i.test(key) && env[key]) ||
143 noProxy.includes("*")
144 ) {
145 return {};
146 }
147 const output = yield* spawner
148 .string(
149 // Without -d, scutil leaves the per-domain proxies out.
150 ChildProcess.make("/usr/sbin/scutil", ["-d", "--proxy"], {
151 stdin: "ignore",
152 stderr: "ignore",
153 }),
154 )
155 .pipe(
156 Effect.timeout("2 seconds"),
157 Effect.orElseSucceed(() => ""),
158 );
159 return macosSystemProxyEnv(output, noProxy);
160});