echo-t3-bridge 0.1.1 → 0.1.3
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 +288 -8
- package/dist/tsc/bridge.js +21 -2
- package/dist/tsc/config.js +1 -1
- package/dist/tsc/index.js +2 -0
- package/dist/tsc/local-t3.js +31 -6
- package/dist/tsc/proxy.js +284 -0
- package/package.json +1 -1
- package/scripts/service.mjs +67 -2
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.
|
|
219
|
+
var APP_VERSION = "0.1.3";
|
|
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());
|
|
@@ -1036,6 +1036,7 @@ var LocalT3Client = class {
|
|
|
1036
1036
|
lastProviders = [];
|
|
1037
1037
|
pending = /* @__PURE__ */ new Map();
|
|
1038
1038
|
streams = /* @__PURE__ */ new Map();
|
|
1039
|
+
streamThreads = /* @__PURE__ */ new Map();
|
|
1039
1040
|
subscribedThreads = /* @__PURE__ */ new Set();
|
|
1040
1041
|
wantedThreads = /* @__PURE__ */ new Map();
|
|
1041
1042
|
terminalMetadata = /* @__PURE__ */ new Map();
|
|
@@ -1083,6 +1084,7 @@ var LocalT3Client = class {
|
|
|
1083
1084
|
const wasConnected = this.connected;
|
|
1084
1085
|
this.connected = false;
|
|
1085
1086
|
this.subscribedThreads.clear();
|
|
1087
|
+
this.streamThreads.clear();
|
|
1086
1088
|
this.terminalStreams.clear();
|
|
1087
1089
|
this.terminalMetadata.clear();
|
|
1088
1090
|
this.streams.clear();
|
|
@@ -1214,6 +1216,11 @@ var LocalT3Client = class {
|
|
|
1214
1216
|
}
|
|
1215
1217
|
if (msg._tag === "Exit") {
|
|
1216
1218
|
this.streams.delete(reqId);
|
|
1219
|
+
const exitedThread = this.streamThreads.get(reqId);
|
|
1220
|
+
if (exitedThread) {
|
|
1221
|
+
this.streamThreads.delete(reqId);
|
|
1222
|
+
this.subscribedThreads.delete(exitedThread);
|
|
1223
|
+
}
|
|
1217
1224
|
const pending = this.pending.get(reqId);
|
|
1218
1225
|
if (!pending) return;
|
|
1219
1226
|
this.pending.delete(reqId);
|
|
@@ -1346,22 +1353,32 @@ var LocalT3Client = class {
|
|
|
1346
1353
|
ensureThreadSubscribed(threadId, afterSequence = 0) {
|
|
1347
1354
|
if (!threadId) return;
|
|
1348
1355
|
const prev = this.wantedThreads.get(threadId) ?? 0;
|
|
1349
|
-
|
|
1350
|
-
|
|
1356
|
+
const effectiveAfter = Math.max(prev, afterSequence);
|
|
1357
|
+
if (effectiveAfter > prev || !this.wantedThreads.has(threadId)) {
|
|
1358
|
+
this.wantedThreads.set(threadId, effectiveAfter);
|
|
1351
1359
|
}
|
|
1352
1360
|
if (this.subscribedThreads.has(threadId) || !this.isConnected()) return;
|
|
1353
1361
|
this.subscribedThreads.add(threadId);
|
|
1354
1362
|
const payload = { threadId };
|
|
1355
|
-
if (
|
|
1363
|
+
if (effectiveAfter > 0) payload.afterSequence = effectiveAfter;
|
|
1356
1364
|
const reqId = this.startStream("orchestration.subscribeThread", payload, (rawItem) => {
|
|
1357
1365
|
if (!rawItem || typeof rawItem !== "object") return;
|
|
1358
1366
|
const env = rawItem;
|
|
1367
|
+
if (env.kind === "snapshot" && typeof env.snapshotSequence === "number") {
|
|
1368
|
+
const cur2 = this.wantedThreads.get(threadId) ?? 0;
|
|
1369
|
+
if (env.snapshotSequence > cur2) {
|
|
1370
|
+
this.wantedThreads.set(threadId, env.snapshotSequence);
|
|
1371
|
+
}
|
|
1372
|
+
return;
|
|
1373
|
+
}
|
|
1359
1374
|
if (env.kind !== "event" || typeof env.sequence !== "number" || !env.event) return;
|
|
1360
1375
|
const cur = this.wantedThreads.get(threadId) ?? 0;
|
|
1361
1376
|
if (env.sequence > cur) this.wantedThreads.set(threadId, env.sequence);
|
|
1362
1377
|
this.callbacks.onThreadEvent({ sequence: env.sequence, event: env.event });
|
|
1363
1378
|
});
|
|
1364
|
-
if (
|
|
1379
|
+
if (reqId) {
|
|
1380
|
+
this.streamThreads.set(reqId, threadId);
|
|
1381
|
+
} else {
|
|
1365
1382
|
this.subscribedThreads.delete(threadId);
|
|
1366
1383
|
}
|
|
1367
1384
|
}
|
|
@@ -1514,7 +1531,11 @@ var LocalT3Client = class {
|
|
|
1514
1531
|
message: text.trim() || `HTTP ${resp.status}`
|
|
1515
1532
|
};
|
|
1516
1533
|
}
|
|
1517
|
-
|
|
1534
|
+
const parsed = JSON.parse(text);
|
|
1535
|
+
if (parsed && typeof parsed === "object" && typeof parsed.sequence !== "number" && typeof parsed.snapshotSequence === "number") {
|
|
1536
|
+
parsed.sequence = parsed.snapshotSequence;
|
|
1537
|
+
}
|
|
1538
|
+
return parsed;
|
|
1518
1539
|
}
|
|
1519
1540
|
async resolveDefaultCwd(override) {
|
|
1520
1541
|
const trimmed = (override ?? "").trim();
|
|
@@ -1703,6 +1724,247 @@ var LocalT3Client = class {
|
|
|
1703
1724
|
}
|
|
1704
1725
|
};
|
|
1705
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
|
+
return {
|
|
1963
|
+
agent: new HttpConnectAgent({ keepAlive: false }),
|
|
1964
|
+
proxyUrl: proxyUrlStr
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1706
1968
|
// src/bridge.ts
|
|
1707
1969
|
var EchoT3Bridge = class {
|
|
1708
1970
|
configPath;
|
|
@@ -1714,10 +1976,12 @@ var EchoT3Bridge = class {
|
|
|
1714
1976
|
reconnectTimer = null;
|
|
1715
1977
|
backoffMs = 2e3;
|
|
1716
1978
|
saveThreadsTimer = null;
|
|
1979
|
+
bypassProxyOnNextAttempt = false;
|
|
1717
1980
|
constructor(configPath) {
|
|
1718
1981
|
this.configPath = configPath;
|
|
1719
1982
|
}
|
|
1720
1983
|
async start() {
|
|
1984
|
+
ensureProcessProxyEnv();
|
|
1721
1985
|
this.config = await loadConfig(this.configPath);
|
|
1722
1986
|
if (!this.config.hub) {
|
|
1723
1987
|
throw new Error(
|
|
@@ -1822,14 +2086,21 @@ var EchoT3Bridge = class {
|
|
|
1822
2086
|
url: linkHttpUrl,
|
|
1823
2087
|
accessToken: creds.accessToken
|
|
1824
2088
|
});
|
|
2089
|
+
const useProxy = !this.bypassProxyOnNextAttempt;
|
|
2090
|
+
const proxyInfo = useProxy ? createHubWebSocketAgent(wsUrl.toString()) : null;
|
|
2091
|
+
if (proxyInfo) {
|
|
2092
|
+
this.bypassProxyOnNextAttempt = false;
|
|
2093
|
+
}
|
|
1825
2094
|
const ws = new WebSocket2(wsUrl.toString(), {
|
|
1826
2095
|
headers: {
|
|
1827
2096
|
Authorization: `DPoP ${creds.accessToken}`,
|
|
1828
2097
|
DPoP: proof
|
|
1829
2098
|
},
|
|
2099
|
+
...proxyInfo ? { agent: proxyInfo.agent } : {},
|
|
1830
2100
|
maxPayload: 16 * 1024 * 1024
|
|
1831
2101
|
});
|
|
1832
2102
|
this.hubWs = ws;
|
|
2103
|
+
let opened = false;
|
|
1833
2104
|
ws.on("unexpected-response", async (_req, res) => {
|
|
1834
2105
|
if (this.hubWs !== ws) return;
|
|
1835
2106
|
const status = res.statusCode ?? 0;
|
|
@@ -1851,8 +2122,11 @@ var EchoT3Bridge = class {
|
|
|
1851
2122
|
});
|
|
1852
2123
|
ws.on("open", () => {
|
|
1853
2124
|
if (this.hubWs !== ws) return;
|
|
2125
|
+
opened = true;
|
|
1854
2126
|
this.backoffMs = 2e3;
|
|
1855
|
-
|
|
2127
|
+
this.bypassProxyOnNextAttempt = false;
|
|
2128
|
+
const via = proxyInfo ? ` via proxy ${proxyInfo.proxyUrl}` : "";
|
|
2129
|
+
console.log(`[hub] \u5DF2\u5EFA\u7ACB\u516C\u7F51\u53CD\u5411\u957F\u8FDE\u63A5 (${creds.serverUrl}, env=${creds.environmentId}${via})`);
|
|
1856
2130
|
this.sendHubFrame({
|
|
1857
2131
|
type: "hello",
|
|
1858
2132
|
data: {
|
|
@@ -1879,7 +2153,12 @@ var EchoT3Bridge = class {
|
|
|
1879
2153
|
});
|
|
1880
2154
|
ws.on("error", (err) => {
|
|
1881
2155
|
if (this.hubWs !== ws) return;
|
|
1882
|
-
|
|
2156
|
+
if (!opened && proxyInfo) {
|
|
2157
|
+
this.bypassProxyOnNextAttempt = true;
|
|
2158
|
+
} else if (!opened && !proxyInfo) {
|
|
2159
|
+
this.bypassProxyOnNextAttempt = false;
|
|
2160
|
+
}
|
|
2161
|
+
console.error(`[hub] WebSocket \u9519\u8BEF${proxyInfo ? ` (proxy=${proxyInfo.proxyUrl})` : ""}: ${err.message}`);
|
|
1883
2162
|
});
|
|
1884
2163
|
}
|
|
1885
2164
|
sendHubFrame(frame) {
|
|
@@ -2083,6 +2362,7 @@ var EchoT3Bridge = class {
|
|
|
2083
2362
|
};
|
|
2084
2363
|
|
|
2085
2364
|
// src/index.ts
|
|
2365
|
+
ensureProcessProxyEnv();
|
|
2086
2366
|
function parseArgs(argv) {
|
|
2087
2367
|
const positionals = [];
|
|
2088
2368
|
const flags = {};
|
package/dist/tsc/bridge.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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) {
|
package/dist/tsc/config.js
CHANGED
|
@@ -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.
|
|
6
|
+
export const APP_VERSION = '0.1.3';
|
|
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 = {};
|
package/dist/tsc/local-t3.js
CHANGED
|
@@ -194,6 +194,7 @@ export class LocalT3Client {
|
|
|
194
194
|
lastProviders = [];
|
|
195
195
|
pending = new Map();
|
|
196
196
|
streams = new Map();
|
|
197
|
+
streamThreads = new Map();
|
|
197
198
|
subscribedThreads = new Set();
|
|
198
199
|
wantedThreads = new Map();
|
|
199
200
|
terminalMetadata = new Map();
|
|
@@ -242,6 +243,7 @@ export class LocalT3Client {
|
|
|
242
243
|
const wasConnected = this.connected;
|
|
243
244
|
this.connected = false;
|
|
244
245
|
this.subscribedThreads.clear();
|
|
246
|
+
this.streamThreads.clear();
|
|
245
247
|
this.terminalStreams.clear();
|
|
246
248
|
this.terminalMetadata.clear();
|
|
247
249
|
this.streams.clear();
|
|
@@ -388,6 +390,11 @@ export class LocalT3Client {
|
|
|
388
390
|
}
|
|
389
391
|
if (msg._tag === 'Exit') {
|
|
390
392
|
this.streams.delete(reqId);
|
|
393
|
+
const exitedThread = this.streamThreads.get(reqId);
|
|
394
|
+
if (exitedThread) {
|
|
395
|
+
this.streamThreads.delete(reqId);
|
|
396
|
+
this.subscribedThreads.delete(exitedThread);
|
|
397
|
+
}
|
|
391
398
|
const pending = this.pending.get(reqId);
|
|
392
399
|
if (!pending)
|
|
393
400
|
return;
|
|
@@ -531,19 +538,27 @@ export class LocalT3Client {
|
|
|
531
538
|
if (!threadId)
|
|
532
539
|
return;
|
|
533
540
|
const prev = this.wantedThreads.get(threadId) ?? 0;
|
|
534
|
-
|
|
535
|
-
|
|
541
|
+
const effectiveAfter = Math.max(prev, afterSequence);
|
|
542
|
+
if (effectiveAfter > prev || !this.wantedThreads.has(threadId)) {
|
|
543
|
+
this.wantedThreads.set(threadId, effectiveAfter);
|
|
536
544
|
}
|
|
537
545
|
if (this.subscribedThreads.has(threadId) || !this.isConnected())
|
|
538
546
|
return;
|
|
539
547
|
this.subscribedThreads.add(threadId);
|
|
540
548
|
const payload = { threadId };
|
|
541
|
-
if (
|
|
542
|
-
payload.afterSequence =
|
|
549
|
+
if (effectiveAfter > 0)
|
|
550
|
+
payload.afterSequence = effectiveAfter;
|
|
543
551
|
const reqId = this.startStream('orchestration.subscribeThread', payload, (rawItem) => {
|
|
544
552
|
if (!rawItem || typeof rawItem !== 'object')
|
|
545
553
|
return;
|
|
546
554
|
const env = rawItem;
|
|
555
|
+
if (env.kind === 'snapshot' && typeof env.snapshotSequence === 'number') {
|
|
556
|
+
const cur = this.wantedThreads.get(threadId) ?? 0;
|
|
557
|
+
if (env.snapshotSequence > cur) {
|
|
558
|
+
this.wantedThreads.set(threadId, env.snapshotSequence);
|
|
559
|
+
}
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
547
562
|
if (env.kind !== 'event' || typeof env.sequence !== 'number' || !env.event)
|
|
548
563
|
return;
|
|
549
564
|
const cur = this.wantedThreads.get(threadId) ?? 0;
|
|
@@ -551,7 +566,10 @@ export class LocalT3Client {
|
|
|
551
566
|
this.wantedThreads.set(threadId, env.sequence);
|
|
552
567
|
this.callbacks.onThreadEvent({ sequence: env.sequence, event: env.event });
|
|
553
568
|
});
|
|
554
|
-
if (
|
|
569
|
+
if (reqId) {
|
|
570
|
+
this.streamThreads.set(reqId, threadId);
|
|
571
|
+
}
|
|
572
|
+
else {
|
|
555
573
|
this.subscribedThreads.delete(threadId);
|
|
556
574
|
}
|
|
557
575
|
}
|
|
@@ -707,7 +725,14 @@ export class LocalT3Client {
|
|
|
707
725
|
message: text.trim() || `HTTP ${resp.status}`,
|
|
708
726
|
};
|
|
709
727
|
}
|
|
710
|
-
|
|
728
|
+
const parsed = JSON.parse(text);
|
|
729
|
+
if (parsed &&
|
|
730
|
+
typeof parsed === 'object' &&
|
|
731
|
+
typeof parsed.sequence !== 'number' &&
|
|
732
|
+
typeof parsed.snapshotSequence === 'number') {
|
|
733
|
+
parsed.sequence = parsed.snapshotSequence;
|
|
734
|
+
}
|
|
735
|
+
return parsed;
|
|
711
736
|
}
|
|
712
737
|
async resolveDefaultCwd(override) {
|
|
713
738
|
const trimmed = (override ?? '').trim();
|
|
@@ -0,0 +1,284 @@
|
|
|
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
|
+
return {
|
|
281
|
+
agent: new HttpConnectAgent({ keepAlive: false }),
|
|
282
|
+
proxyUrl: proxyUrlStr,
|
|
283
|
+
};
|
|
284
|
+
}
|
package/package.json
CHANGED
package/scripts/service.mjs
CHANGED
|
@@ -8,6 +8,16 @@ import { spawnSync } from 'node:child_process';
|
|
|
8
8
|
|
|
9
9
|
const SERVICE_NAME = 'echo-t3-bridge';
|
|
10
10
|
const LAUNCHD_LABEL = 'top.stormapex.echo-t3-bridge';
|
|
11
|
+
const PROXY_ENV_KEYS = [
|
|
12
|
+
'http_proxy',
|
|
13
|
+
'https_proxy',
|
|
14
|
+
'all_proxy',
|
|
15
|
+
'no_proxy',
|
|
16
|
+
'HTTP_PROXY',
|
|
17
|
+
'HTTPS_PROXY',
|
|
18
|
+
'ALL_PROXY',
|
|
19
|
+
'NO_PROXY',
|
|
20
|
+
];
|
|
11
21
|
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
12
22
|
const cliEntry = join(root, 'dist', 'cli.mjs');
|
|
13
23
|
const action = process.argv[2];
|
|
@@ -59,6 +69,55 @@ function buildServicePath() {
|
|
|
59
69
|
return [...new Set([...extras, ...current])].join(':');
|
|
60
70
|
}
|
|
61
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
|
+
|
|
94
|
+
function collectProxyEnvEntries() {
|
|
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()];
|
|
119
|
+
}
|
|
120
|
+
|
|
62
121
|
function xmlEscape(val) {
|
|
63
122
|
return String(val)
|
|
64
123
|
.replaceAll('&', '&')
|
|
@@ -90,6 +149,9 @@ async function manageLaunchd(mode) {
|
|
|
90
149
|
await mkdir(dirname(target), { recursive: true });
|
|
91
150
|
await mkdir(logDir, { recursive: true, mode: 0o700 });
|
|
92
151
|
|
|
152
|
+
const proxyXml = collectProxyEnvEntries()
|
|
153
|
+
.map(([k, v]) => ` <key>${xmlEscape(k)}</key><string>${xmlEscape(v)}</string>`)
|
|
154
|
+
.join('\n');
|
|
93
155
|
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
94
156
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
95
157
|
<plist version="1.0"><dict>
|
|
@@ -105,7 +167,7 @@ async function manageLaunchd(mode) {
|
|
|
105
167
|
<key>HOME</key><string>${xmlEscape(homedir())}</string>
|
|
106
168
|
<key>SHELL</key><string>${xmlEscape(process.env.SHELL ?? '/bin/zsh')}</string>
|
|
107
169
|
<key>PATH</key><string>${xmlEscape(buildServicePath())}</string>
|
|
108
|
-
</dict>
|
|
170
|
+
${proxyXml ? `${proxyXml}\n` : ''} </dict>
|
|
109
171
|
<key>RunAtLoad</key><true/>
|
|
110
172
|
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
|
111
173
|
<key>ThrottleInterval</key><integer>5</integer>
|
|
@@ -132,6 +194,9 @@ async function manageSystemd(mode) {
|
|
|
132
194
|
|
|
133
195
|
runCmd('systemctl', ['--user', 'stop', SERVICE_NAME], true);
|
|
134
196
|
await mkdir(dirname(target), { recursive: true });
|
|
197
|
+
const proxyLines = collectProxyEnvEntries()
|
|
198
|
+
.map(([k, v]) => `Environment="${k}=${v}"`)
|
|
199
|
+
.join('\n');
|
|
135
200
|
const unit = `[Unit]
|
|
136
201
|
Description=Echo T3 Bridge (zero-fork local T3 to Echo Hub reverse tunnel)
|
|
137
202
|
After=network-online.target
|
|
@@ -142,7 +207,7 @@ Type=simple
|
|
|
142
207
|
Environment="ECHO_T3_BRIDGE_CONFIG=${configPath}"
|
|
143
208
|
Environment="ECHO_T3_BRIDGE_DATA_DIR=${dataDir}"
|
|
144
209
|
Environment="PATH=${buildServicePath()}"
|
|
145
|
-
ExecStart="${process.execPath}" "${cliEntry}" run
|
|
210
|
+
${proxyLines ? `${proxyLines}\n` : ''}ExecStart="${process.execPath}" "${cliEntry}" run
|
|
146
211
|
Restart=always
|
|
147
212
|
RestartSec=3
|
|
148
213
|
|