@testsprite/testsprite-cli 0.10.0 → 0.12.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 (61) hide show
  1. package/README.md +65 -41
  2. package/dist/commands/auth.d.ts +5 -1
  3. package/dist/commands/auth.js +17 -5
  4. package/dist/commands/ci.js +34 -4
  5. package/dist/commands/init.d.ts +6 -1
  6. package/dist/commands/init.js +13 -5
  7. package/dist/commands/project-env.d.ts +90 -0
  8. package/dist/commands/project-env.js +486 -0
  9. package/dist/commands/project.d.ts +19 -0
  10. package/dist/commands/project.js +92 -25
  11. package/dist/commands/test.d.ts +42 -4
  12. package/dist/commands/test.js +344 -49
  13. package/dist/commands/testlist.js +29 -3
  14. package/dist/commands/tunnel.d.ts +2 -2
  15. package/dist/commands/tunnel.js +139 -31
  16. package/dist/index.js +42 -14
  17. package/dist/lib/client-factory.d.ts +4 -1
  18. package/dist/lib/client-factory.js +14 -4
  19. package/dist/lib/client-tag.d.ts +13 -0
  20. package/dist/lib/client-tag.js +44 -0
  21. package/dist/lib/conflict-reason.d.ts +43 -2
  22. package/dist/lib/conflict-reason.js +100 -14
  23. package/dist/lib/credentials.d.ts +4 -0
  24. package/dist/lib/credentials.js +43 -4
  25. package/dist/lib/cron.js +8 -1
  26. package/dist/lib/errors.d.ts +44 -1
  27. package/dist/lib/errors.js +69 -12
  28. package/dist/lib/gh-output.d.ts +25 -11
  29. package/dist/lib/gh-output.js +36 -13
  30. package/dist/lib/http.d.ts +21 -2
  31. package/dist/lib/http.js +45 -8
  32. package/dist/lib/local-target.d.ts +32 -0
  33. package/dist/lib/local-target.js +77 -0
  34. package/dist/lib/output.d.ts +27 -1
  35. package/dist/lib/output.js +22 -3
  36. package/dist/lib/response-schemas.d.ts +5 -2
  37. package/dist/lib/response-schemas.js +39 -1
  38. package/dist/lib/runs.types.d.ts +50 -2
  39. package/dist/lib/target-url.d.ts +1 -1
  40. package/dist/lib/target-url.js +35 -12
  41. package/dist/lib/telemetry.d.ts +174 -4
  42. package/dist/lib/telemetry.js +286 -13
  43. package/dist/lib/tunnel-session.d.ts +13 -2
  44. package/dist/lib/tunnel-session.js +92 -23
  45. package/dist/lib/tunnel.types.d.ts +3 -1
  46. package/dist/lib/version-notice.d.ts +20 -1
  47. package/dist/lib/version-notice.js +59 -12
  48. package/dist/vendor/tunnel-client/client.d.ts +11 -0
  49. package/dist/vendor/tunnel-client/client.js +383 -56
  50. package/dist/vendor/tunnel-client/config.d.ts +11 -3
  51. package/dist/vendor/tunnel-client/config.js +11 -3
  52. package/dist/vendor/tunnel-client/types.d.ts +26 -1
  53. package/dist/vendor/tunnel-client/types.js +1 -0
  54. package/dist/vendor/tunnel-client/ws-compat.d.ts +3 -2
  55. package/dist/vendor/tunnel-client/ws-compat.js +3 -2
  56. package/dist/version.d.ts +1 -1
  57. package/dist/version.js +1 -1
  58. package/package.json +2 -1
  59. package/skills/testsprite-onboard.skill.md +74 -59
  60. package/skills/testsprite-verify.codex.md +82 -97
  61. package/skills/testsprite-verify.skill.md +64 -15
@@ -19,13 +19,37 @@
19
19
  * would be cut off before delivery anyway).
20
20
  *
21
21
  * Privacy: the event is a fixed allowlist of low-cardinality, PII-free fields.
22
- * It NEVER carries target URLs, api keys, flag values, arg values, or error
23
- * messages — `errorCode` is a stable machine code, never the human message.
22
+ * It NEVER carries target URLs, api keys, arg values, error messages, or
23
+ * repository names — `errorCode` is a stable machine code, never the human
24
+ * message, and the CI repository is reduced to a salted, truncated hash so
25
+ * runs from one repo can be grouped without the slug ever leaving the runner.
26
+ * `timeoutSeconds` is the one field derived from a flag, and it is allowed
27
+ * for a narrow, checkable reason, not a case-by-case judgment call: it is the
28
+ * literal integer value of `--timeout`/`--request-timeout` as typed by the
29
+ * operator — not a path, not a URL, not free text, and not derived from
30
+ * anything the target application returned. It carries no more information
31
+ * than `exitCode` or `durationMs` already do, and is included so a `--wait`
32
+ * timeout is distinguishable from a genuinely slow backend (see `errorOrigin`
33
+ * below). Anyone auditing this allowlist can verify that reasoning against
34
+ * the two call sites that set it (`RequestTimeoutError.timeoutMs`, and the
35
+ * `ApiError` `details.timeoutSeconds` a `--wait` deadline conversion stamps)
36
+ * without having to trust a one-off exception.
37
+ *
38
+ * `errorOrigin` ('client' | 'server') and `timeoutSeconds` are sent by this
39
+ * revision of the CLI. The telemetry endpoint validates against an allowlist
40
+ * and silently DROPS fields it does not declare rather than rejecting the
41
+ * request, so a server that predates these two fields accepts the event and
42
+ * discards them — inert, not an error. Declaring a field is also not enough
43
+ * on its own: the server has a separate mapping step onto the analytics
44
+ * event, so a field can pass validation and still not be recorded.
24
45
  */
46
+ import { createHash } from 'node:crypto';
25
47
  import { CommanderError } from 'commander';
48
+ import { buildUserAgent, resolveClientTag } from './client-tag.js';
49
+ import { dominantConflictReason } from './conflict-reason.js';
26
50
  import { loadConfig } from './config.js';
27
51
  import { defaultCredentialsPath } from './credentials.js';
28
- import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './errors.js';
52
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './errors.js';
29
53
  import { facadeBaseUrl } from './facade.js';
30
54
  import { VERSION } from '../version.js';
31
55
  /**
@@ -35,20 +59,234 @@ import { VERSION } from '../version.js';
35
59
  * dropping the event is the correct best-effort behavior.
36
60
  */
37
61
  export const TELEMETRY_TIMEOUT_MS = 1000;
62
+ /**
63
+ * Which CI system the process is running under, from the standard env markers
64
+ * each vendor documents. `other` is any CI that only sets the generic `CI`
65
+ * variable; `none` is an interactive/unknown context.
66
+ */
67
+ export function detectCiProvider(env) {
68
+ if (env.GITHUB_ACTIONS === 'true')
69
+ return 'github';
70
+ if (isTruthyEnv(env.GITLAB_CI))
71
+ return 'gitlab';
72
+ if (isTruthyEnv(env.CIRCLECI))
73
+ return 'circleci';
74
+ if (isTruthyEnv(env.BUILDKITE))
75
+ return 'buildkite';
76
+ if (isTruthyEnv(env.CI))
77
+ return 'other';
78
+ return 'none';
79
+ }
80
+ const CI_EVENTS = new Set([
81
+ 'push',
82
+ 'pull_request',
83
+ 'schedule',
84
+ 'workflow_dispatch',
85
+ ]);
86
+ /**
87
+ * The GitHub Actions event that triggered the workflow, bucketed to a fixed
88
+ * vocabulary (`other` for everything outside it, e.g. `release`). Only
89
+ * meaningful under GitHub; undefined for every other provider and when the
90
+ * runner did not set `GITHUB_EVENT_NAME`.
91
+ */
92
+ export function detectCiEvent(env, provider) {
93
+ if (provider !== 'github')
94
+ return undefined;
95
+ const name = env.GITHUB_EVENT_NAME;
96
+ if (typeof name !== 'string' || name === '')
97
+ return undefined;
98
+ return CI_EVENTS.has(name) ? name : 'other';
99
+ }
100
+ /**
101
+ * Stable, non-reversible grouping key for a CI repository: the first 16 hex
102
+ * chars of `sha256('testsprite-ci-repo:' + slug)`. The salt prefix keeps the
103
+ * digest from matching a plain `sha256(slug)` lookup table; the slug itself
104
+ * never leaves the runner.
105
+ */
106
+ export function hashRepository(slug) {
107
+ return createHash('sha256').update(`testsprite-ci-repo:${slug}`).digest('hex').slice(0, 16);
108
+ }
109
+ /** The CI-context slice of the event (provider always present; the rest only when known). */
110
+ export function buildCiContext(env) {
111
+ const ciProvider = detectCiProvider(env);
112
+ const ciEvent = detectCiEvent(env, ciProvider);
113
+ const repo = env.GITHUB_REPOSITORY;
114
+ return {
115
+ ciProvider,
116
+ ...(ciEvent !== undefined ? { ciEvent } : {}),
117
+ ...(typeof repo === 'string' && repo !== '' ? { repoHash: hashRepository(repo) } : {}),
118
+ };
119
+ }
120
+ const COUNT_KEYS = [
121
+ 'accepted',
122
+ 'conflicts',
123
+ 'deferred',
124
+ 'skipped',
125
+ 'passed',
126
+ 'failed',
127
+ 'blocked',
128
+ 'timedOut',
129
+ ];
130
+ const BOOLEAN_KEYS = ['force', 'workflowExisted'];
131
+ const ENUM_KEYS = {
132
+ conflictReason: new Set([
133
+ 'in_flight',
134
+ 'insufficient_credits',
135
+ 'billing_hold',
136
+ 'mcp_view_only',
137
+ 'local_address',
138
+ 'tunnel-required',
139
+ 'error',
140
+ ]),
141
+ platform: new Set(['github']),
142
+ projectResolved: new Set(['flag', 'auto']),
143
+ };
144
+ /**
145
+ * Keep only the allowlisted keys with a value of the right shape. Pure: this is
146
+ * the single gate both the sink and the event builder run, so a stray field or
147
+ * a mistyped value can never reach the wire from either direction.
148
+ */
149
+ export function sanitizeTelemetryExtras(partial) {
150
+ const rec = partial;
151
+ const out = {};
152
+ for (const key of COUNT_KEYS) {
153
+ const v = rec[key];
154
+ if (typeof v === 'number' && Number.isInteger(v) && v >= 0)
155
+ out[key] = v;
156
+ }
157
+ for (const key of BOOLEAN_KEYS) {
158
+ const v = rec[key];
159
+ if (typeof v === 'boolean')
160
+ out[key] = v;
161
+ }
162
+ for (const key of Object.keys(ENUM_KEYS)) {
163
+ const v = rec[key];
164
+ if (typeof v === 'string' && ENUM_KEYS[key].has(v)) {
165
+ out[key] = v;
166
+ }
167
+ }
168
+ return out;
169
+ }
170
+ /** Module-level sink: the extras the running command has recorded so far. */
171
+ let pendingExtras = {};
172
+ /**
173
+ * Record outcome facts for the event this process will fire. Called by a
174
+ * command just before it returns/throws; merged per key, so a later call for
175
+ * the same key wins and different commands' keys never collide. Values outside
176
+ * the allowlist (or of the wrong shape) are dropped silently — a caller can
177
+ * never widen the wire contract from here.
178
+ */
179
+ export function recordTelemetryExtras(partial) {
180
+ pendingExtras = { ...pendingExtras, ...sanitizeTelemetryExtras(partial) };
181
+ }
182
+ /** Return everything recorded so far and clear the sink (one event per process). */
183
+ export function takeTelemetryExtras() {
184
+ const taken = pendingExtras;
185
+ pendingExtras = {};
186
+ return taken;
187
+ }
188
+ /**
189
+ * Disjoint verdict counts over a set of polled runs — `passed` + `failed` +
190
+ * `blocked` + `timedOut` = total. Unlike the CI summary's `failed` (which folds
191
+ * blocked in), `blocked` is split out here because it is the signal that
192
+ * separates a broken target from a failing assertion.
193
+ */
194
+ export function batchOutcomeCounts(results) {
195
+ let passed = 0;
196
+ let blocked = 0;
197
+ let timedOut = 0;
198
+ for (const r of results) {
199
+ if (r.status === 'passed')
200
+ passed++;
201
+ else if (r.status === 'blocked')
202
+ blocked++;
203
+ else if (r.status === 'timeout')
204
+ timedOut++;
205
+ }
206
+ return { passed, failed: results.length - passed - blocked - timedOut, blocked, timedOut };
207
+ }
208
+ /**
209
+ * Record a batch command's dispatch accounting (and, under `--wait`, its
210
+ * verdict counts) in one call, so `test run --all` and `testlist run` cannot
211
+ * drift in how they count. `conflictReason` is the dominant reason of the
212
+ * batch; `results` are the polled runs (omit for a non-wait dispatch).
213
+ */
214
+ export function recordBatchOutcome(batch) {
215
+ recordTelemetryExtras({
216
+ accepted: batch.accepted,
217
+ conflicts: batch.conflicts.length,
218
+ deferred: batch.deferred,
219
+ skipped: batch.skipped,
220
+ conflictReason: dominantConflictReason(batch.conflicts),
221
+ ...(batch.results !== undefined ? batchOutcomeCounts(batch.results) : {}),
222
+ });
223
+ }
38
224
  /**
39
225
  * Map a thrown CLI error to its telemetry disposition — mirrors the exit-code
40
226
  * mapping in `index.ts`'s top-level catch so telemetry and the process exit
41
227
  * code never disagree. Pure; safe to unit-test.
228
+ *
229
+ * Every branch below now fills `errorCode` — the two fallback branches
230
+ * (`CLIError`, and the final catch-all for a non-CLIError throw) previously
231
+ * left it `undefined`, which is why a meaningful share of `test run`
232
+ * invocations and `setup` failures landed in telemetry with `errorCode=None`.
233
+ *
234
+ * `errorOrigin` ('client' | 'server') resolves a real UNSUPPORTED
235
+ * misclassification: prod data showed genuine backend 501 UNSUPPORTED
236
+ * responses are rare compared to the PostHog events carrying that code,
237
+ * because every `--wait` timeout is ALSO converted to a client-fabricated
238
+ * `UNSUPPORTED`/exit-7 envelope (exit 7 is the timeout bucket by design;
239
+ * this patch does not touch that contract, only observability).
240
+ *
241
+ * Discriminator: for an `ApiError`, `err.httpStatus !== undefined` iff the
242
+ * code came from a real HTTP response (http.ts passes `response.status` into
243
+ * `ApiError.fromEnvelope` on every non-OK response it parses) — every
244
+ * CLI-fabricated envelope (`localValidationError`, `ApiError.authRequired()`,
245
+ * `TransportError`, and every `throw ApiError.fromEnvelope({... requestId:
246
+ * 'local' ...})` timeout conversion in commands/test.ts) never passes an
247
+ * `httpStatus`, so it reads `undefined`. `requestId` was considered and
248
+ * REJECTED as the discriminator: http.ts stamps a real, non-'local'
249
+ * `x-request-id` (`newRequestId()`) on every OUTGOING request before it knows
250
+ * whether a response will ever arrive, so `TransportError` (a DNS/TLS
251
+ * failure that never got a response) carries a real requestId despite being
252
+ * 100% client-side — `requestId === 'local'` would have misclassified it as
253
+ * 'server'. All non-`ApiError` branches (`RequestTimeoutError`,
254
+ * `InterruptError`, a plain `CLIError`, `CommanderError`, and a genuinely
255
+ * uncaught exception) never involve an HTTP response at all, so they are
256
+ * unconditionally 'client'.
42
257
  */
43
258
  export function classifyCliError(err) {
44
259
  if (err instanceof InterruptError) {
45
- return { outcome: 'abort', exitCode: err.exitCode, errorCode: 'INTERRUPTED' };
260
+ // err.code is 'INTERRUPTED' (set in its constructor) — read it rather
261
+ // than re-hardcoding the literal, so there is exactly one place that
262
+ // knows InterruptError's telemetry code.
263
+ return {
264
+ outcome: 'abort',
265
+ exitCode: err.exitCode,
266
+ errorCode: err.code,
267
+ errorOrigin: 'client',
268
+ };
46
269
  }
47
270
  if (err instanceof RequestTimeoutError) {
48
- return { outcome: 'error', exitCode: err.exitCode, errorCode: 'REQUEST_TIMEOUT' };
271
+ // err.code is 'REQUEST_TIMEOUT' (set in its constructor) — same reasoning.
272
+ return {
273
+ outcome: 'error',
274
+ exitCode: err.exitCode,
275
+ errorCode: err.code,
276
+ errorOrigin: 'client',
277
+ timeoutSeconds: Math.round(err.timeoutMs / 1000),
278
+ };
49
279
  }
50
280
  if (err instanceof ApiError) {
51
- return { outcome: 'error', exitCode: err.exitCode, errorCode: err.code };
281
+ const errorOrigin = err.httpStatus !== undefined ? 'server' : 'client';
282
+ const timeoutSeconds = err.getDetail('timeoutSeconds', (v) => typeof v === 'number');
283
+ return {
284
+ outcome: 'error',
285
+ exitCode: err.exitCode,
286
+ errorCode: err.code,
287
+ errorOrigin,
288
+ ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),
289
+ };
52
290
  }
53
291
  if (err instanceof CommanderError) {
54
292
  // Help / version are user-requested successes (exit 0); everything else
@@ -58,12 +296,22 @@ export function classifyCliError(err) {
58
296
  err.code === 'commander.version') {
59
297
  return { outcome: 'success', exitCode: 0 };
60
298
  }
61
- return { outcome: 'error', exitCode: 5, errorCode: 'VALIDATION_ERROR' };
299
+ return {
300
+ outcome: 'error',
301
+ exitCode: 5,
302
+ errorCode: 'VALIDATION_ERROR',
303
+ errorOrigin: 'client',
304
+ };
62
305
  }
63
306
  if (err instanceof CLIError) {
64
- return { outcome: 'error', exitCode: err.exitCode };
307
+ return { outcome: 'error', exitCode: err.exitCode, errorCode: err.code, errorOrigin: 'client' };
65
308
  }
66
- return { outcome: 'error', exitCode: 1 };
309
+ return {
310
+ outcome: 'error',
311
+ exitCode: 1,
312
+ errorCode: extractNodeErrorCode(err) ?? 'UNCAUGHT_EXCEPTION',
313
+ errorOrigin: 'client',
314
+ };
67
315
  }
68
316
  /** True when the operator has opted out via either supported env var. */
69
317
  export function isTelemetryOptedOut(env) {
@@ -75,20 +323,42 @@ function isTruthyEnv(v) {
75
323
  const t = v.trim().toLowerCase();
76
324
  return t !== '' && t !== '0' && t !== 'false';
77
325
  }
78
- /** Assemble the allowlisted wire event. No URL / message / flag value ever. */
79
- export function buildTelemetryEvent(input, env, isTTY) {
326
+ /**
327
+ * Assemble the allowlisted wire event. No URL / message / flag value ever.
328
+ * `extras` are the per-command facts the sink collected (re-sanitized here so a
329
+ * direct caller cannot bypass the allowlist).
330
+ */
331
+ export function buildTelemetryEvent(input, env, isTTY, extras = {}) {
332
+ const client = resolveClientTag(env);
80
333
  return {
81
334
  command: input.command,
82
335
  outcome: input.outcome,
83
336
  exitCode: input.exitCode,
84
337
  ...(input.errorCode ? { errorCode: input.errorCode } : {}),
338
+ ...(input.errorOrigin ? { errorOrigin: input.errorOrigin } : {}),
339
+ ...(typeof input.timeoutSeconds === 'number' ? { timeoutSeconds: input.timeoutSeconds } : {}),
85
340
  durationMs: input.durationMs,
86
341
  cliVersion: VERSION,
87
342
  os: process.platform,
88
343
  nodeVersion: process.versions.node,
89
344
  ...(input.output === 'json' || input.output === 'text' ? { output: input.output } : {}),
90
345
  ci: isTruthyEnv(env.CI) || !isTTY,
346
+ ...(client !== undefined ? { client } : {}),
347
+ ...buildCiContext(env),
91
348
  ...(input.local ? { local: true } : {}),
349
+ ...(input.outcome === 'error' && input.reason === 'wait_timeout'
350
+ ? {
351
+ reason: 'wait_timeout',
352
+ ...(input.local &&
353
+ (input.cancelOutcome === 'cancelled' ||
354
+ input.cancelOutcome === 'already_terminal' ||
355
+ input.cancelOutcome === 'failed' ||
356
+ input.cancelOutcome === 'skipped')
357
+ ? { cancelOutcome: input.cancelOutcome }
358
+ : {}),
359
+ }
360
+ : {}),
361
+ ...sanitizeTelemetryExtras(extras),
92
362
  };
93
363
  }
94
364
  /**
@@ -115,6 +385,9 @@ export function resolveTelemetryAuth(opts, deps = {}) {
115
385
  * command, or when no api-key is configured.
116
386
  */
117
387
  export async function recordOutcome(input, deps = {}) {
388
+ // Drain the sink unconditionally — one event per process, and a gated-out
389
+ // flush must not leave a previous command's facts behind for the next test.
390
+ const extras = takeTelemetryExtras();
118
391
  try {
119
392
  const env = deps.env ?? process.env;
120
393
  if (isTelemetryOptedOut(env))
@@ -142,7 +415,7 @@ export async function recordOutcome(input, deps = {}) {
142
415
  return; // authenticated-only
143
416
  const url = `${facadeBaseUrl(config.apiUrl)}/telemetry`;
144
417
  const isTTY = deps.isTTY ?? process.stderr.isTTY === true;
145
- const body = buildTelemetryEvent(input, env, isTTY);
418
+ const body = buildTelemetryEvent(input, env, isTTY, extras);
146
419
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
147
420
  const controller = new AbortController();
148
421
  const timer = setTimeout(() => controller.abort(), TELEMETRY_TIMEOUT_MS);
@@ -155,7 +428,7 @@ export async function recordOutcome(input, deps = {}) {
155
428
  headers: {
156
429
  'content-type': 'application/json',
157
430
  'x-api-key': config.apiKey,
158
- 'user-agent': `testsprite-cli/${VERSION}`,
431
+ 'user-agent': buildUserAgent(env),
159
432
  },
160
433
  body: JSON.stringify(body),
161
434
  signal: controller.signal,
@@ -57,6 +57,10 @@ export declare const TUNNEL_CLIENT_STOP_TIMEOUT_MS = 2000;
57
57
  export type TunnelFatalReason =
58
58
  /** The server refused or dropped a client WE minted and connected. */
59
59
  'auth-failed'
60
+ /** The server revoked our credential or another connection took over. */
61
+ | 'credential-revoked'
62
+ /** The selected data-plane transport could not connect inside its retry window. */
63
+ | 'data-plane-unreachable'
60
64
  /**
61
65
  * A BORROWED client (`--tunnel-client`) is no longer registered. Different
62
66
  * cause and different remedy from `auth-failed`: nobody disconnected us,
@@ -66,10 +70,14 @@ export type TunnelFatalReason =
66
70
  export interface TunnelSession {
67
71
  readonly clientId: string;
68
72
  readonly expiresAt: string;
73
+ /** Unknown only for an adopted client whose owning process chose the transport. */
74
+ readonly transport: 'tls' | 'plaintext' | undefined;
69
75
  /** True when this session attached to a client someone else minted. */
70
76
  readonly adopted: boolean;
71
77
  /** The fatal reason, once one has occurred. `undefined` while healthy. */
72
78
  fatalReason(): TunnelFatalReason | undefined;
79
+ /** Safe client detail for the fatal reason, when one carries user-facing context. */
80
+ fatalMessage(): string | undefined;
73
81
  /** Give the client a bounded stop window, then delete our binding. Idempotent. */
74
82
  close(): Promise<void>;
75
83
  }
@@ -92,7 +100,7 @@ export interface OpenTunnelSessionOptions {
92
100
  /** See {@link DEFAULT_TUNNEL_CONNECT_TIMEOUT_MS}. */
93
101
  connectTimeoutMs?: number;
94
102
  /** Called once, the first time the tunnel becomes unusable for this run. */
95
- onFatal?: (reason: TunnelFatalReason) => void;
103
+ onFatal?: (reason: TunnelFatalReason, message?: string) => void;
96
104
  /**
97
105
  * Attach to a client someone else minted (`testsprite tunnel start` in
98
106
  * another terminal) instead of minting one. No secret is available, so
@@ -123,8 +131,11 @@ export interface TunnelSessionDeps {
123
131
  * the already-started server-side run before deciding whether to retry.
124
132
  */
125
133
  export declare class TunnelLostError extends ApiError {
126
- constructor(reason: TunnelFatalReason, runId: string);
134
+ constructor(reason: TunnelFatalReason, runId: string, fatalMessage?: string);
127
135
  }
136
+ export declare function formatDataPlaneUnreachableMessage(clientMessage?: string): string;
137
+ export declare function formatDataPlaneUnreachableNextAction(clientMessage: string | undefined, retryAction: string): string;
138
+ export declare const TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION: string;
128
139
  /**
129
140
  * Mint (or adopt) a tunnel client and connect it.
130
141
  *
@@ -40,6 +40,7 @@
40
40
  */
41
41
  import { ApiError } from './errors.js';
42
42
  import { ErrCode, TunnelClient } from '../vendor/tunnel-client/index.js';
43
+ import { DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS } from '../vendor/tunnel-client/config.js';
43
44
  /**
44
45
  * How long to wait for the control plane's first successful connection.
45
46
  *
@@ -53,6 +54,10 @@ export const DEFAULT_TUNNEL_CONNECT_TIMEOUT_MS = 20_000;
53
54
  /** Maximum time teardown lets a wedged client delay credential deletion. */
54
55
  export const TUNNEL_CLIENT_STOP_TIMEOUT_MS = 2_000;
55
56
  const TUNNEL_SECRET_REDACTION = '[REDACTED]';
57
+ function isCredentialRevokedMessage(message) {
58
+ return (message === 'tunnel credential revoked' ||
59
+ message === 'tunnel connection superseded or credential revoked');
60
+ }
56
61
  /**
57
62
  * Thrown when the tunnel a run depends on dies mid-run. `UNAVAILABLE` (exit
58
63
  * 10 rather than a run failure: the test did not fail, the transport under it
@@ -60,35 +65,75 @@ const TUNNEL_SECRET_REDACTION = '[REDACTED]';
60
65
  * the already-started server-side run before deciding whether to retry.
61
66
  */
62
67
  export class TunnelLostError extends ApiError {
63
- constructor(reason, runId) {
68
+ constructor(reason, runId, fatalMessage) {
64
69
  // Two different things go wrong here and they do NOT share a remedy.
65
- // Telling a borrower to "run again" both hides the already-started billed
66
- // run and is false about the tunnel — `--tunnel-client <id>` re-attaches
67
- // to the same dead id and mints nothing. Naming the wrong cause is the
68
- // failure mode this whole area keeps repeating, so each reason carries its
69
- // own copy.
70
+ // `--tunnel-client <id>` re-attaches to the same dead id and mints nothing,
71
+ // so a borrower must inspect this run before deciding what to do next.
72
+ // The wait path reports the observed cancellation outcome separately.
70
73
  const ownerGone = reason === 'owner-gone';
74
+ const dataPlaneUnreachable = reason === 'data-plane-unreachable';
71
75
  super({
72
76
  code: 'UNAVAILABLE',
73
77
  message: ownerGone
74
78
  ? `The borrowed tunnel for run ${runId} is no longer registered. It was minted by ` +
75
79
  `another process (\`testsprite tunnel start\`), and that process has stopped or its ` +
76
- `credential expired. Run ${runId} was left executing server-side and may still ` +
77
- `finish; if it is cancelled, its verdict is discarded.`
78
- : `The tunnel carrying run ${runId} was disconnected by the server and cannot be ` +
79
- `restored for this run (${reason}).`,
80
+ `credential expired. The run cannot reach your app through that tunnel.`
81
+ : dataPlaneUnreachable
82
+ ? formatDataPlaneUnreachableMessage(fatalMessage)
83
+ : `The tunnel carrying run ${runId} was disconnected by the server and cannot be ` +
84
+ `restored for this run (${reason}).`,
80
85
  nextAction: ownerGone
81
- ? `Run ${runId} has lost its tunnel and cannot reach your app any more. Stop it now ` +
82
- `with: testsprite test cancel ${runId} (idempotent). To watch it instead: ` +
83
- `testsprite test wait ${runId} --timeout <s>.`
84
- : 'This usually means the tunnel service was redeployed mid-run. Start the run again: ' +
85
- 'the retry mints a fresh tunnel.',
86
+ ? `Check the run before re-running: testsprite test wait ${runId}.`
87
+ : dataPlaneUnreachable
88
+ ? `Check the cancelled run with testsprite test wait ${runId}. ` +
89
+ formatDataPlaneUnreachableNextAction(fatalMessage, 'start a new run')
90
+ : 'This usually means the tunnel service was redeployed mid-run. Start the run again: ' +
91
+ 'the retry mints a fresh tunnel.',
86
92
  requestId: 'local',
87
93
  details: { reason, runId },
88
94
  });
89
95
  this.name = 'TunnelLostError';
90
96
  }
91
97
  }
98
+ function parseDataPlaneUnreachableMessage(clientMessage) {
99
+ const parsed = /^Data plane (tls|plaintext) at (.+) is unreachable after (\d+)ms: ([\s\S]+)$/u.exec(clientMessage ?? '');
100
+ if (!parsed)
101
+ return undefined;
102
+ return {
103
+ transport: parsed[1],
104
+ address: parsed[2],
105
+ deadlineMs: Number(parsed[3]),
106
+ error: parsed[4],
107
+ };
108
+ }
109
+ export function formatDataPlaneUnreachableMessage(clientMessage) {
110
+ const parsed = parseDataPlaneUnreachableMessage(clientMessage);
111
+ const base = parsed
112
+ ? `The tunnel's ${parsed.transport === 'tls' ? 'encrypted' : 'plaintext'} data connection to ${parsed.address} ` +
113
+ `could not be established for ${parsed.deadlineMs / 1_000}s (last error: ${parsed.error}).`
114
+ : (clientMessage ?? "The tunnel's encrypted data connection could not be established.");
115
+ if (parsed?.transport === 'plaintext') {
116
+ return (`${base} Check that the self-hosted tunnel service at ${parsed.address} is running and ` +
117
+ 'that the egress firewall allows a direct connection to that address and port.');
118
+ }
119
+ if (base.includes('NODE_EXTRA_CA_CERTS'))
120
+ return base;
121
+ return (`${base} Corporate TLS interception, a wrong system clock, or a firewall blocking port 443 ` +
122
+ "are the usual causes; set NODE_EXTRA_CA_CERTS to your organisation's CA bundle if your " +
123
+ 'network re-signs TLS.');
124
+ }
125
+ export function formatDataPlaneUnreachableNextAction(clientMessage, retryAction) {
126
+ const parsed = parseDataPlaneUnreachableMessage(clientMessage);
127
+ if (parsed?.transport === 'plaintext') {
128
+ return (`Check that the self-hosted tunnel service at ${parsed.address} is running and that the ` +
129
+ `egress firewall allows a direct connection to that address and port. Then ${retryAction}.`);
130
+ }
131
+ return ('Fix the network or TLS trust configuration: check for TLS interception, correct the system ' +
132
+ "clock, allow outbound port 443, and set NODE_EXTRA_CA_CERTS to your organisation's CA " +
133
+ `bundle when the network re-signs TLS. Then ${retryAction}.`);
134
+ }
135
+ export const TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION = 'the tunnel data plane uses a direct socket connection (TLS when the server advertises it; ' +
136
+ 'raw TCP only for the legacy transport) that bypasses HTTP proxies';
92
137
  function defaultCreateClient(options) {
93
138
  return new TunnelClient(options);
94
139
  }
@@ -125,14 +170,17 @@ function redactTunnelSecret(line, secret) {
125
170
  export async function openTunnelSession(options, deps) {
126
171
  const { log } = options;
127
172
  let fatal;
173
+ let fatalMessage;
128
174
  let closed = false;
129
175
  if (options.adopt) {
130
176
  // Adopted: no secret here, so no connection and no teardown obligation.
131
177
  return {
132
178
  clientId: options.adopt.clientId,
133
179
  expiresAt: options.adopt.expiresAt,
180
+ transport: undefined,
134
181
  adopted: true,
135
182
  fatalReason: () => fatal,
183
+ fatalMessage: () => fatalMessage,
136
184
  close: async () => { },
137
185
  };
138
186
  }
@@ -141,6 +189,10 @@ export async function openTunnelSession(options, deps) {
141
189
  // scrubbed before the caller-owned sink can observe it. This remains safe if
142
190
  // a future client log message accidentally interpolates its options.
143
191
  const sessionLog = (line) => log(redactTunnelSecret(line, minted.secret));
192
+ const transport = minted.tunnelTlsAddr === undefined ? 'plaintext' : 'tls';
193
+ if (transport === 'plaintext') {
194
+ sessionLog('Warning: this TestSprite server did not advertise an encrypted tunnel data plane; the tunnel secret will be sent over plaintext TCP.');
195
+ }
144
196
  const createClient = deps.createClient ?? defaultCreateClient;
145
197
  let client;
146
198
  const stopAndDestroy = async () => {
@@ -171,6 +223,8 @@ export async function openTunnelSession(options, deps) {
171
223
  secret: minted.secret,
172
224
  controlUrl: minted.controlUrl,
173
225
  tunnelAddr: minted.tunnelAddr,
226
+ ...(minted.tunnelTlsAddr !== undefined ? { tunnelTlsAddr: minted.tunnelTlsAddr } : {}),
227
+ dataPlaneRetryDeadlineMs: DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS,
174
228
  logLevel: options.logLevel ?? 'error',
175
229
  // Never opened up. The point of `--local` is the caller's own loopback;
176
230
  // a run that pivots into the rest of their network is the failure this
@@ -178,14 +232,24 @@ export async function openTunnelSession(options, deps) {
178
232
  allowPrivateNetworkTarget: false,
179
233
  logSink: (_level, line) => sessionLog(line),
180
234
  onError: e => {
181
- if (e.code === ErrCode.AuthFailed && fatal === undefined) {
235
+ const terminal = e.code === ErrCode.AuthFailed || e.code === ErrCode.DataPlaneUnreachable;
236
+ if (terminal && fatal === undefined) {
182
237
  // Terminal: the vendored client has stopped reconnecting, and a
183
238
  // remint cannot rescue this run (see the module docstring).
184
- fatal = 'auth-failed';
185
- options.onFatal?.('auth-failed');
239
+ fatal =
240
+ e.code === ErrCode.DataPlaneUnreachable
241
+ ? 'data-plane-unreachable'
242
+ : isCredentialRevokedMessage(e.message)
243
+ ? 'credential-revoked'
244
+ : 'auth-failed';
245
+ fatalMessage =
246
+ e.code === ErrCode.DataPlaneUnreachable
247
+ ? redactTunnelSecret(e.message, minted.secret)
248
+ : undefined;
249
+ options.onFatal?.(fatal, fatalMessage);
186
250
  return;
187
251
  }
188
- if (e.code === ErrCode.AuthFailed)
252
+ if (terminal)
189
253
  return;
190
254
  sessionLog(`[tunnel] ${e.message}`);
191
255
  },
@@ -205,8 +269,7 @@ export async function openTunnelSession(options, deps) {
205
269
  code: 'UNAVAILABLE',
206
270
  message: `The tunnel did not connect within ${Math.round(timeoutMs / 1000)}s.`,
207
271
  nextAction: 'Check that outbound WebSocket traffic is allowed from this machine, then retry. ' +
208
- 'An HTTP proxy does not help here: the tunnel data plane is a raw TCP connection ' +
209
- 'and does not go through one.',
272
+ `An HTTP proxy does not help here: ${TUNNEL_DATA_PLANE_PROXY_BYPASS_DESCRIPTION}.`,
210
273
  requestId: 'local',
211
274
  details: { reason: 'tunnel-connect-timeout', timeoutMs },
212
275
  },
@@ -222,10 +285,14 @@ export async function openTunnelSession(options, deps) {
222
285
  throw ApiError.fromEnvelope({
223
286
  error: {
224
287
  code: 'UNAVAILABLE',
225
- message: `Could not connect the tunnel: ${err instanceof Error ? err.message : String(err)}`,
288
+ message: fatal === 'credential-revoked'
289
+ ? `Tunnel credential ${minted.clientId} was revoked, expired, or taken over by another process.`
290
+ : `Could not connect the tunnel: ${err instanceof Error ? err.message : String(err)}`,
226
291
  nextAction: 'Retry. If this persists, report it to support@testsprite.com.',
227
292
  requestId: 'local',
228
- details: { reason: 'tunnel-connect-failed' },
293
+ details: {
294
+ reason: fatal === 'credential-revoked' ? 'credential-revoked' : 'tunnel-connect-failed',
295
+ },
229
296
  },
230
297
  });
231
298
  }
@@ -236,8 +303,10 @@ export async function openTunnelSession(options, deps) {
236
303
  return {
237
304
  clientId: minted.clientId,
238
305
  expiresAt: minted.expiresAt,
306
+ transport,
239
307
  adopted: false,
240
308
  fatalReason: () => fatal,
309
+ fatalMessage: () => fatalMessage,
241
310
  close: async () => {
242
311
  if (closed)
243
312
  return;
@@ -35,8 +35,10 @@ export interface TunnelMintResponse {
35
35
  * the facade returns these two explicitly instead of a host/port pair.
36
36
  */
37
37
  controlUrl: string;
38
- /** `host:port` of the tunnel DATA plane the client dials over raw TCP. */
38
+ /** Plaintext `host:port` retained for compatibility with older clients. */
39
39
  tunnelAddr: string;
40
+ /** TLS `host:port` for the encrypted data plane; absent on older backends. */
41
+ tunnelTlsAddr?: string;
40
42
  /** ISO8601. After this the binding is gone and the run can no longer attach. */
41
43
  expiresAt: string;
42
44
  }