@testsprite/testsprite-cli 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +51 -48
  2. package/dist/commands/doctor.js +12 -11
  3. package/dist/commands/project-env.d.ts +11 -1
  4. package/dist/commands/project-env.js +399 -61
  5. package/dist/commands/project-sign-in.d.ts +60 -0
  6. package/dist/commands/project-sign-in.js +289 -0
  7. package/dist/commands/project.d.ts +9 -0
  8. package/dist/commands/project.js +68 -28
  9. package/dist/commands/schedule.d.ts +12 -0
  10. package/dist/commands/schedule.js +175 -5
  11. package/dist/commands/test.d.ts +53 -20
  12. package/dist/commands/test.js +1356 -342
  13. package/dist/commands/testlist.d.ts +10 -5
  14. package/dist/commands/testlist.js +170 -30
  15. package/dist/commands/tunnel.js +11 -5
  16. package/dist/index.js +12 -37
  17. package/dist/lib/client-factory.d.ts +12 -1
  18. package/dist/lib/client-factory.js +14 -4
  19. package/dist/lib/dry-run/samples.js +53 -0
  20. package/dist/lib/environment-tunnel.d.ts +109 -0
  21. package/dist/lib/environment-tunnel.js +465 -0
  22. package/dist/lib/errors.js +12 -1
  23. package/dist/lib/gh-output.js +3 -0
  24. package/dist/lib/http.d.ts +2 -0
  25. package/dist/lib/junit-report.d.ts +11 -7
  26. package/dist/lib/junit-report.js +13 -7
  27. package/dist/lib/local-target.d.ts +13 -3
  28. package/dist/lib/local-target.js +47 -12
  29. package/dist/lib/output.js +15 -1
  30. package/dist/lib/plan-poll.js +3 -4
  31. package/dist/lib/redact.d.ts +38 -0
  32. package/dist/lib/redact.js +140 -0
  33. package/dist/lib/render-error.d.ts +19 -5
  34. package/dist/lib/render-error.js +31 -0
  35. package/dist/lib/runs.types.d.ts +9 -1
  36. package/dist/lib/target-url.js +5 -5
  37. package/dist/lib/telemetry.d.ts +6 -7
  38. package/dist/lib/telemetry.js +11 -4
  39. package/dist/lib/testlist.types.d.ts +1 -0
  40. package/dist/lib/ticker.d.ts +9 -0
  41. package/dist/lib/ticker.js +18 -0
  42. package/dist/lib/tunnel-session.d.ts +3 -4
  43. package/dist/lib/tunnel-session.js +3 -4
  44. package/dist/lib/v3-advisory.js +0 -1
  45. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  46. package/dist/vendor/tunnel-client/client.js +477 -407
  47. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  48. package/dist/vendor/tunnel-client/config.js +5 -5
  49. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  50. package/dist/vendor/tunnel-client/index.js +4 -4
  51. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  52. package/dist/vendor/tunnel-client/types.js +1 -0
  53. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  54. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/package.json +1 -1
  58. package/skills/testsprite-onboard.skill.md +4 -4
@@ -6,9 +6,11 @@ import { localValidationError, TransportError } from './errors.js';
6
6
  import { isNonDispatchedStatus } from './gh-output.js';
7
7
  /**
8
8
  * Duration in seconds between two ISO timestamps, or `undefined` when either is
9
- * missing / unparseable / negative (clock skew). Kept ≥ 0.
9
+ * missing / unparseable / negative (clock skew). Prefer startedAt, falling back
10
+ * to createdAt on servers that do not record a start. Kept ≥ 0.
10
11
  */
11
- export function durationSecondsBetween(startedAt, finishedAt) {
12
+ export function durationSecondsBetween(startedAt, finishedAt, createdAt) {
13
+ startedAt = startedAt ?? createdAt;
12
14
  if (!startedAt || !finishedAt)
13
15
  return undefined;
14
16
  const start = Date.parse(startedAt);
@@ -179,13 +181,17 @@ export function buildJUnitReport(opts) {
179
181
  }
180
182
  /**
181
183
  * The summary's non-dispatched rows (deferred / conflict / not-found) as
182
- * skipped JUnit results. Accepted rows carry run statuses and never match
183
- * `isNonDispatchedStatus`, so the filter alone separates the two without
184
- * relying on row order.
184
+ * skipped JUnit results. Accepted rows carry run statuses and today never
185
+ * match `isNonDispatchedStatus`, but the two vocabularies are only disjoint
186
+ * by convention: `skipped` is a word both could use. So a member already in
187
+ * `dispatched` (the polled results the caller is writing) is left out here
188
+ * rather than trusted to stay apart, which keeps `tests` from counting one
189
+ * member twice if the server ever reports such a status for an admitted run.
185
190
  */
186
- export function skippedJUnitResultsFromSummary(summary) {
191
+ export function skippedJUnitResultsFromSummary(summary, dispatched = []) {
192
+ const alreadyIncluded = new Set(dispatched.map(row => row.testId));
187
193
  return summary.runs
188
- .filter(row => isNonDispatchedStatus(row.status))
194
+ .filter(row => isNonDispatchedStatus(row.status) && !alreadyIncluded.has(row.testId))
189
195
  .map(row => ({ testId: row.testId, status: 'skipped', skipReason: row.error ?? row.status }));
190
196
  }
191
197
  async function assertReportFileParent(rawPath) {
@@ -32,7 +32,7 @@
32
32
  */
33
33
  export declare const LOOPBACK_HOSTS: readonly ["localhost", "127.0.0.1", "::1"];
34
34
  export type LoopbackHost = (typeof LOOPBACK_HOSTS)[number];
35
- /** Default `--local-host`. An IP literal, so no resolver is involved at all. */
35
+ /** Default host for a new `--local <port>` shorthand target. */
36
36
  export declare const DEFAULT_LOCAL_HOST: LoopbackHost;
37
37
  /**
38
38
  * Per-candidate dial budget. Deliberately short: this is a loopback connect on
@@ -68,6 +68,13 @@ export declare function parseLocalPort(raw: string): number;
68
68
  * caller's own machine and nothing else, so a non-loopback value here is a
69
69
  * misunderstanding to correct immediately, not a request to forward.
70
70
  */
71
+ /**
72
+ * The loopback spelling a host string names, or `undefined` when it names
73
+ * anything else. Accepts bracketed IPv6 (`[::1]`, as `URL.hostname` renders
74
+ * it) and any letter case. This is the membership question; callers that
75
+ * need a refusal on a miss use {@link normalizeLocalHost}.
76
+ */
77
+ export declare function loopbackHost(raw: string): LoopbackHost | undefined;
71
78
  export declare function normalizeLocalHost(raw: string | undefined): LoopbackHost;
72
79
  /**
73
80
  * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
@@ -80,13 +87,15 @@ export interface StoredLocalTarget {
80
87
  host: LoopbackHost;
81
88
  port: number;
82
89
  }
90
+ /** Parse a loopback origin that the stored-target API and tunnel can reach. */
91
+ export declare function parseLoopbackTargetUrl(raw: string, field?: string): StoredLocalTarget | undefined;
83
92
  /**
84
93
  * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
85
94
  * takes. `--local` and `--url` are two spellings of one field, so both is a
86
95
  * contradiction; `--local-host` only means something next to `--local`; the
87
96
  * port is validated strictly because it becomes part of a URL runs are billed
88
- * against. Returns the local target, or `undefined` when `--url` (or nothing)
89
- * was given.
97
+ * against. Returns the local target for either shorthand or loopback URL input,
98
+ * or `undefined` for a public URL (or no target).
90
99
  */
91
100
  export declare function parseStoredLocalTarget(opts: {
92
101
  local?: string;
@@ -124,4 +133,5 @@ export declare function probeLocalPort(host: string, port: number, deps?: LocalP
124
133
  */
125
134
  export declare function assertLocalPortListening(host: LoopbackHost | string, port: number, opts: {
126
135
  skipPreflight?: boolean;
136
+ environmentName?: string;
127
137
  }, _stderrFn: (line: string) => void, deps?: LocalPortProbeDeps): Promise<void>;
@@ -34,8 +34,8 @@ import { resolveDialCandidates } from '../vendor/tunnel-client/index.js';
34
34
  * value this rejects but the server accepts is a capability silently withheld.
35
35
  */
36
36
  export const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '::1'];
37
- /** Default `--local-host`. An IP literal, so no resolver is involved at all. */
38
- export const DEFAULT_LOCAL_HOST = '127.0.0.1';
37
+ /** Default host for a new `--local <port>` shorthand target. */
38
+ export const DEFAULT_LOCAL_HOST = 'localhost';
39
39
  /**
40
40
  * Per-candidate dial budget. Deliberately short: this is a loopback connect on
41
41
  * the caller's own machine, where a live listener answers in microseconds. A
@@ -60,12 +60,21 @@ export function parseLocalPort(raw) {
60
60
  * caller's own machine and nothing else, so a non-loopback value here is a
61
61
  * misunderstanding to correct immediately, not a request to forward.
62
62
  */
63
+ /**
64
+ * The loopback spelling a host string names, or `undefined` when it names
65
+ * anything else. Accepts bracketed IPv6 (`[::1]`, as `URL.hostname` renders
66
+ * it) and any letter case. This is the membership question; callers that
67
+ * need a refusal on a miss use {@link normalizeLocalHost}.
68
+ */
69
+ export function loopbackHost(raw) {
70
+ const unbracketed = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
71
+ const candidate = unbracketed.trim().toLowerCase();
72
+ return LOOPBACK_HOSTS.find(host => host === candidate);
73
+ }
63
74
  export function normalizeLocalHost(raw) {
64
75
  if (raw === undefined)
65
76
  return DEFAULT_LOCAL_HOST;
66
- const unbracketed = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
67
- const candidate = unbracketed.trim().toLowerCase();
68
- const match = LOOPBACK_HOSTS.find(host => host === candidate);
77
+ const match = loopbackHost(raw);
69
78
  if (match === undefined) {
70
79
  throw localValidationError('local-host', `must name your own machine — one of ${LOOPBACK_HOSTS.join(', ')}. ` +
71
80
  'A tunnel only reaches the machine running this CLI; to test a reachable ' +
@@ -89,13 +98,34 @@ export function normalizeStoredLocalHost(raw) {
89
98
  throw err;
90
99
  }
91
100
  }
101
+ /** Parse a loopback origin that the stored-target API and tunnel can reach. */
102
+ export function parseLoopbackTargetUrl(raw, field = 'target-url') {
103
+ let parsed;
104
+ try {
105
+ parsed = new URL(raw);
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ const host = loopbackHost(parsed.hostname);
111
+ if (host === undefined)
112
+ return undefined;
113
+ // Read the explicit port from the input: URL.port drops the default :80.
114
+ const match = /^http:\/\/(localhost|127\.0\.0\.1|\[::1\]):([0-9]+)\/?$/.exec(raw);
115
+ const port = match === null ? 0 : Number(match[2]);
116
+ if (match === null || !Number.isInteger(port) || port < 1 || port > 65535) {
117
+ throw localValidationError(field, 'loopback URLs must use http://localhost:<port>, http://127.0.0.1:<port>, or http://[::1]:<port>, with a port between 1 and 65535 and no path ' +
118
+ '(an optional trailing / is allowed), query, fragment, or credentials');
119
+ }
120
+ return { host, port };
121
+ }
92
122
  /**
93
123
  * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
94
124
  * takes. `--local` and `--url` are two spellings of one field, so both is a
95
125
  * contradiction; `--local-host` only means something next to `--local`; the
96
126
  * port is validated strictly because it becomes part of a URL runs are billed
97
- * against. Returns the local target, or `undefined` when `--url` (or nothing)
98
- * was given.
127
+ * against. Returns the local target for either shorthand or loopback URL input,
128
+ * or `undefined` for a public URL (or no target).
99
129
  */
100
130
  export function parseStoredLocalTarget(opts) {
101
131
  if (opts.local !== undefined && opts.url !== undefined) {
@@ -104,8 +134,9 @@ export function parseStoredLocalTarget(opts) {
104
134
  if (opts.localHost !== undefined && opts.local === undefined) {
105
135
  throw flagPairError('--local-host requires --local');
106
136
  }
107
- if (opts.local === undefined)
108
- return undefined;
137
+ if (opts.local === undefined) {
138
+ return opts.url === undefined ? undefined : parseLoopbackTargetUrl(opts.url, 'url');
139
+ }
109
140
  if (!/^\d+$/.test(opts.local)) {
110
141
  throw flagPairError('--local must be a port number between 1 and 65535');
111
142
  }
@@ -243,9 +274,13 @@ export async function assertLocalPortListening(host, port, opts, _stderrFn, deps
243
274
  throw ApiError.fromEnvelope({
244
275
  error: {
245
276
  code: 'VALIDATION_ERROR',
246
- message: `Nothing is listening on ${host}:${port}, so a tunnel run would fail after being billed.`,
247
- nextAction: `Start your app on port ${port} first, or point --local at the port it is actually ` +
248
- `serving. ${SKIP_HINT}`,
277
+ message: opts.environmentName !== undefined
278
+ ? `Nothing is listening on ${host}:${port} (environment "${opts.environmentName}"). Start your app or run with --skip-preflight.`
279
+ : `Nothing is listening on ${host}:${port}, so a tunnel run would fail after being billed.`,
280
+ nextAction: opts.environmentName !== undefined
281
+ ? `Start your app on ${host}:${port} (environment "${opts.environmentName}") or run with --skip-preflight.`
282
+ : `Start your app on port ${port} first, or point --local at the port it is actually ` +
283
+ `serving. ${SKIP_HINT}`,
249
284
  requestId: 'local',
250
285
  details: {
251
286
  field: 'local',
@@ -1,4 +1,5 @@
1
1
  import { localValidationError } from './errors.js';
2
+ import { redactDeep } from './redact.js';
2
3
  /**
3
4
  * Help-text footer pointing at the global options surface so users
4
5
  * looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
@@ -50,6 +51,15 @@ export class Output {
50
51
  this.rawStdoutWrite = streams.rawStdout ?? defaultRawStdout;
51
52
  }
52
53
  print(data, textRenderer) {
54
+ // Success data is the caller's OWN content — generated test code, plans,
55
+ // backend-test fixtures — and must round-trip byte-identical (`test code
56
+ // get --output json` -> edit -> `test code put`), even when it
57
+ // legitimately contains a literal `Authorization: Bearer …` header or a
58
+ // `password` fixture key. Never redacted here, in either mode. Secret
59
+ // redaction (see `redact.ts`) applies only at error and request-trace
60
+ // boundaries — `Output.error` below, the ApiError envelope in
61
+ // `index.ts`, and `--debug` tracing in `client-factory.ts` — never to a
62
+ // success payload.
53
63
  if (this.mode === 'json' || !textRenderer) {
54
64
  this.stdoutWrite(JSON.stringify(data, null, 2));
55
65
  return;
@@ -84,7 +94,11 @@ export class Output {
84
94
  message: input.message,
85
95
  nextAction: input.nextAction ?? '',
86
96
  requestId: input.requestId ?? 'local',
87
- details: input.details ?? {},
97
+ // Defence in depth: `details` from a server envelope is already
98
+ // redacted server-side and (for an ApiError) at construction — see
99
+ // `errors.ts` — but this render boundary redacts again so no path
100
+ // that builds an envelope by hand here can ever skip it.
101
+ details: redactDeep(input.details ?? {}),
88
102
  },
89
103
  };
90
104
  this.stderrWrite(JSON.stringify(envelope, null, 2));
@@ -370,10 +370,9 @@ async function ladderLoop(client, projectId, options) {
370
370
  throw ApiError.fromEnvelope({
371
371
  error: {
372
372
  code: 'INTERNAL',
373
- message: `Plan generation appears stuck: ${state.triggerPosts} trigger request(s) ` +
374
- `(${state.acceptedPosts} accepted) but the server still reports no staged ` +
375
- `proposals and nothing running.`,
376
- nextAction: 'Retry later or check the project in the Portal. If this persists, report the requestId to support@testsprite.com.',
373
+ message: `Plan generation is not making progress after ${state.triggerPosts} ` +
374
+ `${state.triggerPosts === 1 ? 'try' : 'tries'}: nothing new is staged and no stage is running.`,
375
+ nextAction: 'Wait a few minutes, then run the same command again. If this keeps happening, check the project in the Portal or contact support@testsprite.com.',
377
376
  requestId: 'local',
378
377
  details: {
379
378
  projectId,
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Recursive, key-based secret redaction for CLI output.
3
+ *
4
+ * Before this module, the only redaction anywhere in the codebase was
5
+ * `tunnel-session.ts`'s `redactTunnelSecret` — a literal `String.replaceAll`
6
+ * of an ALREADY-KNOWN secret value out of a single log line. That only works
7
+ * when the caller already holds the plaintext to search for; it does nothing
8
+ * for an arbitrary server error `details` blob or a `--debug` trace, where
9
+ * the secret has to be found by its KEY name (`password`, `apiKey`, …), not
10
+ * by a value the caller can search for. This module fills that gap.
11
+ *
12
+ * Deliberately NOT applied to `Output.print`'s success data: generated test
13
+ * code, plans and backend-test fixtures are the user's OWN content and must
14
+ * round-trip byte-identical (`test code get --output json` -> edit ->
15
+ * `test code put`), even when they legitimately contain a literal
16
+ * `Authorization: Bearer …` header or a `password` fixture key — that is
17
+ * not a secret the CLI is leaking, it is the value the user is asking to see
18
+ * back. Applied instead at `Output.error`'s `details`, the hand-built
19
+ * ApiError envelope in `index.ts`, and the `--debug` / dry-run request
20
+ * tracing in `client-factory.ts` — server/error prose and request traces,
21
+ * never the user's stored data — and never at request-construction time (the
22
+ * real secret still has to go out on the wire). `--dry-run` previews that
23
+ * commands print are built from non-secret shapes (booleans such as
24
+ * `hasCredentials`, field names), so they never carry a secret to redact.
25
+ */
26
+ export declare const REDACTED = "[REDACTED]";
27
+ /**
28
+ * Deep-walk `value`, replacing:
29
+ * - the string value of any object key matching {@link isSecretKey}, at any
30
+ * depth, arrays included, with {@link REDACTED};
31
+ * - a `Bearer <token>` substring inside any other string, wherever it
32
+ * appears (key name irrelevant).
33
+ *
34
+ * Never mutates its input — returns a new tree. Plain data only (the values
35
+ * that ever reach here are parsed JSON or plain option objects); a `Date`,
36
+ * `Map`, etc. is returned unchanged rather than walked.
37
+ */
38
+ export declare function redactDeep<T>(value: T): T;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Recursive, key-based secret redaction for CLI output.
3
+ *
4
+ * Before this module, the only redaction anywhere in the codebase was
5
+ * `tunnel-session.ts`'s `redactTunnelSecret` — a literal `String.replaceAll`
6
+ * of an ALREADY-KNOWN secret value out of a single log line. That only works
7
+ * when the caller already holds the plaintext to search for; it does nothing
8
+ * for an arbitrary server error `details` blob or a `--debug` trace, where
9
+ * the secret has to be found by its KEY name (`password`, `apiKey`, …), not
10
+ * by a value the caller can search for. This module fills that gap.
11
+ *
12
+ * Deliberately NOT applied to `Output.print`'s success data: generated test
13
+ * code, plans and backend-test fixtures are the user's OWN content and must
14
+ * round-trip byte-identical (`test code get --output json` -> edit ->
15
+ * `test code put`), even when they legitimately contain a literal
16
+ * `Authorization: Bearer …` header or a `password` fixture key — that is
17
+ * not a secret the CLI is leaking, it is the value the user is asking to see
18
+ * back. Applied instead at `Output.error`'s `details`, the hand-built
19
+ * ApiError envelope in `index.ts`, and the `--debug` / dry-run request
20
+ * tracing in `client-factory.ts` — server/error prose and request traces,
21
+ * never the user's stored data — and never at request-construction time (the
22
+ * real secret still has to go out on the wire). `--dry-run` previews that
23
+ * commands print are built from non-secret shapes (booleans such as
24
+ * `hasCredentials`, field names), so they never carry a secret to redact.
25
+ */
26
+ export const REDACTED = '[REDACTED]';
27
+ /**
28
+ * Key-name suffixes (case-insensitive, separators ignored) whose STRING
29
+ * value is replaced by {@link REDACTED}. A suffix match, not a substring or
30
+ * exact match: it has to catch the realistic compound names a server or a
31
+ * future field could use (`refreshToken`, `clientSecret`, `x-api-key`,
32
+ * `Set-Cookie`) while still excluding names that merely contain the word,
33
+ * such as `credentialsPath` (a filesystem path, ends in "path") or
34
+ * `tokenEndpoint` (a URL, ends in "endpoint").
35
+ *
36
+ * Only applied when the value is a `string`. Two real shapes in this
37
+ * codebase would otherwise break under a type-blind rule:
38
+ * - `ci init`'s JSON output has a top-level `secret: {name, attempted, set,
39
+ * reason}` object describing metadata ABOUT a GitHub secret, never the
40
+ * secret's value.
41
+ * - `CliProjectEnvironment.hasCredentials` is a boolean PRESENCE flag, not
42
+ * a credential.
43
+ * Both keys are left untouched by the string-only guard below, and their
44
+ * children are still walked recursively (so an object nested under a
45
+ * matching key can carry its own, separately-matched, leaf secret).
46
+ */
47
+ const SECRET_KEY_SUFFIXES = [
48
+ 'password',
49
+ 'secret',
50
+ 'apikey',
51
+ 'authorization',
52
+ 'cookie',
53
+ 'credential',
54
+ 'credentials',
55
+ ];
56
+ /**
57
+ * Exact (post-normalization) key names treated as an auth token — NOT a
58
+ * suffix rule like the list above. This CLI's own pagination continuation
59
+ * handles are also literally named "...Token" (`nextToken`, `startingToken`)
60
+ * and are opaque cursors, not secrets; a suffix match on "token" would blank
61
+ * them (`test result --history`'s `nextToken`, `project list`'s
62
+ * `startingToken`/`nextToken`). Add a new compound auth-token name here, not
63
+ * to the suffix list above.
64
+ */
65
+ const SECRET_TOKEN_KEYS = new Set([
66
+ 'token',
67
+ 'apitoken',
68
+ 'authtoken',
69
+ 'accesstoken',
70
+ 'refreshtoken',
71
+ 'bearertoken',
72
+ 'idtoken',
73
+ 'sessiontoken',
74
+ ]);
75
+ /** Lowercase and strip every non-alphanumeric character for key matching. */
76
+ function normalizeKey(key) {
77
+ return key.replace(/[^a-z0-9]/gi, '').toLowerCase();
78
+ }
79
+ function isSecretKey(key) {
80
+ const normalized = normalizeKey(key);
81
+ if (SECRET_TOKEN_KEYS.has(normalized))
82
+ return true;
83
+ return SECRET_KEY_SUFFIXES.some(suffix => normalized.endsWith(suffix));
84
+ }
85
+ /**
86
+ * A conservative check for a secret-shaped string VALUE regardless of its
87
+ * key name — a bearer token embedded in server/error prose (e.g. inside a
88
+ * free-form `message`/`nextAction` string) has no key to match on.
89
+ * Deliberately narrow: only the `Bearer <token>` wire form, and only when
90
+ * the run of token characters contains an actual DIGIT, so an ordinary
91
+ * hyphenated or dotted phrase — "a Bearer authentication header", "Bearer
92
+ * token-based auth" — is left alone. A separator alone used to be enough
93
+ * (any of `._~+/=-`), which let the `{8,}` scan's greedy, position-blind
94
+ * match swallow a whole compound word merely because it contained a hyphen
95
+ * — a broader entropy/length heuristic would also flag long environment
96
+ * names, test ids, or UUIDs, which must never be redacted.
97
+ */
98
+ const BEARER_TOKEN_RE = /\bBearer\s+(?=[A-Za-z0-9._~+/=-]*[0-9])[A-Za-z0-9._~+/=-]{8,}/gi;
99
+ /**
100
+ * Keys whose object value is user-authored data shown back on purpose:
101
+ * environment `variables` are plaintext by design (a variable named
102
+ * `DB_PASSWORD` is the user's own fixture value), so they are never masked.
103
+ */
104
+ const VERBATIM_KEYS = new Set(['variables']);
105
+ /** Replace any `Bearer <token>` substring inside a free-form string. */
106
+ function redactSecretLookingSubstrings(value) {
107
+ return value.replace(BEARER_TOKEN_RE, `Bearer ${REDACTED}`);
108
+ }
109
+ /**
110
+ * Deep-walk `value`, replacing:
111
+ * - the string value of any object key matching {@link isSecretKey}, at any
112
+ * depth, arrays included, with {@link REDACTED};
113
+ * - a `Bearer <token>` substring inside any other string, wherever it
114
+ * appears (key name irrelevant).
115
+ *
116
+ * Never mutates its input — returns a new tree. Plain data only (the values
117
+ * that ever reach here are parsed JSON or plain option objects); a `Date`,
118
+ * `Map`, etc. is returned unchanged rather than walked.
119
+ */
120
+ export function redactDeep(value) {
121
+ if (Array.isArray(value)) {
122
+ return value.map(item => redactDeep(item));
123
+ }
124
+ if (typeof value === 'string') {
125
+ return redactSecretLookingSubstrings(value);
126
+ }
127
+ if (value !== null && typeof value === 'object' && value.constructor === Object) {
128
+ const result = {};
129
+ for (const [key, v] of Object.entries(value)) {
130
+ if (VERBATIM_KEYS.has(key) && v !== null && typeof v === 'object' && !Array.isArray(v)) {
131
+ result[key] = v;
132
+ continue;
133
+ }
134
+ result[key] = isSecretKey(key) && typeof v === 'string' ? REDACTED : redactDeep(v);
135
+ }
136
+ return result;
137
+ }
138
+ return value;
139
+ }
140
+ //# sourceMappingURL=redact.js.map
@@ -1,10 +1,24 @@
1
+ import type { InterruptError } from './errors.js';
2
+ import type { OutputMode } from './output.js';
3
+ /** The JSON-mode stderr envelope for a signal detach (errors.md §8.1). */
4
+ export interface InterruptEnvelope {
5
+ error: {
6
+ code: 'INTERRUPTED';
7
+ message: string;
8
+ nextAction: string;
9
+ requestId: 'local';
10
+ details: Record<string, unknown>;
11
+ };
12
+ }
1
13
  /**
2
- * Shared error rendering helpers for `src/index.ts`.
3
- *
4
- * Extracted so the output-interceptor rephrasing logic (P10) is
5
- * unit-testable without spawning a full CLI process.
14
+ * Build the `INTERRUPTED` envelope from whatever the interrupted command
15
+ * attached to the error. A tunnel run attaches `tunnelDetach` and
16
+ * `test plan generate` attaches `planDetach`; each carries its own
17
+ * `nextAction` so the envelope never contradicts the text line the catch
18
+ * block already printed. Otherwise a run wait gets the run-detach story
19
+ * (`test wait`) and any other request gets the generic check-state hint.
6
20
  */
7
- import type { OutputMode } from './output.js';
21
+ export declare function buildInterruptEnvelope(err: InterruptError): InterruptEnvelope;
8
22
  /**
9
23
  * Rephrase Commander's "unknown option '--foo'" error when `--foo` is
10
24
  * a known global flag that was placed after the subcommand.
@@ -1,3 +1,34 @@
1
+ /**
2
+ * Build the `INTERRUPTED` envelope from whatever the interrupted command
3
+ * attached to the error. A tunnel run attaches `tunnelDetach` and
4
+ * `test plan generate` attaches `planDetach`; each carries its own
5
+ * `nextAction` so the envelope never contradicts the text line the catch
6
+ * block already printed. Otherwise a run wait gets the run-detach story
7
+ * (`test wait`) and any other request gets the generic check-state hint.
8
+ */
9
+ export function buildInterruptEnvelope(err) {
10
+ const { tunnelDetach, planDetach } = err;
11
+ const nextAction = tunnelDetach?.nextAction ??
12
+ planDetach?.nextAction ??
13
+ (err.runWaitContext
14
+ ? 'The server-side run (if any) keeps executing and billing. ' +
15
+ 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
16
+ '(runId is in the partial JSON on stdout).'
17
+ : 'The request was interrupted. Check the current state before retrying; ' +
18
+ 'a multi-item command may have processed some items.');
19
+ const details = { signal: err.signal };
20
+ if (tunnelDetach) {
21
+ details.runId = tunnelDetach.runId;
22
+ details.cancelOutcome = tunnelDetach.cancel;
23
+ }
24
+ else if (planDetach) {
25
+ details.projectId = planDetach.projectId;
26
+ details.stagesRemaining = planDetach.stagesRemaining;
27
+ }
28
+ return {
29
+ error: { code: 'INTERRUPTED', message: err.message, nextAction, requestId: 'local', details },
30
+ };
31
+ }
1
32
  /**
2
33
  * Global flags that belong before the subcommand, not after it.
3
34
  *
@@ -55,10 +55,13 @@ export interface RunEnvironmentRef {
55
55
  }
56
56
  /**
57
57
  * Body sent to `POST /api/cli/v1/tests/{testId}/runs/rerun`.
58
- * No `targetUrl` — rerun replays against the project's configured URL.
58
+ * Tunnel replay includes the saved environment URL verbatim; ordinary replay
59
+ * uses the configured URL.
59
60
  * `source` must be "cli" (not "cli-rerun" — that is not a valid RUN_SOURCES value).
60
61
  */
61
62
  export interface RerunRequest {
63
+ tunnelClientId?: string;
64
+ targetUrl?: string;
62
65
  source: 'cli';
63
66
  /** Opt into AI heal-on-drift. Paid + FE only. Server tier-gates and echoes effective value. */
64
67
  autoHeal?: boolean;
@@ -101,6 +104,7 @@ export interface RerunAdvisory {
101
104
  * `runId` is always non-null (minted synchronously before async invoke).
102
105
  */
103
106
  export interface RerunResponse {
107
+ tunnelClientId?: string;
104
108
  /** The named test's runId (minted synchronously before async Lambda invoke). */
105
109
  runId: string;
106
110
  status: 'queued';
@@ -131,6 +135,8 @@ export interface RerunResponse {
131
135
  * Mixed FE/BE testIds allowed; BE closure deduped server-side per project.
132
136
  */
133
137
  export interface BatchRerunRequest {
138
+ tunnelClientId?: string;
139
+ targetUrl?: string;
134
140
  source: 'cli';
135
141
  testIds: string[];
136
142
  autoHeal?: boolean;
@@ -188,6 +194,7 @@ export interface BatchRerunClosure {
188
194
  * chunked dispatch requests (see `dedupeRerunAdvisories` in `commands/test.ts`).
189
195
  */
190
196
  export interface BatchRerunResponse {
197
+ tunnelClientId?: string;
191
198
  accepted: BatchRerunAccepted[];
192
199
  deferred: BatchRerunDeferred[];
193
200
  conflicts: BatchRerunConflict[];
@@ -200,6 +207,7 @@ export interface BatchRerunResponse {
200
207
  * All fields are stamped at trigger time and cannot change for this runId.
201
208
  */
202
209
  export interface TriggerRunResponse {
210
+ tunnelClientId?: string;
203
211
  runId: string;
204
212
  status: 'queued';
205
213
  enqueuedAt: string;
@@ -33,7 +33,7 @@ import { ApiError } from './errors.js';
33
33
  // on `127.0.0.1`/`::1`, so `--local`'s default dial reaches it) — NOT for
34
34
  // the rest of `127.0.0.0/8`, which `--local` cannot dial by name at all. See
35
35
  // `'loopback-other'` below for that distinction.
36
- const LOCAL_DEV_RUNTIME_HINT = "This looks like a local-dev target. Run it with `testsprite test run <test-id> --local <port>` instead — it tunnels this machine's loopback address to the test runner (frontend tests only; requires an API key with the `run:tunnel` scope).";
36
+ const LOCAL_DEV_RUNTIME_HINT = "This looks like a local-dev target. Save `--url http://localhost:<port>` on an environment, then run `testsprite test run <test-id> --env <name>` — it tunnels this machine's loopback address to the test runner (frontend tests only; requires an API key with the `run:tunnel` scope).";
37
37
  // Creation-time callers that take a per-run target (`test create
38
38
  // --target-url`, which only applies with `--run`). A project or environment
39
39
  // that names an app on this machine is created with `--local <port>`, so this
@@ -42,15 +42,15 @@ const LOCAL_DEV_RUNTIME_HINT = "This looks like a local-dev target. Run it with
42
42
  // loopback and are refused everywhere.
43
43
  const LOCAL_DEV_BOOTSTRAP_HINT = 'TestSprite executes tests from the cloud, so the runner needs an address it can reach: ' +
44
44
  'a deployed or staging URL. For an app that only runs on this machine, create the project ' +
45
- 'or environment with `--local <port>` instead of a URL, then run with ' +
46
- '`testsprite test run <test-id> --local <port>`.';
45
+ 'or environment with `--url http://localhost:<port>`, then run with ' +
46
+ '`testsprite test run <test-id> --env <name>`.';
47
47
  /**
48
48
  * `0.0.0.0` / `::` bind every interface, so an app listening there IS reachable
49
49
  * on loopback — but the address itself is not loopback and the server refuses
50
50
  * it as a stored URL. Naming the remedy is the whole point of the message.
51
51
  */
52
52
  const UNSPECIFIED_ADDRESS_REASON = 'the unspecified address (0.0.0.0 / ::) is not allowed — use 127.0.0.1 or ::1 instead';
53
- const LOCAL_PROJECT_CREATE_HINT = 'Use --local <port> instead of --url for an app on this machine. ' +
53
+ const LOCAL_PROJECT_CREATE_HINT = 'Use --url http://localhost:<port> for an app on this machine. ' +
54
54
  'Local projects are frontend-only and require the V3 project platform.';
55
55
  const DEFAULT_TARGET_URL_CALLER = {
56
56
  field: 'target-url',
@@ -228,7 +228,7 @@ function disallowedIpv4Reason(address) {
228
228
  *
229
229
  * This is the SAME primitive `src/vendor/tunnel-client/client.ts`'s
230
230
  * `blockedTargetReason` already uses for the identical problem (see its
231
- * VENDOR.md deltas #7/#10) — the two host classifiers in this repo now
231
+ * VENDOR.md upstreamed entries #7/#10) — the two host classifiers in this repo now
232
232
  * share one mechanism instead of two independently maintained spelling
233
233
  * lists, so a future NAT64-shaped bypass can't reopen only one of them.
234
234
  *
@@ -42,12 +42,8 @@ export interface TelemetryOutcomeInput extends Partial<WaitTimeoutTelemetry> {
42
42
  output?: string;
43
43
  dryRun?: boolean;
44
44
  /**
45
- * True when the invocation requested a local tunnel target (`test run
46
- * --local <port>`) — the flag's mere presence, never its port number or
47
- * host. Reported regardless of outcome, including a zero-network refusal
48
- * (dead port, `--local` combined with an incompatible flag): those are
49
- * exactly the attempts nothing server-side ever sees, which is why this
50
- * field is not redundant with a backend-side mint/attach analytics event.
45
+ * True when --local was present, including refusals and borrowed tunnels,
46
+ * or when this invocation automatically opened a saved-environment tunnel.
51
47
  */
52
48
  local?: boolean;
53
49
  }
@@ -111,6 +107,7 @@ export type TelemetryConflictReason = 'in_flight' | 'insufficient_credits' | 'pa
111
107
  * integers; enums are closed. Nothing here can carry an id, a URL, or a message.
112
108
  */
113
109
  export interface TelemetryExtras {
110
+ local?: boolean;
114
111
  /** Batch dispatch accounting (`test run --all`, `testlist run`). */
115
112
  accepted?: number;
116
113
  conflicts?: number;
@@ -148,6 +145,8 @@ export declare function sanitizeTelemetryExtras(partial: TelemetryExtrasInput):
148
145
  * never widen the wire contract from here.
149
146
  */
150
147
  export declare function recordTelemetryExtras(partial: TelemetryExtrasInput): void;
148
+ /** Extend explicit --local telemetry to commands that automatically open a tunnel. */
149
+ export declare function recordTelemetryTunnelOpened(opened: boolean): void;
151
150
  /** Return everything recorded so far and clear the sink (one event per process). */
152
151
  export declare function takeTelemetryExtras(): TelemetryExtras;
153
152
  /**
@@ -193,7 +192,7 @@ export interface TelemetryEvent extends Partial<WaitTimeoutTelemetry>, Telemetry
193
192
  nodeVersion?: string;
194
193
  output?: string;
195
194
  ci?: boolean;
196
- /** Present (always `true`) only for a `test run --local` invocation; absent otherwise. */
195
+ /** Present (always `true`) for --local attempts or automatically opened tunnels. */
197
196
  local?: boolean;
198
197
  /** The validated `TESTSPRITE_CLIENT` tag (e.g. `github-action/v1`); absent when unset/invalid. */
199
198
  client?: string;