@fabrika/cli 0.9.0-dev.2 → 0.9.0-dev.20

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