@testsprite/testsprite-cli 0.6.0 → 0.8.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 +52 -31
- package/dist/commands/agent.js +91 -45
- package/dist/commands/ci.d.ts +88 -0
- package/dist/commands/ci.js +429 -0
- package/dist/commands/doctor.d.ts +1 -1
- package/dist/commands/doctor.js +104 -8
- package/dist/commands/init.js +8 -0
- package/dist/commands/project.d.ts +78 -0
- package/dist/commands/project.js +429 -5
- package/dist/commands/schedule.d.ts +120 -0
- package/dist/commands/schedule.js +487 -0
- package/dist/commands/test.d.ts +176 -2
- package/dist/commands/test.js +2235 -609
- package/dist/commands/testlist.d.ts +88 -0
- package/dist/commands/testlist.js +753 -0
- package/dist/commands/tunnel.d.ts +72 -0
- package/dist/commands/tunnel.js +367 -0
- package/dist/index.js +113 -40
- package/dist/lib/agent-targets.d.ts +13 -4
- package/dist/lib/agent-targets.js +11 -2
- package/dist/lib/conflict-reason.d.ts +30 -0
- package/dist/lib/conflict-reason.js +45 -0
- package/dist/lib/credentials.js +42 -1
- package/dist/lib/cron.d.ts +40 -0
- package/dist/lib/cron.js +190 -0
- package/dist/lib/dry-run/samples.d.ts +9 -0
- package/dist/lib/dry-run/samples.js +293 -55
- package/dist/lib/errors.d.ts +9 -0
- package/dist/lib/errors.js +11 -0
- package/dist/lib/gh-output.d.ts +33 -1
- package/dist/lib/gh-output.js +97 -27
- package/dist/lib/http.d.ts +119 -0
- package/dist/lib/http.js +243 -2
- package/dist/lib/interrupt.d.ts +38 -13
- package/dist/lib/interrupt.js +130 -15
- package/dist/lib/junit-report.d.ts +20 -2
- package/dist/lib/junit-report.js +38 -5
- package/dist/lib/local-target.d.ts +95 -0
- package/dist/lib/local-target.js +184 -0
- package/dist/lib/plan-poll.d.ts +171 -0
- package/dist/lib/plan-poll.js +442 -0
- package/dist/lib/plans.types.d.ts +130 -0
- package/dist/lib/plans.types.js +31 -0
- package/dist/lib/poll-support.d.ts +26 -0
- package/dist/lib/poll-support.js +65 -0
- package/dist/lib/poll.d.ts +1 -0
- package/dist/lib/poll.js +2 -40
- package/dist/lib/proxy.d.ts +16 -0
- package/dist/lib/proxy.js +19 -1
- package/dist/lib/response-schemas.d.ts +20 -0
- package/dist/lib/response-schemas.js +55 -1
- package/dist/lib/run-progress.d.ts +41 -0
- package/dist/lib/run-progress.js +56 -0
- package/dist/lib/runs.types.d.ts +32 -3
- package/dist/lib/secret-file.d.ts +15 -0
- package/dist/lib/secret-file.js +82 -0
- package/dist/lib/target-url-preflight.d.ts +91 -0
- package/dist/lib/target-url-preflight.js +259 -0
- package/dist/lib/target-url.d.ts +63 -9
- package/dist/lib/target-url.js +283 -62
- package/dist/lib/telemetry.d.ts +11 -0
- package/dist/lib/telemetry.js +1 -0
- package/dist/lib/testlist.types.d.ts +77 -0
- package/dist/lib/testlist.types.js +9 -0
- package/dist/lib/ticker.d.ts +8 -0
- package/dist/lib/ticker.js +3 -0
- package/dist/lib/tunnel-session.d.ts +129 -0
- package/dist/lib/tunnel-session.js +232 -0
- package/dist/lib/tunnel.types.d.ts +54 -0
- package/dist/lib/tunnel.types.js +8 -0
- package/dist/lib/v3-advisory.d.ts +35 -22
- package/dist/lib/v3-advisory.js +44 -24
- package/dist/lib/wait-exit.d.ts +29 -0
- package/dist/lib/wait-exit.js +103 -0
- package/dist/vendor/tunnel-client/client.d.ts +83 -0
- package/dist/vendor/tunnel-client/client.js +871 -0
- package/dist/vendor/tunnel-client/config.d.ts +41 -0
- package/dist/vendor/tunnel-client/config.js +42 -0
- package/dist/vendor/tunnel-client/index.d.ts +9 -0
- package/dist/vendor/tunnel-client/index.js +9 -0
- package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
- package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
- package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
- package/dist/vendor/tunnel-client/protocol.js +143 -0
- package/dist/vendor/tunnel-client/types.d.ts +96 -0
- package/dist/vendor/tunnel-client/types.js +10 -0
- package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
- package/dist/vendor/tunnel-client/ws-compat.js +316 -0
- package/dist/version-guard.d.ts +10 -7
- package/dist/version-guard.js +37 -9
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -1
- package/skills/testsprite-onboard.skill.md +60 -4
- package/skills/testsprite-verify.codex.md +22 -16
- package/skills/testsprite-verify.skill.md +27 -18
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
2
|
import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
|
|
3
3
|
import type { FetchImpl } from '../lib/http.js';
|
|
4
|
+
import { type ShutdownHandle } from '../lib/interrupt.js';
|
|
4
5
|
import { type Page } from '../lib/pagination.js';
|
|
5
6
|
export interface CliProject {
|
|
6
7
|
id: string;
|
|
@@ -48,6 +49,8 @@ export interface ProjectDeps {
|
|
|
48
49
|
fetchImpl?: FetchImpl;
|
|
49
50
|
stdout?: (line: string) => void;
|
|
50
51
|
stderr?: (line: string) => void;
|
|
52
|
+
/** Graceful-detach coordinator (DEV-331); tests inject their own. */
|
|
53
|
+
shutdown?: ShutdownHandle;
|
|
51
54
|
}
|
|
52
55
|
type CommonOptions = FactoryCommonOptions;
|
|
53
56
|
interface ListOptions extends CommonOptions {
|
|
@@ -215,5 +218,80 @@ interface AutoAuthOptions extends CommonOptions {
|
|
|
215
218
|
idempotencyKey?: string;
|
|
216
219
|
}
|
|
217
220
|
export declare function runAutoAuth(opts: AutoAuthOptions, deps?: ProjectDeps): Promise<CliProjectAutoAuthResponse>;
|
|
221
|
+
/**
|
|
222
|
+
* CLI-facing role flags → wire enum. Default is `api-doc` (stated in help);
|
|
223
|
+
* no inference from project type in v1 (design §3.4).
|
|
224
|
+
*/
|
|
225
|
+
declare const DOC_ROLES: {
|
|
226
|
+
readonly 'api-doc': "API_DOC";
|
|
227
|
+
readonly prd: "PRD";
|
|
228
|
+
};
|
|
229
|
+
type DocRoleFlag = keyof typeof DOC_ROLES;
|
|
230
|
+
type DocRoleWire = (typeof DOC_ROLES)[DocRoleFlag];
|
|
231
|
+
/** `POST /projects/{id}/docs/upload-url` response (V3-A facade). */
|
|
232
|
+
export interface CliDocsUploadUrlResponse {
|
|
233
|
+
uploadUrl: string;
|
|
234
|
+
s3Key: string;
|
|
235
|
+
expiresInSeconds: number;
|
|
236
|
+
}
|
|
237
|
+
/** `POST /projects/{id}/docs` (register) response (V3-A facade). */
|
|
238
|
+
export interface CliDocsRegisterResponse {
|
|
239
|
+
resourceId: string;
|
|
240
|
+
displayName: string;
|
|
241
|
+
docRole: DocRoleWire | null;
|
|
242
|
+
processStatus: string;
|
|
243
|
+
}
|
|
244
|
+
/** Success result — the JSON-mode stdout shape (piece V3-D scope item 3). */
|
|
245
|
+
export interface CliDocsUploadResult {
|
|
246
|
+
resourceId: string;
|
|
247
|
+
displayName: string;
|
|
248
|
+
role: DocRoleWire | null;
|
|
249
|
+
size: number;
|
|
250
|
+
processStatus: string;
|
|
251
|
+
}
|
|
252
|
+
/** Dry-run result: the would-be plan. Zero network, nothing read beyond a stat. */
|
|
253
|
+
export interface CliDocsUploadPlan {
|
|
254
|
+
dryRun: true;
|
|
255
|
+
projectId: string;
|
|
256
|
+
file: string;
|
|
257
|
+
fileName: string;
|
|
258
|
+
displayName: string;
|
|
259
|
+
role: DocRoleWire;
|
|
260
|
+
contentType: string;
|
|
261
|
+
size: number;
|
|
262
|
+
steps: string[];
|
|
263
|
+
}
|
|
264
|
+
interface DocsUploadOptions extends CommonOptions {
|
|
265
|
+
file: string;
|
|
266
|
+
projectId?: string;
|
|
267
|
+
role?: string;
|
|
268
|
+
name?: string;
|
|
269
|
+
idempotencyKey?: string;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* `project docs upload <file>` — upload an API spec or PRD as a project
|
|
273
|
+
* source so plan generation has inputs to feed on (closes the API-project
|
|
274
|
+
* cold start at `no_processed_inputs`).
|
|
275
|
+
*
|
|
276
|
+
* Three-step flow against the V3-A facade routes:
|
|
277
|
+
*
|
|
278
|
+
* 1. `POST /projects/{id}/docs/upload-url` — mints a one-hour presigned
|
|
279
|
+
* S3 PUT URL plus the S3 key to register afterwards.
|
|
280
|
+
* 2. HTTP PUT of the file bytes to the presigned URL — **streamed**
|
|
281
|
+
* (`createReadStream` → web stream), never buffering the whole file.
|
|
282
|
+
* This request goes straight to S3: no facade base URL, no API key.
|
|
283
|
+
* 3. `POST /projects/{id}/docs` — registers the S3 object with its role
|
|
284
|
+
* and display name, which starts processing + embedding.
|
|
285
|
+
*
|
|
286
|
+
* Reading the local file as INPUT is allowed by DR-21 (the no-local-OUTPUTS
|
|
287
|
+
* rule); nothing is ever written back to disk.
|
|
288
|
+
*
|
|
289
|
+
* Failure modes are deliberately distinguished (design non-negotiable): a
|
|
290
|
+
* step-2 failure names the presigned PUT and the fix (re-running mints a
|
|
291
|
+
* fresh URL — they expire); a step-3 failure preserves the server envelope
|
|
292
|
+
* and says the upload already succeeded (re-running is safe: the server
|
|
293
|
+
* upserts the document by S3 key, so no duplicate is created).
|
|
294
|
+
*/
|
|
295
|
+
export declare function runDocsUpload(opts: DocsUploadOptions, deps?: ProjectDeps): Promise<CliDocsUploadResult | CliDocsUploadPlan>;
|
|
218
296
|
export declare function createProjectCommand(deps?: ProjectDeps): Command;
|
|
219
297
|
export {};
|
package/dist/commands/project.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createReadStream, readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import { basename, extname } from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
3
5
|
import { Command } from 'commander';
|
|
4
|
-
import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
|
|
5
|
-
import { ApiError } from '../lib/errors.js';
|
|
6
|
+
import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
|
|
7
|
+
import { ApiError, InterruptError, RequestTimeoutError } from '../lib/errors.js';
|
|
8
|
+
import { globalShutdown } from '../lib/interrupt.js';
|
|
6
9
|
import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
|
|
10
|
+
import { readSecretFileGuarded } from '../lib/secret-file.js';
|
|
7
11
|
import { assertNotLocal } from '../lib/target-url.js';
|
|
8
12
|
import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
|
|
9
13
|
import { assertIdempotencyKey } from '../lib/validate.js';
|
|
@@ -113,7 +117,7 @@ export async function runCreate(opts, deps = {}) {
|
|
|
113
117
|
// Resolve password: flag > file > none
|
|
114
118
|
let password = opts.password;
|
|
115
119
|
if (password === undefined && opts.passwordFile !== undefined) {
|
|
116
|
-
password =
|
|
120
|
+
password = readSecretFileGuarded('password-file', opts.passwordFile);
|
|
117
121
|
}
|
|
118
122
|
const idempotencyKey = opts.idempotencyKey ?? `cli-proj-create-${randomUUID()}`;
|
|
119
123
|
if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
|
|
@@ -245,7 +249,7 @@ export async function runUpdate(opts, deps = {}) {
|
|
|
245
249
|
// filesystem, even when --password-file is present.
|
|
246
250
|
let password = opts.password;
|
|
247
251
|
if (password === undefined && opts.passwordFile !== undefined) {
|
|
248
|
-
password =
|
|
252
|
+
password = readSecretFileGuarded('password-file', opts.passwordFile);
|
|
249
253
|
}
|
|
250
254
|
const idempotencyKey = opts.idempotencyKey ?? `cli-proj-update-${randomUUID()}`;
|
|
251
255
|
if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
|
|
@@ -452,6 +456,382 @@ function renderAutoAuthText(r) {
|
|
|
452
456
|
}
|
|
453
457
|
return lines.join('\n');
|
|
454
458
|
}
|
|
459
|
+
// ---------------------------------------------------------------------------
|
|
460
|
+
// project docs upload — DEV-384 piece V3-D
|
|
461
|
+
// ---------------------------------------------------------------------------
|
|
462
|
+
/**
|
|
463
|
+
* CLI-facing role flags → wire enum. Default is `api-doc` (stated in help);
|
|
464
|
+
* no inference from project type in v1 (design §3.4).
|
|
465
|
+
*/
|
|
466
|
+
const DOC_ROLES = { 'api-doc': 'API_DOC', prd: 'PRD' };
|
|
467
|
+
/**
|
|
468
|
+
* MIME type sent in step 1 and echoed on the step-2 PUT. The backend signs
|
|
469
|
+
* `ContentType` into the presigned URL when supplied, so the PUT's
|
|
470
|
+
* `Content-Type` header must be byte-identical to what step 1 declared —
|
|
471
|
+
* both come from this one lookup, so they cannot drift.
|
|
472
|
+
*/
|
|
473
|
+
const DOC_CONTENT_TYPES = {
|
|
474
|
+
'.json': 'application/json',
|
|
475
|
+
'.yaml': 'application/yaml',
|
|
476
|
+
'.yml': 'application/yaml',
|
|
477
|
+
'.md': 'text/markdown',
|
|
478
|
+
'.markdown': 'text/markdown',
|
|
479
|
+
'.txt': 'text/plain',
|
|
480
|
+
'.pdf': 'application/pdf',
|
|
481
|
+
};
|
|
482
|
+
const DEFAULT_DOC_CONTENT_TYPE = 'application/octet-stream';
|
|
483
|
+
/**
|
|
484
|
+
* `project docs upload <file>` — upload an API spec or PRD as a project
|
|
485
|
+
* source so plan generation has inputs to feed on (closes the API-project
|
|
486
|
+
* cold start at `no_processed_inputs`).
|
|
487
|
+
*
|
|
488
|
+
* Three-step flow against the V3-A facade routes:
|
|
489
|
+
*
|
|
490
|
+
* 1. `POST /projects/{id}/docs/upload-url` — mints a one-hour presigned
|
|
491
|
+
* S3 PUT URL plus the S3 key to register afterwards.
|
|
492
|
+
* 2. HTTP PUT of the file bytes to the presigned URL — **streamed**
|
|
493
|
+
* (`createReadStream` → web stream), never buffering the whole file.
|
|
494
|
+
* This request goes straight to S3: no facade base URL, no API key.
|
|
495
|
+
* 3. `POST /projects/{id}/docs` — registers the S3 object with its role
|
|
496
|
+
* and display name, which starts processing + embedding.
|
|
497
|
+
*
|
|
498
|
+
* Reading the local file as INPUT is allowed by DR-21 (the no-local-OUTPUTS
|
|
499
|
+
* rule); nothing is ever written back to disk.
|
|
500
|
+
*
|
|
501
|
+
* Failure modes are deliberately distinguished (design non-negotiable): a
|
|
502
|
+
* step-2 failure names the presigned PUT and the fix (re-running mints a
|
|
503
|
+
* fresh URL — they expire); a step-3 failure preserves the server envelope
|
|
504
|
+
* and says the upload already succeeded (re-running is safe: the server
|
|
505
|
+
* upserts the document by S3 key, so no duplicate is created).
|
|
506
|
+
*/
|
|
507
|
+
export async function runDocsUpload(opts, deps = {}) {
|
|
508
|
+
const out = makeOutput(opts.output, deps);
|
|
509
|
+
const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
510
|
+
assertIdempotencyKey(opts.idempotencyKey);
|
|
511
|
+
const projectId = requireDocsProjectId(opts.projectId, deps);
|
|
512
|
+
const roleFlag = opts.role ?? 'api-doc';
|
|
513
|
+
if (!(roleFlag in DOC_ROLES)) {
|
|
514
|
+
throw localValidationError('--role must be api-doc (API spec, the default) or prd (product requirements document)');
|
|
515
|
+
}
|
|
516
|
+
const role = DOC_ROLES[roleFlag];
|
|
517
|
+
if (opts.name !== undefined && opts.name.trim().length === 0) {
|
|
518
|
+
throw localValidationError('--name must not be empty or whitespace-only');
|
|
519
|
+
}
|
|
520
|
+
if (opts.name !== undefined && opts.name.length > 255) {
|
|
521
|
+
throw localValidationError('--name must be at most 255 characters');
|
|
522
|
+
}
|
|
523
|
+
if (opts.file === undefined || opts.file.trim().length === 0) {
|
|
524
|
+
throw localValidationError('<file> is required');
|
|
525
|
+
}
|
|
526
|
+
// Size + existence sanity via stat only — the dry-run contract is "nothing
|
|
527
|
+
// read beyond a stat", and the real path opens the file exactly once, in
|
|
528
|
+
// the streamed PUT below.
|
|
529
|
+
let stat;
|
|
530
|
+
try {
|
|
531
|
+
stat = statSync(opts.file);
|
|
532
|
+
}
|
|
533
|
+
catch (cause) {
|
|
534
|
+
const code = cause.code;
|
|
535
|
+
if (code === 'ENOENT') {
|
|
536
|
+
throw localValidationError(`file does not exist: ${opts.file}`);
|
|
537
|
+
}
|
|
538
|
+
throw localValidationError(`cannot stat file ${opts.file}: ${cause.message ?? String(cause)}`);
|
|
539
|
+
}
|
|
540
|
+
if (!stat.isFile()) {
|
|
541
|
+
throw localValidationError(`${opts.file} is not a regular file (is it a directory?)`);
|
|
542
|
+
}
|
|
543
|
+
if (stat.size === 0) {
|
|
544
|
+
throw localValidationError(`file is empty (0 bytes), nothing to upload: ${opts.file}`);
|
|
545
|
+
}
|
|
546
|
+
const fileName = basename(opts.file);
|
|
547
|
+
if (fileName.length > 255) {
|
|
548
|
+
throw localValidationError('the file name (basename) must be at most 255 characters — rename the file ' +
|
|
549
|
+
'(--name only changes the display name, not the stored file name)');
|
|
550
|
+
}
|
|
551
|
+
const displayName = opts.name ?? fileName;
|
|
552
|
+
const contentType = DOC_CONTENT_TYPES[extname(fileName).toLowerCase()] ?? DEFAULT_DOC_CONTENT_TYPE;
|
|
553
|
+
const projectPath = encodeURIComponent(projectId);
|
|
554
|
+
if (opts.dryRun) {
|
|
555
|
+
// Same inline early-exit family as `test delete-batch --dry-run`: the
|
|
556
|
+
// command's dry-run contract (zero network, stat only, print the plan)
|
|
557
|
+
// cannot be expressed through canned fetch samples — step 2 would have
|
|
558
|
+
// to PUT somewhere. The `docsUploadUrl`/`docsRegister` entries in
|
|
559
|
+
// `samples.ts` are shape-guards/documentation, not consumed here.
|
|
560
|
+
emitDryRunBanner(stderr);
|
|
561
|
+
const plan = {
|
|
562
|
+
dryRun: true,
|
|
563
|
+
projectId,
|
|
564
|
+
file: opts.file,
|
|
565
|
+
fileName,
|
|
566
|
+
displayName,
|
|
567
|
+
role,
|
|
568
|
+
contentType,
|
|
569
|
+
size: stat.size,
|
|
570
|
+
steps: [
|
|
571
|
+
`POST /projects/${projectId}/docs/upload-url — mint a presigned S3 PUT URL for ${fileName} (${contentType})`,
|
|
572
|
+
`PUT ${stat.size} bytes to the presigned URL (streamed from disk, never buffered)`,
|
|
573
|
+
`POST /projects/${projectId}/docs — register ${displayName} as ${role}; starts processing + embedding`,
|
|
574
|
+
],
|
|
575
|
+
};
|
|
576
|
+
out.print(plan, data => renderDocsUploadPlanText(data));
|
|
577
|
+
return plan;
|
|
578
|
+
}
|
|
579
|
+
const idempotencyKey = opts.idempotencyKey ?? `cli-docs-upload-${randomUUID()}`;
|
|
580
|
+
if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
|
|
581
|
+
stderr(`idempotency-key: ${idempotencyKey}`);
|
|
582
|
+
}
|
|
583
|
+
const client = makeClient(opts, deps);
|
|
584
|
+
// ── Step 1 of 3: mint the presigned upload URL ────────────────────────────
|
|
585
|
+
const minted = await client.post(`/projects/${projectPath}/docs/upload-url`, { body: { fileName, contentType } });
|
|
586
|
+
// ── Step 2 of 3: stream the file bytes to S3 ──────────────────────────────
|
|
587
|
+
// Straight to the presigned host with the raw fetch impl — NOT through
|
|
588
|
+
// HttpClient, which would attach the facade base URL and leak the API key
|
|
589
|
+
// to S3. Content-Length comes from the stat: S3 rejects chunked
|
|
590
|
+
// transfer-encoding on presigned PUTs, and Node's fetch uses the explicit
|
|
591
|
+
// header to keep identity framing with a streamed body.
|
|
592
|
+
const fetchImpl = deps.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
593
|
+
// DEV-384 review F3: a remote facade must mint a non-local https URL.
|
|
594
|
+
assertSafePresignedUploadUrl(minted.uploadUrl, client.resolvedBaseUrl);
|
|
595
|
+
// Same flag > TESTSPRITE_REQUEST_TIMEOUT_MS > default resolution (and 1-600s
|
|
596
|
+
// clamp) as makeHttpClient — this leg bypasses HttpClient, so resolve here.
|
|
597
|
+
const requestTimeoutMs = resolveRequestTimeoutMs(opts, deps.env ?? process.env);
|
|
598
|
+
const controller = new AbortController();
|
|
599
|
+
const timer = setTimeout(() => controller.abort(), requestTimeoutMs);
|
|
600
|
+
// DEV-384 review F14b: compose the shutdown signal into the PUT abort
|
|
601
|
+
// (manual listeners, house style — no AbortSignal.any) and arm the
|
|
602
|
+
// graceful scope for the upload's duration, so Ctrl-C during a long PUT
|
|
603
|
+
// takes the honest DEV-331 detach path instead of being unabortable.
|
|
604
|
+
const shutdown = deps.shutdown ?? globalShutdown;
|
|
605
|
+
const shutdownSignal = shutdown.signal;
|
|
606
|
+
const onShutdownAbort = () => controller.abort(shutdownSignal.reason);
|
|
607
|
+
const disarm = shutdown.arm();
|
|
608
|
+
if (shutdownSignal.aborted)
|
|
609
|
+
onShutdownAbort();
|
|
610
|
+
else
|
|
611
|
+
shutdownSignal.addEventListener('abort', onShutdownAbort, { once: true });
|
|
612
|
+
let putResponse;
|
|
613
|
+
try {
|
|
614
|
+
putResponse = await fetchImpl(minted.uploadUrl, {
|
|
615
|
+
method: 'PUT',
|
|
616
|
+
headers: { 'content-type': contentType, 'content-length': String(stat.size) },
|
|
617
|
+
body: Readable.toWeb(createReadStream(opts.file)),
|
|
618
|
+
duplex: 'half',
|
|
619
|
+
// #342 review: assertSafePresignedUploadUrl vets the MINTED url, but a
|
|
620
|
+
// default `redirect: 'follow'` would let a 3xx from that host resend
|
|
621
|
+
// the request to an unvetted Location (e.g. a 303 → 169.254.169.254) —
|
|
622
|
+
// an SSRF-shaped hop the guard never sees. A real S3 presigned PUT never
|
|
623
|
+
// redirects, so refuse: the thrown TypeError falls through to the catch
|
|
624
|
+
// below as a normal `presigned_put_failed` (no new error reason).
|
|
625
|
+
redirect: 'error',
|
|
626
|
+
signal: controller.signal,
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
catch (cause) {
|
|
630
|
+
// Interrupt outranks the timeout mapping: a Ctrl-C-aborted fetch must
|
|
631
|
+
// surface as InterruptError (exit 130/143), never as a timeout.
|
|
632
|
+
if (cause instanceof InterruptError)
|
|
633
|
+
throw cause;
|
|
634
|
+
if (shutdownSignal.aborted)
|
|
635
|
+
throw shutdownSignal.reason;
|
|
636
|
+
// Any other abort here is ours (the per-request timer): map to the CLI's
|
|
637
|
+
// typed exit-7 timeout, same contract as HttpClient's per-request timeout.
|
|
638
|
+
if (isAbortError(cause)) {
|
|
639
|
+
throw new RequestTimeoutError(requestTimeoutMs);
|
|
640
|
+
}
|
|
641
|
+
throw presignedPutError(`network error before S3 responded: ${describeCause(cause)}`, minted.expiresInSeconds);
|
|
642
|
+
}
|
|
643
|
+
finally {
|
|
644
|
+
clearTimeout(timer);
|
|
645
|
+
shutdownSignal.removeEventListener('abort', onShutdownAbort);
|
|
646
|
+
disarm();
|
|
647
|
+
}
|
|
648
|
+
if (!putResponse.ok) {
|
|
649
|
+
const snippet = (await putResponse.text().catch(() => '')).slice(0, 300);
|
|
650
|
+
throw presignedPutError(`S3 returned HTTP ${putResponse.status}${snippet ? ` — ${snippet}` : ''}`, minted.expiresInSeconds);
|
|
651
|
+
}
|
|
652
|
+
// ── Step 3 of 3: register the uploaded object ─────────────────────────────
|
|
653
|
+
let registered;
|
|
654
|
+
try {
|
|
655
|
+
registered = await client.post(`/projects/${projectPath}/docs`, {
|
|
656
|
+
body: { s3Key: minted.s3Key, displayName, docRole: role },
|
|
657
|
+
headers: { 'idempotency-key': idempotencyKey },
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
catch (cause) {
|
|
661
|
+
if (cause instanceof ApiError)
|
|
662
|
+
throw registerStepError(cause);
|
|
663
|
+
// DEV-384 review F4: a register timeout needs the same step-3 context —
|
|
664
|
+
// it is precisely the case where the caller can't tell whether the
|
|
665
|
+
// register landed. Class and exit 7 are preserved; only the text gains
|
|
666
|
+
// the upload-succeeded / safe-to-re-run explanation.
|
|
667
|
+
if (cause instanceof RequestTimeoutError) {
|
|
668
|
+
cause.message =
|
|
669
|
+
`Document register timed out (step 3 of 3) — the S3 upload succeeded, and the ` +
|
|
670
|
+
`register may or may not have landed. ${cause.message} Re-running the whole command ` +
|
|
671
|
+
`is safe: the server upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).`;
|
|
672
|
+
throw cause;
|
|
673
|
+
}
|
|
674
|
+
throw cause;
|
|
675
|
+
}
|
|
676
|
+
const result = {
|
|
677
|
+
resourceId: registered.resourceId,
|
|
678
|
+
displayName: registered.displayName ?? displayName,
|
|
679
|
+
role: registered.docRole ?? role,
|
|
680
|
+
size: stat.size,
|
|
681
|
+
processStatus: registered.processStatus,
|
|
682
|
+
};
|
|
683
|
+
out.print(result, data => renderDocsUploadText(data));
|
|
684
|
+
return result;
|
|
685
|
+
}
|
|
686
|
+
function isAbortError(cause) {
|
|
687
|
+
return cause instanceof Error && cause.name === 'AbortError';
|
|
688
|
+
}
|
|
689
|
+
function describeCause(cause) {
|
|
690
|
+
if (!(cause instanceof Error))
|
|
691
|
+
return String(cause);
|
|
692
|
+
// undici wraps network failures as `TypeError: fetch failed` with the
|
|
693
|
+
// useful detail on `.cause` — surface both.
|
|
694
|
+
const nested = cause.cause;
|
|
695
|
+
const nestedMsg = nested instanceof Error ? ` (${nested.message})` : '';
|
|
696
|
+
return `${cause.message}${nestedMsg}`;
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* DEV-384 review F3 — defense-in-depth on the server-minted presigned URL.
|
|
700
|
+
*
|
|
701
|
+
* A REMOTE facade must mint a non-local `https:` URL; a localhost/private or
|
|
702
|
+
* plain-http mint from a remote facade is exactly the anomaly to reject
|
|
703
|
+
* (compromised/misconfigured facade or an active MITM) — the PUT would
|
|
704
|
+
* otherwise send the user's file wherever that URL points, before any bytes
|
|
705
|
+
* leave the machine. A facade that is ITSELF loopback (dev rig, localhost
|
|
706
|
+
* e2e) is a deliberate operator configuration and is trusted to mint local
|
|
707
|
+
* URLs — and ONLY loopback qualifies (#342 review): the gate is a positive,
|
|
708
|
+
* fail-closed check, because gating on "anything `assertNotLocal` dislikes"
|
|
709
|
+
* would silently disable the guard for an unparsable base URL or a
|
|
710
|
+
* user-settable private-range endpoint (`--endpoint-url https://10.1.2.3`).
|
|
711
|
+
* Literal checks only (same scope as `assertNotLocal`); no host
|
|
712
|
+
* allow-listing by design.
|
|
713
|
+
*
|
|
714
|
+
* Known residual (#342 review): a loopback facade that is really a TUNNEL to a
|
|
715
|
+
* remote backend (`ssh -L`, a localhost corporate proxy) is trusted here even
|
|
716
|
+
* though the real conversation is remote and MITM-able upstream. This is
|
|
717
|
+
* inherent to "loopback facade = trusted dev rig" and accepted — the CLI
|
|
718
|
+
* cannot tell a dev rig from a tunnel by the base URL alone.
|
|
719
|
+
*/
|
|
720
|
+
function assertSafePresignedUploadUrl(uploadUrl, facadeBaseUrl) {
|
|
721
|
+
if (isLoopbackFacade(facadeBaseUrl))
|
|
722
|
+
return;
|
|
723
|
+
const reject = (reason) => {
|
|
724
|
+
throw ApiError.fromEnvelope({
|
|
725
|
+
error: {
|
|
726
|
+
code: 'VALIDATION_ERROR',
|
|
727
|
+
message: `Refusing the presigned upload URL the server returned: ${reason}.`,
|
|
728
|
+
nextAction: 'No bytes were uploaded. This can indicate a misconfigured or intercepted API ' +
|
|
729
|
+
'endpoint — verify --endpoint-url / TESTSPRITE_API_URL and retry.',
|
|
730
|
+
requestId: 'local',
|
|
731
|
+
details: { field: 'uploadUrl', reason: 'unsafe_presigned_url' },
|
|
732
|
+
},
|
|
733
|
+
});
|
|
734
|
+
};
|
|
735
|
+
let parsed;
|
|
736
|
+
try {
|
|
737
|
+
parsed = new URL(uploadUrl);
|
|
738
|
+
}
|
|
739
|
+
catch {
|
|
740
|
+
return reject('it is not a valid URL');
|
|
741
|
+
}
|
|
742
|
+
if (parsed.protocol !== 'https:')
|
|
743
|
+
return reject('it is not https');
|
|
744
|
+
if (isLocalUrl(uploadUrl))
|
|
745
|
+
return reject('it points at a local/private address');
|
|
746
|
+
}
|
|
747
|
+
/** True when `assertNotLocal` rejects the URL (localhost, RFC1918, link-local,
|
|
748
|
+
* metadata, non-http(s), unparsable). Fail-closed in the REJECTION direction
|
|
749
|
+
* only — used to refuse a suspicious mint, never to grant trust (that side
|
|
750
|
+
* is `isLoopbackFacade`). */
|
|
751
|
+
function isLocalUrl(url) {
|
|
752
|
+
try {
|
|
753
|
+
assertNotLocal(url);
|
|
754
|
+
return false;
|
|
755
|
+
}
|
|
756
|
+
catch {
|
|
757
|
+
return true;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* #342 review: the facade-trust gate for `assertSafePresignedUploadUrl`.
|
|
762
|
+
* Positive and narrow — only an explicitly-loopback facade (`localhost`,
|
|
763
|
+
* a `127.0.0.0/8` literal, or `[::1]`) is trusted to mint local upload URLs.
|
|
764
|
+
* Anything else — including an unparsable base URL or a private-range
|
|
765
|
+
* endpoint — leaves the guard ON.
|
|
766
|
+
*/
|
|
767
|
+
function isLoopbackFacade(url) {
|
|
768
|
+
let parsed;
|
|
769
|
+
try {
|
|
770
|
+
parsed = new URL(url);
|
|
771
|
+
}
|
|
772
|
+
catch {
|
|
773
|
+
return false;
|
|
774
|
+
}
|
|
775
|
+
// `localhost.` is the fully-qualified form of `localhost` (RFC 6761).
|
|
776
|
+
const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
|
|
777
|
+
if (host === 'localhost')
|
|
778
|
+
return true;
|
|
779
|
+
if (/^127\.\d+\.\d+\.\d+$/.test(host))
|
|
780
|
+
return true;
|
|
781
|
+
return host === '[::1]';
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Step-2 failure: the presigned PUT to S3. Distinguished from a register
|
|
785
|
+
* failure per the design non-negotiable — the fix is different (re-running
|
|
786
|
+
* re-mints the URL; nothing was registered, so nothing is half-done).
|
|
787
|
+
*/
|
|
788
|
+
function presignedPutError(detail, expiresInSeconds) {
|
|
789
|
+
return new ApiError({
|
|
790
|
+
code: 'UNAVAILABLE',
|
|
791
|
+
message: `Presigned S3 upload failed (step 2 of 3): ${detail}`,
|
|
792
|
+
nextAction: 'The document was NOT registered. Re-run the command — each run mints a fresh ' +
|
|
793
|
+
`upload URL (presigned URLs expire, this one after ${Math.round(expiresInSeconds / 60)} minutes).`,
|
|
794
|
+
requestId: 'local',
|
|
795
|
+
details: { reason: 'presigned_put_failed' },
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Step-3 failure: register. The server envelope (code, exit, requestId,
|
|
800
|
+
* details) passes through unchanged; only the text gains step context so
|
|
801
|
+
* the caller knows the upload itself already landed and a re-run is safe
|
|
802
|
+
* (the server upserts the document by S3 key — no duplicate).
|
|
803
|
+
*/
|
|
804
|
+
function registerStepError(cause) {
|
|
805
|
+
return new ApiError({
|
|
806
|
+
code: cause.code,
|
|
807
|
+
message: `Document register failed (step 3 of 3) — the S3 upload succeeded, but the document is not registered yet. ${cause.message}`,
|
|
808
|
+
nextAction: `${cause.nextAction ? `${cause.nextAction} ` : ''}` +
|
|
809
|
+
'Re-running the whole command is safe: the same file re-uploads and the server ' +
|
|
810
|
+
'upserts the document by its S3 key (no duplicate is created; a PRD re-register re-runs the embedding compute, but the embedding charge is idempotent per document — never billed twice).',
|
|
811
|
+
requestId: cause.requestId,
|
|
812
|
+
details: cause.details,
|
|
813
|
+
}, cause.httpStatus, cause.retryAfterMs);
|
|
814
|
+
}
|
|
815
|
+
function formatDocSize(bytes) {
|
|
816
|
+
if (bytes < 1024)
|
|
817
|
+
return `${bytes} B`;
|
|
818
|
+
if (bytes < 1024 * 1024)
|
|
819
|
+
return `${Math.round(bytes / 1024)} KB`;
|
|
820
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
821
|
+
}
|
|
822
|
+
function renderDocsUploadText(r) {
|
|
823
|
+
return [
|
|
824
|
+
`uploaded ${r.displayName} (${formatDocSize(r.size)}) — processing started`,
|
|
825
|
+
'note: generation can use this source once processing and embedding finish',
|
|
826
|
+
' (check with `testsprite test plan generate` — it says if inputs are still processing)',
|
|
827
|
+
].join('\n');
|
|
828
|
+
}
|
|
829
|
+
function renderDocsUploadPlanText(p) {
|
|
830
|
+
return [
|
|
831
|
+
`would upload ${p.file} (${formatDocSize(p.size)}) to project ${p.projectId} as ${p.role}:`,
|
|
832
|
+
...p.steps.map((step, i) => ` ${i + 1}. ${step}`),
|
|
833
|
+
].join('\n');
|
|
834
|
+
}
|
|
455
835
|
export function createProjectCommand(deps = {}) {
|
|
456
836
|
const project = new Command('project').description('Manage TestSprite projects');
|
|
457
837
|
project
|
|
@@ -648,6 +1028,36 @@ export function createProjectCommand(deps = {}) {
|
|
|
648
1028
|
idempotencyKey: cmdOpts.idempotencyKey,
|
|
649
1029
|
}, deps);
|
|
650
1030
|
});
|
|
1031
|
+
const docs = new Command('docs').description('Manage project documents — the sources plan generation feeds on');
|
|
1032
|
+
docs
|
|
1033
|
+
.command('upload <file>')
|
|
1034
|
+
.description('Upload an API spec or PRD as a project source (DEV-384). Three steps:\n' +
|
|
1035
|
+
'mint a presigned S3 URL, stream the file bytes to it, register the\n' +
|
|
1036
|
+
'document — which starts processing + embedding. The local file is\n' +
|
|
1037
|
+
'only read; nothing is written back to disk.\n' +
|
|
1038
|
+
'\nExit codes:\n' +
|
|
1039
|
+
' 0 upload registered (processing started)\n' +
|
|
1040
|
+
' 3 auth error\n' +
|
|
1041
|
+
' 4 project not found (or not accessible in this workspace)\n' +
|
|
1042
|
+
' 5 validation error (missing/empty file, bad --role)\n' +
|
|
1043
|
+
' 7 request timeout (also: backend predates the docs routes)\n' +
|
|
1044
|
+
' 10 presigned S3 PUT failed — re-run to mint a fresh URL')
|
|
1045
|
+
.option('--project <id>', 'project id the document belongs to (required)')
|
|
1046
|
+
.option('--role <role>', 'document role: api-doc (API spec, default) | prd')
|
|
1047
|
+
.option('--name <display-name>', 'display name for the document (default: file basename)')
|
|
1048
|
+
.option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
|
|
1049
|
+
.addHelpText('after', GLOBAL_OPTS_HINT)
|
|
1050
|
+
.action(async (file, cmdOpts, command) => {
|
|
1051
|
+
await runDocsUpload({
|
|
1052
|
+
...resolveCommonOptions(command),
|
|
1053
|
+
file,
|
|
1054
|
+
projectId: cmdOpts.project,
|
|
1055
|
+
role: cmdOpts.role,
|
|
1056
|
+
name: cmdOpts.name,
|
|
1057
|
+
idempotencyKey: cmdOpts.idempotencyKey,
|
|
1058
|
+
}, deps);
|
|
1059
|
+
});
|
|
1060
|
+
project.addCommand(docs);
|
|
651
1061
|
return project;
|
|
652
1062
|
}
|
|
653
1063
|
function parseFlag(raw, flagName) {
|
|
@@ -803,6 +1213,20 @@ function renderUpdateText(r) {
|
|
|
803
1213
|
function renderDeleteText(r) {
|
|
804
1214
|
return [`projectId ${r.projectId}`, `deletedAt ${r.deletedAt}`].join('\n');
|
|
805
1215
|
}
|
|
1216
|
+
/**
|
|
1217
|
+
* `--project` resolution for `project docs upload` — mirrors test.ts's
|
|
1218
|
+
* resolveProjectId/requireProjectId so `TESTSPRITE_PROJECT_ID` works here the
|
|
1219
|
+
* same as on every other command (DEV-384 review F5). Flag wins over env.
|
|
1220
|
+
*/
|
|
1221
|
+
function requireDocsProjectId(projectId, deps) {
|
|
1222
|
+
const explicit = projectId?.trim();
|
|
1223
|
+
if (explicit && explicit.length > 0)
|
|
1224
|
+
return explicit;
|
|
1225
|
+
const envValue = (deps.env ?? process.env).TESTSPRITE_PROJECT_ID?.trim();
|
|
1226
|
+
if (envValue && envValue.length > 0)
|
|
1227
|
+
return envValue;
|
|
1228
|
+
throw localValidationError('--project <id> is required; pass --project <id> or set TESTSPRITE_PROJECT_ID');
|
|
1229
|
+
}
|
|
806
1230
|
function localValidationError(message) {
|
|
807
1231
|
return ApiError.fromEnvelope({
|
|
808
1232
|
error: {
|