@testsprite/testsprite-cli 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +51 -48
  2. package/dist/commands/doctor.js +12 -11
  3. package/dist/commands/project-env.d.ts +11 -1
  4. package/dist/commands/project-env.js +399 -61
  5. package/dist/commands/project-sign-in.d.ts +60 -0
  6. package/dist/commands/project-sign-in.js +289 -0
  7. package/dist/commands/project.d.ts +9 -0
  8. package/dist/commands/project.js +68 -28
  9. package/dist/commands/schedule.d.ts +12 -0
  10. package/dist/commands/schedule.js +175 -5
  11. package/dist/commands/test.d.ts +53 -20
  12. package/dist/commands/test.js +1356 -342
  13. package/dist/commands/testlist.d.ts +10 -5
  14. package/dist/commands/testlist.js +170 -30
  15. package/dist/commands/tunnel.js +11 -5
  16. package/dist/index.js +12 -37
  17. package/dist/lib/client-factory.d.ts +12 -1
  18. package/dist/lib/client-factory.js +14 -4
  19. package/dist/lib/dry-run/samples.js +53 -0
  20. package/dist/lib/environment-tunnel.d.ts +109 -0
  21. package/dist/lib/environment-tunnel.js +465 -0
  22. package/dist/lib/errors.js +12 -1
  23. package/dist/lib/gh-output.js +3 -0
  24. package/dist/lib/http.d.ts +2 -0
  25. package/dist/lib/junit-report.d.ts +11 -7
  26. package/dist/lib/junit-report.js +13 -7
  27. package/dist/lib/local-target.d.ts +13 -3
  28. package/dist/lib/local-target.js +47 -12
  29. package/dist/lib/output.js +15 -1
  30. package/dist/lib/plan-poll.js +3 -4
  31. package/dist/lib/redact.d.ts +38 -0
  32. package/dist/lib/redact.js +140 -0
  33. package/dist/lib/render-error.d.ts +19 -5
  34. package/dist/lib/render-error.js +31 -0
  35. package/dist/lib/runs.types.d.ts +9 -1
  36. package/dist/lib/target-url.js +5 -5
  37. package/dist/lib/telemetry.d.ts +6 -7
  38. package/dist/lib/telemetry.js +11 -4
  39. package/dist/lib/testlist.types.d.ts +1 -0
  40. package/dist/lib/ticker.d.ts +9 -0
  41. package/dist/lib/ticker.js +18 -0
  42. package/dist/lib/tunnel-session.d.ts +3 -4
  43. package/dist/lib/tunnel-session.js +3 -4
  44. package/dist/lib/v3-advisory.js +0 -1
  45. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  46. package/dist/vendor/tunnel-client/client.js +477 -407
  47. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  48. package/dist/vendor/tunnel-client/config.js +5 -5
  49. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  50. package/dist/vendor/tunnel-client/index.js +4 -4
  51. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  52. package/dist/vendor/tunnel-client/types.js +1 -0
  53. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  54. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/package.json +1 -1
  58. package/skills/testsprite-onboard.skill.md +4 -4
@@ -6,20 +6,10 @@
6
6
  * picks one by NAME, which is unique per project server-side; the default
7
7
  * environment is what every run without `--env` has always used.
8
8
  *
9
- * An app that only runs on your own machine is named with `--local <port>`
10
- * instead of `--url` — the same spelling as `project create`. The CLI builds
11
- * the loopback URL and sends the `originMode: 'local'` marker that lets the
12
- * server store it:
13
- *
14
- * project env create <pid> --name local-dev --local 5173 \
15
- * --username … --password-file …
16
- * test run <test-id> --env local-dev --local 5173
17
- *
18
- * `--local` on the run is what makes that address reachable from the cloud
19
- * runner; a run against a loopback environment without it is refused before
20
- * dispatch. A loopback `--url` is redirected to `--local`; everything the
21
- * runner can never reach (RFC1918, link-local, the metadata address,
22
- * non-http(s)) stays rejected.
9
+ * A loopback URL names an app on this machine. `--local <port>` is shorthand
10
+ * for `--url http://localhost:<port>`; both send the existing local marker.
11
+ * Frontend runs resolve this URL and open a tunnel automatically. Other
12
+ * private addresses and non-http(s) URLs remain rejected.
23
13
  *
24
14
  * Thin facade over `/api/cli/v1/projects/{id}/env`; the server owns every
25
15
  * rule (name uniqueness, default recompute, credential storage). Passwords go
@@ -27,16 +17,17 @@
27
17
  * renderer here.
28
18
  */
29
19
  import { randomUUID } from 'node:crypto';
30
- import { Command } from 'commander';
20
+ import { Command, Option } from 'commander';
31
21
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
32
22
  import { resolveProfileName } from '../lib/config.js';
33
- import { ApiError } from '../lib/errors.js';
23
+ import { ApiError, InterruptError } from '../lib/errors.js';
34
24
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
35
25
  import { readSecretFileGuarded } from '../lib/secret-file.js';
36
26
  import { assertStoredLocalTargetListening, buildLocalTargetUrl, parseStoredLocalTarget, } from '../lib/local-target.js';
37
27
  import { assertNotLocal } from '../lib/target-url.js';
38
28
  import { renderTextTable } from '../lib/text-table.js';
39
29
  import { assertIdempotencyKey } from '../lib/validate.js';
30
+ import { parseSessionTtl, parseSignInMode, signInValidationError, validateSignInFlags, } from './project-sign-in.js';
40
31
  // ---------------------------------------------------------------------------
41
32
  // Shared plumbing (same shape as `project.ts`; kept local so this module does
42
33
  // not import `project.ts` at runtime — that file imports this one).
@@ -67,14 +58,14 @@ function makeOutput(mode, deps) {
67
58
  function stderrOf(deps) {
68
59
  return deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
69
60
  }
70
- function localValidationError(message) {
61
+ function localValidationError(message, field) {
71
62
  return ApiError.fromEnvelope({
72
63
  error: {
73
64
  code: 'VALIDATION_ERROR',
74
65
  message: 'Invalid request.',
75
66
  nextAction: message,
76
67
  requestId: 'local',
77
- details: { reason: 'missing_required_flag' },
68
+ details: { reason: 'missing_required_flag', ...(field ? { field } : {}) },
78
69
  },
79
70
  });
80
71
  }
@@ -86,23 +77,163 @@ function envPath(projectId, name) {
86
77
  function requireEnvName(raw, flag) {
87
78
  const name = raw?.trim() ?? '';
88
79
  if (name.length === 0) {
89
- throw localValidationError(`${flag} is required and must not be empty or whitespace-only`);
80
+ throw localValidationError(`${flag} is required and must not be empty or whitespace-only`, flag === '--rename' ? 'rename' : undefined);
90
81
  }
91
82
  if (name.length > 100)
92
- throw localValidationError(`${flag} must be at most 100 characters`);
83
+ throw localValidationError(`${flag} must be at most 100 characters`, flag === '--rename' ? 'rename' : undefined);
93
84
  return name;
94
85
  }
95
- /** Resolve `--password` / `--password-file` (mutually exclusive; never both). */
96
- function resolvePassword(opts) {
86
+ const RESERVED_VARIABLE_KEYS = new Set([
87
+ 'url',
88
+ 'username',
89
+ 'password',
90
+ 'authType',
91
+ 'credential',
92
+ 'memory_hints',
93
+ 'rerun_context',
94
+ '__proto__',
95
+ 'constructor',
96
+ 'prototype',
97
+ ]);
98
+ function parseVariables(raw) {
99
+ if (raw === undefined || raw.length === 0)
100
+ return undefined;
101
+ if (raw.length > 50)
102
+ throw localValidationError('--var supports at most 50 keys.');
103
+ const variables = Object.create(null);
104
+ let totalBytes = 0;
105
+ for (const item of raw) {
106
+ const separator = item.indexOf('=');
107
+ if (separator <= 0)
108
+ throw localValidationError('--var requires KEY=VALUE with a nonempty key.');
109
+ const key = item.slice(0, separator);
110
+ const value = item.slice(separator + 1);
111
+ if (!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(key) || RESERVED_VARIABLE_KEYS.has(key)) {
112
+ throw localValidationError('--var key is invalid or reserved.');
113
+ }
114
+ if (Object.hasOwn(variables, key))
115
+ throw localValidationError('--var key was repeated.');
116
+ if (Buffer.byteLength(value, 'utf8') > 4096) {
117
+ throw localValidationError('--var value exceeds 4096 UTF-8 bytes.');
118
+ }
119
+ totalBytes += Buffer.byteLength(key, 'utf8') + Buffer.byteLength(value, 'utf8');
120
+ if (totalBytes > 32768)
121
+ throw localValidationError('--var values exceed 32 KiB.');
122
+ variables[key] = value;
123
+ }
124
+ return variables;
125
+ }
126
+ function collectVar(value, previous) {
127
+ return [...previous, value];
128
+ }
129
+ function unsupportedServer(feature) {
130
+ return ApiError.fromEnvelope({
131
+ error: {
132
+ code: 'UNSUPPORTED',
133
+ message: `The server is too old to support ${feature}.${feature === 'project env get' ? '' : ' No requested write was sent.'}`,
134
+ nextAction: `Upgrade the server before using ${feature}.`,
135
+ requestId: 'local',
136
+ details: {},
137
+ },
138
+ });
139
+ }
140
+ async function assertEnvironmentWriteSupport(client, projectId, name, feature) {
141
+ try {
142
+ const listed = await client.get(envPath(projectId));
143
+ if (listed.environments?.length) {
144
+ if (listed.environments.every(environment => environment.variables !== undefined &&
145
+ environment.variables !== null &&
146
+ typeof environment.variables === 'object'))
147
+ return;
148
+ throw unsupportedServer(feature);
149
+ }
150
+ const detail = await client.get(envPath(projectId, name));
151
+ if (!detail.environment ||
152
+ detail.environment.variables === undefined ||
153
+ detail.environment.variables === null ||
154
+ typeof detail.environment.variables !== 'object')
155
+ throw unsupportedServer(feature);
156
+ }
157
+ catch (err) {
158
+ if (err instanceof InterruptError)
159
+ throw err;
160
+ if (err instanceof ApiError) {
161
+ if (err.code === 'UNSUPPORTED')
162
+ throw err;
163
+ if (err.httpStatus === 404 && !err.details.resource)
164
+ throw unsupportedServer(feature);
165
+ if (err.code === 'VALIDATION_ERROR' && err.details.field === 'environment')
166
+ return;
167
+ if (err.httpStatus !== 403)
168
+ throw err;
169
+ }
170
+ // A key may have write:projects without read:projects. If the probe is
171
+ // unavailable, preserve that write path and require the response echo below.
172
+ }
173
+ }
174
+ function confirmRequestedEffects(environment, requested, urlMayHaveChanged, created, updated) {
175
+ const unapplied = [];
176
+ if (requested.clearCredentials &&
177
+ (environment?.hasCredentials !== false || environment.username)) {
178
+ unapplied.push('--clear-credentials');
179
+ }
180
+ if (requested.variables !== undefined) {
181
+ const returned = environment?.variables;
182
+ if (returned === undefined ||
183
+ returned === null ||
184
+ typeof returned !== 'object' ||
185
+ Object.entries(requested.variables).some(([key, value]) => !Object.hasOwn(returned, key) || returned[key] !== value)) {
186
+ unapplied.push('--var');
187
+ }
188
+ }
189
+ if (unapplied.length === 0)
190
+ return;
191
+ // A create already wrote the environment, so "retry" would hit a name
192
+ // conflict; say what exists and how to finish once the server supports it.
193
+ const receipt = created
194
+ ? `The server did not apply ${unapplied.join(' / ')}; environment '${created.name}' was created without them.`
195
+ : updated
196
+ ? `The server did not apply ${unapplied.join(' / ')}; environment '${updated.name}' ${updated.appliedFields.length ? `was updated (${updated.appliedFields.join(' / ')} applied)` : 'accepted the update'}.`
197
+ : `The server did not apply ${unapplied.join(' / ')}; upgrade the server or retry.`;
198
+ const message = receipt +
199
+ (updated?.passwordSupplied
200
+ ? ' --password was supplied; its stored value is not returned.'
201
+ : '');
202
+ const retryFlags = unapplied.map(flag => (flag === '--var' ? '--var KEY=VALUE' : flag)).join(' ');
203
+ const nextAction = created
204
+ ? `${message} After the server is upgraded, run: testsprite project env update ${created.projectId} ${created.name} ${retryFlags}`
205
+ : updated
206
+ ? `${message} After the server is upgraded, run: testsprite project env update ${updated.projectId} ${updated.name} ${retryFlags}${urlMayHaveChanged ? ' URL may already have been applied.' : ''}`
207
+ : `${message}${urlMayHaveChanged ? ' URL may already have been applied.' : ''}`;
208
+ throw ApiError.fromEnvelope({
209
+ error: {
210
+ code: 'UNSUPPORTED',
211
+ message,
212
+ nextAction,
213
+ requestId: 'local',
214
+ details: {},
215
+ },
216
+ });
217
+ }
218
+ /**
219
+ * Pure validation for `--password` / `--password-file`: mutual exclusion and
220
+ * non-empty inline value. No filesystem I/O — safe to call before a
221
+ * `--dry-run` early return, which must never touch the filesystem even when
222
+ * `--password-file` is present (see `resolvePassword`).
223
+ */
224
+ function assertPasswordFlagsValid(opts) {
97
225
  if (opts.password !== undefined && opts.passwordFile !== undefined) {
98
226
  throw localValidationError('--password and --password-file are mutually exclusive.');
99
227
  }
100
- if (opts.password !== undefined) {
101
- if (opts.password.trim().length === 0) {
102
- throw localValidationError('--password must not be empty or whitespace-only');
103
- }
104
- return opts.password;
228
+ if (opts.password !== undefined && opts.password.trim().length === 0) {
229
+ throw localValidationError('--password must not be empty or whitespace-only');
105
230
  }
231
+ }
232
+ /** Resolve `--password` / `--password-file` (mutually exclusive; never both). Real path only. */
233
+ function resolvePassword(opts) {
234
+ assertPasswordFlagsValid(opts);
235
+ if (opts.password !== undefined)
236
+ return opts.password;
106
237
  if (opts.passwordFile !== undefined) {
107
238
  return readSecretFileGuarded('password-file', opts.passwordFile);
108
239
  }
@@ -150,7 +281,12 @@ function renderEnvListText(r) {
150
281
  return renderTextTable(r.environments, ENV_LIST_COLUMNS);
151
282
  }
152
283
  function renderEnvText(env) {
153
- return [
284
+ const login = env.enableOtp || !['public', 'none', 'account'].includes(env.authMode)
285
+ ? 'managed in Portal'
286
+ : env.authMode === 'public' || env.authMode === 'none' || !env.hasCredentials
287
+ ? 'none'
288
+ : `username+password${env.username ? ` (${env.username})` : ''}`;
289
+ const lines = [
154
290
  `name: ${env.name}`,
155
291
  `id: ${env.id}`,
156
292
  `default: ${env.isDefault ? 'yes' : 'no'}`,
@@ -158,7 +294,14 @@ function renderEnvText(env) {
158
294
  `auth: ${describeAuth(env)}`,
159
295
  `account: ${env.username ?? '(none stored)'}`,
160
296
  `updatedAt: ${env.updatedAt}`,
161
- ].join('\n');
297
+ `login: ${login}`,
298
+ ];
299
+ const variables = Object.entries(env.variables ?? {}).filter(([key]) => key !== 'password');
300
+ lines.push(`variables: ${variables.length}`);
301
+ for (const [key, value] of variables.sort(([a], [b]) => a.localeCompare(b))) {
302
+ lines.push(` ${key}=${value}`);
303
+ }
304
+ return lines.join('\n');
162
305
  }
163
306
  function sampleEnv(overrides) {
164
307
  return {
@@ -171,9 +314,60 @@ function sampleEnv(overrides) {
171
314
  username: null,
172
315
  enableOtp: false,
173
316
  updatedAt: '2026-09-09T00:00:00.000Z',
317
+ variables: {},
174
318
  ...overrides,
175
319
  };
176
320
  }
321
+ /**
322
+ * Defence-in-depth DENY-list applied to an environment ONLY at the point it
323
+ * reaches `Output.print`. `Output.print`'s JSON branch stringifies its input
324
+ * verbatim BY DESIGN for most commands (`test code get --output json`, plans,
325
+ * fixtures) so that success data round-trips byte-identical — see the
326
+ * comment on `Output.print` and `redact.ts` — and this codebase treats an
327
+ * unrecognized field on a success payload as something to PASS THROUGH, not
328
+ * drop (`project get`'s `defaultEnvironment`/`environmentCount`, `test
329
+ * list`'s `statusByEnvironment`, and `CliProjectEnvironment.authMode` itself
330
+ * is an open string specifically so a mode added server-side shows up
331
+ * without a CLI release). An allow-list here would silently swallow any new
332
+ * field the server starts returning until the CLI ships again — so this
333
+ * shallow-copies the environment and removes only the two shapes a
334
+ * regression could use to leak a credential: a stray top-level `password`
335
+ * and the Portal's raw `config` object (see the type comment above — the
336
+ * wire shape is documented to never carry either). `variables` gets the same
337
+ * treatment as the reserved-key set the CLI already enforces on `--var`
338
+ * (`RESERVED_VARIABLE_KEYS`, mirrored server-side): everything else in
339
+ * `variables` — and everything else on the environment — passes through
340
+ * untouched, including a `variables` key the source never had at all ("JSON
341
+ * does not invent fields for older backends" falls out of the copy for
342
+ * free). Only the PRINTED copy is affected — the value `runEnv*` returns to
343
+ * its caller is the untouched server response.
344
+ */
345
+ function forDisplay(env) {
346
+ if (env === undefined || env === null || typeof env !== 'object')
347
+ return env;
348
+ const clone = { ...env };
349
+ delete clone.password;
350
+ delete clone.config;
351
+ if (clone.variables !== undefined &&
352
+ clone.variables !== null &&
353
+ typeof clone.variables === 'object') {
354
+ const variables = { ...clone.variables };
355
+ for (const key of RESERVED_VARIABLE_KEYS)
356
+ delete variables[key];
357
+ clone.variables = variables;
358
+ }
359
+ return clone;
360
+ }
361
+ /** Apply {@link forDisplay} to a single-environment response, for `out.print` only. */
362
+ function envForPrint(res) {
363
+ return { ...res, environment: forDisplay(res.environment) };
364
+ }
365
+ /** Apply {@link forDisplay} to a list response, for `out.print` only. */
366
+ function envListForPrint(res) {
367
+ return {
368
+ environments: res.environments.map(e => forDisplay(e)),
369
+ };
370
+ }
177
371
  export async function runEnvList(opts, deps = {}) {
178
372
  const out = makeOutput(opts.output, deps);
179
373
  if (opts.dryRun) {
@@ -184,12 +378,34 @@ export async function runEnvList(opts, deps = {}) {
184
378
  sampleEnv({ name: 'local-dev', url: 'http://127.0.0.1:5173', hasCredentials: true }),
185
379
  ],
186
380
  };
187
- out.print(sample, data => renderEnvListText(data));
381
+ out.print(envListForPrint(sample), data => renderEnvListText(data));
188
382
  return sample;
189
383
  }
190
384
  const client = makeClient(opts, deps);
191
385
  const res = await client.get(envPath(opts.projectId));
192
- out.print(res, data => renderEnvListText(data));
386
+ out.print(envListForPrint(res), data => renderEnvListText(data));
387
+ return res;
388
+ }
389
+ export async function runEnvGet(opts, deps = {}) {
390
+ const out = makeOutput(opts.output, deps);
391
+ const name = requireEnvName(opts.name, '<name>');
392
+ if (opts.dryRun) {
393
+ emitDryRunBanner(stderrOf(deps));
394
+ const sample = { environment: sampleEnv({ name }) };
395
+ out.print(envForPrint(sample), data => renderEnvText(data.environment));
396
+ return sample;
397
+ }
398
+ const client = makeClient(opts, deps);
399
+ let res;
400
+ try {
401
+ res = await client.get(envPath(opts.projectId, name));
402
+ }
403
+ catch (err) {
404
+ if (err instanceof ApiError && err.httpStatus === 404 && !err.details.resource)
405
+ throw unsupportedServer('project env get');
406
+ throw err;
407
+ }
408
+ out.print(envForPrint(res), data => renderEnvText(data.environment));
193
409
  return res;
194
410
  }
195
411
  export async function runEnvCreate(opts, deps = {}) {
@@ -200,33 +416,57 @@ export async function runEnvCreate(opts, deps = {}) {
200
416
  const localTarget = parseStoredLocalTarget(opts);
201
417
  if (localTarget === undefined && (opts.url === undefined || opts.url.trim().length === 0)) {
202
418
  throw localValidationError('--url is required: it names the address runs against this environment open. ' +
203
- 'For an app that only runs on this machine, pass --local <port> instead, then run it ' +
204
- 'with `test run <id> --env <name> --local <port>`.');
419
+ 'For an app on this machine, pass --url http://localhost:<port> or --local <port>, then run it ' +
420
+ 'with `test run <id> --env <name>`; the CLI opens a tunnel automatically.');
205
421
  }
206
- if (opts.url !== undefined) {
422
+ if (opts.url !== undefined && !localTarget) {
207
423
  assertNotLocal(opts.url, {
208
424
  field: 'url',
209
425
  helpCommand: 'testsprite project env create',
210
426
  hintContext: 'local-project-create',
211
427
  });
212
428
  }
213
- const url = localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : opts.url;
214
- if (opts.username !== undefined && opts.username.trim().length === 0) {
215
- throw localValidationError('--username must not be empty or whitespace-only');
429
+ const url = opts.url ??
430
+ (localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : undefined);
431
+ const signIn = opts.signIn === undefined ? undefined : parseSignInMode(opts.signIn, '--sign-in');
432
+ validateSignInFlags(signIn, opts, true);
433
+ if (localTarget && (signIn === 'otp' || signIn === 'manual')) {
434
+ throw signInValidationError('--sign-in otp and --sign-in manual are not available for --local environments (runs through the tunnel sign in inline); use --sign-in public or account.', 'local-environment-sign-in-unsupported');
435
+ }
436
+ const otpChannels = opts.otpChannel?.flatMap(value => value.split(',').map(channel => channel.trim()));
437
+ if (otpChannels &&
438
+ (otpChannels.length === 0 ||
439
+ otpChannels.some(channel => channel !== 'email' && channel !== 'sms'))) {
440
+ throw signInValidationError('--otp-channel accepts email and sms only.');
441
+ }
442
+ const uniqueOtpChannels = otpChannels === undefined ? undefined : [...new Set(otpChannels)];
443
+ const variables = parseVariables(opts.vars);
444
+ const passwordGiven = opts.password !== undefined || opts.passwordFile !== undefined;
445
+ if (signIn === undefined && (opts.username !== undefined) !== passwordGiven) {
446
+ // Half an account would be stored on a public environment.
447
+ throw localValidationError('--username and --password (or --password-file) go together; pass both for a test account, or neither.');
216
448
  }
217
449
  if (opts.dryRun) {
218
450
  emitDryRunBanner(stderr);
219
451
  mintIdempotencyKey('create', opts, stderr);
452
+ const hasCredentials = opts.username !== undefined &&
453
+ (opts.password !== undefined || opts.passwordFile !== undefined) &&
454
+ (signIn === undefined || signIn === 'account');
455
+ const previewMode = signIn ?? (hasCredentials ? 'account' : 'public');
220
456
  const sample = {
221
457
  environment: sampleEnv({
222
458
  name,
223
459
  url,
224
460
  isDefault: opts.setDefault === true,
225
- hasCredentials: opts.password !== undefined || opts.passwordFile !== undefined,
461
+ authMode: previewMode,
462
+ hasCredentials,
463
+ username: hasCredentials ? (opts.username ?? null) : null,
464
+ enableOtp: previewMode === 'otp',
465
+ variables: variables ?? {},
226
466
  }),
227
467
  created: true,
228
468
  };
229
- out.print(sample, data => renderEnvText(data.environment));
469
+ out.print(envForPrint(sample), data => renderEnvText(data.environment));
230
470
  return sample;
231
471
  }
232
472
  if (localTarget) {
@@ -234,7 +474,10 @@ export async function runEnvCreate(opts, deps = {}) {
234
474
  }
235
475
  // Secrets are read only on the real path — never for a dry run.
236
476
  const password = resolvePassword(opts);
237
- const body = { name, url };
477
+ const body = {
478
+ name,
479
+ url,
480
+ };
238
481
  // The marker rides with the URL: it is what authorizes storing a loopback
239
482
  // address, and it lives on the environment the server creates.
240
483
  if (localTarget)
@@ -245,13 +488,31 @@ export async function runEnvCreate(opts, deps = {}) {
245
488
  body.password = password;
246
489
  if (opts.setDefault)
247
490
  body.setDefault = true;
491
+ if (variables !== undefined)
492
+ body.variables = variables;
493
+ if (signIn !== undefined)
494
+ body.signIn = signIn;
495
+ if (signIn === 'otp')
496
+ body.otpChannels = uniqueOtpChannels ?? ['email'];
497
+ if (opts.sessionTtl !== undefined)
498
+ body.sessionReuseTtlSeconds = parseSessionTtl(opts.sessionTtl);
248
499
  const idempotencyKey = mintIdempotencyKey('create', opts, stderr);
249
500
  const client = makeClient(opts, deps);
501
+ if (variables !== undefined)
502
+ await assertEnvironmentWriteSupport(client, opts.projectId, name, '--var');
250
503
  const res = await client.post(envPath(opts.projectId), {
251
504
  body,
252
505
  headers: { 'idempotency-key': idempotencyKey },
253
506
  });
254
- out.print(res, data => renderEnvText(data.environment));
507
+ confirmRequestedEffects(res.environment, { variables }, false, {
508
+ projectId: opts.projectId,
509
+ name: res.environment?.name ?? name,
510
+ });
511
+ out.print(envForPrint(res), data => renderEnvText(data.environment));
512
+ if (opts.output === 'text' && signIn === 'manual')
513
+ stderr(`SSO selected: runs will NOT be signed in until someone logs in once in the Portal (project → Settings → Environments → ${res.environment.name} → Log in). Check with: testsprite project sign-in get ${opts.projectId} --env ${res.environment.name}`);
514
+ if (opts.output === 'text' && signIn === 'otp')
515
+ stderr(`OTP selected: see the provisioned inbox/phone with: testsprite project sign-in get ${opts.projectId} --env ${res.environment.name}`);
255
516
  return res;
256
517
  }
257
518
  export async function runEnvUpdate(opts, deps = {}) {
@@ -265,31 +526,42 @@ export async function runEnvUpdate(opts, deps = {}) {
265
526
  throw localValidationError('--url must not be empty. An environment always has an address; delete the environment ' +
266
527
  'if it is no longer used (testsprite project env delete <project-id> <name> --confirm).');
267
528
  }
268
- assertNotLocal(opts.url, {
269
- field: 'url',
270
- helpCommand: 'testsprite project env update',
271
- hintContext: 'local-project-create',
272
- });
529
+ if (!localTarget)
530
+ assertNotLocal(opts.url, {
531
+ field: 'url',
532
+ helpCommand: 'testsprite project env update',
533
+ hintContext: 'local-project-create',
534
+ });
273
535
  }
274
- const url = localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : opts.url;
536
+ const url = opts.url ?? (localTarget ? buildLocalTargetUrl(localTarget.host, localTarget.port) : undefined);
275
537
  if (opts.username !== undefined && opts.username.trim().length === 0) {
276
538
  throw localValidationError('--username must not be empty or whitespace-only');
277
539
  }
278
540
  const rename = opts.rename !== undefined ? requireEnvName(opts.rename, '--rename') : undefined;
541
+ const variables = parseVariables(opts.vars);
279
542
  const passwordSupplied = opts.password !== undefined || opts.passwordFile !== undefined;
543
+ if (opts.clearCredentials &&
544
+ (opts.username !== undefined || opts.password !== undefined || opts.passwordFile !== undefined)) {
545
+ throw localValidationError('--clear-credentials excludes --username, --password and --password-file.');
546
+ }
280
547
  const mutable = {
281
548
  url: url !== undefined,
282
549
  username: opts.username !== undefined,
283
550
  password: passwordSupplied,
284
551
  rename: rename !== undefined,
552
+ clearCredentials: opts.clearCredentials === true,
553
+ variables: variables !== undefined,
285
554
  };
286
555
  const present = Object.entries(mutable)
287
556
  .filter(([, on]) => on)
288
557
  .map(([field]) => field);
289
558
  if (present.length === 0) {
290
559
  throw localValidationError('At least one mutable flag is required: --url, --username, ' +
291
- '--password / --password-file, or --rename.');
560
+ '--password / --password-file, --clear-credentials, --rename, or --var.');
292
561
  }
562
+ // See the matching comment in `runEnvCreate`: validate credential flag
563
+ // usage before the dry-run plan is built, not just on the real path.
564
+ assertPasswordFlagsValid(opts);
293
565
  if (opts.dryRun) {
294
566
  emitDryRunBanner(stderr);
295
567
  mintIdempotencyKey('update', opts, stderr);
@@ -298,9 +570,10 @@ export async function runEnvUpdate(opts, deps = {}) {
298
570
  name: rename ?? name,
299
571
  url: url ?? 'https://staging.example.com',
300
572
  hasCredentials: passwordSupplied,
573
+ variables: variables ?? {},
301
574
  }),
302
575
  };
303
- out.print(sample, data => renderEnvText(data.environment));
576
+ out.print(envForPrint(sample), data => renderEnvText(data.environment));
304
577
  return sample;
305
578
  }
306
579
  if (localTarget) {
@@ -318,13 +591,41 @@ export async function runEnvUpdate(opts, deps = {}) {
318
591
  body.password = password;
319
592
  if (rename !== undefined)
320
593
  body.rename = rename;
594
+ if (opts.clearCredentials)
595
+ body.clearCredentials = true;
596
+ if (variables !== undefined)
597
+ body.variables = variables;
321
598
  const idempotencyKey = mintIdempotencyKey('update', opts, stderr);
322
599
  const client = makeClient(opts, deps);
600
+ if (variables !== undefined || opts.clearCredentials) {
601
+ await assertEnvironmentWriteSupport(client, opts.projectId, name, [opts.clearCredentials ? '--clear-credentials' : '', variables !== undefined ? '--var' : '']
602
+ .filter(Boolean)
603
+ .join(' / '));
604
+ }
323
605
  const res = await client.patch(envPath(opts.projectId, name), {
324
606
  body,
325
607
  headers: { 'idempotency-key': idempotencyKey },
326
608
  });
327
- out.print(res, data => renderEnvText(data.environment));
609
+ confirmRequestedEffects(res.environment, { clearCredentials: opts.clearCredentials, variables }, url !== undefined, undefined, {
610
+ projectId: opts.projectId,
611
+ name: res.environment?.name ?? name,
612
+ passwordSupplied: password !== undefined,
613
+ appliedFields: [
614
+ rename !== undefined && res.environment?.name === rename ? '--rename' : '',
615
+ url !== undefined && res.environment?.url === url ? '--url' : '',
616
+ opts.username !== undefined && res.environment?.username === opts.username
617
+ ? '--username'
618
+ : '',
619
+ opts.clearCredentials &&
620
+ res.environment?.hasCredentials === false &&
621
+ !res.environment.username
622
+ ? '--clear-credentials'
623
+ : '',
624
+ ].filter(Boolean),
625
+ });
626
+ out.print(envForPrint(res), data => renderEnvText(data.environment));
627
+ if (opts.output === 'text' && url !== undefined && res.environment.authMode === 'manual')
628
+ stderr(`This environment signs in with an SSO session captured on its previous address; if the site changed, log in again in the Portal (project → Settings → Environments → ${res.environment.name} → Log in).`);
328
629
  return res;
329
630
  }
330
631
  export async function runEnvDelete(opts, deps = {}) {
@@ -362,13 +663,13 @@ export async function runEnvSetDefault(opts, deps = {}) {
362
663
  const sample = {
363
664
  environment: sampleEnv({ name, isDefault: true }),
364
665
  };
365
- out.print(sample, data => renderEnvText(data.environment));
666
+ out.print(envForPrint(sample), data => renderEnvText(data.environment));
366
667
  return sample;
367
668
  }
368
669
  const idempotencyKey = mintIdempotencyKey('set-default', opts, stderr);
369
670
  const client = makeClient(opts, deps);
370
671
  const res = await client.post(`${envPath(opts.projectId, name)}/default`, { body: {}, headers: { 'idempotency-key': idempotencyKey } });
371
- out.print(res, data => renderEnvText(data.environment));
672
+ out.print(envForPrint(res), data => renderEnvText(data.environment));
372
673
  return res;
373
674
  }
374
675
  const IDEMPOTENCY_HELP = 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.';
@@ -378,11 +679,28 @@ const EXIT_CODE_NOTE = '\nExit codes:\n' +
378
679
  ' 4 project (or environment) not found\n' +
379
680
  ' 5 validation error\n' +
380
681
  ' 6 conflict (name already exists / deleting the default)';
682
+ const UPDATE_EXIT_CODE_NOTE = '\nExit codes:\n' +
683
+ ' 0 success\n' +
684
+ ' 3 auth error\n' +
685
+ ' 4 project (or environment) not found\n' +
686
+ ' 5 validation error\n' +
687
+ ' 6 conflict (name already exists) / precondition (credentials or --local on an SSO or OTP environment; see `project sign-in set`)';
688
+ const CREATE_EXIT_CODE_NOTE = '\nExit codes:\n' +
689
+ ' 0 success\n' +
690
+ ' 3 auth error\n' +
691
+ ' 4 project not found\n' +
692
+ ' 5 validation error\n' +
693
+ ' 6 conflict (name already exists) / precondition (OTP or SSO on a local environment)' +
694
+ '\n 7 unsupported (V2 environments or OTP/SSO in BYOC)' +
695
+ '\n 10 service unavailable' +
696
+ '\n 11 rate limited' +
697
+ '\n 13 SSO feature gated' +
698
+ '\n 14 client too old';
381
699
  export function createProjectEnvCommand(deps = {}) {
382
700
  const env = new Command('env')
383
701
  .description("Manage a project's environments — named URL + test-account bundles that `test run --env <name>` selects")
384
702
  .addHelpText('after', '\nFor an app that only runs on this machine, create or update the environment with\n' +
385
- '`--local <port>` instead of `--url`; reach it per run with `test run <id> --env <name> --local <port>`.');
703
+ '`--url http://localhost:<port>` or `--local <port>`; `test run <id> --env <name>` opens a tunnel automatically.');
386
704
  env
387
705
  .command('list <project-id>')
388
706
  .description("List a project's environments (name, default, URL, auth)." + EXIT_CODE_NOTE)
@@ -390,17 +708,29 @@ export function createProjectEnvCommand(deps = {}) {
390
708
  .action(async (projectId, _cmdOpts, command) => {
391
709
  await runEnvList({ ...resolveCommonOptions(command, deps.env), projectId }, deps);
392
710
  });
711
+ env
712
+ .command('get <project-id> <name>')
713
+ .description('Get one environment by name, including its login settings.' + EXIT_CODE_NOTE)
714
+ .addHelpText('after', GLOBAL_OPTS_HINT)
715
+ .action(async (projectId, name, _cmdOpts, command) => {
716
+ await runEnvGet({ ...resolveCommonOptions(command, deps.env), projectId, name }, deps);
717
+ });
393
718
  env
394
719
  .command('create <project-id>')
395
- .description('Create an environment (--name and one of --url / --local are required).' + EXIT_CODE_NOTE)
720
+ .description('Create an environment (--name and one of --url / --local are required).' +
721
+ CREATE_EXIT_CODE_NOTE)
396
722
  .option('--name <name>', 'environment name, unique within the project (required)')
397
- .option('--url <url>', 'address runs open (public http/https; for an app on this machine use --local)')
398
- .option('--local <port>', 'an app on this machine: stores http://<host>:<port> (1-65535; excludes --url; frontend only)')
399
- .option('--local-host <host>', 'loopback host: localhost, 127.0.0.1 (default), or ::1; requires --local')
723
+ .option('--url <url>', 'address runs open (public http/https, or a loopback http origin with an explicit port)')
724
+ .option('--local <port>', 'shorthand for --url http://localhost:<port> (1-65535; excludes --url; frontend only)')
725
+ .addOption(new Option('--local-host <host>', 'deprecated loopback host override; requires --local').hideHelp())
400
726
  .option('--skip-preflight', 'skip the local TCP listener check before creating')
401
727
  .option('--username <user>', 'test-account username the browser logs in with')
402
728
  .option('--password <pw>', 'test-account password (prefer --password-file)')
403
729
  .option('--password-file <path>', 'read the password from a file instead of the command line')
730
+ .option('--var <KEY=VALUE>', 'set a custom variable (repeatable); shown in plain text by `env get` — not for secrets, use --username/--password', collectVar, [])
731
+ .option('--sign-in <mode>', 'public, account, otp, or manual (aliases: none, credentials, sso)')
732
+ .option('--otp-channel <email,sms>', 'OTP channels: email and/or sms; repeat or comma-separate', (value, previous = []) => [...previous, value])
733
+ .option('--session-ttl <seconds|never>', 'SSO session reuse lifetime: 1–2592000 seconds or never (manual only)')
404
734
  .option('--set-default', "make this the project's default environment", false)
405
735
  .option('--idempotency-key <token>', IDEMPOTENCY_HELP)
406
736
  .addHelpText('after', GLOBAL_OPTS_HINT)
@@ -416,20 +746,26 @@ export function createProjectEnvCommand(deps = {}) {
416
746
  username: cmdOpts.username,
417
747
  password: cmdOpts.password,
418
748
  passwordFile: cmdOpts.passwordFile,
749
+ vars: cmdOpts.var,
750
+ signIn: cmdOpts.signIn,
751
+ otpChannel: cmdOpts.otpChannel,
752
+ sessionTtl: cmdOpts.sessionTtl,
419
753
  setDefault: cmdOpts.setDefault === true,
420
754
  idempotencyKey: cmdOpts.idempotencyKey,
421
755
  }, deps);
422
756
  });
423
757
  env
424
758
  .command('update <project-id> <name>')
425
- .description("Change an environment's URL, credentials or name." + EXIT_CODE_NOTE)
426
- .option('--url <url>', 'new address runs open (public http/https; for an app on this machine use --local)')
427
- .option('--local <port>', 'repoint at an app on this machine: stores http://<host>:<port> (1-65535; excludes --url)')
428
- .option('--local-host <host>', 'loopback host: localhost, 127.0.0.1 (default), or ::1; requires --local')
759
+ .description("Change an environment's URL, credentials or name." + UPDATE_EXIT_CODE_NOTE)
760
+ .option('--url <url>', 'new address runs open (public http/https, or a loopback http origin with an explicit port)')
761
+ .option('--local <port>', 'shorthand for --url http://localhost:<port> (1-65535; excludes --url)')
762
+ .addOption(new Option('--local-host <host>', 'deprecated loopback host override; requires --local').hideHelp())
429
763
  .option('--skip-preflight', 'skip the local TCP listener check before the update')
430
764
  .option('--username <user>', 'new test-account username')
431
765
  .option('--password <pw>', 'new test-account password (prefer --password-file)')
432
766
  .option('--password-file <path>', 'read the new password from a file')
767
+ .option('--clear-credentials', 'remove stored username and password; disable account login')
768
+ .option('--var <KEY=VALUE>', 'merge a custom variable (repeatable); shown in plain text by `env get` — not for secrets, use --username/--password', collectVar, [])
433
769
  .option('--rename <new-name>', 'rename the environment (runs keep referring to it by the new name)')
434
770
  .option('--idempotency-key <token>', IDEMPOTENCY_HELP)
435
771
  .addHelpText('after', GLOBAL_OPTS_HINT)
@@ -445,6 +781,8 @@ export function createProjectEnvCommand(deps = {}) {
445
781
  username: cmdOpts.username,
446
782
  password: cmdOpts.password,
447
783
  passwordFile: cmdOpts.passwordFile,
784
+ clearCredentials: cmdOpts.clearCredentials,
785
+ vars: cmdOpts.var,
448
786
  rename: cmdOpts.rename,
449
787
  idempotencyKey: cmdOpts.idempotencyKey,
450
788
  }, deps);