@testsprite/testsprite-cli 0.3.0 → 0.5.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 (63) hide show
  1. package/README.md +55 -29
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +51 -0
  4. package/dist/commands/auth.js +46 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +56 -16
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +102 -4
  11. package/dist/commands/project.js +250 -47
  12. package/dist/commands/test.d.ts +253 -11
  13. package/dist/commands/test.js +1822 -390
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +172 -29
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +144 -84
  21. package/dist/lib/client-factory.d.ts +29 -0
  22. package/dist/lib/client-factory.js +49 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +51 -1
  27. package/dist/lib/errors.d.ts +33 -1
  28. package/dist/lib/errors.js +110 -19
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +12 -1
  32. package/dist/lib/flaky.js +7 -12
  33. package/dist/lib/gh-output.d.ts +62 -0
  34. package/dist/lib/gh-output.js +99 -0
  35. package/dist/lib/http.d.ts +86 -16
  36. package/dist/lib/http.js +181 -11
  37. package/dist/lib/interrupt.d.ts +65 -10
  38. package/dist/lib/interrupt.js +94 -9
  39. package/dist/lib/org-render.d.ts +52 -0
  40. package/dist/lib/org-render.js +59 -0
  41. package/dist/lib/poll.d.ts +11 -0
  42. package/dist/lib/poll.js +71 -6
  43. package/dist/lib/render-error.d.ts +14 -0
  44. package/dist/lib/render-error.js +30 -0
  45. package/dist/lib/response-schemas.d.ts +83 -0
  46. package/dist/lib/response-schemas.js +272 -0
  47. package/dist/lib/runs.types.d.ts +62 -8
  48. package/dist/lib/skill-nudge.d.ts +17 -0
  49. package/dist/lib/skill-nudge.js +19 -0
  50. package/dist/lib/telemetry.d.ts +90 -0
  51. package/dist/lib/telemetry.js +171 -0
  52. package/dist/lib/text-table.d.ts +14 -0
  53. package/dist/lib/text-table.js +45 -0
  54. package/dist/lib/v3-advisory.d.ts +22 -0
  55. package/dist/lib/v3-advisory.js +32 -0
  56. package/dist/lib/version-notice.d.ts +37 -0
  57. package/dist/lib/version-notice.js +87 -0
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/package.json +16 -5
  61. package/schemas/plan.schema.json +61 -0
  62. package/skills/testsprite-verify.codex.md +8 -2
  63. package/skills/testsprite-verify.skill.md +18 -7
@@ -32,10 +32,11 @@
32
32
  * - Resume after a partial bundle. M2 always re-fetches from scratch
33
33
  * when the agent re-runs. M3 may add resume.
34
34
  */
35
+ import { randomUUID } from 'node:crypto';
35
36
  import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
36
37
  import { pipeline } from 'node:stream/promises';
37
38
  import { createWriteStream } from 'node:fs';
38
- import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
39
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
39
40
  import { ApiError, TransportError, localValidationError } from './errors.js';
40
41
  import { requireEnum } from './validate.js';
41
42
  /** Schema version stamped into `meta.json`. Bumps with the contract. */
@@ -169,6 +170,24 @@ export function applyFailedOnly(ctx) {
169
170
  failure: { ...ctx.failure, evidence: filteredEvidence },
170
171
  };
171
172
  }
173
+ /**
174
+ * Strip trailing path separators, tolerating both `/` and `\` since a
175
+ * native Windows `--out` value (typed or pasted from Explorer) commonly
176
+ * ends in a backslash. Preserves a bare drive root (`C:\`) — stripping
177
+ * its separator would turn it into `C:`, which Windows resolves as
178
+ * "current directory on drive C", not the drive root.
179
+ */
180
+ function stripTrailingSeparators(rawPath) {
181
+ if (rawPath.length <= 1)
182
+ return rawPath;
183
+ let end = rawPath.length;
184
+ while (end > 1 && (rawPath[end - 1] === '/' || rawPath[end - 1] === '\\')) {
185
+ if (end === 3 && rawPath[1] === ':' && /[A-Za-z]/.test(rawPath[0]))
186
+ break;
187
+ end--;
188
+ }
189
+ return rawPath.slice(0, end);
190
+ }
172
191
  /**
173
192
  * Resolve the user-supplied `--out` path into an absolute directory.
174
193
  * Empty strings are rejected with `VALIDATION_ERROR` for consistency
@@ -188,7 +207,7 @@ export function resolveBundleDir(rawPath) {
188
207
  },
189
208
  });
190
209
  }
191
- const trimmed = rawPath.endsWith('/') ? rawPath.slice(0, -1) : rawPath;
210
+ const trimmed = stripTrailingSeparators(rawPath);
192
211
  return isAbsolute(trimmed) ? trimmed : resolve(process.cwd(), trimmed);
193
212
  }
194
213
  /**
@@ -211,6 +230,28 @@ export function pickCodeExtension(language, framework) {
211
230
  return 'py';
212
231
  return 'py';
213
232
  }
233
+ /** Recording container extensions the bundle writer will trust from `videoUrl`. */
234
+ const KNOWN_VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'mkv', 'avi']);
235
+ /**
236
+ * Pick the on-disk extension for `<dir>/video.<ext>` from the actual
237
+ * `result.videoUrl`, instead of hardcoding `mp4` (the
238
+ * recording is sometimes a `.webm` container; saving it under a `video.mp4`
239
+ * name misleads strict-extension consumers). Falls back to `mp4` when the
240
+ * URL is malformed or its extension isn't a recognized container, so a
241
+ * response-controlled field can never smuggle an arbitrary suffix onto disk.
242
+ */
243
+ export function pickVideoExtension(url) {
244
+ try {
245
+ const match = /\.([A-Za-z0-9]+)$/.exec(new URL(url).pathname);
246
+ const ext = match?.[1]?.toLowerCase();
247
+ if (ext !== undefined && KNOWN_VIDEO_EXTENSIONS.has(ext))
248
+ return ext;
249
+ }
250
+ catch {
251
+ // Malformed URL — fall through to the default below.
252
+ }
253
+ return 'mp4';
254
+ }
214
255
  /**
215
256
  * Step filename per §7.2 — 1-based index, zero-padded to two digits
216
257
  * for indices ≤ 99, three digits for ≥ 100. `${stepIndex}-snapshot.html`
@@ -260,8 +301,9 @@ export function buildMeta(ctx, fetchedAt = new Date()) {
260
301
  * 2. `applyFailedOnly` — narrow before download (saves bytes).
261
302
  * 3. `mkdir <dir>/.tmp/` — fresh; clean any stale temp.
262
303
  * 4. `writeFile result.json / failure.json / code.<ext>` — local data.
263
- * 5. `fetch + stream` for `video.mp4` (when set) and per-step
264
- * snapshot/screenshot/evidence-json files.
304
+ * 5. `fetch + stream` for `video.<ext>` (when set; extension matches the
305
+ * actual recording container) and per-step snapshot/screenshot/
306
+ * evidence-json files.
265
307
  * 6. `writeFile meta.json` LAST — its presence means "bundle complete".
266
308
  * 7. `rename .tmp/<file> -> <file>` for every file. Last rename
267
309
  * makes meta.json visible.
@@ -310,10 +352,12 @@ export async function writeBundle(ctx, options) {
310
352
  // Optional video. Wire field is `result.videoUrl` (not in `failure`),
311
353
  // and the CLI surfaces it as a top-level on-disk artifact for agent
312
354
  // ergonomics — the agent doesn't have to know which sub-object held
313
- // it on the wire.
355
+ // it on the wire. Extension matches the actual recording container
356
+ // (some runs ship `.webm`, not `.mp4`).
314
357
  if (filtered.result.videoUrl) {
315
- await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, 'video.mp4'), fetchImpl);
316
- filesWritten.push('video.mp4');
358
+ const videoFile = `video.${pickVideoExtension(filtered.result.videoUrl)}`;
359
+ await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl);
360
+ filesWritten.push(videoFile);
317
361
  }
318
362
  for (const step of filtered.steps) {
319
363
  await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten);
@@ -347,101 +391,117 @@ async function freshTmpDir(dir) {
347
391
  await mkdir(tmpDir, { recursive: true });
348
392
  return tmpDir;
349
393
  }
350
- /**
351
- * Rename `<tmp>/<file>` → `<dir>/<file>` for every file in `files`.
352
- *
353
- * Critical ordering for atomicity (the §3 "agent-safe" contract):
354
- *
355
- * 1. **Remove the OLD `meta.json` first.** The bundle's completion
356
- * signal is `meta.json`'s presence; an agent reading `<dir>` while
357
- * we're mutating it must see "no meta → bundle absent or
358
- * mid-write" rather than "meta points at a snapshot that's already
359
- * been partially overwritten." Removing the old meta is what
360
- * makes the rest of the swap safe to do in place.
361
- * 2. Wipe stale top-level files (e.g. an old `video.mp4` when the new
362
- * bundle has no video). Without this, a fresh bundle could ship
363
- * with a stale video lingering at the top level.
364
- * 3. Replace `<dir>/steps/` wholesale.
365
- * 4. Rename top-level files into place.
366
- * 5. **Rename `meta.json` LAST.** Its visible presence is the atomic
367
- * completion signal; until step 5 lands, agents see "incomplete."
368
- *
369
- * The window between (1) and (5) is bounded by a handful of `rename`
370
- * syscalls — small enough that a SIGKILL there is rare, and any agent
371
- * caught reading the dir during it sees no meta and refuses to consume
372
- * (per §7.3). That's what we want.
373
- */
374
394
  /**
375
395
  * Whether a top-level directory entry belongs to the bundle format —
376
396
  * i.e. something a prior `writeBundle` could have produced and this
377
- * commit is therefore allowed to clean up. `code.<ext>` is matched by
378
- * pattern (not the current run's extension) so a stale `code.py` is
379
- * still swept when the new bundle writes `code.ts`. Everything else in
380
- * the directory is the user's and must never be deleted (`--out` can
381
- * point at a pre-existing, populated directory).
397
+ * commit is therefore allowed to clean up. `code.<ext>` and `video.<ext>`
398
+ * are matched by pattern (not the current run's extension) so a stale
399
+ * `code.py` or `video.webm` is still swept when the new bundle writes
400
+ * `code.ts` / `video.mp4` (or no video at all). Everything else in the
401
+ * directory is the user's and must never be deleted (`--out` can point at
402
+ * a pre-existing, populated directory).
382
403
  */
383
404
  export function isBundleOwnedEntry(entry) {
384
405
  if (entry === 'result.json' ||
385
406
  entry === 'failure.json' ||
386
- entry === 'video.mp4' ||
387
407
  entry === 'meta.json' ||
388
408
  entry === 'steps' ||
389
409
  entry === '.tmp' ||
390
410
  entry === '.partial') {
391
411
  return true;
392
412
  }
393
- return /^code\.[A-Za-z0-9]+$/.test(entry);
413
+ // Videos: only the extensions the bundle itself can write (see
414
+ // KNOWN_VIDEO_EXTENSIONS / pickVideoExtension). A broader `video.*`
415
+ // pattern would claim user files like `video.txt` sitting in a
416
+ // pre-existing `--out` directory and delete them in the sweep.
417
+ return (/^code\.[A-Za-z0-9]+$/.test(entry) ||
418
+ (entry.startsWith('video.') && KNOWN_VIDEO_EXTENSIONS.has(entry.slice('video.'.length))));
394
419
  }
395
- async function commitBundle(tmpDir, dir, files) {
396
- // (1) Remove the prior bundle's completion signal FIRST.
397
- await unlink(join(dir, 'meta.json')).catch(() => undefined);
398
- // (2) Sweep stale top-level files that the new bundle won't write.
399
- // If the prior run wrote `video.mp4` and the new run has no video,
400
- // an in-place rename leaves the old video lingering. Only entries the
401
- // bundle format OWNS are candidates: `--out` may point at a directory
402
- // that also holds the user's unrelated files, and those must survive
403
- // the commit (deleting them would be silent data loss).
404
- const topLevel = files.filter(f => !f.startsWith('steps/'));
405
- const newTopLevelSet = new Set(topLevel);
406
- newTopLevelSet.add('meta.json'); // about to land last, do not delete
407
- const existing = await readdir(dir).catch(() => []);
408
- for (const entry of existing) {
409
- // Preserve the writer's own scratch dir + the .partial marker
410
- // (we'll re-evaluate .partial at the end of commit). Any other
411
- // bundle-owned entry not-listed in the new bundle is stale.
412
- if (entry === '.tmp' || entry === '.partial')
413
- continue;
414
- if (newTopLevelSet.has(entry))
415
- continue;
416
- if (entry === 'steps')
417
- continue; // handled below
418
- if (!isBundleOwnedEntry(entry))
419
- continue; // foreign file — never touch
420
- await rm(join(dir, entry), { recursive: true, force: true });
420
+ /**
421
+ * Atomically install the complete bundle staged in `tmpDir` into `dir`.
422
+ *
423
+ * Compatible with the #162 data-loss guard: only `isBundleOwnedEntry`
424
+ * names are moved aside or replaced — foreign files in `--out` survive.
425
+ *
426
+ * Re-commit safety: bundle-owned entries are renamed to a sibling
427
+ * aside directory before the new artifacts land. The prior `meta.json`
428
+ * is moved aside first (§3/§7.3 — no meta ⇒ refuse to consume) so a
429
+ * concurrent reader never sees meta pointing at steps already gone.
430
+ * The new `meta.json` is installed last. On failure, aside entries are
431
+ * restored so a failed re-commit never leaves the directory unusable.
432
+ */
433
+ export async function commitBundle(tmpDir, dir, files) {
434
+ const parent = dirname(dir);
435
+ const base = basename(dir);
436
+ const asideDir = join(parent, `.${base}.aside.${randomUUID()}`);
437
+ const asideLog = [];
438
+ const asideIfPresent = async (entry) => {
439
+ const restorePath = join(dir, entry);
440
+ if (!(await pathExists(restorePath)))
441
+ return;
442
+ const asidePath = join(asideDir, entry);
443
+ await mkdir(dirname(asidePath), { recursive: true });
444
+ await rename(restorePath, asidePath);
445
+ asideLog.push({ asidePath, restorePath });
446
+ };
447
+ const rollback = async () => {
448
+ for (const { asidePath, restorePath } of [...asideLog].reverse()) {
449
+ await rm(restorePath, { recursive: true, force: true }).catch(() => undefined);
450
+ await rename(asidePath, restorePath).catch(() => undefined);
451
+ }
452
+ await rm(asideDir, { recursive: true, force: true }).catch(() => undefined);
453
+ };
454
+ try {
455
+ const topLevel = files.filter(f => !f.startsWith('steps/'));
456
+ const newTopLevelSet = new Set(topLevel);
457
+ newTopLevelSet.add('meta.json');
458
+ // meta.json first — its presence is the completion signal; do not
459
+ // move steps (or anything else) aside while a stale meta is still visible.
460
+ await asideIfPresent('meta.json');
461
+ const existing = await readdir(dir).catch(() => []);
462
+ for (const entry of existing) {
463
+ if (entry === '.tmp' || entry === 'meta.json')
464
+ continue;
465
+ if (!isBundleOwnedEntry(entry))
466
+ continue;
467
+ const isStale = entry !== 'steps' && entry !== '.partial' && !newTopLevelSet.has(entry);
468
+ const willReplace = entry === 'steps' || newTopLevelSet.has(entry);
469
+ if (isStale || willReplace) {
470
+ await asideIfPresent(entry);
471
+ }
472
+ }
473
+ const stepsTmp = join(tmpDir, 'steps');
474
+ const stepsDir = join(dir, 'steps');
475
+ if (await dirExists(stepsTmp)) {
476
+ await rename(stepsTmp, stepsDir);
477
+ }
478
+ const metaIdx = topLevel.indexOf('meta.json');
479
+ const beforeMeta = metaIdx >= 0 ? topLevel.filter((_, i) => i !== metaIdx) : topLevel;
480
+ for (const file of beforeMeta) {
481
+ await rename(join(tmpDir, file), join(dir, file));
482
+ }
483
+ if (metaIdx >= 0) {
484
+ await rename(join(tmpDir, 'meta.json'), join(dir, 'meta.json'));
485
+ }
486
+ await unlink(join(dir, '.partial')).catch(() => undefined);
487
+ await rm(tmpDir, { recursive: true, force: true });
488
+ // Best-effort aside cleanup — failures must not roll back a committed bundle.
489
+ await rm(asideDir, { recursive: true, force: true }).catch(() => undefined);
421
490
  }
422
- // (3) Replace `<dir>/steps/` with `<tmp>/steps/`.
423
- const stepsTmp = join(tmpDir, 'steps');
424
- const stepsDir = join(dir, 'steps');
425
- await rm(stepsDir, { recursive: true, force: true });
426
- if (await dirExists(stepsTmp)) {
427
- await rename(stepsTmp, stepsDir);
491
+ catch (err) {
492
+ await rollback();
493
+ await rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
494
+ throw err;
428
495
  }
429
- // (4) Top-level files (result/failure/code/video). meta.json renames
430
- // LAST; track it separately.
431
- const metaIdx = topLevel.indexOf('meta.json');
432
- const beforeMeta = metaIdx >= 0 ? topLevel.filter((_, i) => i !== metaIdx) : topLevel;
433
- for (const file of beforeMeta) {
434
- await rename(join(tmpDir, file), join(dir, file));
496
+ }
497
+ async function pathExists(path) {
498
+ try {
499
+ await stat(path);
500
+ return true;
435
501
  }
436
- // (5) meta.json LAST → atomic completion signal.
437
- if (metaIdx >= 0) {
438
- await rename(join(tmpDir, 'meta.json'), join(dir, 'meta.json'));
502
+ catch {
503
+ return false;
439
504
  }
440
- // .partial from a prior aborted run is now stale. Remove it so an
441
- // agent inspecting the dir sees only the fresh bundle.
442
- await unlink(join(dir, '.partial')).catch(() => undefined);
443
- // Clean up the now-empty tmp dir.
444
- await rm(tmpDir, { recursive: true, force: true });
445
505
  }
446
506
  async function dirExists(path) {
447
507
  try {
@@ -41,7 +41,27 @@ export interface ClientFactoryDeps {
41
41
  credentialsPath?: string;
42
42
  fetchImpl?: FetchImpl;
43
43
  stderr?: (line: string) => void;
44
+ /**
45
+ * Shutdown signal composed into every outgoing fetch (DEV-331 piece 1).
46
+ * Defaults to `globalShutdown.signal` so an armed SIGINT/SIGTERM aborts an
47
+ * in-flight request; tests inject their own controller's signal.
48
+ */
49
+ shutdownSignal?: AbortSignal;
44
50
  }
51
+ /**
52
+ * Accepted TestSprite API-key prefixes, in the order they are reported to the
53
+ * user. Three families exist today and all three authenticate:
54
+ *
55
+ * - `sk-user-…` legacy encrypted-envelope key — acts as the human
56
+ * - `sk-member-…` membership key — acts as ONE org membership of that human
57
+ * - `tsp_…` the pre-rename spelling of a membership key (`sk-member-…`);
58
+ * still issued to nobody, still valid for everyone holding one
59
+ *
60
+ * `sk-member-` is deliberately NOT shortened to `sk-` here: this list is only
61
+ * a fail-fast format check, but keeping the full prefixes means the message
62
+ * below can name exactly what the server will accept.
63
+ */
64
+ export declare const API_KEY_PREFIXES: readonly ["sk-user-", "sk-member-", "tsp_"];
45
65
  /**
46
66
  * The fake API key used in dry-run. Never sent — the dry-run fetch
47
67
  * impl ignores headers and returns a canned sample. Documented in the
@@ -87,6 +107,15 @@ export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'reque
87
107
  * assuming the flag.
88
108
  */
89
109
  export declare function assertValidEndpointUrl(rawUrl: string): void;
110
+ /**
111
+ * Reject a key that isn't a TestSprite key, up front — so a malformed key
112
+ * fails fast instead of a slow live `fetch failed`. Checks only the prefix +
113
+ * non-empty body against {@link API_KEY_PREFIXES}, so it can never reject a
114
+ * real key of any issued family.
115
+ */
116
+ export declare function assertValidApiKeyFormat(apiKey: string): void;
117
+ /** Up-front key validation: TestSprite format + legal HTTP header value. */
118
+ export declare function assertValidApiKey(apiKey: string): void;
90
119
  export declare function assertValidApiKeyHeaderValue(apiKey: string): void;
91
120
  /**
92
121
  * Parse the `--request-timeout <seconds>` flag value into milliseconds.
@@ -18,7 +18,24 @@ import { defaultCredentialsPath } from './credentials.js';
18
18
  import { ApiError, localValidationError } from './errors.js';
19
19
  import { facadeBaseUrl } from './facade.js';
20
20
  import { HttpClient, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, REQUEST_TIMEOUT_MIN_MS, } from './http.js';
21
+ import { globalShutdown } from './interrupt.js';
21
22
  import { createDryRunFetch } from './dry-run/fetch.js';
23
+ import { noteServerVersion } from './version-notice.js';
24
+ import { VERSION } from '../version.js';
25
+ /**
26
+ * Accepted TestSprite API-key prefixes, in the order they are reported to the
27
+ * user. Three families exist today and all three authenticate:
28
+ *
29
+ * - `sk-user-…` legacy encrypted-envelope key — acts as the human
30
+ * - `sk-member-…` membership key — acts as ONE org membership of that human
31
+ * - `tsp_…` the pre-rename spelling of a membership key (`sk-member-…`);
32
+ * still issued to nobody, still valid for everyone holding one
33
+ *
34
+ * `sk-member-` is deliberately NOT shortened to `sk-` here: this list is only
35
+ * a fail-fast format check, but keeping the full prefixes means the message
36
+ * below can name exactly what the server will accept.
37
+ */
38
+ export const API_KEY_PREFIXES = ['sk-user-', 'sk-member-', 'tsp_'];
22
39
  /**
23
40
  * The fake API key used in dry-run. Never sent — the dry-run fetch
24
41
  * impl ignores headers and returns a canned sample. Documented in the
@@ -109,6 +126,24 @@ export function assertValidEndpointUrl(rawUrl) {
109
126
  `(e.g. https://api.testsprite.com)`, undefined, 'field');
110
127
  }
111
128
  }
129
+ /**
130
+ * Reject a key that isn't a TestSprite key, up front — so a malformed key
131
+ * fails fast instead of a slow live `fetch failed`. Checks only the prefix +
132
+ * non-empty body against {@link API_KEY_PREFIXES}, so it can never reject a
133
+ * real key of any issued family.
134
+ */
135
+ export function assertValidApiKeyFormat(apiKey) {
136
+ const matchesPrefix = (prefix) => apiKey.startsWith(prefix) && apiKey.length > prefix.length;
137
+ if (!API_KEY_PREFIXES.some(matchesPrefix)) {
138
+ const shown = API_KEY_PREFIXES.map(p => `\`${p}\``).join(', ');
139
+ throw localValidationError('api-key', `must be a TestSprite API key beginning with one of ${shown} (create one in the dashboard, then run \`testsprite setup\`)`, undefined, 'field');
140
+ }
141
+ }
142
+ /** Up-front key validation: TestSprite format + legal HTTP header value. */
143
+ export function assertValidApiKey(apiKey) {
144
+ assertValidApiKeyFormat(apiKey);
145
+ assertValidApiKeyHeaderValue(apiKey);
146
+ }
112
147
  export function assertValidApiKeyHeaderValue(apiKey) {
113
148
  const reason = 'must be a non-empty HTTP header value; paste the raw key without smart punctuation, emoji, or line breaks';
114
149
  if (apiKey.trim().length === 0) {
@@ -173,6 +208,7 @@ export function makeHttpClient(opts, deps = {}) {
173
208
  onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
174
209
  onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
175
210
  requestTimeoutMs,
211
+ shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
176
212
  });
177
213
  }
178
214
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
@@ -188,14 +224,26 @@ export function makeHttpClient(opts, deps = {}) {
188
224
  assertValidEndpointUrl(config.apiUrl);
189
225
  if (!config.apiKey)
190
226
  throw ApiError.authRequired();
191
- assertValidApiKeyHeaderValue(config.apiKey);
227
+ assertValidApiKey(config.apiKey);
192
228
  return new HttpClient({
193
229
  baseUrl: facadeBaseUrl(config.apiUrl),
194
230
  apiKey: config.apiKey,
195
231
  fetchImpl: deps.fetchImpl,
196
232
  onDebug: opts.debug ? (event) => stderr(formatDebug(event)) : undefined,
197
233
  onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
234
+ // Warn once if the backend advertises a minimum supported version above
235
+ // this binary's. Gating (opt-out env, TTY, output mode, dry-run) lives in
236
+ // noteServerVersion; the client just forwards the observed headers.
237
+ onServerVersion: info => noteServerVersion(info, {
238
+ currentVersion: VERSION,
239
+ env,
240
+ isTTY: process.stderr.isTTY === true,
241
+ outputMode: opts.output,
242
+ dryRun: opts.dryRun,
243
+ stderr,
244
+ }),
198
245
  requestTimeoutMs,
246
+ shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
199
247
  });
200
248
  }
201
249
  function formatDebug(event) {
@@ -22,12 +22,16 @@ export function defaultConfigPath() {
22
22
  */
23
23
  export function loadConfig(options = {}) {
24
24
  const env = options.env ?? process.env;
25
- const profile = options.profile ?? env.TESTSPRITE_PROFILE ?? DEFAULT_PROFILE;
25
+ const profile = options.profile ?? normalizeEnvVar(env.TESTSPRITE_PROFILE) ?? DEFAULT_PROFILE;
26
26
  const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
27
27
  const fileEntry = readProfile(profile, { path: credentialsPath });
28
28
  // Empty / whitespace-only env vars are treated as unset so they do not
29
- // short-circuit the `??` chain (e.g. `export TESTSPRITE_API_URL=` in a shell
30
- // profile). Matches the normalization in auth configure and init/setup.
29
+ // short-circuit the `??` chain (e.g. `export TESTSPRITE_API_URL=` or
30
+ // `export TESTSPRITE_PROFILE=` in a shell profile). For the profile this
31
+ // also avoids a confusing VALIDATION_ERROR: an empty name fails the INI
32
+ // section-name guard, so without normalization a blank env var would break
33
+ // every command instead of falling back to the default profile. Matches the
34
+ // normalization in auth configure and init/setup.
31
35
  const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
32
36
  const envApiKey = normalizeEnvVar(env.TESTSPRITE_API_KEY);
33
37
  return {
@@ -1,3 +1,4 @@
1
+ import { type SpawnSyncReturns } from 'node:child_process';
1
2
  export declare const DEFAULT_PROFILE = "default";
2
3
  /**
3
4
  * Throw a typed VALIDATION_ERROR (exit 5) when `profile` is not a safe INI
@@ -15,10 +16,25 @@ export type CredentialsFile = Record<string, ProfileEntry>;
15
16
  export interface CredentialsOptions {
16
17
  path?: string;
17
18
  }
19
+ interface RestrictiveModeOptions {
20
+ platform?: NodeJS.Platform;
21
+ env?: NodeJS.ProcessEnv;
22
+ spawnSync?: (command: string, args: readonly string[], options: {
23
+ shell: false;
24
+ stdio: 'ignore';
25
+ windowsHide: true;
26
+ }) => SpawnSyncReturns<Buffer>;
27
+ warn?: (line: string) => void;
28
+ }
18
29
  export declare function parseCredentials(content: string): CredentialsFile;
19
30
  export declare function serializeCredentials(file: CredentialsFile): string;
20
31
  export declare function readCredentialsFile(options?: CredentialsOptions): CredentialsFile;
21
32
  export declare function readProfile(profile: string, options?: CredentialsOptions): ProfileEntry | undefined;
22
33
  export declare function writeProfile(profile: string, entry: ProfileEntry, options?: CredentialsOptions): void;
23
34
  export declare function deleteProfile(profile: string, options?: CredentialsOptions): boolean;
24
- export declare function ensureRestrictiveMode(path: string): void;
35
+ /**
36
+ * Enforce restrictive access on the credentials file after atomic writes.
37
+ * POSIX hosts use chmod(0600); Windows hosts use ACL tightening via icacls.
38
+ */
39
+ export declare function ensureRestrictiveMode(path: string, options?: RestrictiveModeOptions): void;
40
+ export {};