@fabrika/cli 0.9.0-dev.4 → 0.9.0-dev.41

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,9 +9,9 @@
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
- import { APP_ENV_KINDS } from '@fabrika/control-contract'
14
+ import { APP_ENV_KINDS, CONTROL_CLI_PRESETS } from '@fabrika/control-contract'
15
15
  import type {
16
16
  AppDto,
17
17
  AppEnvDto,
@@ -31,6 +31,16 @@ import type {
31
31
  RunDto,
32
32
  } from '@fabrika/control-contract'
33
33
  import { z } from 'zod'
34
+ import {
35
+ authorizeDevice,
36
+ controlOAuthBearer,
37
+ type ControlOAuthDependencies,
38
+ controlResourceFor,
39
+ CREDENTIAL_HELPER_VARIABLE,
40
+ defaultControlOAuthDependencies,
41
+ parseControlCliPreset,
42
+ } from './control-oauth.js'
43
+ import { credentialOrigin, type OriginSource } from './credential-origin.js'
34
44
 
35
45
  const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
36
46
  z.union([z.null(), z.string(), z.number(), z.boolean(), z.array(jsonValueSchema), z.record(jsonValueSchema)])
@@ -52,6 +62,7 @@ const issueKeyResultSchema = z.union([
52
62
  const USAGE = `fabrika control — operate the Delivery control plane
53
63
 
54
64
  Usage:
65
+ fabrika control auth device --preset=<read|deploy|operate|create> [--app=<id>]
55
66
  fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]
56
67
  fabrika control apps list
57
68
  fabrika control apps get --app=<id>
@@ -59,8 +70,10 @@ Usage:
59
70
  fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>
60
71
  [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]
61
72
  [--cross-origin=<origin> ...] [--kind=standard|dev]
73
+ fabrika control apps environments suspend --app=<id> --env=<name>
74
+ fabrika control apps environments resume --app=<id> --env=<name>
62
75
  fabrika control apps variables list --app=<id>
63
- fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>]
76
+ fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret]
64
77
  fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]
65
78
  fabrika control apps secrets list --app=<id>
66
79
  fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)
@@ -75,14 +88,16 @@ Usage:
75
88
  fabrika control namespaces reconcile --namespace=<id>
76
89
  fabrika control namespaces update --namespace=<id> --proxy-source=current
77
90
  fabrika control namespaces remove --namespace=<id>
91
+ fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>
78
92
  fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]
79
93
  fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]
80
94
  fabrika control runs get --run=<id>
81
95
  fabrika control runs log --run=<id>
82
96
 
83
97
  \`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.
98
+ manifest — a new import document, or a new \`zerops.yaml\` of an app without a contract — is
99
+ \`apps environments put\`, which replaces one environment's envelopes and leaves the app row alone. A
100
+ contract app's deploy registers the \`zerops.yaml\` of its commit itself.
86
101
 
87
102
  A manifest that publishes the app through the namespace proxy is routed by HOST, so \`--domain\` is
88
103
  REQUIRED for it — on \`register\` and on \`apps environments put\` alike — and a registration without one is
@@ -90,7 +105,16 @@ refused before anything is created. \`namespaces get\` lists the hosts a \`zerop
90
105
  serves and which of them are still free; a custom-domain namespace serves the domain you bound to its
91
106
  proxy. A manifest with no proxy target needs no domain.
92
107
 
93
- A variable's value is stored and printed in clear. A secret's value is write-only: \`apps secrets put\`
108
+ \`apps environments suspend\` takes an environment offline in an incident, such as a compromised or leaked application.
109
+ Behind a Zerops namespace proxy every request to it answers 503 once the republished proxy is live, which takes the
110
+ minutes of a proxy build; \`namespaces get\` follows it. A namespace pinned to an older proxy source is refused with the
111
+ re-pin to run first. On Cloudflare the environment's object goes into maintenance \`closed\`. \`resume\` restores the
112
+ routing it had, or on Cloudflare the maintenance mode it was in. Neither stops the application's service, nor
113
+ revokes a key. Repeating either is a retry.
114
+
115
+ A variable's value is stored and printed in clear, so \`apps variables put\` refuses one that looks like a
116
+ credential (by its name, such as \`*_TOKEN\` or \`*_PASSWORD\`, or by its value) and names \`apps secrets put\` instead.
117
+ \`--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
118
  reads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and
95
119
  one trailing newline is dropped. No command prints it back; \`apps secrets list\` shows names, scope and
96
120
  storage only. Generate one in the pipe:
@@ -108,7 +132,7 @@ repeats: the flags given are the environment's whole list. Each is an exact orig
108
132
  On Zerops the change reaches the namespace proxy at once; on Cloudflare the next deploy of the environment
109
133
  applies it.
110
134
 
111
- \`--installation-id\` has three states: omitted resolves the installation from the organization's
135
+ \`--installation-id\` has three states: omitted resolves the installation from the repository owner's
112
136
  connected GitHub App, \`none\` registers an anonymous PUBLIC repository source, and a number names one
113
137
  installation outright. With \`none\`, control reads the repository once without a token and refuses one
114
138
  GitHub hides: a private repository needs the GitHub App connected in the console first.
@@ -117,7 +141,8 @@ GitHub hides: a private repository needs the GitHub App connected in the console
117
141
  on \`deploy\`. A bare name is a branch: \`--trigger-ref=deploy/prod\` is stored as \`refs/heads/deploy/prod\`.
118
142
  A full ref is kept as given: \`refs/heads/<branch>\`, \`refs/tags/<tag>\`, or a \`*\` glob such as
119
143
  \`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.
144
+ environment of an app needs its own trigger ref. Branches named \`fabrika/…\` are reserved for MCP
145
+ workspaces and are never a trigger ref.
121
146
 
122
147
  Namespace placement options, each defaulting to what the preset would choose:
123
148
 
@@ -127,6 +152,11 @@ Namespace placement options, each defaulting to what the preset would choose:
127
152
  SERIOUS is a deliberate choice: a project cannot be downgraded again
128
153
  --public-access=<custom-domain|zerops-subdomain>
129
154
  --exclusive-app=<id> required by, and only by, the \`full\` preset
155
+ --postgres-type=<type> the \`cheap\` preset's shared PostgreSQL; on Zerops postgresql:single@18
156
+ (default) or postgresql:ha@18, which keeps its data through a node loss.
157
+ Fixed once created
158
+ --postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,
159
+ oltp-staging (about $11) or oltp-production (about $72) for HA
130
160
 
131
161
  \`namespaces plan\` is a preview and changes nothing. It prints one \`<path>\\t<value>\` row per field of
132
162
  the plan, keyed by its path in \`--json\`; a multi-line value such as the proxy's descriptor file is shown
@@ -139,6 +169,10 @@ the provider resources it stopped tracking. \`namespaces update --proxy-source=c
139
169
  proxy to the source this control plane deploys new placements from — a placement keeps the one it was created
140
170
  with until you do — and queues the reconcile that rebuilds the proxy from it; a \`failed\` placement accepts it.
141
171
 
172
+ \`namespaces release-claims\` frees the resource names one app environment holds in a placement, which an
173
+ environment or app delete otherwise refuses over. Delete those resources at the provider first: the release
174
+ reads each one back and refuses, naming it, while any still exists. It prints one released key per line.
175
+
142
176
  Every command accepts --json, which prints the procedure's result verbatim.
143
177
 
144
178
  The control origin is not a credential and takes either form:
@@ -146,9 +180,27 @@ The control origin is not a credential and takes either form:
146
180
  --url=<origin> FABRIKA_CONTROL_URL
147
181
 
148
182
  Credentials are read from the ENVIRONMENT ONLY and have no flag, so they cannot reach a CI log or a
149
- process listing:
183
+ process listing. One of:
184
+
185
+ FABRIKA_CONTROL_KEY a machine \`px_\` credential for the control app; it wins when both are set
186
+ FABRIKA_CONTROL_CREDENTIAL_HELPER a command with \`get\` and \`store\` that holds the refresh token of a
187
+ \`control auth device\` grant (below)
188
+
189
+ \`auth device\` asks IAM for a grant a person approves in the browser (RFC 8628). It prints the page and the
190
+ code on stderr and waits; the person signs in, checks the code, and picks how long the grant lasts (an hour, a
191
+ day or a week). The grant holds the preset's actions at one application, never more than that person may:
192
+
193
+ read deploy.read, data.read, operations.read
194
+ deploy read, and deploy.trigger
195
+ operate deploy, secret.manage, app.manage and operations.triage
196
+ create app.manage wherever the person holds it, with no --app: it also changes and deletes apps
150
197
 
151
- FABRIKA_CONTROL_KEY required a machine \`px_\` credential for the control app
198
+ The refresh token goes to the helper and nowhere else: the helper runs as \`sh -c '<helper> get|store'\`,
199
+ reads \`origin=<console origin>\` (and, for \`store\`, \`refresh_token=<token>\`) on stdin, and \`get\` prints
200
+ \`refresh_token=<token>\`, or nothing. Every call then trades it for a short-lived access token, and IAM
201
+ rotates it each time; a lock under $XDG_CACHE_HOME/fabrika (~/.cache/fabrika when unset) serializes that
202
+ between processes on this machine. If a refresh's answer is lost, the stored token is spent and the next
203
+ call says to run \`auth device\` again.
152
204
 
153
205
  \`key issue\` mints that credential and therefore authenticates differently — it presents the
154
206
  installation's IAM RPC key as transport authentication and its provisioning key as the ISSUING
@@ -176,18 +228,23 @@ interface Flags {
176
228
  /** Every value of every option, in order; `values` keeps the last. Only a repeatable option reads it. */
177
229
  readonly repeated: ReadonlyMap<string, readonly string[]>
178
230
  readonly json: boolean
231
+ /** `--not-secret`: `apps variables put` stores a value that looks like a credential. */
232
+ readonly notSecret: boolean
179
233
  readonly positional: readonly string[]
180
234
  }
181
235
 
182
- /** Split `--key=value` options from positional words; `--json` is the one flag every verb shares. */
236
+ /** Split `--key=value` options from positional words; `--json` is the one flag every verb shares, `--not-secret` the other bare one. */
183
237
  export const parseControlFlags = (argv: readonly string[]): Flags => {
184
238
  const values = new Map<string, string>()
185
239
  const repeated = new Map<string, string[]>()
186
240
  const positional: string[] = []
187
241
  let json = false
242
+ let notSecret = false
188
243
  for (const arg of argv) {
189
244
  if (arg === '--json') {
190
245
  json = true
246
+ } else if (arg === '--not-secret') {
247
+ notSecret = true
191
248
  } else if (arg.startsWith('--')) {
192
249
  const eq = arg.indexOf('=')
193
250
  if (eq === -1) {
@@ -201,7 +258,7 @@ export const parseControlFlags = (argv: readonly string[]): Flags => {
201
258
  positional.push(arg)
202
259
  }
203
260
  }
204
- return { values, repeated, json, positional }
261
+ return { values, repeated, json, notSecret, positional }
205
262
  }
206
263
 
207
264
  const required = (flags: Flags, name: string): string => {
@@ -239,26 +296,6 @@ const positiveInteger = (raw: string, name: string): number => {
239
296
  return parsed
240
297
  }
241
298
 
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
299
  const secret = (variable: string, env: Readonly<Record<string, string | undefined>>): string => {
263
300
  const value = env[variable]
264
301
  if (value === undefined || value.trim() === '') {
@@ -268,21 +305,123 @@ const secret = (variable: string, env: Readonly<Record<string, string | undefine
268
305
  }
269
306
 
270
307
  /** 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>
272
-
273
- const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => {
274
- const base = origin(flags, 'url', 'FABRIKA_CONTROL_URL', env, 'Control')
275
- const key = secret('FABRIKA_CONTROL_KEY', env)
276
- return createRpcClient<ControlRpcContract>({
277
- baseUrl: `${base}/api/rpc`,
278
- fetch: (input, init) => {
308
+ export type ControlClient = InferRpcClient<ControlRpcContract>
309
+
310
+ const CONTROL_ORIGIN: OriginSource = { label: 'Control', flag: 'url', variable: 'FABRIKA_CONTROL_URL' }
311
+
312
+ const IAM_ORIGIN: OriginSource = {
313
+ label: 'IAM',
314
+ flag: 'iam-url',
315
+ variable: 'FABRIKA_IAM_RPC_URL',
316
+ hint: "It is IAM's PUBLIC https origin (control's FABRIKA_IAM_ISSUER): a private hostname such as `http://iam:3000` answers only "
317
+ + "inside the provider's project, never from this machine.",
318
+ }
319
+
320
+ const KEY_LABEL = '[FABRIKA_CONTROL_KEY]'
321
+
322
+ /** `text` with the control key cut out: every diagnostic of an area that holds the key passes through it. */
323
+ export const withoutControlKey = (text: string, env: Readonly<Record<string, string | undefined>>): string => {
324
+ const key = env['FABRIKA_CONTROL_KEY']?.trim()
325
+ return key === undefined || key === '' ? text : text.replaceAll(key, KEY_LABEL)
326
+ }
327
+
328
+ /** Whether a JSON body holds `key`, also behind JSON escapes, which a plain search of the text would miss. */
329
+ const carriesKey = (text: string, key: string): boolean => {
330
+ if (text.includes(key)) return true
331
+ try {
332
+ return JSON.stringify(JSON.parse(text)).includes(JSON.stringify(key).slice(1, -1))
333
+ } catch {
334
+ return false
335
+ }
336
+ }
337
+
338
+ /**
339
+ * A JSON answer that carries the key is dropped whole, so no row, `--json` output or error can repeat it. Any other
340
+ * body passes: the RPC client reports a non-JSON answer by its status alone.
341
+ */
342
+ const withoutEchoedKey = async (response: Response, key: string): Promise<Response> => {
343
+ if (!(response.headers.get('content-type') ?? '').includes('application/json')) return response
344
+ const text = await response.text()
345
+ if (carriesKey(text, key)) {
346
+ return Response.json({ error: { type: 'transport', message: `Control's answer carried ${KEY_LABEL}; it was dropped` } }, { status: 502 })
347
+ }
348
+ return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
349
+ }
350
+
351
+ /** Control's origin and the fetch that carries the Control credential to it. */
352
+ export interface ControlTransport {
353
+ readonly origin: string
354
+ readonly fetch: RpcFetch
355
+ /** The credential is a person's device grant, not FABRIKA_CONTROL_KEY. */
356
+ readonly grant: boolean
357
+ }
358
+
359
+ /** Neither credential is set; both are read from the environment only. */
360
+ export const MISSING_CONTROL_CREDENTIAL = `FABRIKA_CONTROL_KEY is required (environment only — it has no flag), or ${CREDENTIAL_HELPER_VARIABLE} `
361
+ + 'after `fabrika control auth device`.'
362
+
363
+ /**
364
+ * The bearer for one request: FABRIKA_CONTROL_KEY when it is set, else an access token for the resource the request
365
+ * calls, refreshed through the grant the credential helper holds.
366
+ */
367
+ const controlBearer = (
368
+ origin: string,
369
+ env: Readonly<Record<string, string | undefined>>,
370
+ send: RpcFetch,
371
+ oauth: ControlOAuthDependencies | undefined,
372
+ ): (input: RequestInfo | URL) => Promise<string> => {
373
+ const key = env['FABRIKA_CONTROL_KEY']?.trim()
374
+ if (key !== undefined && key !== '') return () => Promise.resolve(key)
375
+ const helper = env[CREDENTIAL_HELPER_VARIABLE]?.trim()
376
+ if (helper === undefined || helper === '') throw new Error(MISSING_CONTROL_CREDENTIAL)
377
+ const bearer = controlOAuthBearer(origin, oauth ?? defaultControlOAuthDependencies(helper, env, send))
378
+ return (input) => bearer(controlResourceFor(origin, input))
379
+ }
380
+
381
+ /**
382
+ * The origin from `url` or FABRIKA_CONTROL_URL, the credential from the environment only, no redirect followed. Every
383
+ * client of the console's origin is built on it.
384
+ */
385
+ export const controlTransport = (
386
+ url: string | undefined,
387
+ env: Readonly<Record<string, string | undefined>>,
388
+ send: RpcFetch = fetch,
389
+ oauth?: ControlOAuthDependencies,
390
+ ): ControlTransport => {
391
+ const origin = credentialOrigin(url ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
392
+ const bearer = controlBearer(origin, env, send, oauth)
393
+ return {
394
+ origin,
395
+ grant: (env['FABRIKA_CONTROL_KEY']?.trim() ?? '') === '',
396
+ fetch: async (input, init) => {
397
+ let token: string
398
+ try {
399
+ token = await bearer(input)
400
+ } catch (error) {
401
+ // The RPC client reads a rejected fetch as "Network request failed"; this answer keeps the reason.
402
+ const message = error instanceof Error ? error.message : 'the Control credential could not be obtained'
403
+ return Response.json({ error: { type: 'credential', message } }, { status: 401 })
404
+ }
279
405
  const headers = new Headers(init?.headers)
280
- headers.set('authorization', `Bearer ${key}`)
281
- return fetch(input, { ...init, headers })
406
+ headers.set('authorization', `Bearer ${token}`)
407
+ // A redirect would carry the bearer to wherever it points.
408
+ return await withoutEchoedKey(await send(input, { ...init, headers, redirect: 'manual' }), token)
282
409
  },
283
- })
410
+ }
411
+ }
412
+
413
+ /** The one client of Control that `fabrika control`, `fabrika env` and `fabrika operations` share. */
414
+ export const connectControl = (
415
+ url: string | undefined,
416
+ env: Readonly<Record<string, string | undefined>>,
417
+ oauth?: ControlOAuthDependencies,
418
+ ): ControlClient => {
419
+ const transport = controlTransport(url, env, fetch, oauth)
420
+ return createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch })
284
421
  }
285
422
 
423
+ const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => connectControl(flags.values.get('url'), env)
424
+
286
425
  const readJsonFile = async (path: string): Promise<JsonValue> => {
287
426
  const file = Bun.file(path)
288
427
  if (!(await file.exists())) {
@@ -329,32 +468,16 @@ const appLine = (app: AppDto): string => `${app.id}\t${app.repoUrl}\t${app.defau
329
468
 
330
469
  const runLine = (run: RunDto): string => `${run.id}\t${run.appId}\t${run.env}\t${run.status}\t${run.ref}`
331
470
 
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
471
  /**
336
472
  * The one `key issue` failure whose cause is almost always the address itself.
337
473
  *
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.
474
+ * `fetch` rejects only when the request never completed, so this reports what could not be reached and the mistake that
475
+ * produces it. The cause object may quote anything, so only its short error code is.
342
476
  */
343
- const unreachableIam = (base: string, cause: unknown): string => {
477
+ const unreachableIam = (origin: string, cause: unknown): string => {
344
478
  const code = typeof cause === 'object' && cause !== null ? Reflect.get(cause, 'code') : undefined
345
479
  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."
480
+ return `IAM could not be reached at ${origin} (${reason}). ${IAM_ORIGIN.hint}`
358
481
  }
359
482
 
360
483
  const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
@@ -374,14 +497,19 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
374
497
  label: required(flags, 'label'),
375
498
  expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
376
499
  }
377
- const base = origin(flags, 'iam-url', 'FABRIKA_IAM_RPC_URL', env, 'IAM')
500
+ const base = credentialOrigin(flags.values.get('iam-url') ?? env['FABRIKA_IAM_RPC_URL'], IAM_ORIGIN)
378
501
  const response = await fetch(`${base}/rpc/issueKey`, {
379
502
  method: 'POST',
380
503
  headers: { authorization: `Bearer ${secret('FABRIKA_IAM_RPC_KEY', env)}`, 'content-type': 'application/json' },
381
504
  body: JSON.stringify(body),
505
+ // A followed 307/308 would re-send the provisioning key to wherever it points.
506
+ redirect: 'manual',
382
507
  }).catch((cause: unknown) => {
383
508
  throw new Error(unreachableIam(base, cause))
384
509
  })
510
+ if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {
511
+ throw new Error(`IAM answered with a redirect (HTTP ${response.status}), which is not followed. ${IAM_ORIGIN.hint}`)
512
+ }
385
513
  if (!response.ok) {
386
514
  // The body can quote what came off the wire, so report the status and nothing else.
387
515
  throw new Error(`IAM refused the issue request: HTTP ${response.status}`)
@@ -397,6 +525,24 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
397
525
  console.info(flags.json ? JSON.stringify(outcome, null, 2) : outcome.token)
398
526
  }
399
527
 
528
+ const APP_ID = /^[a-z0-9][a-z0-9-]*$/
529
+
530
+ /** `auth device`: the device grant for one preset, stored through the credential helper; nothing goes to stdout. */
531
+ const runAuthDevice = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
532
+ const origin = credentialOrigin(flags.values.get('url') ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
533
+ const raw = required(flags, 'preset')
534
+ const preset = parseControlCliPreset(raw)
535
+ if (preset === null) throw new Error(`--preset must be one of ${CONTROL_CLI_PRESETS.join(', ')}`)
536
+ const app = optional(flags, 'app')
537
+ if (preset === 'create' && app !== undefined) throw new Error('--preset=create holds its action wherever you may, and takes no --app')
538
+ if (preset !== 'create' && (app === undefined || !APP_ID.test(app))) throw new Error(`--preset=${preset} needs --app=<application id>`)
539
+ const helper = env[CREDENTIAL_HELPER_VARIABLE]?.trim()
540
+ if (helper === undefined || helper === '') {
541
+ throw new Error(`${CREDENTIAL_HELPER_VARIABLE} is required: the refresh token is stored through it and never printed`)
542
+ }
543
+ await authorizeDevice({ origin, preset, ...(app === undefined ? {} : { app }) }, defaultControlOAuthDependencies(helper, env, fetch))
544
+ }
545
+
400
546
  const decodeIssueKeyResult = (value: unknown): IssueKeyResult => {
401
547
  const result = issueKeyResultSchema.safeParse(value)
402
548
  if (!result.success) {
@@ -595,6 +741,17 @@ const runEnvironments = async (
595
741
  emit(flags, result, () => `${result.appId}\t${result.env}\t${result.provider}`)
596
742
  return
597
743
  }
744
+ if (verb === 'suspend' || verb === 'resume') {
745
+ const target = { appId: required(flags, 'app'), env: required(flags, 'env') }
746
+ const result = verb === 'suspend' ? await client.apps.environments.suspend(target) : await client.apps.environments.resume(target)
747
+ if (result.namespaceId !== null) {
748
+ console.warn(
749
+ `the proxy of namespace ${result.namespaceId} is rebuilding; follow it: fabrika control namespaces get --namespace=${result.namespaceId}`,
750
+ )
751
+ }
752
+ emit(flags, result, () => `${result.appId}\t${result.env}\t${result.suspendedAt === undefined ? 'serving' : 'suspended'}`)
753
+ return
754
+ }
598
755
  throw new Error(`Unknown \`control apps environments\` verb: ${verb ?? '(missing)'}`)
599
756
  }
600
757
 
@@ -632,6 +789,7 @@ const runVariables = async (verb: string | undefined, flags: Flags, env: Readonl
632
789
  name: required(flags, 'name'),
633
790
  value: required(flags, 'value'),
634
791
  ...(scope === undefined ? {} : { env: scope }),
792
+ ...(flags.notSecret ? { notSecret: true } : {}),
635
793
  }
636
794
  const result = await client.apps.variables.put({ appId, variable })
637
795
  emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\t${result.value}`)
@@ -839,6 +997,11 @@ const namespacePlan = (flags: Flags): PlanDeploymentNamespaceRequest => {
839
997
  if (project !== undefined) options['projectName'] = project
840
998
  if (corePackage !== undefined) options['corePackage'] = corePackage
841
999
  if (publicAccess !== undefined) options['publicAccess'] = publicAccess
1000
+ const postgresType = optional(flags, 'postgres-type')
1001
+ const postgresProfile = optional(flags, 'postgres-profile')
1002
+ // Together or not at all: a type without a profile gets the platform's default, which for HA is the dedicated ~$72 one.
1003
+ if ((postgresType === undefined) !== (postgresProfile === undefined)) throw new Error('--postgres-type and --postgres-profile go together')
1004
+ if (postgresType !== undefined && postgresProfile !== undefined) options['postgres'] = { type: postgresType, profile: postgresProfile }
842
1005
  return {
843
1006
  id: required(flags, 'namespace'),
844
1007
  env: required(flags, 'env'),
@@ -884,6 +1047,15 @@ const runNamespaces = async (verb: string | undefined, flags: Flags, env: Readon
884
1047
  emit(flags, result, () => namespaceLine(result.removed))
885
1048
  return
886
1049
  }
1050
+ if (verb === 'release-claims') {
1051
+ const result = await client.namespaces.releaseClaims({
1052
+ namespaceId: required(flags, 'namespace'),
1053
+ appId: required(flags, 'app'),
1054
+ env: required(flags, 'env'),
1055
+ })
1056
+ emit(flags, result, () => result.released.map((key) => `released\t${key}`).join('\n'))
1057
+ return
1058
+ }
887
1059
  if (verb === 'update') {
888
1060
  const namespaceId = required(flags, 'namespace')
889
1061
  if (required(flags, 'proxy-source') !== 'current') {
@@ -938,13 +1110,17 @@ export const runControlCli = async (
938
1110
  env: Readonly<Record<string, string | undefined>> = process.env,
939
1111
  input: SecretValueInput = processStdin,
940
1112
  ): Promise<void> => {
941
- const flags = parseControlFlags(argv)
942
- const verb = flags.positional[0]
943
1113
  try {
1114
+ const flags = parseControlFlags(argv)
1115
+ const verb = flags.positional[0]
944
1116
  switch (command) {
945
1117
  case undefined:
946
1118
  console.info(USAGE)
947
1119
  return
1120
+ case 'auth':
1121
+ if (verb !== 'device') throw new Error(`Unknown \`control auth\` verb: ${verb ?? '(missing)'}`)
1122
+ await runAuthDevice(flags, env)
1123
+ return
948
1124
  case 'key':
949
1125
  if (verb !== 'issue') throw new Error(`Unknown \`control key\` verb: ${verb ?? '(missing)'}`)
950
1126
  await runKeyIssue(flags, env)
@@ -970,7 +1146,8 @@ export const runControlCli = async (
970
1146
  } catch (error) {
971
1147
  // An RPC denial is an ANSWER, not a transport fault; keep its type so a caller can tell "the
972
1148
  // control plane said no" from "the control plane was unreachable".
973
- throw error instanceof RpcError ? new Error(`${error.type}: ${error.message}`) : error
1149
+ const message = error instanceof RpcError ? `${error.type}: ${error.message}` : error instanceof Error ? error.message : String(error)
1150
+ throw new Error(withoutControlKey(message, env))
974
1151
  }
975
1152
  }
976
1153
 
@@ -0,0 +1,54 @@
1
+ // The origin check every credential the CLI sends passes before it goes anywhere.
2
+
3
+ /** Plain http may carry a credential to loopback only: 127.0.0.0/8, [::1], and the names RFC 6761 reserves for it, `localhost` and `*.localhost`. */
4
+ const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
5
+
6
+ /** Which origin a check reads, so its refusals name the right flag and variable. `hint` follows a refusal of the value. */
7
+ export interface OriginSource {
8
+ readonly label: string
9
+ readonly flag: string
10
+ readonly variable: string
11
+ readonly hint?: string
12
+ }
13
+
14
+ type OriginCheck = { readonly origin: string } | { readonly refusal: 'not_url' | 'scheme' | 'not_origin' }
15
+
16
+ /** `raw`'s origin when it may carry a credential: https, or http to a loopback host, and nothing but scheme, host and port. */
17
+ function checkOrigin(raw: string): OriginCheck {
18
+ let url: URL
19
+ try {
20
+ url = new URL(raw.trim())
21
+ } catch {
22
+ return { refusal: 'not_url' }
23
+ }
24
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) return { refusal: 'scheme' }
25
+ if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
26
+ return { refusal: 'not_origin' }
27
+ }
28
+ return { origin: url.origin }
29
+ }
30
+
31
+ /** The origin of a value another party published (an authorization server), or null when no credential may go there. */
32
+ export const credentialOriginOf = (raw: string): string | null => {
33
+ const checked = checkOrigin(raw)
34
+ return 'origin' in checked ? checked.origin : null
35
+ }
36
+
37
+ /**
38
+ * An origin a credential is sent to, checked before the credential goes anywhere. A refusal never repeats the value,
39
+ * which may hold userinfo.
40
+ */
41
+ export const credentialOrigin = (raw: string | undefined, source: OriginSource): string => {
42
+ const { label, flag, variable } = source
43
+ if (raw === undefined || raw.trim() === '') {
44
+ throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
45
+ }
46
+ const checked = checkOrigin(raw)
47
+ if ('origin' in checked) return checked.origin
48
+ const reason = {
49
+ not_url: `--${flag} or ${variable} is not a URL`,
50
+ scheme: `--${flag} or ${variable} must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]`,
51
+ not_origin: `--${flag} or ${variable} must be an origin only: no credentials, path, query or fragment`,
52
+ }[checked.refusal]
53
+ throw new Error(source.hint === undefined ? reason : `${reason}. ${source.hint}`)
54
+ }