@testsprite/testsprite-cli 0.6.0 → 0.7.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 (50) hide show
  1. package/README.md +38 -30
  2. package/dist/commands/agent.js +44 -42
  3. package/dist/commands/doctor.d.ts +1 -1
  4. package/dist/commands/doctor.js +4 -7
  5. package/dist/commands/project.js +3 -2
  6. package/dist/commands/schedule.d.ts +120 -0
  7. package/dist/commands/schedule.js +487 -0
  8. package/dist/commands/test.d.ts +15 -1
  9. package/dist/commands/test.js +460 -256
  10. package/dist/commands/testlist.d.ts +88 -0
  11. package/dist/commands/testlist.js +747 -0
  12. package/dist/index.js +6 -2
  13. package/dist/lib/agent-targets.d.ts +13 -4
  14. package/dist/lib/agent-targets.js +11 -2
  15. package/dist/lib/conflict-reason.d.ts +30 -0
  16. package/dist/lib/conflict-reason.js +45 -0
  17. package/dist/lib/credentials.js +42 -1
  18. package/dist/lib/cron.d.ts +40 -0
  19. package/dist/lib/cron.js +190 -0
  20. package/dist/lib/dry-run/samples.js +177 -55
  21. package/dist/lib/errors.d.ts +9 -0
  22. package/dist/lib/errors.js +11 -0
  23. package/dist/lib/gh-output.d.ts +26 -1
  24. package/dist/lib/gh-output.js +47 -20
  25. package/dist/lib/http.d.ts +25 -0
  26. package/dist/lib/http.js +128 -2
  27. package/dist/lib/junit-report.d.ts +20 -2
  28. package/dist/lib/junit-report.js +38 -5
  29. package/dist/lib/proxy.d.ts +16 -0
  30. package/dist/lib/proxy.js +19 -1
  31. package/dist/lib/response-schemas.d.ts +7 -0
  32. package/dist/lib/response-schemas.js +23 -1
  33. package/dist/lib/runs.types.d.ts +8 -3
  34. package/dist/lib/secret-file.d.ts +15 -0
  35. package/dist/lib/secret-file.js +82 -0
  36. package/dist/lib/target-url-preflight.d.ts +91 -0
  37. package/dist/lib/target-url-preflight.js +259 -0
  38. package/dist/lib/target-url.d.ts +22 -5
  39. package/dist/lib/target-url.js +60 -28
  40. package/dist/lib/testlist.types.d.ts +77 -0
  41. package/dist/lib/testlist.types.js +9 -0
  42. package/dist/lib/v3-advisory.d.ts +35 -22
  43. package/dist/lib/v3-advisory.js +44 -24
  44. package/dist/lib/wait-exit.d.ts +29 -0
  45. package/dist/lib/wait-exit.js +103 -0
  46. package/dist/version-guard.d.ts +10 -7
  47. package/dist/version-guard.js +37 -9
  48. package/dist/version.d.ts +1 -1
  49. package/dist/version.js +1 -1
  50. package/package.json +1 -1
package/dist/lib/http.js CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import * as v from 'valibot';
3
3
  import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
4
4
  import { VERSION } from '../version.js';
5
- import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, } from './response-schemas.js';
5
+ import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, } from './response-schemas.js';
6
6
  /**
7
7
  * Default per-request timeout (120s). Comfortably covers every metadata/read
8
8
  * request and every <=25s long-poll request (`?waitSeconds` is capped at 25
@@ -41,6 +41,14 @@ const MAX_ATTEMPTS_INTERNAL = 2;
41
41
  const MAX_RATE_LIMITED_DELAY_MS = 60_000;
42
42
  const CONFLICT_DELAY_MS = 1000;
43
43
  const INTERNAL_DELAY_MS = 500;
44
+ // Upper bound on the size of a successful JSON response body the client will
45
+ // buffer into memory. `response.json()` reads the ENTIRE body before parsing,
46
+ // with no limit, so a large `test result --history` page or a run with a long
47
+ // `steps[]` array (getRun `includeSteps`) would grow the heap in proportion to
48
+ // the payload. 64 MiB sits far above any legitimate metadata/history/steps
49
+ // response yet still bounds a pathological — or hostile — one. Override per
50
+ // client via `HttpClientOptions.maxResponseBytes`.
51
+ const MAX_RESPONSE_BYTES_DEFAULT = 64 * 1024 * 1024;
44
52
  // Cap on how many valibot issues a shape-mismatch INTERNAL envelope carries in
45
53
  // `details.issues` (path + message each). Keeps the envelope readable and
46
54
  // guarantees the response body itself is never echoed back to the operator.
@@ -56,6 +64,7 @@ export class HttpClient {
56
64
  onServerVersion;
57
65
  requestTimeoutMs;
58
66
  shutdownSignal;
67
+ maxResponseBytes;
59
68
  constructor(options) {
60
69
  this.baseUrl = trimTrailingSlash(options.baseUrl);
61
70
  this.apiKey = options.apiKey;
@@ -67,6 +76,7 @@ export class HttpClient {
67
76
  this.onTransition = options.onTransition;
68
77
  this.onServerVersion = options.onServerVersion;
69
78
  this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
79
+ this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES_DEFAULT;
70
80
  }
71
81
  /**
72
82
  * Read the backend's supported-floor header off a response and forward it to
@@ -216,6 +226,24 @@ export class HttpClient {
216
226
  retryOnConflict: false,
217
227
  }).then(r => r.body);
218
228
  }
229
+ /**
230
+ * POST /api/cli/v1/testlist/{listId}/run
231
+ * Dispatch a test list's cases (optionally a `testIds` subset) per project
232
+ * with their configured environments; returns pollable runIds. `--wait` polls
233
+ * each `accepted[].runId`.
234
+ *
235
+ * `retryOnConflict: false` — a 409 here (every dispatched project is an
236
+ * MCP-mirrored view-only mirror) is a permanent condition, not a transient one.
237
+ */
238
+ async triggerTestListRun(listId, body, options) {
239
+ return this.postWithMeta(`/testlist/${encodeURIComponent(listId)}/run`, {
240
+ body,
241
+ headers: { 'idempotency-key': options.idempotencyKey },
242
+ signal: options.signal,
243
+ schema: TESTLIST_RUN_RESPONSE_SCHEMA,
244
+ retryOnConflict: false,
245
+ }).then(r => r.body);
246
+ }
219
247
  /**
220
248
  * GET /api/cli/v1/tests/{testId}/runs
221
249
  * List a test's prior run history, newest-first.
@@ -435,12 +463,20 @@ export class HttpClient {
435
463
  });
436
464
  let raw;
437
465
  try {
438
- raw = await response.json();
466
+ // Bounded read, then parse — assigning to `raw` rather than returning
467
+ // here keeps the schema validation below on the success path.
468
+ const text = await readBoundedText(response, this.maxResponseBytes, requestId);
469
+ raw = JSON.parse(text);
439
470
  }
440
471
  catch (err) {
441
472
  // Interrupt passthrough (see the fetch catch above).
442
473
  if (err instanceof InterruptError)
443
474
  throw err;
475
+ // A bounded-read rejection (PAYLOAD_TOO_LARGE) — or any typed ApiError —
476
+ // is a real, actionable outcome; surface it unchanged rather than
477
+ // masking it as a malformed-body error below.
478
+ if (err instanceof ApiError)
479
+ throw err;
444
480
  // A timeout/abort can fire mid-body-read (headers received, stream stalls).
445
481
  this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
446
482
  // Otherwise the successful response body was not valid JSON — a
@@ -805,6 +841,96 @@ export function malformedResponseError(response, requestId, cause) {
805
841
  },
806
842
  }, response.status);
807
843
  }
844
+ /**
845
+ * Read a successful response body as text, bounded to `maxBytes`.
846
+ *
847
+ * `response.json()` buffers the ENTIRE body into memory before parsing, with no
848
+ * upper limit — a large `test result --history` page, or a run with a long
849
+ * `steps[]` array (getRun `includeSteps`), grows the heap in proportion to the
850
+ * payload. This reads the body incrementally and stops once the accumulated
851
+ * size crosses `maxBytes`, so a pathological (or hostile) response fails fast
852
+ * with a typed PAYLOAD_TOO_LARGE error instead of exhausting memory.
853
+ *
854
+ * A declared `Content-Length` over the cap is rejected before any body is read.
855
+ * Chunked bodies (no `Content-Length`) are bounded by counting bytes as they
856
+ * stream. Decoding happens once, at the end, so multi-byte UTF-8 sequences that
857
+ * straddle a chunk boundary still decode correctly.
858
+ */
859
+ async function readBoundedText(response, maxBytes, requestId) {
860
+ const declared = Number(response.headers.get('content-length'));
861
+ if (Number.isFinite(declared) && declared > maxBytes) {
862
+ throw responseTooLargeError(requestId, maxBytes, declared);
863
+ }
864
+ const stream = response.body;
865
+ if (stream === null) {
866
+ // No readable stream exposed (some runtimes / test doubles): fall back to a
867
+ // buffered read, then enforce the cap on the materialized text.
868
+ const text = await response.text();
869
+ if (new TextEncoder().encode(text).length > maxBytes) {
870
+ throw responseTooLargeError(requestId, maxBytes);
871
+ }
872
+ return text;
873
+ }
874
+ const reader = stream.getReader();
875
+ const chunks = [];
876
+ let total = 0;
877
+ try {
878
+ for (;;) {
879
+ const { done, value } = await reader.read();
880
+ if (done)
881
+ break;
882
+ if (value === undefined)
883
+ continue;
884
+ total += value.byteLength;
885
+ if (total > maxBytes) {
886
+ await reader.cancel();
887
+ throw responseTooLargeError(requestId, maxBytes, total);
888
+ }
889
+ chunks.push(value);
890
+ }
891
+ }
892
+ finally {
893
+ try {
894
+ reader.releaseLock();
895
+ }
896
+ catch {
897
+ // The reader may already be released after cancel(); releasing twice is a
898
+ // no-op we don't want surfacing over the original error.
899
+ }
900
+ }
901
+ return new TextDecoder('utf-8').decode(concatChunks(chunks, total));
902
+ }
903
+ /** Concatenate byte chunks into a single `Uint8Array` of known total length. */
904
+ function concatChunks(chunks, total) {
905
+ const out = new Uint8Array(total);
906
+ let offset = 0;
907
+ for (const chunk of chunks) {
908
+ out.set(chunk, offset);
909
+ offset += chunk.byteLength;
910
+ }
911
+ return out;
912
+ }
913
+ /**
914
+ * Typed error for a response body that exceeds the client-side buffering cap.
915
+ * Reuses PAYLOAD_TOO_LARGE (exit 5, validation family) — the same code the
916
+ * backend returns for oversized request bodies — so machine consumers route on
917
+ * it uniformly. `nextAction` names the knobs that shrink the result set.
918
+ */
919
+ function responseTooLargeError(requestId, maxBytes, observedBytes) {
920
+ const limitMiB = Math.round(maxBytes / (1024 * 1024));
921
+ return new ApiError({
922
+ code: 'PAYLOAD_TOO_LARGE',
923
+ message: `The server response exceeded the client-side ${limitMiB} MiB limit and was not ` +
924
+ `buffered, to avoid unbounded memory use.`,
925
+ nextAction: 'Narrow the result set and retry — e.g. a smaller --page-size, a tighter --since ' +
926
+ 'window, or scope --history to a single run.',
927
+ requestId,
928
+ details: {
929
+ maxBytes,
930
+ ...(observedBytes !== undefined ? { observedBytes } : {}),
931
+ },
932
+ });
933
+ }
808
934
  export function parseRetryAfter(headerValue) {
809
935
  if (!headerValue)
810
936
  return undefined;
@@ -11,7 +11,24 @@ export interface JUnitTestResult {
11
11
  message: string;
12
12
  exitCode?: number;
13
13
  };
14
+ /**
15
+ * Human-readable test name for the `testcase name` attribute. Falls back to
16
+ * `testId` when absent (older data / a run whose name could not be resolved).
17
+ * A CI test tab renders this, not the UUID.
18
+ */
19
+ name?: string;
20
+ /**
21
+ * Wall-clock duration of the run in seconds, for `testcase time`. Derived from
22
+ * the poll result's `startedAt`/`finishedAt`; omitted when timing is absent
23
+ * (rendered as `0`, the pre-fix behaviour).
24
+ */
25
+ durationSeconds?: number;
14
26
  }
27
+ /**
28
+ * Duration in seconds between two ISO timestamps, or `undefined` when either is
29
+ * missing / unparseable / negative (clock skew). Kept ≥ 0.
30
+ */
31
+ export declare function durationSecondsBetween(startedAt: string | null | undefined, finishedAt: string | null | undefined): number | undefined;
15
32
  export interface JUnitReportBuildOptions {
16
33
  suiteName: string;
17
34
  classname: string;
@@ -48,8 +65,9 @@ export declare function resolveBatchReportProjectId(opts: {
48
65
  */
49
66
  export declare function escapeXml(text: string): string;
50
67
  /**
51
- * Build a JUnit XML document from batch poll results. Duration is `0` in v1
52
- * because batch poll envelopes do not carry per-run timing.
68
+ * Build a JUnit XML document from batch poll results. Per-`testcase` `time` is
69
+ * the run's wall-clock duration (from `startedAt`/`finishedAt`); the `testsuite`
70
+ * `time` is their sum. `time` falls back to `0` for a run with no timing.
53
71
  */
54
72
  export declare function buildJUnitReport(opts: JUnitReportBuildOptions): string;
55
73
  /**
@@ -3,6 +3,26 @@ import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { localValidationError, TransportError } from './errors.js';
6
+ /**
7
+ * Duration in seconds between two ISO timestamps, or `undefined` when either is
8
+ * missing / unparseable / negative (clock skew). Kept ≥ 0.
9
+ */
10
+ export function durationSecondsBetween(startedAt, finishedAt) {
11
+ if (!startedAt || !finishedAt)
12
+ return undefined;
13
+ const start = Date.parse(startedAt);
14
+ const end = Date.parse(finishedAt);
15
+ if (Number.isNaN(start) || Number.isNaN(end))
16
+ return undefined;
17
+ const seconds = (end - start) / 1000;
18
+ return seconds >= 0 ? seconds : undefined;
19
+ }
20
+ /** Format a duration for the JUnit `time` attribute (3 dp; absent → `0`). */
21
+ function formatTime(seconds) {
22
+ if (seconds === undefined || Number.isNaN(seconds))
23
+ return '0';
24
+ return (Math.round(seconds * 1000) / 1000).toString();
25
+ }
6
26
  const XML_DECL = '<?xml version="1.0" encoding="UTF-8"?>';
7
27
  /**
8
28
  * Parse `--report <format>`. Only `junit` is accepted in v1.
@@ -79,9 +99,17 @@ function failureMessage(result) {
79
99
  }
80
100
  function renderTestcase(result, classname) {
81
101
  const outcome = classifyJUnitOutcome(result.status, result.error);
82
- const name = escapeXml(result.testId);
102
+ // A readable CI test tab keys on `name`: prefer the human test name, fall back
103
+ // to the id. The UUID is preserved as a `testId` attribute (ignored by
104
+ // renderers, read by machine consumers) so the switch loses no information.
105
+ const name = escapeXml(result.name?.trim() || result.testId);
83
106
  const cls = escapeXml(classname);
84
- const lines = [` <testcase classname="${cls}" name="${name}" time="0">`];
107
+ const time = formatTime(result.durationSeconds);
108
+ const idAttr = ` testId="${escapeXml(result.testId)}"`;
109
+ const runAttr = result.runId ? ` runId="${escapeXml(result.runId)}"` : '';
110
+ const lines = [
111
+ ` <testcase classname="${cls}" name="${name}"${idAttr}${runAttr} time="${time}">`,
112
+ ];
85
113
  if (outcome === 'failure') {
86
114
  const message = escapeXml(failureMessage(result));
87
115
  const type = escapeXml(result.status);
@@ -114,14 +142,16 @@ function renderTestcase(result, classname) {
114
142
  return lines.join('\n');
115
143
  }
116
144
  /**
117
- * Build a JUnit XML document from batch poll results. Duration is `0` in v1
118
- * because batch poll envelopes do not carry per-run timing.
145
+ * Build a JUnit XML document from batch poll results. Per-`testcase` `time` is
146
+ * the run's wall-clock duration (from `startedAt`/`finishedAt`); the `testsuite`
147
+ * `time` is their sum. `time` falls back to `0` for a run with no timing.
119
148
  */
120
149
  export function buildJUnitReport(opts) {
121
150
  const results = opts.results;
122
151
  let failures = 0;
123
152
  let errors = 0;
124
153
  let skipped = 0;
154
+ let totalSeconds = 0;
125
155
  for (const result of results) {
126
156
  const outcome = classifyJUnitOutcome(result.status, result.error);
127
157
  if (outcome === 'failure')
@@ -130,13 +160,16 @@ export function buildJUnitReport(opts) {
130
160
  errors++;
131
161
  else if (outcome === 'skipped')
132
162
  skipped++;
163
+ if (typeof result.durationSeconds === 'number' && result.durationSeconds >= 0) {
164
+ totalSeconds += result.durationSeconds;
165
+ }
133
166
  }
134
167
  const suiteName = escapeXml(opts.suiteName);
135
168
  const testcases = results.map(r => renderTestcase(r, opts.classname)).join('\n');
136
169
  return [
137
170
  XML_DECL,
138
171
  '<testsuites>',
139
- ` <testsuite name="${suiteName}" tests="${results.length}" failures="${failures}" errors="${errors}" skipped="${skipped}" time="0">`,
172
+ ` <testsuite name="${suiteName}" tests="${results.length}" failures="${failures}" errors="${errors}" skipped="${skipped}" time="${formatTime(totalSeconds)}">`,
140
173
  testcases,
141
174
  ' </testsuite>',
142
175
  '</testsuites>',
@@ -27,3 +27,19 @@ export interface ProxyDeps {
27
27
  * Returns whether an agent was installed (observable for tests/debugging).
28
28
  */
29
29
  export declare function maybeInstallProxyAgent(deps?: ProxyDeps): boolean;
30
+ /**
31
+ * Whether the currently-installed global dispatcher is the proxy-aware
32
+ * agent `maybeInstallProxyAgent` installs — i.e., whether a proxy is
33
+ * actually wired up for outgoing `fetch()` calls in this process, not
34
+ * merely whether an `HTTP(S)_PROXY` env var happens to be set.
35
+ *
36
+ * This distinction matters: a CI runner can export `HTTPS_PROXY` for
37
+ * unrelated registry/package-manager egress without that value ever
38
+ * reaching this CLI's proxy path (e.g. it ran before `maybeInstallProxyAgent`
39
+ * executed, or `install()` threw and fell back to the default dispatcher).
40
+ * Consumers that need to know "is my request actually going through a
41
+ * proxy" — the target-url reachability preflight's refuse→warn downgrade,
42
+ * specifically — must check this, not the env var, or an unrelated,
43
+ * unexercised proxy variable silently defangs their guard.
44
+ */
45
+ export declare function isProxyAgentActive(): boolean;
package/dist/lib/proxy.js CHANGED
@@ -1,4 +1,4 @@
1
- import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
1
+ import { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
2
2
  /**
3
3
  * Install the env-driven proxy dispatcher when any proxy variable is set
4
4
  * (both canonical upper-case and conventional lower-case spellings).
@@ -27,4 +27,22 @@ export function maybeInstallProxyAgent(deps = {}) {
27
27
  return false;
28
28
  }
29
29
  }
30
+ /**
31
+ * Whether the currently-installed global dispatcher is the proxy-aware
32
+ * agent `maybeInstallProxyAgent` installs — i.e., whether a proxy is
33
+ * actually wired up for outgoing `fetch()` calls in this process, not
34
+ * merely whether an `HTTP(S)_PROXY` env var happens to be set.
35
+ *
36
+ * This distinction matters: a CI runner can export `HTTPS_PROXY` for
37
+ * unrelated registry/package-manager egress without that value ever
38
+ * reaching this CLI's proxy path (e.g. it ran before `maybeInstallProxyAgent`
39
+ * executed, or `install()` threw and fell back to the default dispatcher).
40
+ * Consumers that need to know "is my request actually going through a
41
+ * proxy" — the target-url reachability preflight's refuse→warn downgrade,
42
+ * specifically — must check this, not the env var, or an unrelated,
43
+ * unexercised proxy variable silently defangs their guard.
44
+ */
45
+ export function isProxyAgentActive() {
46
+ return getGlobalDispatcher() instanceof EnvHttpProxyAgent;
47
+ }
30
48
  //# sourceMappingURL=proxy.js.map
@@ -33,6 +33,7 @@
33
33
  */
34
34
  import * as v from 'valibot';
35
35
  import type { BatchRerunResponse, BatchRunFreshResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
36
+ import type { CliTestListRunResponse } from './testlist.types.js';
36
37
  /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
37
38
  export declare const RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RunResponse>;
38
39
  /** Mirrors `TriggerRunResponse` (runs.types.ts): `POST /tests/{testId}/runs`. */
@@ -43,6 +44,12 @@ export declare const RERUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RerunRespon
43
44
  export declare const BATCH_RERUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, BatchRerunResponse>;
44
45
  /** Mirrors `BatchRunFreshResponse` (runs.types.ts): `POST /tests/batch/run`. */
45
46
  export declare const BATCH_RUN_FRESH_RESPONSE_SCHEMA: v.GenericSchema<unknown, BatchRunFreshResponse>;
47
+ /**
48
+ * `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
49
+ * the `--wait` fan-out reuses the same poll tail; `conflicts[]` additionally
50
+ * carry the in-flight `currentRunId`, and `reason` marks a nothing-dispatched run.
51
+ */
52
+ export declare const TESTLIST_RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, CliTestListRunResponse>;
46
53
  /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
47
54
  export declare const LIST_RUNS_RESPONSE_SCHEMA: v.GenericSchema<unknown, ListRunsResponse>;
48
55
  /**
@@ -220,11 +220,33 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
220
220
  enqueuedAt: v.string(),
221
221
  dashboardUrl: v.optional(v.string()),
222
222
  })),
223
- conflicts: v.array(v.looseObject({ testId: v.string() })),
223
+ conflicts: v.array(v.looseObject({
224
+ testId: v.string(),
225
+ currentRunId: v.optional(v.string()),
226
+ reason: v.optional(v.string()),
227
+ message: v.optional(v.string()),
228
+ })),
224
229
  deferred: v.array(v.looseObject({ testId: v.string() })),
225
230
  skippedFrontend: v.array(v.string()),
226
231
  skippedIntegration: v.array(v.looseObject({ testId: v.string() })),
227
232
  });
233
+ /**
234
+ * `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
235
+ * the `--wait` fan-out reuses the same poll tail; `conflicts[]` additionally
236
+ * carry the in-flight `currentRunId`, and `reason` marks a nothing-dispatched run.
237
+ */
238
+ export const TESTLIST_RUN_RESPONSE_SCHEMA = v.looseObject({
239
+ accepted: v.array(v.looseObject({ testId: v.string(), runId: v.string(), enqueuedAt: v.string() })),
240
+ conflicts: v.array(v.looseObject({
241
+ testId: v.string(),
242
+ currentRunId: v.optional(v.string()),
243
+ reason: v.optional(v.string()),
244
+ message: v.optional(v.string()),
245
+ })),
246
+ deferred: v.array(v.looseObject({ testId: v.string() })),
247
+ notFound: v.optional(v.array(v.string())),
248
+ reason: v.optional(v.string()),
249
+ });
228
250
  // ---------------------------------------------------------------------------
229
251
  // GET /tests/{testId}/runs
230
252
  // ---------------------------------------------------------------------------
@@ -4,6 +4,7 @@
4
4
  * Extended by M3.4 piece-5 — `test result --history` command.
5
5
 
6
6
  */
7
+ import type { RunConflict } from './conflict-reason.js';
7
8
  /** Literal body sent to `POST /api/cli/v1/tests/{testId}/runs`. */
8
9
  export interface TriggerRunBody {
9
10
  /** Fixed source literal for CLI-triggered runs. */
@@ -385,9 +386,13 @@ export interface BatchRunFreshAccepted {
385
386
  */
386
387
  export interface BatchRunFreshResponse {
387
388
  accepted: BatchRunFreshAccepted[];
388
- conflicts: Array<{
389
- testId: string;
390
- }>;
389
+ /**
390
+ * A run-slot conflict. `currentRunId`, when present, is the id of the run
391
+ * ALREADY in flight for this test — under `--wait` the CLI polls it to a
392
+ * verdict (auto-resume) instead of failing the batch. Absent ⇒ a hard
393
+ * conflict with no resolvable in-flight run (still fails the batch).
394
+ */
395
+ conflicts: RunConflict[];
391
396
  deferred: Array<{
392
397
  testId: string;
393
398
  }>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Read a secret from `path`, surfacing every filesystem failure as a typed
3
+ * `VALIDATION_ERROR` (exit 5) attributed to `flag`.
4
+ *
5
+ * The returned value is trimmed, matching what the unguarded call sites did.
6
+ * Trimming also drops a leading UTF-8 BOM: `U+FEFF` is ECMAScript whitespace,
7
+ * so a file written by PowerShell 5.1's default `Set-Content -Encoding utf8`
8
+ * no longer smuggles an invisible character into the secret.
9
+ *
10
+ * @param flag - Flag name without the leading dashes, e.g. `'password-file'`.
11
+ * @param path - Path as supplied by the user; may be relative.
12
+ * @throws {ApiError} `VALIDATION_ERROR` when the path is missing, unreadable,
13
+ * or not a regular file.
14
+ */
15
+ export declare function readSecretFileGuarded(flag: string, path: string): string;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Guarded reader for the `--*-file` secret flags.
3
+ *
4
+ * Every one of these flags exists so a secret stays out of shell history, and
5
+ * every one of them is a path the user types by hand — so a typo is the
6
+ * expected failure, not an exceptional one. A bare
7
+ * `readFileSync(path, 'utf8').trim()` turns that typo into an unhandled Node
8
+ * exception: exit `1` instead of `5`, an `--output json` payload whose `error`
9
+ * is a bare string rather than the `{ code, message, nextAction }` envelope the
10
+ * rest of the CLI emits, and the absolute path plus errno leaked to stderr.
11
+ *
12
+ * This maps those failures onto the same typed `VALIDATION_ERROR` envelope the
13
+ * already-guarded file flags produce, mirroring `readCodeFileGuarded` in
14
+ * `src/commands/test.ts`. The payload cap is deliberately not carried over:
15
+ * secrets are small, and a size ceiling would be a behaviour change on a
16
+ * shipped flag rather than part of fixing the crash.
17
+ *
18
+ * Callers pass the flag name so the envelope names the flag the user actually
19
+ * typed — one helper serves `--password-file` today and the remaining
20
+ * credential/auto-auth file flags once they are migrated.
21
+ */
22
+ import { readFileSync, statSync } from 'node:fs';
23
+ import { isAbsolute, resolve } from 'node:path';
24
+ import { localValidationError } from './errors.js';
25
+ /**
26
+ * Read a secret from `path`, surfacing every filesystem failure as a typed
27
+ * `VALIDATION_ERROR` (exit 5) attributed to `flag`.
28
+ *
29
+ * The returned value is trimmed, matching what the unguarded call sites did.
30
+ * Trimming also drops a leading UTF-8 BOM: `U+FEFF` is ECMAScript whitespace,
31
+ * so a file written by PowerShell 5.1's default `Set-Content -Encoding utf8`
32
+ * no longer smuggles an invisible character into the secret.
33
+ *
34
+ * @param flag - Flag name without the leading dashes, e.g. `'password-file'`.
35
+ * @param path - Path as supplied by the user; may be relative.
36
+ * @throws {ApiError} `VALIDATION_ERROR` when the path is missing, unreadable,
37
+ * or not a regular file.
38
+ */
39
+ export function readSecretFileGuarded(flag, path) {
40
+ const absolute = isAbsolute(path) ? path : resolve(process.cwd(), path);
41
+ let stat;
42
+ try {
43
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- this is the guard itself: `absolute` is the user-supplied `--*-file` path after isAbsolute()/resolve() normalization, and this statSync().isFile() check (below) plus the try/catch mapping every errno to a typed VALIDATION_ERROR is exactly the mitigation for a non-literal fs path here.
44
+ stat = statSync(absolute);
45
+ }
46
+ catch (err) {
47
+ throw secretFileError(flag, path, err, 'stat');
48
+ }
49
+ // A directory would otherwise reach readFileSync and throw EISDIR on Linux
50
+ // while resolving to an empty read on some platforms — reject it up front so
51
+ // the contract is the same everywhere.
52
+ if (!stat.isFile()) {
53
+ throw localValidationError(flag, `not a regular file: ${path}`);
54
+ }
55
+ try {
56
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- same guarded path as the statSync() above: `absolute` already passed the isFile() regular-file check, so this read is the guard's intended purpose (reading a user-supplied secret path), not an unvalidated pass-through.
57
+ return readFileSync(absolute, 'utf8').trim();
58
+ }
59
+ catch (err) {
60
+ throw secretFileError(flag, path, err, 'read');
61
+ }
62
+ }
63
+ /**
64
+ * Translate a Node filesystem error into the CLI's validation envelope,
65
+ * reporting the path the user typed rather than the resolved absolute path so
66
+ * no directory layout leaks into output.
67
+ */
68
+ function secretFileError(flag, path, err, verb) {
69
+ const code = err.code;
70
+ if (code === 'ENOENT') {
71
+ return localValidationError(flag, `file does not exist: ${path}`);
72
+ }
73
+ if (code === 'EACCES' || code === 'EPERM') {
74
+ return localValidationError(flag, `permission denied reading ${path}`);
75
+ }
76
+ if (code === 'EISDIR') {
77
+ return localValidationError(flag, `not a regular file: ${path}`);
78
+ }
79
+ const reason = err instanceof Error ? err.message : 'unknown error';
80
+ return localValidationError(flag, `cannot ${verb} ${path}: ${reason}`);
81
+ }
82
+ //# sourceMappingURL=secret-file.js.map
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Pre-charge reachability preflight for a caller-supplied `--target-url`.
3
+ *
4
+ * A blocked-run analysis measured 1,003 blocked-with-URL CLI runs: 26%
5
+ * pointed at a third-party tunnel host (`*.trycloudflare.com`, `*.loca.lt`,
6
+ * ngrok), 55.5% of those were blocked, and every one of them was charged
7
+ * anyway — the run row and its credit spend happen before the Lambda ever
8
+ * discovers the target is dead. This probe runs BEFORE the trigger POST so
9
+ * an obviously-doomed run never gets a run row or a charge.
10
+ *
11
+ * **Honest limitation** (this must also be stated in `--help` and the PR
12
+ * body): the probe below runs from wherever this CLI process runs — the
13
+ * caller's laptop, a CI runner — while the actual test executes from a
14
+ * Lambda inside AWS. Reachability from one is not proof of reachability
15
+ * from the other. That asymmetry is why the refusal set is deliberately
16
+ * narrow (only the failure classes that analysis actually measured — a
17
+ * broader rule would not have prevented a single one of those 1,003 runs), why
18
+ * every ambiguous signal downgrades to a warning instead of a hard block,
19
+ * and why `--skip-preflight` exists as a full opt-out (zero network calls).
20
+ *
21
+ * Two injectable seams, mirroring the MCP plugin's `checkPortListening`
22
+ * shape (a cheap first check, then an HTTP-level fallback for the signal
23
+ * the first check can't see) rather than inventing a new one:
24
+ * - `dnsLookup` — a raw DNS resolution. Deliberately separate from the
25
+ * HTTP probe below: `proxy.ts` installs a proxy dispatcher that only
26
+ * `fetch()` honours, never a raw socket/DNS call, so behind a
27
+ * configured HTTP(S) proxy this step can fail locally (the real
28
+ * resolution happens at the proxy) even though the target is reachable
29
+ * — hence the proxy carve-out downgrades a negative *failure* result
30
+ * here. A resolved address landing in the private/loopback/link-local/
31
+ * metadata range is a different kind of signal (DNS rebinding, not
32
+ * ambiguity about where resolution happens) and always refuses — see
33
+ * the resolved-address check below.
34
+ * - `fetchImpl` — the actual HTTP probe (proxy-aware once a proxy
35
+ * dispatcher is installed), used for the 502/503/504 gateway-error
36
+ * signal a DNS/TCP-level check cannot see at all. Runs with
37
+ * `redirect: 'manual'`: a 3xx is treated as a live/reachable signal
38
+ * (a real app 302ing to a login page is healthy) but is never
39
+ * followed — the redirect target is unvalidated by everything above
40
+ * (`assertNotLocal` only ever inspected the literal `--target-url`
41
+ * string; the resolved-address check only covers *this* URL's host),
42
+ * so following it would hand an attacker-controlled Location header a
43
+ * live SSRF primitive running on the caller's machine or CI runner.
44
+ */
45
+ export interface TargetUrlPreflightDeps {
46
+ /** DNS resolution hook. Defaults to `dns.promises.lookup`. Injectable for tests. */
47
+ dnsLookup?: (hostname: string) => Promise<unknown>;
48
+ /** HTTP probe hook. Defaults to the global `fetch`. Injectable for tests. */
49
+ fetchImpl?: typeof fetch;
50
+ /**
51
+ * Whether a proxy dispatcher is actually installed for this process.
52
+ * Defaults to `isProxyAgentActive()` (proxy.ts), which inspects the
53
+ * active global undici dispatcher — deliberately NOT an env-var check:
54
+ * an `HTTP(S)_PROXY` variable can be present in the environment (e.g. a
55
+ * CI runner exporting it for unrelated package-registry egress) without
56
+ * this CLI ever having installed a dispatcher for it, and gating the
57
+ * refuse→warn downgrade on the env var alone would silently soften every
58
+ * refusal in exactly that environment. Injectable for tests so they don't
59
+ * need to mutate the real global dispatcher to exercise the proxy path.
60
+ */
61
+ proxyActive?: boolean;
62
+ }
63
+ export type TargetUrlPreflightOutcome = {
64
+ verdict: 'ok';
65
+ } | {
66
+ verdict: 'warn';
67
+ reason: string;
68
+ } | {
69
+ verdict: 'refuse';
70
+ reason: string;
71
+ };
72
+ /**
73
+ * Probe `rawUrl` for the narrow refusal set described in the module
74
+ * docstring. Pure decision function — never throws for a network failure
75
+ * (every reachable failure classifies to `warn` or `refuse`); a malformed
76
+ * URL degrades to `warn` rather than crashing (callers validate the URL
77
+ * shape via `assertNotLocal` before this runs).
78
+ */
79
+ export declare function probeTargetUrl(rawUrl: string, deps?: TargetUrlPreflightDeps): Promise<TargetUrlPreflightOutcome>;
80
+ /**
81
+ * Run the preflight and either throw (refuse), print an `[advisory]` line
82
+ * (warn), or no-op (ok / skipped). This is the call-site integration point
83
+ * — wired at all four `--target-url` trigger paths, after `assertNotLocal`
84
+ * and before the trigger POST.
85
+ *
86
+ * `skipPreflight: true` makes this a pure no-op with ZERO network calls —
87
+ * neither `dnsLookup` nor `fetchImpl` is invoked.
88
+ */
89
+ export declare function assertTargetUrlReachable(targetUrl: string, opts: {
90
+ skipPreflight?: boolean;
91
+ }, deps: TargetUrlPreflightDeps, stderrFn: (line: string) => void): Promise<void>;