@testsprite/testsprite-cli 0.13.0 → 0.14.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.
Files changed (58) hide show
  1. package/README.md +51 -48
  2. package/dist/commands/doctor.js +12 -11
  3. package/dist/commands/project-env.d.ts +11 -1
  4. package/dist/commands/project-env.js +399 -61
  5. package/dist/commands/project-sign-in.d.ts +60 -0
  6. package/dist/commands/project-sign-in.js +289 -0
  7. package/dist/commands/project.d.ts +9 -0
  8. package/dist/commands/project.js +68 -28
  9. package/dist/commands/schedule.d.ts +12 -0
  10. package/dist/commands/schedule.js +175 -5
  11. package/dist/commands/test.d.ts +53 -20
  12. package/dist/commands/test.js +1356 -342
  13. package/dist/commands/testlist.d.ts +10 -5
  14. package/dist/commands/testlist.js +170 -30
  15. package/dist/commands/tunnel.js +11 -5
  16. package/dist/index.js +12 -37
  17. package/dist/lib/client-factory.d.ts +12 -1
  18. package/dist/lib/client-factory.js +14 -4
  19. package/dist/lib/dry-run/samples.js +53 -0
  20. package/dist/lib/environment-tunnel.d.ts +109 -0
  21. package/dist/lib/environment-tunnel.js +465 -0
  22. package/dist/lib/errors.js +12 -1
  23. package/dist/lib/gh-output.js +3 -0
  24. package/dist/lib/http.d.ts +2 -0
  25. package/dist/lib/junit-report.d.ts +11 -7
  26. package/dist/lib/junit-report.js +13 -7
  27. package/dist/lib/local-target.d.ts +13 -3
  28. package/dist/lib/local-target.js +47 -12
  29. package/dist/lib/output.js +15 -1
  30. package/dist/lib/plan-poll.js +3 -4
  31. package/dist/lib/redact.d.ts +38 -0
  32. package/dist/lib/redact.js +140 -0
  33. package/dist/lib/render-error.d.ts +19 -5
  34. package/dist/lib/render-error.js +31 -0
  35. package/dist/lib/runs.types.d.ts +9 -1
  36. package/dist/lib/target-url.js +5 -5
  37. package/dist/lib/telemetry.d.ts +6 -7
  38. package/dist/lib/telemetry.js +11 -4
  39. package/dist/lib/testlist.types.d.ts +1 -0
  40. package/dist/lib/ticker.d.ts +9 -0
  41. package/dist/lib/ticker.js +18 -0
  42. package/dist/lib/tunnel-session.d.ts +3 -4
  43. package/dist/lib/tunnel-session.js +3 -4
  44. package/dist/lib/v3-advisory.js +0 -1
  45. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  46. package/dist/vendor/tunnel-client/client.js +477 -407
  47. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  48. package/dist/vendor/tunnel-client/config.js +5 -5
  49. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  50. package/dist/vendor/tunnel-client/index.js +4 -4
  51. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  52. package/dist/vendor/tunnel-client/types.js +1 -0
  53. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  54. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/package.json +1 -1
  58. 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
- // VENDOR DELTA: no CLIENT_VERSION (no package.json import) and no endpoint
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
- // VENDOR DELTA: reconnect backoffs are tied to this lifecycle controller so stop() cancels
50
- // both control and tunnel sleeps instead of awaiting a still-ref'd timer. See VENDOR.md #9.
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
- const configuredPlaintextAddress = parseTunnelAddr(options.tunnelAddr);
68
- const deadlineMs = options.dataPlaneRetryDeadlineMs ?? DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS;
69
- if (!Number.isInteger(deadlineMs) || deadlineMs < 0) {
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
- const settleMs = options.dataPlaneSettleMs ?? DEFAULT_DATA_PLANE_SETTLE_MS;
73
- if (!Number.isInteger(settleMs) || settleMs < 0) {
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
- const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
77
- if (!Number.isInteger(connectTimeoutMs) || connectTimeoutMs < 0) {
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 tlsHandshakeTimeoutMs = options.tlsHandshakeTimeoutMs ?? DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS;
81
- if (!Number.isInteger(tlsHandshakeTimeoutMs) || tlsHandshakeTimeoutMs < 0) {
82
- throw new RangeError("tlsHandshakeTimeoutMs must be a non-negative integer");
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 (options.tunnelTlsAddr !== undefined) {
86
- const tunnelTlsAddress = parseTunnelAddr(options.tunnelTlsAddr);
87
- this.tunnelAddress = tunnelTlsAddress;
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 = options.tunnelTlsServername ?? tunnelTlsAddress.host;
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
- tunnelAddr: options.tunnelAddr,
110
- ...(options.tunnelTlsAddr !== undefined
111
- ? {
112
- tunnelTlsAddr: options.tunnelTlsAddr,
113
- tunnelTlsServername,
114
- }
115
- : {}),
116
- tunnelTlsCa: extraTlsCa,
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
- // VENDOR DELTA: upstream logs through `console.log`/`console.warn`,
128
- // which would write to STDOUT and corrupt `--output json` — a hard
129
- // contract in this CLI. The default sink is stderr-only, and the CLI
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.reconnectDelayController.signal.aborted) {
145
- this.reconnectDelayController = new AbortController();
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
- this.controlLoopTask = this.runControlLoop();
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 === expectedConnectionGeneration) {
147
+ if (connectionGeneration >= expectedConnectionGeneration) {
168
148
  settle(resolve);
169
149
  }
170
150
  };
171
151
  const onAuthenticationFailed = (connectionGeneration, error) => {
172
- if (connectionGeneration === expectedConnectionGeneration) {
152
+ if (connectionGeneration >= expectedConnectionGeneration) {
173
153
  settle(() => reject(error));
174
154
  }
175
155
  };
176
- const onLoopEnd = () => {
177
- settle(() => reject(new Error("Control loop ended before connecting")));
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.beginStop();
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.revoked
199
+ const message = err.reason.trim().toUpperCase() === "CLIENT_REVOKED"
204
200
  ? "tunnel credential revoked"
205
- : err.acknowledged
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.reconnectDelayController.abort();
207
+ this.lifecycleController.abort();
211
208
  this.controlConnected = false;
212
209
  this.stopAllTunnelRuntimes();
213
210
  return;
214
211
  }
215
- this.reportError(ErrCode.ControlDisconnected, `Control disconnected: ${toErrorMessage(err)}`);
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.reconnectDelayController.signal);
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.recordDataPlaneFailure(tunnelConnectionId, runtime, safeErrorMessage);
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.reconnectDelayController.signal);
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 authenticationAcknowledged = false;
306
+ let authenticated = false;
268
307
  const failAuthentication = (error) => {
269
- if (authenticationSettled) {
270
- return;
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
- authenticationAcknowledged = true;
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
- failAuthentication(new Error(`Control websocket errored before authentication was acknowledged: ${toErrorMessage(err)}`));
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
- failAuthentication(new Error(`Control websocket closed before authentication was acknowledged (code=${code}, reason=${reason || "<empty>"})`));
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, authenticationAcknowledged));
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.clearDataPlaneAttemptTimers(runtime);
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 interrupted = () => !this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect;
456
- const rejectAttempt = (error) => {
457
- this.clearDataPlaneAttemptTimers(runtime);
458
- if (interrupted()) {
459
- settle(resolve);
513
+ const markEstablished = () => {
514
+ if (established
515
+ || settled
516
+ || !this.running
517
+ || !this.allowTunnelReconnect
518
+ || runtime.stopRetryOnDisconnect) {
460
519
  return;
461
520
  }
462
- settle(() => {
463
- if (!socket.destroyed) {
464
- socket.destroy();
465
- }
466
- reject(error);
467
- });
521
+ established = true;
522
+ clearSettleTimeout();
523
+ this.clearDataPlaneFailureEpisode(runtime);
468
524
  };
469
525
  socket.once("error", (err) => {
470
- if (!runtime.sessionEstablished) {
471
- rejectAttempt(err);
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 (interrupted()) {
536
+ if (!this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
484
537
  resolve();
485
538
  return;
486
539
  }
487
- if (!runtime.sessionEstablished) {
488
- const underlyingError = socket.errored;
489
- reject(underlyingError instanceof Error
490
- ? underlyingError
491
- : new Error(transportConnected && helloWritten
492
- ? `Tunnel ${transport} connection closed before the session was established`
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
- resolve();
548
+ reject(new Error(`Tunnel ${this.transport} connection closed before the session was established`));
497
549
  });
498
550
  };
499
- socket.once(transport === "tls" ? "secureConnect" : "connect", () => {
500
- if (runtime.connectTimer !== undefined) {
501
- clearTimeout(runtime.connectTimer);
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
- rejectAttempt(error);
567
+ settle(() => reject(error));
568
+ socket.destroy();
520
569
  return;
521
570
  }
522
- if (settled || interrupted()) {
571
+ if (settled || socket.destroyed) {
523
572
  return;
524
573
  }
525
574
  helloWritten = true;
526
- if (!runtime.sessionEstablished) {
527
- runtime.settleTimer = setTimeout(() => {
528
- runtime.settleTimer = undefined;
529
- this.markDataPlaneEstablished(runtime);
530
- }, this.options.dataPlaneSettleMs);
531
- runtime.settleTimer.unref();
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 (err) {
556
- rejectAttempt(err instanceof Error ? err : new Error(String(err)));
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
- recordDataPlaneFailure(tunnelConnectionId, runtime, errorMessage) {
574
- runtime.lastFailureMessage = errorMessage;
575
- if (runtime.failureEpisodeStartedAt !== undefined
576
- || this.options.dataPlaneRetryDeadlineMs === 0) {
577
- return;
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
- runtime.failureEpisodeStartedAt = performance.now();
580
- this.armDataPlaneFailureDeadline(tunnelConnectionId, runtime);
631
+ return net.connect({
632
+ host: this.tunnelAddress.host,
633
+ port: this.tunnelAddress.port,
634
+ });
581
635
  }
582
- armDataPlaneFailureDeadline(tunnelConnectionId, runtime) {
636
+ openDataPlaneFailureEpisode(runtime, safeErrorMessage) {
637
+ runtime.lastFailureMessage = safeErrorMessage;
583
638
  const deadlineMs = this.options.dataPlaneRetryDeadlineMs;
584
- const startedAt = runtime.failureEpisodeStartedAt;
585
- if (deadlineMs === 0 || startedAt === undefined) {
639
+ if (deadlineMs === 0 || runtime.failureDeadline)
586
640
  return;
587
- }
588
- const elapsedMs = performance.now() - startedAt;
589
- const remainingMs = Math.max(0, Math.ceil(deadlineMs - elapsedMs));
590
- runtime.failureDeadlineTimer = setTimeout(() => {
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.failureDeadlineTimer.unref();
646
+ runtime.failureDeadline.unref();
595
647
  }
596
- expireDataPlaneFailureEpisode(tunnelConnectionId, runtime) {
597
- if (!this.running
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
- this.clearDataPlaneAttemptTimers(runtime);
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
- if (!this.dataPlaneTerminalErrorReported) {
611
- this.dataPlaneTerminalErrorReported = true;
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.beginStop();
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.failureDeadlineTimer !== undefined) {
644
- clearTimeout(runtime.failureDeadlineTimer);
645
- runtime.failureDeadlineTimer = undefined;
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
- // VENDOR DELTA: destroy every outstanding proxy target socket. See the
663
- // `activeTargetSockets` field comment. Iterate a copy: destroy() emits
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 (err instanceof YamuxStreamResetError) {
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
- // `host`/`port` here are the `target_host`/`target_port` relayed verbatim from the inbound
790
- // proxy request on the internet-facing proxy port — untrusted input as far as this client
791
- // is concerned. Resolve once, validate the exact resolved candidate set, then dial that same
792
- // set (never the original hostname): a name that later rebinds to a different address can't
793
- // slip through, because there is no second, independent lookup between the check and the
794
- // dial. Mirrors `connect_target`/`ensure_candidates_are_loopback` in the Rust client.
795
- const candidates = await resolveDialCandidates(host, port);
796
- ensureTargetAllowed(host, port, candidates, this.options.allowPrivateNetworkTarget);
797
- let lastError;
798
- for (const candidate of candidates) {
799
- try {
800
- return await this.connectOnce(candidate.host, candidate.port);
801
- }
802
- catch (err) {
803
- lastError = err;
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
- this.options.onError({ code, message });
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
- // VENDOR DELTA: classify IPv6 loopback and embedded-IPv4 spaces with binary `net.BlockList`
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
- // VENDOR DELTA: `::/32` and `64:ff9b::/32` rather than the narrower canonical-form
1014
- // prefixes (`::/96`, and `64:ff9b::/96` + `64:ff9b:1::/48`) alone. Each /32 is the
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.length === 0 || /\s|[/?#@]/u.test(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 <= 1
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.indexOf(":");
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+$/u.test(portPart)) {
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
- return {
1186
- host: hostPart,
1187
- port,
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
- revoked;
1215
- acknowledged;
1216
- constructor(code, reason, acknowledged) {
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
- this.revoked = reason.trim().toUpperCase() === "CLIENT_REVOKED";
1220
- this.acknowledged = acknowledged;
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
- const normalizedReason = reason.trim().toUpperCase();
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