@testsprite/testsprite-cli 0.7.0 → 0.9.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 (74) hide show
  1. package/README.md +62 -45
  2. package/dist/commands/agent.d.ts +3 -0
  3. package/dist/commands/agent.js +79 -10
  4. package/dist/commands/ci.d.ts +88 -0
  5. package/dist/commands/ci.js +432 -0
  6. package/dist/commands/doctor.js +100 -1
  7. package/dist/commands/init.d.ts +45 -2
  8. package/dist/commands/init.js +198 -29
  9. package/dist/commands/project.d.ts +78 -0
  10. package/dist/commands/project.js +439 -5
  11. package/dist/commands/test.d.ts +193 -4
  12. package/dist/commands/test.js +1948 -398
  13. package/dist/commands/testlist.js +15 -9
  14. package/dist/commands/tunnel.d.ts +72 -0
  15. package/dist/commands/tunnel.js +367 -0
  16. package/dist/index.js +107 -38
  17. package/dist/lib/agent-detect.d.ts +53 -0
  18. package/dist/lib/agent-detect.js +198 -0
  19. package/dist/lib/dry-run/samples.d.ts +9 -0
  20. package/dist/lib/dry-run/samples.js +116 -0
  21. package/dist/lib/gh-output.d.ts +7 -0
  22. package/dist/lib/gh-output.js +50 -7
  23. package/dist/lib/http.d.ts +104 -0
  24. package/dist/lib/http.js +126 -7
  25. package/dist/lib/interrupt.d.ts +38 -13
  26. package/dist/lib/interrupt.js +130 -15
  27. package/dist/lib/local-target.d.ts +95 -0
  28. package/dist/lib/local-target.js +184 -0
  29. package/dist/lib/plan-poll.d.ts +171 -0
  30. package/dist/lib/plan-poll.js +442 -0
  31. package/dist/lib/plans.types.d.ts +130 -0
  32. package/dist/lib/plans.types.js +31 -0
  33. package/dist/lib/poll-support.d.ts +26 -0
  34. package/dist/lib/poll-support.js +65 -0
  35. package/dist/lib/poll.d.ts +1 -0
  36. package/dist/lib/poll.js +2 -40
  37. package/dist/lib/response-schemas.d.ts +13 -0
  38. package/dist/lib/response-schemas.js +46 -0
  39. package/dist/lib/run-progress.d.ts +41 -0
  40. package/dist/lib/run-progress.js +56 -0
  41. package/dist/lib/runs.types.d.ts +50 -0
  42. package/dist/lib/skill-nudge.d.ts +13 -5
  43. package/dist/lib/skill-nudge.js +40 -14
  44. package/dist/lib/target-url-preflight.js +3 -3
  45. package/dist/lib/target-url.d.ts +54 -8
  46. package/dist/lib/target-url.js +274 -68
  47. package/dist/lib/telemetry.d.ts +11 -0
  48. package/dist/lib/telemetry.js +1 -0
  49. package/dist/lib/ticker.d.ts +8 -0
  50. package/dist/lib/ticker.js +3 -0
  51. package/dist/lib/tunnel-session.d.ts +138 -0
  52. package/dist/lib/tunnel-session.js +249 -0
  53. package/dist/lib/tunnel.types.d.ts +54 -0
  54. package/dist/lib/tunnel.types.js +8 -0
  55. package/dist/vendor/tunnel-client/client.d.ts +82 -0
  56. package/dist/vendor/tunnel-client/client.js +924 -0
  57. package/dist/vendor/tunnel-client/config.d.ts +49 -0
  58. package/dist/vendor/tunnel-client/config.js +50 -0
  59. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  60. package/dist/vendor/tunnel-client/index.js +9 -0
  61. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  62. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  63. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  64. package/dist/vendor/tunnel-client/protocol.js +143 -0
  65. package/dist/vendor/tunnel-client/types.d.ts +101 -0
  66. package/dist/vendor/tunnel-client/types.js +10 -0
  67. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  68. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +2 -1
  72. package/skills/testsprite-onboard.skill.md +60 -4
  73. package/skills/testsprite-verify.codex.md +22 -16
  74. package/skills/testsprite-verify.skill.md +27 -18
@@ -0,0 +1,924 @@
1
+ import { EventEmitter, once } from "node:events";
2
+ import dns from "node:dns";
3
+ import net from "node:net";
4
+ // VENDOR DELTA: `ws` -> undici-backed facade. See ./ws-compat.ts.
5
+ import WebSocket from "./ws-compat.js";
6
+ // VENDOR DELTA: `lodash` -> three local predicates. See ./lodash-lite.ts.
7
+ import { isNumber, isPlainObject, isString } from "./lodash-lite.js";
8
+ import { encodeFrame, readTypedFrame } from "./protocol.js";
9
+ // VENDOR DELTA: no CLIENT_VERSION (no package.json import) and no endpoint
10
+ // defaults — `controlUrl`/`tunnelAddr` are required and come from the mint
11
+ // 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";
13
+ import { ErrCode, } from "./types.js";
14
+ import { Client as createYamuxClientSession, YamuxStreamResetError, } from "@llmcode/yamux-ts";
15
+ // VENDOR DELTA: `Record<string, number>` -> `Record<LogLevel, number>`, and
16
+ // the two `keyof typeof LEVEL_ORDER` parameters below become `LogLevel`. This
17
+ // CLI compiles with `noUncheckedIndexedAccess`, under which indexing a string
18
+ // index signature yields `number | undefined`; a mapped type over the four
19
+ // known levels does not. Type-only — no behaviour change. Worth upstreaming.
20
+ const LEVEL_ORDER = {
21
+ debug: 10,
22
+ info: 20,
23
+ warn: 30,
24
+ error: 40,
25
+ };
26
+ const STREAM_CLOSE_TIMEOUT_MS = 1_500;
27
+ const CONTROL_AUTHENTICATION_FAILED = Symbol("control-authentication-failed");
28
+ export class TunnelClient extends EventEmitter {
29
+ options;
30
+ running = false;
31
+ controlConnected = false;
32
+ controlWs;
33
+ controlLoopTask;
34
+ // VENDOR DELTA: monotonically scopes authentication readiness to one
35
+ // control socket. A reconnect gets a new generation, so an Ack emitted by
36
+ // an older socket cannot satisfy a later start() wait. See VENDOR.md #14.
37
+ controlConnectionGeneration = 0;
38
+ allowTunnelReconnect = true;
39
+ tunnelRuntimes = new Map();
40
+ // VENDOR DELTA: reconnect backoffs are tied to this lifecycle controller so stop() cancels
41
+ // both control and tunnel sleeps instead of awaiting a still-ref'd timer. See VENDOR.md #9.
42
+ reconnectDelayController = new AbortController();
43
+ // VENDOR DELTA: every socket this client dials on behalf of an inbound proxy
44
+ // stream (connectOnce). Tearing down a tunnel data session (runtime.socket)
45
+ // does NOT reach these independent per-stream sockets, and a browser
46
+ // keep-alive target that holds the connection open and sends nothing parks
47
+ // proxyStreams()'s copyOneWay(target, …) forever, so its finally-cleanup never
48
+ // runs. On teardown such ESTABLISHED sockets stay ref'd and keep the event loop
49
+ // alive for the remote's idle timeout (minutes) — the visible symptom is a
50
+ // --local run whose Ctrl-C / --timeout appears to hang. stop()/CloseTunnel
51
+ // destroy these directly. See VENDOR.md #13.
52
+ activeTargetSockets = new Set();
53
+ constructor(options) {
54
+ super();
55
+ if (!options.clientId || !options.secret) {
56
+ throw new Error("clientId and secret are required");
57
+ }
58
+ this.options = {
59
+ clientId: options.clientId,
60
+ secret: options.secret,
61
+ controlUrl: options.controlUrl,
62
+ tunnelAddr: options.tunnelAddr,
63
+ authTimeoutMs: options.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS,
64
+ heartbeatMs: options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS,
65
+ reconnectMs: options.reconnectMs ?? DEFAULT_RECONNECT_MS,
66
+ logLevel: options.logLevel ?? DEFAULT_LOG_LEVEL,
67
+ allowPrivateNetworkTarget: options.allowPrivateNetworkTarget ?? DEFAULT_ALLOW_PRIVATE_NETWORK_TARGET,
68
+ onError: options.onError ?? (() => null),
69
+ // VENDOR DELTA: upstream logs through `console.log`/`console.warn`,
70
+ // which would write to STDOUT and corrupt `--output json` — a hard
71
+ // contract in this CLI. The default sink is stderr-only, and the CLI
72
+ // injects its own so tunnel chatter obeys `--verbose`/`--debug`.
73
+ logSink: options.logSink ??
74
+ ((_level, line) => {
75
+ process.stderr.write(`${line}\n`);
76
+ }),
77
+ };
78
+ }
79
+ async start() {
80
+ if (this.running) {
81
+ return;
82
+ }
83
+ if (this.reconnectDelayController.signal.aborted) {
84
+ this.reconnectDelayController = new AbortController();
85
+ }
86
+ this.running = true;
87
+ const expectedConnectionGeneration = this.controlConnectionGeneration + 1;
88
+ this.controlLoopTask = this.runControlLoop();
89
+ await new Promise((resolve, reject) => {
90
+ let settled = false;
91
+ const cleanup = () => {
92
+ clearTimeout(timeout);
93
+ this.off("control-authenticated", onAuthenticated);
94
+ this.off(CONTROL_AUTHENTICATION_FAILED, onAuthenticationFailed);
95
+ };
96
+ const settle = (callback) => {
97
+ if (settled) {
98
+ return;
99
+ }
100
+ settled = true;
101
+ cleanup();
102
+ callback();
103
+ };
104
+ const onAuthenticated = (connectionGeneration) => {
105
+ if (connectionGeneration === expectedConnectionGeneration) {
106
+ settle(resolve);
107
+ }
108
+ };
109
+ const onAuthenticationFailed = (connectionGeneration, error) => {
110
+ if (connectionGeneration === expectedConnectionGeneration) {
111
+ settle(() => reject(error));
112
+ }
113
+ };
114
+ const onLoopEnd = () => {
115
+ settle(() => reject(new Error("Control loop ended before connecting")));
116
+ };
117
+ this.on("control-authenticated", onAuthenticated);
118
+ this.on(CONTROL_AUTHENTICATION_FAILED, onAuthenticationFailed);
119
+ this.controlLoopTask?.then(onLoopEnd);
120
+ const timeout = setTimeout(() => {
121
+ settle(() => reject(new Error(`The tunnel server accepted the connection but never acknowledged authentication within ${this.options.authTimeoutMs}ms`)));
122
+ }, this.options.authTimeoutMs);
123
+ });
124
+ this.log("info", "Tunnel client started");
125
+ }
126
+ 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();
141
+ const tunnelTasks = Array.from(this.tunnelRuntimes.values(), (runtime) => runtime.task);
142
+ await Promise.allSettled([this.controlLoopTask, ...tunnelTasks]);
143
+ this.controlWs = undefined;
144
+ this.tunnelRuntimes.clear();
145
+ this.log("info", "Tunnel client stopped");
146
+ }
147
+ async runControlLoop() {
148
+ while (this.running) {
149
+ try {
150
+ await this.connectControl();
151
+ }
152
+ catch (err) {
153
+ if (isControlAuthFailureError(err)) {
154
+ const message = `Control authentication failed, stop reconnecting: ${toErrorMessage(err)}`;
155
+ this.reportError(ErrCode.AuthFailed, message, "error");
156
+ this.running = false;
157
+ this.controlConnected = false;
158
+ this.stopAllTunnelRuntimes();
159
+ return;
160
+ }
161
+ this.reportError(ErrCode.ControlDisconnected, `Control disconnected: ${toErrorMessage(err)}`);
162
+ }
163
+ if (this.running) {
164
+ await delay(this.options.reconnectMs, this.reconnectDelayController.signal);
165
+ }
166
+ }
167
+ }
168
+ async runTunnelLoop(tunnelConnectionId, runtime) {
169
+ try {
170
+ while (this.running) {
171
+ if (!this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
172
+ return;
173
+ }
174
+ try {
175
+ await this.connectTunnel(tunnelConnectionId, runtime);
176
+ }
177
+ catch (err) {
178
+ this.reportError(ErrCode.TunnelDisconnected, `Tunnel ${tunnelConnectionId} disconnected: ${toErrorMessage(err)}`);
179
+ }
180
+ if (!this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
181
+ this.log("info", `Tunnel ${tunnelConnectionId} reconnect disabled`);
182
+ return;
183
+ }
184
+ if (this.running) {
185
+ await delay(this.options.reconnectMs, this.reconnectDelayController.signal);
186
+ }
187
+ }
188
+ }
189
+ finally {
190
+ runtime.socket = undefined;
191
+ runtime.session = undefined;
192
+ this.tunnelRuntimes.delete(tunnelConnectionId);
193
+ }
194
+ }
195
+ connectControl() {
196
+ return new Promise((resolve, reject) => {
197
+ const connectionGeneration = ++this.controlConnectionGeneration;
198
+ const controlUrl = new URL(this.options.controlUrl);
199
+ controlUrl.searchParams.set("client_id", this.options.clientId);
200
+ const ws = new WebSocket(controlUrl);
201
+ this.controlWs = ws;
202
+ let heartbeatTimer;
203
+ let opened = false;
204
+ let authenticationSettled = false;
205
+ const failAuthentication = (error) => {
206
+ if (authenticationSettled) {
207
+ return;
208
+ }
209
+ authenticationSettled = true;
210
+ this.emit(CONTROL_AUTHENTICATION_FAILED, connectionGeneration, error);
211
+ };
212
+ const cleanup = () => {
213
+ if (heartbeatTimer) {
214
+ clearInterval(heartbeatTimer);
215
+ }
216
+ };
217
+ ws.on("open", () => {
218
+ opened = true;
219
+ this.controlConnected = true;
220
+ this.log("info", "Control websocket connected");
221
+ this.emit("control-connected");
222
+ this.sendControlMessage(ws, {
223
+ type: "Auth",
224
+ payload: {
225
+ secret: this.options.secret,
226
+ },
227
+ });
228
+ // this.sendControlMessage(ws, {
229
+ // type: "Hello",
230
+ // payload: {
231
+ // client_id: this.options.clientId,
232
+ // version: CLIENT_VERSION,
233
+ // },
234
+ // });
235
+ heartbeatTimer = setInterval(() => {
236
+ if (ws.readyState === WebSocket.OPEN) {
237
+ this.sendControlMessage(ws, { type: "Heartbeat" });
238
+ }
239
+ }, this.options.heartbeatMs);
240
+ });
241
+ ws.on("ping", (data) => {
242
+ if (ws.readyState === WebSocket.OPEN) {
243
+ ws.pong(data);
244
+ }
245
+ });
246
+ ws.on("message", (payload) => {
247
+ const text = typeof payload === "string" ? payload : payload.toString("utf8");
248
+ this.emit("control-message", text);
249
+ this.log("debug", `Control message: ${text}`);
250
+ const message = this.parseControlMessage(text);
251
+ if (!message) {
252
+ return;
253
+ }
254
+ if (message.type === "Ack") {
255
+ if (!authenticationSettled) {
256
+ authenticationSettled = true;
257
+ this.emit("control-authenticated", connectionGeneration);
258
+ }
259
+ return;
260
+ }
261
+ if (message.type === "RequestTunnel") {
262
+ this.log("debug", `RequestTunnel received: ${message.payload.tunnel_connection_id}`);
263
+ this.allowTunnelReconnect = true;
264
+ this.ensureTunnelRuntime(message.payload.tunnel_connection_id);
265
+ return;
266
+ }
267
+ if (message.type === "CloseTunnel") {
268
+ this.allowTunnelReconnect = false;
269
+ this.log("info", `Received close tunnel instruction: ${message.payload.reason}`);
270
+ this.stopAllTunnelRuntimes();
271
+ }
272
+ });
273
+ ws.on("error", (err) => {
274
+ cleanup();
275
+ failAuthentication(new Error(`Control websocket errored before authentication was acknowledged: ${toErrorMessage(err)}`));
276
+ if (!opened) {
277
+ this.controlConnected = false;
278
+ this.stopAllTunnelRuntimes();
279
+ reject(err);
280
+ return;
281
+ }
282
+ this.log("warn", `Control websocket error: ${toErrorMessage(err)}`);
283
+ });
284
+ ws.on("close", (code, reasonBuffer) => {
285
+ cleanup();
286
+ this.controlConnected = false;
287
+ this.stopAllTunnelRuntimes();
288
+ this.emit("control-disconnected");
289
+ const reason = reasonBuffer.toString("utf8");
290
+ failAuthentication(new Error(`Control websocket closed before authentication was acknowledged (code=${code}, reason=${reason || "<empty>"})`));
291
+ this.log("warn", `Control websocket closed (code=${code}, reason=${reason || "<empty>"})`);
292
+ if (isAuthFailureClose(code, reason)) {
293
+ reject(new ControlAuthFailureError(code, reason));
294
+ return;
295
+ }
296
+ resolve();
297
+ });
298
+ });
299
+ }
300
+ sendControlMessage(ws, message) {
301
+ ws.send(JSON.stringify(message));
302
+ }
303
+ parseControlMessage(messageText) {
304
+ try {
305
+ const message = JSON.parse(messageText);
306
+ if (message.type === "Ack") {
307
+ return { type: "Ack" };
308
+ }
309
+ if (message.type === "CloseTunnel") {
310
+ const payload = message.payload;
311
+ if (!isPlainObject(payload) || !isString(payload.reason)) {
312
+ return undefined;
313
+ }
314
+ return {
315
+ type: "CloseTunnel",
316
+ payload: {
317
+ reason: payload.reason,
318
+ },
319
+ };
320
+ }
321
+ if (message.type !== "RequestTunnel" || !isPlainObject(message.payload)) {
322
+ return undefined;
323
+ }
324
+ const payload = message.payload;
325
+ if (!isString(payload.tunnel_connection_id)
326
+ || !isString(payload.target_host)
327
+ || !isNumber(payload.target_port)) {
328
+ return undefined;
329
+ }
330
+ return {
331
+ type: "RequestTunnel",
332
+ payload: {
333
+ tunnel_connection_id: payload.tunnel_connection_id,
334
+ target_host: payload.target_host,
335
+ target_port: payload.target_port,
336
+ },
337
+ };
338
+ }
339
+ catch {
340
+ return undefined;
341
+ }
342
+ }
343
+ ensureTunnelRuntime(tunnelConnectionId) {
344
+ if (!this.running || !this.controlConnected) {
345
+ return;
346
+ }
347
+ const existing = this.tunnelRuntimes.get(tunnelConnectionId);
348
+ if (existing) {
349
+ // If server asks again while runtime is shutting down, restore retry intent.
350
+ existing.stopRetryOnDisconnect = false;
351
+ this.log("debug", `Tunnel runtime already active: ${tunnelConnectionId}`);
352
+ return;
353
+ }
354
+ const runtime = {
355
+ stopRetryOnDisconnect: false,
356
+ task: Promise.resolve(),
357
+ };
358
+ runtime.task = this.runTunnelLoop(tunnelConnectionId, runtime);
359
+ this.tunnelRuntimes.set(tunnelConnectionId, runtime);
360
+ this.log("info", `Starting tunnel runtime on demand: ${tunnelConnectionId}`);
361
+ }
362
+ connectTunnel(tunnelConnectionId, runtime) {
363
+ 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
+ });
369
+ runtime.socket = socket;
370
+ let handshakeDone = false;
371
+ let settled = false;
372
+ const settle = (next) => {
373
+ if (settled) {
374
+ return;
375
+ }
376
+ settled = true;
377
+ next();
378
+ };
379
+ socket.once("error", (err) => {
380
+ if (!handshakeDone) {
381
+ settle(() => reject(err));
382
+ }
383
+ });
384
+ const finalizeClose = () => {
385
+ settle(() => {
386
+ this.emit("tunnel-disconnected", tunnelConnectionId);
387
+ this.log("warn", `Tunnel tcp closed: ${tunnelConnectionId}`);
388
+ resolve();
389
+ });
390
+ };
391
+ socket.once("connect", () => {
392
+ if (!this.running || !this.allowTunnelReconnect || runtime.stopRetryOnDisconnect) {
393
+ socket.destroy();
394
+ settle(resolve);
395
+ return;
396
+ }
397
+ this.log("info", `Tunnel tcp connected: ${tunnelConnectionId}`);
398
+ const hello = {
399
+ client_id: this.options.clientId,
400
+ secret: this.options.secret,
401
+ tunnel_connection_id: tunnelConnectionId,
402
+ };
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);
424
+ });
425
+ socket.once("close", finalizeClose);
426
+ socket.once("end", finalizeClose);
427
+ });
428
+ }
429
+ stopAllTunnelRuntimes() {
430
+ for (const runtime of this.tunnelRuntimes.values()) {
431
+ runtime.stopRetryOnDisconnect = true;
432
+ if (runtime.session) {
433
+ runtime.session.close();
434
+ }
435
+ if (runtime.socket && !runtime.socket.destroyed) {
436
+ runtime.socket.destroy();
437
+ }
438
+ }
439
+ // VENDOR DELTA: destroy every outstanding proxy target socket. See the
440
+ // `activeTargetSockets` field comment. Iterate a copy: destroy() emits
441
+ // 'close' synchronously for an already-connected socket, and that handler
442
+ // deletes from the live set.
443
+ for (const socket of [...this.activeTargetSockets]) {
444
+ if (!socket.destroyed) {
445
+ socket.destroy();
446
+ }
447
+ }
448
+ this.activeTargetSockets.clear();
449
+ }
450
+ async handleIncomingStream(stream) {
451
+ try {
452
+ const frame = await readTypedFrame(stream, isStreamOpenRequestFrame);
453
+ const targetHost = frame.target_host;
454
+ const targetPort = frame.target_port;
455
+ const logContext = `${frame.request_id} (${frame.inbound_request_id}, ${frame.tunnel_connection_id}, stream ${frame.mux_stream_id})`;
456
+ this.log("debug", `Stream open: ${logContext}`);
457
+ this.log("info", `Open request ${logContext}: ${targetHost}:${targetPort}`);
458
+ const target = await this.connectTarget(targetHost, targetPort);
459
+ this.log("debug", `Target connected: ${logContext}`);
460
+ await this.proxyStreams(stream, target, logContext);
461
+ this.log("debug", `Stream proxy finished: ${logContext}`);
462
+ }
463
+ catch (err) {
464
+ if (err instanceof YamuxStreamResetError) {
465
+ this.log("debug", `Stream reset while handling inbound stream: ${toErrorMessage(err)}`);
466
+ }
467
+ else if (err instanceof BlockedTargetError) {
468
+ this.reportError(ErrCode.BlockedTargetRejected, `Rejecting stream open request targeting a blocked (private/internal) address: ${toErrorMessage(err)}`);
469
+ }
470
+ else if (err instanceof TargetConnectError) {
471
+ this.reportError(ErrCode.TargetConnectFailed, `Target connect failed: ${toErrorMessage(err)}`);
472
+ }
473
+ else {
474
+ this.reportError(ErrCode.StreamFailed, `Failed handling tunnel stream: ${toErrorMessage(err)}`);
475
+ }
476
+ if (!stream.destroyed && !isBenignCloseError(err)) {
477
+ stream.destroy();
478
+ }
479
+ }
480
+ }
481
+ async proxyStreams(stream, target, logContext) {
482
+ const onTargetError = (err) => {
483
+ if (isBenignCloseError(err)) {
484
+ this.log("debug", `Target error: ${logContext}: ${toErrorMessage(err)}`);
485
+ }
486
+ else {
487
+ this.log("warn", `Target error: ${logContext}: ${toErrorMessage(err)}`);
488
+ }
489
+ };
490
+ const onStreamError = (err) => {
491
+ if (isBenignCloseError(err)) {
492
+ this.log("debug", `Tunnel stream error: ${logContext}: ${toErrorMessage(err)}`);
493
+ }
494
+ else {
495
+ this.log("warn", `Tunnel stream error: ${logContext}: ${toErrorMessage(err)}`);
496
+ }
497
+ };
498
+ target.on("error", onTargetError);
499
+ stream.on("error", onStreamError);
500
+ target.once("close", () => this.log("debug", `Target close: ${logContext}`));
501
+ stream.once("close", () => this.log("debug", `Tunnel stream close: ${logContext}`));
502
+ target.once("end", () => this.log("debug", `Target end: ${logContext}`));
503
+ stream.once("end", () => this.log("debug", `Tunnel stream end: ${logContext}`));
504
+ try {
505
+ this.log("debug", `Proxy copy start: ${logContext}`);
506
+ const tunnelToTarget = this.copyOneWay(stream, target).then(async () => {
507
+ this.log("debug", `Copy complete tunnel->target: ${logContext}`);
508
+ await endWritable(target);
509
+ this.log("debug", `Half-close target write: ${logContext}`);
510
+ });
511
+ const targetToTunnel = this.copyOneWay(target, stream).then(async () => {
512
+ this.log("debug", `Copy complete target->tunnel: ${logContext}`);
513
+ await endWritable(stream);
514
+ this.log("debug", `Half-close tunnel write: ${logContext}`);
515
+ });
516
+ const results = await Promise.allSettled([tunnelToTarget, targetToTunnel]);
517
+ const severe = results
518
+ .filter((result) => result.status === "rejected")
519
+ .map((result) => result.reason)
520
+ .find((reason) => !isBenignCloseError(reason));
521
+ if (severe) {
522
+ throw severe;
523
+ }
524
+ }
525
+ finally {
526
+ target.off("error", onTargetError);
527
+ stream.off("error", onStreamError);
528
+ const [targetClosed, streamClosed] = await Promise.all([
529
+ waitForClose(target, STREAM_CLOSE_TIMEOUT_MS),
530
+ waitForClose(stream, STREAM_CLOSE_TIMEOUT_MS),
531
+ ]);
532
+ if (!targetClosed && !target.destroyed) {
533
+ this.log("debug", `Force close target after timeout: ${logContext}`);
534
+ target.destroy();
535
+ }
536
+ if (!streamClosed && !stream.destroyed) {
537
+ this.log("debug", `Force close tunnel stream after timeout: ${logContext}`);
538
+ stream.destroy();
539
+ }
540
+ }
541
+ }
542
+ async copyOneWay(readable, writable) {
543
+ for await (const chunk of readable) {
544
+ if (!writable.write(chunk)) {
545
+ await once(writable, "drain");
546
+ }
547
+ }
548
+ }
549
+ async connectTarget(host, port) {
550
+ // `host`/`port` here are the `target_host`/`target_port` relayed verbatim from the inbound
551
+ // proxy request on the internet-facing proxy port — untrusted input as far as this client
552
+ // is concerned. Resolve once, validate the exact resolved candidate set, then dial that same
553
+ // set (never the original hostname): a name that later rebinds to a different address can't
554
+ // slip through, because there is no second, independent lookup between the check and the
555
+ // dial. Mirrors `connect_target`/`ensure_candidates_are_loopback` in the Rust client.
556
+ const candidates = await resolveDialCandidates(host, port);
557
+ ensureTargetAllowed(host, port, candidates, this.options.allowPrivateNetworkTarget);
558
+ let lastError;
559
+ for (const candidate of candidates) {
560
+ try {
561
+ return await this.connectOnce(candidate.host, candidate.port);
562
+ }
563
+ catch (err) {
564
+ lastError = err;
565
+ }
566
+ }
567
+ throw new TargetConnectError(host, port, lastError ?? new Error(`no dial candidates for ${host}:${port}`));
568
+ }
569
+ connectOnce(host, port) {
570
+ return new Promise((resolve, reject) => {
571
+ const socket = net.connect({ host, port });
572
+ // VENDOR DELTA: track from creation so a teardown mid-dial destroys it too;
573
+ // the 'close' handler removes it whether the dial succeeds, fails, or is
574
+ // force-destroyed by stopAllTunnelRuntimes(). See the field comment.
575
+ this.activeTargetSockets.add(socket);
576
+ socket.once("close", () => {
577
+ this.activeTargetSockets.delete(socket);
578
+ });
579
+ const onError = (err) => {
580
+ cleanup();
581
+ if (!socket.destroyed) {
582
+ socket.destroy();
583
+ }
584
+ reject(err);
585
+ };
586
+ const onConnect = () => {
587
+ cleanup();
588
+ resolve(socket);
589
+ };
590
+ const timeout = setTimeout(() => {
591
+ onError(new Error(`connect timeout ${DEFAULT_TARGET_CONNECT_TIMEOUT_MS}ms`));
592
+ }, DEFAULT_TARGET_CONNECT_TIMEOUT_MS);
593
+ const cleanup = () => {
594
+ clearTimeout(timeout);
595
+ socket.off("error", onError);
596
+ socket.off("connect", onConnect);
597
+ };
598
+ socket.once("error", onError);
599
+ socket.once("connect", onConnect);
600
+ });
601
+ }
602
+ log(level, message) {
603
+ if (LEVEL_ORDER[level] < LEVEL_ORDER[this.options.logLevel]) {
604
+ return;
605
+ }
606
+ this.options.logSink(level, `[TunnelClient] [${level}] ${message}`);
607
+ }
608
+ reportError(code, message, level = "warn") {
609
+ this.options.onError({ code, message });
610
+ this.log(level, message);
611
+ }
612
+ }
613
+ function delay(ms, signal) {
614
+ if (signal?.aborted) {
615
+ return Promise.resolve();
616
+ }
617
+ return new Promise((resolve) => {
618
+ const finish = () => {
619
+ clearTimeout(timer);
620
+ signal?.removeEventListener("abort", finish);
621
+ resolve();
622
+ };
623
+ const timer = setTimeout(finish, ms);
624
+ signal?.addEventListener("abort", finish, { once: true });
625
+ });
626
+ }
627
+ function toErrorMessage(err) {
628
+ if (err instanceof Error) {
629
+ return err.message;
630
+ }
631
+ return String(err);
632
+ }
633
+ function isBenignCloseError(err) {
634
+ if (err instanceof YamuxStreamResetError) {
635
+ return true;
636
+ }
637
+ if (!(err instanceof Error)) {
638
+ return false;
639
+ }
640
+ const e = err;
641
+ return e.code === "ECONNRESET"
642
+ || e.code === "EPIPE"
643
+ || e.code === "ECONNABORTED"
644
+ || e.code === "ERR_STREAM_PREMATURE_CLOSE"
645
+ || e.code === "ABORT_ERR"
646
+ || e.name === "AbortError"
647
+ || e.message === "The operation was aborted";
648
+ }
649
+ async function waitForClose(stream, timeoutMs) {
650
+ if (stream.destroyed) {
651
+ return true;
652
+ }
653
+ const closed = new Promise((resolve) => {
654
+ const onClose = () => {
655
+ cleanup();
656
+ resolve(true);
657
+ };
658
+ const onEnd = () => {
659
+ cleanup();
660
+ resolve(true);
661
+ };
662
+ const cleanup = () => {
663
+ stream.off("close", onClose);
664
+ stream.off("end", onEnd);
665
+ };
666
+ stream.once("close", onClose);
667
+ stream.once("end", onEnd);
668
+ });
669
+ const timeout = delay(timeoutMs).then(() => false);
670
+ return Promise.race([closed, timeout]);
671
+ }
672
+ async function endWritable(stream) {
673
+ const typed = stream;
674
+ if (typed.destroyed || typed.writableEnded) {
675
+ return;
676
+ }
677
+ await new Promise((resolve) => {
678
+ stream.end(() => resolve());
679
+ });
680
+ }
681
+ function dedupeCandidates(candidates) {
682
+ const seen = new Set();
683
+ const result = [];
684
+ for (const candidate of candidates) {
685
+ const key = `${candidate.host}:${candidate.port}`;
686
+ if (seen.has(key)) {
687
+ continue;
688
+ }
689
+ seen.add(key);
690
+ result.push(candidate);
691
+ }
692
+ return result;
693
+ }
694
+ /**
695
+ * Resolve `host:port` to the exact set of addresses a dial will be attempted against.
696
+ *
697
+ * Mirrors the Rust client's `dial_candidates`: for `localhost` (case-insensitive), `127.0.0.1`
698
+ * and `::1` are added up front; the host is then also resolved normally (an IP literal parses
699
+ * without touching the network, exactly like Rust's `to_socket_addrs`; anything else goes
700
+ * through `dns.lookup`, i.e. getaddrinfo, honoring `/etc/hosts`), and any additional resolved
701
+ * addresses are appended, deduplicated.
702
+ *
703
+ * Callers must validate and dial this exact returned list — re-resolving `host` a second time
704
+ * reopens the DNS-rebind window this function exists to close.
705
+ */
706
+ export async function resolveDialCandidates(host, port) {
707
+ const candidates = [];
708
+ if (host.toLowerCase() === "localhost") {
709
+ candidates.push({ host: "127.0.0.1", port });
710
+ candidates.push({ host: "::1", port });
711
+ }
712
+ for (const address of await resolveHostAddresses(host)) {
713
+ candidates.push({ host: address, port });
714
+ }
715
+ return dedupeCandidates(candidates);
716
+ }
717
+ /** Resolve `host` to literal IP address strings. Returns `[]` if resolution fails (swallowed,
718
+ * matching the Rust side's `if let Ok(resolved) = ...`), never rejects. */
719
+ async function resolveHostAddresses(host) {
720
+ if (net.isIP(host) !== 0) {
721
+ // Already a literal (v4 or v6) — no DNS involved, same as Rust's `to_socket_addrs` parsing
722
+ // an IP literal directly.
723
+ return [host];
724
+ }
725
+ try {
726
+ const results = await dns.promises.lookup(host, { all: true });
727
+ return results.map((entry) => entry.address);
728
+ }
729
+ catch {
730
+ return [];
731
+ }
732
+ }
733
+ /**
734
+ * Why `address` (a literal IPv4 or IPv6 address, e.g. from {@link resolveDialCandidates}) must not
735
+ * be dialled, or `undefined` if it is acceptable. Mirrors the Rust client's
736
+ * `blocked_target_reason` — the two must agree exactly, or the same request succeeds on one
737
+ * client and fails on the other.
738
+ *
739
+ * Acceptable = loopback (the app under test) or a globally-routable address (the fonts, CDNs and
740
+ * third-party APIs a real page legitimately loads). Blocked = the private address space, which is
741
+ * only reachable because this client runs inside someone's network.
742
+ *
743
+ * Not a hostname resolver — callers pass already-resolved literals.
744
+ */
745
+ export function blockedTargetReason(address) {
746
+ const family = net.isIP(address);
747
+ if (family === 0) {
748
+ return "not an IP literal";
749
+ }
750
+ // VENDOR DELTA: classify IPv6 loopback and embedded-IPv4 spaces with binary `net.BlockList`
751
+ // matching instead of spelling-specific mapped-address regexes. This makes equivalent IPv6
752
+ // spellings share one verdict and refuses compatible, mapped, translated, and NAT64 forms.
753
+ const targetFamily = family === 4 ? "ipv4" : "ipv6";
754
+ const loopback = new net.BlockList();
755
+ if (targetFamily === "ipv4") {
756
+ loopback.addSubnet("127.0.0.0", 8, "ipv4");
757
+ }
758
+ else {
759
+ loopback.addSubnet("::1", 128, "ipv6");
760
+ loopback.addSubnet("::ffff:127.0.0.0", 104, "ipv6");
761
+ }
762
+ if (loopback.check(address, targetFamily)) {
763
+ return undefined;
764
+ }
765
+ if (targetFamily === "ipv6") {
766
+ const embeddedIpv4 = new net.BlockList();
767
+ // VENDOR DELTA: `::/32` and `64:ff9b::/32` rather than the narrower canonical-form
768
+ // prefixes (`::/96`, and `64:ff9b::/96` + `64:ff9b:1::/48`) alone. Each /32 is the
769
+ // binary superset of every RFC-named spelling in its family, so a reserved-but-
770
+ // non-canonical prefix that sits between two narrow rules (e.g.
771
+ // `64:ff9b:ffff::a9fe:a9fe`, which is in neither the RFC 6052 `/96` nor the RFC 8215
772
+ // `/48`) can no longer slip through. Mirrors `src/lib/target-url.ts`'s
773
+ // `NAT64_SUBNETS` / `IPV4_COMPATIBLE_SUBNETS` exactly (see that file's doc comment for
774
+ // the full reasoning); both `0000::/8` and `0064::/16` are IETF-reserved, so widening
775
+ // costs no reachable public target. The narrower `::ffff:0:0/96` / `::ffff:0:0:0/80` /
776
+ // `0:0:0:ffff:0:0:0:0/96` entries below are now FULLY SUBSUMED by the wider `::/32` and
777
+ // change no verdict — every hit here returns the one generic string, so unlike
778
+ // `target-url.ts` they name no family. They are kept only as an inline record of which
779
+ // RFC-named spellings this range covers, and deleting them is behaviour-neutral (proved
780
+ // by mutation: removing all three leaves the target-guard spec at 31/31). `::1` and mapped
781
+ // loopback
782
+ // (`::ffff:127.0.0.0/104`) are unaffected — the loopback `BlockList` above is checked
783
+ // first and returns before this one is ever consulted. See VENDOR.md #11.
784
+ embeddedIpv4.addSubnet("::", 32, "ipv6");
785
+ embeddedIpv4.addSubnet("::ffff:0:0", 96, "ipv6");
786
+ embeddedIpv4.addSubnet("::ffff:0:0:0", 80, "ipv6");
787
+ embeddedIpv4.addSubnet("0:0:0:ffff:0:0:0:0", 96, "ipv6");
788
+ embeddedIpv4.addSubnet("64:ff9b::", 32, "ipv6");
789
+ // VENDOR DELTA: 6to4 and Teredo derive IPv4 destinations by construction, so they belong
790
+ // with the other embedded-IPv4 spaces. See VENDOR.md #10.
791
+ embeddedIpv4.addSubnet("2002::", 16, "ipv6");
792
+ embeddedIpv4.addSubnet("2001::", 32, "ipv6");
793
+ if (embeddedIpv4.check(address, "ipv6")) {
794
+ return "IPv4 address embedded in an IPv6 literal";
795
+ }
796
+ }
797
+ for (const [reason, subnets] of targetFamily === "ipv4" ? BLOCKED_IPV4 : BLOCKED_IPV6) {
798
+ const list = new net.BlockList();
799
+ for (const [network, prefix] of subnets) {
800
+ list.addSubnet(network, prefix, targetFamily);
801
+ }
802
+ if (list.check(address, targetFamily)) {
803
+ return reason;
804
+ }
805
+ }
806
+ return undefined;
807
+ }
808
+ const BLOCKED_IPV4 = [
809
+ ["RFC1918 private address", [["10.0.0.0", 8], ["172.16.0.0", 12], ["192.168.0.0", 16]]],
810
+ // 169.254.0.0/16 — also where cloud instance-metadata endpoints live.
811
+ ["link-local address", [["169.254.0.0", 16]]],
812
+ ["RFC6598 carrier-grade NAT address", [["100.64.0.0", 10]]],
813
+ ["RFC2544 benchmarking address", [["198.18.0.0", 15]]],
814
+ ["unspecified address", [["0.0.0.0", 8]]],
815
+ ["multicast address", [["224.0.0.0", 4]]],
816
+ ["reserved address", [["240.0.0.0", 4]]],
817
+ ];
818
+ const BLOCKED_IPV6 = [
819
+ ["IPv6 unique-local address", [["fc00::", 7]]],
820
+ // VENDOR DELTA: deprecated site-local space is private-scope even though it predates ULA.
821
+ // See VENDOR.md #10.
822
+ ["IPv6 site-local address", [["fec0::", 10]]],
823
+ ["IPv6 link-local address", [["fe80::", 10]]],
824
+ ["multicast address", [["ff00::", 8]]],
825
+ ["unspecified address", [["::", 128]]],
826
+ ];
827
+ /**
828
+ * Ensure no candidate in `candidates` sits in a blocked range, unless `allowPrivateNetwork` opts
829
+ * out. Mirrors the Rust client's `ensure_candidates_allowed` / `ensure_target_allowed`: takes an
830
+ * already-resolved candidate set (rather than resolving internally) so callers about to dial that
831
+ * exact set can validate it without a second, independent DNS lookup.
832
+ *
833
+ * Deliberately NOT loopback-only: the browser under test proxies every request through this
834
+ * tunnel (Chromium `bypass='<-loopback>'`), so public targets are normal subresource traffic.
835
+ * See the Rust `ensure_target_allowed` doc comment for the full rationale.
836
+ */
837
+ export function ensureTargetAllowed(host, port, candidates, allowPrivateNetwork) {
838
+ if (allowPrivateNetwork) {
839
+ return;
840
+ }
841
+ if (candidates.length === 0) {
842
+ throw new BlockedTargetError(host, port);
843
+ }
844
+ for (const candidate of candidates) {
845
+ const reason = blockedTargetReason(candidate.host);
846
+ if (reason !== undefined) {
847
+ throw new BlockedTargetError(host, port, candidate.host, reason);
848
+ }
849
+ }
850
+ }
851
+ function parseTunnelAddr(addr) {
852
+ let hostPart = "";
853
+ let portPart = "";
854
+ if (addr.startsWith("[")) {
855
+ const closing = addr.indexOf("]");
856
+ if (closing < 0 || closing + 2 > addr.length || addr[closing + 1] !== ":") {
857
+ throw new Error(`Invalid tunnel address: ${addr}`);
858
+ }
859
+ hostPart = addr.slice(1, closing);
860
+ portPart = addr.slice(closing + 2);
861
+ }
862
+ else {
863
+ const sep = addr.lastIndexOf(":");
864
+ if (sep <= 0 || sep === addr.length - 1) {
865
+ throw new Error(`Invalid tunnel address: ${addr}`);
866
+ }
867
+ hostPart = addr.slice(0, sep);
868
+ portPart = addr.slice(sep + 1);
869
+ }
870
+ const port = Number(portPart);
871
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
872
+ throw new Error(`Invalid tunnel address port: ${addr}`);
873
+ }
874
+ return {
875
+ host: hostPart,
876
+ port,
877
+ };
878
+ }
879
+ function isStreamOpenRequestFrame(value) {
880
+ if (!isPlainObject(value)) {
881
+ return false;
882
+ }
883
+ const frame = value;
884
+ return isString(frame.request_id)
885
+ && isString(frame.inbound_request_id)
886
+ && isString(frame.tunnel_connection_id)
887
+ && isNumber(frame.mux_stream_id)
888
+ && isString(frame.target_host)
889
+ && isNumber(frame.target_port);
890
+ }
891
+ class ControlAuthFailureError extends Error {
892
+ constructor(code, reason) {
893
+ super(`control auth failure (code=${code}, reason=${reason || "unknown"})`);
894
+ this.name = "ControlAuthFailureError";
895
+ }
896
+ }
897
+ class TargetConnectError extends Error {
898
+ constructor(host, port, cause) {
899
+ super(`Target connect failed for ${host}:${port}: ${toErrorMessage(cause)}`);
900
+ this.name = "TargetConnectError";
901
+ }
902
+ }
903
+ /**
904
+ * Thrown by {@link ensureTargetAllowed} when a proxied target resolves into a blocked
905
+ * (private/internal) range. Mirrors the Rust client's `ensure_candidates_allowed` error.
906
+ */
907
+ export class BlockedTargetError extends Error {
908
+ constructor(host, port, address, reason) {
909
+ super(address === undefined
910
+ ? `target ${host}:${port} did not resolve to any address`
911
+ : `target ${host}:${port} resolves to ${address} (${reason}); refusing to dial. `
912
+ + "This run can reach localhost, 127.0.0.1, or ::1 on this machine and the public internet; "
913
+ + "private/LAN/VPN addresses are deliberately blocked. Make the dependency reachable through "
914
+ + "loopback or a public address, then retry.");
915
+ this.name = "BlockedTargetError";
916
+ }
917
+ }
918
+ function isControlAuthFailureError(err) {
919
+ return err instanceof ControlAuthFailureError;
920
+ }
921
+ function isAuthFailureClose(code, reason) {
922
+ return code === 1008 && reason.trim().toUpperCase() === "AUTH_FAILED";
923
+ }
924
+ //# sourceMappingURL=client.js.map