@stewardhq/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 (3) hide show
  1. package/README.md +17 -5
  2. package/dist/bin.js +714 -375
  3. package/package.json +5 -5
package/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { userInfo } from "node:os";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { setTimeout } from "node:timers/promises";
5
- import { ACCOUNT_INCLUDES, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CodeSchema, CreditAdjustmentInputSchema, DateTimeSchema, DiscountCreateInputSchema, DiscountUpdateInputSchema, DunningPolicySchema, EmailSmtpVerifyInputSchema, EventsIngestInputSchema, FxRateSchema, GRANT_LIST_DEFAULT_LIMIT, GRANT_LIST_MAX_LIMIT, GrantListSubscriptionFilterSchema, INVOICE_LINE_TEXTS, IdSchema, InvoiceIssueInputSchema, InvoicePaymentStatusSchema, InvoiceStatusSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, SALES_REPORT_MAX_MONTHS, SmtpUrlSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, TAX_PROVIDERS, TAX_THRESHOLD_PERIODS, TAX_THRESHOLD_SCOPES, TaxThresholdInputSchema, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf, taxIdTypeOf } from "@stewardhq/sdk";
5
+ import { ACCOUNT_INCLUDES, ACCOUNT_LIST_QUERY_MAX, ADMIN_LIST_DEFAULT_LIMIT, ADMIN_LIST_MAX_LIMIT, AUDIT_LIST_FILTER_MAX, AccountListDeletedFilterSchema, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, ApiKeyPrefixSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CodeSchema, CreditAdjustmentInputSchema, DateTimeSchema, DiscountCreateInputSchema, DiscountUpdateInputSchema, DunningPolicySchema, EmailMessageStatusSchema, EmailSmtpVerifyInputSchema, EmailTemplateSchema, EventIdSchema, EventsIngestInputSchema, ExternalRefSchema, FxRateSchema, GRANT_LIST_DEFAULT_LIMIT, GRANT_LIST_MAX_LIMIT, GrantListSubscriptionFilterSchema, INVOICE_LINE_TEXTS, IdSchema, InvoiceIssueInputSchema, InvoicePaymentStatusSchema, InvoiceStatusSchema, METER_CHARGE_MODES, PaymentListDisputedFilterSchema, PaymentMethodSchema, ProductSettingsPatchSchema, RepriceInputSchema, SALES_REPORT_MAX_MONTHS, SmtpUrlSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, SubscriptionStatusSchema, TAX_PROVIDERS, TAX_THRESHOLD_PERIODS, TAX_THRESHOLD_SCOPES, TaxThresholdInputSchema, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, WebhookEventDeliveryFilterSchema, catalogPriceChangeCount as priceChangeCount, createSteward, diffCatalogSync, generateApiKeyToken, generateWebhookSecret, meteredRateText, plainDecimalOf, taxIdTypeOf } from "@stewardhq/sdk";
6
6
  import { parseArgs } from "node:util";
7
7
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
8
8
  import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
@@ -117,11 +117,6 @@ function definesMeters(input) {
117
117
  function definesUnlistedPlans(input) {
118
118
  return input.plans.some((plan) => plan.listed === false);
119
119
  }
120
- const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
121
- /** JSON with sorted object keys: key order does not count as a change. */
122
- const canonical = (value) => JSON.stringify(value ?? null, (_key, v) => isPlainObject(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v);
123
- const priceKey = (p) => `${p.planCode}/${p.interval}/${p.intervalCount}/${p.currency}`;
124
- const priceLabel = (p) => `${p.planCode} ${p.intervalCount > 1 ? `${p.intervalCount}×` : ""}${p.interval}`;
125
120
  /** `TRY 1,250.00`; minor units with the currency's own fraction digits (unknown currency: minor units). */
126
121
  function formatMinor(amountMinor, currency) {
127
122
  try {
@@ -139,147 +134,12 @@ function formatMinor(amountMinor, currency) {
139
134
  const percent$1 = (bps) => `${bps / 100}%`;
140
135
  /** Units as exact text with grouping (`2,000,000`, `0.25`). */
141
136
  const unitsText = (value) => new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
142
- const meteredKey = (p) => `${p.planCode}/${p.meter}/${p.currency}`;
143
- const meteredLabel = (p) => `${p.planCode} ${p.meter}`;
144
- /** `TRY 12.50 per 1,000 units` (+ `, cap TRY 500.00`). */
145
- function meteredRate(p) {
146
- const cap = p.capMinor === void 0 || p.capMinor === null ? "" : `, cap ${formatMinor(p.capMinor, p.currency)}`;
147
- return `${formatMinor(p.amountMinor, p.currency)} per ${unitsText(p.perUnits)} unit${p.perUnits === 1 ? "" : "s"}${cap}`;
148
- }
149
- function creditTerms(properties) {
150
- const parsed = MeterCreditPropertiesSchema.safeParse(properties);
151
- return parsed.success ? {
152
- meter: parsed.data.meter,
153
- units: parsed.data.units,
154
- rolloverCapUnits: parsed.data.rolloverCapUnits ?? null
155
- } : null;
156
- }
157
- function diffMeters(current, input) {
158
- const before = current?.meters ?? {};
159
- const meters = {
160
- added: [],
161
- changed: [],
162
- ruleChanged: [],
163
- archived: []
164
- };
165
- for (const [code, next] of Object.entries(input.meters)) {
166
- const old = Object.hasOwn(before, code) ? before[code] : void 0;
167
- if (old === void 0) {
168
- meters.added.push(code);
169
- continue;
170
- }
171
- if (canonical(old.filter) !== canonical(next.filter) || canonical(old.aggregation) !== canonical(next.aggregation)) meters.ruleChanged.push(code);
172
- if (canonical(old.label) !== canonical(next.label) || canonical(old.unitLabel) !== canonical(next.unitLabel) || (old.displayPer ?? null) !== (next.displayPer ?? null) || old.lowAt !== next.lowAt) meters.changed.push(code);
173
- }
174
- meters.archived = Object.keys(before).filter((code) => !Object.hasOwn(input.meters, code));
175
- return meters;
176
- }
177
- function meteredTerms(p) {
178
- return {
179
- amountMinor: p.amountMinor,
180
- perUnits: p.perUnits,
181
- taxInclusive: p.taxInclusive,
182
- taxRateBps: p.taxRateBps,
183
- capMinor: p.capMinor ?? null
184
- };
185
- }
186
- function diffMeteredPrices(current, input) {
187
- const before = new Map((current?.meteredPrices ?? []).map((p) => [meteredKey(p), p]));
188
- const inputKeys = new Set(input.meteredPrices.map(meteredKey));
189
- const out = {
190
- added: [],
191
- deactivated: [],
192
- changed: []
193
- };
194
- for (const price of input.meteredPrices) {
195
- const old = before.get(meteredKey(price));
196
- if (old === void 0) out.added.push(`${meteredLabel(price)} ${meteredRate(price)}`);
197
- else if (canonical(meteredTerms(old)) !== canonical(meteredTerms(price))) out.changed.push({
198
- label: meteredLabel(price),
199
- id: old.id,
200
- currency: price.currency,
201
- from: meteredTerms(old),
202
- to: meteredTerms(price)
203
- });
204
- }
205
- for (const [key, price] of before) if (!inputKeys.has(key)) out.deactivated.push(`${meteredLabel(price)} ${meteredRate(price)}`);
206
- return out;
207
- }
137
+ const FORMAT = {
138
+ money: formatMinor,
139
+ units: unitsText
140
+ };
208
141
  function diffCatalog(current, file) {
209
- const input = CatalogSyncInputSchema.parse(file);
210
- const currentBenefits = current?.benefits ?? {};
211
- const benefits = {
212
- added: Object.keys(input.benefits).filter((code) => !Object.hasOwn(currentBenefits, code)),
213
- changed: Object.entries(input.benefits).filter(([code]) => Object.hasOwn(currentBenefits, code)).filter(([code, next]) => {
214
- const before = currentBenefits[code];
215
- return before.type !== next.type || canonical(before.properties) !== canonical(next.properties) || canonical(before.description) !== canonical(next.description);
216
- }).map(([code]) => code),
217
- archived: Object.keys(currentBenefits).filter((code) => !Object.hasOwn(input.benefits, code))
218
- };
219
- const currentPlans = new Map((current?.plans ?? []).map((plan) => [plan.code, plan.benefits ?? []]));
220
- const planBenefits = [];
221
- for (const plan of input.plans) {
222
- const before = currentPlans.get(plan.code) ?? [];
223
- const added = plan.benefits.filter((code) => !before.includes(code));
224
- const removed = before.filter((code) => !plan.benefits.includes(code));
225
- if (added.length > 0 || removed.length > 0) planBenefits.push({
226
- plan: plan.code,
227
- added,
228
- removed
229
- });
230
- }
231
- const currentListing = new Map((current?.plans ?? []).map((plan) => [plan.code, plan.listed ?? true]));
232
- const planListing = input.plans.filter((plan) => (currentListing.get(plan.code) ?? true) !== plan.listed).map((plan) => ({
233
- plan: plan.code,
234
- listed: plan.listed
235
- }));
236
- const currentPrices = new Map((current?.prices ?? []).map((price) => [priceKey(price), price]));
237
- const inputKeys = new Set(input.prices.map(priceKey));
238
- const prices = {
239
- added: [],
240
- deactivated: [],
241
- changed: []
242
- };
243
- for (const price of input.prices) {
244
- const before = currentPrices.get(priceKey(price));
245
- if (before === void 0) prices.added.push(`${priceLabel(price)} ${formatMinor(price.amountMinor, price.currency)}`);
246
- else if (before.amountMinor !== price.amountMinor || before.taxInclusive !== price.taxInclusive || before.taxRateBps !== price.taxRateBps) {
247
- const terms = ({ amountMinor, taxInclusive, taxRateBps }) => ({
248
- amountMinor,
249
- taxInclusive,
250
- taxRateBps
251
- });
252
- prices.changed.push({
253
- label: priceLabel(price),
254
- id: before.id,
255
- currency: price.currency,
256
- from: terms(before),
257
- to: terms(price)
258
- });
259
- }
260
- }
261
- for (const [key, price] of currentPrices) if (!inputKeys.has(key)) prices.deactivated.push(`${priceLabel(price)} ${formatMinor(price.amountMinor, price.currency)}`);
262
- const credits = [];
263
- for (const [code, next] of Object.entries(input.benefits)) {
264
- const old = Object.hasOwn(currentBenefits, code) ? currentBenefits[code] : void 0;
265
- if (old === void 0 || old.type !== "meter_credit" || next.type !== "meter_credit") continue;
266
- const from = creditTerms(old.properties);
267
- const to = creditTerms(next.properties);
268
- if (from !== null && to !== null && canonical(from) !== canonical(to)) credits.push({
269
- code,
270
- from,
271
- to
272
- });
273
- }
274
- return {
275
- benefits,
276
- planBenefits,
277
- planListing,
278
- prices,
279
- meters: diffMeters(current, input),
280
- credits,
281
- meteredPrices: diffMeteredPrices(current, input)
282
- };
142
+ return diffCatalogSync(current, CatalogSyncInputSchema.parse(file), FORMAT);
283
143
  }
284
144
  function describePriceChange({ label, currency, from, to }) {
285
145
  const parts = [];
@@ -290,15 +150,15 @@ function describePriceChange({ label, currency, from, to }) {
290
150
  }
291
151
  function describeMeteredPriceChange({ label, currency, from, to }) {
292
152
  const parts = [];
293
- if (from.amountMinor !== to.amountMinor || from.perUnits !== to.perUnits) parts.push(`${meteredRate({
153
+ if (from.amountMinor !== to.amountMinor || from.perUnits !== to.perUnits) parts.push(`${meteredRateText({
294
154
  currency,
295
155
  amountMinor: from.amountMinor,
296
156
  perUnits: from.perUnits
297
- })} → ${meteredRate({
157
+ }, FORMAT)} → ${meteredRateText({
298
158
  currency,
299
159
  amountMinor: to.amountMinor,
300
160
  perUnits: to.perUnits
301
- })}`);
161
+ }, FORMAT)}`);
302
162
  if (from.capMinor !== to.capMinor) {
303
163
  const cap = (minor) => minor === null ? "none" : formatMinor(minor, currency);
304
164
  parts.push(`cap ${cap(from.capMinor)} → ${cap(to.capMinor)}`);
@@ -353,10 +213,6 @@ function describeDiff(diff) {
353
213
  }
354
214
  return lines.length > 0 ? ["changes against the current catalog:", ...lines] : [];
355
215
  }
356
- /** Price changes the operator confirms before the push: base prices and metered prices changed in place. */
357
- function priceChangeCount(diff) {
358
- return diff.prices.changed.length + diff.meteredPrices.changed.length;
359
- }
360
216
  // src/dotenv.ts
361
217
  const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
362
218
  function unquote(rest) {
@@ -522,9 +378,240 @@ function describeStewardError(error, target) {
522
378
  }
523
379
  return `steward response does not match the contract${where}: ${error.code} (HTTP ${error.httpStatus}) — the CLI and steward versions may be incompatible${request}`;
524
380
  }
381
+ // src/secret-file.ts
382
+ async function withSecretFile(cwd, out, secret, options, action) {
383
+ const target = resolve(cwd, out);
384
+ try {
385
+ if ((await lstat(target)).isDirectory()) throw new CliError(`--out is a folder: ${out}`);
386
+ if (!options.force) throw new CliError(`${out} already exists; use --force to overwrite it (no request was sent)`);
387
+ } catch (error) {
388
+ if (error instanceof CliError) throw error;
389
+ if (errnoCode(error) !== "ENOENT") throw error;
390
+ }
391
+ const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
392
+ try {
393
+ await writeFile(temp, secret, {
394
+ mode: 384,
395
+ flag: "wx"
396
+ });
397
+ } catch (error) {
398
+ const code = errnoCode(error);
399
+ if (code === "ENOENT") throw new CliError(`--out folder does not exist: ${relative(cwd, dirname(target)) || "."}`);
400
+ throw new CliError(`could not write the secret file (${code ?? "error"}): ${out} (no request was sent)`);
401
+ }
402
+ let value;
403
+ try {
404
+ value = await action();
405
+ } catch (error) {
406
+ await unlink(temp).catch(() => {});
407
+ throw error;
408
+ }
409
+ try {
410
+ if (options.force) await rename(temp, target);
411
+ else {
412
+ await link(temp, target);
413
+ await unlink(temp).catch(() => {});
414
+ }
415
+ return {
416
+ value,
417
+ path: out,
418
+ fallback: false
419
+ };
420
+ } catch {
421
+ return {
422
+ value,
423
+ path: relative(cwd, temp),
424
+ fallback: true
425
+ };
426
+ }
427
+ }
428
+ // src/commands/endpoints.ts
429
+ const ENDPOINTS_USAGE = `Usage:
430
+ steward endpoints list [--json]
431
+ steward endpoints add --url <url> --out <file> [--event-types <a,b>] [--description <text>] [--force]
432
+ steward endpoints rotate <id> --out <file> [--force]
433
+ steward endpoints deactivate <id>
434
+
435
+ Webhook endpoints (/v1/admin/webhook-endpoints). The signing secret (whsec_…) is
436
+ generated on this machine and written ONLY to the --out file (0600, no trailing
437
+ newline); it is not written to the terminal and steward never returns it in any
438
+ response. If the file exists, no request is sent without --force. The operator moves
439
+ the secret into the product's Secret (the CLI does not call kubectl); on rotation the
440
+ product moves over with a "new,old" list. Delete the file after moving it. Without
441
+ --event-types only account.state_changed. deactivate cannot be undone (open a new
442
+ endpoint).
443
+
444
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
445
+ function schemaProblems$1(issues) {
446
+ return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n");
447
+ }
448
+ const lastDeliveryText = (endpoint) => {
449
+ const last = endpoint.lastDelivery;
450
+ if (last === null) return "-";
451
+ return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
452
+ };
453
+ /** Left-aligned columns; the last column is not padded. */
454
+ function table(rows) {
455
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
456
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
457
+ }
458
+ const typesText = (endpoint) => endpoint.eventTypes === null ? "(no filter: 0.1 types)" : endpoint.eventTypes.join(",");
459
+ async function endpointsCommand(ctx, out, args) {
460
+ const [sub, ...rest] = args;
461
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
462
+ out.out(ENDPOINTS_USAGE);
463
+ return sub === void 0 ? 2 : 0;
464
+ }
465
+ if (sub === "list") {
466
+ const { values, positionals } = parse(rest, {
467
+ ...HELP_OPTION,
468
+ json: { type: "boolean" }
469
+ }, "endpoints");
470
+ if (values.help) return help$7(out);
471
+ expectPositionals(positionals, 0, 0, "endpoints");
472
+ const target = requireAdminTarget(await resolveEnv(ctx));
473
+ out.err(connectionLine(target));
474
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
475
+ if (values.json) out.out(JSON.stringify(items, null, 2));
476
+ else if (items.length === 0) out.out("no endpoints — steward endpoints add --url <url> --out <file>");
477
+ else {
478
+ const rows = [[
479
+ "ID",
480
+ "STATUS",
481
+ "EVENTS",
482
+ "LAST DELIVERY",
483
+ "URL"
484
+ ]];
485
+ for (const e of items) rows.push([
486
+ e.id,
487
+ e.status,
488
+ typesText(e),
489
+ lastDeliveryText(e),
490
+ e.description !== null ? `${e.url} (${e.description})` : e.url
491
+ ]);
492
+ for (const line of table(rows)) out.out(line);
493
+ }
494
+ return 0;
495
+ }
496
+ if (sub === "add") {
497
+ const { values, positionals } = parse(rest, {
498
+ ...HELP_OPTION,
499
+ url: { type: "string" },
500
+ out: { type: "string" },
501
+ "event-types": { type: "string" },
502
+ description: { type: "string" },
503
+ force: { type: "boolean" }
504
+ }, ENDPOINTS_USAGE);
505
+ if (values.help) return help$7(out);
506
+ expectPositionals(positionals, 0, 0, "endpoints");
507
+ const url = requireOption(values.url, "--url", "endpoints");
508
+ const file = requireOption(values.out, "--out", "endpoints");
509
+ const secret = generateWebhookSecret();
510
+ const input = {
511
+ url,
512
+ secret,
513
+ ...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
514
+ ...values.description !== void 0 ? { description: values.description } : {}
515
+ };
516
+ const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
517
+ if (!parsed.success) throw new UsageError(`invalid endpoint (no request was sent)\n${schemaProblems$1(parsed.error.issues)}`);
518
+ const target = requireAdminTarget(await resolveEnv(ctx));
519
+ out.err(connectionLine(target));
520
+ const steward = clientFor(ctx, target);
521
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
522
+ const endpoint = result.value;
523
+ out.out(`endpoint created → ${originOf(target.url)}`);
524
+ out.out(` id ${endpoint.id}`);
525
+ out.out(` url ${endpoint.url}`);
526
+ out.out(` events ${typesText(endpoint)}`);
527
+ secretNotice(out, result.path, result.fallback, "Move the secret into the product's Secret (STEWARD_WEBHOOK_SECRET), then delete the file.");
528
+ return 0;
529
+ }
530
+ if (sub === "rotate") {
531
+ const { values, positionals } = parse(rest, {
532
+ ...HELP_OPTION,
533
+ out: { type: "string" },
534
+ force: { type: "boolean" }
535
+ }, "endpoints");
536
+ if (values.help) return help$7(out);
537
+ expectPositionals(positionals, 1, 1, "endpoints");
538
+ const id = positionals[0];
539
+ const file = requireOption(values.out, "--out", "endpoints");
540
+ const secret = generateWebhookSecret();
541
+ const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
542
+ if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems$1(parsed.error.issues)}`);
543
+ const target = requireAdminTarget(await resolveEnv(ctx));
544
+ out.err(connectionLine(target));
545
+ const steward = clientFor(ctx, target);
546
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
547
+ out.out(`secret rotated → ${originOf(target.url)}`);
548
+ out.out(` id ${result.value.id}`);
549
+ out.out(` url ${result.value.url}`);
550
+ secretNotice(out, result.path, result.fallback, "Set STEWARD_WEBHOOK_SECRET in the product's Secret to \"new,old\" and roll out; the old secret stays in steward as a second signature for the transition. Then delete the file.");
551
+ return 0;
552
+ }
553
+ if (sub === "deactivate") {
554
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
555
+ if (values.help) return help$7(out);
556
+ expectPositionals(positionals, 1, 1, "endpoints");
557
+ const target = requireAdminTarget(await resolveEnv(ctx));
558
+ out.err(connectionLine(target));
559
+ const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
560
+ out.out(`endpoint deactivated → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, status ${endpoint.status})`);
561
+ return 0;
562
+ }
563
+ throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
564
+ }
565
+ function help$7(out) {
566
+ out.out(ENDPOINTS_USAGE);
567
+ return 0;
568
+ }
569
+ /** Where a generated secret went (`withSecretFile`); shared by `endpoints` and `keys`. */
570
+ function secretNotice(out, path, fallback, next) {
571
+ if (fallback) out.err(`! the secret could not be moved to the target file (it may have been created meanwhile); it is in ${path} (0600)`);
572
+ out.out(` secret ${path} (0600; not written to the terminal)`);
573
+ out.err(next);
574
+ }
575
+ // src/commands/list-options.ts
576
+ /** An optional flag's value checked against a contract schema; `message` (it names the flag) when it does not match. */
577
+ function checkedOption(value, schema, message) {
578
+ if (value === void 0) return void 0;
579
+ const parsed = schema.safeParse(value);
580
+ if (!parsed.success) throw new UsageError(message);
581
+ return parsed.data;
582
+ }
583
+ /** `--account <ref>`: the product's external ref of an account. */
584
+ const accountOption = (value) => checkedOption(value, ExternalRefSchema, "--account: an account ref (letters, digits and _ . : -)");
585
+ /**
586
+ * `--from` (inclusive) / `--to` (exclusive): ISO-8601 with an offset (a bare local time would depend on
587
+ * this machine's time zone). The flag names stay inside the messages: the package check
588
+ * (`scripts/check-pack.mjs`) reads a quoted flag name that ends with the word from as an import.
589
+ */
590
+ function periodOptions(values) {
591
+ return {
592
+ from: checkedOption(values.from, DateTimeSchema, "--from: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z"),
593
+ to: checkedOption(values.to, DateTimeSchema, "--to: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z")
594
+ };
595
+ }
596
+ /** Free text of 1–`max` characters (`--search`, `--type`, `--action`, `--source`). */
597
+ function textOption(value, flag, max) {
598
+ if (value !== void 0 && (value.length === 0 || value.length > max)) throw new UsageError(`${flag}: 1–${max} characters`);
599
+ return value;
600
+ }
601
+ const limitOption = (value) => value === void 0 ? void 0 : parsePositiveInt(value, "--limit", { max: ADMIN_LIST_MAX_LIMIT });
602
+ /** The filter without its unset options: the contract's filter types take no explicit `undefined`. */
603
+ function definedOnly(filter) {
604
+ return Object.fromEntries(Object.entries(filter).filter(([, value]) => value !== void 0));
605
+ }
606
+ /** The stderr line of a cut list: how many were listed and the `--after` value of the next page. */
607
+ function nextPageLine(noun, limit, cursor) {
608
+ return `more ${noun} than the ${limit ?? ADMIN_LIST_DEFAULT_LIMIT} listed; next page: --after ${cursor}`;
609
+ }
525
610
  // src/commands/accounts.ts
526
611
  const ACCOUNTS_USAGE = `Usage:
527
612
  steward accounts get <ref> [--include <a,b>] [--json]
613
+ steward accounts list [--search <text>] [--status <status>] [--plan <code>]
614
+ [--deleted exclude|include|only] [--limit <n>] [--after <ref>] [--json]
528
615
  steward accounts metadata set <ref> <key>=<value>… [--reason <text>] [--json]
529
616
  steward accounts metadata unset <ref> <key>… [--reason <text>] [--json]
530
617
 
@@ -536,6 +623,24 @@ metadata. Nothing is written.
536
623
  prints the whole response.
537
624
  --json print the response as JSON
538
625
 
626
+ list (admin) finds accounts without their exact ref: the product's accounts in ref order, one
627
+ line per account with its billing currency and live subscriptions (GET /v1/admin/accounts).
628
+ Nothing personal is listed (no billing profile, no notification address): get <ref> --include
629
+ profile reads one account's profile.
630
+
631
+ --search <text> the ref starts with it, or the display name contains it (case-insensitive,
632
+ 1–${ACCOUNT_LIST_QUERY_MAX} characters)
633
+ --status <status> accounts with a subscription in that status: active, past_due, suspended,
634
+ canceled or expired
635
+ --plan <code> accounts with a live subscription (active, past_due, suspended) of that plan;
636
+ with --status, a subscription of that plan in that status. A code the product
637
+ never had is refused (plan_not_found).
638
+ --deleted exclude (default): accounts that are not deleted; only: deleted (anonymized)
639
+ ones, shown as "(deleted <time>)"; include: both
640
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
641
+ (the last REF) of the next page
642
+ --json print the items as JSON
643
+
539
644
  metadata set / unset change single metadata keys (PATCH /v1/accounts/:ref/metadata) and leave
540
645
  every other key as it is. Steward merges them in one atomic write, so the change cannot
541
646
  overwrite a key another writer (the product, another operator) changes at the same time. The
@@ -552,16 +657,26 @@ The account must exist: these commands never create one (404 account_not_found).
552
657
  must not carry personal data (names, e-mail addresses, phone numbers): use opaque ids and
553
658
  flags. set and unset need a steward whose GET /v1/me lists the "account_metadata" capability.
554
659
 
555
- Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
556
- STEWARD_ADMIN_API_KEY). Environment, otherwise ./.env.local. Changes are sent with
557
- X-Actor-Ref operator:<user>.
558
- Exit code 1: steward refused (unknown or deleted account, no capability); 2: wrong usage,
559
- nothing was sent.`;
660
+ Connection: get and metadata use STEWARD_URL + STEWARD_API_KEY (or, when neither is set,
661
+ STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY); list uses STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY.
662
+ Environment, otherwise ./.env.local. Changes are sent with X-Actor-Ref operator:<user>.
663
+ Exit code 1: steward refused (unknown or deleted account, unknown plan, no capability); 2: wrong
664
+ usage, nothing was sent.`;
560
665
  const GET_OPTIONS$1 = {
561
666
  ...HELP_OPTION,
562
667
  include: { type: "string" },
563
668
  json: { type: "boolean" }
564
669
  };
670
+ const LIST_OPTIONS$4 = {
671
+ ...HELP_OPTION,
672
+ search: { type: "string" },
673
+ status: { type: "string" },
674
+ plan: { type: "string" },
675
+ deleted: { type: "string" },
676
+ limit: { type: "string" },
677
+ after: { type: "string" },
678
+ json: { type: "boolean" }
679
+ };
565
680
  const METADATA_OPTIONS = {
566
681
  ...HELP_OPTION,
567
682
  reason: { type: "string" },
@@ -626,6 +741,48 @@ async function getCommand(ctx, out, args) {
626
741
  else for (const line of formatAccount(account)) out.out(line);
627
742
  return 0;
628
743
  }
744
+ async function listCommand$1(ctx, out, args) {
745
+ const { values, positionals } = parse(args, LIST_OPTIONS$4, "accounts");
746
+ if (values.help) {
747
+ out.out(ACCOUNTS_USAGE);
748
+ return 0;
749
+ }
750
+ expectPositionals(positionals, 0, 0, "accounts");
751
+ const limit = limitOption(values.limit);
752
+ const filter = definedOnly({
753
+ q: textOption(values.search, "--search", ACCOUNT_LIST_QUERY_MAX),
754
+ status: checkedOption(values.status, SubscriptionStatusSchema, `--status: one of ${SubscriptionStatusSchema.options.join(", ")}`),
755
+ plan: checkedOption(values.plan, CodeSchema, "--plan: a plan code"),
756
+ deleted: checkedOption(values.deleted, AccountListDeletedFilterSchema, "--deleted: exclude, include or only"),
757
+ limit,
758
+ after: checkedOption(values.after, ExternalRefSchema, "--after: an account ref (the last REF of the previous page)")
759
+ });
760
+ const target = requireAdminTarget(await resolveEnv(ctx));
761
+ out.err(connectionLine(target));
762
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.accounts.list(filter));
763
+ if (values.json) out.out(JSON.stringify(items, null, 2));
764
+ else if (items.length === 0) out.out("no accounts");
765
+ else {
766
+ const rows = [[
767
+ "REF",
768
+ "NAME",
769
+ "CREATED",
770
+ "CURRENCY",
771
+ "SUBSCRIPTIONS"
772
+ ]];
773
+ for (const a of items) rows.push([
774
+ a.ref,
775
+ a.deletedAt !== null ? `(deleted ${a.deletedAt})` : a.displayName || "-",
776
+ a.createdAt,
777
+ a.billingCurrency ?? "-",
778
+ a.liveSubscriptions.map((s) => `${s.planCode}/${s.interval} ${s.status}`).join(", ") || "-"
779
+ ]);
780
+ for (const line of table(rows)) out.out(line);
781
+ }
782
+ const last = items.at(-1);
783
+ if (hasMore && last !== void 0) out.err(nextPageLine("accounts", limit, last.ref));
784
+ return 0;
785
+ }
629
786
  /** `key=value` arguments (split at the first `=`) or bare keys → the patch: a value sets, `null` removes. */
630
787
  function parseMetadataChange(action, items) {
631
788
  const change = /* @__PURE__ */ new Map();
@@ -682,226 +839,130 @@ async function metadataCommand(ctx, out, args) {
682
839
  for (const line of changeLines(current.metadata, input.data.metadata)) say(line);
683
840
  const updated = await callSteward(target, () => steward.accounts.updateMetadata(ref, input.data));
684
841
  if (values.json) out.out(JSON.stringify(updated, null, 2));
685
- else {
686
- const count = Object.keys(updated.metadata).length;
687
- out.out(`written → ${originOf(target.url)}: ${ref} now has ${count} metadata key${count === 1 ? "" : "s"}`);
688
- }
689
- return 0;
690
- }
691
- async function accountsCommand(ctx, out, args) {
692
- const [sub, ...rest] = args;
693
- if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
694
- out.out(ACCOUNTS_USAGE);
695
- return sub === void 0 ? 2 : 0;
696
- }
697
- if (sub === "get") return getCommand(ctx, out, rest);
698
- if (sub === "metadata") return metadataCommand(ctx, out, rest);
699
- throw new UsageError(`unknown subcommand: accounts ${sub} (see: steward accounts --help)`);
700
- }
701
- // src/confirm.ts
702
- /**
703
- * Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
704
- * terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
705
- */
706
- async function confirm(ctx, question, options) {
707
- if (options.yes) return true;
708
- const answer = await ctx.prompt(`${question} [y/N] `);
709
- if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
710
- return /^y(es)?$/i.test(answer.trim());
711
- }
712
- // src/secret-file.ts
713
- async function withSecretFile(cwd, out, secret, options, action) {
714
- const target = resolve(cwd, out);
715
- try {
716
- if ((await lstat(target)).isDirectory()) throw new CliError(`--out is a folder: ${out}`);
717
- if (!options.force) throw new CliError(`${out} already exists; use --force to overwrite it (no request was sent)`);
718
- } catch (error) {
719
- if (error instanceof CliError) throw error;
720
- if (errnoCode(error) !== "ENOENT") throw error;
721
- }
722
- const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
723
- try {
724
- await writeFile(temp, secret, {
725
- mode: 384,
726
- flag: "wx"
727
- });
728
- } catch (error) {
729
- const code = errnoCode(error);
730
- if (code === "ENOENT") throw new CliError(`--out folder does not exist: ${relative(cwd, dirname(target)) || "."}`);
731
- throw new CliError(`could not write the secret file (${code ?? "error"}): ${out} (no request was sent)`);
732
- }
733
- let value;
734
- try {
735
- value = await action();
736
- } catch (error) {
737
- await unlink(temp).catch(() => {});
738
- throw error;
842
+ else {
843
+ const count = Object.keys(updated.metadata).length;
844
+ out.out(`written → ${originOf(target.url)}: ${ref} now has ${count} metadata key${count === 1 ? "" : "s"}`);
739
845
  }
740
- try {
741
- if (options.force) await rename(temp, target);
742
- else {
743
- await link(temp, target);
744
- await unlink(temp).catch(() => {});
745
- }
746
- return {
747
- value,
748
- path: out,
749
- fallback: false
750
- };
751
- } catch {
752
- return {
753
- value,
754
- path: relative(cwd, temp),
755
- fallback: true
756
- };
846
+ return 0;
847
+ }
848
+ async function accountsCommand(ctx, out, args) {
849
+ const [sub, ...rest] = args;
850
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
851
+ out.out(ACCOUNTS_USAGE);
852
+ return sub === void 0 ? 2 : 0;
757
853
  }
854
+ if (sub === "get") return getCommand(ctx, out, rest);
855
+ if (sub === "list") return listCommand$1(ctx, out, rest);
856
+ if (sub === "metadata") return metadataCommand(ctx, out, rest);
857
+ throw new UsageError(`unknown subcommand: accounts ${sub} (see: steward accounts --help)`);
758
858
  }
759
- // src/commands/endpoints.ts
760
- const ENDPOINTS_USAGE = `Usage:
761
- steward endpoints list [--json]
762
- steward endpoints add --url <url> --out <file> [--event-types <a,b>] [--description <text>] [--force]
763
- steward endpoints rotate <id> --out <file> [--force]
764
- steward endpoints deactivate <id>
765
-
766
- Webhook endpoints (/v1/admin/webhook-endpoints). The signing secret (whsec_…) is
767
- generated on this machine and written ONLY to the --out file (0600, no trailing
768
- newline); it is not written to the terminal and steward never returns it in any
769
- response. If the file exists, no request is sent without --force. The operator moves
770
- the secret into the product's Secret (the CLI does not call kubectl); on rotation the
771
- product moves over with a "new,old" list. Delete the file after moving it. Without
772
- --event-types only account.state_changed. deactivate cannot be undone (open a new
773
- endpoint).
859
+ // src/commands/audit.ts
860
+ const AUDIT_USAGE = `Usage:
861
+ steward audit list [--account <ref>] [--action <action>] [--api-key <prefix>] [--console-user <id>]
862
+ [--source <source>] [--from <iso>] [--to <iso>] [--limit <n>] [--after <id>] [--json]
863
+
864
+ The product's audit trail, newest first, one line per row (GET /v1/admin/audit): when, the
865
+ action (e.g. subscription.canceled, api_key.created), the account, who wrote it and the actor.
866
+ WHO is the API key's prefix for a /v1 request (key a1b2c3d4e5f6), the console user's id for an
867
+ operator console request (console <id>), otherwise the source: job:<name>, cli (the pod CLI),
868
+ hosted or provider_webhook. ACTOR is what the caller reported about itself (X-Actor-Ref, e.g.
869
+ operator:ada), not proof of identity. Reads are not audited.
870
+
871
+ --account <ref> one account's rows (an unknown ref is account_not_found)
872
+ --action <action> one action, exact
873
+ --api-key <prefix> rows written with one API key: the 12 hex characters after stw_ (keys list)
874
+ --console-user <id> rows written by one console user, by id (as WHO shows it)
875
+ --source <source> rows of one source, exact (e.g. job:dunning, hosted)
876
+ --from <iso> written at or after (inclusive); ISO-8601 with an offset
877
+ --to <iso> written before (exclusive); ISO-8601 with an offset
878
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
879
+ (the last row's id) of the next page
880
+ --json print the items as JSON, with each row's writer, request id and detail (its
881
+ own record of what changed; an admin.request row carries the client IP)
774
882
 
775
883
  Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
776
- function schemaProblems$1(issues) {
777
- return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n");
778
- }
779
- const lastDeliveryText = (endpoint) => {
780
- const last = endpoint.lastDelivery;
781
- if (last === null) return "-";
782
- return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
884
+ const LIST_OPTIONS$3 = {
885
+ ...HELP_OPTION,
886
+ account: { type: "string" },
887
+ action: { type: "string" },
888
+ "api-key": { type: "string" },
889
+ "console-user": { type: "string" },
890
+ source: { type: "string" },
891
+ from: { type: "string" },
892
+ to: { type: "string" },
893
+ limit: { type: "string" },
894
+ after: { type: "string" },
895
+ json: { type: "boolean" }
783
896
  };
784
- /** Left-aligned columns; the last column is not padded. */
785
- function table(rows) {
786
- const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
787
- return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
897
+ /** Who wrote the row: the API key of a /v1 request, the console user of a console request, otherwise its source. */
898
+ function writerOf(writer) {
899
+ if (writer === null) return "-";
900
+ switch (writer.kind) {
901
+ case "api_key": return `key ${writer.prefix}`;
902
+ case "console_user": return `console ${writer.id}`;
903
+ case "source": return writer.source;
904
+ }
788
905
  }
789
- const typesText = (endpoint) => endpoint.eventTypes === null ? "(no filter: 0.1 types)" : endpoint.eventTypes.join(",");
790
- async function endpointsCommand(ctx, out, args) {
906
+ async function auditCommand(ctx, out, args) {
791
907
  const [sub, ...rest] = args;
792
908
  if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
793
- out.out(ENDPOINTS_USAGE);
909
+ out.out(AUDIT_USAGE);
794
910
  return sub === void 0 ? 2 : 0;
795
911
  }
796
- if (sub === "list") {
797
- const { values, positionals } = parse(rest, {
798
- ...HELP_OPTION,
799
- json: { type: "boolean" }
800
- }, "endpoints");
801
- if (values.help) return help$7(out);
802
- expectPositionals(positionals, 0, 0, "endpoints");
803
- const target = requireAdminTarget(await resolveEnv(ctx));
804
- out.err(connectionLine(target));
805
- const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
806
- if (values.json) out.out(JSON.stringify(items, null, 2));
807
- else if (items.length === 0) out.out("no endpoints — steward endpoints add --url <url> --out <file>");
808
- else {
809
- const rows = [[
810
- "ID",
811
- "STATUS",
812
- "EVENTS",
813
- "LAST DELIVERY",
814
- "URL"
815
- ]];
816
- for (const e of items) rows.push([
817
- e.id,
818
- e.status,
819
- typesText(e),
820
- lastDeliveryText(e),
821
- e.description !== null ? `${e.url} (${e.description})` : e.url
822
- ]);
823
- for (const line of table(rows)) out.out(line);
824
- }
825
- return 0;
826
- }
827
- if (sub === "add") {
828
- const { values, positionals } = parse(rest, {
829
- ...HELP_OPTION,
830
- url: { type: "string" },
831
- out: { type: "string" },
832
- "event-types": { type: "string" },
833
- description: { type: "string" },
834
- force: { type: "boolean" }
835
- }, ENDPOINTS_USAGE);
836
- if (values.help) return help$7(out);
837
- expectPositionals(positionals, 0, 0, "endpoints");
838
- const url = requireOption(values.url, "--url", "endpoints");
839
- const file = requireOption(values.out, "--out", "endpoints");
840
- const secret = generateWebhookSecret();
841
- const input = {
842
- url,
843
- secret,
844
- ...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
845
- ...values.description !== void 0 ? { description: values.description } : {}
846
- };
847
- const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
848
- if (!parsed.success) throw new UsageError(`invalid endpoint (no request was sent)\n${schemaProblems$1(parsed.error.issues)}`);
849
- const target = requireAdminTarget(await resolveEnv(ctx));
850
- out.err(connectionLine(target));
851
- const steward = clientFor(ctx, target);
852
- const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
853
- const endpoint = result.value;
854
- out.out(`endpoint created → ${originOf(target.url)}`);
855
- out.out(` id ${endpoint.id}`);
856
- out.out(` url ${endpoint.url}`);
857
- out.out(` events ${typesText(endpoint)}`);
858
- secretNotice(out, result.path, result.fallback, "Move the secret into the product's Secret (STEWARD_WEBHOOK_SECRET), then delete the file.");
859
- return 0;
860
- }
861
- if (sub === "rotate") {
862
- const { values, positionals } = parse(rest, {
863
- ...HELP_OPTION,
864
- out: { type: "string" },
865
- force: { type: "boolean" }
866
- }, "endpoints");
867
- if (values.help) return help$7(out);
868
- expectPositionals(positionals, 1, 1, "endpoints");
869
- const id = positionals[0];
870
- const file = requireOption(values.out, "--out", "endpoints");
871
- const secret = generateWebhookSecret();
872
- const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
873
- if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems$1(parsed.error.issues)}`);
874
- const target = requireAdminTarget(await resolveEnv(ctx));
875
- out.err(connectionLine(target));
876
- const steward = clientFor(ctx, target);
877
- const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
878
- out.out(`secret rotated → ${originOf(target.url)}`);
879
- out.out(` id ${result.value.id}`);
880
- out.out(` url ${result.value.url}`);
881
- secretNotice(out, result.path, result.fallback, "Set STEWARD_WEBHOOK_SECRET in the product's Secret to \"new,old\" and roll out; the old secret stays in steward as a second signature for the transition. Then delete the file.");
912
+ if (sub !== "list") throw new UsageError(`unknown subcommand: audit ${sub} (see: steward audit --help)`);
913
+ const { values, positionals } = parse(rest, LIST_OPTIONS$3, "audit");
914
+ if (values.help) {
915
+ out.out(AUDIT_USAGE);
882
916
  return 0;
883
917
  }
884
- if (sub === "deactivate") {
885
- const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
886
- if (values.help) return help$7(out);
887
- expectPositionals(positionals, 1, 1, "endpoints");
888
- const target = requireAdminTarget(await resolveEnv(ctx));
889
- out.err(connectionLine(target));
890
- const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
891
- out.out(`endpoint deactivated → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, status ${endpoint.status})`);
892
- return 0;
918
+ expectPositionals(positionals, 0, 0, "audit");
919
+ const limit = limitOption(values.limit);
920
+ const filter = definedOnly({
921
+ account: accountOption(values.account),
922
+ action: textOption(values.action, "--action", AUDIT_LIST_FILTER_MAX),
923
+ apiKey: checkedOption(values["api-key"], ApiKeyPrefixSchema, "--api-key: a key prefix, the 12 hex characters after stw_"),
924
+ consoleUser: checkedOption(values["console-user"], IdSchema, "--console-user: a console user id"),
925
+ source: textOption(values.source, "--source", AUDIT_LIST_FILTER_MAX),
926
+ ...periodOptions(values),
927
+ limit,
928
+ after: checkedOption(values.after, IdSchema, "--after: an audit row id")
929
+ });
930
+ const target = requireAdminTarget(await resolveEnv(ctx));
931
+ out.err(connectionLine(target));
932
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.audit.list(filter));
933
+ if (values.json) out.out(JSON.stringify(items, null, 2));
934
+ else if (items.length === 0) out.out("no audit rows");
935
+ else {
936
+ const rows = [[
937
+ "TIME",
938
+ "ACTION",
939
+ "ACCOUNT",
940
+ "WHO",
941
+ "ACTOR"
942
+ ]];
943
+ for (const row of items) rows.push([
944
+ row.createdAt,
945
+ row.action,
946
+ row.accountRef ?? "-",
947
+ writerOf(row.writer),
948
+ row.actorRef ?? "-"
949
+ ]);
950
+ for (const line of table(rows)) out.out(line);
893
951
  }
894
- throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
895
- }
896
- function help$7(out) {
897
- out.out(ENDPOINTS_USAGE);
952
+ const last = items.at(-1);
953
+ if (hasMore && last !== void 0) out.err(nextPageLine("audit rows", limit, last.id));
898
954
  return 0;
899
955
  }
900
- /** Where a generated secret went (`withSecretFile`); shared by `endpoints` and `keys`. */
901
- function secretNotice(out, path, fallback, next) {
902
- if (fallback) out.err(`! the secret could not be moved to the target file (it may have been created meanwhile); it is in ${path} (0600)`);
903
- out.out(` secret ${path} (0600; not written to the terminal)`);
904
- out.err(next);
956
+ // src/confirm.ts
957
+ /**
958
+ * Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
959
+ * terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
960
+ */
961
+ async function confirm(ctx, question, options) {
962
+ if (options.yes) return true;
963
+ const answer = await ctx.prompt(`${question} [y/N] `);
964
+ if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
965
+ return /^y(es)?$/i.test(answer.trim());
905
966
  }
906
967
  // src/commands/bank-transfers.ts
907
968
  const BANK_TRANSFERS_USAGE = `Usage:
@@ -2172,10 +2233,99 @@ function help$3(out) {
2172
2233
  out.out(EMAIL_SMTP_USAGE);
2173
2234
  return 0;
2174
2235
  }
2236
+ // src/commands/emails.ts
2237
+ /** Longest email id: an event id, or the source key of an email without one. */
2238
+ const EMAIL_ID_MAX = 200;
2239
+ const EMAILS_USAGE = `Usage:
2240
+ steward emails list [--account <ref>] [--status pending|sent|skipped|dead] [--template <name>]
2241
+ [--limit <n>] [--after <id>] [--json]
2242
+
2243
+ The billing emails steward queued for the product's accounts, newest first, one line per email
2244
+ (GET /v1/admin/emails): the template, the status, the account, the attempts and the last error.
2245
+ pending: waiting or being retried; sent; skipped: not sent, ERROR says why (e.g. no_recipient,
2246
+ template_disabled); dead: the retries ran out, ERROR is the last error code. The ID is the
2247
+ email's webhook event (evt_…) or, for an email without one (e.g. the invoice payment reminder),
2248
+ its source key. Recipient addresses are never stored, so they are not listed (--json has their
2249
+ count).
2250
+
2251
+ --account <ref> one account's emails (an unknown ref is account_not_found)
2252
+ --status <status> pending, sent, skipped or dead
2253
+ --template <name> one template, e.g. payment_receipt, payment_failed, invoice_payment_due (an
2254
+ unknown name is refused with the list)
2255
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
2256
+ (the last ID) of the next page
2257
+ --json print the items as JSON
2258
+
2259
+ Failing emails: steward doctor shows which SMTP account the emails go through and its recent
2260
+ failures; steward email-smtp verify checks the product's own account.
2261
+
2262
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
2263
+ const LIST_OPTIONS$2 = {
2264
+ ...HELP_OPTION,
2265
+ account: { type: "string" },
2266
+ status: { type: "string" },
2267
+ template: { type: "string" },
2268
+ limit: { type: "string" },
2269
+ after: { type: "string" },
2270
+ json: { type: "boolean" }
2271
+ };
2272
+ async function emailsCommand(ctx, out, args) {
2273
+ const [sub, ...rest] = args;
2274
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
2275
+ out.out(EMAILS_USAGE);
2276
+ return sub === void 0 ? 2 : 0;
2277
+ }
2278
+ if (sub !== "list") throw new UsageError(`unknown subcommand: emails ${sub} (see: steward emails --help)`);
2279
+ const { values, positionals } = parse(rest, LIST_OPTIONS$2, "emails");
2280
+ if (values.help) {
2281
+ out.out(EMAILS_USAGE);
2282
+ return 0;
2283
+ }
2284
+ expectPositionals(positionals, 0, 0, "emails");
2285
+ const limit = limitOption(values.limit);
2286
+ const filter = definedOnly({
2287
+ account: accountOption(values.account),
2288
+ status: checkedOption(values.status, EmailMessageStatusSchema, "--status: pending, sent, skipped or dead"),
2289
+ template: checkedOption(values.template, EmailTemplateSchema, `--template: one of ${EmailTemplateSchema.options.join(", ")}`),
2290
+ limit,
2291
+ after: textOption(values.after, "--after", EMAIL_ID_MAX)
2292
+ });
2293
+ const target = requireAdminTarget(await resolveEnv(ctx));
2294
+ out.err(connectionLine(target));
2295
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.emails.list(filter));
2296
+ if (values.json) out.out(JSON.stringify(items, null, 2));
2297
+ else if (items.length === 0) out.out("no emails");
2298
+ else {
2299
+ const rows = [[
2300
+ "CREATED",
2301
+ "TEMPLATE",
2302
+ "STATUS",
2303
+ "ACCOUNT",
2304
+ "ATTEMPTS",
2305
+ "ERROR",
2306
+ "ID"
2307
+ ]];
2308
+ for (const e of items) rows.push([
2309
+ e.createdAt,
2310
+ e.template,
2311
+ e.status,
2312
+ e.accountRef,
2313
+ String(e.attempts),
2314
+ e.lastError ?? "-",
2315
+ e.id
2316
+ ]);
2317
+ for (const line of table(rows)) out.out(line);
2318
+ }
2319
+ const last = items.at(-1);
2320
+ if (hasMore && last !== void 0) out.err(nextPageLine("emails", limit, last.id));
2321
+ return 0;
2322
+ }
2175
2323
  // src/commands/events.ts
2176
2324
  const EVENTS_USAGE = `Usage:
2177
2325
  steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
2178
2326
  [--timestamp <iso>] [--json]
2327
+ steward events list [--account <ref>] [--type <type>] [--delivery pending|delivered|dead|failed]
2328
+ [--limit <n>] [--after <event id>] [--json]
2179
2329
  steward events redeliver <eventId> [<eventId>…]
2180
2330
 
2181
2331
  Sends one event for account <ref> (POST /v1/events/ingest), e.g. to try a meter locally.
@@ -2201,7 +2351,35 @@ Exit code 1: the event was rejected (unknown or deleted account, timestamp out o
2201
2351
  redeliver (admin; STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY): requeues every delivery of a
2202
2352
  webhook event (evt_…; dead ones included) with attempts reset, after the receiver's problem is
2203
2353
  fixed. The dispatcher sends it on its next tick; an account's older events go first. When only
2204
- the current state matters, the product calls POST /v1/accounts/:ref/resync instead.`;
2354
+ the current state matters, the product calls POST /v1/accounts/:ref/resync instead.
2355
+
2356
+ list (admin; STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY): the webhook events steward wrote for
2357
+ the product, newest first, one line per event (GET /v1/admin/events). DELIVERIES has one entry
2358
+ per endpoint, in endpoint order: the status, the attempts so far and the last error code
2359
+ (http_<status>, timeout, network_error, endpoint_inactive, url_not_allowed), e.g.
2360
+ "dead 8× http_500"; "-" when the product had no active endpoint. --json adds each endpoint's
2361
+ address, the last HTTP status and the next attempt time. The payload is not listed: read the
2362
+ account's state with steward accounts get <ref>.
2363
+
2364
+ --account <ref> one account's events (an unknown ref is account_not_found)
2365
+ --type <type> one event type, e.g. account.state_changed
2366
+ --delivery <d> events with a delivery that is pending, delivered or dead; failed: dead, or
2367
+ pending after a failed attempt (being retried)
2368
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
2369
+ (the last ID) of the next page
2370
+ --json print the items as JSON
2371
+
2372
+ A failed event (list --delivery failed) is sent again with steward events redeliver <id> once
2373
+ the receiver's problem is fixed.`;
2374
+ const LIST_OPTIONS$1 = {
2375
+ ...HELP_OPTION,
2376
+ account: { type: "string" },
2377
+ type: { type: "string" },
2378
+ delivery: { type: "string" },
2379
+ limit: { type: "string" },
2380
+ after: { type: "string" },
2381
+ json: { type: "boolean" }
2382
+ };
2205
2383
  const SEND_OPTIONS = {
2206
2384
  ...HELP_OPTION,
2207
2385
  meta: {
@@ -2245,6 +2423,7 @@ async function eventsCommand(ctx, out, args) {
2245
2423
  return sub === void 0 ? 2 : 0;
2246
2424
  }
2247
2425
  if (sub === "redeliver") return redeliverCommand(ctx, out, rest);
2426
+ if (sub === "list") return listCommand(ctx, out, rest);
2248
2427
  if (sub !== "send") throw new UsageError(`unknown subcommand: events ${sub} (see: steward events --help)`);
2249
2428
  const { values, positionals } = parse(rest, SEND_OPTIONS, "events");
2250
2429
  if (values.help) {
@@ -2298,6 +2477,51 @@ async function redeliverCommand(ctx, out, args) {
2298
2477
  }
2299
2478
  return 0;
2300
2479
  }
2480
+ /** One delivery in a table cell: `delivered 1×`, `dead 8× http_500`. */
2481
+ function deliveryText(delivery) {
2482
+ return `${delivery.status} ${delivery.attempts}×${delivery.lastError !== null ? ` ${delivery.lastError}` : ""}`;
2483
+ }
2484
+ async function listCommand(ctx, out, args) {
2485
+ const { values, positionals } = parse(args, LIST_OPTIONS$1, "events");
2486
+ if (values.help) {
2487
+ out.out(EVENTS_USAGE);
2488
+ return 0;
2489
+ }
2490
+ expectPositionals(positionals, 0, 0, "events");
2491
+ const limit = limitOption(values.limit);
2492
+ const filter = definedOnly({
2493
+ account: accountOption(values.account),
2494
+ type: textOption(values.type, "--type", AUDIT_LIST_FILTER_MAX),
2495
+ delivery: checkedOption(values.delivery, WebhookEventDeliveryFilterSchema, "--delivery: pending, delivered, dead or failed"),
2496
+ limit,
2497
+ after: checkedOption(values.after, EventIdSchema, "--after: an event id (evt_…)")
2498
+ });
2499
+ const target = requireAdminTarget(await resolveEnv(ctx));
2500
+ out.err(connectionLine(target));
2501
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.events.list(filter));
2502
+ if (values.json) out.out(JSON.stringify(items, null, 2));
2503
+ else if (items.length === 0) out.out("no events");
2504
+ else {
2505
+ const rows = [[
2506
+ "CREATED",
2507
+ "TYPE",
2508
+ "ACCOUNT",
2509
+ "DELIVERIES",
2510
+ "ID"
2511
+ ]];
2512
+ for (const e of items) rows.push([
2513
+ e.createdAt,
2514
+ e.type,
2515
+ e.accountRef ?? "-",
2516
+ e.deliveries.map(deliveryText).join(", ") || "-",
2517
+ e.id
2518
+ ]);
2519
+ for (const line of table(rows)) out.out(line);
2520
+ }
2521
+ const last = items.at(-1);
2522
+ if (hasMore && last !== void 0) out.err(nextPageLine("events", limit, last.id));
2523
+ return 0;
2524
+ }
2301
2525
  // src/commands/grants.ts
2302
2526
  const GRANTS_USAGE = `Usage:
2303
2527
  steward grants list [--plan <code>] [--subscription none|live|any] [--limit <n>]
@@ -2380,7 +2604,8 @@ async function grantsCommand(ctx, out, args) {
2380
2604
  // src/commands/invoices.ts
2381
2605
  const INVOICES_USAGE = `Usage:
2382
2606
  steward invoices list [--status draft|issued|void|all] [--payment-status <status>]
2383
- [--from <iso>] [--to <iso>] [--limit <n>] [--json | --csv]
2607
+ [--from <iso>] [--to <iso>] [--limit <n>] [--after <invoice id>]
2608
+ [--json | --csv]
2384
2609
  steward invoices issue <id> --number <number> [--external-ref <ref>] [--issued-at <iso>]
2385
2610
  [--document <file.pdf>] [--yes] [--json]
2386
2611
 
@@ -2390,7 +2615,8 @@ list: the product's invoices, oldest first (GET /v1/admin/invoices). draft (defa
2390
2615
  not issued yet, i.e. with no number of the external system; issued: the ones that have it; all:
2391
2616
  every status. --payment-status narrows it (unpaid, paid, …). --from (inclusive) and --to
2392
2617
  (exclusive), ISO-8601 with an offset, keep the invoices written in that window. --limit: 1–500,
2393
- default 100; a cut list says so on stderr.
2618
+ default 100; a cut list says so on stderr with the --after value (the last invoice id) of the
2619
+ next page.
2394
2620
 
2395
2621
  --csv is the export for an accounting system that issues the invoices (one row per invoice, a
2396
2622
  header row first): the invoice, its amounts in minor units, the tax decision (treatment, reason,
@@ -2422,6 +2648,7 @@ async function invoicesCommand(ctx, out, args) {
2422
2648
  from: { type: "string" },
2423
2649
  to: { type: "string" },
2424
2650
  limit: { type: "string" },
2651
+ after: { type: "string" },
2425
2652
  json: { type: "boolean" },
2426
2653
  csv: { type: "boolean" }
2427
2654
  }, "invoices");
@@ -2436,12 +2663,14 @@ async function invoicesCommand(ctx, out, args) {
2436
2663
  const paymentStatus = InvoicePaymentStatusSchema.optional().safeParse(values["payment-status"]);
2437
2664
  if (!paymentStatus.success) throw new UsageError(`--payment-status: one of ${InvoicePaymentStatusSchema.options.join(", ")}`);
2438
2665
  const limit = values.limit !== void 0 ? parsePositiveInt(values.limit, "--limit", { max: 500 }) : void 0;
2666
+ if (values.after !== void 0 && !IdSchema.safeParse(values.after).success) throw new UsageError("--after: an invoice id");
2439
2667
  const filter = {
2440
2668
  ...status !== void 0 ? { status } : {},
2441
2669
  ...paymentStatus.data !== void 0 ? { paymentStatus: paymentStatus.data } : {},
2442
2670
  ...values.from !== void 0 ? { from: values.from } : {},
2443
2671
  ...values.to !== void 0 ? { to: values.to } : {},
2444
- ...limit !== void 0 ? { limit } : {}
2672
+ ...limit !== void 0 ? { limit } : {},
2673
+ ...values.after !== void 0 ? { after: values.after } : {}
2445
2674
  };
2446
2675
  const target = requireAdminTarget(await resolveEnv(ctx));
2447
2676
  out.err(connectionLine(target));
@@ -2472,7 +2701,8 @@ async function invoicesCommand(ctx, out, args) {
2472
2701
  ]);
2473
2702
  for (const line of table(rows)) out.out(line);
2474
2703
  }
2475
- if (hasMore) out.err(`more invoices than the ${limit ?? 100} listed (--limit, at most 500)`);
2704
+ const last = items.at(-1);
2705
+ if (hasMore && last !== void 0) out.err(`more invoices than the ${limit ?? 100} listed (--limit, at most 500); next page: --after ${last.id}`);
2476
2706
  return 0;
2477
2707
  }
2478
2708
  if (sub === "issue") {
@@ -2746,6 +2976,103 @@ function help$1(out) {
2746
2976
  out.out(KEYS_USAGE);
2747
2977
  return 0;
2748
2978
  }
2979
+ // src/commands/payments.ts
2980
+ const PAYMENTS_USAGE = `Usage:
2981
+ steward payments list [--account <ref>] [--method card|bank_transfer] [--disputed any|open|ever]
2982
+ [--from <iso>] [--to <iso>] [--limit <n>] [--after <id>] [--json]
2983
+
2984
+ The product's collected payments, newest collection first, one line per payment
2985
+ (GET /v1/admin/payments): when, the account, the method, the amount, what was refunded at the
2986
+ provider and the dispute (chargeback), if any. Only successful payments are recorded, so a
2987
+ failed charge is not listed (steward invoices list --status all --payment-status unpaid shows
2988
+ what is unpaid). A bank transfer received in another currency also shows what reached the bank;
2989
+ --json adds the rate entered.
2990
+
2991
+ --account <ref> one account's payments (an unknown ref is account_not_found)
2992
+ --method <method> card or bank_transfer
2993
+ --disputed <d> any (default); open: a dispute that is not closed yet; ever: disputed at some
2994
+ point. DISPUTE shows the provider's status and whether it is open or closed.
2995
+ --from <iso> collected at or after (inclusive); ISO-8601 with an offset
2996
+ --to <iso> collected before (exclusive); ISO-8601 with an offset
2997
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
2998
+ (the last ID) of the next page
2999
+ --json print the items as JSON
3000
+
3001
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
3002
+ const LIST_OPTIONS = {
3003
+ ...HELP_OPTION,
3004
+ account: { type: "string" },
3005
+ method: { type: "string" },
3006
+ disputed: { type: "string" },
3007
+ from: { type: "string" },
3008
+ to: { type: "string" },
3009
+ limit: { type: "string" },
3010
+ after: { type: "string" },
3011
+ json: { type: "boolean" }
3012
+ };
3013
+ /** The amount, with what reached the bank when a transfer came in another currency. */
3014
+ function paymentAmountText(p) {
3015
+ const amount = formatMinor(p.amountMinor, p.currency);
3016
+ if (p.receivedAmountMinor === void 0 || p.receivedCurrency === void 0) return amount;
3017
+ return `${amount} (received ${formatMinor(p.receivedAmountMinor, p.receivedCurrency)})`;
3018
+ }
3019
+ /** `-` (never disputed), or the provider's dispute status and whether it is still open. */
3020
+ function disputeText(p) {
3021
+ if (p.dispute === null) return "-";
3022
+ return `${p.dispute.status ?? "disputed"} (${p.dispute.closedAt === null ? "open" : "closed"})`;
3023
+ }
3024
+ async function paymentsCommand(ctx, out, args) {
3025
+ const [sub, ...rest] = args;
3026
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
3027
+ out.out(PAYMENTS_USAGE);
3028
+ return sub === void 0 ? 2 : 0;
3029
+ }
3030
+ if (sub !== "list") throw new UsageError(`unknown subcommand: payments ${sub} (see: steward payments --help)`);
3031
+ const { values, positionals } = parse(rest, LIST_OPTIONS, "payments");
3032
+ if (values.help) {
3033
+ out.out(PAYMENTS_USAGE);
3034
+ return 0;
3035
+ }
3036
+ expectPositionals(positionals, 0, 0, "payments");
3037
+ const limit = limitOption(values.limit);
3038
+ const filter = definedOnly({
3039
+ account: accountOption(values.account),
3040
+ method: checkedOption(values.method, PaymentMethodSchema, "--method: card or bank_transfer"),
3041
+ disputed: checkedOption(values.disputed, PaymentListDisputedFilterSchema, "--disputed: any, open or ever"),
3042
+ ...periodOptions(values),
3043
+ limit,
3044
+ after: checkedOption(values.after, IdSchema, "--after: a payment id")
3045
+ });
3046
+ const target = requireAdminTarget(await resolveEnv(ctx));
3047
+ out.err(connectionLine(target));
3048
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.payments.list(filter));
3049
+ if (values.json) out.out(JSON.stringify(items, null, 2));
3050
+ else if (items.length === 0) out.out("no payments");
3051
+ else {
3052
+ const rows = [[
3053
+ "COLLECTED",
3054
+ "ACCOUNT",
3055
+ "METHOD",
3056
+ "AMOUNT",
3057
+ "REFUNDED",
3058
+ "DISPUTE",
3059
+ "ID"
3060
+ ]];
3061
+ for (const p of items) rows.push([
3062
+ p.occurredAt,
3063
+ p.accountRef,
3064
+ p.method,
3065
+ paymentAmountText(p),
3066
+ p.refundedMinor > 0 ? formatMinor(p.refundedMinor, p.currency) : "-",
3067
+ disputeText(p),
3068
+ p.id
3069
+ ]);
3070
+ for (const line of table(rows)) out.out(line);
3071
+ }
3072
+ const last = items.at(-1);
3073
+ if (hasMore && last !== void 0) out.err(nextPageLine("payments", limit, last.id));
3074
+ return 0;
3075
+ }
2749
3076
  // src/commands/reprice.ts
2750
3077
  const REPRICE_USAGE = `Usage: steward reprice --plan <code> --notice-days <n> [--dry-run] [--yes] [--json]
2751
3078
 
@@ -2841,7 +3168,7 @@ const SETTINGS_USAGE = `Usage:
2841
3168
  [--branding <json>] [--default-locale tr|en] [--display-time-zone <iana>]
2842
3169
  [--default-country <XX>]
2843
3170
  [--checkout-ttl <minutes>] [--portal-ttl <minutes>]
2844
- [--extra-return-origins <a,b>] [--emails <json>]
3171
+ [--extra-return-origins <a,b>] [--public-url <url>] [--emails <json>]
2845
3172
  [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
2846
3173
  [--billing-allow-multiple-subscriptions true|false]
2847
3174
  [--billing-renewal-notice-intervals <year,month>] [--billing-renewal-notice-days <1-90>]
@@ -2857,6 +3184,9 @@ Product settings (GET/PATCH /v1/admin/settings). A field not given is unchanged;
2857
3184
  empty value (--privacy-url "") clears the field, --branding null clears the branding,
2858
3185
  --branding '{"name":"Acme","supportEmail":"support@acme.com"}' merges shallowly (clear a
2859
3186
  field with null). --extra-return-origins "" empties the list.
3187
+ --public-url puts the product's hosted links (checkout, portal, pay pages, e-mailed pay links)
3188
+ on another address of the same steward, e.g. a second brand's domain; steward accepts only an
3189
+ address its deployment serves (STEWARD_EXTRA_PUBLIC_URLS). "" restores the deployment's address.
2860
3190
  --emails '{"billingPath":"/{LOCALE}/billing","templates":{"invoice_issued":{"enabled":false}}}'
2861
3191
  sets billing emails (sender: from.name, from.address; templates merge per
2862
3192
  template, null resets a field or template; --emails null resets all).
@@ -2914,6 +3244,7 @@ const SET_OPTIONS = {
2914
3244
  "checkout-ttl": { type: "string" },
2915
3245
  "portal-ttl": { type: "string" },
2916
3246
  "extra-return-origins": { type: "string" },
3247
+ "public-url": { type: "string" },
2917
3248
  emails: { type: "string" },
2918
3249
  "billing-payment-due-days": { type: "string" },
2919
3250
  "billing-min-invoice-minor": { type: "string" },
@@ -2988,6 +3319,7 @@ function buildSettingsPatch(values) {
2988
3319
  if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
2989
3320
  if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
2990
3321
  if (values["extra-return-origins"] !== void 0) patch.extraReturnOrigins = parseList(values["extra-return-origins"]);
3322
+ if (values["public-url"] !== void 0) patch.publicUrl = orNull(values["public-url"]);
2991
3323
  const billing = {};
2992
3324
  const dueDays = values["billing-payment-due-days"];
2993
3325
  if (dueDays !== void 0) billing.paymentDueDays = dueDays.trim() === "" ? null : parsePositiveInt(dueDays, "--billing-payment-due-days", { max: 60 });
@@ -3321,7 +3653,7 @@ function help(out) {
3321
3653
  return 0;
3322
3654
  }
3323
3655
  // src/main.ts
3324
- const CLI_VERSION = "0.13.0";
3656
+ const CLI_VERSION = "0.14.0";
3325
3657
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
3326
3658
 
3327
3659
  Usage: steward <command> [options]
@@ -3340,17 +3672,21 @@ Commands:
3340
3672
  invoices list | issue invoices not issued yet; write the external invoice number
3341
3673
  grants list active grants; --subscription none: paying for nothing
3342
3674
  credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
3343
- accounts get | metadata set | unset read an account; set or remove metadata keys
3675
+ accounts get | list | metadata set | unset read or list accounts; set or remove metadata keys
3344
3676
  meters get | recompute | close-periods an account's meters; metering repairs (admin)
3345
- events send | redeliver send one event; redeliver webhook events (admin)
3677
+ events send | list | redeliver send one event; list or redeliver webhook events (admin)
3678
+ audit list the product's audit trail: who changed what (admin)
3679
+ emails list billing emails steward queued; never the recipients (admin)
3680
+ payments list collected payments with refunds and disputes (admin)
3346
3681
  tax thresholds list | set | delete tax registration thresholds and their counters
3347
3682
  tax sales [--from] [--to] [--csv] paid sales per month and buyer country (admin)
3348
3683
 
3349
3684
  Connection: admin commands use STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY; doctor,
3350
- accounts, meters and events use STEWARD_URL + STEWARD_API_KEY (or the admin pair). If even
3351
- one of these four variables is in the environment, all of them (and APP_URL) are read from
3352
- the environment and ./.env.local is not read at all; otherwise from ./.env.local. The source
3353
- in use is written to stderr (connection: …). Changes send X-Actor-Ref operator:<user>.
3685
+ accounts get|metadata, meters get and events send use STEWARD_URL + STEWARD_API_KEY (or the
3686
+ admin pair). If even one of these four variables is in the environment, all of them (and
3687
+ APP_URL) are read from the environment and ./.env.local is not read at all; otherwise from
3688
+ ./.env.local. The source in use is written to stderr (connection: …). Changes send
3689
+ X-Actor-Ref operator:<user>.
3354
3690
  The CLI never writes secrets to the terminal and never calls kubectl.
3355
3691
 
3356
3692
  Details: steward <command> --help`;
@@ -3364,6 +3700,9 @@ const COMMANDS = {
3364
3700
  accounts: accountsCommand,
3365
3701
  meters: metersCommand,
3366
3702
  events: eventsCommand,
3703
+ audit: auditCommand,
3704
+ emails: emailsCommand,
3705
+ payments: paymentsCommand,
3367
3706
  keys: keysCommand,
3368
3707
  dunning: dunningCommand,
3369
3708
  reprice: repriceCommand,