@testsprite/testsprite-cli 0.1.2 → 0.3.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.
- package/README.md +34 -26
- package/dist/commands/agent.d.ts +52 -0
- package/dist/commands/agent.js +341 -93
- package/dist/commands/auth.js +29 -27
- package/dist/commands/doctor.d.ts +49 -0
- package/dist/commands/doctor.js +211 -0
- package/dist/commands/init.d.ts +7 -1
- package/dist/commands/init.js +66 -26
- package/dist/commands/project.d.ts +50 -1
- package/dist/commands/project.js +257 -43
- package/dist/commands/test.d.ts +214 -12
- package/dist/commands/test.js +1310 -174
- package/dist/commands/usage.js +13 -12
- package/dist/index.js +71 -18
- package/dist/lib/agent-targets.d.ts +169 -22
- package/dist/lib/agent-targets.js +335 -34
- package/dist/lib/bundle.d.ts +51 -1
- package/dist/lib/bundle.js +146 -55
- package/dist/lib/client-factory.d.ts +43 -0
- package/dist/lib/client-factory.js +89 -2
- package/dist/lib/config.d.ts +2 -0
- package/dist/lib/config.js +11 -2
- package/dist/lib/credentials.d.ts +7 -0
- package/dist/lib/credentials.js +40 -1
- package/dist/lib/dry-run/samples.d.ts +5 -0
- package/dist/lib/dry-run/samples.js +54 -9
- package/dist/lib/flaky.d.ts +80 -0
- package/dist/lib/flaky.js +76 -0
- package/dist/lib/http.d.ts +20 -0
- package/dist/lib/http.js +216 -132
- package/dist/lib/interrupt.d.ts +61 -0
- package/dist/lib/interrupt.js +97 -0
- package/dist/lib/junit-report.d.ts +58 -0
- package/dist/lib/junit-report.js +210 -0
- package/dist/lib/output.d.ts +16 -1
- package/dist/lib/output.js +24 -2
- package/dist/lib/pagination.d.ts +4 -3
- package/dist/lib/pagination.js +34 -6
- package/dist/lib/prompt.js +52 -8
- package/dist/lib/proxy.d.ts +29 -0
- package/dist/lib/proxy.js +30 -0
- package/dist/lib/render-error.d.ts +13 -0
- package/dist/lib/render-error.js +30 -7
- package/dist/lib/skill-nudge.d.ts +2 -2
- package/dist/lib/skill-nudge.js +13 -4
- package/dist/lib/target-url.js +8 -1
- package/dist/lib/ticker.d.ts +11 -1
- package/dist/lib/ticker.js +33 -1
- package/dist/lib/update-check.d.ts +67 -0
- package/dist/lib/update-check.js +246 -0
- package/dist/version-guard.d.ts +33 -0
- package/dist/version-guard.js +39 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -2
- package/skills/testsprite-onboard.skill.md +183 -0
- package/skills/testsprite-verify.codex.md +2 -0
- package/skills/testsprite-verify.skill.md +52 -1
package/dist/lib/bundle.js
CHANGED
|
@@ -35,10 +35,15 @@
|
|
|
35
35
|
import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
|
|
36
36
|
import { pipeline } from 'node:stream/promises';
|
|
37
37
|
import { createWriteStream } from 'node:fs';
|
|
38
|
-
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
39
|
-
import { ApiError, TransportError } from './errors.js';
|
|
38
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
39
|
+
import { ApiError, TransportError, localValidationError } from './errors.js';
|
|
40
|
+
import { requireEnum } from './validate.js';
|
|
40
41
|
/** Schema version stamped into `meta.json`. Bumps with the contract. */
|
|
41
42
|
export const BUNDLE_SCHEMA_VERSION = 'cli-v1';
|
|
43
|
+
/** Max fetch attempts for each presigned URL (initial + retries). */
|
|
44
|
+
export const STREAM_URL_MAX_RETRIES = 3;
|
|
45
|
+
/** Delay between retries for transient transport failures (ms). */
|
|
46
|
+
export const STREAM_URL_RETRY_DELAY_MS = 1000;
|
|
42
47
|
/** Default radius around the failed step when `--failed-only` is set. */
|
|
43
48
|
export const FAILED_ONLY_RADIUS = 1;
|
|
44
49
|
/**
|
|
@@ -198,10 +203,13 @@ export function pickCodeExtension(language, framework) {
|
|
|
198
203
|
return 'js';
|
|
199
204
|
if (language === 'typescript')
|
|
200
205
|
return 'ts';
|
|
201
|
-
// Fallback
|
|
206
|
+
// Fallback when the server didn't stamp a language: both TestSprite
|
|
207
|
+
// frameworks are Python — backend `pytest` and frontend Playwright
|
|
208
|
+
// (`playwright.async_api`) — so default to `.py`. (Legacy TS/JS rows
|
|
209
|
+
// carry an explicit `language` above and are honored as `.ts`/`.js`.)
|
|
202
210
|
if (framework === 'pytest')
|
|
203
211
|
return 'py';
|
|
204
|
-
return '
|
|
212
|
+
return 'py';
|
|
205
213
|
}
|
|
206
214
|
/**
|
|
207
215
|
* Step filename per §7.2 — 1-based index, zero-padded to two digits
|
|
@@ -213,6 +221,19 @@ export function pickCodeExtension(language, framework) {
|
|
|
213
221
|
export function stepFilenamePrefix(stepIndex) {
|
|
214
222
|
return stepIndex >= 100 ? String(stepIndex).padStart(3, '0') : String(stepIndex).padStart(2, '0');
|
|
215
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Refuse a composed artifact path that escapes `baseDir`. Step filenames are
|
|
226
|
+
* built from response-controlled fields, so this is the final containment
|
|
227
|
+
* check before any write. Returns the validated absolute path.
|
|
228
|
+
*/
|
|
229
|
+
export function assertNoEscape(baseDir, segment) {
|
|
230
|
+
const composed = resolve(baseDir, segment);
|
|
231
|
+
const rel = relative(baseDir, composed);
|
|
232
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
233
|
+
throw localValidationError('out', 'resolved artifact path escapes the bundle directory', undefined, 'field');
|
|
234
|
+
}
|
|
235
|
+
return composed;
|
|
236
|
+
}
|
|
216
237
|
/**
|
|
217
238
|
* Build the §7.1 meta.json given a context. Pure function, no I/O —
|
|
218
239
|
* lets specs assert the meta shape without touching disk.
|
|
@@ -350,28 +371,52 @@ async function freshTmpDir(dir) {
|
|
|
350
371
|
* caught reading the dir during it sees no meta and refuses to consume
|
|
351
372
|
* (per §7.3). That's what we want.
|
|
352
373
|
*/
|
|
374
|
+
/**
|
|
375
|
+
* Whether a top-level directory entry belongs to the bundle format —
|
|
376
|
+
* 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).
|
|
382
|
+
*/
|
|
383
|
+
export function isBundleOwnedEntry(entry) {
|
|
384
|
+
if (entry === 'result.json' ||
|
|
385
|
+
entry === 'failure.json' ||
|
|
386
|
+
entry === 'video.mp4' ||
|
|
387
|
+
entry === 'meta.json' ||
|
|
388
|
+
entry === 'steps' ||
|
|
389
|
+
entry === '.tmp' ||
|
|
390
|
+
entry === '.partial') {
|
|
391
|
+
return true;
|
|
392
|
+
}
|
|
393
|
+
return /^code\.[A-Za-z0-9]+$/.test(entry);
|
|
394
|
+
}
|
|
353
395
|
async function commitBundle(tmpDir, dir, files) {
|
|
354
396
|
// (1) Remove the prior bundle's completion signal FIRST.
|
|
355
397
|
await unlink(join(dir, 'meta.json')).catch(() => undefined);
|
|
356
398
|
// (2) Sweep stale top-level files that the new bundle won't write.
|
|
357
399
|
// If the prior run wrote `video.mp4` and the new run has no video,
|
|
358
|
-
// an in-place rename leaves the old video lingering.
|
|
359
|
-
//
|
|
360
|
-
//
|
|
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).
|
|
361
404
|
const topLevel = files.filter(f => !f.startsWith('steps/'));
|
|
362
405
|
const newTopLevelSet = new Set(topLevel);
|
|
363
406
|
newTopLevelSet.add('meta.json'); // about to land last, do not delete
|
|
364
407
|
const existing = await readdir(dir).catch(() => []);
|
|
365
408
|
for (const entry of existing) {
|
|
366
409
|
// Preserve the writer's own scratch dir + the .partial marker
|
|
367
|
-
// (we'll re-evaluate .partial at the end of commit).
|
|
368
|
-
// not-listed in the new bundle is stale.
|
|
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.
|
|
369
412
|
if (entry === '.tmp' || entry === '.partial')
|
|
370
413
|
continue;
|
|
371
414
|
if (newTopLevelSet.has(entry))
|
|
372
415
|
continue;
|
|
373
416
|
if (entry === 'steps')
|
|
374
417
|
continue; // handled below
|
|
418
|
+
if (!isBundleOwnedEntry(entry))
|
|
419
|
+
continue; // foreign file — never touch
|
|
375
420
|
await rm(join(dir, entry), { recursive: true, force: true });
|
|
376
421
|
}
|
|
377
422
|
// (3) Replace `<dir>/steps/` with `<tmp>/steps/`.
|
|
@@ -417,15 +462,20 @@ async function dirExists(path) {
|
|
|
417
462
|
* there's nothing to put in it; it's NOT a placeholder.
|
|
418
463
|
*/
|
|
419
464
|
async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten) {
|
|
465
|
+
// stepIndex comes straight from the response and is used to build the
|
|
466
|
+
// filename — reject anything that isn't a real index before composing a path.
|
|
467
|
+
if (!Number.isInteger(step.stepIndex) || step.stepIndex < 0) {
|
|
468
|
+
throw localValidationError('stepIndex', 'must be a non-negative integer', undefined, 'field');
|
|
469
|
+
}
|
|
420
470
|
const prefix = stepFilenamePrefix(step.stepIndex);
|
|
421
471
|
if (step.screenshotUrl) {
|
|
422
472
|
const file = `${prefix}-screenshot.png`;
|
|
423
|
-
await streamUrlToFile(step.screenshotUrl,
|
|
473
|
+
await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
|
|
424
474
|
filesWritten.push(`steps/${file}`);
|
|
425
475
|
}
|
|
426
476
|
if (step.htmlSnapshotUrl) {
|
|
427
477
|
const file = `${prefix}-snapshot.html`;
|
|
428
|
-
await streamUrlToFile(step.htmlSnapshotUrl,
|
|
478
|
+
await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
|
|
429
479
|
filesWritten.push(`steps/${file}`);
|
|
430
480
|
}
|
|
431
481
|
// Evidence sidecar artifacts. Per codex round-1 P2: the bundle must
|
|
@@ -448,6 +498,8 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
|
|
|
448
498
|
const sidecar = allEvidence.filter(e => e.stepIndex === step.stepIndex);
|
|
449
499
|
if (sidecar.length > 0) {
|
|
450
500
|
const dereferenced = await Promise.all(sidecar.map(async (entry, i) => {
|
|
501
|
+
// kind comes from the response and is used in the filename — validate it.
|
|
502
|
+
requireEnum('kind', entry.kind, ['screenshot', 'snapshot', 'log', 'network', 'console']);
|
|
451
503
|
// Reuse the already-downloaded step file when the evidence URL
|
|
452
504
|
// matches the step's primary screenshot/snapshot URL. Cheap
|
|
453
505
|
// dedupe — no extra HTTP round-trip, no duplicate bytes on disk.
|
|
@@ -471,7 +523,7 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
|
|
|
471
523
|
}
|
|
472
524
|
const ext = sidecarExtension(entry.kind);
|
|
473
525
|
const filename = `${prefix}-${entry.kind}-${i}.${ext}`;
|
|
474
|
-
await streamUrlToFile(entry.url,
|
|
526
|
+
await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl);
|
|
475
527
|
filesWritten.push(`steps/${filename}`);
|
|
476
528
|
return {
|
|
477
529
|
kind: entry.kind,
|
|
@@ -484,7 +536,7 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
|
|
|
484
536
|
};
|
|
485
537
|
}));
|
|
486
538
|
const file = `${prefix}-evidence.json`;
|
|
487
|
-
await writeFile(
|
|
539
|
+
await writeFile(assertNoEscape(stepsTmpDir, file), JSON.stringify(dereferenced, null, 2) + '\n', 'utf8');
|
|
488
540
|
filesWritten.push(`steps/${file}`);
|
|
489
541
|
}
|
|
490
542
|
}
|
|
@@ -510,52 +562,91 @@ function sidecarExtension(kind) {
|
|
|
510
562
|
* the upstream reader rather than buffering chunks in V8 heap. This
|
|
511
563
|
* matters for video files (multi-MB) and for very large HTML
|
|
512
564
|
* snapshots.
|
|
565
|
+
*
|
|
566
|
+
* Transport failures (network reset, DNS blip, mid-stream EOF) are
|
|
567
|
+
* retried up to STREAM_URL_MAX_RETRIES times with a fixed delay.
|
|
568
|
+
* Presigned URLs are valid for 15 minutes, so retries are safe.
|
|
513
569
|
*/
|
|
514
|
-
export async function streamUrlToFile(url, filePath, fetchImpl) {
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
570
|
+
export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
571
|
+
const sleepFn = deps?.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
|
|
572
|
+
const artifactUrl = redactArtifactUrlForDetails(url);
|
|
573
|
+
for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
|
|
574
|
+
let response;
|
|
575
|
+
try {
|
|
576
|
+
response = await fetchImpl(url, { redirect: 'error' });
|
|
577
|
+
}
|
|
578
|
+
catch (err) {
|
|
579
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
580
|
+
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
581
|
+
await sleepFn(STREAM_URL_RETRY_DELAY_MS);
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
585
|
+
}
|
|
586
|
+
if (!response.ok) {
|
|
587
|
+
// Non-2xx: the URL itself is bad (expired, unauthorized, not found).
|
|
588
|
+
// Retrying the same URL won't help — surface immediately.
|
|
589
|
+
throw ApiError.fromEnvelope({
|
|
590
|
+
error: {
|
|
591
|
+
code: 'UNAVAILABLE',
|
|
592
|
+
message: `Failed to download presigned URL (HTTP ${response.status}).`,
|
|
593
|
+
nextAction: 'Re-run `testsprite test failure get`. Presigned URLs in the bundle expire after 15 minutes.',
|
|
594
|
+
requestId: 'local',
|
|
595
|
+
details: { status: response.status, artifactUrl },
|
|
596
|
+
},
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
if (!response.body) {
|
|
600
|
+
// Some test runtimes / fetch polyfills don't expose `body` as a
|
|
601
|
+
// ReadableStream. Fall back to a buffered write — same correctness,
|
|
602
|
+
// just no streaming benefit. The bundle is bounded by the
|
|
603
|
+
// backend's 15-min TTL, so even a multi-MB video buffers fully in
|
|
604
|
+
// a tolerable amount of memory.
|
|
605
|
+
try {
|
|
606
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
607
|
+
await writeFile(filePath, buffer);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
catch (err) {
|
|
611
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
612
|
+
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
613
|
+
await sleepFn(STREAM_URL_RETRY_DELAY_MS);
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
await mkdir(dirname(filePath), { recursive: true });
|
|
620
|
+
// `response.body` is a Web ReadableStream. Node's `pipeline` accepts
|
|
621
|
+
// it via `Readable.fromWeb` (Node >= 18). Wrap in a try so any error
|
|
622
|
+
// from the stream propagates as a TransportError, preserving the
|
|
623
|
+
// exit-code contract. `pipeline` destroys both streams on error, so
|
|
624
|
+
// a new WriteStream on retry starts clean.
|
|
625
|
+
const fileSink = createWriteStream(filePath);
|
|
626
|
+
try {
|
|
627
|
+
const webBody = response.body;
|
|
628
|
+
const { Readable } = await import('node:stream');
|
|
629
|
+
const nodeStream = Readable.fromWeb(webBody);
|
|
630
|
+
await pipeline(nodeStream, fileSink);
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
catch (err) {
|
|
634
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
635
|
+
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
636
|
+
await sleepFn(STREAM_URL_RETRY_DELAY_MS);
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
|
|
640
|
+
}
|
|
543
641
|
}
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
// it via `Readable.fromWeb` (Node ≥ 18). Wrap in a try so any error
|
|
547
|
-
// from the stream propagates as a TransportError, preserving the
|
|
548
|
-
// exit-code contract.
|
|
549
|
-
const fileSink = createWriteStream(filePath);
|
|
642
|
+
}
|
|
643
|
+
function redactArtifactUrlForDetails(url) {
|
|
550
644
|
try {
|
|
551
|
-
const
|
|
552
|
-
|
|
553
|
-
const nodeStream = Readable.fromWeb(webBody);
|
|
554
|
-
await pipeline(nodeStream, fileSink);
|
|
645
|
+
const parsed = new URL(url);
|
|
646
|
+
return `${parsed.origin}${parsed.pathname}`;
|
|
555
647
|
}
|
|
556
|
-
catch
|
|
557
|
-
|
|
558
|
-
throw new TransportError(`Failed mid-download of ${url}: ${message}`);
|
|
648
|
+
catch {
|
|
649
|
+
return '<invalid-url>';
|
|
559
650
|
}
|
|
560
651
|
}
|
|
561
652
|
function isPresignedUrl(value) {
|
|
@@ -69,4 +69,47 @@ export declare function resetDryRunBannerForTesting(): void;
|
|
|
69
69
|
* not a safety-critical gate.
|
|
70
70
|
*/
|
|
71
71
|
export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'requestTimeoutMs'>, env: NodeJS.ProcessEnv): number;
|
|
72
|
+
/**
|
|
73
|
+
* Validate that the resolved API endpoint is a syntactically valid http(s)
|
|
74
|
+
* URL before it is used to build requests.
|
|
75
|
+
*
|
|
76
|
+
* Unlike the `--target-url` guard in `target-url.ts`, this deliberately does
|
|
77
|
+
* NOT reject localhost or private addresses: the API endpoint legitimately
|
|
78
|
+
* points at a self-hosted, local-dev, or mock backend on a private host. It
|
|
79
|
+
* only catches a malformed value (unparseable, or a non-http(s) scheme) so the
|
|
80
|
+
* operator gets a fast, actionable VALIDATION_ERROR (exit 5) instead of an
|
|
81
|
+
* opaque `Invalid URL` (exit 1, a raw `new URL()` throw) or a misleading
|
|
82
|
+
* `fetch failed / Service temporarily unavailable` emitted only after a full
|
|
83
|
+
* retry-and-backoff cycle.
|
|
84
|
+
*
|
|
85
|
+
* The value can originate from `--endpoint-url`, `TESTSPRITE_API_URL`, or the
|
|
86
|
+
* credentials file `api_url`, so the message names all three rather than
|
|
87
|
+
* assuming the flag.
|
|
88
|
+
*/
|
|
89
|
+
export declare function assertValidEndpointUrl(rawUrl: string): void;
|
|
90
|
+
export declare function assertValidApiKeyHeaderValue(apiKey: string): void;
|
|
91
|
+
/**
|
|
92
|
+
* Parse the `--request-timeout <seconds>` flag value into milliseconds.
|
|
93
|
+
*
|
|
94
|
+
* Returns `undefined` when the flag was omitted (the factory then falls back to
|
|
95
|
+
* the `TESTSPRITE_REQUEST_TIMEOUT_MS` env var, else the 120s default).
|
|
96
|
+
*
|
|
97
|
+
* A supplied-but-invalid value (non-numeric, zero, or negative) throws a typed
|
|
98
|
+
* VALIDATION_ERROR (exit 5) rather than being silently dropped. An explicit
|
|
99
|
+
* `--request-timeout 30s` typo previously resolved to `undefined` and the
|
|
100
|
+
* command ran with the default 120s deadline — the operator believed they had
|
|
101
|
+
* set a timeout but had not, with no signal. Failing loudly here is consistent
|
|
102
|
+
* with every other validated flag (`--page-size`, `--output`, `--type`).
|
|
103
|
+
*
|
|
104
|
+
* Out-of-range but positive values are intentionally NOT rejected — they flow
|
|
105
|
+
* through to {@link resolveRequestTimeoutMs}, which clamps to
|
|
106
|
+
* `[REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS]`. The env-var path stays
|
|
107
|
+
* lenient by design (a stray global env var should not hard-fail every
|
|
108
|
+
* command); only the explicit per-invocation flag is strict.
|
|
109
|
+
*
|
|
110
|
+
* This single definition replaces five byte-identical copies that previously
|
|
111
|
+
* lived in `auth`, `project`, `usage`, `init`, and `test` — drift between them
|
|
112
|
+
* would have silently changed timeout behaviour depending on the command.
|
|
113
|
+
*/
|
|
114
|
+
export declare function parseRequestTimeoutFlag(raw: string | undefined): number | undefined;
|
|
72
115
|
export declare function makeHttpClient(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClient;
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import { loadConfig } from './config.js';
|
|
17
17
|
import { defaultCredentialsPath } from './credentials.js';
|
|
18
|
-
import { ApiError } from './errors.js';
|
|
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
21
|
import { createDryRunFetch } from './dry-run/fetch.js';
|
|
@@ -78,14 +78,96 @@ export function resolveRequestTimeoutMs(opts, env) {
|
|
|
78
78
|
function clampRequestTimeout(ms) {
|
|
79
79
|
return Math.min(Math.max(Math.round(ms), REQUEST_TIMEOUT_MIN_MS), REQUEST_TIMEOUT_MAX_MS);
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Validate that the resolved API endpoint is a syntactically valid http(s)
|
|
83
|
+
* URL before it is used to build requests.
|
|
84
|
+
*
|
|
85
|
+
* Unlike the `--target-url` guard in `target-url.ts`, this deliberately does
|
|
86
|
+
* NOT reject localhost or private addresses: the API endpoint legitimately
|
|
87
|
+
* points at a self-hosted, local-dev, or mock backend on a private host. It
|
|
88
|
+
* only catches a malformed value (unparseable, or a non-http(s) scheme) so the
|
|
89
|
+
* operator gets a fast, actionable VALIDATION_ERROR (exit 5) instead of an
|
|
90
|
+
* opaque `Invalid URL` (exit 1, a raw `new URL()` throw) or a misleading
|
|
91
|
+
* `fetch failed / Service temporarily unavailable` emitted only after a full
|
|
92
|
+
* retry-and-backoff cycle.
|
|
93
|
+
*
|
|
94
|
+
* The value can originate from `--endpoint-url`, `TESTSPRITE_API_URL`, or the
|
|
95
|
+
* credentials file `api_url`, so the message names all three rather than
|
|
96
|
+
* assuming the flag.
|
|
97
|
+
*/
|
|
98
|
+
export function assertValidEndpointUrl(rawUrl) {
|
|
99
|
+
let parsed;
|
|
100
|
+
try {
|
|
101
|
+
parsed = new URL(rawUrl);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw localValidationError('endpoint-url', `"${rawUrl}" is not a valid URL — provide an http(s) URL (e.g. https://api.testsprite.com) ` +
|
|
105
|
+
`via --endpoint-url, TESTSPRITE_API_URL, or the credentials file`, undefined, 'field');
|
|
106
|
+
}
|
|
107
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
108
|
+
throw localValidationError('endpoint-url', `scheme "${parsed.protocol.replace(/:$/, '')}" is not supported — use http or https ` +
|
|
109
|
+
`(e.g. https://api.testsprite.com)`, undefined, 'field');
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
export function assertValidApiKeyHeaderValue(apiKey) {
|
|
113
|
+
const reason = 'must be a non-empty HTTP header value; paste the raw key without smart punctuation, emoji, or line breaks';
|
|
114
|
+
if (apiKey.trim().length === 0) {
|
|
115
|
+
throw localValidationError('api-key', reason, undefined, 'field');
|
|
116
|
+
}
|
|
117
|
+
for (let i = 0; i < apiKey.length; i += 1) {
|
|
118
|
+
const code = apiKey.charCodeAt(i);
|
|
119
|
+
if (code < 0x20 || code === 0x7f || code > 0xff) {
|
|
120
|
+
throw localValidationError('api-key', reason, undefined, 'field');
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Parse the `--request-timeout <seconds>` flag value into milliseconds.
|
|
126
|
+
*
|
|
127
|
+
* Returns `undefined` when the flag was omitted (the factory then falls back to
|
|
128
|
+
* the `TESTSPRITE_REQUEST_TIMEOUT_MS` env var, else the 120s default).
|
|
129
|
+
*
|
|
130
|
+
* A supplied-but-invalid value (non-numeric, zero, or negative) throws a typed
|
|
131
|
+
* VALIDATION_ERROR (exit 5) rather than being silently dropped. An explicit
|
|
132
|
+
* `--request-timeout 30s` typo previously resolved to `undefined` and the
|
|
133
|
+
* command ran with the default 120s deadline — the operator believed they had
|
|
134
|
+
* set a timeout but had not, with no signal. Failing loudly here is consistent
|
|
135
|
+
* with every other validated flag (`--page-size`, `--output`, `--type`).
|
|
136
|
+
*
|
|
137
|
+
* Out-of-range but positive values are intentionally NOT rejected — they flow
|
|
138
|
+
* through to {@link resolveRequestTimeoutMs}, which clamps to
|
|
139
|
+
* `[REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS]`. The env-var path stays
|
|
140
|
+
* lenient by design (a stray global env var should not hard-fail every
|
|
141
|
+
* command); only the explicit per-invocation flag is strict.
|
|
142
|
+
*
|
|
143
|
+
* This single definition replaces five byte-identical copies that previously
|
|
144
|
+
* lived in `auth`, `project`, `usage`, `init`, and `test` — drift between them
|
|
145
|
+
* would have silently changed timeout behaviour depending on the command.
|
|
146
|
+
*/
|
|
147
|
+
export function parseRequestTimeoutFlag(raw) {
|
|
148
|
+
if (raw === undefined)
|
|
149
|
+
return undefined;
|
|
150
|
+
const n = Number(raw);
|
|
151
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
152
|
+
// Surface the offending value in the message (same as assertValidEndpointUrl)
|
|
153
|
+
// so the operator sees exactly what they typed.
|
|
154
|
+
throw localValidationError('request-timeout', `"${raw}" is not valid — must be a positive number of seconds`);
|
|
155
|
+
}
|
|
156
|
+
return Math.round(n * 1000); // seconds → milliseconds
|
|
157
|
+
}
|
|
81
158
|
export function makeHttpClient(opts, deps = {}) {
|
|
82
159
|
const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
83
160
|
const env = deps.env ?? process.env;
|
|
84
161
|
const requestTimeoutMs = resolveRequestTimeoutMs(opts, env);
|
|
85
162
|
if (opts.dryRun) {
|
|
163
|
+
const dryRunEndpoint = opts.endpointUrl ?? DRY_RUN_DEFAULT_ENDPOINT;
|
|
164
|
+
// Validate even under --dry-run so a typo in --endpoint-url is caught
|
|
165
|
+
// offline (no creds, no network). Validate BEFORE the banner so a rejected
|
|
166
|
+
// endpoint doesn't first announce a "sample response".
|
|
167
|
+
assertValidEndpointUrl(dryRunEndpoint);
|
|
86
168
|
emitDryRunBanner(stderr);
|
|
87
169
|
return new HttpClient({
|
|
88
|
-
baseUrl: facadeBaseUrl(
|
|
170
|
+
baseUrl: facadeBaseUrl(dryRunEndpoint),
|
|
89
171
|
apiKey: DRY_RUN_API_KEY,
|
|
90
172
|
fetchImpl: deps.fetchImpl ?? createDryRunFetch(),
|
|
91
173
|
onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
|
|
@@ -100,8 +182,13 @@ export function makeHttpClient(opts, deps = {}) {
|
|
|
100
182
|
env,
|
|
101
183
|
credentialsPath,
|
|
102
184
|
});
|
|
185
|
+
// Catch a malformed endpoint (from --endpoint-url / TESTSPRITE_API_URL /
|
|
186
|
+
// credentials) before the auth check so a config typo surfaces as a clear
|
|
187
|
+
// VALIDATION_ERROR rather than an opaque URL throw or a retried "fetch failed".
|
|
188
|
+
assertValidEndpointUrl(config.apiUrl);
|
|
103
189
|
if (!config.apiKey)
|
|
104
190
|
throw ApiError.authRequired();
|
|
191
|
+
assertValidApiKeyHeaderValue(config.apiKey);
|
|
105
192
|
return new HttpClient({
|
|
106
193
|
baseUrl: facadeBaseUrl(config.apiUrl),
|
|
107
194
|
apiKey: config.apiKey,
|
package/dist/lib/config.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export interface LoadConfigOptions {
|
|
|
9
9
|
env?: NodeJS.ProcessEnv;
|
|
10
10
|
credentialsPath?: string;
|
|
11
11
|
}
|
|
12
|
+
/** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
|
|
13
|
+
export declare function normalizeEnvVar(value: string | undefined): string | undefined;
|
|
12
14
|
export declare function defaultConfigPath(): string;
|
|
13
15
|
/**
|
|
14
16
|
* Resolves the active profile name and its (apiUrl, apiKey) pair.
|
package/dist/lib/config.js
CHANGED
|
@@ -2,6 +2,10 @@ import { homedir } from 'node:os';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { DEFAULT_PROFILE, defaultCredentialsPath, readProfile } from './credentials.js';
|
|
4
4
|
const DEFAULT_API_URL = 'https://api.testsprite.com';
|
|
5
|
+
/** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
|
|
6
|
+
export function normalizeEnvVar(value) {
|
|
7
|
+
return value?.trim() || undefined;
|
|
8
|
+
}
|
|
5
9
|
export function defaultConfigPath() {
|
|
6
10
|
return join(homedir(), '.testsprite', 'config');
|
|
7
11
|
}
|
|
@@ -21,9 +25,14 @@ export function loadConfig(options = {}) {
|
|
|
21
25
|
const profile = options.profile ?? env.TESTSPRITE_PROFILE ?? DEFAULT_PROFILE;
|
|
22
26
|
const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
|
|
23
27
|
const fileEntry = readProfile(profile, { path: credentialsPath });
|
|
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.
|
|
31
|
+
const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
|
|
32
|
+
const envApiKey = normalizeEnvVar(env.TESTSPRITE_API_KEY);
|
|
24
33
|
return {
|
|
25
|
-
apiUrl: options.endpointUrl ??
|
|
26
|
-
apiKey:
|
|
34
|
+
apiUrl: options.endpointUrl ?? envApiUrl ?? fileEntry?.apiUrl ?? DEFAULT_API_URL,
|
|
35
|
+
apiKey: envApiKey ?? fileEntry?.apiKey,
|
|
27
36
|
profile,
|
|
28
37
|
};
|
|
29
38
|
}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
export declare const DEFAULT_PROFILE = "default";
|
|
2
|
+
/**
|
|
3
|
+
* Throw a typed VALIDATION_ERROR (exit 5) when `profile` is not a safe INI
|
|
4
|
+
* section name. Guards every credential read/write so a malformed `--profile`
|
|
5
|
+
* (or `TESTSPRITE_PROFILE`) value fails loudly instead of silently corrupting
|
|
6
|
+
* `~/.testsprite/credentials` or failing to persist a key written by `setup`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function assertValidProfileName(profile: string): void;
|
|
2
9
|
export declare function defaultCredentialsPath(): string;
|
|
3
10
|
export interface ProfileEntry {
|
|
4
11
|
apiKey?: string;
|
package/dist/lib/credentials.js
CHANGED
|
@@ -1,7 +1,34 @@
|
|
|
1
1
|
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { dirname, join } from 'node:path';
|
|
4
|
+
import { localValidationError } from './errors.js';
|
|
4
5
|
export const DEFAULT_PROFILE = 'default';
|
|
6
|
+
/**
|
|
7
|
+
* Allowed profile-name characters. A profile name is written verbatim as an
|
|
8
|
+
* INI section header (`[name]`) in the credentials file, so any character that
|
|
9
|
+
* breaks that grammar must be rejected:
|
|
10
|
+
* - `]` closes the header early — `prod]` serialises to `[prod]]`, which the
|
|
11
|
+
* section regex cannot match, so the api_key/api_url lines that follow are
|
|
12
|
+
* silently dropped on read (the credential never persists).
|
|
13
|
+
* - CR/LF splits the header across lines, corrupting the file.
|
|
14
|
+
* - leading/trailing whitespace does not round-trip — the parser trims
|
|
15
|
+
* section names, so `[ prod ]` reads back as `prod`.
|
|
16
|
+
* A conservative allowlist (letters, digits, dot, underscore, hyphen) matches
|
|
17
|
+
* conventional profile names (`default`, `prod`, `ci-staging`, `team.qa`) and
|
|
18
|
+
* cannot corrupt the file.
|
|
19
|
+
*/
|
|
20
|
+
const PROFILE_NAME_RE = /^[A-Za-z0-9._-]+$/;
|
|
21
|
+
/**
|
|
22
|
+
* Throw a typed VALIDATION_ERROR (exit 5) when `profile` is not a safe INI
|
|
23
|
+
* section name. Guards every credential read/write so a malformed `--profile`
|
|
24
|
+
* (or `TESTSPRITE_PROFILE`) value fails loudly instead of silently corrupting
|
|
25
|
+
* `~/.testsprite/credentials` or failing to persist a key written by `setup`.
|
|
26
|
+
*/
|
|
27
|
+
export function assertValidProfileName(profile) {
|
|
28
|
+
if (!PROFILE_NAME_RE.test(profile)) {
|
|
29
|
+
throw localValidationError('profile', 'must contain only letters, digits, dot, underscore, or hyphen (no spaces, brackets, or newlines)', undefined, 'flag');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
5
32
|
export function defaultCredentialsPath() {
|
|
6
33
|
return join(homedir(), '.testsprite', 'credentials');
|
|
7
34
|
}
|
|
@@ -66,7 +93,16 @@ export function serializeCredentials(file) {
|
|
|
66
93
|
const value = entry[field];
|
|
67
94
|
if (value === undefined || value === '')
|
|
68
95
|
continue;
|
|
69
|
-
|
|
96
|
+
// Guard against INI injection: a value containing newline characters
|
|
97
|
+
// would be serialized across multiple lines, allowing an attacker to
|
|
98
|
+
// inject arbitrary key-value pairs (or new section headers) into the
|
|
99
|
+
// credentials file. A valid API key or URL never contains \n or \r.
|
|
100
|
+
// Strip them so a compromised env var or MITM'd backend response
|
|
101
|
+
// cannot override the stored api_key on subsequent reads.
|
|
102
|
+
const sanitized = value.replace(/[\r\n]/g, '');
|
|
103
|
+
if (sanitized === '')
|
|
104
|
+
continue;
|
|
105
|
+
lines.push(`${FIELD_TO_FILE_KEY[field]} = ${sanitized}`);
|
|
70
106
|
}
|
|
71
107
|
lines.push('');
|
|
72
108
|
}
|
|
@@ -79,16 +115,19 @@ export function readCredentialsFile(options = {}) {
|
|
|
79
115
|
return parseCredentials(readFileSync(path, 'utf-8'));
|
|
80
116
|
}
|
|
81
117
|
export function readProfile(profile, options = {}) {
|
|
118
|
+
assertValidProfileName(profile);
|
|
82
119
|
const file = readCredentialsFile(options);
|
|
83
120
|
return file[profile];
|
|
84
121
|
}
|
|
85
122
|
export function writeProfile(profile, entry, options = {}) {
|
|
123
|
+
assertValidProfileName(profile);
|
|
86
124
|
const path = resolvePath(options);
|
|
87
125
|
const file = readCredentialsFile(options);
|
|
88
126
|
file[profile] = { ...file[profile], ...entry };
|
|
89
127
|
writeCredentialsAtomic(path, file);
|
|
90
128
|
}
|
|
91
129
|
export function deleteProfile(profile, options = {}) {
|
|
130
|
+
assertValidProfileName(profile);
|
|
92
131
|
const path = resolvePath(options);
|
|
93
132
|
const file = readCredentialsFile(options);
|
|
94
133
|
if (!(profile in file))
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
export declare const SAMPLE_RUN_ID = "run_abc";
|
|
2
2
|
export declare const SAMPLE_DRY_RUN_REQUEST_ID = "req_dry-run";
|
|
3
|
+
/**
|
|
4
|
+
* Canned JUnit XML for batch `--wait --report junit --dry-run`. Mirrors the
|
|
5
|
+
* fresh batch-run sample ids so agents can learn the sidecar shape offline.
|
|
6
|
+
*/
|
|
7
|
+
export declare function sampleJUnitReportXml(projectId?: string, reportSuiteName?: string): string;
|
|
3
8
|
/**
|
|
4
9
|
* Dry-run sample lookup keyed by OpenAPI operationId. Order matters in
|
|
5
10
|
* {@link findSample}: more specific patterns must precede their generic
|