@fabrika/cli 0.9.0-dev.1 → 0.9.0-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/cli",
3
- "version": "0.9.0-dev.1",
3
+ "version": "0.9.0-dev.11",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,12 +15,13 @@
15
15
  },
16
16
  "files": [
17
17
  "src",
18
- "!src/**/__tests__/**"
18
+ "!src/**/__tests__/**",
19
+ "types"
19
20
  ],
20
21
  "exports": {
21
22
  ".": {
22
23
  "bun": "./src/index.ts",
23
- "types": "./src/index.ts",
24
+ "types": "./types/src/index.d.ts",
24
25
  "default": "./src/index.ts"
25
26
  }
26
27
  },
@@ -30,19 +31,19 @@
30
31
  },
31
32
  "dependencies": {
32
33
  "zod": "^3.25.76",
33
- "@fabrika/app": "0.9.0-dev.1",
34
- "@fabrika/auth-core": "0.9.0-dev.1",
35
- "@fabrika/control-contract": "0.9.0-dev.1",
36
- "@fabrika/provider-contract": "0.9.0-dev.1",
37
- "@fabrika/db": "0.9.0-dev.1",
38
- "@fabrika/platform": "0.9.0-dev.1",
39
- "@fabrika/platform-node": "0.9.0-dev.1",
40
- "@fabrika/check": "0.9.0-dev.1"
34
+ "@fabrika/app": "0.9.0-dev.11",
35
+ "@fabrika/auth-core": "0.9.0-dev.11",
36
+ "@fabrika/control-contract": "0.9.0-dev.11",
37
+ "@fabrika/provider-contract": "0.9.0-dev.11",
38
+ "@fabrika/db": "0.9.0-dev.11",
39
+ "@fabrika/platform": "0.9.0-dev.11",
40
+ "@fabrika/platform-node": "0.9.0-dev.11",
41
+ "@fabrika/check": "0.9.0-dev.11"
41
42
  },
42
43
  "peerDependencies": {
43
- "@fabrika/builder": "0.9.0-dev.1",
44
- "@fabrika/provider-cloudflare": "0.9.0-dev.1",
45
- "@fabrika/provider-zerops": "0.9.0-dev.1"
44
+ "@fabrika/builder": "0.9.0-dev.11",
45
+ "@fabrika/provider-cloudflare": "0.9.0-dev.11",
46
+ "@fabrika/provider-zerops": "0.9.0-dev.11"
46
47
  },
47
48
  "peerDependenciesMeta": {
48
49
  "@fabrika/builder": {
package/src/app-dev.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // `fabrika app dev`: a contract application served through its test kit on a loopback port, to click through its
2
2
  // screens. The kit is the whole server: production's proxy decision, the stand-in IAM, the real `boot`, the SPAs from
3
- // their build directories; Postgres is a throwaway schema of the tests' database. A seed module fills it through the
3
+ // their build directories; Postgres is a throwaway schema of the tests' database, SQLite (Cloudflare) an in-memory
4
+ // database. A seed module fills it through the
4
5
  // endpoints first. A caller picker chooses who the browser is; a cookie keeps the choice, and the kit's own session
5
6
  // never leaves the process. Every SPA page gets the dev toolbar, which switches the caller without leaving the page.
6
7
 
@@ -9,10 +10,12 @@ import { implementationAt } from '@fabrika/app/bun'
9
10
  import type { AnyContract } from '@fabrika/app/contract'
10
11
  import { BootError, type ContractImplementation } from '@fabrika/app/implement'
11
12
  import { DEV_OUTBOX_ORIGIN, type DevKit, devKit, type DevOutside, type LabelledTestCaller, type TestCaller } from '@fabrika/app/testing'
13
+ import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
14
+ import { SqliteMigrationError } from '@fabrika/db/sqlite-migrate'
12
15
  import { TEST_POSTGRES_URL, type TestDatabase, testDatabase } from '@fabrika/db/testing'
13
16
  import { PostgresMigrationError } from '@fabrika/platform-node'
14
17
  import { MemoryFileObjects } from '@fabrika/platform/testing'
15
- import { existsSync } from 'node:fs'
18
+ import { existsSync, readFileSync } from 'node:fs'
16
19
  import { join } from 'node:path'
17
20
  import { z } from 'zod/v4'
18
21
  import { DEV_ENV_FILE, DevEnvProblem, type DevOutbox, devOutbox, mailHeadOf, readDevEnv, shownBody } from './app-dev-outside'
@@ -41,7 +44,8 @@ Usage:
41
44
 
42
45
  Run from the application root. It serves ${IMPLEMENTATION_FILE} through its test kit: the production proxy decision,
43
46
  the kit's stand-in IAM, each SPA from its built directory (run the SPA build first; an unbuilt one is an empty page),
44
- and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit.
47
+ and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit; an
48
+ application on Cloudflare (its ${CONFIG_FILE} is @fabrika/provider-cloudflare's) gets an in-memory SQLite database instead.
45
49
  The seed module (--seed, or ${DEFAULT_SEED} when it exists) default-exports a DevSeed of @fabrika/app/testing: it
46
50
  receives the kit, writes through the endpoints, and answers the personas, link pages and scope values to offer.
47
51
  Pick who the browser is at /__fabrika/dev; every SPA page shows a toolbar that switches the caller and lists the
@@ -87,7 +91,7 @@ export class AppDevError extends Error {
87
91
  export function startupFailure(error: unknown): Error {
88
92
  if (
89
93
  error instanceof AppDevError || error instanceof SeedProblem || error instanceof DevEnvProblem || error instanceof BootError
90
- || error instanceof PostgresMigrationError
94
+ || error instanceof PostgresMigrationError || error instanceof SqliteMigrationError
91
95
  ) {
92
96
  return new Error(error.message)
93
97
  }
@@ -190,21 +194,31 @@ function addressedHere(request: Request, port: number): boolean {
190
194
  const plain = (status: number, text: string): Response =>
191
195
  new Response(`${text}\n`, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' } })
192
196
 
197
+ /** The dialect the application's `fabrika.config.ts` names, as the checker reads it. */
198
+ function dialectAt(root: string): ApplicationDialect {
199
+ const path = join(root, CONFIG_FILE)
200
+ return applicationDialect(new Map(existsSync(path) ? [[CONFIG_FILE, readFileSync(path, 'utf8')]] : []))
201
+ }
202
+
193
203
  /** Serves `app` through its test kit on a loopback port until `stop`. */
194
204
  export async function startAppDev(app: ContractImplementation<AnyContract>, options: AppDevOptions): Promise<AppDevServer> {
195
205
  if (!LOOPBACK.has(options.host)) throw new AppDevError(`app dev serves this machine only, not ${options.host}`)
196
- let postgres: TestDatabase | null = null
197
- if (app.database !== null) {
206
+ let testDb: TestDatabase | null = null
207
+ if (app.database !== null && dialectAt(options.root) === 'sqlite') {
208
+ // The SQLite twin of the kit opens an in-memory database: no URL, and nothing left behind to drop.
209
+ const sqlite = await import('@fabrika/db/testing-sqlite')
210
+ testDb = await sqlite.testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
211
+ } else if (app.database !== null) {
198
212
  if ((options.env[TEST_POSTGRES_URL] ?? '') === '') {
199
213
  throw new AppDevError(`app dev needs ${TEST_POSTGRES_URL}, the database the tests use: it migrates a throwaway schema there`)
200
214
  }
201
- postgres = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
215
+ testDb = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
202
216
  }
203
217
  try {
204
- return await serveThroughKit(app, options, postgres)
218
+ return await serveThroughKit(app, options, testDb)
205
219
  } catch (error) {
206
220
  // The schema and its roles exist from here on: a failed start drops them as a stop does.
207
- await postgres?.close()
221
+ await testDb?.close()
208
222
  throw error
209
223
  }
210
224
  }
@@ -226,24 +240,24 @@ async function runSeed(dev: DevKit<AnyContract>, outside: DevOutside, path: stri
226
240
  return parseSeeded(dev, answer)
227
241
  }
228
242
 
229
- /** What a job's handler threw, printed whole on the developer's terminal. */
243
+ /** What a request's 5xx or a job attempt threw, printed whole on the developer's terminal. */
230
244
  const printHandlerError = (where: string, error: unknown): void => {
231
245
  console.error(`fabrika app dev: ${where} threw\n${Bun.inspect(error)}`)
232
246
  }
233
247
 
234
248
  /**
235
- * The server over the kit of `app`, on `postgres` when it has a data layer; its `stop` also drops the schema. The dev
249
+ * The server over the kit of `app`, on `testDb` when it has a data layer; its `stop` also drops a Postgres schema. The dev
236
250
  * outbox captures the process's `fetch` from before the seed runs until `stop`, or until a failed start.
237
251
  */
238
252
  async function serveThroughKit(
239
253
  app: ContractImplementation<AnyContract>,
240
254
  options: AppDevOptions,
241
- postgres: TestDatabase | null,
255
+ testDb: TestDatabase | null,
242
256
  ): Promise<AppDevServer> {
243
257
  const outbox = devOutbox()
244
258
  const restoreFetch = outbox.install()
245
259
  try {
246
- return await serveDevKit(app, options, postgres, outbox, restoreFetch)
260
+ return await serveDevKit(app, options, testDb, outbox, restoreFetch)
247
261
  } catch (error) {
248
262
  restoreFetch()
249
263
  throw error
@@ -253,7 +267,7 @@ async function serveThroughKit(
253
267
  async function serveDevKit(
254
268
  app: ContractImplementation<AnyContract>,
255
269
  options: AppDevOptions,
256
- postgres: TestDatabase | null,
270
+ testDb: TestDatabase | null,
257
271
  outbox: DevOutbox,
258
272
  restoreFetch: () => void,
259
273
  ): Promise<AppDevServer> {
@@ -263,7 +277,7 @@ async function serveDevKit(
263
277
  const dev = devKit(app, {
264
278
  root: options.root,
265
279
  env: { ...applicationVariables(options.env), ...readDevEnv(options.root) },
266
- ...(postgres === null ? {} : { database: postgres.database }),
280
+ ...(testDb === null ? {} : { database: testDb.database }),
267
281
  ...(hasFiles ? { files: new MemoryFileObjects() } : {}),
268
282
  revealHandlerErrors: printHandlerError,
269
283
  })
@@ -561,7 +575,7 @@ async function serveDevKit(
561
575
  await server.stop(true)
562
576
  } finally {
563
577
  restoreFetch()
564
- await postgres?.close()
578
+ await testDb?.close()
565
579
  }
566
580
  },
567
581
  }
package/src/control.ts CHANGED
@@ -60,7 +60,7 @@ Usage:
60
60
  [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]
61
61
  [--cross-origin=<origin> ...] [--kind=standard|dev]
62
62
  fabrika control apps variables list --app=<id>
63
- fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>]
63
+ fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret]
64
64
  fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]
65
65
  fabrika control apps secrets list --app=<id>
66
66
  fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)
@@ -75,6 +75,7 @@ Usage:
75
75
  fabrika control namespaces reconcile --namespace=<id>
76
76
  fabrika control namespaces update --namespace=<id> --proxy-source=current
77
77
  fabrika control namespaces remove --namespace=<id>
78
+ fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>
78
79
  fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]
79
80
  fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]
80
81
  fabrika control runs get --run=<id>
@@ -90,7 +91,9 @@ refused before anything is created. \`namespaces get\` lists the hosts a \`zerop
90
91
  serves and which of them are still free; a custom-domain namespace serves the domain you bound to its
91
92
  proxy. A manifest with no proxy target needs no domain.
92
93
 
93
- A variable's value is stored and printed in clear. A secret's value is write-only: \`apps secrets put\`
94
+ A variable's value is stored and printed in clear, so \`apps variables put\` refuses one that looks like a
95
+ credential (by its name, such as \`*_TOKEN\` or \`*_PASSWORD\`, or by its value) and names \`apps secrets put\` instead.
96
+ \`--not-secret\` stores it anyway, for a value you have checked is not one. A secret's value is write-only: \`apps secrets put\`
94
97
  reads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and
95
98
  one trailing newline is dropped. No command prints it back; \`apps secrets list\` shows names, scope and
96
99
  storage only. Generate one in the pipe:
@@ -127,6 +130,11 @@ Namespace placement options, each defaulting to what the preset would choose:
127
130
  SERIOUS is a deliberate choice: a project cannot be downgraded again
128
131
  --public-access=<custom-domain|zerops-subdomain>
129
132
  --exclusive-app=<id> required by, and only by, the \`full\` preset
133
+ --postgres-type=<type> the \`cheap\` preset's shared PostgreSQL; on Zerops postgresql:single@18
134
+ (default) or postgresql:ha@18, which keeps its data through a node loss.
135
+ Fixed once created
136
+ --postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,
137
+ oltp-staging (about $11) or oltp-production (about $72) for HA
130
138
 
131
139
  \`namespaces plan\` is a preview and changes nothing. It prints one \`<path>\\t<value>\` row per field of
132
140
  the plan, keyed by its path in \`--json\`; a multi-line value such as the proxy's descriptor file is shown
@@ -139,6 +147,10 @@ the provider resources it stopped tracking. \`namespaces update --proxy-source=c
139
147
  proxy to the source this control plane deploys new placements from — a placement keeps the one it was created
140
148
  with until you do — and queues the reconcile that rebuilds the proxy from it; a \`failed\` placement accepts it.
141
149
 
150
+ \`namespaces release-claims\` frees the resource names one app environment holds in a placement, which an
151
+ environment or app delete otherwise refuses over. Delete those resources at the provider first: the release
152
+ reads each one back and refuses, naming it, while any still exists. It prints one released key per line.
153
+
142
154
  Every command accepts --json, which prints the procedure's result verbatim.
143
155
 
144
156
  The control origin is not a credential and takes either form:
@@ -176,18 +188,23 @@ interface Flags {
176
188
  /** Every value of every option, in order; `values` keeps the last. Only a repeatable option reads it. */
177
189
  readonly repeated: ReadonlyMap<string, readonly string[]>
178
190
  readonly json: boolean
191
+ /** `--not-secret`: `apps variables put` stores a value that looks like a credential. */
192
+ readonly notSecret: boolean
179
193
  readonly positional: readonly string[]
180
194
  }
181
195
 
182
- /** Split `--key=value` options from positional words; `--json` is the one flag every verb shares. */
196
+ /** Split `--key=value` options from positional words; `--json` is the one flag every verb shares, `--not-secret` the other bare one. */
183
197
  export const parseControlFlags = (argv: readonly string[]): Flags => {
184
198
  const values = new Map<string, string>()
185
199
  const repeated = new Map<string, string[]>()
186
200
  const positional: string[] = []
187
201
  let json = false
202
+ let notSecret = false
188
203
  for (const arg of argv) {
189
204
  if (arg === '--json') {
190
205
  json = true
206
+ } else if (arg === '--not-secret') {
207
+ notSecret = true
191
208
  } else if (arg.startsWith('--')) {
192
209
  const eq = arg.indexOf('=')
193
210
  if (eq === -1) {
@@ -201,7 +218,7 @@ export const parseControlFlags = (argv: readonly string[]): Flags => {
201
218
  positional.push(arg)
202
219
  }
203
220
  }
204
- return { values, repeated, json, positional }
221
+ return { values, repeated, json, notSecret, positional }
205
222
  }
206
223
 
207
224
  const required = (flags: Flags, name: string): string => {
@@ -268,21 +285,85 @@ const secret = (variable: string, env: Readonly<Record<string, string | undefine
268
285
  }
269
286
 
270
287
  /** The console's client with a bearer instead of a cookie, and no SSO bounce: there is no browser to send. */
271
- type ControlClient = InferRpcClient<ControlRpcContract>
288
+ export type ControlClient = InferRpcClient<ControlRpcContract>
289
+
290
+ /** Plain http may carry the key to loopback only: 127.0.0.0/8, [::1], and the names RFC 6761 reserves for it, `localhost` and `*.localhost`. */
291
+ const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
292
+
293
+ /**
294
+ * Control's origin, checked before the key is sent anywhere: https, or http to a loopback host for local development,
295
+ * and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
296
+ */
297
+ export const controlOrigin = (raw: string | undefined): string => {
298
+ if (raw === undefined || raw.trim() === '') {
299
+ throw new Error('Control origin is required. Pass --url=<origin> or set FABRIKA_CONTROL_URL.')
300
+ }
301
+ let url: URL
302
+ try {
303
+ url = new URL(raw.trim())
304
+ } catch {
305
+ throw new Error('--url or FABRIKA_CONTROL_URL is not a URL')
306
+ }
307
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) {
308
+ throw new Error('--url or FABRIKA_CONTROL_URL must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]')
309
+ }
310
+ if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
311
+ throw new Error('--url or FABRIKA_CONTROL_URL must be an origin only: no credentials, path, query or fragment')
312
+ }
313
+ return url.origin
314
+ }
315
+
316
+ const KEY_LABEL = '[FABRIKA_CONTROL_KEY]'
317
+
318
+ /** `text` with the control key cut out: every diagnostic of an area that holds the key passes through it. */
319
+ export const withoutControlKey = (text: string, env: Readonly<Record<string, string | undefined>>): string => {
320
+ const key = env['FABRIKA_CONTROL_KEY']?.trim()
321
+ return key === undefined || key === '' ? text : text.replaceAll(key, KEY_LABEL)
322
+ }
323
+
324
+ /** Whether a JSON body holds `key`, also behind JSON escapes, which a plain search of the text would miss. */
325
+ const carriesKey = (text: string, key: string): boolean => {
326
+ if (text.includes(key)) return true
327
+ try {
328
+ return JSON.stringify(JSON.parse(text)).includes(JSON.stringify(key).slice(1, -1))
329
+ } catch {
330
+ return false
331
+ }
332
+ }
333
+
334
+ /**
335
+ * A JSON answer that carries the key is dropped whole, so no row, `--json` output or error can repeat it. Any other
336
+ * body passes: the RPC client reports a non-JSON answer by its status alone.
337
+ */
338
+ const withoutEchoedKey = async (response: Response, key: string): Promise<Response> => {
339
+ if (!(response.headers.get('content-type') ?? '').includes('application/json')) return response
340
+ const text = await response.text()
341
+ if (carriesKey(text, key)) {
342
+ return Response.json({ error: { type: 'transport', message: `Control's answer carried ${KEY_LABEL}; it was dropped` } }, { status: 502 })
343
+ }
344
+ return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
345
+ }
272
346
 
273
- const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => {
274
- const base = origin(flags, 'url', 'FABRIKA_CONTROL_URL', env, 'Control')
347
+ /**
348
+ * The one client of Control that `fabrika control` and `fabrika env` share: the origin from `url` or
349
+ * FABRIKA_CONTROL_URL, the key from FABRIKA_CONTROL_KEY in the environment only, no redirect followed.
350
+ */
351
+ export const connectControl = (url: string | undefined, env: Readonly<Record<string, string | undefined>>): ControlClient => {
352
+ const base = controlOrigin(url ?? env['FABRIKA_CONTROL_URL'])
275
353
  const key = secret('FABRIKA_CONTROL_KEY', env)
276
354
  return createRpcClient<ControlRpcContract>({
277
355
  baseUrl: `${base}/api/rpc`,
278
- fetch: (input, init) => {
356
+ fetch: async (input, init) => {
279
357
  const headers = new Headers(init?.headers)
280
358
  headers.set('authorization', `Bearer ${key}`)
281
- return fetch(input, { ...init, headers })
359
+ // A redirect would carry the bearer to wherever it points.
360
+ return await withoutEchoedKey(await fetch(input, { ...init, headers, redirect: 'manual' }), key)
282
361
  },
283
362
  })
284
363
  }
285
364
 
365
+ const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => connectControl(flags.values.get('url'), env)
366
+
286
367
  const readJsonFile = async (path: string): Promise<JsonValue> => {
287
368
  const file = Bun.file(path)
288
369
  if (!(await file.exists())) {
@@ -632,6 +713,7 @@ const runVariables = async (verb: string | undefined, flags: Flags, env: Readonl
632
713
  name: required(flags, 'name'),
633
714
  value: required(flags, 'value'),
634
715
  ...(scope === undefined ? {} : { env: scope }),
716
+ ...(flags.notSecret ? { notSecret: true } : {}),
635
717
  }
636
718
  const result = await client.apps.variables.put({ appId, variable })
637
719
  emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\t${result.value}`)
@@ -839,6 +921,11 @@ const namespacePlan = (flags: Flags): PlanDeploymentNamespaceRequest => {
839
921
  if (project !== undefined) options['projectName'] = project
840
922
  if (corePackage !== undefined) options['corePackage'] = corePackage
841
923
  if (publicAccess !== undefined) options['publicAccess'] = publicAccess
924
+ const postgresType = optional(flags, 'postgres-type')
925
+ const postgresProfile = optional(flags, 'postgres-profile')
926
+ // Together or not at all: a type without a profile gets the platform's default, which for HA is the dedicated ~$72 one.
927
+ if ((postgresType === undefined) !== (postgresProfile === undefined)) throw new Error('--postgres-type and --postgres-profile go together')
928
+ if (postgresType !== undefined && postgresProfile !== undefined) options['postgres'] = { type: postgresType, profile: postgresProfile }
842
929
  return {
843
930
  id: required(flags, 'namespace'),
844
931
  env: required(flags, 'env'),
@@ -884,6 +971,15 @@ const runNamespaces = async (verb: string | undefined, flags: Flags, env: Readon
884
971
  emit(flags, result, () => namespaceLine(result.removed))
885
972
  return
886
973
  }
974
+ if (verb === 'release-claims') {
975
+ const result = await client.namespaces.releaseClaims({
976
+ namespaceId: required(flags, 'namespace'),
977
+ appId: required(flags, 'app'),
978
+ env: required(flags, 'env'),
979
+ })
980
+ emit(flags, result, () => result.released.map((key) => `released\t${key}`).join('\n'))
981
+ return
982
+ }
887
983
  if (verb === 'update') {
888
984
  const namespaceId = required(flags, 'namespace')
889
985
  if (required(flags, 'proxy-source') !== 'current') {
@@ -938,9 +1034,9 @@ export const runControlCli = async (
938
1034
  env: Readonly<Record<string, string | undefined>> = process.env,
939
1035
  input: SecretValueInput = processStdin,
940
1036
  ): Promise<void> => {
941
- const flags = parseControlFlags(argv)
942
- const verb = flags.positional[0]
943
1037
  try {
1038
+ const flags = parseControlFlags(argv)
1039
+ const verb = flags.positional[0]
944
1040
  switch (command) {
945
1041
  case undefined:
946
1042
  console.info(USAGE)
@@ -970,7 +1066,8 @@ export const runControlCli = async (
970
1066
  } catch (error) {
971
1067
  // An RPC denial is an ANSWER, not a transport fault; keep its type so a caller can tell "the
972
1068
  // control plane said no" from "the control plane was unreachable".
973
- throw error instanceof RpcError ? new Error(`${error.type}: ${error.message}`) : error
1069
+ const message = error instanceof RpcError ? `${error.type}: ${error.message}` : error instanceof Error ? error.message : String(error)
1070
+ throw new Error(withoutControlKey(message, env))
974
1071
  }
975
1072
  }
976
1073