@testsprite/testsprite-cli 0.16.0 → 0.18.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 (206) hide show
  1. package/README.md +52 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +40 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +741 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +434 -43
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +19 -186
  19. package/dist/commands/project.js +108 -926
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +216 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1838
  25. package/dist/commands/test.js +1880 -13917
  26. package/dist/commands/testlist.d.ts +130 -5
  27. package/dist/commands/testlist.js +300 -342
  28. package/dist/commands/tunnel.d.ts +3 -3
  29. package/dist/commands/tunnel.js +23 -20
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +191 -110
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +12 -4
  45. package/dist/lib/client-factory.js +41 -30
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +75 -0
  56. package/dist/lib/conversation/api.js +151 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +29 -0
  60. package/dist/lib/conversation/context.js +82 -0
  61. package/dist/lib/conversation/environment.d.ts +16 -0
  62. package/dist/lib/conversation/environment.js +21 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +318 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +158 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +100 -0
  77. package/dist/lib/download.js +408 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +19 -30
  83. package/dist/lib/environment-tunnel.js +168 -202
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +20 -30
  91. package/dist/lib/first-suite-hint.js +57 -72
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +354 -291
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +8 -7
  107. package/dist/lib/local-target.js +14 -13
  108. package/dist/lib/output.d.ts +2 -41
  109. package/dist/lib/output.js +13 -51
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +170 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +73 -0
  127. package/dist/lib/result/evidence.js +422 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +8 -8
  151. package/dist/lib/target-url.js +14 -24
  152. package/dist/lib/telemetry.d.ts +35 -15
  153. package/dist/lib/telemetry.js +38 -9
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +8 -2
  169. package/dist/lib/tunnel-session.js +24 -11
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +52 -23
  183. package/skills/testsprite-onboard.skill.md +70 -153
  184. package/skills/testsprite-verify.codex.md +54 -58
  185. package/skills/testsprite-verify.skill.md +189 -358
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
@@ -2,7 +2,7 @@
2
2
  * `testsprite project env <verb>` — the per-project environment surface.
3
3
  *
4
4
  * An environment is a named bundle of "how to reach and log in to the app": a
5
- * URL and a login method. `test run --env <name>`
5
+ * URL and a login method. `run --env <name>`
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
  *
@@ -22,12 +22,14 @@ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../l
22
22
  import { resolveProfileName } from '../lib/config.js';
23
23
  import { ApiError, InterruptError } from '../lib/errors.js';
24
24
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
25
+ import { basicAuthToken, BASIC_AUTH_FORMAT } from '../lib/basic-auth.js';
25
26
  import { readSecretFileGuarded } from '../lib/secret-file.js';
26
27
  import { assertStoredLocalTargetListening, buildLocalTargetUrl, parseStoredLocalTarget, } from '../lib/local-target.js';
27
28
  import { assertNotLocal } from '../lib/target-url.js';
28
29
  import { renderTextTable } from '../lib/text-table.js';
29
30
  import { assertIdempotencyKey } from '../lib/validate.js';
30
31
  import { parseSessionTtl, parseSignInMode, signInValidationError, validateSignInFlags, } from './project-sign-in.js';
32
+ import { terminalSafeLine, terminalSafeWriter } from '../lib/terminal-text.js';
31
33
  // ---------------------------------------------------------------------------
32
34
  // Shared plumbing (same shape as `project.ts`; kept local so this module does
33
35
  // not import `project.ts` at runtime — that file imports this one).
@@ -56,7 +58,7 @@ function makeOutput(mode, deps) {
56
58
  return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
57
59
  }
58
60
  function stderrOf(deps) {
59
- return deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
61
+ return terminalSafeWriter(deps.stderr);
60
62
  }
61
63
  function localValidationError(message, field) {
62
64
  return ApiError.fromEnvelope({
@@ -73,12 +75,19 @@ function envPath(projectId, name) {
73
75
  const base = `/projects/${encodeURIComponent(projectId)}/env`;
74
76
  return name === undefined ? base : `${base}/${encodeURIComponent(name)}`;
75
77
  }
76
- /** Trim + reject an empty environment name; the server owns every other rule. */
78
+ /**
79
+ * Trim + reject an empty environment name and the dot names `.` and `..`
80
+ * (they would escape the route when used as a path segment, and could never
81
+ * be addressed again once created or renamed); the server owns every other rule.
82
+ */
77
83
  function requireEnvName(raw, flag) {
78
84
  const name = raw?.trim() ?? '';
79
85
  if (name.length === 0) {
80
86
  throw localValidationError(`${flag} is required and must not be empty or whitespace-only`, flag === '--rename' ? 'rename' : undefined);
81
87
  }
88
+ if (name === '.' || name === '..') {
89
+ throw localValidationError(`${flag} must not be "." or "..", which would escape the route. Use a descriptive name of 1-100 characters, unique within the project (for example "staging" or "local-dev").`, flag === '--rename' ? 'rename' : undefined);
90
+ }
82
91
  if (name.length > 100)
83
92
  throw localValidationError(`${flag} must be at most 100 characters`, flag === '--rename' ? 'rename' : undefined);
84
93
  return name;
@@ -239,6 +248,192 @@ function resolvePassword(opts) {
239
248
  }
240
249
  return undefined;
241
250
  }
251
+ // ---------------------------------------------------------------------------
252
+ // API sign-in flags (backend projects only)
253
+ // ---------------------------------------------------------------------------
254
+ const API_AUTHS = ['none', 'bearer', 'basic', 'apikey'];
255
+ /** The API sign-in flags present, by name. */
256
+ function apiAuthFlagNames(opts) {
257
+ return [
258
+ opts.auth !== undefined ? '--auth' : '',
259
+ opts.credential !== undefined || opts.credentialFile !== undefined ? '--credential' : '',
260
+ opts.header?.length ? '--header' : '',
261
+ opts.headerFile !== undefined ? '--header-file' : '',
262
+ opts.autoAuthFile !== undefined ? '--auto-auth-file' : '',
263
+ ].filter(Boolean);
264
+ }
265
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
266
+ /** One `Name: value` line, from `--header` or a line of `--header-file`. */
267
+ function parseHeaderLine(line, where) {
268
+ const colon = line.indexOf(':');
269
+ const name = colon === -1 ? '' : line.slice(0, colon).trim();
270
+ const value = colon === -1 ? '' : line.slice(colon + 1).trim();
271
+ if (!HEADER_NAME.test(name)) {
272
+ throw localValidationError(`${where} must be "Name: value", with a header name before the colon.`);
273
+ }
274
+ if (!value)
275
+ throw localValidationError(`${where}: header ${name} has no value.`);
276
+ if ([...value].some(ch => ch < ' ' || ch === '\x7f')) {
277
+ throw localValidationError(`${where}: header ${name} has a control character in its value.`);
278
+ }
279
+ return [name, value];
280
+ }
281
+ function collectHeaders(lines, where, into) {
282
+ for (const line of lines) {
283
+ const [name, value] = parseHeaderLine(line, where);
284
+ if (Object.keys(into).some(key => key.toLowerCase() === name.toLowerCase())) {
285
+ throw localValidationError(`Header ${name} is given twice; a header has one value.`);
286
+ }
287
+ into[name] = value;
288
+ }
289
+ }
290
+ /**
291
+ * Every check that needs no file read, so `--dry-run` still runs it: the
292
+ * `--header` lines parse and the flags agree with each other. A new
293
+ * environment has no stored type for a credential to attach to.
294
+ */
295
+ function assertApiAuthFlagsValid(opts, creating) {
296
+ if (opts.auth !== undefined && !API_AUTHS.includes(opts.auth)) {
297
+ throw localValidationError(`--auth must be one of: ${API_AUTHS.join(', ')}.`);
298
+ }
299
+ if (opts.credential !== undefined && opts.credentialFile !== undefined) {
300
+ throw localValidationError('--credential and --credential-file are mutually exclusive.');
301
+ }
302
+ if (opts.credential !== undefined && opts.credential.trim().length === 0) {
303
+ throw localValidationError('--credential must not be empty or whitespace-only');
304
+ }
305
+ if (opts.auth === 'basic' &&
306
+ opts.credential !== undefined &&
307
+ opts.dryRun &&
308
+ !basicAuthToken(opts.credential)) {
309
+ throw localValidationError(BASIC_AUTH_FORMAT);
310
+ }
311
+ const credentialGiven = opts.credential !== undefined || opts.credentialFile !== undefined;
312
+ if (opts.auth === 'none' && credentialGiven) {
313
+ throw localValidationError('--auth none sends no credential; drop --credential.');
314
+ }
315
+ if (creating && credentialGiven && opts.auth === undefined) {
316
+ throw localValidationError('--credential needs --auth on a new environment.');
317
+ }
318
+ if (opts.autoAuthFile !== undefined && (opts.auth !== undefined || credentialGiven)) {
319
+ throw localValidationError('--auto-auth-file is a sign-in and replaces a static credential; drop --auth and --credential.');
320
+ }
321
+ collectHeaders(opts.header ?? [], '--header', {});
322
+ }
323
+ function readJsonFlagFile(flag, path) {
324
+ const text = readSecretFileGuarded(flag, path);
325
+ try {
326
+ return JSON.parse(text);
327
+ }
328
+ catch {
329
+ throw localValidationError(`--${flag} is not valid JSON.`);
330
+ }
331
+ }
332
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
333
+ /**
334
+ * The request fields for the API sign-in flags. Reads the files, so real path
335
+ * only. Headers replace the stored set. The auto-auth file goes to the server
336
+ * as it is, switched on unless it says `"enabled": false`; the server refuses
337
+ * a field it does not know.
338
+ */
339
+ function resolveApiAuthBody(opts) {
340
+ const body = {};
341
+ if (opts.auth !== undefined)
342
+ body.auth = opts.auth;
343
+ let credential = opts.credential;
344
+ if (opts.credentialFile !== undefined) {
345
+ credential = readSecretFileGuarded('credential-file', opts.credentialFile);
346
+ if (!credential.trim())
347
+ throw localValidationError('--credential-file is empty.');
348
+ // With no --auth on an update only the server knows the stored type.
349
+ if (opts.auth && opts.auth !== 'basic')
350
+ credential = credential.trim();
351
+ }
352
+ if (credential !== undefined) {
353
+ if (opts.auth === 'basic') {
354
+ const token = basicAuthToken(credential);
355
+ if (!token)
356
+ throw localValidationError(BASIC_AUTH_FORMAT);
357
+ body.credential = token;
358
+ }
359
+ else {
360
+ body.credential = credential;
361
+ }
362
+ }
363
+ if (opts.header?.length || opts.headerFile !== undefined) {
364
+ const headers = {};
365
+ collectHeaders(opts.header ?? [], '--header', headers);
366
+ if (opts.headerFile !== undefined) {
367
+ const lines = readSecretFileGuarded('header-file', opts.headerFile)
368
+ .split(/\r?\n/)
369
+ .filter(line => line.trim().length > 0);
370
+ collectHeaders(lines, '--header-file line', headers);
371
+ }
372
+ body.extraHeaders = headers;
373
+ }
374
+ if (opts.autoAuthFile !== undefined) {
375
+ const config = readJsonFlagFile('auto-auth-file', opts.autoAuthFile);
376
+ if (!isRecord(config))
377
+ throw localValidationError('--auto-auth-file must hold a JSON object.');
378
+ body.autoAuth = { enabled: true, ...config };
379
+ }
380
+ return body;
381
+ }
382
+ /**
383
+ * What `get` will show once the flags apply, for `--dry-run`. No file is
384
+ * read, and every header is shown as set: a dry run's output may land in a
385
+ * log, and the server decides which values are secret.
386
+ */
387
+ function sampleApi(opts, url) {
388
+ if (apiAuthFlagNames(opts).length === 0)
389
+ return undefined;
390
+ const headers = {};
391
+ collectHeaders(opts.header ?? [], '--header', headers);
392
+ return {
393
+ url,
394
+ auth: opts.autoAuthFile !== undefined ? 'login' : (opts.auth ?? 'none'),
395
+ loginUrl: '',
396
+ loginMethod: '',
397
+ loginContentType: '',
398
+ loginBody: '',
399
+ username: '',
400
+ tokenPath: '',
401
+ tokenUrl: '',
402
+ clientId: '',
403
+ scope: '',
404
+ region: '',
405
+ inject: '',
406
+ headers: Object.fromEntries(Object.keys(headers).map(name => [name, null])),
407
+ credentialSet: opts.credential !== undefined || opts.credentialFile !== undefined,
408
+ passwordSet: false,
409
+ clientSecretSet: false,
410
+ refreshTokenSet: false,
411
+ authError: '',
412
+ };
413
+ }
414
+ /**
415
+ * The server answered without `api`: an older server's whitelist dropped the
416
+ * API sign-in fields silently, so nothing of them was applied.
417
+ */
418
+ function apiAuthNotApplied(projectId, name, created) {
419
+ return ApiError.fromEnvelope({
420
+ error: {
421
+ code: 'UNSUPPORTED',
422
+ message: `The server did not apply the API sign-in${created ? `; environment '${name}' was created without it` : ''}.`,
423
+ nextAction: `Upgrade the server, then run: testsprite project env update ${projectId} ${name} <the same --auth / --credential-file / --header / --auto-auth-file flags>`,
424
+ requestId: 'local',
425
+ details: {},
426
+ },
427
+ });
428
+ }
429
+ /** A save that sent a sign-in switched on but came back failing: its trial login failed. */
430
+ function warnIfSignInFailed(environment, body, projectId, stderr) {
431
+ const wanted = isRecord(body.autoAuth) && body.autoAuth.enabled === true;
432
+ if (!wanted || !environment?.api?.authError)
433
+ return;
434
+ stderr(`The sign-in was saved switched off: its trial login failed (${terminalSafeLine(environment.api.authError)}). ` +
435
+ `Fix the config and run: testsprite project env update ${projectId} ${terminalSafeLine(environment.name)} --auto-auth-file <path>`);
436
+ }
242
437
  function mintIdempotencyKey(verb, opts, stderr) {
243
438
  const key = opts.idempotencyKey ?? `cli-proj-env-${verb}-${randomUUID()}`;
244
439
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -247,14 +442,60 @@ function mintIdempotencyKey(verb, opts, stderr) {
247
442
  return key;
248
443
  }
249
444
  function describeAuth(env) {
445
+ if (env.api) {
446
+ return [
447
+ terminalSafeLine(env.api.auth),
448
+ env.api.credentialSet ? '(credential set)' : '',
449
+ env.api.authError ? '(sign-in failing)' : '',
450
+ ]
451
+ .filter(Boolean)
452
+ .join(' ');
453
+ }
250
454
  // `otp` already says the mode; repeating it as a suffix read as two settings.
251
- const parts = [env.authMode];
455
+ const parts = [terminalSafeLine(env.authMode)];
252
456
  if (env.hasCredentials)
253
457
  parts.push('(credentials set)');
254
458
  if (env.enableOtp && env.authMode !== 'otp')
255
459
  parts.push('+otp');
256
460
  return parts.join(' ');
257
461
  }
462
+ const LIST_SESSION = {
463
+ valid: 'signed in',
464
+ never: 'not logged in',
465
+ expired: 'expired',
466
+ };
467
+ /** The list's AUTH cell: the mode and, for a manual environment, whether its login is usable. */
468
+ function listAuth(env) {
469
+ if (!env.manualLogin)
470
+ return describeAuth(env);
471
+ const { session } = env.manualLogin;
472
+ return `${describeAuth(env)} (${LIST_SESSION[session] ?? session})`;
473
+ }
474
+ /** A manual environment's login, for `get`. */
475
+ function describeManualLogin(login) {
476
+ switch (login.session) {
477
+ case 'valid':
478
+ return login.expiresAt
479
+ ? `signed in until ${terminalSafeLine(login.expiresAt)}`
480
+ : 'signed in (never expires)';
481
+ case 'never':
482
+ return 'not logged in yet';
483
+ case 'expired':
484
+ return login.expiresAt ? `expired at ${terminalSafeLine(login.expiresAt)}` : 'expired';
485
+ default:
486
+ return terminalSafeLine(login.session);
487
+ }
488
+ }
489
+ /**
490
+ * "in the Portal" and where: the environment's own page when the server links it,
491
+ * else the way there.
492
+ */
493
+ function inPortal(env, step) {
494
+ const then = step ? ` → ${step}` : '';
495
+ return env.portalUrl
496
+ ? `in the Portal: ${terminalSafeLine(env.portalUrl)}${then}`
497
+ : `in the Portal (project → Settings → Environments → ${terminalSafeLine(env.name)}${then})`;
498
+ }
258
499
  const ENV_LIST_COLUMNS = [
259
500
  {
260
501
  header: 'NAME',
@@ -269,8 +510,8 @@ const ENV_LIST_COLUMNS = [
269
510
  },
270
511
  {
271
512
  header: 'AUTH',
272
- width: rows => Math.max(4, ...rows.map(env => describeAuth(env).length)),
273
- render: describeAuth,
513
+ width: rows => Math.max(4, ...rows.map(env => listAuth(env).length)),
514
+ render: listAuth,
274
515
  },
275
516
  { header: 'ACCOUNT', width: 0, render: env => env.username ?? '—' },
276
517
  ];
@@ -280,26 +521,82 @@ function renderEnvListText(r) {
280
521
  }
281
522
  return renderTextTable(r.environments, ENV_LIST_COLUMNS);
282
523
  }
524
+ const STATIC_API_AUTHS = ['bearer', 'basic', 'apikey'];
525
+ const SIGN_IN_API_AUTHS = ['login', 'refresh-token', 'cognito'];
526
+ /** The lines of the agent's `environments/<name>.md`, under `get`'s keys; an empty value is left out. */
527
+ function renderApiLines(api) {
528
+ const mark = (set) => (set ? 'set' : 'none');
529
+ const lines = [];
530
+ const add = (key, value) => {
531
+ if (value)
532
+ lines.push(`${key}:`.padEnd(13) + terminalSafeLine(value));
533
+ };
534
+ if (STATIC_API_AUTHS.includes(api.auth))
535
+ add('credential', mark(api.credentialSet));
536
+ if (api.auth === 'login') {
537
+ add('login-url', api.loginUrl);
538
+ add('login-method', api.loginMethod);
539
+ add('login-content-type', api.loginContentType);
540
+ add('login-body', api.loginBody);
541
+ add('username', api.username);
542
+ add('password', mark(api.passwordSet));
543
+ add('token-path', api.tokenPath);
544
+ }
545
+ if (api.auth === 'refresh-token')
546
+ add('token-url', api.tokenUrl);
547
+ if (api.auth === 'cognito')
548
+ add('region', api.region);
549
+ if (api.auth === 'refresh-token' || api.auth === 'cognito') {
550
+ add('client-id', api.clientId);
551
+ add('client-secret', mark(api.clientSecretSet));
552
+ add('refresh-token', mark(api.refreshTokenSet));
553
+ }
554
+ if (api.auth === 'refresh-token')
555
+ add('scope', api.scope);
556
+ if (SIGN_IN_API_AUTHS.includes(api.auth))
557
+ add('inject', api.inject);
558
+ add('auth-error', api.authError);
559
+ const names = Object.keys(api.headers).sort((a, b) => a.localeCompare(b));
560
+ lines.push(`headers: ${names.length}`);
561
+ for (const name of names) {
562
+ const value = api.headers[name];
563
+ lines.push(` ${terminalSafeLine(name)}: ${value == null ? '<set>' : terminalSafeLine(value)}`);
564
+ }
565
+ return lines;
566
+ }
283
567
  function renderEnvText(env) {
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})` : ''}`;
568
+ const login = env.manualLogin
569
+ ? describeManualLogin(env.manualLogin)
570
+ : env.enableOtp || !['public', 'none', 'account'].includes(env.authMode)
571
+ ? 'managed in Portal'
572
+ : env.authMode === 'public' || env.authMode === 'none' || !env.hasCredentials
573
+ ? 'none'
574
+ : `username+password${env.username ? ` (${terminalSafeLine(env.username)})` : ''}`;
575
+ const ttl = env.manualLogin?.sessionReuseTtlSeconds;
289
576
  const lines = [
290
- `name: ${env.name}`,
291
- `id: ${env.id}`,
577
+ `name: ${terminalSafeLine(env.name)}`,
578
+ `id: ${terminalSafeLine(env.id)}`,
292
579
  `default: ${env.isDefault ? 'yes' : 'no'}`,
293
- `url: ${env.url}`,
580
+ `url: ${terminalSafeLine(env.url)}`,
294
581
  `auth: ${describeAuth(env)}`,
295
- `account: ${env.username ?? '(none stored)'}`,
296
- `updatedAt: ${env.updatedAt}`,
297
- `login: ${login}`,
582
+ ...(env.api
583
+ ? [...renderApiLines(env.api), `updatedAt: ${terminalSafeLine(env.updatedAt)}`]
584
+ : [
585
+ `account: ${terminalSafeLine(env.username ?? '(none stored)')}`,
586
+ `updatedAt: ${terminalSafeLine(env.updatedAt)}`,
587
+ `login: ${login}`,
588
+ ...(ttl === undefined
589
+ ? []
590
+ : [
591
+ `session-ttl: ${ttl === -1 ? 'never expires' : `${terminalSafeLine(String(ttl))}s`}`,
592
+ ]),
593
+ ]),
594
+ ...(env.portalUrl ? [`portal: ${terminalSafeLine(env.portalUrl)}`] : []),
298
595
  ];
299
596
  const variables = Object.entries(env.variables ?? {}).filter(([key]) => key !== 'password');
300
597
  lines.push(`variables: ${variables.length}`);
301
598
  for (const [key, value] of variables.sort(([a], [b]) => a.localeCompare(b))) {
302
- lines.push(` ${key}=${value}`);
599
+ lines.push(` ${terminalSafeLine(key)}=${terminalSafeLine(value)}`);
303
600
  }
304
601
  return lines.join('\n');
305
602
  }
@@ -321,12 +618,11 @@ function sampleEnv(overrides) {
321
618
  /**
322
619
  * Defence-in-depth DENY-list applied to an environment ONLY at the point it
323
620
  * 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
621
+ * verbatim BY DESIGN so that success data round-trips byte-identical — see the
326
622
  * comment on `Output.print` and `redact.ts` — and this codebase treats an
327
623
  * 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
624
+ * drop (`project get`'s `defaultEnvironment`/`environmentCount`, and
625
+ * `CliProjectEnvironment.authMode` itself
330
626
  * is an open string specifically so a mode added server-side shows up
331
627
  * without a CLI release). An allow-list here would silently swallow any new
332
628
  * field the server starts returning until the CLI ships again — so this
@@ -416,8 +712,8 @@ export async function runEnvCreate(opts, deps = {}) {
416
712
  const localTarget = parseStoredLocalTarget(opts);
417
713
  if (localTarget === undefined && (opts.url === undefined || opts.url.trim().length === 0)) {
418
714
  throw localValidationError('--url is required: it names the address runs against this environment open. ' +
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.');
715
+ 'For a web app on this machine, pass --url http://localhost:<port>, then run it ' +
716
+ 'with `run <id> --env <name>`; the CLI opens a tunnel automatically.');
421
717
  }
422
718
  if (opts.url !== undefined && !localTarget) {
423
719
  assertNotLocal(opts.url, {
@@ -431,7 +727,7 @@ export async function runEnvCreate(opts, deps = {}) {
431
727
  const signIn = opts.signIn === undefined ? undefined : parseSignInMode(opts.signIn, '--sign-in');
432
728
  validateSignInFlags(signIn, opts, true);
433
729
  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');
730
+ 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
731
  }
436
732
  const otpChannels = opts.otpChannel?.flatMap(value => value.split(',').map(channel => channel.trim()));
437
733
  if (otpChannels &&
@@ -446,6 +742,7 @@ export async function runEnvCreate(opts, deps = {}) {
446
742
  // Half an account would be stored on a public environment.
447
743
  throw localValidationError('--username and --password (or --password-file) go together; pass both for a test account, or neither.');
448
744
  }
745
+ assertApiAuthFlagsValid(opts, true);
449
746
  if (opts.dryRun) {
450
747
  emitDryRunBanner(stderr);
451
748
  mintIdempotencyKey('create', opts, stderr);
@@ -463,21 +760,21 @@ export async function runEnvCreate(opts, deps = {}) {
463
760
  username: hasCredentials ? (opts.username ?? null) : null,
464
761
  enableOtp: previewMode === 'otp',
465
762
  variables: variables ?? {},
763
+ api: sampleApi(opts, url),
466
764
  }),
467
765
  created: true,
468
766
  };
469
767
  out.print(envForPrint(sample), data => renderEnvText(data.environment));
470
768
  return sample;
471
769
  }
770
+ const client = makeClient(opts, deps);
472
771
  if (localTarget) {
772
+ await assertLocalEnvironmentAllowed(client, opts);
473
773
  await assertStoredLocalTargetListening(localTarget, opts, deps.localPortProbeDeps);
474
774
  }
475
775
  // Secrets are read only on the real path — never for a dry run.
476
776
  const password = resolvePassword(opts);
477
- const body = {
478
- name,
479
- url,
480
- };
777
+ const body = { name, url };
481
778
  // The marker rides with the URL: it is what authorizes storing a loopback
482
779
  // address, and it lives on the environment the server creates.
483
780
  if (localTarget)
@@ -496,8 +793,8 @@ export async function runEnvCreate(opts, deps = {}) {
496
793
  body.otpChannels = uniqueOtpChannels ?? ['email'];
497
794
  if (opts.sessionTtl !== undefined)
498
795
  body.sessionReuseTtlSeconds = parseSessionTtl(opts.sessionTtl);
796
+ Object.assign(body, resolveApiAuthBody(opts));
499
797
  const idempotencyKey = mintIdempotencyKey('create', opts, stderr);
500
- const client = makeClient(opts, deps);
501
798
  if (variables !== undefined)
502
799
  await assertEnvironmentWriteSupport(client, opts.projectId, name, '--var');
503
800
  const res = await client.post(envPath(opts.projectId), {
@@ -508,13 +805,54 @@ export async function runEnvCreate(opts, deps = {}) {
508
805
  projectId: opts.projectId,
509
806
  name: res.environment?.name ?? name,
510
807
  });
808
+ if (apiAuthFlagNames(opts).length > 0 && res.environment?.api === undefined) {
809
+ throw apiAuthNotApplied(opts.projectId, res.environment?.name ?? name, true);
810
+ }
811
+ if (opts.output === 'text')
812
+ warnIfSignInFailed(res.environment, body, opts.projectId, stderr);
511
813
  out.print(envForPrint(res), data => renderEnvText(data.environment));
512
814
  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}`);
815
+ stderr(`SSO selected: runs will NOT be signed in until someone logs in once ${inPortal(res.environment, 'Log in')}.`);
514
816
  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}`);
817
+ stderr(`OTP selected: see the provisioned inbox/phone ${inPortal(res.environment)}.`);
818
+ // Said once, when the address is stored: the agent can only open an app on
819
+ // this machine through a tunnel the user starts, and `plan` has no flag for it.
820
+ if (opts.output === 'text' && localTarget)
821
+ stderr(LOCAL_ENVIRONMENT_HINT);
516
822
  return res;
517
823
  }
824
+ const LOCAL_ENVIRONMENT_HINT = 'This app is on your machine: before `testsprite plan`, run `testsprite tunnel start` in another terminal so the agent can open it (`testsprite run` opens its own tunnel).';
825
+ /**
826
+ * A local environment is a web app the tunnel reaches; a backend project's
827
+ * tests never use one. Asked before the port check, so the answer does not
828
+ * depend on whether anything listens there. A key that cannot read the
829
+ * project keeps the old path: the server refuses it too.
830
+ */
831
+ async function assertLocalEnvironmentAllowed(client, opts) {
832
+ let type;
833
+ try {
834
+ ({ type } = await client.get(`/projects/${encodeURIComponent(opts.projectId)}`));
835
+ }
836
+ catch (err) {
837
+ if (err instanceof ApiError && err.httpStatus === 403)
838
+ return;
839
+ throw err;
840
+ }
841
+ if (type !== 'backend')
842
+ return;
843
+ throw ApiError.fromEnvelope({
844
+ error: {
845
+ code: 'VALIDATION_ERROR',
846
+ message: 'Invalid request.',
847
+ nextAction: "A backend project's environment must point at a publicly deployed API; local environments are for frontend projects only.",
848
+ requestId: 'local',
849
+ details: {
850
+ field: opts.local !== undefined ? 'local' : 'url',
851
+ reason: 'backend-local-environment',
852
+ },
853
+ },
854
+ });
855
+ }
518
856
  export async function runEnvUpdate(opts, deps = {}) {
519
857
  const out = makeOutput(opts.output, deps);
520
858
  const stderr = stderrOf(deps);
@@ -551,17 +889,20 @@ export async function runEnvUpdate(opts, deps = {}) {
551
889
  rename: rename !== undefined,
552
890
  clearCredentials: opts.clearCredentials === true,
553
891
  variables: variables !== undefined,
892
+ api: apiAuthFlagNames(opts).length > 0,
554
893
  };
555
894
  const present = Object.entries(mutable)
556
895
  .filter(([, on]) => on)
557
896
  .map(([field]) => field);
558
897
  if (present.length === 0) {
559
898
  throw localValidationError('At least one mutable flag is required: --url, --username, ' +
560
- '--password / --password-file, --clear-credentials, --rename, or --var.');
899
+ '--password / --password-file, --clear-credentials, --rename, --var, ' +
900
+ '--auth, --credential / --credential-file, --header / --header-file, or --auto-auth-file.');
561
901
  }
562
902
  // See the matching comment in `runEnvCreate`: validate credential flag
563
903
  // usage before the dry-run plan is built, not just on the real path.
564
904
  assertPasswordFlagsValid(opts);
905
+ assertApiAuthFlagsValid(opts, false);
565
906
  if (opts.dryRun) {
566
907
  emitDryRunBanner(stderr);
567
908
  mintIdempotencyKey('update', opts, stderr);
@@ -571,12 +912,15 @@ export async function runEnvUpdate(opts, deps = {}) {
571
912
  url: url ?? 'https://staging.example.com',
572
913
  hasCredentials: passwordSupplied,
573
914
  variables: variables ?? {},
915
+ api: sampleApi(opts, url ?? 'https://staging.example.com'),
574
916
  }),
575
917
  };
576
918
  out.print(envForPrint(sample), data => renderEnvText(data.environment));
577
919
  return sample;
578
920
  }
921
+ const client = makeClient(opts, deps);
579
922
  if (localTarget) {
923
+ await assertLocalEnvironmentAllowed(client, opts);
580
924
  await assertStoredLocalTargetListening(localTarget, opts, deps.localPortProbeDeps);
581
925
  }
582
926
  const password = resolvePassword(opts);
@@ -595,8 +939,8 @@ export async function runEnvUpdate(opts, deps = {}) {
595
939
  body.clearCredentials = true;
596
940
  if (variables !== undefined)
597
941
  body.variables = variables;
942
+ Object.assign(body, resolveApiAuthBody(opts));
598
943
  const idempotencyKey = mintIdempotencyKey('update', opts, stderr);
599
- const client = makeClient(opts, deps);
600
944
  if (variables !== undefined || opts.clearCredentials) {
601
945
  await assertEnvironmentWriteSupport(client, opts.projectId, name, [opts.clearCredentials ? '--clear-credentials' : '', variables !== undefined ? '--var' : '']
602
946
  .filter(Boolean)
@@ -623,9 +967,16 @@ export async function runEnvUpdate(opts, deps = {}) {
623
967
  : '',
624
968
  ].filter(Boolean),
625
969
  });
970
+ if (apiAuthFlagNames(opts).length > 0 && res.environment?.api === undefined) {
971
+ throw apiAuthNotApplied(opts.projectId, res.environment?.name ?? name, false);
972
+ }
626
973
  out.print(envForPrint(res), data => renderEnvText(data.environment));
974
+ if (opts.output === 'text')
975
+ warnIfSignInFailed(res.environment, body, opts.projectId, stderr);
627
976
  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).`);
977
+ stderr(`This environment signs in with an SSO session captured on its previous address; if the site changed, log in again ${inPortal(res.environment, 'Log in')}.`);
978
+ if (opts.output === 'text' && localTarget)
979
+ stderr(LOCAL_ENVIRONMENT_HINT);
629
980
  return res;
630
981
  }
631
982
  export async function runEnvDelete(opts, deps = {}) {
@@ -649,7 +1000,7 @@ export async function runEnvDelete(opts, deps = {}) {
649
1000
  const res = await client.delete(envPath(opts.projectId, name), {
650
1001
  headers: { 'idempotency-key': idempotencyKey },
651
1002
  });
652
- out.print(res, data => `deleted: ${data.name}`);
1003
+ out.print(res, data => `deleted: ${terminalSafeLine(data.name)}`);
653
1004
  return res;
654
1005
  }
655
1006
  export async function runEnvSetDefault(opts, deps = {}) {
@@ -673,6 +1024,20 @@ export async function runEnvSetDefault(opts, deps = {}) {
673
1024
  return res;
674
1025
  }
675
1026
  const IDEMPOTENCY_HELP = 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.';
1027
+ const API_AUTH_HELP = '\nAPI sign-in (backend projects): what runs sign in to the API with, kept on the environment as the\n' +
1028
+ 'project\'s agent reads it. --auth none|bearer|basic|apikey with --credential-file; --header "Name: value"\n' +
1029
+ '(repeatable) and --header-file (one "Name: value" per line, for secret values) replace the extra\n' +
1030
+ 'headers every request carries; --auto-auth-file holds a sign-in that refreshes the credential, e.g.\n' +
1031
+ ' {"method": "password", "inject": "bearer", "loginUrl": "https://api.example.com/login",\n' +
1032
+ ' "loginBodyTemplate": "{\\"email\\":\\"{{username}}\\",\\"password\\":\\"{{password}}\\"}",\n' +
1033
+ ' "username": "qa@example.com", "password": "<secret>", "tokenPath": "$.access_token"}\n' +
1034
+ 'method: password | refresh_token (tokenEndpoint, clientId, refreshToken) | aws_cognito_refresh (region,\n' +
1035
+ 'clientId, refreshToken); inject: bearer | header | cookie (header and cookie take injectKey). The file is\n' +
1036
+ 'sent as it is: the server refuses a field it does not know, a secret left out keeps its stored value,\n' +
1037
+ '"enabled": false saves it switched off. Saving a sign-in runs a trial login and needs a plan with\n' +
1038
+ 'advanced environment settings; --auth replaces a sign-in with a static credential. Which endpoint\n' +
1039
+ 'needs which header is decided in the Portal.\n' +
1040
+ 'For Basic auth, supply username:password or its base64 encoding.\n';
676
1041
  const LIST_EXIT_CODE_NOTE = '\nExit codes:\n' +
677
1042
  ' 0 success\n' +
678
1043
  ' 3 auth error\n' +
@@ -699,14 +1064,14 @@ const UPDATE_EXIT_CODE_NOTE = '\nExit codes:\n' +
699
1064
  ' 3 auth error\n' +
700
1065
  ' 4 project (or environment) not found\n' +
701
1066
  ' 5 validation error\n' +
702
- ' 6 conflict (name already exists) / precondition (credentials or --local on an SSO or OTP environment; see `project sign-in set`)';
1067
+ ' 6 conflict (name already exists) / precondition (credentials or a local address on an SSO or OTP environment; change its sign-in in the Portal)';
703
1068
  const CREATE_EXIT_CODE_NOTE = '\nExit codes:\n' +
704
1069
  ' 0 success\n' +
705
1070
  ' 3 auth error\n' +
706
1071
  ' 4 project not found\n' +
707
1072
  ' 5 validation error\n' +
708
1073
  ' 6 conflict (name already exists) / precondition (OTP or SSO on a local environment)' +
709
- '\n 7 unsupported (V2 environments or OTP/SSO in BYOC)' +
1074
+ '\n 7 unsupported (OTP/SSO in BYOC)' +
710
1075
  '\n 10 service unavailable' +
711
1076
  '\n 11 rate limited' +
712
1077
  '\n 13 SSO feature gated' +
@@ -714,9 +1079,9 @@ const CREATE_EXIT_CODE_NOTE = '\nExit codes:\n' +
714
1079
  export function createProjectEnvCommand(deps = {}) {
715
1080
  const env = new Command('env')
716
1081
  .summary("Manage a project's environments")
717
- .description("Manage a project's environments — named URL + test-account bundles that `test run --env <name>` selects")
718
- .addHelpText('after', '\nFor an app that only runs on this machine, create or update the environment with\n' +
719
- '`--url http://localhost:<port>` or `--local <port>`; `test run <id> --env <name>` opens a tunnel automatically.');
1082
+ .description("Manage a project's environments — named URL + test-account bundles that `run --env <name>` selects")
1083
+ .addHelpText('after', '\nFor a web app that only runs on this machine (frontend projects), create or update the environment\n' +
1084
+ 'with `--url http://localhost:<port>`; `run <id> --env <name>` opens a tunnel automatically.');
720
1085
  env
721
1086
  .command('list <project-id>')
722
1087
  .summary("List a project's environments")
@@ -736,7 +1101,7 @@ export function createProjectEnvCommand(deps = {}) {
736
1101
  env
737
1102
  .command('create <project-id>')
738
1103
  .summary('Create an environment')
739
- .description('Create an environment (--name and one of --url / --local are required).' +
1104
+ .description('Create an environment (--name and --url are required; --local <port> is shorthand for --url http://localhost:<port>).' +
740
1105
  CREATE_EXIT_CODE_NOTE)
741
1106
  .option('--name <name>', 'environment name, unique within the project (required)')
742
1107
  .option('--url <url>', 'address runs open (public http/https, or a loopback http origin with an explicit port)')
@@ -750,8 +1115,15 @@ export function createProjectEnvCommand(deps = {}) {
750
1115
  .option('--sign-in <mode>', 'public, account, otp, or manual (aliases: none, credentials, sso). manual: log in once in the Portal, runs reuse that session (not signed in until then). otp and manual: not for local environments')
751
1116
  .option('--otp-channel <email,sms>', 'OTP channels: email and/or sms; repeat or comma-separate (default: email)', (value, previous = []) => [...previous, value])
752
1117
  .option('--session-ttl <seconds|never>', 'SSO session reuse lifetime: 1–2592000 seconds or never (manual only)')
1118
+ .option('--auth <type>', 'backend projects: how runs sign in to the API — none, bearer, basic or apikey; replaces a sign-in')
1119
+ .option('--credential <value>', 'backend projects: static credential value (prefer --credential-file, exclusive)')
1120
+ .option('--credential-file <path>', 'backend projects: read the static credential from a file')
1121
+ .option('--header <"Name: value">', 'backend projects: an extra request header (repeatable; replaces the stored set)', (value, previous = []) => [...previous, value])
1122
+ .option('--header-file <path>', 'backend projects: extra request headers, one "Name: value" per line (for secret values)')
1123
+ .option('--auto-auth-file <path>', 'backend projects: JSON sign-in that refreshes the credential; replaces a static one (see below)')
753
1124
  .option('--set-default', "make this the project's default environment", false)
754
1125
  .option('--idempotency-key <token>', IDEMPOTENCY_HELP)
1126
+ .addHelpText('after', API_AUTH_HELP)
755
1127
  .addHelpText('after', GLOBAL_OPTS_HINT)
756
1128
  .action(async (projectId, cmdOpts, command) => {
757
1129
  await runEnvCreate({
@@ -769,6 +1141,12 @@ export function createProjectEnvCommand(deps = {}) {
769
1141
  signIn: cmdOpts.signIn,
770
1142
  otpChannel: cmdOpts.otpChannel,
771
1143
  sessionTtl: cmdOpts.sessionTtl,
1144
+ auth: cmdOpts.auth,
1145
+ credential: cmdOpts.credential,
1146
+ credentialFile: cmdOpts.credentialFile,
1147
+ header: cmdOpts.header,
1148
+ headerFile: cmdOpts.headerFile,
1149
+ autoAuthFile: cmdOpts.autoAuthFile,
772
1150
  setDefault: cmdOpts.setDefault === true,
773
1151
  idempotencyKey: cmdOpts.idempotencyKey,
774
1152
  }, deps);
@@ -776,7 +1154,7 @@ export function createProjectEnvCommand(deps = {}) {
776
1154
  env
777
1155
  .command('update <project-id> <name>')
778
1156
  .summary('Change an environment')
779
- .description("Change an environment's URL, credentials, custom variables or name (sign-in mode: `project sign-in set`)." +
1157
+ .description("Change an environment's URL, credentials, custom variables, name or (backend projects) API sign-in; a frontend sign-in mode changes in the Portal." +
780
1158
  UPDATE_EXIT_CODE_NOTE)
781
1159
  .option('--url <url>', 'new address runs open (public http/https, or a loopback http origin with an explicit port)')
782
1160
  .option('--local <port>', 'shorthand for --url http://localhost:<port> (1-65535; excludes --url)')
@@ -788,7 +1166,14 @@ export function createProjectEnvCommand(deps = {}) {
788
1166
  .option('--clear-credentials', 'remove stored username and password; disable account login')
789
1167
  .option('--var <KEY=VALUE>', 'merge a custom variable (repeatable; max 50, 4096 bytes each, key [A-Za-z_][A-Za-z0-9_]*, reserved names like url/username/password rejected); shown in plain text by `env get`, not for secrets', collectVar, [])
790
1168
  .option('--rename <new-name>', 'rename the environment (runs keep referring to it by the new name)')
1169
+ .option('--auth <type>', 'backend projects: how runs sign in to the API — none, bearer, basic or apikey; replaces a sign-in')
1170
+ .option('--credential <value>', 'backend projects: static credential value (prefer --credential-file, exclusive)')
1171
+ .option('--credential-file <path>', 'backend projects: read the static credential from a file')
1172
+ .option('--header <"Name: value">', 'backend projects: an extra request header (repeatable; replaces the stored set)', (value, previous = []) => [...previous, value])
1173
+ .option('--header-file <path>', 'backend projects: extra request headers, one "Name: value" per line (for secret values)')
1174
+ .option('--auto-auth-file <path>', 'backend projects: JSON sign-in that refreshes the credential; replaces a static one (see below)')
791
1175
  .option('--idempotency-key <token>', IDEMPOTENCY_HELP)
1176
+ .addHelpText('after', API_AUTH_HELP)
792
1177
  .addHelpText('after', GLOBAL_OPTS_HINT)
793
1178
  .action(async (projectId, name, cmdOpts, command) => {
794
1179
  await runEnvUpdate({
@@ -805,6 +1190,12 @@ export function createProjectEnvCommand(deps = {}) {
805
1190
  clearCredentials: cmdOpts.clearCredentials,
806
1191
  vars: cmdOpts.var,
807
1192
  rename: cmdOpts.rename,
1193
+ auth: cmdOpts.auth,
1194
+ credential: cmdOpts.credential,
1195
+ credentialFile: cmdOpts.credentialFile,
1196
+ header: cmdOpts.header,
1197
+ headerFile: cmdOpts.headerFile,
1198
+ autoAuthFile: cmdOpts.autoAuthFile,
808
1199
  idempotencyKey: cmdOpts.idempotencyKey,
809
1200
  }, deps);
810
1201
  });