@fabrika/cli 0.9.0-dev.3 → 0.9.0-dev.31

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/src/control.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  // Output contract, matching `zops`: stdout carries DATA ONLY, progress and errors go to stderr, and
10
10
  // `--json` prints the procedure's result verbatim so a caller never parses a table.
11
11
 
12
- import { createRpcClient, type InferRpcClient, RpcError } from '@fabrika/app'
12
+ import { createRpcClient, type InferRpcClient, RpcError, type RpcFetch } from '@fabrika/app'
13
13
  import { type IssueKeyInput, type IssueKeyResult, MAX_KEY_LIFETIME_SECONDS } from '@fabrika/auth-core'
14
14
  import { APP_ENV_KINDS } from '@fabrika/control-contract'
15
15
  import type {
@@ -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,14 +75,16 @@ 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>
81
82
  fabrika control runs log --run=<id>
82
83
 
83
84
  \`register\` CREATES an app and refuses a second one with the same id. Re-registering a changed
84
- manifest — a new \`zerops.yaml\`, a new import document — is \`apps environments put\`, which replaces
85
- one environment's envelopes and leaves the app row alone.
85
+ manifest — a new import document, or a new \`zerops.yaml\` of an app without a contract — is
86
+ \`apps environments put\`, which replaces one environment's envelopes and leaves the app row alone. A
87
+ contract app's deploy registers the \`zerops.yaml\` of its commit itself.
86
88
 
87
89
  A manifest that publishes the app through the namespace proxy is routed by HOST, so \`--domain\` is
88
90
  REQUIRED for it — on \`register\` and on \`apps environments put\` alike — and a registration without one is
@@ -90,7 +92,9 @@ refused before anything is created. \`namespaces get\` lists the hosts a \`zerop
90
92
  serves and which of them are still free; a custom-domain namespace serves the domain you bound to its
91
93
  proxy. A manifest with no proxy target needs no domain.
92
94
 
93
- A variable's value is stored and printed in clear. A secret's value is write-only: \`apps secrets put\`
95
+ A variable's value is stored and printed in clear, so \`apps variables put\` refuses one that looks like a
96
+ credential (by its name, such as \`*_TOKEN\` or \`*_PASSWORD\`, or by its value) and names \`apps secrets put\` instead.
97
+ \`--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
98
  reads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and
95
99
  one trailing newline is dropped. No command prints it back; \`apps secrets list\` shows names, scope and
96
100
  storage only. Generate one in the pipe:
@@ -108,7 +112,7 @@ repeats: the flags given are the environment's whole list. Each is an exact orig
108
112
  On Zerops the change reaches the namespace proxy at once; on Cloudflare the next deploy of the environment
109
113
  applies it.
110
114
 
111
- \`--installation-id\` has three states: omitted resolves the installation from the organization's
115
+ \`--installation-id\` has three states: omitted resolves the installation from the repository owner's
112
116
  connected GitHub App, \`none\` registers an anonymous PUBLIC repository source, and a number names one
113
117
  installation outright. With \`none\`, control reads the repository once without a token and refuses one
114
118
  GitHub hides: a private repository needs the GitHub App connected in the console first.
@@ -117,7 +121,8 @@ GitHub hides: a private repository needs the GitHub App connected in the console
117
121
  on \`deploy\`. A bare name is a branch: \`--trigger-ref=deploy/prod\` is stored as \`refs/heads/deploy/prod\`.
118
122
  A full ref is kept as given: \`refs/heads/<branch>\`, \`refs/tags/<tag>\`, or a \`*\` glob such as
119
123
  \`refs/tags/v*\`, which deploys every matching tag. A tag always needs the \`refs/tags/\` form. Each
120
- environment of an app needs its own trigger ref.
124
+ environment of an app needs its own trigger ref. Branches named \`fabrika/…\` are reserved for MCP
125
+ workspaces and are never a trigger ref.
121
126
 
122
127
  Namespace placement options, each defaulting to what the preset would choose:
123
128
 
@@ -127,6 +132,11 @@ Namespace placement options, each defaulting to what the preset would choose:
127
132
  SERIOUS is a deliberate choice: a project cannot be downgraded again
128
133
  --public-access=<custom-domain|zerops-subdomain>
129
134
  --exclusive-app=<id> required by, and only by, the \`full\` preset
135
+ --postgres-type=<type> the \`cheap\` preset's shared PostgreSQL; on Zerops postgresql:single@18
136
+ (default) or postgresql:ha@18, which keeps its data through a node loss.
137
+ Fixed once created
138
+ --postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,
139
+ oltp-staging (about $11) or oltp-production (about $72) for HA
130
140
 
131
141
  \`namespaces plan\` is a preview and changes nothing. It prints one \`<path>\\t<value>\` row per field of
132
142
  the plan, keyed by its path in \`--json\`; a multi-line value such as the proxy's descriptor file is shown
@@ -139,6 +149,10 @@ the provider resources it stopped tracking. \`namespaces update --proxy-source=c
139
149
  proxy to the source this control plane deploys new placements from — a placement keeps the one it was created
140
150
  with until you do — and queues the reconcile that rebuilds the proxy from it; a \`failed\` placement accepts it.
141
151
 
152
+ \`namespaces release-claims\` frees the resource names one app environment holds in a placement, which an
153
+ environment or app delete otherwise refuses over. Delete those resources at the provider first: the release
154
+ reads each one back and refuses, naming it, while any still exists. It prints one released key per line.
155
+
142
156
  Every command accepts --json, which prints the procedure's result verbatim.
143
157
 
144
158
  The control origin is not a credential and takes either form:
@@ -176,18 +190,23 @@ interface Flags {
176
190
  /** Every value of every option, in order; `values` keeps the last. Only a repeatable option reads it. */
177
191
  readonly repeated: ReadonlyMap<string, readonly string[]>
178
192
  readonly json: boolean
193
+ /** `--not-secret`: `apps variables put` stores a value that looks like a credential. */
194
+ readonly notSecret: boolean
179
195
  readonly positional: readonly string[]
180
196
  }
181
197
 
182
- /** Split `--key=value` options from positional words; `--json` is the one flag every verb shares. */
198
+ /** Split `--key=value` options from positional words; `--json` is the one flag every verb shares, `--not-secret` the other bare one. */
183
199
  export const parseControlFlags = (argv: readonly string[]): Flags => {
184
200
  const values = new Map<string, string>()
185
201
  const repeated = new Map<string, string[]>()
186
202
  const positional: string[] = []
187
203
  let json = false
204
+ let notSecret = false
188
205
  for (const arg of argv) {
189
206
  if (arg === '--json') {
190
207
  json = true
208
+ } else if (arg === '--not-secret') {
209
+ notSecret = true
191
210
  } else if (arg.startsWith('--')) {
192
211
  const eq = arg.indexOf('=')
193
212
  if (eq === -1) {
@@ -201,7 +220,7 @@ export const parseControlFlags = (argv: readonly string[]): Flags => {
201
220
  positional.push(arg)
202
221
  }
203
222
  }
204
- return { values, repeated, json, positional }
223
+ return { values, repeated, json, notSecret, positional }
205
224
  }
206
225
 
207
226
  const required = (flags: Flags, name: string): string => {
@@ -239,26 +258,6 @@ const positiveInteger = (raw: string, name: string): number => {
239
258
  return parsed
240
259
  }
241
260
 
242
- /**
243
- * An origin from the flag, else the environment. Trailing slashes are dropped so paths concatenate.
244
- *
245
- * `label` names WHICH origin is missing: `key issue` reaches IAM, not the control plane, and a message
246
- * that says "Control origin" while asking for `--iam-url` sends the operator to the wrong variable.
247
- */
248
- const origin = (
249
- flags: Flags,
250
- flag: string,
251
- variable: string,
252
- env: Readonly<Record<string, string | undefined>>,
253
- label: string,
254
- ): string => {
255
- const value = flags.values.get(flag) ?? env[variable]
256
- if (value === undefined || value.trim() === '') {
257
- throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
258
- }
259
- return value.trim().replace(/\/+$/, '')
260
- }
261
-
262
261
  const secret = (variable: string, env: Readonly<Record<string, string | undefined>>): string => {
263
262
  const value = env[variable]
264
263
  if (value === undefined || value.trim() === '') {
@@ -268,21 +267,121 @@ const secret = (variable: string, env: Readonly<Record<string, string | undefine
268
267
  }
269
268
 
270
269
  /** 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>
270
+ export type ControlClient = InferRpcClient<ControlRpcContract>
271
+
272
+ /** 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`. */
273
+ const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
274
+
275
+ /** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
276
+ interface OriginSource {
277
+ readonly label: string
278
+ readonly flag: string
279
+ readonly variable: string
280
+ readonly hint?: string
281
+ }
282
+
283
+ const CONTROL_ORIGIN: OriginSource = { label: 'Control', flag: 'url', variable: 'FABRIKA_CONTROL_URL' }
284
+
285
+ const IAM_ORIGIN: OriginSource = {
286
+ label: 'IAM',
287
+ flag: 'iam-url',
288
+ variable: 'FABRIKA_IAM_RPC_URL',
289
+ hint: "It is IAM's PUBLIC https origin (control's FABRIKA_IAM_ISSUER): a private hostname such as `http://iam:3000` answers only "
290
+ + "inside the provider's project, never from this machine.",
291
+ }
292
+
293
+ /**
294
+ * An origin a credential is sent to, checked before the credential goes anywhere: https, or http to a loopback host for
295
+ * local development, and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
296
+ */
297
+ export const credentialOrigin = (raw: string | undefined, source: OriginSource): string => {
298
+ const { label, flag, variable } = source
299
+ if (raw === undefined || raw.trim() === '') {
300
+ throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
301
+ }
302
+ const refuse = (reason: string): Error => new Error(source.hint === undefined ? reason : `${reason}. ${source.hint}`)
303
+ let url: URL
304
+ try {
305
+ url = new URL(raw.trim())
306
+ } catch {
307
+ throw refuse(`--${flag} or ${variable} is not a URL`)
308
+ }
309
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) {
310
+ throw refuse(`--${flag} or ${variable} must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]`)
311
+ }
312
+ if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
313
+ throw refuse(`--${flag} or ${variable} must be an origin only: no credentials, path, query or fragment`)
314
+ }
315
+ return url.origin
316
+ }
317
+
318
+ const KEY_LABEL = '[FABRIKA_CONTROL_KEY]'
319
+
320
+ /** `text` with the control key cut out: every diagnostic of an area that holds the key passes through it. */
321
+ export const withoutControlKey = (text: string, env: Readonly<Record<string, string | undefined>>): string => {
322
+ const key = env['FABRIKA_CONTROL_KEY']?.trim()
323
+ return key === undefined || key === '' ? text : text.replaceAll(key, KEY_LABEL)
324
+ }
272
325
 
273
- const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => {
274
- const base = origin(flags, 'url', 'FABRIKA_CONTROL_URL', env, 'Control')
326
+ /** Whether a JSON body holds `key`, also behind JSON escapes, which a plain search of the text would miss. */
327
+ const carriesKey = (text: string, key: string): boolean => {
328
+ if (text.includes(key)) return true
329
+ try {
330
+ return JSON.stringify(JSON.parse(text)).includes(JSON.stringify(key).slice(1, -1))
331
+ } catch {
332
+ return false
333
+ }
334
+ }
335
+
336
+ /**
337
+ * A JSON answer that carries the key is dropped whole, so no row, `--json` output or error can repeat it. Any other
338
+ * body passes: the RPC client reports a non-JSON answer by its status alone.
339
+ */
340
+ const withoutEchoedKey = async (response: Response, key: string): Promise<Response> => {
341
+ if (!(response.headers.get('content-type') ?? '').includes('application/json')) return response
342
+ const text = await response.text()
343
+ if (carriesKey(text, key)) {
344
+ return Response.json({ error: { type: 'transport', message: `Control's answer carried ${KEY_LABEL}; it was dropped` } }, { status: 502 })
345
+ }
346
+ return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
347
+ }
348
+
349
+ /** Control's origin and the fetch that carries FABRIKA_CONTROL_KEY to it. */
350
+ export interface ControlTransport {
351
+ readonly origin: string
352
+ readonly fetch: RpcFetch
353
+ }
354
+
355
+ /**
356
+ * The origin from `url` or FABRIKA_CONTROL_URL, the key from FABRIKA_CONTROL_KEY in the environment only, no redirect
357
+ * followed. Every client of the console's origin is built on it.
358
+ */
359
+ export const controlTransport = (
360
+ url: string | undefined,
361
+ env: Readonly<Record<string, string | undefined>>,
362
+ send: RpcFetch = fetch,
363
+ ): ControlTransport => {
364
+ const origin = credentialOrigin(url ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
275
365
  const key = secret('FABRIKA_CONTROL_KEY', env)
276
- return createRpcClient<ControlRpcContract>({
277
- baseUrl: `${base}/api/rpc`,
278
- fetch: (input, init) => {
366
+ return {
367
+ origin,
368
+ fetch: async (input, init) => {
279
369
  const headers = new Headers(init?.headers)
280
370
  headers.set('authorization', `Bearer ${key}`)
281
- return fetch(input, { ...init, headers })
371
+ // A redirect would carry the bearer to wherever it points.
372
+ return await withoutEchoedKey(await send(input, { ...init, headers, redirect: 'manual' }), key)
282
373
  },
283
- })
374
+ }
375
+ }
376
+
377
+ /** The one client of Control that `fabrika control`, `fabrika env` and `fabrika operations` share. */
378
+ export const connectControl = (url: string | undefined, env: Readonly<Record<string, string | undefined>>): ControlClient => {
379
+ const transport = controlTransport(url, env)
380
+ return createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch })
284
381
  }
285
382
 
383
+ const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => connectControl(flags.values.get('url'), env)
384
+
286
385
  const readJsonFile = async (path: string): Promise<JsonValue> => {
287
386
  const file = Bun.file(path)
288
387
  if (!(await file.exists())) {
@@ -329,32 +428,16 @@ const appLine = (app: AppDto): string => `${app.id}\t${app.repoUrl}\t${app.defau
329
428
 
330
429
  const runLine = (run: RunDto): string => `${run.id}\t${run.appId}\t${run.env}\t${run.status}\t${run.ref}`
331
430
 
332
- /** How the IAM origin was supplied, for a message that must not echo the value itself. */
333
- const IAM_ORIGIN_SOURCE = '--iam-url / FABRIKA_IAM_RPC_URL'
334
-
335
431
  /**
336
432
  * The one `key issue` failure whose cause is almost always the address itself.
337
433
  *
338
- * `fetch` rejects only when the request never completed, so this reports what could not be reached and
339
- * the mistake that produces it. Only the PARSED origin is named: an operator may put userinfo in the
340
- * value, and `new URL().origin` drops it. A value that does not parse is not echoed at all — the
341
- * variable is named instead. The cause object may quote anything, so only its short error code is.
434
+ * `fetch` rejects only when the request never completed, so this reports what could not be reached and the mistake that
435
+ * produces it. The cause object may quote anything, so only its short error code is.
342
436
  */
343
- const unreachableIam = (base: string, cause: unknown): string => {
437
+ const unreachableIam = (origin: string, cause: unknown): string => {
344
438
  const code = typeof cause === 'object' && cause !== null ? Reflect.get(cause, 'code') : undefined
345
439
  const reason = typeof code === 'string' && code !== '' && code.length <= 40 ? code : 'the connection failed'
346
- let parsed: string | undefined
347
- try {
348
- parsed = new URL(base).origin
349
- } catch {
350
- parsed = undefined
351
- }
352
- if (parsed === undefined || parsed === 'null' || code === 'ERR_INVALID_URL') {
353
- return `${IAM_ORIGIN_SOURCE} is not a URL — it needs the \`https://\` scheme and IAM's PUBLIC host, `
354
- + 'shaped `https://<iam-host>`.'
355
- }
356
- return `IAM could not be reached at ${parsed} (${reason}). ${IAM_ORIGIN_SOURCE} must be IAM's PUBLIC origin: `
357
- + "a private hostname such as `http://iam:3000` answers only inside the provider's project, never from this machine."
440
+ return `IAM could not be reached at ${origin} (${reason}). ${IAM_ORIGIN.hint}`
358
441
  }
359
442
 
360
443
  const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
@@ -374,14 +457,19 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
374
457
  label: required(flags, 'label'),
375
458
  expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
376
459
  }
377
- const base = origin(flags, 'iam-url', 'FABRIKA_IAM_RPC_URL', env, 'IAM')
460
+ const base = credentialOrigin(flags.values.get('iam-url') ?? env['FABRIKA_IAM_RPC_URL'], IAM_ORIGIN)
378
461
  const response = await fetch(`${base}/rpc/issueKey`, {
379
462
  method: 'POST',
380
463
  headers: { authorization: `Bearer ${secret('FABRIKA_IAM_RPC_KEY', env)}`, 'content-type': 'application/json' },
381
464
  body: JSON.stringify(body),
465
+ // A followed 307/308 would re-send the provisioning key to wherever it points.
466
+ redirect: 'manual',
382
467
  }).catch((cause: unknown) => {
383
468
  throw new Error(unreachableIam(base, cause))
384
469
  })
470
+ if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {
471
+ throw new Error(`IAM answered with a redirect (HTTP ${response.status}), which is not followed. ${IAM_ORIGIN.hint}`)
472
+ }
385
473
  if (!response.ok) {
386
474
  // The body can quote what came off the wire, so report the status and nothing else.
387
475
  throw new Error(`IAM refused the issue request: HTTP ${response.status}`)
@@ -632,6 +720,7 @@ const runVariables = async (verb: string | undefined, flags: Flags, env: Readonl
632
720
  name: required(flags, 'name'),
633
721
  value: required(flags, 'value'),
634
722
  ...(scope === undefined ? {} : { env: scope }),
723
+ ...(flags.notSecret ? { notSecret: true } : {}),
635
724
  }
636
725
  const result = await client.apps.variables.put({ appId, variable })
637
726
  emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\t${result.value}`)
@@ -839,6 +928,11 @@ const namespacePlan = (flags: Flags): PlanDeploymentNamespaceRequest => {
839
928
  if (project !== undefined) options['projectName'] = project
840
929
  if (corePackage !== undefined) options['corePackage'] = corePackage
841
930
  if (publicAccess !== undefined) options['publicAccess'] = publicAccess
931
+ const postgresType = optional(flags, 'postgres-type')
932
+ const postgresProfile = optional(flags, 'postgres-profile')
933
+ // Together or not at all: a type without a profile gets the platform's default, which for HA is the dedicated ~$72 one.
934
+ if ((postgresType === undefined) !== (postgresProfile === undefined)) throw new Error('--postgres-type and --postgres-profile go together')
935
+ if (postgresType !== undefined && postgresProfile !== undefined) options['postgres'] = { type: postgresType, profile: postgresProfile }
842
936
  return {
843
937
  id: required(flags, 'namespace'),
844
938
  env: required(flags, 'env'),
@@ -884,6 +978,15 @@ const runNamespaces = async (verb: string | undefined, flags: Flags, env: Readon
884
978
  emit(flags, result, () => namespaceLine(result.removed))
885
979
  return
886
980
  }
981
+ if (verb === 'release-claims') {
982
+ const result = await client.namespaces.releaseClaims({
983
+ namespaceId: required(flags, 'namespace'),
984
+ appId: required(flags, 'app'),
985
+ env: required(flags, 'env'),
986
+ })
987
+ emit(flags, result, () => result.released.map((key) => `released\t${key}`).join('\n'))
988
+ return
989
+ }
887
990
  if (verb === 'update') {
888
991
  const namespaceId = required(flags, 'namespace')
889
992
  if (required(flags, 'proxy-source') !== 'current') {
@@ -938,9 +1041,9 @@ export const runControlCli = async (
938
1041
  env: Readonly<Record<string, string | undefined>> = process.env,
939
1042
  input: SecretValueInput = processStdin,
940
1043
  ): Promise<void> => {
941
- const flags = parseControlFlags(argv)
942
- const verb = flags.positional[0]
943
1044
  try {
1045
+ const flags = parseControlFlags(argv)
1046
+ const verb = flags.positional[0]
944
1047
  switch (command) {
945
1048
  case undefined:
946
1049
  console.info(USAGE)
@@ -970,7 +1073,8 @@ export const runControlCli = async (
970
1073
  } catch (error) {
971
1074
  // An RPC denial is an ANSWER, not a transport fault; keep its type so a caller can tell "the
972
1075
  // control plane said no" from "the control plane was unreachable".
973
- throw error instanceof RpcError ? new Error(`${error.type}: ${error.message}`) : error
1076
+ const message = error instanceof RpcError ? `${error.type}: ${error.message}` : error instanceof Error ? error.message : String(error)
1077
+ throw new Error(withoutControlKey(message, env))
974
1078
  }
975
1079
  }
976
1080