@testsprite/testsprite-cli 0.13.0 → 0.15.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 +54 -49
- package/dist/commands/ci.d.ts +66 -17
- package/dist/commands/ci.js +466 -104
- package/dist/commands/doctor.d.ts +3 -0
- package/dist/commands/doctor.js +62 -20
- package/dist/commands/init.js +17 -3
- package/dist/commands/project-env.d.ts +11 -1
- package/dist/commands/project-env.js +399 -61
- package/dist/commands/project-sign-in.d.ts +60 -0
- package/dist/commands/project-sign-in.js +289 -0
- package/dist/commands/project.d.ts +9 -0
- package/dist/commands/project.js +82 -28
- package/dist/commands/schedule.d.ts +12 -0
- package/dist/commands/schedule.js +175 -5
- package/dist/commands/test.d.ts +126 -30
- package/dist/commands/test.js +1928 -447
- package/dist/commands/testlist.d.ts +10 -5
- package/dist/commands/testlist.js +170 -30
- package/dist/commands/tunnel.js +11 -5
- package/dist/index.js +17 -38
- package/dist/lib/agent-targets.d.ts +8 -3
- package/dist/lib/agent-targets.js +15 -4
- package/dist/lib/ci-run.d.ts +11 -0
- package/dist/lib/ci-run.js +34 -0
- package/dist/lib/client-factory.d.ts +35 -1
- package/dist/lib/client-factory.js +21 -10
- package/dist/lib/config.d.ts +1 -0
- package/dist/lib/config.js +1 -1
- package/dist/lib/credentials.d.ts +0 -1
- package/dist/lib/credentials.js +51 -14
- package/dist/lib/dry-run/samples.js +95 -1
- package/dist/lib/environment-tunnel.d.ts +109 -0
- package/dist/lib/environment-tunnel.js +465 -0
- package/dist/lib/errors.js +12 -1
- package/dist/lib/first-suite-hint.d.ts +55 -0
- package/dist/lib/first-suite-hint.js +101 -0
- package/dist/lib/gh-output.d.ts +62 -4
- package/dist/lib/gh-output.js +152 -7
- package/dist/lib/github-context.d.ts +21 -0
- package/dist/lib/github-context.js +153 -0
- package/dist/lib/http.d.ts +12 -1
- package/dist/lib/http.js +9 -1
- package/dist/lib/junit-report.d.ts +11 -7
- package/dist/lib/junit-report.js +13 -7
- package/dist/lib/local-target.d.ts +13 -3
- package/dist/lib/local-target.js +47 -12
- package/dist/lib/output.js +15 -1
- package/dist/lib/plan-poll.js +3 -4
- package/dist/lib/plans.types.d.ts +1 -1
- package/dist/lib/redact.d.ts +38 -0
- package/dist/lib/redact.js +140 -0
- package/dist/lib/render-error.d.ts +19 -5
- package/dist/lib/render-error.js +31 -0
- package/dist/lib/response-schemas.d.ts +5 -1
- package/dist/lib/response-schemas.js +54 -0
- package/dist/lib/runs.types.d.ts +115 -1
- package/dist/lib/target-url.js +5 -5
- package/dist/lib/telemetry.d.ts +31 -8
- package/dist/lib/telemetry.js +55 -7
- package/dist/lib/testlist.types.d.ts +1 -0
- package/dist/lib/ticker.d.ts +9 -0
- package/dist/lib/ticker.js +18 -0
- package/dist/lib/tunnel-session.d.ts +3 -4
- package/dist/lib/tunnel-session.js +3 -4
- package/dist/lib/v3-advisory.js +0 -1
- package/dist/vendor/tunnel-client/client.d.ts +15 -8
- package/dist/vendor/tunnel-client/client.js +477 -407
- package/dist/vendor/tunnel-client/config.d.ts +5 -5
- package/dist/vendor/tunnel-client/config.js +5 -5
- package/dist/vendor/tunnel-client/index.d.ts +4 -4
- package/dist/vendor/tunnel-client/index.js +4 -4
- package/dist/vendor/tunnel-client/types.d.ts +19 -34
- package/dist/vendor/tunnel-client/types.js +1 -0
- package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
- package/dist/vendor/tunnel-client/ws-compat.js +70 -12
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/schemas/plan.schema.json +2 -2
- package/skills/testsprite-ci.skill.md +154 -0
- package/skills/testsprite-onboard.skill.md +4 -4
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
// VENDOR DELTA: terminal 1008 auth closes distinguish revocation and
|
|
2
|
-
// post-Ack takeover from initial authentication failure. See ./VENDOR.md #16.
|
|
3
1
|
import { EventEmitter, once } from "node:events";
|
|
4
2
|
import dns from "node:dns";
|
|
5
3
|
import { readFileSync } from "node:fs";
|
|
@@ -7,22 +5,12 @@ import net from "node:net";
|
|
|
7
5
|
import { performance } from "node:perf_hooks";
|
|
8
6
|
import tls from "node:tls";
|
|
9
7
|
import { domainToASCII } from "node:url";
|
|
10
|
-
// VENDOR DELTA: `ws` -> undici-backed facade. See ./ws-compat.ts.
|
|
11
8
|
import WebSocket from "./ws-compat.js";
|
|
12
|
-
// VENDOR DELTA: `lodash` -> three local predicates. See ./lodash-lite.ts.
|
|
13
9
|
import { isNumber, isPlainObject, isString } from "./lodash-lite.js";
|
|
14
10
|
import { encodeFrame, readTypedFrame } from "./protocol.js";
|
|
15
|
-
|
|
16
|
-
// defaults — `controlUrl`/`tunnelAddr` are required and come from the mint
|
|
17
|
-
// response. See ./config.ts.
|
|
18
|
-
import { DEFAULT_ALLOW_PRIVATE_NETWORK_TARGET, DEFAULT_AUTH_TIMEOUT_MS, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS, DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS, DEFAULT_DATA_PLANE_SETTLE_MS, DEFAULT_HEARTBEAT_MS, DEFAULT_LOG_LEVEL, DEFAULT_RECONNECT_MS, DEFAULT_TARGET_CONNECT_TIMEOUT_MS, } from "./config.js";
|
|
11
|
+
import { DEFAULT_ALLOW_PRIVATE_NETWORK_TARGET, DEFAULT_AUTH_TIMEOUT_MS, DEFAULT_CLIENT_UNKNOWN_RETRY_DEADLINE_MS, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS, DEFAULT_DATA_PLANE_SETTLE_MS, DEFAULT_HEARTBEAT_MS, DEFAULT_LOG_LEVEL, DEFAULT_RECONNECT_MS, DEFAULT_TARGET_CONNECT_TIMEOUT_MS, DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS, } from "./config.js";
|
|
19
12
|
import { ErrCode, } from "./types.js";
|
|
20
13
|
import { Client as createYamuxClientSession, YamuxStreamResetError, } from "@llmcode/yamux-ts";
|
|
21
|
-
// VENDOR DELTA: `Record<string, number>` -> `Record<LogLevel, number>`, and
|
|
22
|
-
// the two `keyof typeof LEVEL_ORDER` parameters below become `LogLevel`. This
|
|
23
|
-
// CLI compiles with `noUncheckedIndexedAccess`, under which indexing a string
|
|
24
|
-
// index signature yields `number | undefined`; a mapped type over the four
|
|
25
|
-
// known levels does not. Type-only — no behaviour change. Worth upstreaming.
|
|
26
14
|
const LEVEL_ORDER = {
|
|
27
15
|
debug: 10,
|
|
28
16
|
info: 20,
|
|
@@ -31,107 +19,94 @@ const LEVEL_ORDER = {
|
|
|
31
19
|
};
|
|
32
20
|
const STREAM_CLOSE_TIMEOUT_MS = 1_500;
|
|
33
21
|
const CONTROL_AUTHENTICATION_FAILED = Symbol("control-authentication-failed");
|
|
22
|
+
const CONTROL_CLIENT_UNKNOWN = Symbol("control-client-unknown");
|
|
23
|
+
const CONTROL_CLIENT_UNKNOWN_EXPIRED = Symbol("control-client-unknown-expired");
|
|
34
24
|
export class TunnelClient extends EventEmitter {
|
|
35
|
-
options;
|
|
36
25
|
#transportMode;
|
|
26
|
+
options;
|
|
37
27
|
tunnelAddress;
|
|
38
28
|
running = false;
|
|
39
29
|
controlConnected = false;
|
|
40
30
|
controlWs;
|
|
41
31
|
controlLoopTask;
|
|
42
|
-
// VENDOR DELTA: monotonically scopes authentication readiness to one
|
|
43
|
-
// control socket. A reconnect gets a new generation, so an Ack emitted by
|
|
44
|
-
// an older socket cannot satisfy a later start() wait. See VENDOR.md #14.
|
|
45
32
|
controlConnectionGeneration = 0;
|
|
46
33
|
allowTunnelReconnect = true;
|
|
47
34
|
dataPlaneTerminalErrorReported = false;
|
|
35
|
+
clientUnknownEpisodeStartedAt;
|
|
36
|
+
clientUnknownDeadline;
|
|
48
37
|
tunnelRuntimes = new Map();
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
reconnectDelayController = new AbortController();
|
|
52
|
-
// VENDOR DELTA: every socket this client dials on behalf of an inbound proxy
|
|
53
|
-
// stream (connectOnce). Tearing down a tunnel data session (runtime.socket)
|
|
54
|
-
// does NOT reach these independent per-stream sockets, and a browser
|
|
55
|
-
// keep-alive target that holds the connection open and sends nothing parks
|
|
56
|
-
// proxyStreams()'s copyOneWay(target, …) forever, so its finally-cleanup never
|
|
57
|
-
// runs. On teardown such ESTABLISHED sockets stay ref'd and keep the event loop
|
|
58
|
-
// alive for the remote's idle timeout (minutes) — the visible symptom is a
|
|
59
|
-
// --local run whose Ctrl-C / --timeout appears to hang. stop()/CloseTunnel
|
|
60
|
-
// destroy these directly. See VENDOR.md #13.
|
|
38
|
+
lifecycleController = new AbortController();
|
|
39
|
+
targetDialController = new AbortController();
|
|
61
40
|
activeTargetSockets = new Set();
|
|
62
41
|
constructor(options) {
|
|
63
42
|
super();
|
|
64
43
|
if (!options.clientId || !options.secret) {
|
|
65
44
|
throw new Error("clientId and secret are required");
|
|
66
45
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
46
|
+
if (!Number.isInteger(options.tlsHandshakeTimeoutMs ?? DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS)
|
|
47
|
+
|| (options.tlsHandshakeTimeoutMs ?? DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS) < 0) {
|
|
48
|
+
throw new RangeError("tlsHandshakeTimeoutMs must be a non-negative integer");
|
|
49
|
+
}
|
|
50
|
+
if (!Number.isInteger(options.dataPlaneRetryDeadlineMs ?? DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS)
|
|
51
|
+
|| (options.dataPlaneRetryDeadlineMs ?? DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS) < 0) {
|
|
70
52
|
throw new RangeError("dataPlaneRetryDeadlineMs must be a non-negative integer");
|
|
71
53
|
}
|
|
72
|
-
|
|
73
|
-
|
|
54
|
+
if (!Number.isInteger(options.clientUnknownRetryDeadlineMs ?? DEFAULT_CLIENT_UNKNOWN_RETRY_DEADLINE_MS)
|
|
55
|
+
|| (options.clientUnknownRetryDeadlineMs ?? DEFAULT_CLIENT_UNKNOWN_RETRY_DEADLINE_MS) < 0) {
|
|
56
|
+
throw new RangeError("clientUnknownRetryDeadlineMs must be a non-negative integer");
|
|
57
|
+
}
|
|
58
|
+
if (!Number.isInteger(options.dataPlaneSettleMs ?? DEFAULT_DATA_PLANE_SETTLE_MS)
|
|
59
|
+
|| (options.dataPlaneSettleMs ?? DEFAULT_DATA_PLANE_SETTLE_MS) < 0) {
|
|
74
60
|
throw new RangeError("dataPlaneSettleMs must be a non-negative integer");
|
|
75
61
|
}
|
|
76
|
-
|
|
77
|
-
|
|
62
|
+
if (!Number.isInteger(options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS)
|
|
63
|
+
|| (options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS) < 0) {
|
|
78
64
|
throw new RangeError("connectTimeoutMs must be a non-negative integer");
|
|
79
65
|
}
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
66
|
+
const configuredPlaintextAddress = parseTunnelAddr(options.tunnelAddr);
|
|
67
|
+
const configuredTlsAddress = options.tunnelTlsAddr === undefined
|
|
68
|
+
? undefined
|
|
69
|
+
: parseTunnelAddr(options.tunnelTlsAddr);
|
|
70
|
+
if (configuredTlsAddress !== undefined) {
|
|
71
|
+
this.#transportMode = "tls";
|
|
72
|
+
this.tunnelAddress = configuredTlsAddress;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
this.#transportMode = "plaintext";
|
|
76
|
+
this.tunnelAddress = configuredPlaintextAddress;
|
|
83
77
|
}
|
|
84
78
|
let tunnelTlsServername;
|
|
85
|
-
if (
|
|
86
|
-
const
|
|
87
|
-
this.tunnelAddress
|
|
88
|
-
if (net.isIP(tunnelTlsAddress.host) !== 0 && !options.tunnelTlsServername) {
|
|
79
|
+
if (this.transport === "tls") {
|
|
80
|
+
const configuredServername = options.tunnelTlsServername;
|
|
81
|
+
if (net.isIP(this.tunnelAddress.host) !== 0 && !configuredServername) {
|
|
89
82
|
throw new Error("tunnelTlsServername is required when tunnelTlsAddr uses an IP-literal host");
|
|
90
83
|
}
|
|
91
|
-
tunnelTlsServername =
|
|
84
|
+
tunnelTlsServername = configuredServername ?? this.tunnelAddress.host;
|
|
92
85
|
if (tunnelTlsServername.trim().length === 0) {
|
|
93
86
|
throw new Error("tunnelTlsServername must not be empty");
|
|
94
87
|
}
|
|
95
88
|
}
|
|
96
|
-
else {
|
|
97
|
-
this.tunnelAddress = configuredPlaintextAddress;
|
|
98
|
-
}
|
|
99
|
-
this.#transportMode = options.tunnelTlsAddr === undefined ? "plaintext" : "tls";
|
|
100
|
-
const extraTlsCa = options.tunnelTlsCa === undefined
|
|
101
|
-
? []
|
|
102
|
-
: Array.isArray(options.tunnelTlsCa)
|
|
103
|
-
? options.tunnelTlsCa
|
|
104
|
-
: [options.tunnelTlsCa];
|
|
105
89
|
this.options = {
|
|
106
90
|
clientId: options.clientId,
|
|
107
91
|
secret: options.secret,
|
|
108
92
|
controlUrl: options.controlUrl,
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
connectTimeoutMs,
|
|
118
|
-
tlsHandshakeTimeoutMs,
|
|
119
|
-
dataPlaneRetryDeadlineMs: deadlineMs,
|
|
120
|
-
dataPlaneSettleMs: settleMs,
|
|
93
|
+
tunnelTlsServername,
|
|
94
|
+
tunnelTlsCa: normalizeTlsCa(options.tunnelTlsCa),
|
|
95
|
+
tlsHandshakeTimeoutMs: options.tlsHandshakeTimeoutMs ?? DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS,
|
|
96
|
+
connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
|
|
97
|
+
dataPlaneRetryDeadlineMs: options.dataPlaneRetryDeadlineMs ?? DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS,
|
|
98
|
+
clientUnknownRetryDeadlineMs: options.clientUnknownRetryDeadlineMs ?? DEFAULT_CLIENT_UNKNOWN_RETRY_DEADLINE_MS,
|
|
99
|
+
onClientUnknown: options.onClientUnknown,
|
|
100
|
+
dataPlaneSettleMs: options.dataPlaneSettleMs ?? DEFAULT_DATA_PLANE_SETTLE_MS,
|
|
121
101
|
authTimeoutMs: options.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS,
|
|
122
102
|
heartbeatMs: options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS,
|
|
123
103
|
reconnectMs: options.reconnectMs ?? DEFAULT_RECONNECT_MS,
|
|
124
104
|
logLevel: options.logLevel ?? DEFAULT_LOG_LEVEL,
|
|
125
105
|
allowPrivateNetworkTarget: options.allowPrivateNetworkTarget ?? DEFAULT_ALLOW_PRIVATE_NETWORK_TARGET,
|
|
126
106
|
onError: options.onError ?? (() => null),
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
// injects its own so tunnel chatter obeys `--verbose`/`--debug`.
|
|
131
|
-
logSink: options.logSink ??
|
|
132
|
-
((_level, line) => {
|
|
133
|
-
process.stderr.write(`${line}\n`);
|
|
134
|
-
}),
|
|
107
|
+
logSink: options.logSink ?? ((_level, line) => {
|
|
108
|
+
process.stderr.write(`${line}\n`);
|
|
109
|
+
}),
|
|
135
110
|
};
|
|
136
111
|
}
|
|
137
112
|
get transport() {
|
|
@@ -141,19 +116,24 @@ export class TunnelClient extends EventEmitter {
|
|
|
141
116
|
if (this.running) {
|
|
142
117
|
return;
|
|
143
118
|
}
|
|
144
|
-
if (this.
|
|
145
|
-
this.
|
|
119
|
+
if (this.lifecycleController.signal.aborted) {
|
|
120
|
+
this.lifecycleController = new AbortController();
|
|
146
121
|
}
|
|
122
|
+
if (this.targetDialController.signal.aborted) {
|
|
123
|
+
this.targetDialController = new AbortController();
|
|
124
|
+
}
|
|
125
|
+
this.clearClientUnknownEpisode();
|
|
147
126
|
this.running = true;
|
|
148
127
|
this.dataPlaneTerminalErrorReported = false;
|
|
149
128
|
const expectedConnectionGeneration = this.controlConnectionGeneration + 1;
|
|
150
|
-
|
|
151
|
-
await new Promise((resolve, reject) => {
|
|
129
|
+
const readiness = new Promise((resolve, reject) => {
|
|
152
130
|
let settled = false;
|
|
153
131
|
const cleanup = () => {
|
|
154
132
|
clearTimeout(timeout);
|
|
155
133
|
this.off("control-authenticated", onAuthenticated);
|
|
156
134
|
this.off(CONTROL_AUTHENTICATION_FAILED, onAuthenticationFailed);
|
|
135
|
+
this.off(CONTROL_CLIENT_UNKNOWN, onClientUnknown);
|
|
136
|
+
this.off(CONTROL_CLIENT_UNKNOWN_EXPIRED, onClientUnknownExpired);
|
|
157
137
|
};
|
|
158
138
|
const settle = (callback) => {
|
|
159
139
|
if (settled) {
|
|
@@ -164,29 +144,43 @@ export class TunnelClient extends EventEmitter {
|
|
|
164
144
|
callback();
|
|
165
145
|
};
|
|
166
146
|
const onAuthenticated = (connectionGeneration) => {
|
|
167
|
-
if (connectionGeneration
|
|
147
|
+
if (connectionGeneration >= expectedConnectionGeneration) {
|
|
168
148
|
settle(resolve);
|
|
169
149
|
}
|
|
170
150
|
};
|
|
171
151
|
const onAuthenticationFailed = (connectionGeneration, error) => {
|
|
172
|
-
if (connectionGeneration
|
|
152
|
+
if (connectionGeneration >= expectedConnectionGeneration) {
|
|
173
153
|
settle(() => reject(error));
|
|
174
154
|
}
|
|
175
155
|
};
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
};
|
|
179
|
-
this.on("control-authenticated", onAuthenticated);
|
|
180
|
-
this.on(CONTROL_AUTHENTICATION_FAILED, onAuthenticationFailed);
|
|
181
|
-
this.controlLoopTask?.then(onLoopEnd);
|
|
156
|
+
const onClientUnknown = () => clearTimeout(timeout);
|
|
157
|
+
const onClientUnknownExpired = (error) => settle(() => reject(error));
|
|
182
158
|
const timeout = setTimeout(() => {
|
|
183
159
|
settle(() => reject(new Error(`The tunnel server accepted the connection but never acknowledged authentication within ${this.options.authTimeoutMs}ms`)));
|
|
184
160
|
}, this.options.authTimeoutMs);
|
|
161
|
+
this.on("control-authenticated", onAuthenticated);
|
|
162
|
+
this.on(CONTROL_AUTHENTICATION_FAILED, onAuthenticationFailed);
|
|
163
|
+
this.on(CONTROL_CLIENT_UNKNOWN, onClientUnknown);
|
|
164
|
+
this.on(CONTROL_CLIENT_UNKNOWN_EXPIRED, onClientUnknownExpired);
|
|
165
|
+
this.controlLoopTask = this.runControlLoop();
|
|
166
|
+
const onLoopEnd = () => {
|
|
167
|
+
settle(() => reject(new Error("Control loop ended before connecting")));
|
|
168
|
+
};
|
|
169
|
+
this.controlLoopTask.then(onLoopEnd, onLoopEnd);
|
|
185
170
|
});
|
|
171
|
+
await readiness;
|
|
186
172
|
this.log("info", "Tunnel client started");
|
|
187
173
|
}
|
|
188
174
|
async stop() {
|
|
189
|
-
this.
|
|
175
|
+
this.running = false;
|
|
176
|
+
this.clearClientUnknownEpisode();
|
|
177
|
+
this.lifecycleController.abort();
|
|
178
|
+
if (this.controlWs &&
|
|
179
|
+
(this.controlWs.readyState === WebSocket.OPEN ||
|
|
180
|
+
this.controlWs.readyState === WebSocket.CONNECTING)) {
|
|
181
|
+
this.controlWs.close();
|
|
182
|
+
}
|
|
183
|
+
this.stopAllTunnelRuntimes();
|
|
190
184
|
const tunnelTasks = Array.from(this.tunnelRuntimes.values(), (runtime) => runtime.task);
|
|
191
185
|
await Promise.allSettled([this.controlLoopTask, ...tunnelTasks]);
|
|
192
186
|
this.controlWs = undefined;
|
|
@@ -199,26 +193,71 @@ export class TunnelClient extends EventEmitter {
|
|
|
199
193
|
await this.connectControl();
|
|
200
194
|
}
|
|
201
195
|
catch (err) {
|
|
196
|
+
if (!this.running)
|
|
197
|
+
return;
|
|
202
198
|
if (isControlAuthFailureError(err)) {
|
|
203
|
-
const message = err.
|
|
199
|
+
const message = err.reason.trim().toUpperCase() === "CLIENT_REVOKED"
|
|
204
200
|
? "tunnel credential revoked"
|
|
205
|
-
: err.
|
|
201
|
+
: err.authenticated
|
|
206
202
|
? "tunnel connection superseded or credential revoked"
|
|
207
203
|
: `Control authentication failed, stop reconnecting: ${toErrorMessage(err)}`;
|
|
208
204
|
this.reportError(ErrCode.AuthFailed, message, "error");
|
|
205
|
+
this.clearClientUnknownEpisode();
|
|
209
206
|
this.running = false;
|
|
210
|
-
this.
|
|
207
|
+
this.lifecycleController.abort();
|
|
211
208
|
this.controlConnected = false;
|
|
212
209
|
this.stopAllTunnelRuntimes();
|
|
213
210
|
return;
|
|
214
211
|
}
|
|
215
|
-
|
|
212
|
+
if (err instanceof ControlClientUnknownCloseError) {
|
|
213
|
+
this.openClientUnknownEpisode();
|
|
214
|
+
if (this.options.onClientUnknown) {
|
|
215
|
+
try {
|
|
216
|
+
await abortable(Promise.resolve().then(() => this.options.onClientUnknown()), this.lifecycleController.signal);
|
|
217
|
+
}
|
|
218
|
+
catch (hookError) {
|
|
219
|
+
if (this.running)
|
|
220
|
+
this.log("warn", `Client recovery hook failed: ${redactSecret(toErrorMessage(hookError), this.options.secret)}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
this.reportError(ErrCode.ControlDisconnected, `Control disconnected: ${toErrorMessage(err)}`);
|
|
226
|
+
}
|
|
216
227
|
}
|
|
217
228
|
if (this.running) {
|
|
218
|
-
await delay(this.options.reconnectMs, this.
|
|
229
|
+
await delay(this.options.reconnectMs, this.lifecycleController.signal);
|
|
219
230
|
}
|
|
220
231
|
}
|
|
221
232
|
}
|
|
233
|
+
openClientUnknownEpisode() {
|
|
234
|
+
this.clientUnknownEpisodeStartedAt ??= performance.now();
|
|
235
|
+
if (this.options.clientUnknownRetryDeadlineMs === 0 || this.clientUnknownDeadline)
|
|
236
|
+
return;
|
|
237
|
+
const remainingMs = Math.max(0, this.options.clientUnknownRetryDeadlineMs - (performance.now() - this.clientUnknownEpisodeStartedAt));
|
|
238
|
+
this.clientUnknownDeadline = setTimeout(() => {
|
|
239
|
+
this.clientUnknownDeadline = undefined;
|
|
240
|
+
if (!this.running || this.clientUnknownEpisodeStartedAt === undefined)
|
|
241
|
+
return;
|
|
242
|
+
const error = new ClientUnknownError(this.options.clientUnknownRetryDeadlineMs);
|
|
243
|
+
this.emit(CONTROL_CLIENT_UNKNOWN_EXPIRED, error);
|
|
244
|
+
try {
|
|
245
|
+
this.options.onError(error);
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
this.log("warn", "onError callback threw; continuing client lifecycle");
|
|
249
|
+
}
|
|
250
|
+
this.log("error", error.message);
|
|
251
|
+
void this.stop();
|
|
252
|
+
}, remainingMs);
|
|
253
|
+
this.clientUnknownDeadline.unref();
|
|
254
|
+
}
|
|
255
|
+
clearClientUnknownEpisode() {
|
|
256
|
+
if (this.clientUnknownDeadline)
|
|
257
|
+
clearTimeout(this.clientUnknownDeadline);
|
|
258
|
+
this.clientUnknownDeadline = undefined;
|
|
259
|
+
this.clientUnknownEpisodeStartedAt = undefined;
|
|
260
|
+
}
|
|
222
261
|
async runTunnelLoop(tunnelConnectionId, runtime) {
|
|
223
262
|
try {
|
|
224
263
|
while (this.running) {
|
|
@@ -234,7 +273,7 @@ export class TunnelClient extends EventEmitter {
|
|
|
234
273
|
}
|
|
235
274
|
const errorMessage = toErrorMessage(err);
|
|
236
275
|
const safeErrorMessage = redactSecret(errorMessage, this.options.secret);
|
|
237
|
-
this.
|
|
276
|
+
this.openDataPlaneFailureEpisode(runtime, safeErrorMessage);
|
|
238
277
|
this.reportError(ErrCode.TunnelDisconnected, `Tunnel ${tunnelConnectionId} disconnected: ${safeErrorMessage}`);
|
|
239
278
|
}
|
|
240
279
|
if (!this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
|
|
@@ -242,13 +281,13 @@ export class TunnelClient extends EventEmitter {
|
|
|
242
281
|
return;
|
|
243
282
|
}
|
|
244
283
|
if (this.running) {
|
|
245
|
-
await delay(this.options.reconnectMs, this.
|
|
284
|
+
await delay(this.options.reconnectMs, this.lifecycleController.signal);
|
|
246
285
|
}
|
|
247
286
|
}
|
|
248
287
|
}
|
|
249
288
|
finally {
|
|
250
|
-
this.clearDataPlaneAttemptTimers(runtime);
|
|
251
289
|
this.clearDataPlaneFailureEpisode(runtime);
|
|
290
|
+
this.clearAttemptTimers(runtime);
|
|
252
291
|
runtime.socket = undefined;
|
|
253
292
|
runtime.session = undefined;
|
|
254
293
|
this.tunnelRuntimes.delete(tunnelConnectionId);
|
|
@@ -264,13 +303,12 @@ export class TunnelClient extends EventEmitter {
|
|
|
264
303
|
let heartbeatTimer;
|
|
265
304
|
let opened = false;
|
|
266
305
|
let authenticationSettled = false;
|
|
267
|
-
let
|
|
306
|
+
let authenticated = false;
|
|
268
307
|
const failAuthentication = (error) => {
|
|
269
|
-
if (authenticationSettled) {
|
|
270
|
-
|
|
308
|
+
if (!authenticationSettled) {
|
|
309
|
+
authenticationSettled = true;
|
|
310
|
+
this.emit(CONTROL_AUTHENTICATION_FAILED, connectionGeneration, error);
|
|
271
311
|
}
|
|
272
|
-
authenticationSettled = true;
|
|
273
|
-
this.emit(CONTROL_AUTHENTICATION_FAILED, connectionGeneration, error);
|
|
274
312
|
};
|
|
275
313
|
const cleanup = () => {
|
|
276
314
|
if (heartbeatTimer) {
|
|
@@ -315,9 +353,10 @@ export class TunnelClient extends EventEmitter {
|
|
|
315
353
|
return;
|
|
316
354
|
}
|
|
317
355
|
if (message.type === "Ack") {
|
|
318
|
-
|
|
356
|
+
authenticated = true;
|
|
319
357
|
if (!authenticationSettled) {
|
|
320
358
|
authenticationSettled = true;
|
|
359
|
+
this.clearClientUnknownEpisode();
|
|
321
360
|
this.emit("control-authenticated", connectionGeneration);
|
|
322
361
|
}
|
|
323
362
|
return;
|
|
@@ -325,6 +364,9 @@ export class TunnelClient extends EventEmitter {
|
|
|
325
364
|
if (message.type === "RequestTunnel") {
|
|
326
365
|
this.log("debug", `RequestTunnel received: ${message.payload.tunnel_connection_id}`);
|
|
327
366
|
this.allowTunnelReconnect = true;
|
|
367
|
+
if (this.targetDialController.signal.aborted) {
|
|
368
|
+
this.targetDialController = new AbortController();
|
|
369
|
+
}
|
|
328
370
|
this.ensureTunnelRuntime(message.payload.tunnel_connection_id);
|
|
329
371
|
return;
|
|
330
372
|
}
|
|
@@ -336,7 +378,9 @@ export class TunnelClient extends EventEmitter {
|
|
|
336
378
|
});
|
|
337
379
|
ws.on("error", (err) => {
|
|
338
380
|
cleanup();
|
|
339
|
-
|
|
381
|
+
if (this.clientUnknownEpisodeStartedAt === undefined) {
|
|
382
|
+
failAuthentication(new Error(`Control websocket errored before authentication was acknowledged: ${toErrorMessage(err)}`));
|
|
383
|
+
}
|
|
340
384
|
if (!opened) {
|
|
341
385
|
this.controlConnected = false;
|
|
342
386
|
this.stopAllTunnelRuntimes();
|
|
@@ -351,10 +395,17 @@ export class TunnelClient extends EventEmitter {
|
|
|
351
395
|
this.stopAllTunnelRuntimes();
|
|
352
396
|
this.emit("control-disconnected");
|
|
353
397
|
const reason = reasonBuffer.toString("utf8");
|
|
354
|
-
|
|
398
|
+
if (code === 1008 && reason.trim().toUpperCase() === "CLIENT_UNKNOWN") {
|
|
399
|
+
this.emit(CONTROL_CLIENT_UNKNOWN);
|
|
400
|
+
reject(new ControlClientUnknownCloseError());
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (this.clientUnknownEpisodeStartedAt === undefined || isAuthFailureClose(code, reason)) {
|
|
404
|
+
failAuthentication(new Error(`Control websocket closed before authentication was acknowledged (code=${code}, reason=${reason || "<empty>"})`));
|
|
405
|
+
}
|
|
355
406
|
this.log("warn", `Control websocket closed (code=${code}, reason=${reason || "<empty>"})`);
|
|
356
407
|
if (isAuthFailureClose(code, reason)) {
|
|
357
|
-
reject(new ControlAuthFailureError(code, reason,
|
|
408
|
+
reject(new ControlAuthFailureError(code, reason, authenticated));
|
|
358
409
|
return;
|
|
359
410
|
}
|
|
360
411
|
resolve();
|
|
@@ -417,7 +468,6 @@ export class TunnelClient extends EventEmitter {
|
|
|
417
468
|
}
|
|
418
469
|
const runtime = {
|
|
419
470
|
stopRetryOnDisconnect: false,
|
|
420
|
-
sessionEstablished: false,
|
|
421
471
|
task: Promise.resolve(),
|
|
422
472
|
};
|
|
423
473
|
runtime.task = this.runTunnelLoop(tunnelConnectionId, runtime);
|
|
@@ -426,232 +476,224 @@ export class TunnelClient extends EventEmitter {
|
|
|
426
476
|
}
|
|
427
477
|
connectTunnel(tunnelConnectionId, runtime) {
|
|
428
478
|
return new Promise((resolve, reject) => {
|
|
429
|
-
this.
|
|
430
|
-
runtime.sessionEstablished = false;
|
|
431
|
-
const transport = this.#transportMode;
|
|
432
|
-
const socket = transport === "tls"
|
|
433
|
-
? tls.connect({
|
|
434
|
-
host: this.tunnelAddress.host,
|
|
435
|
-
port: this.tunnelAddress.port,
|
|
436
|
-
servername: this.options.tunnelTlsServername,
|
|
437
|
-
minVersion: "TLSv1.2",
|
|
438
|
-
ca: tlsCaOption(this.options.tunnelTlsCa),
|
|
439
|
-
})
|
|
440
|
-
: net.connect({
|
|
441
|
-
host: this.tunnelAddress.host,
|
|
442
|
-
port: this.tunnelAddress.port,
|
|
443
|
-
});
|
|
479
|
+
const socket = this.connectDataPlane();
|
|
444
480
|
runtime.socket = socket;
|
|
445
|
-
let transportConnected = false;
|
|
446
481
|
let helloWritten = false;
|
|
482
|
+
let established = false;
|
|
447
483
|
let settled = false;
|
|
484
|
+
let session;
|
|
485
|
+
const clearDialTimeout = () => {
|
|
486
|
+
if (runtime.dialTimeout) {
|
|
487
|
+
clearTimeout(runtime.dialTimeout);
|
|
488
|
+
runtime.dialTimeout = undefined;
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
const clearSettleTimeout = () => {
|
|
492
|
+
if (runtime.settleTimeout) {
|
|
493
|
+
clearTimeout(runtime.settleTimeout);
|
|
494
|
+
runtime.settleTimeout = undefined;
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
const cleanup = () => {
|
|
498
|
+
clearDialTimeout();
|
|
499
|
+
clearSettleTimeout();
|
|
500
|
+
if (runtime.socket === socket)
|
|
501
|
+
runtime.socket = undefined;
|
|
502
|
+
if (runtime.session === session)
|
|
503
|
+
runtime.session = undefined;
|
|
504
|
+
};
|
|
448
505
|
const settle = (next) => {
|
|
449
506
|
if (settled) {
|
|
450
507
|
return;
|
|
451
508
|
}
|
|
452
509
|
settled = true;
|
|
510
|
+
cleanup();
|
|
453
511
|
next();
|
|
454
512
|
};
|
|
455
|
-
const
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
513
|
+
const markEstablished = () => {
|
|
514
|
+
if (established
|
|
515
|
+
|| settled
|
|
516
|
+
|| !this.running
|
|
517
|
+
|| !this.allowTunnelReconnect
|
|
518
|
+
|| runtime.stopRetryOnDisconnect) {
|
|
460
519
|
return;
|
|
461
520
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
}
|
|
466
|
-
reject(error);
|
|
467
|
-
});
|
|
521
|
+
established = true;
|
|
522
|
+
clearSettleTimeout();
|
|
523
|
+
this.clearDataPlaneFailureEpisode(runtime);
|
|
468
524
|
};
|
|
469
525
|
socket.once("error", (err) => {
|
|
470
|
-
if (!
|
|
471
|
-
|
|
526
|
+
if (!established) {
|
|
527
|
+
settle(() => reject(err));
|
|
528
|
+
return;
|
|
472
529
|
}
|
|
530
|
+
this.log("warn", `Tunnel ${this.transport} error on established session ${tunnelConnectionId}: ${redactSecret(toErrorMessage(err), this.options.secret)}`);
|
|
473
531
|
});
|
|
474
532
|
const finalizeClose = () => {
|
|
475
|
-
this.clearDataPlaneAttemptTimers(runtime);
|
|
476
|
-
if (runtime.socket === socket) {
|
|
477
|
-
runtime.socket = undefined;
|
|
478
|
-
runtime.session = undefined;
|
|
479
|
-
}
|
|
480
533
|
settle(() => {
|
|
481
534
|
this.emit("tunnel-disconnected", tunnelConnectionId);
|
|
482
535
|
this.log("warn", `Tunnel tcp closed: ${tunnelConnectionId}`);
|
|
483
|
-
if (
|
|
536
|
+
if (!this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
|
|
484
537
|
resolve();
|
|
485
538
|
return;
|
|
486
539
|
}
|
|
487
|
-
if (!
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
: `Tunnel ${transport} connection closed before TunnelHello was sent`));
|
|
540
|
+
if (!helloWritten) {
|
|
541
|
+
reject(new Error(`Tunnel ${this.transport} connection closed before TunnelHello was sent`));
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
if (established) {
|
|
545
|
+
resolve();
|
|
494
546
|
return;
|
|
495
547
|
}
|
|
496
|
-
|
|
548
|
+
reject(new Error(`Tunnel ${this.transport} connection closed before the session was established`));
|
|
497
549
|
});
|
|
498
550
|
};
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
runtime.connectTimer = undefined;
|
|
503
|
-
}
|
|
504
|
-
transportConnected = true;
|
|
505
|
-
if (interrupted()) {
|
|
551
|
+
const onReady = () => {
|
|
552
|
+
clearDialTimeout();
|
|
553
|
+
if (!this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
|
|
506
554
|
socket.destroy();
|
|
507
555
|
settle(resolve);
|
|
508
556
|
return;
|
|
509
557
|
}
|
|
510
|
-
this.log("info", `Tunnel ${transport} connected: ${tunnelConnectionId}`);
|
|
558
|
+
this.log("info", `Tunnel ${this.transport} connected: ${tunnelConnectionId}`);
|
|
511
559
|
const hello = {
|
|
512
560
|
client_id: this.options.clientId,
|
|
513
561
|
secret: this.options.secret,
|
|
514
562
|
tunnel_connection_id: tunnelConnectionId,
|
|
515
563
|
};
|
|
516
564
|
try {
|
|
517
|
-
socket.write(encodeFrame(hello), error => {
|
|
565
|
+
socket.write(encodeFrame(hello), (error) => {
|
|
518
566
|
if (error) {
|
|
519
|
-
|
|
567
|
+
settle(() => reject(error));
|
|
568
|
+
socket.destroy();
|
|
520
569
|
return;
|
|
521
570
|
}
|
|
522
|
-
if (settled ||
|
|
571
|
+
if (settled || socket.destroyed) {
|
|
523
572
|
return;
|
|
524
573
|
}
|
|
525
574
|
helloWritten = true;
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
575
|
+
runtime.settleTimeout = setTimeout(markEstablished, this.options.dataPlaneSettleMs);
|
|
576
|
+
runtime.settleTimeout.unref();
|
|
577
|
+
session = createYamuxClientSession(socket);
|
|
578
|
+
runtime.session = session;
|
|
579
|
+
session.on("stream", (stream) => {
|
|
580
|
+
markEstablished();
|
|
581
|
+
void this.handleIncomingStream(stream);
|
|
582
|
+
});
|
|
583
|
+
session.on("error", (err) => {
|
|
584
|
+
if (isBenignCloseError(err)) {
|
|
585
|
+
this.log("debug", `Yamux benign close (${tunnelConnectionId}): ${toErrorMessage(err)}`);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
this.log("warn", `Yamux error (${tunnelConnectionId}): ${toErrorMessage(err)}`);
|
|
589
|
+
if (!socket.destroyed) {
|
|
590
|
+
socket.destroy(err);
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
session.on("close", () => {
|
|
594
|
+
this.log("debug", `Yamux session closed: ${tunnelConnectionId}`);
|
|
595
|
+
});
|
|
533
596
|
this.emit("tunnel-connected", tunnelConnectionId);
|
|
534
597
|
});
|
|
535
|
-
const session = createYamuxClientSession(socket);
|
|
536
|
-
runtime.session = session;
|
|
537
|
-
session.on("stream", (stream) => {
|
|
538
|
-
this.markDataPlaneEstablished(runtime);
|
|
539
|
-
void this.handleIncomingStream(stream);
|
|
540
|
-
});
|
|
541
|
-
session.on("error", (err) => {
|
|
542
|
-
if (isBenignCloseError(err)) {
|
|
543
|
-
this.log("debug", `Yamux benign close (${tunnelConnectionId}): ${toErrorMessage(err)}`);
|
|
544
|
-
return;
|
|
545
|
-
}
|
|
546
|
-
this.log("warn", `Yamux error (${tunnelConnectionId}): ${toErrorMessage(err)}`);
|
|
547
|
-
if (!socket.destroyed) {
|
|
548
|
-
socket.destroy(err);
|
|
549
|
-
}
|
|
550
|
-
});
|
|
551
|
-
session.on("close", () => {
|
|
552
|
-
this.log("debug", `Yamux session closed: ${tunnelConnectionId}`);
|
|
553
|
-
});
|
|
554
598
|
}
|
|
555
|
-
catch (
|
|
556
|
-
|
|
599
|
+
catch (error) {
|
|
600
|
+
settle(() => reject(error));
|
|
601
|
+
socket.destroy();
|
|
557
602
|
}
|
|
558
|
-
}
|
|
603
|
+
};
|
|
604
|
+
socket.once(this.transport === "tls" ? "secureConnect" : "connect", onReady);
|
|
605
|
+
if (this.transport === "tls") {
|
|
606
|
+
runtime.dialTimeout = setTimeout(() => {
|
|
607
|
+
socket.destroy(new Error(`TLS handshake timed out after ${this.options.tlsHandshakeTimeoutMs}ms`));
|
|
608
|
+
}, this.options.tlsHandshakeTimeoutMs);
|
|
609
|
+
}
|
|
610
|
+
else {
|
|
611
|
+
runtime.dialTimeout = setTimeout(() => {
|
|
612
|
+
socket.destroy(new Error(`Plaintext connect timed out after ${this.options.connectTimeoutMs}ms`));
|
|
613
|
+
}, this.options.connectTimeoutMs);
|
|
614
|
+
}
|
|
615
|
+
runtime.dialTimeout.unref();
|
|
559
616
|
socket.once("close", finalizeClose);
|
|
560
617
|
socket.once("end", finalizeClose);
|
|
561
|
-
const attemptTimeoutMs = transport === "tls" ? this.options.tlsHandshakeTimeoutMs : this.options.connectTimeoutMs;
|
|
562
|
-
runtime.connectTimer = setTimeout(() => {
|
|
563
|
-
runtime.connectTimer = undefined;
|
|
564
|
-
if (transportConnected || settled) {
|
|
565
|
-
return;
|
|
566
|
-
}
|
|
567
|
-
const label = transport === "tls" ? "TLS handshake" : "Plaintext connect";
|
|
568
|
-
rejectAttempt(new Error(`${label} timed out after ${attemptTimeoutMs}ms`));
|
|
569
|
-
}, attemptTimeoutMs);
|
|
570
|
-
runtime.connectTimer.unref();
|
|
571
618
|
});
|
|
572
619
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
620
|
+
connectDataPlane() {
|
|
621
|
+
if (this.transport === "tls") {
|
|
622
|
+
const ca = tlsCaOption(this.options.tunnelTlsCa);
|
|
623
|
+
return tls.connect({
|
|
624
|
+
host: this.tunnelAddress.host,
|
|
625
|
+
port: this.tunnelAddress.port,
|
|
626
|
+
servername: this.options.tunnelTlsServername,
|
|
627
|
+
minVersion: "TLSv1.2",
|
|
628
|
+
...(ca === undefined ? {} : { ca }),
|
|
629
|
+
});
|
|
578
630
|
}
|
|
579
|
-
|
|
580
|
-
|
|
631
|
+
return net.connect({
|
|
632
|
+
host: this.tunnelAddress.host,
|
|
633
|
+
port: this.tunnelAddress.port,
|
|
634
|
+
});
|
|
581
635
|
}
|
|
582
|
-
|
|
636
|
+
openDataPlaneFailureEpisode(runtime, safeErrorMessage) {
|
|
637
|
+
runtime.lastFailureMessage = safeErrorMessage;
|
|
583
638
|
const deadlineMs = this.options.dataPlaneRetryDeadlineMs;
|
|
584
|
-
|
|
585
|
-
if (deadlineMs === 0 || startedAt === undefined) {
|
|
639
|
+
if (deadlineMs === 0 || runtime.failureDeadline)
|
|
586
640
|
return;
|
|
587
|
-
|
|
588
|
-
const
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
runtime.failureDeadlineTimer = undefined;
|
|
592
|
-
this.expireDataPlaneFailureEpisode(tunnelConnectionId, runtime);
|
|
641
|
+
runtime.failureEpisodeStartedAt ??= performance.now();
|
|
642
|
+
const remainingMs = Math.max(0, Math.ceil(deadlineMs - (performance.now() - runtime.failureEpisodeStartedAt)));
|
|
643
|
+
runtime.failureDeadline = setTimeout(() => {
|
|
644
|
+
this.expireDataPlaneFailureEpisode(runtime);
|
|
593
645
|
}, remainingMs);
|
|
594
|
-
runtime.
|
|
646
|
+
runtime.failureDeadline.unref();
|
|
595
647
|
}
|
|
596
|
-
expireDataPlaneFailureEpisode(
|
|
597
|
-
|
|
648
|
+
expireDataPlaneFailureEpisode(runtime) {
|
|
649
|
+
runtime.failureDeadline = undefined;
|
|
650
|
+
if (runtime.failureEpisodeStartedAt === undefined
|
|
651
|
+
|| !this.running
|
|
598
652
|
|| !this.allowTunnelReconnect
|
|
599
|
-
|| runtime.stopRetryOnDisconnect
|
|
600
|
-
|| runtime.failureEpisodeStartedAt === undefined) {
|
|
601
|
-
this.clearDataPlaneFailureEpisode(runtime);
|
|
653
|
+
|| runtime.stopRetryOnDisconnect) {
|
|
602
654
|
return;
|
|
603
655
|
}
|
|
604
656
|
runtime.stopRetryOnDisconnect = true;
|
|
605
|
-
|
|
606
|
-
if (runtime.socket && !runtime.socket.destroyed) {
|
|
657
|
+
if (runtime.socket && !runtime.socket.destroyed)
|
|
607
658
|
runtime.socket.destroy();
|
|
608
|
-
|
|
659
|
+
if (this.dataPlaneTerminalErrorReported)
|
|
660
|
+
return;
|
|
661
|
+
this.dataPlaneTerminalErrorReported = true;
|
|
662
|
+
const address = formatTunnelAddress(this.tunnelAddress);
|
|
609
663
|
try {
|
|
610
|
-
|
|
611
|
-
this.
|
|
612
|
-
this.reportError(ErrCode.DataPlaneUnreachable, `Data plane ${this.#transportMode} at ${formatTunnelAddress(this.tunnelAddress)} `
|
|
613
|
-
+ `is unreachable after ${this.options.dataPlaneRetryDeadlineMs}ms: `
|
|
614
|
-
+ (runtime.lastFailureMessage ?? "unknown data-plane failure"), "error");
|
|
615
|
-
}
|
|
664
|
+
this.reportError(ErrCode.DataPlaneUnreachable, `Data plane ${this.transport} at ${address} is unreachable after `
|
|
665
|
+
+ `${this.options.dataPlaneRetryDeadlineMs}ms: ${runtime.lastFailureMessage ?? "unknown data-plane failure"}`, "error");
|
|
616
666
|
}
|
|
617
667
|
finally {
|
|
618
|
-
this.
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
markDataPlaneEstablished(runtime) {
|
|
622
|
-
if (!this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
|
|
623
|
-
return;
|
|
624
|
-
}
|
|
625
|
-
runtime.sessionEstablished = true;
|
|
626
|
-
if (runtime.settleTimer !== undefined) {
|
|
627
|
-
clearTimeout(runtime.settleTimer);
|
|
628
|
-
runtime.settleTimer = undefined;
|
|
629
|
-
}
|
|
630
|
-
this.clearDataPlaneFailureEpisode(runtime);
|
|
631
|
-
}
|
|
632
|
-
clearDataPlaneAttemptTimers(runtime) {
|
|
633
|
-
if (runtime.connectTimer !== undefined) {
|
|
634
|
-
clearTimeout(runtime.connectTimer);
|
|
635
|
-
runtime.connectTimer = undefined;
|
|
636
|
-
}
|
|
637
|
-
if (runtime.settleTimer !== undefined) {
|
|
638
|
-
clearTimeout(runtime.settleTimer);
|
|
639
|
-
runtime.settleTimer = undefined;
|
|
668
|
+
void this.stop();
|
|
640
669
|
}
|
|
641
670
|
}
|
|
642
671
|
clearDataPlaneFailureEpisode(runtime) {
|
|
643
|
-
if (runtime.
|
|
644
|
-
clearTimeout(runtime.
|
|
645
|
-
runtime.
|
|
672
|
+
if (runtime.failureDeadline) {
|
|
673
|
+
clearTimeout(runtime.failureDeadline);
|
|
674
|
+
runtime.failureDeadline = undefined;
|
|
646
675
|
}
|
|
647
676
|
runtime.failureEpisodeStartedAt = undefined;
|
|
648
677
|
runtime.lastFailureMessage = undefined;
|
|
649
678
|
}
|
|
679
|
+
clearAttemptTimers(runtime) {
|
|
680
|
+
if (runtime.dialTimeout) {
|
|
681
|
+
clearTimeout(runtime.dialTimeout);
|
|
682
|
+
runtime.dialTimeout = undefined;
|
|
683
|
+
}
|
|
684
|
+
if (runtime.settleTimeout) {
|
|
685
|
+
clearTimeout(runtime.settleTimeout);
|
|
686
|
+
runtime.settleTimeout = undefined;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
650
689
|
stopAllTunnelRuntimes() {
|
|
690
|
+
// Invalidate pending DNS/connection work before draining sockets. A later
|
|
691
|
+
// RequestTunnel gets a fresh signal without reviving work from this session.
|
|
692
|
+
this.targetDialController.abort();
|
|
651
693
|
for (const runtime of this.tunnelRuntimes.values()) {
|
|
652
694
|
runtime.stopRetryOnDisconnect = true;
|
|
653
|
-
this.clearDataPlaneAttemptTimers(runtime);
|
|
654
695
|
this.clearDataPlaneFailureEpisode(runtime);
|
|
696
|
+
this.clearAttemptTimers(runtime);
|
|
655
697
|
if (runtime.session) {
|
|
656
698
|
runtime.session.close();
|
|
657
699
|
}
|
|
@@ -659,34 +701,18 @@ export class TunnelClient extends EventEmitter {
|
|
|
659
701
|
runtime.socket.destroy();
|
|
660
702
|
}
|
|
661
703
|
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
// 'close' synchronously for an already-connected socket, and that handler
|
|
665
|
-
// deletes from the live set.
|
|
666
|
-
for (const socket of [...this.activeTargetSockets]) {
|
|
667
|
-
if (!socket.destroyed) {
|
|
668
|
-
socket.destroy();
|
|
669
|
-
}
|
|
704
|
+
for (const socket of this.activeTargetSockets) {
|
|
705
|
+
socket.destroy();
|
|
670
706
|
}
|
|
671
707
|
this.activeTargetSockets.clear();
|
|
672
708
|
}
|
|
673
|
-
beginStop() {
|
|
674
|
-
this.running = false;
|
|
675
|
-
this.reconnectDelayController.abort();
|
|
676
|
-
// VENDOR DELTA: also close a socket still in CONNECTING. Upstream only
|
|
677
|
-
// closes an OPEN one, so a control plane that accepts TCP and never
|
|
678
|
-
// completes the WebSocket handshake leaves the socket untouched — and the
|
|
679
|
-
// `await this.controlLoopTask` in stop() then waits on the very handshake
|
|
680
|
-
// nothing is going to finish. stop() never returns, so the caller's
|
|
681
|
-
// teardown never reaches the credential delete that follows it.
|
|
682
|
-
if (this.controlWs
|
|
683
|
-
&& (this.controlWs.readyState === WebSocket.OPEN
|
|
684
|
-
|| this.controlWs.readyState === WebSocket.CONNECTING)) {
|
|
685
|
-
this.controlWs.close();
|
|
686
|
-
}
|
|
687
|
-
this.stopAllTunnelRuntimes();
|
|
688
|
-
}
|
|
689
709
|
async handleIncomingStream(stream) {
|
|
710
|
+
const completed = new AbortController();
|
|
711
|
+
const signal = anySignal([
|
|
712
|
+
this.lifecycleController.signal,
|
|
713
|
+
this.targetDialController.signal,
|
|
714
|
+
completed.signal,
|
|
715
|
+
]);
|
|
690
716
|
try {
|
|
691
717
|
const frame = await readTypedFrame(stream, isStreamOpenRequestFrame);
|
|
692
718
|
const targetHost = frame.target_host;
|
|
@@ -694,13 +720,16 @@ export class TunnelClient extends EventEmitter {
|
|
|
694
720
|
const logContext = `${frame.request_id} (${frame.inbound_request_id}, ${frame.tunnel_connection_id}, stream ${frame.mux_stream_id})`;
|
|
695
721
|
this.log("debug", `Stream open: ${logContext}`);
|
|
696
722
|
this.log("info", `Open request ${logContext}: ${targetHost}:${targetPort}`);
|
|
697
|
-
const target = await this.connectTarget(targetHost, targetPort);
|
|
723
|
+
const target = await this.connectTarget(targetHost, targetPort, signal);
|
|
698
724
|
this.log("debug", `Target connected: ${logContext}`);
|
|
699
725
|
await this.proxyStreams(stream, target, logContext);
|
|
700
726
|
this.log("debug", `Stream proxy finished: ${logContext}`);
|
|
701
727
|
}
|
|
702
728
|
catch (err) {
|
|
703
|
-
if (
|
|
729
|
+
if (signal.aborted || !this.running) {
|
|
730
|
+
// Lifecycle teardown is expected; keep stream cleanup below.
|
|
731
|
+
}
|
|
732
|
+
else if (err instanceof YamuxStreamResetError) {
|
|
704
733
|
this.log("debug", `Stream reset while handling inbound stream: ${toErrorMessage(err)}`);
|
|
705
734
|
}
|
|
706
735
|
else if (err instanceof BlockedTargetError) {
|
|
@@ -716,6 +745,9 @@ export class TunnelClient extends EventEmitter {
|
|
|
716
745
|
stream.destroy();
|
|
717
746
|
}
|
|
718
747
|
}
|
|
748
|
+
finally {
|
|
749
|
+
completed.abort();
|
|
750
|
+
}
|
|
719
751
|
}
|
|
720
752
|
async proxyStreams(stream, target, logContext) {
|
|
721
753
|
const onTargetError = (err) => {
|
|
@@ -785,36 +817,47 @@ export class TunnelClient extends EventEmitter {
|
|
|
785
817
|
}
|
|
786
818
|
}
|
|
787
819
|
}
|
|
788
|
-
async connectTarget(host, port) {
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
820
|
+
async connectTarget(host, port, signal) {
|
|
821
|
+
const completed = new AbortController();
|
|
822
|
+
try {
|
|
823
|
+
signal ??= anySignal([
|
|
824
|
+
this.lifecycleController.signal,
|
|
825
|
+
this.targetDialController.signal,
|
|
826
|
+
completed.signal,
|
|
827
|
+
]);
|
|
828
|
+
// `host`/`port` here are the `target_host`/`target_port` relayed verbatim from the inbound
|
|
829
|
+
// proxy request on the internet-facing proxy port — untrusted input as far as this client
|
|
830
|
+
// is concerned. Resolve once, validate the exact resolved candidate set, then dial that same
|
|
831
|
+
// set (never the original hostname): a name that later rebinds to a different address can't
|
|
832
|
+
// slip through, because there is no second, independent lookup between the check and the
|
|
833
|
+
// dial. Mirrors `connect_target`/`ensure_candidates_are_loopback` in the Rust client.
|
|
834
|
+
signal.throwIfAborted();
|
|
835
|
+
const candidates = await abortable(resolveDialCandidates(host, port), signal);
|
|
836
|
+
signal.throwIfAborted();
|
|
837
|
+
ensureTargetAllowed(host, port, candidates, this.options.allowPrivateNetworkTarget);
|
|
838
|
+
let lastError;
|
|
839
|
+
for (const candidate of candidates) {
|
|
840
|
+
signal.throwIfAborted();
|
|
841
|
+
try {
|
|
842
|
+
return await this.connectOnce(candidate.host, candidate.port, signal);
|
|
843
|
+
}
|
|
844
|
+
catch (err) {
|
|
845
|
+
signal.throwIfAborted();
|
|
846
|
+
lastError = err;
|
|
847
|
+
}
|
|
804
848
|
}
|
|
849
|
+
throw new TargetConnectError(host, port, lastError ?? new Error(`no dial candidates for ${host}:${port}`));
|
|
850
|
+
}
|
|
851
|
+
finally {
|
|
852
|
+
completed.abort();
|
|
805
853
|
}
|
|
806
|
-
throw new TargetConnectError(host, port, lastError ?? new Error(`no dial candidates for ${host}:${port}`));
|
|
807
854
|
}
|
|
808
|
-
connectOnce(host, port) {
|
|
855
|
+
connectOnce(host, port, signal) {
|
|
809
856
|
return new Promise((resolve, reject) => {
|
|
857
|
+
signal.throwIfAborted();
|
|
810
858
|
const socket = net.connect({ host, port });
|
|
811
|
-
// VENDOR DELTA: track from creation so a teardown mid-dial destroys it too;
|
|
812
|
-
// the 'close' handler removes it whether the dial succeeds, fails, or is
|
|
813
|
-
// force-destroyed by stopAllTunnelRuntimes(). See the field comment.
|
|
814
859
|
this.activeTargetSockets.add(socket);
|
|
815
|
-
socket.once("close", () =>
|
|
816
|
-
this.activeTargetSockets.delete(socket);
|
|
817
|
-
});
|
|
860
|
+
socket.once("close", () => this.activeTargetSockets.delete(socket));
|
|
818
861
|
const onError = (err) => {
|
|
819
862
|
cleanup();
|
|
820
863
|
if (!socket.destroyed) {
|
|
@@ -826,6 +869,7 @@ export class TunnelClient extends EventEmitter {
|
|
|
826
869
|
cleanup();
|
|
827
870
|
resolve(socket);
|
|
828
871
|
};
|
|
872
|
+
const onAbort = () => onError(signal.reason);
|
|
829
873
|
const timeout = setTimeout(() => {
|
|
830
874
|
onError(new Error(`connect timeout ${DEFAULT_TARGET_CONNECT_TIMEOUT_MS}ms`));
|
|
831
875
|
}, DEFAULT_TARGET_CONNECT_TIMEOUT_MS);
|
|
@@ -833,9 +877,11 @@ export class TunnelClient extends EventEmitter {
|
|
|
833
877
|
clearTimeout(timeout);
|
|
834
878
|
socket.off("error", onError);
|
|
835
879
|
socket.off("connect", onConnect);
|
|
880
|
+
signal.removeEventListener("abort", onAbort);
|
|
836
881
|
};
|
|
837
882
|
socket.once("error", onError);
|
|
838
883
|
socket.once("connect", onConnect);
|
|
884
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
839
885
|
});
|
|
840
886
|
}
|
|
841
887
|
log(level, message) {
|
|
@@ -845,10 +891,58 @@ export class TunnelClient extends EventEmitter {
|
|
|
845
891
|
this.options.logSink(level, `[TunnelClient] [${level}] ${message}`);
|
|
846
892
|
}
|
|
847
893
|
reportError(code, message, level = "warn") {
|
|
848
|
-
|
|
894
|
+
try {
|
|
895
|
+
this.options.onError({ code, message });
|
|
896
|
+
}
|
|
897
|
+
catch {
|
|
898
|
+
this.log("warn", "onError callback threw; continuing client lifecycle");
|
|
899
|
+
}
|
|
849
900
|
this.log(level, message);
|
|
850
901
|
}
|
|
851
902
|
}
|
|
903
|
+
function anySignal(signals) {
|
|
904
|
+
const controller = new AbortController();
|
|
905
|
+
const aborted = signals.find((signal) => signal.aborted);
|
|
906
|
+
if (aborted) {
|
|
907
|
+
controller.abort(aborted.reason);
|
|
908
|
+
return controller.signal;
|
|
909
|
+
}
|
|
910
|
+
const listeners = new Map();
|
|
911
|
+
const cleanup = () => {
|
|
912
|
+
for (const [signal, listener] of listeners) {
|
|
913
|
+
signal.removeEventListener("abort", listener);
|
|
914
|
+
}
|
|
915
|
+
listeners.clear();
|
|
916
|
+
};
|
|
917
|
+
for (const signal of new Set(signals)) {
|
|
918
|
+
const onAbort = () => {
|
|
919
|
+
cleanup();
|
|
920
|
+
controller.abort(signal.reason);
|
|
921
|
+
};
|
|
922
|
+
listeners.set(signal, onAbort);
|
|
923
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
924
|
+
}
|
|
925
|
+
return controller.signal;
|
|
926
|
+
}
|
|
927
|
+
function abortable(task, signal) {
|
|
928
|
+
return new Promise((resolve, reject) => {
|
|
929
|
+
const onAbort = () => {
|
|
930
|
+
signal.removeEventListener("abort", onAbort);
|
|
931
|
+
reject(signal.reason);
|
|
932
|
+
};
|
|
933
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
934
|
+
if (signal.aborted) {
|
|
935
|
+
onAbort();
|
|
936
|
+
}
|
|
937
|
+
task.then((value) => {
|
|
938
|
+
signal.removeEventListener("abort", onAbort);
|
|
939
|
+
resolve(value);
|
|
940
|
+
}, (error) => {
|
|
941
|
+
signal.removeEventListener("abort", onAbort);
|
|
942
|
+
reject(error);
|
|
943
|
+
});
|
|
944
|
+
});
|
|
945
|
+
}
|
|
852
946
|
function delay(ms, signal) {
|
|
853
947
|
if (signal?.aborted) {
|
|
854
948
|
return Promise.resolve();
|
|
@@ -993,9 +1087,7 @@ export function blockedTargetReason(address) {
|
|
|
993
1087
|
if (family === 0) {
|
|
994
1088
|
return "not an IP literal";
|
|
995
1089
|
}
|
|
996
|
-
//
|
|
997
|
-
// matching instead of spelling-specific mapped-address regexes. This makes equivalent IPv6
|
|
998
|
-
// spellings share one verdict and refuses compatible, mapped, translated, and NAT64 forms.
|
|
1090
|
+
// Match IPv6 ranges in binary so expanded and compressed spellings share one verdict.
|
|
999
1091
|
const targetFamily = family === 4 ? "ipv4" : "ipv6";
|
|
1000
1092
|
const loopback = new net.BlockList();
|
|
1001
1093
|
if (targetFamily === "ipv4") {
|
|
@@ -1010,30 +1102,10 @@ export function blockedTargetReason(address) {
|
|
|
1010
1102
|
}
|
|
1011
1103
|
if (targetFamily === "ipv6") {
|
|
1012
1104
|
const embeddedIpv4 = new net.BlockList();
|
|
1013
|
-
//
|
|
1014
|
-
//
|
|
1015
|
-
// binary superset of every RFC-named spelling in its family, so a reserved-but-
|
|
1016
|
-
// non-canonical prefix that sits between two narrow rules (e.g.
|
|
1017
|
-
// `64:ff9b:ffff::a9fe:a9fe`, which is in neither the RFC 6052 `/96` nor the RFC 8215
|
|
1018
|
-
// `/48`) can no longer slip through. Mirrors `src/lib/target-url.ts`'s
|
|
1019
|
-
// `NAT64_SUBNETS` / `IPV4_COMPATIBLE_SUBNETS` exactly (see that file's doc comment for
|
|
1020
|
-
// the full reasoning); both `0000::/8` and `0064::/16` are IETF-reserved, so widening
|
|
1021
|
-
// costs no reachable public target. The narrower `::ffff:0:0/96` / `::ffff:0:0:0/80` /
|
|
1022
|
-
// `0:0:0:ffff:0:0:0:0/96` entries below are now FULLY SUBSUMED by the wider `::/32` and
|
|
1023
|
-
// change no verdict — every hit here returns the one generic string, so unlike
|
|
1024
|
-
// `target-url.ts` they name no family. They are kept only as an inline record of which
|
|
1025
|
-
// RFC-named spellings this range covers, and deleting them is behaviour-neutral (proved
|
|
1026
|
-
// by mutation: removing all three leaves the target-guard spec at 31/31). `::1` and mapped
|
|
1027
|
-
// loopback
|
|
1028
|
-
// (`::ffff:127.0.0.0/104`) are unaffected — the loopback `BlockList` above is checked
|
|
1029
|
-
// first and returns before this one is ever consulted. See VENDOR.md #11.
|
|
1105
|
+
// The /32 supersets cover compatible, mapped, translated and non-canonical NAT64 forms.
|
|
1106
|
+
// Native and mapped loopback are exempted above before these reserved ranges are checked.
|
|
1030
1107
|
embeddedIpv4.addSubnet("::", 32, "ipv6");
|
|
1031
|
-
embeddedIpv4.addSubnet("::ffff:0:0", 96, "ipv6");
|
|
1032
|
-
embeddedIpv4.addSubnet("::ffff:0:0:0", 80, "ipv6");
|
|
1033
|
-
embeddedIpv4.addSubnet("0:0:0:ffff:0:0:0:0", 96, "ipv6");
|
|
1034
1108
|
embeddedIpv4.addSubnet("64:ff9b::", 32, "ipv6");
|
|
1035
|
-
// VENDOR DELTA: 6to4 and Teredo derive IPv4 destinations by construction, so they belong
|
|
1036
|
-
// with the other embedded-IPv4 spaces. See VENDOR.md #10.
|
|
1037
1109
|
embeddedIpv4.addSubnet("2002::", 16, "ipv6");
|
|
1038
1110
|
embeddedIpv4.addSubnet("2001::", 32, "ipv6");
|
|
1039
1111
|
if (embeddedIpv4.check(address, "ipv6")) {
|
|
@@ -1063,8 +1135,6 @@ const BLOCKED_IPV4 = [
|
|
|
1063
1135
|
];
|
|
1064
1136
|
const BLOCKED_IPV6 = [
|
|
1065
1137
|
["IPv6 unique-local address", [["fc00::", 7]]],
|
|
1066
|
-
// VENDOR DELTA: deprecated site-local space is private-scope even though it predates ULA.
|
|
1067
|
-
// See VENDOR.md #10.
|
|
1068
1138
|
["IPv6 site-local address", [["fec0::", 10]]],
|
|
1069
1139
|
["IPv6 link-local address", [["fe80::", 10]]],
|
|
1070
1140
|
["multicast address", [["ff00::", 8]]],
|
|
@@ -1094,98 +1164,43 @@ export function ensureTargetAllowed(host, port, candidates, allowPrivateNetwork)
|
|
|
1094
1164
|
}
|
|
1095
1165
|
}
|
|
1096
1166
|
}
|
|
1097
|
-
/**
|
|
1098
|
-
* Build the `ca` option for a TLS dial. Extra roots are appended to Node's
|
|
1099
|
-
* DEFAULT trust store — the bundled Mozilla roots plus whatever
|
|
1100
|
-
* NODE_EXTRA_CA_CERTS / --use-system-ca added — because `tls.rootCertificates`
|
|
1101
|
-
* alone silently drops NODE_EXTRA_CA_CERTS, which is exactly how corporate
|
|
1102
|
-
* TLS-inspecting proxies are trusted. With no extra root configured the option
|
|
1103
|
-
* stays undefined so Node applies its defaults untouched.
|
|
1104
|
-
*/
|
|
1105
|
-
function tlsCaOption(extraRoots) {
|
|
1106
|
-
if (extraRoots.length === 0)
|
|
1107
|
-
return undefined;
|
|
1108
|
-
const withDefaults = tls;
|
|
1109
|
-
const defaults = typeof withDefaults.getCACertificates === "function"
|
|
1110
|
-
? withDefaults.getCACertificates("default")
|
|
1111
|
-
: [...tls.rootCertificates, ...readNodeExtraCaCertificates()];
|
|
1112
|
-
return [...defaults, ...extraRoots];
|
|
1113
|
-
}
|
|
1114
|
-
/**
|
|
1115
|
-
* Certificates from the NODE_EXTRA_CA_CERTS file, cached per path. Node reads
|
|
1116
|
-
* that file once at startup; re-reading only when the path changes keeps the
|
|
1117
|
-
* same semantics while letting tests point at a temporary file.
|
|
1118
|
-
*/
|
|
1119
|
-
let nodeExtraCaCertificates;
|
|
1120
|
-
function readNodeExtraCaCertificates() {
|
|
1121
|
-
const path = process.env.NODE_EXTRA_CA_CERTS;
|
|
1122
|
-
if (!path)
|
|
1123
|
-
return [];
|
|
1124
|
-
if (nodeExtraCaCertificates?.path === path) {
|
|
1125
|
-
return nodeExtraCaCertificates.certificates;
|
|
1126
|
-
}
|
|
1127
|
-
let certificates;
|
|
1128
|
-
try {
|
|
1129
|
-
// eslint-disable-next-line security/detect-non-literal-fs-filename -- `NODE_EXTRA_CA_CERTS` is the operator-set path Node itself reads at startup, never request or user input.
|
|
1130
|
-
const contents = readFileSync(path, "utf8");
|
|
1131
|
-
certificates =
|
|
1132
|
-
contents.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/gu) ?? [];
|
|
1133
|
-
}
|
|
1134
|
-
catch {
|
|
1135
|
-
certificates = [];
|
|
1136
|
-
}
|
|
1137
|
-
nodeExtraCaCertificates = { path, certificates };
|
|
1138
|
-
return certificates;
|
|
1139
|
-
}
|
|
1140
1167
|
function parseTunnelAddr(addr) {
|
|
1141
|
-
if (addr.
|
|
1168
|
+
if (addr !== addr.trim() || addr.includes("://") || /[\s\0/\\?#@]/.test(addr)) {
|
|
1142
1169
|
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1143
1170
|
}
|
|
1144
1171
|
let hostPart = "";
|
|
1145
1172
|
let portPart = "";
|
|
1146
1173
|
if (addr.startsWith("[")) {
|
|
1147
1174
|
const closing = addr.indexOf("]");
|
|
1148
|
-
if (closing
|
|
1149
|
-
|| closing !== addr.lastIndexOf("]")
|
|
1175
|
+
if (closing < 0
|
|
1150
1176
|
|| closing + 2 > addr.length
|
|
1151
|
-
|| addr[closing + 1] !== ":"
|
|
1177
|
+
|| addr[closing + 1] !== ":"
|
|
1178
|
+
|| net.isIP(addr.slice(1, closing)) !== 6) {
|
|
1152
1179
|
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1153
1180
|
}
|
|
1154
1181
|
hostPart = addr.slice(1, closing);
|
|
1155
1182
|
portPart = addr.slice(closing + 2);
|
|
1156
|
-
if (net.isIP(hostPart) !== 6) {
|
|
1157
|
-
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1158
|
-
}
|
|
1159
1183
|
}
|
|
1160
1184
|
else {
|
|
1161
|
-
const sep = addr.
|
|
1162
|
-
if (sep <= 0 || sep === addr.length - 1) {
|
|
1163
|
-
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1164
|
-
}
|
|
1165
|
-
if (sep !== addr.lastIndexOf(":")) {
|
|
1185
|
+
const sep = addr.lastIndexOf(":");
|
|
1186
|
+
if (sep <= 0 || sep === addr.length - 1 || addr.indexOf(":") !== sep) {
|
|
1166
1187
|
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1167
1188
|
}
|
|
1168
1189
|
hostPart = addr.slice(0, sep);
|
|
1169
1190
|
portPart = addr.slice(sep + 1);
|
|
1170
|
-
if (net.isIP(hostPart) === 0) {
|
|
1171
|
-
const canonicalHost = canonicalDnsHostname(hostPart);
|
|
1172
|
-
if (canonicalHost === undefined) {
|
|
1173
|
-
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1174
|
-
}
|
|
1175
|
-
hostPart = canonicalHost;
|
|
1176
|
-
}
|
|
1177
1191
|
}
|
|
1178
|
-
if (!/^\d
|
|
1192
|
+
if (!/^\d+$/.test(portPart)) {
|
|
1179
1193
|
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1180
1194
|
}
|
|
1181
1195
|
const port = Number(portPart);
|
|
1182
|
-
if (port <= 0 || port > 65535) {
|
|
1196
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
1183
1197
|
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1184
1198
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
}
|
|
1199
|
+
const host = net.isIP(hostPart) === 0 ? canonicalDnsHostname(hostPart) : hostPart;
|
|
1200
|
+
if (host === undefined) {
|
|
1201
|
+
throw new Error(`Invalid tunnel address: ${addr}`);
|
|
1202
|
+
}
|
|
1203
|
+
return { host, port };
|
|
1189
1204
|
}
|
|
1190
1205
|
function canonicalDnsHostname(host) {
|
|
1191
1206
|
const ascii = domainToASCII(host).toLowerCase();
|
|
@@ -1198,6 +1213,53 @@ function canonicalDnsHostname(host) {
|
|
|
1198
1213
|
&& /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/iu.test(label));
|
|
1199
1214
|
return valid ? ascii : undefined;
|
|
1200
1215
|
}
|
|
1216
|
+
function normalizeTlsCa(extraCa) {
|
|
1217
|
+
if (extraCa === undefined)
|
|
1218
|
+
return [];
|
|
1219
|
+
return Array.isArray(extraCa) ? [...extraCa] : [extraCa];
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Certificates from the NODE_EXTRA_CA_CERTS file, cached per path. Node reads
|
|
1223
|
+
* that file once at startup; re-reading only when the path changes keeps the
|
|
1224
|
+
* same semantics while letting tests point at a temporary file.
|
|
1225
|
+
*/
|
|
1226
|
+
let nodeExtraCaCertificates;
|
|
1227
|
+
function readNodeExtraCaCertificates() {
|
|
1228
|
+
const path = process.env.NODE_EXTRA_CA_CERTS;
|
|
1229
|
+
if (!path)
|
|
1230
|
+
return [];
|
|
1231
|
+
if (nodeExtraCaCertificates?.path === path) {
|
|
1232
|
+
return nodeExtraCaCertificates.certificates;
|
|
1233
|
+
}
|
|
1234
|
+
let certificates;
|
|
1235
|
+
try {
|
|
1236
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- `NODE_EXTRA_CA_CERTS` is the operator-set path Node itself reads at startup, never request or user input.
|
|
1237
|
+
const contents = readFileSync(path, "utf8");
|
|
1238
|
+
certificates =
|
|
1239
|
+
contents.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/gu) ?? [];
|
|
1240
|
+
}
|
|
1241
|
+
catch {
|
|
1242
|
+
certificates = [];
|
|
1243
|
+
}
|
|
1244
|
+
nodeExtraCaCertificates = { path, certificates };
|
|
1245
|
+
return certificates;
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Build the `ca` option for a TLS dial. Extra roots are appended to Node's
|
|
1249
|
+
* default trust store. Node 22.15+ exposes that store directly. Older supported
|
|
1250
|
+
* releases expose only bundled roots, so append the NODE_EXTRA_CA_CERTS file
|
|
1251
|
+
* cached per path before adding the caller's roots (CLI compatibility). With no explicit
|
|
1252
|
+
* root configured the option stays undefined so Node applies its defaults.
|
|
1253
|
+
*/
|
|
1254
|
+
function tlsCaOption(extraRoots) {
|
|
1255
|
+
if (extraRoots.length === 0)
|
|
1256
|
+
return undefined;
|
|
1257
|
+
const withDefaults = tls;
|
|
1258
|
+
const defaults = typeof withDefaults.getCACertificates === "function"
|
|
1259
|
+
? withDefaults.getCACertificates("default")
|
|
1260
|
+
: [...tls.rootCertificates, ...readNodeExtraCaCertificates()];
|
|
1261
|
+
return [...defaults, ...extraRoots];
|
|
1262
|
+
}
|
|
1201
1263
|
function isStreamOpenRequestFrame(value) {
|
|
1202
1264
|
if (!isPlainObject(value)) {
|
|
1203
1265
|
return false;
|
|
@@ -1211,13 +1273,22 @@ function isStreamOpenRequestFrame(value) {
|
|
|
1211
1273
|
&& isNumber(frame.target_port);
|
|
1212
1274
|
}
|
|
1213
1275
|
class ControlAuthFailureError extends Error {
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
constructor(code, reason,
|
|
1276
|
+
reason;
|
|
1277
|
+
authenticated;
|
|
1278
|
+
constructor(code, reason, authenticated) {
|
|
1217
1279
|
super(`control auth failure (code=${code}, reason=${reason || "unknown"})`);
|
|
1280
|
+
this.reason = reason;
|
|
1281
|
+
this.authenticated = authenticated;
|
|
1218
1282
|
this.name = "ControlAuthFailureError";
|
|
1219
|
-
|
|
1220
|
-
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
class ControlClientUnknownCloseError extends Error {
|
|
1286
|
+
}
|
|
1287
|
+
export class ClientUnknownError extends Error {
|
|
1288
|
+
code = ErrCode.ClientUnknown;
|
|
1289
|
+
constructor(deadlineMs) {
|
|
1290
|
+
super(`Tunnel client registration was not found after ${deadlineMs}ms`);
|
|
1291
|
+
this.name = "ClientUnknownError";
|
|
1221
1292
|
}
|
|
1222
1293
|
}
|
|
1223
1294
|
class TargetConnectError extends Error {
|
|
@@ -1245,7 +1316,6 @@ function isControlAuthFailureError(err) {
|
|
|
1245
1316
|
return err instanceof ControlAuthFailureError;
|
|
1246
1317
|
}
|
|
1247
1318
|
function isAuthFailureClose(code, reason) {
|
|
1248
|
-
|
|
1249
|
-
return code === 1008 && (normalizedReason === "AUTH_FAILED" || normalizedReason === "CLIENT_REVOKED");
|
|
1319
|
+
return code === 1008 && ["AUTH_FAILED", "CLIENT_REVOKED"].includes(reason.trim().toUpperCase());
|
|
1250
1320
|
}
|
|
1251
1321
|
//# sourceMappingURL=client.js.map
|