eas-cli 24.0.0 → 24.1.0
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/README.md +387 -257
- package/build/commands/simulator/egress.d.ts +13 -0
- package/build/commands/simulator/egress.js +60 -0
- package/build/commands/simulator/index.d.ts +2 -0
- package/build/commands/simulator/index.js +75 -9
- package/build/graphql/generated.d.ts +141 -0
- package/build/graphql/generated.js +19 -3
- package/build/graphql/queries/DeviceRunSessionQuery.js +20 -0
- package/build/simulator/egress.d.ts +121 -0
- package/build/simulator/egress.js +865 -0
- package/build/simulator/env.d.ts +5 -0
- package/build/simulator/env.js +42 -1
- package/build/simulator/utils.d.ts +42 -2
- package/build/simulator/utils.js +114 -5
- package/oclif.manifest.json +1438 -1338
- package/package.json +2 -2
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveEgressTargetAsync = exports.EgressPolicyError = exports.LOCAL_EGRESS_USERNAME = exports.LOCAL_EGRESS_PROXY_HOST = void 0;
|
|
4
|
+
exports.readLocalEgressConfigFromEnv = readLocalEgressConfigFromEnv;
|
|
5
|
+
exports.isForbiddenEgressAddress = isForbiddenEgressAddress;
|
|
6
|
+
exports.orderEgressAddresses = orderEgressAddresses;
|
|
7
|
+
exports.parseEgressAllowEntry = parseEgressAllowEntry;
|
|
8
|
+
exports.parseEgressAllowList = parseEgressAllowList;
|
|
9
|
+
exports.createEgressTargetResolver = createEgressTargetResolver;
|
|
10
|
+
exports.startLocalEgressProxyServerAsync = startLocalEgressProxyServerAsync;
|
|
11
|
+
exports.getChiselAssetName = getChiselAssetName;
|
|
12
|
+
exports.ensureChiselBinaryAsync = ensureChiselBinaryAsync;
|
|
13
|
+
exports.buildChiselClientArgs = buildChiselClientArgs;
|
|
14
|
+
exports.isChiselRemoteRejectionLine = isChiselRemoteRejectionLine;
|
|
15
|
+
exports.classifyChiselClientLogLine = classifyChiselClientLogLine;
|
|
16
|
+
exports.runLocalEgressAsync = runLocalEgressAsync;
|
|
17
|
+
const tslib_1 = require("tslib");
|
|
18
|
+
const spawn_async_1 = tslib_1.__importDefault(require("@expo/spawn-async"));
|
|
19
|
+
const fs = tslib_1.__importStar(require("fs-extra"));
|
|
20
|
+
const node_crypto_1 = require("node:crypto");
|
|
21
|
+
const promises_1 = tslib_1.__importDefault(require("node:dns/promises"));
|
|
22
|
+
const node_http_1 = tslib_1.__importDefault(require("node:http"));
|
|
23
|
+
const node_net_1 = tslib_1.__importDefault(require("node:net"));
|
|
24
|
+
const node_path_1 = tslib_1.__importDefault(require("node:path"));
|
|
25
|
+
const node_readline_1 = tslib_1.__importDefault(require("node:readline"));
|
|
26
|
+
const node_zlib_1 = tslib_1.__importDefault(require("node:zlib"));
|
|
27
|
+
const env_1 = require("./env");
|
|
28
|
+
const utils_1 = require("./utils");
|
|
29
|
+
const fetch_1 = tslib_1.__importDefault(require("../fetch"));
|
|
30
|
+
const log_1 = tslib_1.__importDefault(require("../log"));
|
|
31
|
+
const paths_1 = require("../utils/paths");
|
|
32
|
+
/**
|
|
33
|
+
* Local egress client. Two pieces run on the developer's machine for the life of
|
|
34
|
+
* a simulator session started with `--egress local`:
|
|
35
|
+
*
|
|
36
|
+
* 1. An HTTP proxy on loopback that forwards the requests it receives to the
|
|
37
|
+
* internet from this machine. It supports CONNECT tunnels (HTTPS, WSS), plain
|
|
38
|
+
* HTTP requests with absolute URLs, and HTTP upgrades (WS). It refuses
|
|
39
|
+
* destinations on this machine's local networks: the requests it forwards
|
|
40
|
+
* come from code running in the remote simulator, not from the developer.
|
|
41
|
+
* 2. A chisel client that connects out to the session's tunnel server and asks it
|
|
42
|
+
* to listen on the device host's loopback proxy port, forwarding every
|
|
43
|
+
* connection back to the local proxy. The device host's system proxy points at
|
|
44
|
+
* that port, so requests that honor it (WebKit, URLSession and other CFNetwork
|
|
45
|
+
* clients) arrive here. Requests from libraries that bypass the system proxy
|
|
46
|
+
* never reach this client and exit from the device host instead.
|
|
47
|
+
*
|
|
48
|
+
* `--egress-allow host:port` names destinations on the developer's machine or
|
|
49
|
+
* network that the proxy may connect to despite the local-network refusal, so a
|
|
50
|
+
* dev server on `localhost:3000` is reachable from the remote simulator the way
|
|
51
|
+
* it is from a local one. Entries are exact host and port pairs, never ranges.
|
|
52
|
+
*/
|
|
53
|
+
exports.LOCAL_EGRESS_PROXY_HOST = '127.0.0.1';
|
|
54
|
+
/** Username in the worker's chisel authfile; the session token is its password. */
|
|
55
|
+
exports.LOCAL_EGRESS_USERNAME = 'eas';
|
|
56
|
+
const CHISEL_VERSION = '1.12.0';
|
|
57
|
+
// sha256 of the release .gz assets, cross-checked against chisel_1.12.0_checksums.txt.
|
|
58
|
+
const CHISEL_SHA256_BY_ASSET = {
|
|
59
|
+
'chisel_1.12.0_darwin_arm64.gz': '707a4b932eea214765146504a0df246cefc415b4297af65a80dd67cf69ba85a9',
|
|
60
|
+
'chisel_1.12.0_darwin_amd64.gz': '4aeae36c867f11c8e8c3f2b913a0e063ea3c6d29e1c14a52ed2e6eef8cfc4395',
|
|
61
|
+
'chisel_1.12.0_linux_amd64.gz': 'f3f180f1d93aa72cce4e6386f98cc06569a0146fbd65eb4423cf83e6434bcfe6',
|
|
62
|
+
'chisel_1.12.0_linux_arm64.gz': '2ec6152cd2c74fe0146d4d79e4e7aa174521368c56e433d55e023a92ea404ec3',
|
|
63
|
+
};
|
|
64
|
+
const MAX_CONCURRENT_CONNECTIONS = 512;
|
|
65
|
+
const UPSTREAM_ATTEMPT_TIMEOUT_MS = 5_000;
|
|
66
|
+
const UPSTREAM_RESPONSE_TIMEOUT_MS = 30_000;
|
|
67
|
+
const SOCKET_IDLE_TIMEOUT_MS = 120_000;
|
|
68
|
+
const HOP_BY_HOP_HEADERS = new Set([
|
|
69
|
+
'connection',
|
|
70
|
+
'keep-alive',
|
|
71
|
+
'proxy-authenticate',
|
|
72
|
+
'proxy-authorization',
|
|
73
|
+
'proxy-connection',
|
|
74
|
+
'te',
|
|
75
|
+
'trailer',
|
|
76
|
+
'transfer-encoding',
|
|
77
|
+
'upgrade',
|
|
78
|
+
]);
|
|
79
|
+
function readLocalEgressConfigFromEnv(env) {
|
|
80
|
+
const url = env[env_1.EAS_SIMULATOR_EGRESS_URL];
|
|
81
|
+
const token = env[env_1.EAS_SIMULATOR_EGRESS_TOKEN];
|
|
82
|
+
const fingerprint = env[env_1.EAS_SIMULATOR_EGRESS_FINGERPRINT];
|
|
83
|
+
const port = Number(env[env_1.EAS_SIMULATOR_EGRESS_PORT]);
|
|
84
|
+
if (!url || !token || !fingerprint || !Number.isInteger(port) || port <= 0) {
|
|
85
|
+
throw new Error('The current simulator session was not started with local egress, so there is no egress ' +
|
|
86
|
+
`client to run (${env_1.EAS_SIMULATOR_EGRESS_URL} is not set). Start one with ` +
|
|
87
|
+
'`eas simulator:start --platform ios --egress local`.');
|
|
88
|
+
}
|
|
89
|
+
const allow = parseEgressAllowList((env[env_1.EAS_SIMULATOR_EGRESS_ALLOW] ?? '').split(',').filter(entry => entry.trim().length > 0));
|
|
90
|
+
return { url, token, fingerprint, port, allow };
|
|
91
|
+
}
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
// Destination policy
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
class EgressPolicyError extends Error {
|
|
96
|
+
constructor(host, address) {
|
|
97
|
+
super(`Refused to connect to ${host}${address && address !== host ? ` (${address})` : ''}: ` +
|
|
98
|
+
'local, private, link-local, and multicast addresses are not reachable through local egress.');
|
|
99
|
+
this.name = 'EgressPolicyError';
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
exports.EgressPolicyError = EgressPolicyError;
|
|
103
|
+
function isForbiddenIpv4(address) {
|
|
104
|
+
const octets = address.split('.').map(Number);
|
|
105
|
+
if (octets.length !== 4 ||
|
|
106
|
+
octets.some(octet => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
const [a, b] = octets;
|
|
110
|
+
return (a === 0 || // "this" network
|
|
111
|
+
a === 10 || // private
|
|
112
|
+
a === 127 || // loopback
|
|
113
|
+
(a === 100 && b >= 64 && b <= 127) || // carrier-grade NAT
|
|
114
|
+
(a === 169 && b === 254) || // link-local, cloud metadata
|
|
115
|
+
(a === 172 && b >= 16 && b <= 31) || // private
|
|
116
|
+
(a === 192 && b === 168) || // private
|
|
117
|
+
a >= 224 // multicast and reserved
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
function expandIpv6(address) {
|
|
121
|
+
const withoutZone = address.split('%')[0];
|
|
122
|
+
const halves = withoutZone.split('::');
|
|
123
|
+
if (halves.length > 2) {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
const head = halves[0] ? halves[0].split(':') : [];
|
|
127
|
+
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
|
|
128
|
+
if ([...head, ...tail].some(group => group.includes('.'))) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
const missing = 8 - head.length - tail.length;
|
|
132
|
+
if (missing < 0 || (halves.length === 1 && missing !== 0)) {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const groups = [...head, ...new Array(missing).fill('0'), ...tail].map(group => parseInt(group, 16));
|
|
136
|
+
if (groups.some(group => Number.isNaN(group) || group < 0 || group > 0xffff)) {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
return groups;
|
|
140
|
+
}
|
|
141
|
+
function isForbiddenIpv6(address) {
|
|
142
|
+
const lower = address.toLowerCase();
|
|
143
|
+
const mappedIpv4 = /^(?:0*:)*:ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
|
|
144
|
+
if (mappedIpv4) {
|
|
145
|
+
return isForbiddenIpv4(mappedIpv4[1]);
|
|
146
|
+
}
|
|
147
|
+
const groups = expandIpv6(lower);
|
|
148
|
+
if (!groups) {
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
const isUnspecified = groups.every(group => group === 0);
|
|
152
|
+
const isLoopback = groups.slice(0, 7).every(group => group === 0) && groups[7] === 1;
|
|
153
|
+
if (isUnspecified || isLoopback) {
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
if (groups.slice(0, 5).every(group => group === 0) && groups[5] === 0xffff) {
|
|
157
|
+
const embedded = `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`;
|
|
158
|
+
return isForbiddenIpv4(embedded);
|
|
159
|
+
}
|
|
160
|
+
const first = groups[0];
|
|
161
|
+
return ((first & 0xfe00) === 0xfc00 || // fc00::/7 unique local
|
|
162
|
+
(first & 0xffc0) === 0xfe80 || // fe80::/10 link-local
|
|
163
|
+
(first & 0xff00) === 0xff00 // ff00::/8 multicast
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
/** True for any address the egress client must never connect to. */
|
|
167
|
+
function isForbiddenEgressAddress(address) {
|
|
168
|
+
switch (node_net_1.default.isIP(address)) {
|
|
169
|
+
case 4:
|
|
170
|
+
return isForbiddenIpv4(address);
|
|
171
|
+
case 6:
|
|
172
|
+
return isForbiddenIpv6(address);
|
|
173
|
+
default:
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* IPv4 first. Developer networks often have broken or slow IPv6, and a hung
|
|
179
|
+
* first attempt would stall the simulator's request for the whole timeout.
|
|
180
|
+
*/
|
|
181
|
+
function orderEgressAddresses(addresses) {
|
|
182
|
+
const ordered = [
|
|
183
|
+
...addresses.filter(({ family }) => family === 4),
|
|
184
|
+
...addresses.filter(({ family }) => family !== 4),
|
|
185
|
+
].map(({ address }) => address);
|
|
186
|
+
return [...new Set(ordered)];
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Resolve a destination hostname to the addresses the proxy may connect to,
|
|
190
|
+
* refusing anything local. Every address the name resolves to is checked, so a
|
|
191
|
+
* name that mixes public and private records is refused as a whole, and
|
|
192
|
+
* connections are made to the returned addresses rather than by re-resolving.
|
|
193
|
+
*/
|
|
194
|
+
const resolveEgressTargetAsync = async (hostname) => {
|
|
195
|
+
const host = hostname.replace(/^\[|\]$/g, '');
|
|
196
|
+
const lowerHost = host.toLowerCase();
|
|
197
|
+
if (lowerHost === 'localhost' ||
|
|
198
|
+
lowerHost.endsWith('.localhost') ||
|
|
199
|
+
lowerHost.endsWith('.local')) {
|
|
200
|
+
throw new EgressPolicyError(host);
|
|
201
|
+
}
|
|
202
|
+
if (node_net_1.default.isIP(host)) {
|
|
203
|
+
if (isForbiddenEgressAddress(host)) {
|
|
204
|
+
throw new EgressPolicyError(host);
|
|
205
|
+
}
|
|
206
|
+
return [host];
|
|
207
|
+
}
|
|
208
|
+
const addresses = await promises_1.default.lookup(host, { all: true, verbatim: true });
|
|
209
|
+
if (addresses.length === 0) {
|
|
210
|
+
throw new Error(`Could not resolve ${host}.`);
|
|
211
|
+
}
|
|
212
|
+
const forbidden = addresses.find(({ address }) => isForbiddenEgressAddress(address));
|
|
213
|
+
if (forbidden) {
|
|
214
|
+
throw new EgressPolicyError(host, forbidden.address);
|
|
215
|
+
}
|
|
216
|
+
return orderEgressAddresses(addresses);
|
|
217
|
+
};
|
|
218
|
+
exports.resolveEgressTargetAsync = resolveEgressTargetAsync;
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
// Allowed local destinations (--egress-allow)
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
function formatEgressDestination(host, port) {
|
|
223
|
+
return `${node_net_1.default.isIPv6(host) ? `[${host}]` : host}:${port}`;
|
|
224
|
+
}
|
|
225
|
+
function normalizeEgressHostname(hostname) {
|
|
226
|
+
const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
227
|
+
if (node_net_1.default.isIPv6(host)) {
|
|
228
|
+
// URL canonicalizes IPv6 but does not accept interface zone identifiers.
|
|
229
|
+
const [address, zone] = host.split('%');
|
|
230
|
+
const normalized = new URL(`http://[${address}]`).hostname.slice(1, -1);
|
|
231
|
+
return zone ? `${normalized}%${zone}` : normalized;
|
|
232
|
+
}
|
|
233
|
+
if (!/^[\p{L}\p{M}\p{N}_.-]+$/u.test(host)) {
|
|
234
|
+
throw new Error(`Invalid destination hostname "${hostname}".`);
|
|
235
|
+
}
|
|
236
|
+
// Match absolute-form HTTP URL parsing, including IPv4 and IDN normalization.
|
|
237
|
+
return new URL(`http://${host}`).hostname;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Parse one `--egress-allow` value into its normalized `host:port` form. Only an
|
|
241
|
+
* exact host and port pair is accepted. Web pages and SDKs inside the simulator
|
|
242
|
+
* can use the proxy too, so nothing here opens a range or a wildcard.
|
|
243
|
+
*/
|
|
244
|
+
function parseEgressAllowEntry(entry) {
|
|
245
|
+
const match = /^(\[[^\]]+\]|[^\s:/[\]*]+):(\d{1,5})$/.exec(entry.trim());
|
|
246
|
+
const host = match ? match[1].replace(/^\[|\]$/g, '').toLowerCase() : '';
|
|
247
|
+
const port = match ? Number(match[2]) : 0;
|
|
248
|
+
const bracketed = match ? match[1].startsWith('[') : false;
|
|
249
|
+
if (!match || port <= 0 || port > 65535 || (bracketed && !node_net_1.default.isIPv6(host))) {
|
|
250
|
+
throw new Error(`Invalid --egress-allow value "${entry}". Use an exact host and port, for example ` +
|
|
251
|
+
'localhost:3000, 192.168.1.20:8080, or [::1]:3000. Wildcards and address ranges are not accepted.');
|
|
252
|
+
}
|
|
253
|
+
try {
|
|
254
|
+
return formatEgressDestination(normalizeEgressHostname(host), port);
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
throw new Error(`Invalid --egress-allow value "${entry}". Use an exact hostname or IP address and port.`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function parseEgressAllowList(entries) {
|
|
261
|
+
return [...new Set(entries.map(parseEgressAllowEntry))];
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Wrap the default destination policy with the `--egress-allow` list. A listed
|
|
265
|
+
* destination connects to this machine's loopback or network exactly as named;
|
|
266
|
+
* every other destination keeps the default refusals. `localhost` maps to the
|
|
267
|
+
* loopback addresses directly and never goes through DNS.
|
|
268
|
+
*/
|
|
269
|
+
function createEgressTargetResolver({ allow, onAllowed, }) {
|
|
270
|
+
const allowed = new Set(allow);
|
|
271
|
+
if (allowed.size === 0) {
|
|
272
|
+
return exports.resolveEgressTargetAsync;
|
|
273
|
+
}
|
|
274
|
+
return async (hostname, port) => {
|
|
275
|
+
const host = normalizeEgressHostname(hostname);
|
|
276
|
+
const destination = formatEgressDestination(host, port);
|
|
277
|
+
if (!allowed.has(destination)) {
|
|
278
|
+
return await (0, exports.resolveEgressTargetAsync)(hostname, port);
|
|
279
|
+
}
|
|
280
|
+
onAllowed?.(destination);
|
|
281
|
+
if (host === 'localhost') {
|
|
282
|
+
return ['127.0.0.1', '::1'];
|
|
283
|
+
}
|
|
284
|
+
if (node_net_1.default.isIP(host)) {
|
|
285
|
+
return [host];
|
|
286
|
+
}
|
|
287
|
+
const addresses = await promises_1.default.lookup(host, { all: true, verbatim: true });
|
|
288
|
+
if (addresses.length === 0) {
|
|
289
|
+
throw new Error(`Could not resolve ${host}.`);
|
|
290
|
+
}
|
|
291
|
+
return orderEgressAddresses(addresses);
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
function parseAuthority(authority, defaultPort) {
|
|
295
|
+
const match = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(authority);
|
|
296
|
+
if (!match) {
|
|
297
|
+
throw new Error(`Invalid destination "${authority}".`);
|
|
298
|
+
}
|
|
299
|
+
const port = match[2] ? Number(match[2]) : defaultPort;
|
|
300
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
301
|
+
throw new Error(`Invalid destination port in "${authority}".`);
|
|
302
|
+
}
|
|
303
|
+
return { host: match[1], port };
|
|
304
|
+
}
|
|
305
|
+
/** Try each validated address in order; the first that connects wins. */
|
|
306
|
+
async function connectUpstreamAsync({ addresses, port, signal, onSocket, }) {
|
|
307
|
+
let lastError;
|
|
308
|
+
for (const address of addresses) {
|
|
309
|
+
signal.throwIfAborted();
|
|
310
|
+
try {
|
|
311
|
+
return await connectOnceAsync({ host: address, port, signal, onSocket });
|
|
312
|
+
}
|
|
313
|
+
catch (err) {
|
|
314
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
throw lastError ?? new Error(`No addresses to connect to on port ${port}.`);
|
|
318
|
+
}
|
|
319
|
+
async function connectOnceAsync({ host, port, signal, onSocket, }) {
|
|
320
|
+
return await new Promise((resolve, reject) => {
|
|
321
|
+
signal.throwIfAborted();
|
|
322
|
+
const socket = node_net_1.default.connect({ host, port, signal });
|
|
323
|
+
onSocket(socket);
|
|
324
|
+
const timeout = setTimeout(() => {
|
|
325
|
+
socket.destroy();
|
|
326
|
+
reject(new Error(`Timed out connecting to ${host}:${port}.`));
|
|
327
|
+
}, UPSTREAM_ATTEMPT_TIMEOUT_MS);
|
|
328
|
+
socket.once('connect', () => {
|
|
329
|
+
clearTimeout(timeout);
|
|
330
|
+
resolve(socket);
|
|
331
|
+
});
|
|
332
|
+
socket.once('error', err => {
|
|
333
|
+
clearTimeout(timeout);
|
|
334
|
+
socket.destroy();
|
|
335
|
+
reject(err);
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
function pipeBothWays(a, b, onClose) {
|
|
340
|
+
let closed = false;
|
|
341
|
+
const finish = () => {
|
|
342
|
+
if (closed) {
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
closed = true;
|
|
346
|
+
a.destroy();
|
|
347
|
+
b.destroy();
|
|
348
|
+
onClose();
|
|
349
|
+
};
|
|
350
|
+
for (const socket of [a, b]) {
|
|
351
|
+
if (socket instanceof node_net_1.default.Socket) {
|
|
352
|
+
socket.setTimeout(SOCKET_IDLE_TIMEOUT_MS, finish);
|
|
353
|
+
}
|
|
354
|
+
socket.on('error', finish);
|
|
355
|
+
socket.on('close', finish);
|
|
356
|
+
}
|
|
357
|
+
a.pipe(b);
|
|
358
|
+
b.pipe(a);
|
|
359
|
+
}
|
|
360
|
+
function statusForError(err) {
|
|
361
|
+
return err instanceof EgressPolicyError ? 403 : 502;
|
|
362
|
+
}
|
|
363
|
+
function filteredRawHeaders(rawHeaders, upgrade = false) {
|
|
364
|
+
const removed = new Set(HOP_BY_HOP_HEADERS);
|
|
365
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
366
|
+
if (rawHeaders[i].toLowerCase() === 'connection') {
|
|
367
|
+
for (const token of rawHeaders[i + 1].split(',')) {
|
|
368
|
+
removed.add(token.trim().toLowerCase());
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const result = [];
|
|
373
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
374
|
+
const name = rawHeaders[i].toLowerCase();
|
|
375
|
+
if (!removed.has(name) || (upgrade && name === 'upgrade')) {
|
|
376
|
+
result.push(rawHeaders[i], rawHeaders[i + 1]);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (upgrade) {
|
|
380
|
+
result.push('Connection', 'Upgrade');
|
|
381
|
+
}
|
|
382
|
+
return result;
|
|
383
|
+
}
|
|
384
|
+
async function startLocalEgressProxyServerAsync({ host = exports.LOCAL_EGRESS_PROXY_HOST, port, resolveTargetAsync = exports.resolveEgressTargetAsync, }) {
|
|
385
|
+
const stats = { active: 0, total: 0, refused: 0 };
|
|
386
|
+
const sockets = new Set();
|
|
387
|
+
const operations = new Set();
|
|
388
|
+
let closing = false;
|
|
389
|
+
const trackSocket = (socket) => {
|
|
390
|
+
sockets.add(socket);
|
|
391
|
+
// Keep errors handled between connecting and assigning a socket to its request.
|
|
392
|
+
socket.on('error', () => { });
|
|
393
|
+
socket.once('close', () => sockets.delete(socket));
|
|
394
|
+
if (closing) {
|
|
395
|
+
socket.destroy();
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
const acquire = () => {
|
|
399
|
+
if (closing || stats.active >= MAX_CONCURRENT_CONNECTIONS) {
|
|
400
|
+
stats.refused += 1;
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
stats.active += 1;
|
|
404
|
+
stats.total += 1;
|
|
405
|
+
const controller = new AbortController();
|
|
406
|
+
const finish = () => {
|
|
407
|
+
if (operations.delete(finish)) {
|
|
408
|
+
stats.active -= 1;
|
|
409
|
+
controller.abort();
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
operations.add(finish);
|
|
413
|
+
return { signal: controller.signal, finish };
|
|
414
|
+
};
|
|
415
|
+
const connectAsync = async (hostname, targetPort, signal) => {
|
|
416
|
+
const addresses = await resolveTargetAsync(hostname, targetPort);
|
|
417
|
+
// DNS lookup itself cannot be canceled, but a late answer must never open a socket.
|
|
418
|
+
signal.throwIfAborted();
|
|
419
|
+
return await connectUpstreamAsync({
|
|
420
|
+
addresses,
|
|
421
|
+
port: targetPort,
|
|
422
|
+
signal,
|
|
423
|
+
onSocket: trackSocket,
|
|
424
|
+
});
|
|
425
|
+
};
|
|
426
|
+
const server = node_http_1.default.createServer();
|
|
427
|
+
// Bound accepted sockets as well as parsed operations: idle peers and upgraded
|
|
428
|
+
// connections still consume descriptors. Upstream sockets use a separate budget.
|
|
429
|
+
server.maxConnections = MAX_CONCURRENT_CONNECTIONS;
|
|
430
|
+
server.setTimeout(SOCKET_IDLE_TIMEOUT_MS);
|
|
431
|
+
server.on('timeout', (socket) => socket.destroy());
|
|
432
|
+
server.on('drop', () => {
|
|
433
|
+
stats.refused += 1;
|
|
434
|
+
});
|
|
435
|
+
server.on('connection', trackSocket);
|
|
436
|
+
// HTTPS and WSS use CONNECT. Acquire and observe disconnects before the first await.
|
|
437
|
+
server.on('connect', (req, clientSocket, head) => {
|
|
438
|
+
const operation = acquire();
|
|
439
|
+
if (!operation) {
|
|
440
|
+
clientSocket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n');
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
const { signal, finish } = operation;
|
|
444
|
+
const cancel = () => {
|
|
445
|
+
finish();
|
|
446
|
+
clientSocket.destroy();
|
|
447
|
+
};
|
|
448
|
+
clientSocket.once('close', finish);
|
|
449
|
+
clientSocket.once('end', cancel);
|
|
450
|
+
clientSocket.once('error', cancel);
|
|
451
|
+
void (async () => {
|
|
452
|
+
try {
|
|
453
|
+
const { host: targetHost, port: targetPort } = parseAuthority(req.url ?? '', 443);
|
|
454
|
+
const upstream = await connectAsync(targetHost, targetPort, signal);
|
|
455
|
+
signal.throwIfAborted();
|
|
456
|
+
clientSocket.removeListener('end', cancel);
|
|
457
|
+
log_1.default.debug(`[egress] CONNECT ${targetHost}:${targetPort}`);
|
|
458
|
+
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
459
|
+
if (head.length > 0) {
|
|
460
|
+
upstream.write(head);
|
|
461
|
+
}
|
|
462
|
+
pipeBothWays(clientSocket, upstream, finish);
|
|
463
|
+
}
|
|
464
|
+
catch (err) {
|
|
465
|
+
finish();
|
|
466
|
+
log_1.default.debug(`[egress] CONNECT ${req.url} refused: ${err instanceof Error ? err.message : err}`);
|
|
467
|
+
if (!clientSocket.destroyed) {
|
|
468
|
+
clientSocket.end(`HTTP/1.1 ${statusForError(err)} ${node_http_1.default.STATUS_CODES[statusForError(err)]}\r\nConnection: close\r\n\r\n`);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
})();
|
|
472
|
+
});
|
|
473
|
+
const forwardHttp = (req, res, upgradeClient) => {
|
|
474
|
+
const operation = acquire();
|
|
475
|
+
if (!operation) {
|
|
476
|
+
res.writeHead(503).end();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const { signal, finish } = operation;
|
|
480
|
+
res.once('close', finish);
|
|
481
|
+
req.once('aborted', finish);
|
|
482
|
+
req.once('error', finish);
|
|
483
|
+
const cancelUpgrade = () => {
|
|
484
|
+
finish();
|
|
485
|
+
upgradeClient?.socket.destroy();
|
|
486
|
+
};
|
|
487
|
+
upgradeClient?.socket.once('end', cancelUpgrade);
|
|
488
|
+
upgradeClient?.socket.once('close', finish);
|
|
489
|
+
upgradeClient?.socket.once('error', cancelUpgrade);
|
|
490
|
+
void (async () => {
|
|
491
|
+
try {
|
|
492
|
+
let url;
|
|
493
|
+
try {
|
|
494
|
+
url = new URL(req.url ?? '');
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
res.writeHead(400).end('This proxy only accepts requests with absolute URLs.');
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (url.protocol !== 'http:') {
|
|
501
|
+
res.writeHead(400).end(`Unsupported URL scheme ${url.protocol}`);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const transferEncoding = req.headers['transfer-encoding'];
|
|
505
|
+
if (transferEncoding && transferEncoding.trim().toLowerCase() !== 'chunked') {
|
|
506
|
+
// Node removes chunk framing but does not decode other transfer codings.
|
|
507
|
+
res.writeHead(501).end('Only chunked request transfer encoding is supported.');
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
const upstreamSocket = await connectAsync(url.hostname, url.port ? Number(url.port) : 80, signal);
|
|
511
|
+
signal.throwIfAborted();
|
|
512
|
+
log_1.default.debug(`[egress] ${req.method} ${url.host}`);
|
|
513
|
+
const rawHeaders = filteredRawHeaders(req.rawHeaders, !!upgradeClient);
|
|
514
|
+
const headers = {};
|
|
515
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
516
|
+
const name = rawHeaders[i].toLowerCase();
|
|
517
|
+
const value = rawHeaders[i + 1];
|
|
518
|
+
const previous = headers[name];
|
|
519
|
+
headers[name] =
|
|
520
|
+
previous === undefined
|
|
521
|
+
? value
|
|
522
|
+
: [...(Array.isArray(previous) ? previous : [String(previous)]), value];
|
|
523
|
+
}
|
|
524
|
+
// Absolute-form authority is authoritative, even if a client sends a conflicting Host.
|
|
525
|
+
headers.host = url.host;
|
|
526
|
+
if (transferEncoding ||
|
|
527
|
+
(req.headers['content-length'] !== undefined && headers['content-length'] === undefined)) {
|
|
528
|
+
// Reframe the decoded body explicitly: Node does not enable chunking by
|
|
529
|
+
// default for GET/DELETE, including when Connection nominated its framing header.
|
|
530
|
+
headers['transfer-encoding'] = 'chunked';
|
|
531
|
+
}
|
|
532
|
+
const upstreamRequest = node_http_1.default.request({
|
|
533
|
+
createConnection: () => upstreamSocket,
|
|
534
|
+
method: req.method,
|
|
535
|
+
path: `${url.pathname}${url.search}`,
|
|
536
|
+
headers,
|
|
537
|
+
setHost: false,
|
|
538
|
+
signal,
|
|
539
|
+
timeout: UPSTREAM_RESPONSE_TIMEOUT_MS,
|
|
540
|
+
});
|
|
541
|
+
let failed = false;
|
|
542
|
+
let completed = false;
|
|
543
|
+
const fail = (err) => {
|
|
544
|
+
if (failed) {
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
failed = true;
|
|
548
|
+
if (completed && signal.aborted) {
|
|
549
|
+
// finish() aborts the shared signal once the response has been sent or
|
|
550
|
+
// the upgrade handed off, which errors the already-completed upstream
|
|
551
|
+
// request. That is cleanup, not a failure.
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
log_1.default.debug(`[egress] ${req.method} ${url.host} failed: ${err.message}`);
|
|
555
|
+
if (!res.destroyed) {
|
|
556
|
+
if (res.headersSent) {
|
|
557
|
+
// Do not turn a truncated successful response into an apparently complete one.
|
|
558
|
+
res.destroy();
|
|
559
|
+
}
|
|
560
|
+
else {
|
|
561
|
+
res.writeHead(502).end();
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
finish();
|
|
565
|
+
};
|
|
566
|
+
upstreamRequest.on('timeout', () => {
|
|
567
|
+
upstreamRequest.destroy(new Error('Upstream timed out.'));
|
|
568
|
+
});
|
|
569
|
+
upstreamRequest.on('error', fail);
|
|
570
|
+
upstreamRequest.on('response', upstreamResponse => {
|
|
571
|
+
upstreamResponse.on('error', fail);
|
|
572
|
+
upstreamResponse.on('aborted', () => {
|
|
573
|
+
fail(new Error('Upstream response was truncated.'));
|
|
574
|
+
});
|
|
575
|
+
const transferEncoding = upstreamResponse.headers['transfer-encoding'];
|
|
576
|
+
if (transferEncoding && transferEncoding.trim().toLowerCase() !== 'chunked') {
|
|
577
|
+
fail(new Error('Unsupported upstream transfer encoding.'));
|
|
578
|
+
upstreamResponse.destroy();
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
res.writeHead(upstreamResponse.statusCode ?? 502, filteredRawHeaders(upstreamResponse.rawHeaders));
|
|
582
|
+
upstreamResponse.once('end', () => {
|
|
583
|
+
completed = true;
|
|
584
|
+
});
|
|
585
|
+
upstreamResponse.pipe(res);
|
|
586
|
+
});
|
|
587
|
+
if (upgradeClient) {
|
|
588
|
+
upstreamRequest.on('upgrade', (upstreamResponse, upstream, upstreamHead) => {
|
|
589
|
+
if (signal.aborted) {
|
|
590
|
+
upstream.destroy();
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
completed = true;
|
|
594
|
+
const { socket, head } = upgradeClient;
|
|
595
|
+
socket.removeListener('end', cancelUpgrade);
|
|
596
|
+
res.removeListener('close', finish);
|
|
597
|
+
res.detachSocket(socket);
|
|
598
|
+
const rawHeaders = filteredRawHeaders(upstreamResponse.rawHeaders, true);
|
|
599
|
+
const headerLines = [];
|
|
600
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
601
|
+
headerLines.push(`${rawHeaders[i]}: ${rawHeaders[i + 1]}`);
|
|
602
|
+
}
|
|
603
|
+
socket.write(`HTTP/1.1 ${upstreamResponse.statusCode} ${upstreamResponse.statusMessage}\r\n${headerLines.join('\r\n')}\r\n\r\n`);
|
|
604
|
+
if (upstreamHead.length > 0) {
|
|
605
|
+
socket.write(upstreamHead);
|
|
606
|
+
}
|
|
607
|
+
if (head.length > 0) {
|
|
608
|
+
upstream.write(head);
|
|
609
|
+
}
|
|
610
|
+
pipeBothWays(socket, upstream, finish);
|
|
611
|
+
});
|
|
612
|
+
upstreamRequest.end();
|
|
613
|
+
}
|
|
614
|
+
else {
|
|
615
|
+
req.pipe(upstreamRequest);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
catch (err) {
|
|
619
|
+
if (!res.destroyed) {
|
|
620
|
+
res.writeHead(statusForError(err)).end();
|
|
621
|
+
}
|
|
622
|
+
finish();
|
|
623
|
+
log_1.default.debug(`[egress] ${req.method} ${req.url} refused: ${err instanceof Error ? err.message : err}`);
|
|
624
|
+
}
|
|
625
|
+
})();
|
|
626
|
+
};
|
|
627
|
+
server.on('request', (req, res) => {
|
|
628
|
+
forwardHttp(req, res);
|
|
629
|
+
});
|
|
630
|
+
server.on('upgrade', (req, socket, head) => {
|
|
631
|
+
// Parse/filter the handshake in both directions before switching to a raw tunnel.
|
|
632
|
+
const res = new node_http_1.default.ServerResponse(req);
|
|
633
|
+
res.assignSocket(socket);
|
|
634
|
+
res.shouldKeepAlive = false;
|
|
635
|
+
res.once('finish', () => socket.end());
|
|
636
|
+
forwardHttp(req, res, { socket, head });
|
|
637
|
+
});
|
|
638
|
+
server.on('clientError', (_err, socket) => {
|
|
639
|
+
if (!socket.destroyed) {
|
|
640
|
+
socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
await new Promise((resolve, reject) => {
|
|
644
|
+
server.once('error', reject);
|
|
645
|
+
server.listen(port, host, () => {
|
|
646
|
+
server.removeListener('error', reject);
|
|
647
|
+
resolve();
|
|
648
|
+
});
|
|
649
|
+
});
|
|
650
|
+
const address = server.address();
|
|
651
|
+
const boundPort = address && typeof address !== 'string' ? address.port : port;
|
|
652
|
+
let closePromise;
|
|
653
|
+
return {
|
|
654
|
+
port: boundPort,
|
|
655
|
+
getStats: () => ({ ...stats }),
|
|
656
|
+
closeAsync: async () => {
|
|
657
|
+
closePromise ??= new Promise(resolve => {
|
|
658
|
+
closing = true;
|
|
659
|
+
server.close(() => {
|
|
660
|
+
resolve();
|
|
661
|
+
});
|
|
662
|
+
for (const finish of operations) {
|
|
663
|
+
finish();
|
|
664
|
+
}
|
|
665
|
+
// closeAllConnections excludes CONNECT/upgrade sockets; own all sockets explicitly.
|
|
666
|
+
for (const socket of sockets) {
|
|
667
|
+
socket.destroy();
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
await closePromise;
|
|
671
|
+
},
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
// ---------------------------------------------------------------------------
|
|
675
|
+
// chisel client
|
|
676
|
+
// ---------------------------------------------------------------------------
|
|
677
|
+
function getChiselAssetName({ platform, arch, }) {
|
|
678
|
+
const os = platform === 'darwin' ? 'darwin' : platform === 'linux' ? 'linux' : null;
|
|
679
|
+
const cpu = arch === 'arm64' ? 'arm64' : arch === 'x64' ? 'amd64' : null;
|
|
680
|
+
if (!os || !cpu) {
|
|
681
|
+
throw new Error(`Local egress is not supported on ${platform}/${arch}. The tunnel client is available for macOS and Linux on arm64 and x64.`);
|
|
682
|
+
}
|
|
683
|
+
return `chisel_${CHISEL_VERSION}_${os}_${cpu}.gz`;
|
|
684
|
+
}
|
|
685
|
+
async function ensureChiselBinaryAsync({ platform = process.platform, arch = process.arch, signal, } = {}) {
|
|
686
|
+
signal?.throwIfAborted();
|
|
687
|
+
const assetName = getChiselAssetName({ platform, arch });
|
|
688
|
+
const expectedSha256 = CHISEL_SHA256_BY_ASSET[assetName];
|
|
689
|
+
const binaryDir = node_path_1.default.join((0, paths_1.getCacheDirectory)(), 'chisel', CHISEL_VERSION);
|
|
690
|
+
const binaryPath = node_path_1.default.join(binaryDir, 'chisel');
|
|
691
|
+
if (await fs.pathExists(binaryPath)) {
|
|
692
|
+
signal?.throwIfAborted();
|
|
693
|
+
return binaryPath;
|
|
694
|
+
}
|
|
695
|
+
const url = `https://github.com/jpillora/chisel/releases/download/v${CHISEL_VERSION}/${assetName}`;
|
|
696
|
+
log_1.default.log(`Downloading the tunnel client (chisel ${CHISEL_VERSION})...`);
|
|
697
|
+
signal?.throwIfAborted();
|
|
698
|
+
const response = await (0, fetch_1.default)(url, { signal, timeout: 60_000 });
|
|
699
|
+
if (!response.ok) {
|
|
700
|
+
throw new Error(`Failed to download ${url}: ${response.status} ${response.statusText}`);
|
|
701
|
+
}
|
|
702
|
+
const archive = Buffer.from(await response.arrayBuffer());
|
|
703
|
+
signal?.throwIfAborted();
|
|
704
|
+
const actualSha256 = (0, node_crypto_1.createHash)('sha256').update(archive).digest('hex');
|
|
705
|
+
if (actualSha256 !== expectedSha256) {
|
|
706
|
+
throw new Error(`Checksum mismatch for ${assetName}: expected ${expectedSha256}, got ${actualSha256}. ` +
|
|
707
|
+
'The download may be corrupted or tampered with; the egress client was not started.');
|
|
708
|
+
}
|
|
709
|
+
await fs.ensureDir(binaryDir);
|
|
710
|
+
const temporaryPath = `${binaryPath}.${process.pid}.tmp`;
|
|
711
|
+
await fs.writeFile(temporaryPath, node_zlib_1.default.gunzipSync(archive), { mode: 0o755 });
|
|
712
|
+
await fs.move(temporaryPath, binaryPath, { overwrite: true });
|
|
713
|
+
return binaryPath;
|
|
714
|
+
}
|
|
715
|
+
function buildChiselClientArgs({ url, fingerprint, port, localPort = port, forwardPorts = [], }) {
|
|
716
|
+
const remote = `R:${exports.LOCAL_EGRESS_PROXY_HOST}:${port}:${exports.LOCAL_EGRESS_PROXY_HOST}:${localPort}`;
|
|
717
|
+
const forwards = forwardPorts.map(forwardPort => `R:${exports.LOCAL_EGRESS_PROXY_HOST}:${forwardPort}:${exports.LOCAL_EGRESS_PROXY_HOST}:${forwardPort}`);
|
|
718
|
+
return [
|
|
719
|
+
'client',
|
|
720
|
+
'--fingerprint',
|
|
721
|
+
fingerprint,
|
|
722
|
+
'--keepalive',
|
|
723
|
+
'25s',
|
|
724
|
+
'--max-retry-count',
|
|
725
|
+
'-1',
|
|
726
|
+
url,
|
|
727
|
+
remote,
|
|
728
|
+
...forwards,
|
|
729
|
+
];
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* The device host refuses a reverse remote it does not permit, or one whose
|
|
733
|
+
* port is already in use there. chisel then drops the whole connection and
|
|
734
|
+
* retries, so proxied requests stay unavailable until the entry is removed.
|
|
735
|
+
*/
|
|
736
|
+
function isChiselRemoteRejectionLine(line) {
|
|
737
|
+
return /access to '[^']*' denied|address already in use|bind:/i.test(line);
|
|
738
|
+
}
|
|
739
|
+
function classifyChiselClientLogLine(line) {
|
|
740
|
+
if (line.includes('Connected (Latency')) {
|
|
741
|
+
return 'connected';
|
|
742
|
+
}
|
|
743
|
+
if (/Disconnected|Connection error|Retrying in|Give up/.test(line)) {
|
|
744
|
+
return 'disconnected';
|
|
745
|
+
}
|
|
746
|
+
return 'other';
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Run the egress client until `signal` aborts. Rejects if the tunnel client exits
|
|
750
|
+
* on its own, which means proxied HTTP(S) requests have lost their tunnel.
|
|
751
|
+
*/
|
|
752
|
+
async function runLocalEgressAsync({ url, token, fingerprint, port, allow = [], localPort = 0, signal, onConnected, onDisconnected, }) {
|
|
753
|
+
let proxy;
|
|
754
|
+
let child;
|
|
755
|
+
let killTimer;
|
|
756
|
+
let proxyClosing;
|
|
757
|
+
const readers = [];
|
|
758
|
+
const stop = () => {
|
|
759
|
+
if (proxy) {
|
|
760
|
+
proxyClosing ??= proxy.closeAsync();
|
|
761
|
+
}
|
|
762
|
+
if (child && child.exitCode === null && child.signalCode === null && !killTimer) {
|
|
763
|
+
child.kill('SIGTERM');
|
|
764
|
+
killTimer = setTimeout(() => {
|
|
765
|
+
if (child && child.exitCode === null && child.signalCode === null) {
|
|
766
|
+
child.kill('SIGKILL');
|
|
767
|
+
}
|
|
768
|
+
}, 5_000);
|
|
769
|
+
killTimer.unref();
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
773
|
+
try {
|
|
774
|
+
signal.throwIfAborted();
|
|
775
|
+
const chiselPath = await ensureChiselBinaryAsync({ signal });
|
|
776
|
+
signal.throwIfAborted();
|
|
777
|
+
const reportedAllowed = new Set();
|
|
778
|
+
const resolveAllowedTarget = createEgressTargetResolver({
|
|
779
|
+
allow,
|
|
780
|
+
onAllowed: destination => {
|
|
781
|
+
if (reportedAllowed.has(destination)) {
|
|
782
|
+
log_1.default.debug(`[egress] ${destination} allowed by --egress-allow`);
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
reportedAllowed.add(destination);
|
|
786
|
+
log_1.default.log(`The simulator reached ${destination} on this machine's network.`);
|
|
787
|
+
},
|
|
788
|
+
});
|
|
789
|
+
proxy = await startLocalEgressProxyServerAsync({
|
|
790
|
+
port: localPort,
|
|
791
|
+
resolveTargetAsync: async (hostname, targetPort) => await resolveAllowedTarget(hostname, targetPort),
|
|
792
|
+
});
|
|
793
|
+
signal.throwIfAborted();
|
|
794
|
+
log_1.default.debug(`[egress] proxy listening on ${exports.LOCAL_EGRESS_PROXY_HOST}:${proxy.port}`);
|
|
795
|
+
const forwards = (0, utils_1.getLoopbackForwardPlan)(allow, port);
|
|
796
|
+
for (const forwardPort of forwards.ports) {
|
|
797
|
+
log_1.default.debug(`[egress] forwarding ${exports.LOCAL_EGRESS_PROXY_HOST}:${forwardPort} on the device host to this machine`);
|
|
798
|
+
}
|
|
799
|
+
const chisel = (0, spawn_async_1.default)(chiselPath, buildChiselClientArgs({
|
|
800
|
+
url,
|
|
801
|
+
fingerprint,
|
|
802
|
+
port,
|
|
803
|
+
localPort: proxy.port,
|
|
804
|
+
forwardPorts: forwards.ports,
|
|
805
|
+
}), {
|
|
806
|
+
// Stream diagnostics without retaining the entire session's logs in spawnAsync.
|
|
807
|
+
ignoreStdio: true,
|
|
808
|
+
env: { ...process.env, AUTH: `${exports.LOCAL_EGRESS_USERNAME}:${token}` },
|
|
809
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
810
|
+
});
|
|
811
|
+
child = chisel.child;
|
|
812
|
+
let connected = false;
|
|
813
|
+
const handleLine = (line) => {
|
|
814
|
+
log_1.default.debug(`[egress] ${line}`);
|
|
815
|
+
if (isChiselRemoteRejectionLine(line)) {
|
|
816
|
+
log_1.default.warn(`The device host rejected a forwarded loopback port, so the tunnel cannot connect: ${line}\n` +
|
|
817
|
+
'Remove the --egress-allow localhost/127.0.0.1 entry for that port, or check that the ' +
|
|
818
|
+
'session runs a worker that permits loopback port forwarding.');
|
|
819
|
+
}
|
|
820
|
+
switch (classifyChiselClientLogLine(line)) {
|
|
821
|
+
case 'connected':
|
|
822
|
+
connected = true;
|
|
823
|
+
onConnected?.();
|
|
824
|
+
break;
|
|
825
|
+
case 'disconnected':
|
|
826
|
+
if (connected) {
|
|
827
|
+
connected = false;
|
|
828
|
+
onDisconnected?.(line);
|
|
829
|
+
}
|
|
830
|
+
break;
|
|
831
|
+
case 'other':
|
|
832
|
+
break;
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
836
|
+
if (stream) {
|
|
837
|
+
readers.push(node_readline_1.default.createInterface({ input: stream }).on('line', handleLine));
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if (signal.aborted) {
|
|
841
|
+
stop();
|
|
842
|
+
}
|
|
843
|
+
await chisel;
|
|
844
|
+
if (!signal.aborted) {
|
|
845
|
+
throw new Error('The egress tunnel client exited unexpectedly.');
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
catch (err) {
|
|
849
|
+
if (!signal.aborted) {
|
|
850
|
+
throw new Error(`The egress tunnel client stopped: ${err instanceof Error ? err.message : String(err)}. ` +
|
|
851
|
+
'Proxied HTTP(S) requests are unavailable until the tunnel reconnects.');
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
finally {
|
|
855
|
+
signal.removeEventListener('abort', stop);
|
|
856
|
+
stop();
|
|
857
|
+
if (killTimer) {
|
|
858
|
+
clearTimeout(killTimer);
|
|
859
|
+
}
|
|
860
|
+
for (const reader of readers) {
|
|
861
|
+
reader.close();
|
|
862
|
+
}
|
|
863
|
+
await proxyClosing;
|
|
864
|
+
}
|
|
865
|
+
}
|