echo-t3-bridge 0.1.2 → 0.1.4

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/dist/cli.mjs CHANGED
@@ -216,7 +216,7 @@ import { homedir as homedir2, hostname } from "node:os";
216
216
  import { dirname, join as join2, resolve } from "node:path";
217
217
  var DEFAULT_HUB_SERVER = "https://wq.stormapex.top";
218
218
  var DEFAULT_LOCAL_T3_URL = "http://127.0.0.1:3773";
219
- var APP_VERSION = "0.1.0";
219
+ var APP_VERSION = "0.1.4";
220
220
  function defaultDataDir() {
221
221
  if (process.env.ECHO_T3_BRIDGE_DATA_DIR?.trim()) {
222
222
  return resolve(process.env.ECHO_T3_BRIDGE_DATA_DIR.trim());
@@ -1724,6 +1724,252 @@ var LocalT3Client = class {
1724
1724
  }
1725
1725
  };
1726
1726
 
1727
+ // src/proxy.ts
1728
+ import { execFileSync } from "node:child_process";
1729
+ import http from "node:http";
1730
+ import net from "node:net";
1731
+ import tls from "node:tls";
1732
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1733
+ var cachedSystemProxy = null;
1734
+ var SYSTEM_PROXY_TTL_MS = 3e4;
1735
+ function normalizeProxyUrl(raw) {
1736
+ const trimmed = (raw ?? "").trim();
1737
+ if (!trimmed) return null;
1738
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) {
1739
+ return trimmed;
1740
+ }
1741
+ return `http://${trimmed}`;
1742
+ }
1743
+ function parseNoProxyList() {
1744
+ const raw = process.env.no_proxy ?? process.env.NO_PROXY ?? "";
1745
+ return raw.split(",").map((entry) => entry.trim().toLowerCase()).filter(Boolean);
1746
+ }
1747
+ function shouldBypassProxy(hostname2) {
1748
+ const host = hostname2.toLowerCase();
1749
+ if (LOOPBACK_HOSTS.has(host) || host.startsWith("127.")) return true;
1750
+ for (const rule of parseNoProxyList()) {
1751
+ if (rule === "*") return true;
1752
+ const clean = rule.startsWith("*.") ? rule.slice(1) : rule;
1753
+ if (clean.startsWith(".")) {
1754
+ if (host === clean.slice(1) || host.endsWith(clean)) return true;
1755
+ } else if (host === clean || host.endsWith(`.${clean}`)) {
1756
+ return true;
1757
+ }
1758
+ }
1759
+ return false;
1760
+ }
1761
+ function detectMacSystemProxy() {
1762
+ try {
1763
+ const out = execFileSync("scutil", ["--proxy"], {
1764
+ encoding: "utf8",
1765
+ timeout: 2e3,
1766
+ stdio: ["ignore", "pipe", "ignore"]
1767
+ });
1768
+ const read = (key) => {
1769
+ const m = new RegExp(`^\\s*${key}\\s*:\\s*(.+)$`, "m").exec(out);
1770
+ return m ? m[1].trim() : "";
1771
+ };
1772
+ if (read("HTTPSEnable") === "1" && read("HTTPSProxy") && read("HTTPSPort")) {
1773
+ return `http://${read("HTTPSProxy")}:${read("HTTPSPort")}`;
1774
+ }
1775
+ if (read("HTTPEnable") === "1" && read("HTTPProxy") && read("HTTPPort")) {
1776
+ return `http://${read("HTTPProxy")}:${read("HTTPPort")}`;
1777
+ }
1778
+ } catch {
1779
+ }
1780
+ return null;
1781
+ }
1782
+ function detectWindowsSystemProxy() {
1783
+ try {
1784
+ const out = execFileSync(
1785
+ "reg",
1786
+ [
1787
+ "query",
1788
+ "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
1789
+ ],
1790
+ {
1791
+ encoding: "utf8",
1792
+ timeout: 2e3,
1793
+ stdio: ["ignore", "pipe", "ignore"]
1794
+ }
1795
+ );
1796
+ const enabled = /ProxyEnable\s+REG_DWORD\s+0x([0-9a-fA-F]+)/.exec(out);
1797
+ if (!enabled || Number.parseInt(enabled[1], 16) !== 1) return null;
1798
+ const serverMatch = /ProxyServer\s+REG_SZ\s+(.+)/.exec(out);
1799
+ if (!serverMatch) return null;
1800
+ const raw = serverMatch[1].trim();
1801
+ if (!raw) return null;
1802
+ if (raw.includes("=")) {
1803
+ const parts = Object.fromEntries(
1804
+ raw.split(";").map((p) => p.trim()).filter(Boolean).map((p) => {
1805
+ const idx = p.indexOf("=");
1806
+ return idx > 0 ? [p.slice(0, idx).toLowerCase(), p.slice(idx + 1)] : ["", p];
1807
+ })
1808
+ );
1809
+ return normalizeProxyUrl(parts.https || parts.http || "");
1810
+ }
1811
+ return normalizeProxyUrl(raw);
1812
+ } catch {
1813
+ }
1814
+ return null;
1815
+ }
1816
+ function detectSystemHttpProxy(force = false) {
1817
+ if (!force && cachedSystemProxy && Date.now() - cachedSystemProxy.checkedAt < SYSTEM_PROXY_TTL_MS) {
1818
+ return cachedSystemProxy.url;
1819
+ }
1820
+ let url = null;
1821
+ if (process.platform === "darwin") {
1822
+ url = detectMacSystemProxy();
1823
+ } else if (process.platform === "win32") {
1824
+ url = detectWindowsSystemProxy();
1825
+ }
1826
+ cachedSystemProxy = { checkedAt: Date.now(), url };
1827
+ return url;
1828
+ }
1829
+ function resolveProxyUrl(targetUrl) {
1830
+ let parsed;
1831
+ try {
1832
+ parsed = new URL(targetUrl);
1833
+ } catch {
1834
+ return null;
1835
+ }
1836
+ if (shouldBypassProxy(parsed.hostname)) return null;
1837
+ const isSecure = parsed.protocol === "https:" || parsed.protocol === "wss:";
1838
+ const envCandidates = isSecure ? [
1839
+ process.env.https_proxy,
1840
+ process.env.HTTPS_PROXY,
1841
+ process.env.http_proxy,
1842
+ process.env.HTTP_PROXY,
1843
+ process.env.all_proxy,
1844
+ process.env.ALL_PROXY
1845
+ ] : [
1846
+ process.env.http_proxy,
1847
+ process.env.HTTP_PROXY,
1848
+ process.env.https_proxy,
1849
+ process.env.HTTPS_PROXY,
1850
+ process.env.all_proxy,
1851
+ process.env.ALL_PROXY
1852
+ ];
1853
+ for (const candidate of envCandidates) {
1854
+ const normalized = normalizeProxyUrl(candidate);
1855
+ if (normalized && (normalized.startsWith("http://") || normalized.startsWith("https://"))) {
1856
+ return normalized;
1857
+ }
1858
+ }
1859
+ return detectSystemHttpProxy();
1860
+ }
1861
+ function ensureProcessProxyEnv() {
1862
+ const hasEnvProxy = Boolean(
1863
+ process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY
1864
+ );
1865
+ if (!hasEnvProxy) {
1866
+ const detected = detectSystemHttpProxy();
1867
+ if (detected) {
1868
+ process.env.http_proxy = detected;
1869
+ process.env.https_proxy = detected;
1870
+ process.env.HTTP_PROXY = detected;
1871
+ process.env.HTTPS_PROXY = detected;
1872
+ if (!process.env.no_proxy && !process.env.NO_PROXY) {
1873
+ process.env.no_proxy = "localhost,127.0.0.1,::1,.local";
1874
+ process.env.NO_PROXY = "localhost,127.0.0.1,::1,.local";
1875
+ }
1876
+ }
1877
+ }
1878
+ if (process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY) {
1879
+ if (!process.env.NODE_USE_ENV_PROXY) {
1880
+ process.env.NODE_USE_ENV_PROXY = "1";
1881
+ }
1882
+ }
1883
+ }
1884
+ function createHubWebSocketAgent(targetUrl) {
1885
+ const proxyUrlStr = resolveProxyUrl(targetUrl);
1886
+ if (!proxyUrlStr) return null;
1887
+ let target;
1888
+ let proxy;
1889
+ try {
1890
+ target = new URL(targetUrl);
1891
+ proxy = new URL(proxyUrlStr);
1892
+ } catch {
1893
+ return null;
1894
+ }
1895
+ const isSecureTarget = target.protocol === "wss:" || target.protocol === "https:";
1896
+ const targetPort = Number(target.port || (isSecureTarget ? 443 : 80));
1897
+ const targetHost = target.hostname;
1898
+ const proxyPort = Number(proxy.port || (proxy.protocol === "https:" ? 443 : 80));
1899
+ const proxyHost = proxy.hostname;
1900
+ const proxyAuth = proxy.username || proxy.password ? `Basic ${Buffer.from(
1901
+ `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
1902
+ ).toString("base64")}` : null;
1903
+ class HttpConnectAgent extends http.Agent {
1904
+ createConnection(_options, callback) {
1905
+ const done = (err, sock) => {
1906
+ if (callback) callback(err, sock);
1907
+ };
1908
+ const connectReqHeaders = {
1909
+ Host: `${targetHost}:${targetPort}`,
1910
+ "Proxy-Connection": "Keep-Alive"
1911
+ };
1912
+ if (proxyAuth) {
1913
+ connectReqHeaders["Proxy-Authorization"] = proxyAuth;
1914
+ }
1915
+ const connectReq = http.request({
1916
+ host: proxyHost,
1917
+ port: proxyPort,
1918
+ method: "CONNECT",
1919
+ path: `${targetHost}:${targetPort}`,
1920
+ headers: connectReqHeaders,
1921
+ timeout: 15e3
1922
+ });
1923
+ let settled = false;
1924
+ const fail = (err) => {
1925
+ if (settled) return;
1926
+ settled = true;
1927
+ done(err);
1928
+ };
1929
+ connectReq.once("timeout", () => {
1930
+ connectReq.destroy(new Error(`\u4EE3\u7406\u8FDE\u63A5\u8D85\u65F6 (${proxyHost}:${proxyPort})`));
1931
+ });
1932
+ connectReq.once("error", fail);
1933
+ connectReq.once("connect", (res, socket, head) => {
1934
+ if (settled) {
1935
+ socket.destroy();
1936
+ return;
1937
+ }
1938
+ if (res.statusCode !== 200) {
1939
+ socket.destroy();
1940
+ fail(new Error(`\u4EE3\u7406 CONNECT \u96A7\u9053\u5931\u8D25 (HTTP ${res.statusCode ?? 0})`));
1941
+ return;
1942
+ }
1943
+ if (head && head.length > 0) {
1944
+ socket.unshift(head);
1945
+ }
1946
+ settled = true;
1947
+ if (isSecureTarget) {
1948
+ const tlsSocket = tls.connect({
1949
+ socket,
1950
+ servername: net.isIP(targetHost) ? void 0 : targetHost,
1951
+ rejectUnauthorized: true
1952
+ });
1953
+ done(null, tlsSocket);
1954
+ } else {
1955
+ done(null, socket);
1956
+ }
1957
+ });
1958
+ connectReq.end();
1959
+ return void 0;
1960
+ }
1961
+ }
1962
+ const agent = new HttpConnectAgent({ keepAlive: false });
1963
+ Object.assign(agent, {
1964
+ protocol: isSecureTarget ? "https:" : "http:",
1965
+ defaultPort: isSecureTarget ? 443 : 80
1966
+ });
1967
+ return {
1968
+ agent,
1969
+ proxyUrl: proxyUrlStr
1970
+ };
1971
+ }
1972
+
1727
1973
  // src/bridge.ts
1728
1974
  var EchoT3Bridge = class {
1729
1975
  configPath;
@@ -1735,10 +1981,12 @@ var EchoT3Bridge = class {
1735
1981
  reconnectTimer = null;
1736
1982
  backoffMs = 2e3;
1737
1983
  saveThreadsTimer = null;
1984
+ bypassProxyOnNextAttempt = false;
1738
1985
  constructor(configPath) {
1739
1986
  this.configPath = configPath;
1740
1987
  }
1741
1988
  async start() {
1989
+ ensureProcessProxyEnv();
1742
1990
  this.config = await loadConfig(this.configPath);
1743
1991
  if (!this.config.hub) {
1744
1992
  throw new Error(
@@ -1843,14 +2091,21 @@ var EchoT3Bridge = class {
1843
2091
  url: linkHttpUrl,
1844
2092
  accessToken: creds.accessToken
1845
2093
  });
2094
+ const useProxy = !this.bypassProxyOnNextAttempt;
2095
+ const proxyInfo = useProxy ? createHubWebSocketAgent(wsUrl.toString()) : null;
2096
+ if (proxyInfo) {
2097
+ this.bypassProxyOnNextAttempt = false;
2098
+ }
1846
2099
  const ws = new WebSocket2(wsUrl.toString(), {
1847
2100
  headers: {
1848
2101
  Authorization: `DPoP ${creds.accessToken}`,
1849
2102
  DPoP: proof
1850
2103
  },
2104
+ ...proxyInfo ? { agent: proxyInfo.agent } : {},
1851
2105
  maxPayload: 16 * 1024 * 1024
1852
2106
  });
1853
2107
  this.hubWs = ws;
2108
+ let opened = false;
1854
2109
  ws.on("unexpected-response", async (_req, res) => {
1855
2110
  if (this.hubWs !== ws) return;
1856
2111
  const status = res.statusCode ?? 0;
@@ -1872,8 +2127,11 @@ var EchoT3Bridge = class {
1872
2127
  });
1873
2128
  ws.on("open", () => {
1874
2129
  if (this.hubWs !== ws) return;
2130
+ opened = true;
1875
2131
  this.backoffMs = 2e3;
1876
- console.log(`[hub] \u5DF2\u5EFA\u7ACB\u516C\u7F51\u53CD\u5411\u957F\u8FDE\u63A5 (${creds.serverUrl}, env=${creds.environmentId})`);
2132
+ this.bypassProxyOnNextAttempt = false;
2133
+ const via = proxyInfo ? ` via proxy ${proxyInfo.proxyUrl}` : "";
2134
+ console.log(`[hub] \u5DF2\u5EFA\u7ACB\u516C\u7F51\u53CD\u5411\u957F\u8FDE\u63A5 (${creds.serverUrl}, env=${creds.environmentId}${via})`);
1877
2135
  this.sendHubFrame({
1878
2136
  type: "hello",
1879
2137
  data: {
@@ -1900,7 +2158,12 @@ var EchoT3Bridge = class {
1900
2158
  });
1901
2159
  ws.on("error", (err) => {
1902
2160
  if (this.hubWs !== ws) return;
1903
- console.error(`[hub] WebSocket \u9519\u8BEF: ${err.message}`);
2161
+ if (!opened && proxyInfo) {
2162
+ this.bypassProxyOnNextAttempt = true;
2163
+ } else if (!opened && !proxyInfo) {
2164
+ this.bypassProxyOnNextAttempt = false;
2165
+ }
2166
+ console.error(`[hub] WebSocket \u9519\u8BEF${proxyInfo ? ` (proxy=${proxyInfo.proxyUrl})` : ""}: ${err.message}`);
1904
2167
  });
1905
2168
  }
1906
2169
  sendHubFrame(frame) {
@@ -2104,6 +2367,7 @@ var EchoT3Bridge = class {
2104
2367
  };
2105
2368
 
2106
2369
  // src/index.ts
2370
+ ensureProcessProxyEnv();
2107
2371
  function parseArgs(argv) {
2108
2372
  const positionals = [];
2109
2373
  const flags = {};
@@ -3,6 +3,7 @@ import { APP_VERSION, loadConfig, saveConfig, } from './config.js';
3
3
  import { createDpopProof, renewHubToken } from './dpop.js';
4
4
  import { listDirectories } from './fs-list.js';
5
5
  import { LocalT3Client } from './local-t3.js';
6
+ import { createHubWebSocketAgent, ensureProcessProxyEnv } from './proxy.js';
6
7
  /**
7
8
  * Bidirectional reverse bridge daemon:
8
9
  * - Outbound DPoP-authenticated WebSocket to Echo Hub (`wss://wq.stormapex.top/api/t3/device/link`)
@@ -19,10 +20,12 @@ export class EchoT3Bridge {
19
20
  reconnectTimer = null;
20
21
  backoffMs = 2_000;
21
22
  saveThreadsTimer = null;
23
+ bypassProxyOnNextAttempt = false;
22
24
  constructor(configPath) {
23
25
  this.configPath = configPath;
24
26
  }
25
27
  async start() {
28
+ ensureProcessProxyEnv();
26
29
  this.config = await loadConfig(this.configPath);
27
30
  if (!this.config.hub) {
28
31
  throw new Error('尚未与公网 Hub 配对。请先在网页端点击「生成配对码」,然后执行:\n echo-t3-bridge setup --code <配对码>');
@@ -130,14 +133,21 @@ export class EchoT3Bridge {
130
133
  url: linkHttpUrl,
131
134
  accessToken: creds.accessToken,
132
135
  });
136
+ const useProxy = !this.bypassProxyOnNextAttempt;
137
+ const proxyInfo = useProxy ? createHubWebSocketAgent(wsUrl.toString()) : null;
138
+ if (proxyInfo) {
139
+ this.bypassProxyOnNextAttempt = false;
140
+ }
133
141
  const ws = new WebSocket(wsUrl.toString(), {
134
142
  headers: {
135
143
  Authorization: `DPoP ${creds.accessToken}`,
136
144
  DPoP: proof,
137
145
  },
146
+ ...(proxyInfo ? { agent: proxyInfo.agent } : {}),
138
147
  maxPayload: 16 * 1024 * 1024,
139
148
  });
140
149
  this.hubWs = ws;
150
+ let opened = false;
141
151
  ws.on('unexpected-response', async (_req, res) => {
142
152
  if (this.hubWs !== ws)
143
153
  return;
@@ -162,8 +172,11 @@ export class EchoT3Bridge {
162
172
  ws.on('open', () => {
163
173
  if (this.hubWs !== ws)
164
174
  return;
175
+ opened = true;
165
176
  this.backoffMs = 2_000;
166
- console.log(`[hub] 已建立公网反向长连接 (${creds.serverUrl}, env=${creds.environmentId})`);
177
+ this.bypassProxyOnNextAttempt = false;
178
+ const via = proxyInfo ? ` via proxy ${proxyInfo.proxyUrl}` : '';
179
+ console.log(`[hub] 已建立公网反向长连接 (${creds.serverUrl}, env=${creds.environmentId}${via})`);
167
180
  this.sendHubFrame({
168
181
  type: 'hello',
169
182
  data: {
@@ -194,7 +207,13 @@ export class EchoT3Bridge {
194
207
  ws.on('error', (err) => {
195
208
  if (this.hubWs !== ws)
196
209
  return;
197
- console.error(`[hub] WebSocket 错误: ${err.message}`);
210
+ if (!opened && proxyInfo) {
211
+ this.bypassProxyOnNextAttempt = true;
212
+ }
213
+ else if (!opened && !proxyInfo) {
214
+ this.bypassProxyOnNextAttempt = false;
215
+ }
216
+ console.error(`[hub] WebSocket 错误${proxyInfo ? ` (proxy=${proxyInfo.proxyUrl})` : ''}: ${err.message}`);
198
217
  });
199
218
  }
200
219
  sendHubFrame(frame) {
@@ -3,7 +3,7 @@ import { homedir, hostname } from 'node:os';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  export const DEFAULT_HUB_SERVER = 'https://wq.stormapex.top';
5
5
  export const DEFAULT_LOCAL_T3_URL = 'http://127.0.0.1:3773';
6
- export const APP_VERSION = '0.1.0';
6
+ export const APP_VERSION = '0.1.4';
7
7
  export function defaultDataDir() {
8
8
  if (process.env.ECHO_T3_BRIDGE_DATA_DIR?.trim()) {
9
9
  return resolve(process.env.ECHO_T3_BRIDGE_DATA_DIR.trim());
package/dist/tsc/index.js CHANGED
@@ -6,6 +6,8 @@ import { EchoT3Bridge } from './bridge.js';
6
6
  import { APP_VERSION, clearHubCredentials, DEFAULT_HUB_SERVER, DEFAULT_LOCAL_T3_URL, defaultConfigPath, defaultDeviceLabel, loadConfig, normalizeServerUrl, saveConfig, } from './config.js';
7
7
  import { fetchHubSelf, pairWithHub, unpairFromHub } from './dpop.js';
8
8
  import { pairLocalOfficialT3, probeLocalT3Health, resolveLocalT3Binary } from './local-t3.js';
9
+ import { ensureProcessProxyEnv } from './proxy.js';
10
+ ensureProcessProxyEnv();
9
11
  function parseArgs(argv) {
10
12
  const positionals = [];
11
13
  const flags = {};
@@ -0,0 +1,290 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import http from 'node:http';
3
+ import net from 'node:net';
4
+ import tls from 'node:tls';
5
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
6
+ let cachedSystemProxy = null;
7
+ const SYSTEM_PROXY_TTL_MS = 30_000;
8
+ function normalizeProxyUrl(raw) {
9
+ const trimmed = (raw ?? '').trim();
10
+ if (!trimmed)
11
+ return null;
12
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) {
13
+ return trimmed;
14
+ }
15
+ return `http://${trimmed}`;
16
+ }
17
+ function parseNoProxyList() {
18
+ const raw = process.env.no_proxy ?? process.env.NO_PROXY ?? '';
19
+ return raw
20
+ .split(',')
21
+ .map((entry) => entry.trim().toLowerCase())
22
+ .filter(Boolean);
23
+ }
24
+ function shouldBypassProxy(hostname) {
25
+ const host = hostname.toLowerCase();
26
+ if (LOOPBACK_HOSTS.has(host) || host.startsWith('127.'))
27
+ return true;
28
+ for (const rule of parseNoProxyList()) {
29
+ if (rule === '*')
30
+ return true;
31
+ const clean = rule.startsWith('*.') ? rule.slice(1) : rule;
32
+ if (clean.startsWith('.')) {
33
+ if (host === clean.slice(1) || host.endsWith(clean))
34
+ return true;
35
+ }
36
+ else if (host === clean || host.endsWith(`.${clean}`)) {
37
+ return true;
38
+ }
39
+ }
40
+ return false;
41
+ }
42
+ function detectMacSystemProxy() {
43
+ try {
44
+ const out = execFileSync('scutil', ['--proxy'], {
45
+ encoding: 'utf8',
46
+ timeout: 2_000,
47
+ stdio: ['ignore', 'pipe', 'ignore'],
48
+ });
49
+ const read = (key) => {
50
+ const m = new RegExp(`^\\s*${key}\\s*:\\s*(.+)$`, 'm').exec(out);
51
+ return m ? m[1].trim() : '';
52
+ };
53
+ if (read('HTTPSEnable') === '1' && read('HTTPSProxy') && read('HTTPSPort')) {
54
+ return `http://${read('HTTPSProxy')}:${read('HTTPSPort')}`;
55
+ }
56
+ if (read('HTTPEnable') === '1' && read('HTTPProxy') && read('HTTPPort')) {
57
+ return `http://${read('HTTPProxy')}:${read('HTTPPort')}`;
58
+ }
59
+ }
60
+ catch {
61
+ // ignore
62
+ }
63
+ return null;
64
+ }
65
+ function detectWindowsSystemProxy() {
66
+ try {
67
+ const out = execFileSync('reg', [
68
+ 'query',
69
+ 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
70
+ ], {
71
+ encoding: 'utf8',
72
+ timeout: 2_000,
73
+ stdio: ['ignore', 'pipe', 'ignore'],
74
+ });
75
+ const enabled = /ProxyEnable\s+REG_DWORD\s+0x([0-9a-fA-F]+)/.exec(out);
76
+ if (!enabled || Number.parseInt(enabled[1], 16) !== 1)
77
+ return null;
78
+ const serverMatch = /ProxyServer\s+REG_SZ\s+(.+)/.exec(out);
79
+ if (!serverMatch)
80
+ return null;
81
+ const raw = serverMatch[1].trim();
82
+ if (!raw)
83
+ return null;
84
+ // Handle `http=127.0.0.1:7890;https=127.0.0.1:7890` or plain `127.0.0.1:7890`
85
+ if (raw.includes('=')) {
86
+ const parts = Object.fromEntries(raw
87
+ .split(';')
88
+ .map((p) => p.trim())
89
+ .filter(Boolean)
90
+ .map((p) => {
91
+ const idx = p.indexOf('=');
92
+ return idx > 0 ? [p.slice(0, idx).toLowerCase(), p.slice(idx + 1)] : ['', p];
93
+ }));
94
+ return normalizeProxyUrl(parts.https || parts.http || '');
95
+ }
96
+ return normalizeProxyUrl(raw);
97
+ }
98
+ catch {
99
+ // ignore
100
+ }
101
+ return null;
102
+ }
103
+ export function detectSystemHttpProxy(force = false) {
104
+ if (!force &&
105
+ cachedSystemProxy &&
106
+ Date.now() - cachedSystemProxy.checkedAt < SYSTEM_PROXY_TTL_MS) {
107
+ return cachedSystemProxy.url;
108
+ }
109
+ let url = null;
110
+ if (process.platform === 'darwin') {
111
+ url = detectMacSystemProxy();
112
+ }
113
+ else if (process.platform === 'win32') {
114
+ url = detectWindowsSystemProxy();
115
+ }
116
+ cachedSystemProxy = { checkedAt: Date.now(), url };
117
+ return url;
118
+ }
119
+ /**
120
+ * Resolves an HTTP(S) proxy URL for a given outbound target URL (e.g. `wss://wq.stormapex.top/...`).
121
+ * Checks environment variables first, then falls back to OS system proxy settings so launchd/Windows
122
+ * background services work seamlessly even when they didn't inherit shell proxy env vars.
123
+ */
124
+ export function resolveProxyUrl(targetUrl) {
125
+ let parsed;
126
+ try {
127
+ parsed = new URL(targetUrl);
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ if (shouldBypassProxy(parsed.hostname))
133
+ return null;
134
+ const isSecure = parsed.protocol === 'https:' || parsed.protocol === 'wss:';
135
+ const envCandidates = isSecure
136
+ ? [
137
+ process.env.https_proxy,
138
+ process.env.HTTPS_PROXY,
139
+ process.env.http_proxy,
140
+ process.env.HTTP_PROXY,
141
+ process.env.all_proxy,
142
+ process.env.ALL_PROXY,
143
+ ]
144
+ : [
145
+ process.env.http_proxy,
146
+ process.env.HTTP_PROXY,
147
+ process.env.https_proxy,
148
+ process.env.HTTPS_PROXY,
149
+ process.env.all_proxy,
150
+ process.env.ALL_PROXY,
151
+ ];
152
+ for (const candidate of envCandidates) {
153
+ const normalized = normalizeProxyUrl(candidate);
154
+ if (normalized && (normalized.startsWith('http://') || normalized.startsWith('https://'))) {
155
+ return normalized;
156
+ }
157
+ }
158
+ return detectSystemHttpProxy();
159
+ }
160
+ /**
161
+ * Ensures Node's built-in `fetch` and child processes (like `agy -p /usage`) inherit
162
+ * a working proxy configuration even when launched from launchd/systemd/Startup without
163
+ * shell rc files.
164
+ */
165
+ export function ensureProcessProxyEnv() {
166
+ const hasEnvProxy = Boolean(process.env.https_proxy ||
167
+ process.env.HTTPS_PROXY ||
168
+ process.env.http_proxy ||
169
+ process.env.HTTP_PROXY);
170
+ if (!hasEnvProxy) {
171
+ const detected = detectSystemHttpProxy();
172
+ if (detected) {
173
+ process.env.http_proxy = detected;
174
+ process.env.https_proxy = detected;
175
+ process.env.HTTP_PROXY = detected;
176
+ process.env.HTTPS_PROXY = detected;
177
+ if (!process.env.no_proxy && !process.env.NO_PROXY) {
178
+ process.env.no_proxy = 'localhost,127.0.0.1,::1,.local';
179
+ process.env.NO_PROXY = 'localhost,127.0.0.1,::1,.local';
180
+ }
181
+ }
182
+ }
183
+ if (process.env.https_proxy ||
184
+ process.env.HTTPS_PROXY ||
185
+ process.env.http_proxy ||
186
+ process.env.HTTP_PROXY) {
187
+ if (!process.env.NODE_USE_ENV_PROXY) {
188
+ process.env.NODE_USE_ENV_PROXY = '1';
189
+ }
190
+ }
191
+ }
192
+ /**
193
+ * Zero-dependency HTTP CONNECT tunneling agent compatible with `ws` (`new WebSocket(url, { agent })`).
194
+ * Lets the proxy perform remote DNS resolution and TLS forwarding so hosts that rely on a local
195
+ * HTTP/HTTPS proxy (e.g. Clash/Surge on port 7892 without TUN) never fail with `ENOTFOUND`.
196
+ */
197
+ export function createHubWebSocketAgent(targetUrl) {
198
+ const proxyUrlStr = resolveProxyUrl(targetUrl);
199
+ if (!proxyUrlStr)
200
+ return null;
201
+ let target;
202
+ let proxy;
203
+ try {
204
+ target = new URL(targetUrl);
205
+ proxy = new URL(proxyUrlStr);
206
+ }
207
+ catch {
208
+ return null;
209
+ }
210
+ const isSecureTarget = target.protocol === 'wss:' || target.protocol === 'https:';
211
+ const targetPort = Number(target.port || (isSecureTarget ? 443 : 80));
212
+ const targetHost = target.hostname;
213
+ const proxyPort = Number(proxy.port || (proxy.protocol === 'https:' ? 443 : 80));
214
+ const proxyHost = proxy.hostname;
215
+ const proxyAuth = proxy.username || proxy.password
216
+ ? `Basic ${Buffer.from(`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`).toString('base64')}`
217
+ : null;
218
+ class HttpConnectAgent extends http.Agent {
219
+ createConnection(_options, callback) {
220
+ const done = (err, sock) => {
221
+ if (callback)
222
+ callback(err, sock);
223
+ };
224
+ const connectReqHeaders = {
225
+ Host: `${targetHost}:${targetPort}`,
226
+ 'Proxy-Connection': 'Keep-Alive',
227
+ };
228
+ if (proxyAuth) {
229
+ connectReqHeaders['Proxy-Authorization'] = proxyAuth;
230
+ }
231
+ const connectReq = http.request({
232
+ host: proxyHost,
233
+ port: proxyPort,
234
+ method: 'CONNECT',
235
+ path: `${targetHost}:${targetPort}`,
236
+ headers: connectReqHeaders,
237
+ timeout: 15_000,
238
+ });
239
+ let settled = false;
240
+ const fail = (err) => {
241
+ if (settled)
242
+ return;
243
+ settled = true;
244
+ done(err);
245
+ };
246
+ connectReq.once('timeout', () => {
247
+ connectReq.destroy(new Error(`代理连接超时 (${proxyHost}:${proxyPort})`));
248
+ });
249
+ connectReq.once('error', fail);
250
+ connectReq.once('connect', (res, socket, head) => {
251
+ if (settled) {
252
+ socket.destroy();
253
+ return;
254
+ }
255
+ if (res.statusCode !== 200) {
256
+ socket.destroy();
257
+ fail(new Error(`代理 CONNECT 隧道失败 (HTTP ${res.statusCode ?? 0})`));
258
+ return;
259
+ }
260
+ if (head && head.length > 0) {
261
+ socket.unshift(head);
262
+ }
263
+ settled = true;
264
+ if (isSecureTarget) {
265
+ const tlsSocket = tls.connect({
266
+ socket,
267
+ servername: net.isIP(targetHost) ? undefined : targetHost,
268
+ rejectUnauthorized: true,
269
+ });
270
+ done(null, tlsSocket);
271
+ }
272
+ else {
273
+ done(null, socket);
274
+ }
275
+ });
276
+ connectReq.end();
277
+ return undefined;
278
+ }
279
+ }
280
+ const agent = new HttpConnectAgent({ keepAlive: false });
281
+ // Node's `https.request` (used by `ws` for `wss://`) validates `agent.protocol === 'https:'`.
282
+ Object.assign(agent, {
283
+ protocol: isSecureTarget ? 'https:' : 'http:',
284
+ defaultPort: isSecureTarget ? 443 : 80,
285
+ });
286
+ return {
287
+ agent,
288
+ proxyUrl: proxyUrlStr,
289
+ };
290
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "echo-t3-bridge",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Zero-fork bridge connecting an unmodified local T3 Code server to Echo Hub over a reverse WebSocket tunnel.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -69,9 +69,53 @@ function buildServicePath() {
69
69
  return [...new Set([...extras, ...current])].join(':');
70
70
  }
71
71
 
72
+ function detectMacProxyFromScutil() {
73
+ if (process.platform !== 'darwin') return null;
74
+ try {
75
+ const res = spawnSync('scutil', ['--proxy'], { encoding: 'utf8', timeout: 2000 });
76
+ if (res.status !== 0 || !res.stdout) return null;
77
+ const out = res.stdout;
78
+ const read = (key) => {
79
+ const m = new RegExp(`^\\s*${key}\\s*:\\s*(.+)$`, 'm').exec(out);
80
+ return m ? m[1].trim() : '';
81
+ };
82
+ if (read('HTTPSEnable') === '1' && read('HTTPSProxy') && read('HTTPSPort')) {
83
+ return `http://${read('HTTPSProxy')}:${read('HTTPSPort')}`;
84
+ }
85
+ if (read('HTTPEnable') === '1' && read('HTTPProxy') && read('HTTPPort')) {
86
+ return `http://${read('HTTPProxy')}:${read('HTTPPort')}`;
87
+ }
88
+ } catch {
89
+ // ignore
90
+ }
91
+ return null;
92
+ }
93
+
72
94
  function collectProxyEnvEntries() {
73
- return PROXY_ENV_KEYS.map((key) => [key, process.env[key]])
74
- .filter(([, val]) => typeof val === 'string' && val.trim().length > 0);
95
+ const entries = new Map();
96
+ for (const key of PROXY_ENV_KEYS) {
97
+ const val = process.env[key];
98
+ if (typeof val === 'string' && val.trim().length > 0) {
99
+ entries.set(key, val.trim());
100
+ }
101
+ }
102
+ if (!entries.has('https_proxy') && !entries.has('HTTPS_PROXY') && !entries.has('http_proxy') && !entries.has('HTTP_PROXY')) {
103
+ const sysProxy = detectMacProxyFromScutil();
104
+ if (sysProxy) {
105
+ entries.set('http_proxy', sysProxy);
106
+ entries.set('https_proxy', sysProxy);
107
+ entries.set('HTTP_PROXY', sysProxy);
108
+ entries.set('HTTPS_PROXY', sysProxy);
109
+ if (!entries.has('no_proxy') && !entries.has('NO_PROXY')) {
110
+ entries.set('no_proxy', 'localhost,127.0.0.1,::1,.local');
111
+ entries.set('NO_PROXY', 'localhost,127.0.0.1,::1,.local');
112
+ }
113
+ }
114
+ }
115
+ if (entries.size > 0) {
116
+ entries.set('NODE_USE_ENV_PROXY', '1');
117
+ }
118
+ return [...entries.entries()];
75
119
  }
76
120
 
77
121
  function xmlEscape(val) {
@@ -88,6 +132,11 @@ function runCmd(cmd, args, ignoreFailure = false) {
88
132
  if (!ignoreFailure && res.status !== 0) {
89
133
  process.exit(res.status ?? 1);
90
134
  }
135
+ return res.status ?? 0;
136
+ }
137
+
138
+ function sleepMs(ms) {
139
+ return new Promise((resolve) => setTimeout(resolve, ms));
91
140
  }
92
141
 
93
142
  async function manageLaunchd(mode) {
@@ -133,7 +182,26 @@ ${proxyXml ? `${proxyXml}\n` : ''} </dict>
133
182
  `;
134
183
  await writeFile(target, plist, { mode: 0o600 });
135
184
  runCmd('launchctl', ['enable', `${domain}/${LAUNCHD_LABEL}`], true);
136
- runCmd('launchctl', ['bootstrap', domain, target]);
185
+ // macOS launchd tears down bootout asynchronously; retry bootstrap briefly before failing.
186
+ let bootstrapped = false;
187
+ for (let attempt = 1; attempt <= 4; attempt++) {
188
+ if (attempt > 1) {
189
+ await sleepMs(700);
190
+ runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
191
+ await sleepMs(400);
192
+ }
193
+ const status = runCmd('launchctl', ['bootstrap', domain, target], true);
194
+ if (status === 0) {
195
+ bootstrapped = true;
196
+ break;
197
+ }
198
+ }
199
+ if (!bootstrapped) {
200
+ const kicked = runCmd('launchctl', ['kickstart', '-k', `${domain}/${LAUNCHD_LABEL}`], true);
201
+ if (kicked !== 0) {
202
+ process.exit(1);
203
+ }
204
+ }
137
205
  console.log(`✓ 已安装并启动 macOS 后台服务: ${LAUNCHD_LABEL}`);
138
206
  console.log(` 日志目录: ${logDir}`);
139
207
  }