@testsprite/testsprite-cli 0.9.0 → 0.11.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 (43) hide show
  1. package/README.md +64 -41
  2. package/dist/commands/auth.d.ts +5 -1
  3. package/dist/commands/auth.js +17 -5
  4. package/dist/commands/init.d.ts +6 -1
  5. package/dist/commands/init.js +13 -5
  6. package/dist/commands/project.d.ts +30 -0
  7. package/dist/commands/project.js +193 -27
  8. package/dist/commands/test.d.ts +14 -2
  9. package/dist/commands/test.js +141 -33
  10. package/dist/commands/tunnel.d.ts +2 -2
  11. package/dist/commands/tunnel.js +139 -31
  12. package/dist/index.js +29 -11
  13. package/dist/lib/client-factory.d.ts +4 -1
  14. package/dist/lib/client-factory.js +12 -4
  15. package/dist/lib/credentials.d.ts +4 -0
  16. package/dist/lib/credentials.js +43 -4
  17. package/dist/lib/dry-run/samples.js +16 -9
  18. package/dist/lib/http.d.ts +14 -2
  19. package/dist/lib/http.js +38 -6
  20. package/dist/lib/response-schemas.d.ts +5 -2
  21. package/dist/lib/response-schemas.js +21 -1
  22. package/dist/lib/runs.types.d.ts +11 -0
  23. package/dist/lib/target-url.d.ts +1 -1
  24. package/dist/lib/target-url.js +4 -0
  25. package/dist/lib/telemetry.d.ts +6 -2
  26. package/dist/lib/telemetry.js +12 -0
  27. package/dist/lib/tunnel-session.d.ts +13 -2
  28. package/dist/lib/tunnel-session.js +92 -23
  29. package/dist/lib/tunnel.types.d.ts +3 -1
  30. package/dist/vendor/tunnel-client/client.d.ts +11 -0
  31. package/dist/vendor/tunnel-client/client.js +383 -56
  32. package/dist/vendor/tunnel-client/config.d.ts +11 -3
  33. package/dist/vendor/tunnel-client/config.js +11 -3
  34. package/dist/vendor/tunnel-client/types.d.ts +26 -1
  35. package/dist/vendor/tunnel-client/types.js +1 -0
  36. package/dist/vendor/tunnel-client/ws-compat.d.ts +3 -2
  37. package/dist/vendor/tunnel-client/ws-compat.js +3 -2
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/package.json +2 -1
  41. package/skills/testsprite-onboard.skill.md +80 -59
  42. package/skills/testsprite-verify.codex.md +82 -97
  43. package/skills/testsprite-verify.skill.md +67 -16
@@ -1,6 +1,12 @@
1
+ // VENDOR DELTA: terminal 1008 auth closes distinguish revocation and
2
+ // post-Ack takeover from initial authentication failure. See ./VENDOR.md #16.
1
3
  import { EventEmitter, once } from "node:events";
2
4
  import dns from "node:dns";
5
+ import { readFileSync } from "node:fs";
3
6
  import net from "node:net";
7
+ import { performance } from "node:perf_hooks";
8
+ import tls from "node:tls";
9
+ import { domainToASCII } from "node:url";
4
10
  // VENDOR DELTA: `ws` -> undici-backed facade. See ./ws-compat.ts.
5
11
  import WebSocket from "./ws-compat.js";
6
12
  // VENDOR DELTA: `lodash` -> three local predicates. See ./lodash-lite.ts.
@@ -9,7 +15,7 @@ import { encodeFrame, readTypedFrame } from "./protocol.js";
9
15
  // VENDOR DELTA: no CLIENT_VERSION (no package.json import) and no endpoint
10
16
  // defaults — `controlUrl`/`tunnelAddr` are required and come from the mint
11
17
  // response. See ./config.ts.
12
- import { DEFAULT_ALLOW_PRIVATE_NETWORK_TARGET, DEFAULT_AUTH_TIMEOUT_MS, DEFAULT_HEARTBEAT_MS, DEFAULT_LOG_LEVEL, DEFAULT_RECONNECT_MS, DEFAULT_TARGET_CONNECT_TIMEOUT_MS, } from "./config.js";
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";
13
19
  import { ErrCode, } from "./types.js";
14
20
  import { Client as createYamuxClientSession, YamuxStreamResetError, } from "@llmcode/yamux-ts";
15
21
  // VENDOR DELTA: `Record<string, number>` -> `Record<LogLevel, number>`, and
@@ -27,6 +33,8 @@ const STREAM_CLOSE_TIMEOUT_MS = 1_500;
27
33
  const CONTROL_AUTHENTICATION_FAILED = Symbol("control-authentication-failed");
28
34
  export class TunnelClient extends EventEmitter {
29
35
  options;
36
+ #transportMode;
37
+ tunnelAddress;
30
38
  running = false;
31
39
  controlConnected = false;
32
40
  controlWs;
@@ -36,6 +44,7 @@ export class TunnelClient extends EventEmitter {
36
44
  // an older socket cannot satisfy a later start() wait. See VENDOR.md #14.
37
45
  controlConnectionGeneration = 0;
38
46
  allowTunnelReconnect = true;
47
+ dataPlaneTerminalErrorReported = false;
39
48
  tunnelRuntimes = new Map();
40
49
  // VENDOR DELTA: reconnect backoffs are tied to this lifecycle controller so stop() cancels
41
50
  // both control and tunnel sleeps instead of awaiting a still-ref'd timer. See VENDOR.md #9.
@@ -55,11 +64,60 @@ export class TunnelClient extends EventEmitter {
55
64
  if (!options.clientId || !options.secret) {
56
65
  throw new Error("clientId and secret are required");
57
66
  }
67
+ const configuredPlaintextAddress = parseTunnelAddr(options.tunnelAddr);
68
+ const deadlineMs = options.dataPlaneRetryDeadlineMs ?? DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS;
69
+ if (!Number.isInteger(deadlineMs) || deadlineMs < 0) {
70
+ throw new RangeError("dataPlaneRetryDeadlineMs must be a non-negative integer");
71
+ }
72
+ const settleMs = options.dataPlaneSettleMs ?? DEFAULT_DATA_PLANE_SETTLE_MS;
73
+ if (!Number.isInteger(settleMs) || settleMs < 0) {
74
+ throw new RangeError("dataPlaneSettleMs must be a non-negative integer");
75
+ }
76
+ const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
77
+ if (!Number.isInteger(connectTimeoutMs) || connectTimeoutMs < 0) {
78
+ throw new RangeError("connectTimeoutMs must be a non-negative integer");
79
+ }
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");
83
+ }
84
+ 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) {
89
+ throw new Error("tunnelTlsServername is required when tunnelTlsAddr uses an IP-literal host");
90
+ }
91
+ tunnelTlsServername = options.tunnelTlsServername ?? tunnelTlsAddress.host;
92
+ if (tunnelTlsServername.trim().length === 0) {
93
+ throw new Error("tunnelTlsServername must not be empty");
94
+ }
95
+ }
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];
58
105
  this.options = {
59
106
  clientId: options.clientId,
60
107
  secret: options.secret,
61
108
  controlUrl: options.controlUrl,
62
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,
63
121
  authTimeoutMs: options.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS,
64
122
  heartbeatMs: options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS,
65
123
  reconnectMs: options.reconnectMs ?? DEFAULT_RECONNECT_MS,
@@ -76,6 +134,9 @@ export class TunnelClient extends EventEmitter {
76
134
  }),
77
135
  };
78
136
  }
137
+ get transport() {
138
+ return this.#transportMode;
139
+ }
79
140
  async start() {
80
141
  if (this.running) {
81
142
  return;
@@ -84,6 +145,7 @@ export class TunnelClient extends EventEmitter {
84
145
  this.reconnectDelayController = new AbortController();
85
146
  }
86
147
  this.running = true;
148
+ this.dataPlaneTerminalErrorReported = false;
87
149
  const expectedConnectionGeneration = this.controlConnectionGeneration + 1;
88
150
  this.controlLoopTask = this.runControlLoop();
89
151
  await new Promise((resolve, reject) => {
@@ -124,20 +186,7 @@ export class TunnelClient extends EventEmitter {
124
186
  this.log("info", "Tunnel client started");
125
187
  }
126
188
  async stop() {
127
- this.running = false;
128
- this.reconnectDelayController.abort();
129
- // VENDOR DELTA: also close a socket still in CONNECTING. Upstream only
130
- // closes an OPEN one, so a control plane that accepts TCP and never
131
- // completes the WebSocket handshake leaves the socket untouched — and the
132
- // `await this.controlLoopTask` below then waits on the very handshake
133
- // nothing is going to finish. `stop()` never returns, so the caller's
134
- // teardown never reaches the credential delete that follows it.
135
- if (this.controlWs &&
136
- (this.controlWs.readyState === WebSocket.OPEN ||
137
- this.controlWs.readyState === WebSocket.CONNECTING)) {
138
- this.controlWs.close();
139
- }
140
- this.stopAllTunnelRuntimes();
189
+ this.beginStop();
141
190
  const tunnelTasks = Array.from(this.tunnelRuntimes.values(), (runtime) => runtime.task);
142
191
  await Promise.allSettled([this.controlLoopTask, ...tunnelTasks]);
143
192
  this.controlWs = undefined;
@@ -151,9 +200,14 @@ export class TunnelClient extends EventEmitter {
151
200
  }
152
201
  catch (err) {
153
202
  if (isControlAuthFailureError(err)) {
154
- const message = `Control authentication failed, stop reconnecting: ${toErrorMessage(err)}`;
203
+ const message = err.revoked
204
+ ? "tunnel credential revoked"
205
+ : err.acknowledged
206
+ ? "tunnel connection superseded or credential revoked"
207
+ : `Control authentication failed, stop reconnecting: ${toErrorMessage(err)}`;
155
208
  this.reportError(ErrCode.AuthFailed, message, "error");
156
209
  this.running = false;
210
+ this.reconnectDelayController.abort();
157
211
  this.controlConnected = false;
158
212
  this.stopAllTunnelRuntimes();
159
213
  return;
@@ -175,7 +229,13 @@ export class TunnelClient extends EventEmitter {
175
229
  await this.connectTunnel(tunnelConnectionId, runtime);
176
230
  }
177
231
  catch (err) {
178
- this.reportError(ErrCode.TunnelDisconnected, `Tunnel ${tunnelConnectionId} disconnected: ${toErrorMessage(err)}`);
232
+ if (!this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
233
+ return;
234
+ }
235
+ const errorMessage = toErrorMessage(err);
236
+ const safeErrorMessage = redactSecret(errorMessage, this.options.secret);
237
+ this.recordDataPlaneFailure(tunnelConnectionId, runtime, safeErrorMessage);
238
+ this.reportError(ErrCode.TunnelDisconnected, `Tunnel ${tunnelConnectionId} disconnected: ${safeErrorMessage}`);
179
239
  }
180
240
  if (!this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
181
241
  this.log("info", `Tunnel ${tunnelConnectionId} reconnect disabled`);
@@ -187,6 +247,8 @@ export class TunnelClient extends EventEmitter {
187
247
  }
188
248
  }
189
249
  finally {
250
+ this.clearDataPlaneAttemptTimers(runtime);
251
+ this.clearDataPlaneFailureEpisode(runtime);
190
252
  runtime.socket = undefined;
191
253
  runtime.session = undefined;
192
254
  this.tunnelRuntimes.delete(tunnelConnectionId);
@@ -202,6 +264,7 @@ export class TunnelClient extends EventEmitter {
202
264
  let heartbeatTimer;
203
265
  let opened = false;
204
266
  let authenticationSettled = false;
267
+ let authenticationAcknowledged = false;
205
268
  const failAuthentication = (error) => {
206
269
  if (authenticationSettled) {
207
270
  return;
@@ -252,6 +315,7 @@ export class TunnelClient extends EventEmitter {
252
315
  return;
253
316
  }
254
317
  if (message.type === "Ack") {
318
+ authenticationAcknowledged = true;
255
319
  if (!authenticationSettled) {
256
320
  authenticationSettled = true;
257
321
  this.emit("control-authenticated", connectionGeneration);
@@ -290,7 +354,7 @@ export class TunnelClient extends EventEmitter {
290
354
  failAuthentication(new Error(`Control websocket closed before authentication was acknowledged (code=${code}, reason=${reason || "<empty>"})`));
291
355
  this.log("warn", `Control websocket closed (code=${code}, reason=${reason || "<empty>"})`);
292
356
  if (isAuthFailureClose(code, reason)) {
293
- reject(new ControlAuthFailureError(code, reason));
357
+ reject(new ControlAuthFailureError(code, reason, authenticationAcknowledged));
294
358
  return;
295
359
  }
296
360
  resolve();
@@ -353,6 +417,7 @@ export class TunnelClient extends EventEmitter {
353
417
  }
354
418
  const runtime = {
355
419
  stopRetryOnDisconnect: false,
420
+ sessionEstablished: false,
356
421
  task: Promise.resolve(),
357
422
  };
358
423
  runtime.task = this.runTunnelLoop(tunnelConnectionId, runtime);
@@ -361,13 +426,24 @@ export class TunnelClient extends EventEmitter {
361
426
  }
362
427
  connectTunnel(tunnelConnectionId, runtime) {
363
428
  return new Promise((resolve, reject) => {
364
- const tunnelAddress = parseTunnelAddr(this.options.tunnelAddr);
365
- const socket = net.connect({
366
- host: tunnelAddress.host,
367
- port: tunnelAddress.port,
368
- });
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
+ });
369
444
  runtime.socket = socket;
370
- let handshakeDone = false;
445
+ let transportConnected = false;
446
+ let helloWritten = false;
371
447
  let settled = false;
372
448
  const settle = (next) => {
373
449
  if (settled) {
@@ -376,59 +452,206 @@ export class TunnelClient extends EventEmitter {
376
452
  settled = true;
377
453
  next();
378
454
  };
455
+ const interrupted = () => !this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect;
456
+ const rejectAttempt = (error) => {
457
+ this.clearDataPlaneAttemptTimers(runtime);
458
+ if (interrupted()) {
459
+ settle(resolve);
460
+ return;
461
+ }
462
+ settle(() => {
463
+ if (!socket.destroyed) {
464
+ socket.destroy();
465
+ }
466
+ reject(error);
467
+ });
468
+ };
379
469
  socket.once("error", (err) => {
380
- if (!handshakeDone) {
381
- settle(() => reject(err));
470
+ if (!runtime.sessionEstablished) {
471
+ rejectAttempt(err);
382
472
  }
383
473
  });
384
474
  const finalizeClose = () => {
475
+ this.clearDataPlaneAttemptTimers(runtime);
476
+ if (runtime.socket === socket) {
477
+ runtime.socket = undefined;
478
+ runtime.session = undefined;
479
+ }
385
480
  settle(() => {
386
481
  this.emit("tunnel-disconnected", tunnelConnectionId);
387
482
  this.log("warn", `Tunnel tcp closed: ${tunnelConnectionId}`);
483
+ if (interrupted()) {
484
+ resolve();
485
+ return;
486
+ }
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`));
494
+ return;
495
+ }
388
496
  resolve();
389
497
  });
390
498
  };
391
- socket.once("connect", () => {
392
- if (!this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
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()) {
393
506
  socket.destroy();
394
507
  settle(resolve);
395
508
  return;
396
509
  }
397
- this.log("info", `Tunnel tcp connected: ${tunnelConnectionId}`);
510
+ this.log("info", `Tunnel ${transport} connected: ${tunnelConnectionId}`);
398
511
  const hello = {
399
512
  client_id: this.options.clientId,
400
513
  secret: this.options.secret,
401
514
  tunnel_connection_id: tunnelConnectionId,
402
515
  };
403
- socket.write(encodeFrame(hello));
404
- handshakeDone = true;
405
- const session = createYamuxClientSession(socket);
406
- runtime.session = session;
407
- session.on("stream", (stream) => {
408
- void this.handleIncomingStream(stream);
409
- });
410
- session.on("error", (err) => {
411
- if (isBenignCloseError(err)) {
412
- this.log("debug", `Yamux benign close (${tunnelConnectionId}): ${toErrorMessage(err)}`);
413
- return;
414
- }
415
- this.log("warn", `Yamux error (${tunnelConnectionId}): ${toErrorMessage(err)}`);
416
- if (!socket.destroyed) {
417
- socket.destroy();
418
- }
419
- });
420
- session.on("close", () => {
421
- this.log("debug", `Yamux session closed: ${tunnelConnectionId}`);
422
- });
423
- this.emit("tunnel-connected", tunnelConnectionId);
516
+ try {
517
+ socket.write(encodeFrame(hello), error => {
518
+ if (error) {
519
+ rejectAttempt(error);
520
+ return;
521
+ }
522
+ if (settled || interrupted()) {
523
+ return;
524
+ }
525
+ 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
+ }
533
+ this.emit("tunnel-connected", tunnelConnectionId);
534
+ });
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
+ }
555
+ catch (err) {
556
+ rejectAttempt(err instanceof Error ? err : new Error(String(err)));
557
+ }
424
558
  });
425
559
  socket.once("close", finalizeClose);
426
560
  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();
427
571
  });
428
572
  }
573
+ recordDataPlaneFailure(tunnelConnectionId, runtime, errorMessage) {
574
+ runtime.lastFailureMessage = errorMessage;
575
+ if (runtime.failureEpisodeStartedAt !== undefined
576
+ || this.options.dataPlaneRetryDeadlineMs === 0) {
577
+ return;
578
+ }
579
+ runtime.failureEpisodeStartedAt = performance.now();
580
+ this.armDataPlaneFailureDeadline(tunnelConnectionId, runtime);
581
+ }
582
+ armDataPlaneFailureDeadline(tunnelConnectionId, runtime) {
583
+ const deadlineMs = this.options.dataPlaneRetryDeadlineMs;
584
+ const startedAt = runtime.failureEpisodeStartedAt;
585
+ if (deadlineMs === 0 || startedAt === undefined) {
586
+ 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);
593
+ }, remainingMs);
594
+ runtime.failureDeadlineTimer.unref();
595
+ }
596
+ expireDataPlaneFailureEpisode(tunnelConnectionId, runtime) {
597
+ if (!this.running
598
+ || !this.allowTunnelReconnect
599
+ || runtime.stopRetryOnDisconnect
600
+ || runtime.failureEpisodeStartedAt === undefined) {
601
+ this.clearDataPlaneFailureEpisode(runtime);
602
+ return;
603
+ }
604
+ runtime.stopRetryOnDisconnect = true;
605
+ this.clearDataPlaneAttemptTimers(runtime);
606
+ if (runtime.socket && !runtime.socket.destroyed) {
607
+ runtime.socket.destroy();
608
+ }
609
+ 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
+ }
616
+ }
617
+ 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;
640
+ }
641
+ }
642
+ clearDataPlaneFailureEpisode(runtime) {
643
+ if (runtime.failureDeadlineTimer !== undefined) {
644
+ clearTimeout(runtime.failureDeadlineTimer);
645
+ runtime.failureDeadlineTimer = undefined;
646
+ }
647
+ runtime.failureEpisodeStartedAt = undefined;
648
+ runtime.lastFailureMessage = undefined;
649
+ }
429
650
  stopAllTunnelRuntimes() {
430
651
  for (const runtime of this.tunnelRuntimes.values()) {
431
652
  runtime.stopRetryOnDisconnect = true;
653
+ this.clearDataPlaneAttemptTimers(runtime);
654
+ this.clearDataPlaneFailureEpisode(runtime);
432
655
  if (runtime.session) {
433
656
  runtime.session.close();
434
657
  }
@@ -447,6 +670,22 @@ export class TunnelClient extends EventEmitter {
447
670
  }
448
671
  this.activeTargetSockets.clear();
449
672
  }
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
+ }
450
689
  async handleIncomingStream(stream) {
451
690
  try {
452
691
  const frame = await readTypedFrame(stream, isStreamOpenRequestFrame);
@@ -630,6 +869,13 @@ function toErrorMessage(err) {
630
869
  }
631
870
  return String(err);
632
871
  }
872
+ function redactSecret(message, secret) {
873
+ return secret.length === 0 ? message : message.replaceAll(secret, "[REDACTED]");
874
+ }
875
+ function formatTunnelAddress(address) {
876
+ const host = net.isIP(address.host) === 6 ? `[${address.host}]` : address.host;
877
+ return `${host}:${address.port}`;
878
+ }
633
879
  function isBenignCloseError(err) {
634
880
  if (err instanceof YamuxStreamResetError) {
635
881
  return true;
@@ -848,34 +1094,110 @@ export function ensureTargetAllowed(host, port, candidates, allowPrivateNetwork)
848
1094
  }
849
1095
  }
850
1096
  }
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
+ }
851
1140
  function parseTunnelAddr(addr) {
1141
+ if (addr.length === 0 || /\s|[/?#@]/u.test(addr)) {
1142
+ throw new Error(`Invalid tunnel address: ${addr}`);
1143
+ }
852
1144
  let hostPart = "";
853
1145
  let portPart = "";
854
1146
  if (addr.startsWith("[")) {
855
1147
  const closing = addr.indexOf("]");
856
- if (closing < 0 || closing + 2 > addr.length || addr[closing + 1] !== ":") {
1148
+ if (closing <= 1
1149
+ || closing !== addr.lastIndexOf("]")
1150
+ || closing + 2 > addr.length
1151
+ || addr[closing + 1] !== ":") {
857
1152
  throw new Error(`Invalid tunnel address: ${addr}`);
858
1153
  }
859
1154
  hostPart = addr.slice(1, closing);
860
1155
  portPart = addr.slice(closing + 2);
1156
+ if (net.isIP(hostPart) !== 6) {
1157
+ throw new Error(`Invalid tunnel address: ${addr}`);
1158
+ }
861
1159
  }
862
1160
  else {
863
- const sep = addr.lastIndexOf(":");
1161
+ const sep = addr.indexOf(":");
864
1162
  if (sep <= 0 || sep === addr.length - 1) {
865
1163
  throw new Error(`Invalid tunnel address: ${addr}`);
866
1164
  }
1165
+ if (sep !== addr.lastIndexOf(":")) {
1166
+ throw new Error(`Invalid tunnel address: ${addr}`);
1167
+ }
867
1168
  hostPart = addr.slice(0, sep);
868
1169
  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
+ }
1178
+ if (!/^\d+$/u.test(portPart)) {
1179
+ throw new Error(`Invalid tunnel address: ${addr}`);
869
1180
  }
870
1181
  const port = Number(portPart);
871
- if (!Number.isInteger(port) || port <= 0 || port > 65535) {
872
- throw new Error(`Invalid tunnel address port: ${addr}`);
1182
+ if (port <= 0 || port > 65535) {
1183
+ throw new Error(`Invalid tunnel address: ${addr}`);
873
1184
  }
874
1185
  return {
875
1186
  host: hostPart,
876
1187
  port,
877
1188
  };
878
1189
  }
1190
+ function canonicalDnsHostname(host) {
1191
+ const ascii = domainToASCII(host).toLowerCase();
1192
+ if (ascii.length === 0 || ascii.length > 253) {
1193
+ return undefined;
1194
+ }
1195
+ const withoutTrailingDot = ascii.endsWith(".") ? ascii.slice(0, -1) : ascii;
1196
+ const valid = withoutTrailingDot.split(".").every((label) => label.length > 0
1197
+ && label.length <= 63
1198
+ && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/iu.test(label));
1199
+ return valid ? ascii : undefined;
1200
+ }
879
1201
  function isStreamOpenRequestFrame(value) {
880
1202
  if (!isPlainObject(value)) {
881
1203
  return false;
@@ -889,9 +1211,13 @@ function isStreamOpenRequestFrame(value) {
889
1211
  && isNumber(frame.target_port);
890
1212
  }
891
1213
  class ControlAuthFailureError extends Error {
892
- constructor(code, reason) {
1214
+ revoked;
1215
+ acknowledged;
1216
+ constructor(code, reason, acknowledged) {
893
1217
  super(`control auth failure (code=${code}, reason=${reason || "unknown"})`);
894
1218
  this.name = "ControlAuthFailureError";
1219
+ this.revoked = reason.trim().toUpperCase() === "CLIENT_REVOKED";
1220
+ this.acknowledged = acknowledged;
895
1221
  }
896
1222
  }
897
1223
  class TargetConnectError extends Error {
@@ -919,6 +1245,7 @@ function isControlAuthFailureError(err) {
919
1245
  return err instanceof ControlAuthFailureError;
920
1246
  }
921
1247
  function isAuthFailureClose(code, reason) {
922
- return code === 1008 && reason.trim().toUpperCase() === "AUTH_FAILED";
1248
+ const normalizedReason = reason.trim().toUpperCase();
1249
+ return code === 1008 && (normalizedReason === "AUTH_FAILED" || normalizedReason === "CLIENT_REVOKED");
923
1250
  }
924
1251
  //# sourceMappingURL=client.js.map
@@ -7,9 +7,9 @@
7
7
  * - the endpoints are internal infrastructure names, and a default value is
8
8
  * still a value that ships;
9
9
  * - a default endpoint is the failure mode the facade exists to prevent.
10
- * `POST /api/cli/v1/tunnel` returns `controlUrl` and `tunnelAddr` for the
11
- * environment the caller authenticated against, and those are the ONLY
12
- * endpoints this client may dial. A default would let a
10
+ * `POST /api/cli/v1/tunnel` returns `controlUrl`, `tunnelAddr`, and
11
+ * optionally `tunnelTlsAddr` for the environment the caller authenticated
12
+ * against, and those are the ONLY endpoints this client may dial. A default would let a
13
13
  * misconfigured/partially-constructed client silently connect somewhere
14
14
  * else and fail in a way that reads like an auth problem.
15
15
  *
@@ -28,6 +28,14 @@ export declare const DEFAULT_HEARTBEAT_MS = 10000;
28
28
  * accepted the transport but never authenticated it.
29
29
  */
30
30
  export declare const DEFAULT_AUTH_TIMEOUT_MS = 10000;
31
+ /** Maximum time allowed for each plaintext TCP connect. */
32
+ export declare const DEFAULT_CONNECT_TIMEOUT_MS = 10000;
33
+ /** Maximum time allowed for each TLS connect + handshake. */
34
+ export declare const DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS = 10000;
35
+ /** Retry window after the first failed data-plane dial. Zero retries forever. */
36
+ export declare const DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS = 60000;
37
+ /** Post-hello interval after which an otherwise-idle data-plane session is established. */
38
+ export declare const DEFAULT_DATA_PLANE_SETTLE_MS = 5000;
31
39
  /** Delay between control/tunnel reconnect attempts. Upstream default. */
32
40
  export declare const DEFAULT_RECONNECT_MS = 3000;
33
41
  /** Log verbosity floor. Upstream default. */