@fabrika/cli 0.9.0-dev.5 → 0.9.0-dev.51

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,15 +9,31 @@
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'
13
- import { type IssueKeyInput, type IssueKeyResult, MAX_KEY_LIFETIME_SECONDS } from '@fabrika/auth-core'
14
- import { APP_ENV_KINDS } from '@fabrika/control-contract'
12
+ import { createRpcClient, type InferRpcClient, RpcError, type RpcFetch } from '@fabrika/app'
13
+ import {
14
+ displayNameProblem,
15
+ isCimdClientId,
16
+ isOAuthResourceUri,
17
+ type IssueKeyInput,
18
+ type IssueKeyResult,
19
+ MAX_KEY_LIFETIME_SECONDS,
20
+ sha256Hex,
21
+ } from '@fabrika/auth-core'
22
+ import {
23
+ APP_ENV_KINDS,
24
+ APPROVAL_REQUESTED,
25
+ type ApprovalRequestDto,
26
+ approvalRequestedSchema,
27
+ CONTROL_CLI_PRESETS,
28
+ isFinalApprovalRequestState,
29
+ } from '@fabrika/control-contract'
15
30
  import type {
16
31
  AppDto,
17
32
  AppEnvDto,
18
33
  AppEnvKind,
19
34
  AppSecretDto,
20
35
  ControlRpcContract,
36
+ CreateApprovalRequestResponse,
21
37
  DeploymentNamespaceDetailDto,
22
38
  DeploymentNamespaceDto,
23
39
  JsonValue,
@@ -30,7 +46,34 @@ import type {
30
46
  RegisterAppResponse,
31
47
  RunDto,
32
48
  } from '@fabrika/control-contract'
49
+ import {
50
+ type ExternalAppDto,
51
+ type IamAdminRpcContract,
52
+ isHttpsDocumentUrl,
53
+ isOAuthIdentityAppId,
54
+ isOAuthIdentityRoleKey,
55
+ MAX_EXTERNAL_APP_CLIENTS,
56
+ MAX_OAUTH_IDENTITY_ROLES,
57
+ OAUTH_CLIENT_PROVIDERS,
58
+ type OAuthClientDto,
59
+ type PutExternalAppRequest,
60
+ type PutOAuthClientRequest,
61
+ recipientKeyThumbprint,
62
+ type RecipientPublicKey,
63
+ REQUESTED_KEY_JWE,
64
+ } from '@fabrika/iam-contract'
65
+ import { compactDecrypt, exportJWK, generateKeyPair } from 'jose'
33
66
  import { z } from 'zod'
67
+ import {
68
+ authorizeDevice,
69
+ controlOAuthBearer,
70
+ type ControlOAuthDependencies,
71
+ controlResourceFor,
72
+ CREDENTIAL_HELPER_VARIABLE,
73
+ defaultControlOAuthDependencies,
74
+ parseControlCliPreset,
75
+ } from './control-oauth.js'
76
+ import { credentialOrigin, type OriginSource } from './credential-origin.js'
34
77
 
35
78
  const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
36
79
  z.union([z.null(), z.string(), z.number(), z.boolean(), z.array(jsonValueSchema), z.record(jsonValueSchema)])
@@ -52,19 +95,22 @@ const issueKeyResultSchema = z.union([
52
95
  const USAGE = `fabrika control — operate the Delivery control plane
53
96
 
54
97
  Usage:
98
+ fabrika control auth device --preset=<read|deploy|operate|create> [--app=<id>]
55
99
  fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]
56
100
  fabrika control apps list
57
101
  fabrika control apps get --app=<id>
58
102
  fabrika control apps environments list --app=<id>
59
103
  fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>
60
104
  [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]
61
- [--cross-origin=<origin> ...] [--kind=standard|dev]
105
+ [--cross-origin=<origin> ...] [--kind=standard|dev] [--wait]
106
+ fabrika control apps environments suspend --app=<id> --env=<name> [--wait]
107
+ fabrika control apps environments resume --app=<id> --env=<name> [--wait]
62
108
  fabrika control apps variables list --app=<id>
63
- fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>]
64
- fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]
109
+ fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>] [--not-secret] [--request] [--wait]
110
+ fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>] [--request] [--wait]
65
111
  fabrika control apps secrets list --app=<id>
66
- fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] (the value on stdin)
67
- fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>]
112
+ fabrika control apps secrets put --app=<id> --name=<name> [--env=<name>] [--request] [--wait] (the value on stdin)
113
+ fabrika control apps secrets delete --app=<id> --name=<name> [--env=<name>] [--request] [--wait]
68
114
  fabrika control register --provider=<name> --app=<id> --repo=<url> --env=<name> --manifest=<path>
69
115
  [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>]
70
116
  [--namespace=<id>] [--installation-id=<n|none>] [--cross-origin=<origin> ...]
@@ -76,14 +122,22 @@ Usage:
76
122
  fabrika control namespaces update --namespace=<id> --proxy-source=current
77
123
  fabrika control namespaces remove --namespace=<id>
78
124
  fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>
79
- fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]
125
+ fabrika control deploy --app=<id> --env=<name> [--ref=<ref>] [--wait]
80
126
  fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]
81
127
  fabrika control runs get --run=<id>
82
128
  fabrika control runs log --run=<id>
129
+ fabrika control requests get <id> [--wait]
130
+ fabrika control access request-grant --app=<id> --env=<name> --principal=<id> --role=<role>
131
+ [--scope=<dimension>:<value>] --expires-in=<seconds> [--wait]
132
+ fabrika control access request-key --app=<id> --action=<action> [--action=<action>…] --label=<text>
133
+ --expires-in=<seconds> --wait
134
+ fabrika control external-apps list | get <app> | put --file=<app.json> | delete <app> [--iam-url=<origin>]
135
+ fabrika control oauth-clients list | put --file=<client.json> | delete <client id> [--iam-url=<origin>]
83
136
 
84
137
  \`register\` CREATES an app and refuses a second one with the same id. Re-registering a changed
85
- manifest — a new \`zerops.yaml\`, a new import document — is \`apps environments put\`, which replaces
86
- one environment's envelopes and leaves the app row alone.
138
+ manifest — a new import document, or a new \`zerops.yaml\` of an app without a contract — is
139
+ \`apps environments put\`, which replaces one environment's envelopes and leaves the app row alone. A
140
+ contract app's deploy registers the \`zerops.yaml\` of its commit itself.
87
141
 
88
142
  A manifest that publishes the app through the namespace proxy is routed by HOST, so \`--domain\` is
89
143
  REQUIRED for it — on \`register\` and on \`apps environments put\` alike — and a registration without one is
@@ -91,7 +145,16 @@ refused before anything is created. \`namespaces get\` lists the hosts a \`zerop
91
145
  serves and which of them are still free; a custom-domain namespace serves the domain you bound to its
92
146
  proxy. A manifest with no proxy target needs no domain.
93
147
 
94
- A variable's value is stored and printed in clear. A secret's value is write-only: \`apps secrets put\`
148
+ \`apps environments suspend\` takes an environment offline in an incident, such as a compromised or leaked application.
149
+ Behind a Zerops namespace proxy every request to it answers 503 once the republished proxy is live, which takes the
150
+ minutes of a proxy build; \`namespaces get\` follows it. A namespace pinned to an older proxy source is refused with the
151
+ re-pin to run first. On Cloudflare the environment's object goes into maintenance \`closed\`. \`resume\` restores the
152
+ routing it had, or on Cloudflare the maintenance mode it was in. Neither stops the application's service, nor
153
+ revokes a key. Repeating either is a retry.
154
+
155
+ A variable's value is stored and printed in clear, so \`apps variables put\` refuses one that looks like a
156
+ credential (by its name, such as \`*_TOKEN\` or \`*_PASSWORD\`, or by its value) and names \`apps secrets put\` instead.
157
+ \`--not-secret\` stores it anyway, for a value you have checked is not one. A secret's value is write-only: \`apps secrets put\`
95
158
  reads it from STDIN, never from a flag, so it reaches neither shell history nor a process listing, and
96
159
  one trailing newline is dropped. No command prints it back; \`apps secrets list\` shows names, scope and
97
160
  storage only. Generate one in the pipe:
@@ -109,7 +172,7 @@ repeats: the flags given are the environment's whole list. Each is an exact orig
109
172
  On Zerops the change reaches the namespace proxy at once; on Cloudflare the next deploy of the environment
110
173
  applies it.
111
174
 
112
- \`--installation-id\` has three states: omitted resolves the installation from the organization's
175
+ \`--installation-id\` has three states: omitted resolves the installation from the repository owner's
113
176
  connected GitHub App, \`none\` registers an anonymous PUBLIC repository source, and a number names one
114
177
  installation outright. With \`none\`, control reads the repository once without a token and refuses one
115
178
  GitHub hides: a private repository needs the GitHub App connected in the console first.
@@ -118,7 +181,52 @@ GitHub hides: a private repository needs the GitHub App connected in the console
118
181
  on \`deploy\`. A bare name is a branch: \`--trigger-ref=deploy/prod\` is stored as \`refs/heads/deploy/prod\`.
119
182
  A full ref is kept as given: \`refs/heads/<branch>\`, \`refs/tags/<tag>\`, or a \`*\` glob such as
120
183
  \`refs/tags/v*\`, which deploys every matching tag. A tag always needs the \`refs/tags/\` form. Each
121
- environment of an app needs its own trigger ref.
184
+ environment of an app needs its own trigger ref. Branches named \`fabrika/…\` are reserved for MCP
185
+ workspaces and are never a trigger ref.
186
+
187
+ \`deploy\` of a protected environment with \`FABRIKA_CONTROL_KEY\` or a device grant is a request a person approves:
188
+ \`--ref\` names a 40-character commit SHA, by default one merged into the environment's trigger ref (or the default
189
+ branch), and stderr prints the console link the person opens. \`--wait\` follows the run until it succeeds or
190
+ fails, approval being one step on the way, and prints its final row; a refusal or an expiry says so on stderr.
191
+
192
+ \`requests get\` reads one approval request: a change an agent or a key asked a person to approve, by the id its
193
+ creation answered. stderr prints the console link while it waits, and why it did not run once it failed, went stale or
194
+ expired. \`--wait\` reads it again until it is refused, expired, executed, failed or stale, and prints its final row;
195
+ once a person decided it, it stops with an error after 15 minutes without an outcome.
196
+
197
+ \`--request\` on \`apps secrets put|delete\` and \`apps variables put|delete\` does not make the change: it asks a person
198
+ to approve it. Every other verb refuses it. Control stores the request, inert, and stderr prints the console link the person opens; for a secret it
199
+ also prints the value's fingerprint (the first 8 hex characters of its SHA-256, computed here), which the page shows
200
+ beside the value's length, so the person can tell it is the value you sent; when Control's answer names another
201
+ fingerprint, the command fails and says to refuse the request. Control seals the value and stores only that. stdout
202
+ prints the request's id, state and link; \`--wait\` follows it as \`requests get --wait\` does. Without \`--env\` the request
203
+ is for every environment of the app, and every protected one judges it. A secret the provider keeps (a Zerops
204
+ environment) is requested for one \`--env\`.
205
+
206
+ \`access request-grant\` asks a person to give a principal (this agent's own, or another) one role of an application
207
+ environment. It needs \`access.request\` at the app, the role must be one the environment's approved contract declares,
208
+ a membership role takes \`--scope\` with a value of its dimension, and \`--expires-in\` is at most 30 days. An IAM
209
+ administrator of the application approves it at the console link stderr prints; the grant is then theirs, and where
210
+ the application's grants wait for approval, IAM holds it for a second administrator. An environment that does not gate
211
+ an agent's grants (not protected, or \`agent-grants\` off) refuses it: there is nothing to approve there. stdout prints
212
+ the request's id, state and link; \`--wait\` follows it as \`requests get --wait\` does.
213
+
214
+ Without \`--request\`, a write by \`FABRIKA_CONTROL_KEY\` or a device grant on a protected environment meets that
215
+ environment's approval policy (ADR-0083): \`apps secrets\` and \`apps variables\` are \`secrets\` and \`variables\` writes,
216
+ \`apps environments put\` is a \`registry\` write, and \`apps environments suspend|resume\` are \`data\` writes.
217
+ A category set to \`off\` applies the write; \`refuse\` refuses it; \`person\` does not make the change but stores it as a
218
+ request, exactly as \`--request\` does: stdout prints its id, state and link, stderr the fingerprint of a secret, and the
219
+ command exits 75. Hand the person the link; nothing changes until they approve it. \`--wait\` follows the request
220
+ instead, and succeeds only when it executed.
221
+
222
+ \`access request-key\` asks a person for a key holding exact Control actions at one application (each \`--action\`, no
223
+ wildcard), for someone other than this agent, expiring in at most 30 days. It needs \`access.request\` at the app, and
224
+ the protected environments' \`credentialCeiling\` decides whether the key may hold actions this agent does not. It
225
+ makes a key pair in memory, sends only the public key, and prints on stderr the console link and the public key's
226
+ thumbprint, which the page shows: an IAM installation administrator checks it there and approves with a passkey. IAM
227
+ encrypts the key to that public key, and Control hands it out once. \`--wait\` is required: the private key never leaves
228
+ this process, so the key cannot be fetched later; the command waits for the decision, fetches the key, decrypts it, and
229
+ prints it once on stdout. A request that issues no key (refused, expired, failed) fails with why.
122
230
 
123
231
  Namespace placement options, each defaulting to what the preset would choose:
124
232
 
@@ -156,9 +264,27 @@ The control origin is not a credential and takes either form:
156
264
  --url=<origin> FABRIKA_CONTROL_URL
157
265
 
158
266
  Credentials are read from the ENVIRONMENT ONLY and have no flag, so they cannot reach a CI log or a
159
- process listing:
267
+ process listing. One of:
268
+
269
+ FABRIKA_CONTROL_KEY a machine \`px_\` credential for the control app; it wins when both are set
270
+ FABRIKA_CONTROL_CREDENTIAL_HELPER a command with \`get\` and \`store\` that holds the refresh token of a
271
+ \`control auth device\` grant (below)
272
+
273
+ \`auth device\` asks IAM for a grant a person approves in the browser (RFC 8628). It prints the page and the
274
+ code on stderr and waits; the person signs in, checks the code, and picks how long the grant lasts (an hour, a
275
+ day or a week). The grant holds the preset's actions at one application, never more than that person may:
160
276
 
161
- FABRIKA_CONTROL_KEY required a machine \`px_\` credential for the control app
277
+ read deploy.read, data.read, operations.read
278
+ deploy read, and deploy.trigger
279
+ operate deploy, secret.manage, app.manage and operations.triage
280
+ create app.manage wherever the person holds it, with no --app: it also changes and deletes apps
281
+
282
+ The refresh token goes to the helper and nowhere else: the helper runs as \`sh -c '<helper> get|store'\`,
283
+ reads \`origin=<console origin>\` (and, for \`store\`, \`refresh_token=<token>\`) on stdin, and \`get\` prints
284
+ \`refresh_token=<token>\`, or nothing. Every call then trades it for a short-lived access token, and IAM
285
+ rotates it each time; a lock under $XDG_CACHE_HOME/fabrika (~/.cache/fabrika when unset) serializes that
286
+ between processes on this machine. If a refresh's answer is lost, the stored token is spent and the next
287
+ call says to run \`auth device\` again.
162
288
 
163
289
  \`key issue\` mints that credential and therefore authenticates differently — it presents the
164
290
  installation's IAM RPC key as transport authentication and its provisioning key as the ISSUING
@@ -175,6 +301,31 @@ and \`platform init\` print in their closing block, and the value \`FABRIKA_IAM_
175
301
  control service. It is NOT the private hostname the services use between themselves: \`http://iam:3000\`
176
302
  resolves inside the provider's project and nowhere else, so from here it only ever fails to connect.
177
303
 
304
+ \`external-apps\` and \`oauth-clients\` manage the OAuth clients IAM serves (ADR-0089). They call IAM's admin API
305
+ with two of the variables \`key issue\` reads, and nothing else: FABRIKA_IAM_RPC_URL (or --iam-url), IAM's PUBLIC origin,
306
+ and FABRIKA_IAM_PROVISIONING_KEY, the bearer. An external application is an application outside this installation that
307
+ signs people in through IAM; \`put\` replaces it whole from a file (record, roles and clients) and is idempotent:
308
+
309
+ {
310
+ "app": "ops-tool",
311
+ "name": "Ops tool",
312
+ "resource": "https://ops.example.com",
313
+ "roles": [{ "key": "viewer", "name": "Viewer" }],
314
+ "clients": [{ "clientId": "https://ops.example.com/oauth/client.json",
315
+ "redirectUris": ["https://ops.example.com/oauth/callback"], "metadataUrl": null }]
316
+ }
317
+
318
+ \`roles\` null or left out: every active user of the installation signs in. \`get\` prints the same file, ready to edit
319
+ and put back. Removing a client, changing the resource or deleting the application revokes the sign-ins through it.
320
+ \`oauth-clients put\` writes an MCP authoring client, whose tokens reach the console's /mcp:
321
+
322
+ { "clientId": "https://claude.ai/oauth/mcp-oauth-client-metadata", "label": "claude",
323
+ "redirectUris": ["https://claude.ai/api/mcp/auth_callback"] }
324
+
325
+ \`label\` is claude, chatgpt or external. A client of an external application is written only through
326
+ \`external-apps put\`, and \`oauth-clients\` refuses it. \`put\` checks the file before anything is sent.
327
+ The console registers external applications too, under Access → External applications.
328
+
178
329
  Connecting a GitHub source is NOT here and will not be: App creation is a browser flow whose
179
330
  authorization requires a human principal (ADR-0029). Use Settings → Source in the console.
180
331
  `
@@ -186,18 +337,39 @@ interface Flags {
186
337
  /** Every value of every option, in order; `values` keeps the last. Only a repeatable option reads it. */
187
338
  readonly repeated: ReadonlyMap<string, readonly string[]>
188
339
  readonly json: boolean
340
+ /** `--not-secret`: `apps variables put` stores a value that looks like a credential. */
341
+ readonly notSecret: boolean
342
+ /**
343
+ * `--wait`: `deploy` follows the run until it succeeds or fails; `requests get`, `--request` and a write Control stores as
344
+ * a request follow the request until it settles.
345
+ */
346
+ readonly wait: boolean
347
+ /** `--request`: a secret or variable write asks a person to approve it instead of making it (ADR-0083 §8). */
348
+ readonly request: boolean
189
349
  readonly positional: readonly string[]
190
350
  }
191
351
 
192
- /** Split `--key=value` options from positional words; `--json` is the one flag every verb shares. */
352
+ /**
353
+ * Split `--key=value` options from positional words; `--json` is the one flag every verb shares, `--not-secret`, `--wait`
354
+ * and `--request` the other bare ones.
355
+ */
193
356
  export const parseControlFlags = (argv: readonly string[]): Flags => {
194
357
  const values = new Map<string, string>()
195
358
  const repeated = new Map<string, string[]>()
196
359
  const positional: string[] = []
197
360
  let json = false
361
+ let notSecret = false
362
+ let wait = false
363
+ let request = false
198
364
  for (const arg of argv) {
199
365
  if (arg === '--json') {
200
366
  json = true
367
+ } else if (arg === '--not-secret') {
368
+ notSecret = true
369
+ } else if (arg === '--wait') {
370
+ wait = true
371
+ } else if (arg === '--request') {
372
+ request = true
201
373
  } else if (arg.startsWith('--')) {
202
374
  const eq = arg.indexOf('=')
203
375
  if (eq === -1) {
@@ -211,7 +383,7 @@ export const parseControlFlags = (argv: readonly string[]): Flags => {
211
383
  positional.push(arg)
212
384
  }
213
385
  }
214
- return { values, repeated, json, positional }
386
+ return { values, repeated, json, notSecret, wait, request, positional }
215
387
  }
216
388
 
217
389
  const required = (flags: Flags, name: string): string => {
@@ -249,26 +421,6 @@ const positiveInteger = (raw: string, name: string): number => {
249
421
  return parsed
250
422
  }
251
423
 
252
- /**
253
- * An origin from the flag, else the environment. Trailing slashes are dropped so paths concatenate.
254
- *
255
- * `label` names WHICH origin is missing: `key issue` reaches IAM, not the control plane, and a message
256
- * that says "Control origin" while asking for `--iam-url` sends the operator to the wrong variable.
257
- */
258
- const origin = (
259
- flags: Flags,
260
- flag: string,
261
- variable: string,
262
- env: Readonly<Record<string, string | undefined>>,
263
- label: string,
264
- ): string => {
265
- const value = flags.values.get(flag) ?? env[variable]
266
- if (value === undefined || value.trim() === '') {
267
- throw new Error(`${label} origin is required. Pass --${flag}=<origin> or set ${variable}.`)
268
- }
269
- return value.trim().replace(/\/+$/, '')
270
- }
271
-
272
424
  const secret = (variable: string, env: Readonly<Record<string, string | undefined>>): string => {
273
425
  const value = env[variable]
274
426
  if (value === undefined || value.trim() === '') {
@@ -280,30 +432,14 @@ const secret = (variable: string, env: Readonly<Record<string, string | undefine
280
432
  /** The console's client with a bearer instead of a cookie, and no SSO bounce: there is no browser to send. */
281
433
  export type ControlClient = InferRpcClient<ControlRpcContract>
282
434
 
283
- /** 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`. */
284
- const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
435
+ const CONTROL_ORIGIN: OriginSource = { label: 'Control', flag: 'url', variable: 'FABRIKA_CONTROL_URL' }
285
436
 
286
- /**
287
- * Control's origin, checked before the key is sent anywhere: https, or http to a loopback host for local development,
288
- * and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
289
- */
290
- export const controlOrigin = (raw: string | undefined): string => {
291
- if (raw === undefined || raw.trim() === '') {
292
- throw new Error('Control origin is required. Pass --url=<origin> or set FABRIKA_CONTROL_URL.')
293
- }
294
- let url: URL
295
- try {
296
- url = new URL(raw.trim())
297
- } catch {
298
- throw new Error('--url or FABRIKA_CONTROL_URL is not a URL')
299
- }
300
- if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) {
301
- throw new Error('--url or FABRIKA_CONTROL_URL must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]')
302
- }
303
- if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
304
- throw new Error('--url or FABRIKA_CONTROL_URL must be an origin only: no credentials, path, query or fragment')
305
- }
306
- return url.origin
437
+ const IAM_ORIGIN: OriginSource = {
438
+ label: 'IAM',
439
+ flag: 'iam-url',
440
+ variable: 'FABRIKA_IAM_RPC_URL',
441
+ hint: "It is IAM's PUBLIC https origin (control's FABRIKA_IAM_ISSUER): a private hostname such as `http://iam:3000` answers only "
442
+ + "inside the provider's project, never from this machine.",
307
443
  }
308
444
 
309
445
  const KEY_LABEL = '[FABRIKA_CONTROL_KEY]'
@@ -328,31 +464,91 @@ const carriesKey = (text: string, key: string): boolean => {
328
464
  * A JSON answer that carries the key is dropped whole, so no row, `--json` output or error can repeat it. Any other
329
465
  * body passes: the RPC client reports a non-JSON answer by its status alone.
330
466
  */
331
- const withoutEchoedKey = async (response: Response, key: string): Promise<Response> => {
467
+ const withoutEchoedKey = async (
468
+ response: Response,
469
+ key: string,
470
+ source: { readonly service: string; readonly label: string } = { service: 'Control', label: KEY_LABEL },
471
+ ): Promise<Response> => {
332
472
  if (!(response.headers.get('content-type') ?? '').includes('application/json')) return response
333
473
  const text = await response.text()
334
474
  if (carriesKey(text, key)) {
335
- return Response.json({ error: { type: 'transport', message: `Control's answer carried ${KEY_LABEL}; it was dropped` } }, { status: 502 })
475
+ return Response.json({ error: { type: 'transport', message: `${source.service}'s answer carried ${source.label}; it was dropped` } }, {
476
+ status: 502,
477
+ })
336
478
  }
337
479
  return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
338
480
  }
339
481
 
482
+ /** Control's origin and the fetch that carries the Control credential to it. */
483
+ export interface ControlTransport {
484
+ readonly origin: string
485
+ readonly fetch: RpcFetch
486
+ /** The credential is a person's device grant, not FABRIKA_CONTROL_KEY. */
487
+ readonly grant: boolean
488
+ }
489
+
490
+ /** Neither credential is set; both are read from the environment only. */
491
+ export const MISSING_CONTROL_CREDENTIAL = `FABRIKA_CONTROL_KEY is required (environment only — it has no flag), or ${CREDENTIAL_HELPER_VARIABLE} `
492
+ + 'after `fabrika control auth device`.'
493
+
494
+ /**
495
+ * The bearer for one request: FABRIKA_CONTROL_KEY when it is set, else an access token for the resource the request
496
+ * calls, refreshed through the grant the credential helper holds.
497
+ */
498
+ const controlBearer = (
499
+ origin: string,
500
+ env: Readonly<Record<string, string | undefined>>,
501
+ send: RpcFetch,
502
+ oauth: ControlOAuthDependencies | undefined,
503
+ ): (input: RequestInfo | URL) => Promise<string> => {
504
+ const key = env['FABRIKA_CONTROL_KEY']?.trim()
505
+ if (key !== undefined && key !== '') return () => Promise.resolve(key)
506
+ const helper = env[CREDENTIAL_HELPER_VARIABLE]?.trim()
507
+ if (helper === undefined || helper === '') throw new Error(MISSING_CONTROL_CREDENTIAL)
508
+ const bearer = controlOAuthBearer(origin, oauth ?? defaultControlOAuthDependencies(helper, env, send))
509
+ return (input) => bearer(controlResourceFor(origin, input))
510
+ }
511
+
340
512
  /**
341
- * The one client of Control that `fabrika control` and `fabrika env` share: the origin from `url` or
342
- * FABRIKA_CONTROL_URL, the key from FABRIKA_CONTROL_KEY in the environment only, no redirect followed.
513
+ * The origin from `url` or FABRIKA_CONTROL_URL, the credential from the environment only, no redirect followed. Every
514
+ * client of the console's origin is built on it.
343
515
  */
344
- export const connectControl = (url: string | undefined, env: Readonly<Record<string, string | undefined>>): ControlClient => {
345
- const base = controlOrigin(url ?? env['FABRIKA_CONTROL_URL'])
346
- const key = secret('FABRIKA_CONTROL_KEY', env)
347
- return createRpcClient<ControlRpcContract>({
348
- baseUrl: `${base}/api/rpc`,
516
+ export const controlTransport = (
517
+ url: string | undefined,
518
+ env: Readonly<Record<string, string | undefined>>,
519
+ send: RpcFetch = fetch,
520
+ oauth?: ControlOAuthDependencies,
521
+ ): ControlTransport => {
522
+ const origin = credentialOrigin(url ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
523
+ const bearer = controlBearer(origin, env, send, oauth)
524
+ return {
525
+ origin,
526
+ grant: (env['FABRIKA_CONTROL_KEY']?.trim() ?? '') === '',
349
527
  fetch: async (input, init) => {
528
+ let token: string
529
+ try {
530
+ token = await bearer(input)
531
+ } catch (error) {
532
+ // The RPC client reads a rejected fetch as "Network request failed"; this answer keeps the reason.
533
+ const message = error instanceof Error ? error.message : 'the Control credential could not be obtained'
534
+ return Response.json({ error: { type: 'credential', message } }, { status: 401 })
535
+ }
350
536
  const headers = new Headers(init?.headers)
351
- headers.set('authorization', `Bearer ${key}`)
537
+ headers.set('authorization', `Bearer ${token}`)
352
538
  // A redirect would carry the bearer to wherever it points.
353
- return await withoutEchoedKey(await fetch(input, { ...init, headers, redirect: 'manual' }), key)
539
+ return await withoutEchoedKey(await send(input, { ...init, headers, redirect: 'manual' }), token)
354
540
  },
355
- })
541
+ }
542
+ }
543
+
544
+ /** The one client of Control that `fabrika control`, `fabrika env` and `fabrika operations` share. */
545
+ export const connectControl = (
546
+ url: string | undefined,
547
+ env: Readonly<Record<string, string | undefined>>,
548
+ oauth?: ControlOAuthDependencies,
549
+ ): ControlClient => {
550
+ const transport = controlTransport(url, env, fetch, oauth)
551
+ return createRpcClient<ControlRpcContract>({ baseUrl: `${transport.origin}/api/rpc`, fetch: transport.fetch })
356
552
  }
357
553
 
358
554
  const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => connectControl(flags.values.get('url'), env)
@@ -377,7 +573,7 @@ const parseJsonText = (text: string, label: string): JsonValue => {
377
573
  }
378
574
  }
379
575
 
380
- const emit = (flags: Flags, result: unknown, render: () => string): void => {
576
+ const emit = (flags: Pick<Flags, 'json'>, result: unknown, render: () => string): void => {
381
577
  console.info(flags.json ? JSON.stringify(result, null, 2) : render())
382
578
  }
383
579
 
@@ -403,32 +599,16 @@ const appLine = (app: AppDto): string => `${app.id}\t${app.repoUrl}\t${app.defau
403
599
 
404
600
  const runLine = (run: RunDto): string => `${run.id}\t${run.appId}\t${run.env}\t${run.status}\t${run.ref}`
405
601
 
406
- /** How the IAM origin was supplied, for a message that must not echo the value itself. */
407
- const IAM_ORIGIN_SOURCE = '--iam-url / FABRIKA_IAM_RPC_URL'
408
-
409
602
  /**
410
603
  * The one `key issue` failure whose cause is almost always the address itself.
411
604
  *
412
- * `fetch` rejects only when the request never completed, so this reports what could not be reached and
413
- * the mistake that produces it. Only the PARSED origin is named: an operator may put userinfo in the
414
- * value, and `new URL().origin` drops it. A value that does not parse is not echoed at all — the
415
- * variable is named instead. The cause object may quote anything, so only its short error code is.
605
+ * `fetch` rejects only when the request never completed, so this reports what could not be reached and the mistake that
606
+ * produces it. The cause object may quote anything, so only its short error code is.
416
607
  */
417
- const unreachableIam = (base: string, cause: unknown): string => {
608
+ const unreachableIam = (origin: string, cause: unknown): string => {
418
609
  const code = typeof cause === 'object' && cause !== null ? Reflect.get(cause, 'code') : undefined
419
610
  const reason = typeof code === 'string' && code !== '' && code.length <= 40 ? code : 'the connection failed'
420
- let parsed: string | undefined
421
- try {
422
- parsed = new URL(base).origin
423
- } catch {
424
- parsed = undefined
425
- }
426
- if (parsed === undefined || parsed === 'null' || code === 'ERR_INVALID_URL') {
427
- return `${IAM_ORIGIN_SOURCE} is not a URL — it needs the \`https://\` scheme and IAM's PUBLIC host, `
428
- + 'shaped `https://<iam-host>`.'
429
- }
430
- return `IAM could not be reached at ${parsed} (${reason}). ${IAM_ORIGIN_SOURCE} must be IAM's PUBLIC origin: `
431
- + "a private hostname such as `http://iam:3000` answers only inside the provider's project, never from this machine."
611
+ return `IAM could not be reached at ${origin} (${reason}). ${IAM_ORIGIN.hint}`
432
612
  }
433
613
 
434
614
  const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
@@ -448,14 +628,19 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
448
628
  label: required(flags, 'label'),
449
629
  expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
450
630
  }
451
- const base = origin(flags, 'iam-url', 'FABRIKA_IAM_RPC_URL', env, 'IAM')
631
+ const base = credentialOrigin(flags.values.get('iam-url') ?? env['FABRIKA_IAM_RPC_URL'], IAM_ORIGIN)
452
632
  const response = await fetch(`${base}/rpc/issueKey`, {
453
633
  method: 'POST',
454
634
  headers: { authorization: `Bearer ${secret('FABRIKA_IAM_RPC_KEY', env)}`, 'content-type': 'application/json' },
455
635
  body: JSON.stringify(body),
636
+ // A followed 307/308 would re-send the provisioning key to wherever it points.
637
+ redirect: 'manual',
456
638
  }).catch((cause: unknown) => {
457
639
  throw new Error(unreachableIam(base, cause))
458
640
  })
641
+ if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {
642
+ throw new Error(`IAM answered with a redirect (HTTP ${response.status}), which is not followed. ${IAM_ORIGIN.hint}`)
643
+ }
459
644
  if (!response.ok) {
460
645
  // The body can quote what came off the wire, so report the status and nothing else.
461
646
  throw new Error(`IAM refused the issue request: HTTP ${response.status}`)
@@ -471,6 +656,24 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
471
656
  console.info(flags.json ? JSON.stringify(outcome, null, 2) : outcome.token)
472
657
  }
473
658
 
659
+ const APP_ID = /^[a-z0-9][a-z0-9-]*$/
660
+
661
+ /** `auth device`: the device grant for one preset, stored through the credential helper; nothing goes to stdout. */
662
+ const runAuthDevice = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
663
+ const origin = credentialOrigin(flags.values.get('url') ?? env['FABRIKA_CONTROL_URL'], CONTROL_ORIGIN)
664
+ const raw = required(flags, 'preset')
665
+ const preset = parseControlCliPreset(raw)
666
+ if (preset === null) throw new Error(`--preset must be one of ${CONTROL_CLI_PRESETS.join(', ')}`)
667
+ const app = optional(flags, 'app')
668
+ if (preset === 'create' && app !== undefined) throw new Error('--preset=create holds its action wherever you may, and takes no --app')
669
+ if (preset !== 'create' && (app === undefined || !APP_ID.test(app))) throw new Error(`--preset=${preset} needs --app=<application id>`)
670
+ const helper = env[CREDENTIAL_HELPER_VARIABLE]?.trim()
671
+ if (helper === undefined || helper === '') {
672
+ throw new Error(`${CREDENTIAL_HELPER_VARIABLE} is required: the refresh token is stored through it and never printed`)
673
+ }
674
+ await authorizeDevice({ origin, preset, ...(app === undefined ? {} : { app }) }, defaultControlOAuthDependencies(helper, env, fetch))
675
+ }
676
+
474
677
  const decodeIssueKeyResult = (value: unknown): IssueKeyResult => {
475
678
  const result = issueKeyResultSchema.safeParse(value)
476
679
  if (!result.success) {
@@ -665,10 +868,28 @@ const runEnvironments = async (
665
868
  ...(namespaceId === undefined ? {} : { namespaceId }),
666
869
  ...(kind === undefined ? {} : { kind }),
667
870
  }
668
- const result = await client.apps.environments.put({ appId: required(flags, 'app'), env: required(flags, 'env'), environment })
871
+ const target = { appId: required(flags, 'app'), env: required(flags, 'env') }
872
+ const result = await directWrite(client, flags, () => client.apps.environments.put({ ...target, environment }))
873
+ if (result === null) return
669
874
  emit(flags, result, () => `${result.appId}\t${result.env}\t${result.provider}`)
670
875
  return
671
876
  }
877
+ if (verb === 'suspend' || verb === 'resume') {
878
+ const target = { appId: required(flags, 'app'), env: required(flags, 'env') }
879
+ const result = await directWrite(
880
+ client,
881
+ flags,
882
+ () => verb === 'suspend' ? client.apps.environments.suspend(target) : client.apps.environments.resume(target),
883
+ )
884
+ if (result === null) return
885
+ if (result.namespaceId !== null) {
886
+ console.warn(
887
+ `the proxy of namespace ${result.namespaceId} is rebuilding; follow it: fabrika control namespaces get --namespace=${result.namespaceId}`,
888
+ )
889
+ }
890
+ emit(flags, result, () => `${result.appId}\t${result.env}\t${result.suspendedAt === undefined ? 'serving' : 'suspended'}`)
891
+ return
892
+ }
672
893
  throw new Error(`Unknown \`control apps environments\` verb: ${verb ?? '(missing)'}`)
673
894
  }
674
895
 
@@ -706,13 +927,25 @@ const runVariables = async (verb: string | undefined, flags: Flags, env: Readonl
706
927
  name: required(flags, 'name'),
707
928
  value: required(flags, 'value'),
708
929
  ...(scope === undefined ? {} : { env: scope }),
930
+ ...(flags.notSecret ? { notSecret: true } : {}),
931
+ }
932
+ if (flags.request) {
933
+ await requestChange(client, flags, 'apps.variables.put', { appId, variable: { ...variable } })
934
+ return
709
935
  }
710
- const result = await client.apps.variables.put({ appId, variable })
936
+ const result = await directWrite(client, flags, () => client.apps.variables.put({ appId, variable }))
937
+ if (result === null) return
711
938
  emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\t${result.value}`)
712
939
  return
713
940
  }
714
941
  if (verb === 'delete') {
715
- const result = await client.apps.variables.delete({ appId, name: required(flags, 'name'), ...(scope === undefined ? {} : { env: scope }) })
942
+ const target = { appId, name: required(flags, 'name'), ...(scope === undefined ? {} : { env: scope }) }
943
+ if (flags.request) {
944
+ await requestChange(client, flags, 'apps.variables.delete', target)
945
+ return
946
+ }
947
+ const result = await directWrite(client, flags, () => client.apps.variables.delete(target))
948
+ if (result === null) return
716
949
  emit(flags, result, () => (result.ok ? 'deleted' : 'not deleted'))
717
950
  return
718
951
  }
@@ -770,17 +1003,29 @@ const runSecrets = async (
770
1003
  const name = required(flags, 'name')
771
1004
  const value = await readSecretValue(input, appId, name)
772
1005
  const secret: PutAppSecretRequest = { name, value, ...(scope === undefined ? {} : { env: scope }) }
773
- let result: AppSecretDto
1006
+ if (flags.request) {
1007
+ await requestChange(client, flags, 'apps.secrets.put', { appId, secret: { ...secret } }, value)
1008
+ return
1009
+ }
1010
+ let result: AppSecretDto | null
774
1011
  try {
775
- result = await client.apps.secrets.put({ appId, secret })
1012
+ result = await directWrite(client, flags, () => client.apps.secrets.put({ appId, secret }), value)
776
1013
  } catch (error) {
1014
+ if (error instanceof ApprovalPendingError) throw error
777
1015
  throw new Error(failureMessage(error, value, 'secret value'))
778
1016
  }
1017
+ if (result === null) return
779
1018
  emit(flags, result, () => `${result.env ?? '*'}\t${result.name}\tok`)
780
1019
  return
781
1020
  }
782
1021
  if (verb === 'delete') {
783
- const result = await client.apps.secrets.delete({ appId, name: required(flags, 'name'), ...(scope === undefined ? {} : { env: scope }) })
1022
+ const target = { appId, name: required(flags, 'name'), ...(scope === undefined ? {} : { env: scope }) }
1023
+ if (flags.request) {
1024
+ await requestChange(client, flags, 'apps.secrets.delete', target)
1025
+ return
1026
+ }
1027
+ const result = await directWrite(client, flags, () => client.apps.secrets.delete(target))
1028
+ if (result === null) return
784
1029
  emit(flags, result, () => (result.ok ? 'deleted' : 'not deleted'))
785
1030
  return
786
1031
  }
@@ -836,7 +1081,8 @@ const runRuns = async (verb: string | undefined, flags: Flags, env: Readonly<Rec
836
1081
  }
837
1082
  if (verb === 'get') {
838
1083
  const result = await client.runs.get({ runId: required(flags, 'run') })
839
- if (result.status === 'failed') console.warn(`why it failed: fabrika control runs log --run=${result.id}`)
1084
+ const hint = runHint(result)
1085
+ if (hint !== null) console.warn(hint)
840
1086
  emit(flags, result, () => runLine(result))
841
1087
  return
842
1088
  }
@@ -1005,20 +1251,546 @@ const runNamespaces = async (verb: string | undefined, flags: Flags, env: Readon
1005
1251
  throw new Error(`Unknown \`control namespaces\` verb: ${verb ?? '(missing)'}`)
1006
1252
  }
1007
1253
 
1254
+ // ── IAM's client registry (ADR-0089) ─────────────────────────────────────────
1255
+ // `external-apps` and `oauth-clients` call IAM's `/admin/rpc` with the provisioning key as the bearer, the credential
1256
+ // Control's own IAM provisioning client sends. A person's device grant does not reach IAM's admin API.
1257
+
1258
+ const PROVISIONING_KEY_LABEL = '[FABRIKA_IAM_PROVISIONING_KEY]'
1259
+
1260
+ /** `text` with the provisioning key cut out: every diagnostic of the registry verbs passes through it. */
1261
+ const withoutProvisioningKey = (text: string, env: Readonly<Record<string, string | undefined>>): string => {
1262
+ const key = env['FABRIKA_IAM_PROVISIONING_KEY']?.trim()
1263
+ return key === undefined || key === '' ? text : text.replaceAll(key, PROVISIONING_KEY_LABEL)
1264
+ }
1265
+
1266
+ export type IamAdminClient = InferRpcClient<IamAdminRpcContract>
1267
+
1268
+ /** IAM's admin RPC at its public origin, with the provisioning key from the environment only and no redirect followed. */
1269
+ export const iamAdminClient = (
1270
+ url: string | undefined,
1271
+ env: Readonly<Record<string, string | undefined>>,
1272
+ send: RpcFetch = fetch,
1273
+ ): IamAdminClient => {
1274
+ const origin = credentialOrigin(url ?? env['FABRIKA_IAM_RPC_URL'], IAM_ORIGIN)
1275
+ const key = secret('FABRIKA_IAM_PROVISIONING_KEY', env)
1276
+ return createRpcClient<IamAdminRpcContract>({
1277
+ baseUrl: `${origin}/admin/rpc`,
1278
+ bounceOnAuth: false,
1279
+ fetch: async (input, init) => {
1280
+ const headers = new Headers(init?.headers)
1281
+ headers.set('authorization', `Bearer ${key}`)
1282
+ let response: Response
1283
+ try {
1284
+ // A followed 307/308 would re-send the provisioning key to wherever it points; the client refuses a 3xx.
1285
+ response = await send(input, { ...init, headers, redirect: 'manual' })
1286
+ } catch (cause) {
1287
+ // The RPC client reads a rejected fetch as "Network request failed"; this answer keeps the reason.
1288
+ return Response.json({ error: { type: 'transport', message: unreachableIam(origin, cause) } }, { status: 502 })
1289
+ }
1290
+ return await withoutEchoedKey(response, key, { service: 'IAM', label: PROVISIONING_KEY_LABEL })
1291
+ },
1292
+ })
1293
+ }
1294
+
1295
+ const roleFileSchema = z.object({ key: z.string(), name: z.string() }).strict()
1296
+ const externalAppClientFileSchema = z.object({
1297
+ clientId: z.string(),
1298
+ redirectUris: z.array(z.string()),
1299
+ metadataUrl: z.string().nullable().optional(),
1300
+ }).strict()
1301
+ const externalAppFileSchema = z.object({
1302
+ app: z.string(),
1303
+ name: z.string(),
1304
+ resource: z.string(),
1305
+ roles: z.array(roleFileSchema).nullable().optional(),
1306
+ clients: z.array(externalAppClientFileSchema),
1307
+ }).strict()
1308
+ const oauthClientFileSchema = z.object({
1309
+ clientId: z.string(),
1310
+ label: z.enum(OAUTH_CLIENT_PROVIDERS),
1311
+ redirectUris: z.array(z.string()),
1312
+ metadataUrl: z.string().nullable().optional(),
1313
+ }).strict()
1314
+
1315
+ /** What IAM refuses of one client's coordinates, checked with the contract's own predicates. */
1316
+ const clientProblems = (at: string, client: { clientId: string; redirectUris: string[]; metadataUrl?: string | null | undefined }): string[] => {
1317
+ const problems: string[] = []
1318
+ if (!isCimdClientId(client.clientId)) problems.push(`${at}.clientId must be the https URL of the client's metadata document, with a path`)
1319
+ const uris = client.redirectUris
1320
+ if (uris.length === 0 || uris.length > 32 || !uris.every((uri) => isOAuthResourceUri(uri)) || new Set(uris).size !== uris.length) {
1321
+ problems.push(`${at}.redirectUris must list 1 to 32 distinct exact https URLs (loopback http locally) without a fragment`)
1322
+ }
1323
+ if (client.metadataUrl != null && !isHttpsDocumentUrl(client.metadataUrl)) {
1324
+ problems.push(`${at}.metadataUrl must be an https URL without credentials or a fragment, or null`)
1325
+ }
1326
+ return problems
1327
+ }
1328
+
1329
+ /** Zod's complaints about a file's shape, each as `<path>: <message>`; never the value it read. */
1330
+ const shapeProblems = (error: z.ZodError): string[] =>
1331
+ error.issues.map((issue) => `${issue.path.length === 0 ? '(file)' : issue.path.join('.')}: ${issue.message}`)
1332
+
1333
+ const refuseFile = (path: string, what: string, problems: readonly string[]): never => {
1334
+ throw new Error(`${path} is not ${what}:\n${problems.map((problem) => ` - ${problem}`).join('\n')}`)
1335
+ }
1336
+
1337
+ /** An `externalApps.put` request from a file, checked against the contract before it is sent; IAM checks it again. */
1338
+ export const parseExternalAppFile = (value: JsonValue, path: string): PutExternalAppRequest => {
1339
+ const shape = externalAppFileSchema.safeParse(value)
1340
+ if (!shape.success) return refuseFile(path, 'an external application', shapeProblems(shape.error))
1341
+ const file = shape.data
1342
+ const problems: string[] = []
1343
+ if (!isOAuthIdentityAppId(file.app)) problems.push('app must be lowercase letters, digits and dashes, without `@`, at most 63 characters')
1344
+ const nameProblem = displayNameProblem(file.name)
1345
+ if (nameProblem !== null) problems.push(`name ${nameProblem}`)
1346
+ if (!isOAuthResourceUri(file.resource) || !file.resource.startsWith('https://')) problems.push('resource must be an https URI without a fragment')
1347
+ const roles = file.roles ?? []
1348
+ if (roles.length > MAX_OAUTH_IDENTITY_ROLES) problems.push(`roles holds at most ${MAX_OAUTH_IDENTITY_ROLES} roles`)
1349
+ for (const [index, role] of roles.entries()) {
1350
+ if (!isOAuthIdentityRoleKey(role.key)) problems.push(`roles.${index}.key must be lowercase like an app id and no built-in role`)
1351
+ else if (roles.findIndex((other) => other.key === role.key) !== index) problems.push(`roles.${index}.key repeats '${role.key}'`)
1352
+ if (role.name === '' || role.name.length > 100) problems.push(`roles.${index}.name must be 1 to 100 characters`)
1353
+ }
1354
+ if (file.clients.length > MAX_EXTERNAL_APP_CLIENTS) problems.push(`clients holds at most ${MAX_EXTERNAL_APP_CLIENTS} clients`)
1355
+ for (const [index, client] of file.clients.entries()) {
1356
+ problems.push(...clientProblems(`clients.${index}`, client))
1357
+ if (file.clients.findIndex((other) => other.clientId === client.clientId) !== index) problems.push(`clients.${index}.clientId repeats a client`)
1358
+ }
1359
+ if (problems.length > 0) return refuseFile(path, 'an external application', problems)
1360
+ return {
1361
+ app: file.app,
1362
+ name: file.name,
1363
+ resource: file.resource,
1364
+ roles: roles.length === 0 ? null : roles,
1365
+ clients: file.clients.map((client) => ({ clientId: client.clientId, redirectUris: client.redirectUris, metadataUrl: client.metadataUrl ?? null })),
1366
+ }
1367
+ }
1368
+
1369
+ /** An `oauthClients.put` request (an MCP authoring client) from a file, checked against the contract before it is sent. */
1370
+ export const parseOAuthClientFile = (value: JsonValue, path: string): PutOAuthClientRequest => {
1371
+ const shape = oauthClientFileSchema.safeParse(value)
1372
+ if (!shape.success) return refuseFile(path, 'an authoring client', shapeProblems(shape.error))
1373
+ const file = shape.data
1374
+ const problems = clientProblems('(file)', file)
1375
+ if (problems.length > 0) return refuseFile(path, 'an authoring client', problems)
1376
+ return { clientId: file.clientId, label: file.label, redirectUris: file.redirectUris, metadataUrl: file.metadataUrl ?? null }
1377
+ }
1378
+
1379
+ /** What `external-apps get` prints: the file `external-apps put` takes back, so a record can be kept and edited as a file. */
1380
+ export const externalAppFile = (app: ExternalAppDto): PutExternalAppRequest => ({
1381
+ app: app.app,
1382
+ name: app.name ?? app.app,
1383
+ resource: app.resource,
1384
+ roles: app.roles,
1385
+ clients: app.clients,
1386
+ })
1387
+
1388
+ const externalAppLine = (app: ExternalAppDto): string =>
1389
+ [app.app, app.name ?? '', app.resource, `${app.roles?.length ?? 0} roles`, `${app.clients.length} clients`].join('\t')
1390
+
1391
+ const oauthClientLine = (client: OAuthClientDto): string =>
1392
+ [client.clientId, client.label, client.externalApp ?? 'authoring', client.redirectUris.join(',')].join('\t')
1393
+
1394
+ const positionalArgument = (flags: Flags, what: string, usage: string): string => {
1395
+ const value = flags.positional[1]
1396
+ if (value === undefined || value === '') throw new Error(`${usage} needs ${what}`)
1397
+ if (flags.positional.length > 2) throw new Error(`${usage} takes only ${what}`)
1398
+ return value
1399
+ }
1400
+
1401
+ const fileArgument = async (flags: Flags): Promise<{ readonly path: string; readonly value: JsonValue }> => {
1402
+ const path = required(flags, 'file')
1403
+ return { path, value: await readJsonFile(path) }
1404
+ }
1405
+
1406
+ const runExternalApps = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
1407
+ if (verb === 'put') {
1408
+ const { path, value } = await fileArgument(flags)
1409
+ const request = parseExternalAppFile(value, path)
1410
+ const result = await iamAdminClient(flags.values.get('iam-url'), env).externalApps.put(request)
1411
+ emit(flags, result, () => externalAppLine(result))
1412
+ return
1413
+ }
1414
+ if (verb === 'list') {
1415
+ if (flags.positional.length > 1) throw new Error('`control external-apps list` takes no argument')
1416
+ const result = await iamAdminClient(flags.values.get('iam-url'), env).externalApps.list()
1417
+ emitList(flags, result, externalAppLine, 'no external applications registered')
1418
+ return
1419
+ }
1420
+ if (verb === 'get') {
1421
+ const app = positionalArgument(flags, 'an app id', '`control external-apps get`')
1422
+ const result = await iamAdminClient(flags.values.get('iam-url'), env).externalApps.get({ app })
1423
+ console.info(JSON.stringify(flags.json ? result : externalAppFile(result), null, 2))
1424
+ return
1425
+ }
1426
+ if (verb === 'delete') {
1427
+ const app = positionalArgument(flags, 'an app id', '`control external-apps delete`')
1428
+ const result = await iamAdminClient(flags.values.get('iam-url'), env).externalApps.delete({ app })
1429
+ emit(flags, result, () => 'deleted')
1430
+ return
1431
+ }
1432
+ throw new Error(`Unknown \`control external-apps\` verb: ${verb ?? '(missing)'}`)
1433
+ }
1434
+
1435
+ const runOAuthClients = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
1436
+ if (verb === 'put') {
1437
+ const { path, value } = await fileArgument(flags)
1438
+ const request = parseOAuthClientFile(value, path)
1439
+ const result = await iamAdminClient(flags.values.get('iam-url'), env).oauthClients.put(request)
1440
+ emit(flags, result, () => oauthClientLine(result))
1441
+ return
1442
+ }
1443
+ if (verb === 'list') {
1444
+ if (flags.positional.length > 1) throw new Error('`control oauth-clients list` takes no argument')
1445
+ const result = await iamAdminClient(flags.values.get('iam-url'), env).oauthClients.list()
1446
+ emitList(flags, result, oauthClientLine, 'no OAuth clients registered')
1447
+ return
1448
+ }
1449
+ if (verb === 'delete') {
1450
+ const clientId = positionalArgument(flags, 'a client id', '`control oauth-clients delete`')
1451
+ const result = await iamAdminClient(flags.values.get('iam-url'), env).oauthClients.delete({ clientId })
1452
+ emit(flags, result, () => 'deleted')
1453
+ return
1454
+ }
1455
+ throw new Error(`Unknown \`control oauth-clients\` verb: ${verb ?? '(missing)'}`)
1456
+ }
1457
+
1008
1458
  const runDeploy = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
1009
1459
  const ref = optional(flags, 'ref')
1010
- const result = await controlClient(flags, env).deploy({
1460
+ const client = controlClient(flags, env)
1461
+ const created = await client.deploy({
1011
1462
  appId: required(flags, 'app'),
1012
1463
  env: required(flags, 'env'),
1013
1464
  ...(ref === undefined ? {} : { ref }),
1014
1465
  })
1466
+ const result = flags.wait ? await followRun((runId) => client.runs.get({ runId }), created, { intervalMs: WAIT_INTERVAL_MS }) : created
1467
+ const hint = runHint(result)
1468
+ if (hint !== null && !flags.wait) console.warn(hint)
1015
1469
  emit(flags, result, () => runLine(result))
1016
1470
  }
1017
1471
 
1472
+ /** How often `deploy --wait` reads the run, and `requests get --wait` the request, again. */
1473
+ const WAIT_INTERVAL_MS = 5000
1474
+
1475
+ /**
1476
+ * What stderr says about a run beside its row: the link a person approves it at, or why it failed. A non-person's
1477
+ * deploy of a protected environment carries the link from its creation (ADR-0050 §4).
1478
+ */
1479
+ export const runHint = (run: RunDto): string | null => {
1480
+ if (run.status === 'failed') {
1481
+ if (run.failureCause === 'rejected') return 'a person refused this deploy; nothing was deployed'
1482
+ if (run.failureCause === 'expired') return 'nobody approved or refused this deploy before its deadline, so it expired; nothing was deployed'
1483
+ return `why it failed: fabrika control runs log --run=${run.id}`
1484
+ }
1485
+ if (run.approvalUrl !== undefined) return `a person approves or refuses this deploy at ${run.approvalUrl}`
1486
+ return null
1487
+ }
1488
+
1489
+ /**
1490
+ * Follow a run until it succeeds or fails, saying on stderr when it starts to wait for a person and where. Approval is
1491
+ * only a step: an approved run deploys, and its outcome is what this answers.
1492
+ */
1493
+ export const followRun = async (
1494
+ read: (runId: string) => Promise<RunDto>,
1495
+ created: RunDto,
1496
+ options: { readonly intervalMs: number },
1497
+ ): Promise<RunDto> => {
1498
+ let run = created
1499
+ let said: string | null = null
1500
+ while (run.status !== 'succeeded' && run.status !== 'failed') {
1501
+ const hint = runHint(run)
1502
+ const line = hint === null ? `the run is ${run.status.replace('_', ' ')}` : hint
1503
+ if (line !== said) console.warn(line)
1504
+ said = line
1505
+ await Bun.sleep(options.intervalMs)
1506
+ run = await read(run.id)
1507
+ }
1508
+ const hint = runHint(run)
1509
+ if (hint !== null) console.warn(hint)
1510
+ return run
1511
+ }
1512
+
1513
+ /**
1514
+ * Ask a person to approve a write instead of making it (ADR-0083 §8): stderr says where they decide it and, for a
1515
+ * secret, the value's fingerprint, computed here and compared with Control's; stdout prints the request. `secretValue`
1516
+ * is cut out of any failure that quotes it.
1517
+ */
1518
+ const requestChange = async (client: ControlClient, flags: Flags, kind: string, input: JsonValue, secretValue?: string): Promise<void> => {
1519
+ let created: CreateApprovalRequestResponse
1520
+ try {
1521
+ created = await client.approvals.requests.create({ kind, input })
1522
+ } catch (error) {
1523
+ if (secretValue === undefined) throw error
1524
+ throw new Error(failureMessage(error, secretValue, 'secret value'))
1525
+ }
1526
+ await handRequest(client, flags, created, { routed: false, ...(secretValue === undefined ? {} : { secretValue }) })
1527
+ }
1528
+
1529
+ /**
1530
+ * The exit code of a write that did not apply because it waits for a person (ADR-0083 §3): neither done nor failed.
1531
+ * sysexits' EX_TEMPFAIL, "not done now; it may be later".
1532
+ */
1533
+ export const APPROVAL_PENDING_EXIT_CODE = 75
1534
+
1535
+ /** A write Control stored as a request for a person instead of making it; the process exits with `APPROVAL_PENDING_EXIT_CODE`. */
1536
+ export class ApprovalPendingError extends Error {
1537
+ readonly exitCode = APPROVAL_PENDING_EXIT_CODE
1538
+ }
1539
+
1540
+ /** What printing and following a request takes from a command's flags. */
1541
+ export interface RequestOutput {
1542
+ readonly json: boolean
1543
+ readonly wait: boolean
1544
+ }
1545
+
1546
+ /**
1547
+ * The request Control stored a write as (`approval_requested`), or null for any other answer. An answer whose data does
1548
+ * not read as a request is left as Control's refusal, whose message names the link.
1549
+ */
1550
+ const routedRequest = (error: unknown): CreateApprovalRequestResponse | null => {
1551
+ if (!(error instanceof RpcError) || error.type !== APPROVAL_REQUESTED) return null
1552
+ const parsed = approvalRequestedSchema.safeParse(error.data)
1553
+ return parsed.success ? parsed.data : null
1554
+ }
1555
+
1556
+ /**
1557
+ * Make a write; when Control stores it as a request for a person instead (D8, a protected environment), print the
1558
+ * request as `--request` does and, without `--wait`, fail with `ApprovalPendingError`. With `--wait` the request is
1559
+ * followed: an executed one answers null, anything else fails. `secretValue` is the value a secret write sent, whose
1560
+ * fingerprint is computed here.
1561
+ */
1562
+ export const directWrite = async <T>(
1563
+ client: ControlClient,
1564
+ output: RequestOutput,
1565
+ write: () => Promise<T>,
1566
+ secretValue?: string,
1567
+ ): Promise<T | null> => {
1568
+ try {
1569
+ return await write()
1570
+ } catch (error) {
1571
+ const created = routedRequest(error)
1572
+ if (created === null) throw error
1573
+ await handRequest(client, output, created, { routed: true, ...(secretValue === undefined ? {} : { secretValue }) })
1574
+ return null
1575
+ }
1576
+ }
1577
+
1578
+ /**
1579
+ * Print a request a person decides: for a secret, the value's fingerprint, computed here and compared with Control's;
1580
+ * then follow it with `--wait`, or print it. A routed write that did not execute fails.
1581
+ */
1582
+ const handRequest = async (
1583
+ client: ControlClient,
1584
+ output: RequestOutput,
1585
+ created: CreateApprovalRequestResponse,
1586
+ options: { readonly routed: boolean; readonly secretValue?: string },
1587
+ ): Promise<void> => {
1588
+ if (options.secretValue !== undefined) {
1589
+ // The first 8 hex characters of the value's SHA-256, as the page shows them: the CLI's own, not an echo of Control's.
1590
+ const fingerprint = sha256Hex(options.secretValue).slice(0, 8)
1591
+ if (created.fingerprint !== fingerprint) {
1592
+ throw new Error(
1593
+ `Control answered the fingerprint ${created.fingerprint ?? '(none)'}, but the value sent has ${fingerprint}: `
1594
+ + `refuse the request at ${created.url}, since what it holds is not the value you sent`,
1595
+ )
1596
+ }
1597
+ console.warn(`the value's fingerprint is ${fingerprint}: the person sees the same one beside the value's length on the page`)
1598
+ }
1599
+ if (output.wait) {
1600
+ const read = (id: string) => client.approvals.requests.get({ id })
1601
+ const result = await followRequest(read, await read(created.id), { intervalMs: WAIT_INTERVAL_MS, settleTimeoutMs: REQUEST_SETTLE_TIMEOUT_MS })
1602
+ emit(output, result, () => requestLine(result))
1603
+ if (options.routed && result.state !== 'executed') {
1604
+ throw new Error(requestHint(result) ?? `the request is ${result.state}`)
1605
+ }
1606
+ return
1607
+ }
1608
+ if (!options.routed) console.warn(`a person approves or refuses this request at ${created.url}`)
1609
+ emit(output, created, () => `${created.id}\t${created.state}\t${created.url}`)
1610
+ if (options.routed) {
1611
+ throw new ApprovalPendingError(
1612
+ `the change was not made: it waits for a person, who approves or refuses it at ${created.url}; `
1613
+ + `hand them the link, and follow it with \`fabrika control requests get ${created.id} --wait\``,
1614
+ )
1615
+ }
1616
+ }
1617
+
1618
+ const runRequests = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
1619
+ if (verb !== 'get') throw new Error(`Unknown \`control requests\` verb: ${verb ?? '(missing)'}`)
1620
+ const id = flags.positional[1]
1621
+ if (id === undefined) throw new Error('`control requests get` needs the request id: fabrika control requests get <id>')
1622
+ const client = controlClient(flags, env)
1623
+ const read = (requestId: string) => client.approvals.requests.get({ id: requestId })
1624
+ const request = await read(id)
1625
+ const result = flags.wait
1626
+ ? await followRequest(read, request, { intervalMs: WAIT_INTERVAL_MS, settleTimeoutMs: REQUEST_SETTLE_TIMEOUT_MS })
1627
+ : request
1628
+ const hint = requestHint(result)
1629
+ if (hint !== null && !flags.wait) console.warn(hint)
1630
+ emit(flags, result, () => requestLine(result))
1631
+ }
1632
+
1018
1633
  /**
1019
- * `command` is the group (`key`, `apps`, `runs`, `register`, `deploy`); the verb, where a group has
1634
+ * `access request-grant`: ask a person to give a principal one role of an application environment; `access request-key`:
1635
+ * ask a person for a key (ADR-0083 §8).
1636
+ */
1637
+ const runAccess = async (verb: string | undefined, flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
1638
+ if (verb === 'request-key') return requestKey(flags, env)
1639
+ if (verb !== 'request-grant') throw new Error(`Unknown \`control access\` verb: ${verb ?? '(missing)'}`)
1640
+ const expiresIn = Number(required(flags, 'expires-in'))
1641
+ if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0) throw new Error('--expires-in must be a positive whole number of seconds')
1642
+ const scope = optional(flags, 'scope')
1643
+ const separator = scope?.indexOf(':') ?? -1
1644
+ if (scope !== undefined && (separator <= 0 || separator === scope.length - 1)) {
1645
+ throw new Error("--scope names a value of the role's dimension: --scope=<dimension>:<value>")
1646
+ }
1647
+ const input: JsonValue = {
1648
+ appId: required(flags, 'app'),
1649
+ env: required(flags, 'env'),
1650
+ principalId: required(flags, 'principal'),
1651
+ role: required(flags, 'role'),
1652
+ scope: scope === undefined ? null : { type: scope.slice(0, separator), value: scope.slice(separator + 1) },
1653
+ expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
1654
+ }
1655
+ await requestChange(controlClient(flags, env), flags, 'iam.grants.create', input)
1656
+ }
1657
+
1658
+ /**
1659
+ * `access request-key`: a key pair made in memory, whose public half goes with the request and whose private half opens
1660
+ * the key IAM encrypted to it. The private key is never exported or written, so the key is fetched in this run or never.
1661
+ */
1662
+ const requestKey = async (flags: Flags, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
1663
+ const actions = flags.repeated.get('action') ?? []
1664
+ if (actions.length === 0) throw new Error('--action is required: each action the key holds, e.g. --action=deploy.trigger --action=deploy.read')
1665
+ const expiresIn = Number(required(flags, 'expires-in'))
1666
+ if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0) throw new Error('--expires-in must be a positive whole number of seconds')
1667
+ const appId = required(flags, 'app')
1668
+ const label = required(flags, 'label')
1669
+ if (!flags.wait) {
1670
+ throw new Error(
1671
+ '`control access request-key` needs --wait: the private key that opens the issued key lives only in this process, so the key cannot be fetched later',
1672
+ )
1673
+ }
1674
+ const pair = await generateKeyPair(REQUESTED_KEY_JWE.alg, { crv: 'P-256' })
1675
+ const exported = await exportJWK(pair.publicKey)
1676
+ if (typeof exported.x !== 'string' || typeof exported.y !== 'string') throw new Error('could not export the public key')
1677
+ const publicKey: RecipientPublicKey = { kty: 'EC', crv: 'P-256', x: exported.x, y: exported.y }
1678
+ const client = controlClient(flags, env)
1679
+ const created = await client.approvals.requests.create({
1680
+ kind: 'iam.apiKeys.provision',
1681
+ input: { appId, label, actions: [...actions], expiresAt: Math.floor(Date.now() / 1000) + expiresIn, publicKey },
1682
+ })
1683
+ console.warn(`a person approves or refuses this request at ${created.url}`)
1684
+ console.warn(`the public key's thumbprint is ${recipientKeyThumbprint(publicKey)}: the person sees the same one on the page`)
1685
+ const read = (id: string) => client.approvals.requests.get({ id })
1686
+ const settled = await followRequest(read, await read(created.id), {
1687
+ intervalMs: WAIT_INTERVAL_MS,
1688
+ settleTimeoutMs: REQUEST_SETTLE_TIMEOUT_MS,
1689
+ unsettled: (request, minutes) =>
1690
+ `the request is still ${request.state} after ${minutes} minutes, and this process stops waiting: no other process can fetch the key, `
1691
+ + 'since the private key that opens it lived only here; a key nobody fetched is revoked at its delivery deadline, so ask again',
1692
+ })
1693
+ if (settled.state !== 'executed') throw new Error(requestHint(settled) ?? `the request is ${settled.state}`)
1694
+ const { jwe } = await client.approvals.requests.fetchKey({ id: created.id })
1695
+ const { plaintext } = await compactDecrypt(jwe, pair.privateKey, {
1696
+ keyManagementAlgorithms: [REQUESTED_KEY_JWE.alg],
1697
+ contentEncryptionAlgorithms: [REQUESTED_KEY_JWE.enc],
1698
+ })
1699
+ const key = new TextDecoder().decode(plaintext)
1700
+ emit(flags, { requestId: created.id, key }, () => key)
1701
+ }
1702
+
1703
+ const requestLine = (request: ApprovalRequestDto): string => `${request.id}\t${request.kind}\t${request.appId}\t${request.env}\t${request.state}`
1704
+
1705
+ /** What stderr says about a request beside its row: where a person decides it, or why it did not run. */
1706
+ export const requestHint = (request: ApprovalRequestDto): string | null => {
1707
+ switch (request.state) {
1708
+ case 'pending':
1709
+ return request.url === undefined ? 'the request waits for a person' : `a person approves or refuses this request at ${request.url}`
1710
+ case 'rejected':
1711
+ return 'a person refused this request; nothing changed'
1712
+ case 'expired':
1713
+ return 'nobody approved or refused this request before its deadline, so it expired; nothing changed'
1714
+ case 'failed':
1715
+ case 'stale':
1716
+ case 'unknown':
1717
+ return request.error === undefined ? `the request is ${request.state}` : `the request is ${request.state}: ${request.error}`
1718
+ case 'approved':
1719
+ case 'executing':
1720
+ return `the request is ${request.state}`
1721
+ case 'executed':
1722
+ return null
1723
+ }
1724
+ }
1725
+
1726
+ /**
1727
+ * How long `requests get --wait` follows a request once a person decided it. Waiting is bounded by the request's deadline,
1728
+ * but an `unknown` outcome lasts until Control settles it, which a Control without the request's kind never does.
1729
+ */
1730
+ const REQUEST_SETTLE_TIMEOUT_MS = 15 * 60_000
1731
+
1732
+ /** A failed read worth repeating: the request never arrived, or Control or a hop before it failed (5xx). */
1733
+ const transientFailure = (error: unknown): string | null => {
1734
+ if (!(error instanceof RpcError) || error.httpStatus === undefined) return null
1735
+ if (error.httpStatus === 0) return 'a network error'
1736
+ return error.httpStatus >= 500 ? `HTTP ${error.httpStatus}` : null
1737
+ }
1738
+
1739
+ /**
1740
+ * Follow a request until it settles, saying each stage once on stderr; what it ended as is what this answers. Once it is
1741
+ * no longer pending, it stops with an error after `settleTimeoutMs`, which `unsettled` words. A read that fails on the way
1742
+ * or with a 5xx is repeated at the next interval while the wait lasts: until the deadline of a pending request, and
1743
+ * until `settleTimeoutMs` of a decided one.
1744
+ */
1745
+ export const followRequest = async (
1746
+ read: (id: string) => Promise<ApprovalRequestDto>,
1747
+ first: ApprovalRequestDto,
1748
+ options: {
1749
+ readonly intervalMs: number
1750
+ readonly settleTimeoutMs: number
1751
+ readonly unsettled?: (request: ApprovalRequestDto, minutes: number) => string
1752
+ },
1753
+ ): Promise<ApprovalRequestDto> => {
1754
+ let request = first
1755
+ let said: string | null = null
1756
+ let decidedAt: number | null = null
1757
+ while (!isFinalApprovalRequestState(request.state)) {
1758
+ if (request.state !== 'pending') {
1759
+ decidedAt ??= Date.now()
1760
+ if (Date.now() - decidedAt >= options.settleTimeoutMs) {
1761
+ const minutes = Math.round(options.settleTimeoutMs / 60_000)
1762
+ throw new Error(
1763
+ options.unsettled?.(request, minutes)
1764
+ ?? `the request is still ${request.state} after ${minutes} minutes; Control keeps following it: fabrika control requests get ${request.id}`,
1765
+ )
1766
+ }
1767
+ }
1768
+ const line = requestHint(request) ?? `the request is ${request.state}`
1769
+ if (line !== said) console.warn(line)
1770
+ said = line
1771
+ await Bun.sleep(options.intervalMs)
1772
+ try {
1773
+ request = await read(request.id)
1774
+ } catch (error) {
1775
+ const transient = transientFailure(error)
1776
+ const waitEndsAt = decidedAt === null ? request.deadline * 1000 : decidedAt + options.settleTimeoutMs
1777
+ if (transient === null || Date.now() >= waitEndsAt) throw error
1778
+ console.warn(`could not read the request (${transient}); reading it again`)
1779
+ }
1780
+ }
1781
+ const hint = requestHint(request)
1782
+ if (hint !== null) console.warn(hint)
1783
+ return request
1784
+ }
1785
+
1786
+ /**
1787
+ * `command` is the group (`key`, `apps`, `runs`, `requests`, `register`, `deploy`); the verb, where a group has
1020
1788
  * one, is the first positional word after it. `provider` reaches here only to label an envelope.
1021
1789
  */
1790
+ /** Whether a command takes `--request`: only the writes it routes through an approval request. */
1791
+ const takesRequest = (command: string | undefined, positional: readonly string[]): boolean =>
1792
+ command === 'apps' && (positional[0] === 'secrets' || positional[0] === 'variables') && (positional[1] === 'put' || positional[1] === 'delete')
1793
+
1022
1794
  export const runControlCli = async (
1023
1795
  command: string | undefined,
1024
1796
  argv: readonly string[],
@@ -1029,10 +1801,19 @@ export const runControlCli = async (
1029
1801
  try {
1030
1802
  const flags = parseControlFlags(argv)
1031
1803
  const verb = flags.positional[0]
1804
+ if (flags.request && !takesRequest(command, flags.positional)) {
1805
+ throw new Error(
1806
+ '--request is taken only by apps secrets put|delete and apps variables put|delete; anywhere else it would be ignored and the write made directly',
1807
+ )
1808
+ }
1032
1809
  switch (command) {
1033
1810
  case undefined:
1034
1811
  console.info(USAGE)
1035
1812
  return
1813
+ case 'auth':
1814
+ if (verb !== 'device') throw new Error(`Unknown \`control auth\` verb: ${verb ?? '(missing)'}`)
1815
+ await runAuthDevice(flags, env)
1816
+ return
1036
1817
  case 'key':
1037
1818
  if (verb !== 'issue') throw new Error(`Unknown \`control key\` verb: ${verb ?? '(missing)'}`)
1038
1819
  await runKeyIssue(flags, env)
@@ -1046,20 +1827,33 @@ export const runControlCli = async (
1046
1827
  case 'namespaces':
1047
1828
  await runNamespaces(verb, flags, env)
1048
1829
  return
1830
+ case 'requests':
1831
+ await runRequests(verb, flags, env)
1832
+ return
1833
+ case 'access':
1834
+ await runAccess(verb, flags, env)
1835
+ return
1049
1836
  case 'register':
1050
1837
  await runRegister(flags, provider, env)
1051
1838
  return
1052
1839
  case 'deploy':
1053
1840
  await runDeploy(flags, env)
1054
1841
  return
1842
+ case 'external-apps':
1843
+ await runExternalApps(verb, flags, env)
1844
+ return
1845
+ case 'oauth-clients':
1846
+ await runOAuthClients(verb, flags, env)
1847
+ return
1055
1848
  default:
1056
1849
  throw new Error(`Unknown control command: ${command}\n\n${USAGE}`)
1057
1850
  }
1058
1851
  } catch (error) {
1852
+ if (error instanceof ApprovalPendingError) throw error
1059
1853
  // An RPC denial is an ANSWER, not a transport fault; keep its type so a caller can tell "the
1060
1854
  // control plane said no" from "the control plane was unreachable".
1061
1855
  const message = error instanceof RpcError ? `${error.type}: ${error.message}` : error instanceof Error ? error.message : String(error)
1062
- throw new Error(withoutControlKey(message, env))
1856
+ throw new Error(withoutProvisioningKey(withoutControlKey(message, env), env))
1063
1857
  }
1064
1858
  }
1065
1859