@fabrika/provider-cloudflare 0.8.1 → 0.9.0-cloudflare.1

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.
Files changed (45) hide show
  1. package/package.json +16 -15
  2. package/src/bounds.ts +142 -4
  3. package/src/cli.ts +14 -0
  4. package/src/command.ts +8 -4
  5. package/src/contract-support.ts +118 -0
  6. package/src/control.ts +37 -119
  7. package/src/index.ts +1 -1
  8. package/src/installation/init.ts +11 -18
  9. package/src/installation/installation.ts +2 -4
  10. package/src/installation/scaffold.ts +29 -2
  11. package/src/installation/templates/README.md +29 -11
  12. package/src/installation/templates/platform.yml +9 -5
  13. package/src/managed-secrets.ts +61 -0
  14. package/src/plan.ts +11 -3
  15. package/src/provider.ts +277 -54
  16. package/src/proxy-worker.ts +40 -16
  17. package/src/proxy.ts +48 -16
  18. package/src/runner-protocol.ts +16 -1
  19. package/types/src/assets.d.ts +8 -0
  20. package/types/src/authoring.d.ts +17 -0
  21. package/types/src/bounds.d.ts +81 -0
  22. package/types/src/checkout.d.ts +7 -0
  23. package/types/src/cli-args.d.ts +25 -0
  24. package/types/src/cli.d.ts +8 -0
  25. package/types/src/codec.d.ts +8 -0
  26. package/types/src/collaborators.d.ts +52 -0
  27. package/types/src/command.d.ts +49 -0
  28. package/types/src/config-schema.d.ts +9 -0
  29. package/types/src/contract-support.d.ts +39 -0
  30. package/types/src/control.d.ts +468 -0
  31. package/types/src/index.d.ts +18 -0
  32. package/types/src/installation/cloudflare.d.ts +40 -0
  33. package/types/src/installation/envfile.d.ts +39 -0
  34. package/types/src/installation/index.d.ts +2 -0
  35. package/types/src/installation/init-options.d.ts +59 -0
  36. package/types/src/installation/init.d.ts +114 -0
  37. package/types/src/installation/installation.d.ts +2 -0
  38. package/types/src/installation/scaffold.d.ts +39 -0
  39. package/types/src/managed-secrets.d.ts +19 -0
  40. package/types/src/plan.d.ts +21 -0
  41. package/types/src/provider.d.ts +58 -0
  42. package/types/src/proxy-worker.d.ts +15 -0
  43. package/types/src/proxy.d.ts +72 -0
  44. package/types/src/runner-protocol.d.ts +121 -0
  45. package/types/src/schema.d.ts +17 -0
package/src/control.ts CHANGED
@@ -1,14 +1,4 @@
1
- import { ReconcileSchemaError } from '@fabrika/auth'
2
- import {
3
- type AppEnvironment,
4
- appEnvironmentId,
5
- type AppSchema,
6
- FABRIKA_TOKEN_KEYS,
7
- isEmailTransportVariable,
8
- isPlatformTransportVariable,
9
- isWorkloadKeyVariable,
10
- parseAppEnvironmentId,
11
- } from '@fabrika/auth-core'
1
+ import { type AppEnvironment, appEnvironmentId, FABRIKA_PROXY_SECRET, parseAppEnvironmentId } from '@fabrika/auth-core'
12
2
  import type {
13
3
  ControlProvider,
14
4
  JsonValue,
@@ -24,17 +14,16 @@ import type {
24
14
  ProviderSourceResolution,
25
15
  ProviderSourceResolutionInput,
26
16
  ProviderTerminalOutcome,
27
- SchemaReconciler,
28
17
  } from '@fabrika/provider-contract'
29
18
  import { abortableWait, decodeEnvelope, isLeaseLoss, ProviderInvocationAbort } from '@fabrika/provider-contract'
30
- import { isCrossOrigin, MAX_CROSS_ORIGINS } from '@fabrika/proxy-core/headers'
19
+ import { isCrossOrigin, isPolicyOrigin, MAX_CROSS_ORIGINS } from '@fabrika/proxy-core/headers'
31
20
  import { isProxyHost } from '@fabrika/proxy-core/manifest'
32
21
  import { z } from 'zod'
33
22
  import { cloudflareArtifactCodec } from './codec'
34
- import { type RunnerApprovedAccess, runnerApprovedAccessSchema, type RunnerIamReconcile } from './runner-protocol'
23
+ import { assertCloudflareContract, assertStatelessEnvironment, runsInObject, servesOps } from './contract-support'
35
24
  // `./runner` is this module: keep every import here clear of `oblaka-iac`, which the runner packages
36
25
  // cannot typecheck (they do not relax the two strict flags the raw TS needs).
37
- import { defaultReconcileSchema } from './schema'
26
+ import { type RunnerApprovedAccess, runnerApprovedAccessSchema, type RunnerIamReconcile } from './runner-protocol'
38
27
 
39
28
  export * from './runner-protocol'
40
29
 
@@ -71,8 +60,8 @@ export interface CloudflareRunnerJob {
71
60
  readonly domain?: string
72
61
  /** The environment's cross-origin list from Control's registry (ADR-0022); the proxy Worker's manifest entry lists it. */
73
62
  readonly crossOrigins?: readonly string[]
74
- /** Every origin IAM may hand this app a session at, projected by the control plane (ADR-0022). */
75
- readonly returnOrigins?: readonly string[]
63
+ /** The origin of the environment's Operations ingest, from Control; the proxy Worker's `connect-src` admits it. */
64
+ readonly operationsOrigin?: string
76
65
  /** `<app>@<env>` of every Cloudflare deployment in Control's registry; the deploy refuses another application's names. */
77
66
  readonly installationApps?: readonly string[]
78
67
  /** What the deployed proxy enforces and the application starts as; every run but a dry one carries it. */
@@ -161,7 +150,7 @@ export const cloudflareRunnerJobSchema = z.object({
161
150
  stateNamespace: z.string().min(1).optional(),
162
151
  domain: z.string().refine((value) => isProxyHost(value.toLowerCase())).optional(),
163
152
  crossOrigins: z.array(z.string().refine(isCrossOrigin)).max(MAX_CROSS_ORIGINS).optional(),
164
- returnOrigins: z.array(z.string().min(1)).optional(),
153
+ operationsOrigin: z.string().refine((origin) => isPolicyOrigin(origin, ['https:', 'http:'])).optional(),
165
154
  installationApps: z.array(z.string().refine((id) => !hasUnsafeChars(id) && parseAppEnvironmentId(id) !== null)).optional(),
166
155
  approvedAccess: runnerApprovedAccessSchema.optional(),
167
156
  dryRun: z.boolean().optional(),
@@ -206,13 +195,9 @@ export type CloudflareRunRecovery = CloudflareRunOutcome | { readonly state: 'ru
206
195
  export interface CloudflareControlOptions {
207
196
  readonly accountId: string
208
197
  readonly apiToken: string
209
- readonly propustkaUrl?: string
210
- readonly propustkaProvisioningKey?: string
211
198
  readonly runnerKey: string
212
199
  /** Every Cloudflare deployment in Control's registry, sent with each job so another application's names are refused. */
213
200
  installationApps?(signal: AbortSignal): Promise<readonly AppEnvironment[]>
214
- /** Overridable for tests; production reconciles over HTTPS with the control plane's own admin key. */
215
- readonly reconcileSchema?: SchemaReconciler
216
201
  resolveSource(input: ProviderSourceResolutionInput): Promise<ProviderSourceResolution>
217
202
  prepareClone(source: ProviderSource, signal: AbortSignal, sourceBinding?: ProviderSourceBinding): Promise<CloudflareCloneSource>
218
203
  startRun(job: CloudflareRunnerJob): Promise<CloudflareRunOutcome>
@@ -282,10 +267,16 @@ const awaitWithSignal = async <T>(signal: AbortSignal, invoke: () => Promise<T>)
282
267
  const runnerApprovedAccess = (environment: ProviderEnvironment): RunnerApprovedAccess | undefined =>
283
268
  environment.access === undefined
284
269
  ? undefined
285
- : { kind: 'contract', contract: environment.access.contract, contractDigest: environment.access.contractDigest }
270
+ : {
271
+ kind: 'contract',
272
+ contract: environment.access.contract,
273
+ contractDigest: environment.access.contractDigest,
274
+ framework: environment.access.checker,
275
+ }
286
276
 
287
277
  const buildJob = async (options: CloudflareControlOptions, input: ProviderDeployInput): Promise<CloudflareRunnerJob> => {
288
278
  input.signal.throwIfAborted()
279
+ if (input.environment.kind === 'dev') throw new Error('Cloudflare runs no dev environment (ADR-0049); a dev environment runs on Zerops only')
289
280
  assertRegistrationApp(input)
290
281
  const storedTarget = decodeEnvelope('target', 'cloudflare', input.environment.target, cloudflareStoredTargetCodec)
291
282
  const artifact = decodeEnvelope('artifact', 'cloudflare', input.environment.artifact, cloudflareArtifactCodec)
@@ -294,25 +285,11 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
294
285
  throw new Error('Cloudflare deploy requires a canonical 40-character commit SHA')
295
286
  }
296
287
  const approvedAccess = runnerApprovedAccess(input.environment)
297
- if (!input.dryRun && approvedAccess === undefined) {
298
- throw new Error('Cloudflare deploy requires the access Control approved for this environment')
299
- }
300
- // A job, a webhook and a public procedure need `@fabrika/db` on Postgres, which a Worker has not; their keys would only
301
- // sit in a config.
302
- const workloadKey = Object.keys(input.managedEnvironment).find(isWorkloadKeyVariable)
303
- if (workloadKey !== undefined) {
304
- throw new Error(`cloudflare: the contract declares a job, a webhook or a public procedure (${workloadKey}); they run on Zerops only`)
305
- }
306
- // A dry run hands no workload key, and a mail credential must not land in a plain Worker var either way.
307
- const mailVariable = Object.keys(input.managedEnvironment).find((name) => isEmailTransportVariable(name) || isPlatformTransportVariable(name))
308
- if (mailVariable !== undefined) {
309
- throw new Error(`cloudflare: the contract declares a job that sends mail through the installation (${mailVariable}); jobs run on Zerops only`)
310
- }
311
- // A Worker's vars are plain text in its config, so the signing keys of the application's tokens never go there.
312
- const tokenKeys = input.managedEnvironment[FABRIKA_TOKEN_KEYS]
313
- if (tokenKeys !== undefined && tokenKeys !== null) {
314
- throw new Error('cloudflare: the contract declares token purposes, whose keys a Worker would hold as plain vars; signed tokens run on Zerops only')
315
- }
288
+ // The deployer refuses it again from the contract it serves; this fails before the clone.
289
+ if (approvedAccess !== undefined) assertCloudflareContract(approvedAccess.contract)
290
+ const release = input.environment.access?.checker
291
+ const stateless = release !== undefined && !runsInObject(release)
292
+ if (stateless) assertStatelessEnvironment(input.managedEnvironment, release)
316
293
  const source = await awaitWithSignal(input.signal, () => options.prepareClone(input.app.source, input.signal, input.sourceBinding))
317
294
  const listInstallationApps = options.installationApps
318
295
  const installationApps = listInstallationApps === undefined
@@ -321,8 +298,9 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
321
298
  appEnvironmentId(deployment.app, deployment.env)
322
299
  )
323
300
  const managedEnvironment: Record<string, string> = {}
324
- for (const [name, value] of Object.entries(input.managedEnvironment)) {
325
- if (value !== null) managedEnvironment[name] = value
301
+ for (const [name, { value }] of Object.entries(input.managedEnvironment)) {
302
+ // An older release's Worker would demand the hop secret from a proxy Worker that never sends it.
303
+ if (value !== null && !(stateless && name === FABRIKA_PROXY_SECRET)) managedEnvironment[name] = value
326
304
  }
327
305
  return {
328
306
  runId: input.runId,
@@ -341,7 +319,7 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
341
319
  ...(input.environment.crossOrigins === undefined || input.environment.crossOrigins.length === 0
342
320
  ? {}
343
321
  : { crossOrigins: input.environment.crossOrigins }),
344
- ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
322
+ ...(input.environment.operationsOrigin === undefined ? {} : { operationsOrigin: input.environment.operationsOrigin }),
345
323
  ...(installationApps === undefined ? {} : { installationApps }),
346
324
  ...(approvedAccess === undefined ? {} : { approvedAccess }),
347
325
  ...(input.dryRun ? { dryRun: true } : {}),
@@ -352,85 +330,41 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
352
330
  }
353
331
  }
354
332
 
355
- /** The app a terminal outcome belongs to, and where IAM may hand it a session. */
356
- interface IamReconcileTarget {
357
- readonly appId: string
358
- readonly env: string
359
- readonly returnOrigins?: readonly string[]
360
- /** Control's approved contract (ADR-0050): a contract application's IAM schema comes from it, never from the runner. */
361
- readonly access?: ProviderApprovedAccess
362
- readonly signal: AbortSignal
363
- }
364
-
365
- /** The executor's report itself is unusable; retrying cannot make it valid. */
366
- class InvalidIamReport extends Error {}
367
-
368
- /** Apply a schema with the control plane's own IAM key. */
369
- const applySchema = async (options: CloudflareControlOptions, target: IamReconcileTarget, schema: AppSchema): Promise<void> => {
370
- if (options.propustkaUrl === undefined) return
371
- // Return origins ride this call because `apps.setReturnOrigins` 404s for an app IAM has never heard
372
- // of, and the schema reconcile is what registers it. Separate call, same moment.
373
- const returnOrigins = target.returnOrigins !== undefined && target.returnOrigins.length > 0 ? target.returnOrigins : undefined
374
- await (options.reconcileSchema ?? defaultReconcileSchema)({
375
- url: options.propustkaUrl,
376
- app: appEnvironmentId(target.appId, target.env),
377
- schema,
378
- ...(returnOrigins === undefined ? {} : { returnOrigins }),
379
- ...(options.propustkaProvisioningKey === undefined ? {} : { adminKey: options.propustkaProvisioningKey }),
380
- signal: target.signal,
381
- })
382
- }
383
-
384
333
  /**
385
- * Settle a terminal outcome: apply the IAM schema Control approved, if any, before Control marks the run terminal. Both
386
- * the awaited deploy and a post-restart reconcile come through here under Control's lease. IAM replaces the app's whole
387
- * vocabulary, so applying the same schema again after a lost lease is harmless. `retryUnavailableIam` keeps the run in
388
- * flight when IAM was unreachable or answered 5xx/408/429, so the next reconcile retries; an invalid report or any
389
- * other IAM refusal fails the run.
334
+ * Judge a terminal outcome's report before Control settles it. The runner may report the schema it compiled; Control
335
+ * writes the approved one itself (ADR-0011), so a report is only evidence: a dry run that reports access, or a report
336
+ * where Control approved none, fails the run.
390
337
  */
391
338
  const settleOutcome = async (
392
- options: CloudflareControlOptions,
393
- target: IamReconcileTarget,
339
+ access: ProviderApprovedAccess | undefined,
394
340
  outcome: CloudflareRunOutcome,
395
341
  log: (line: string) => Promise<void>,
396
- retryUnavailableIam: boolean,
397
- ): Promise<ProviderTerminalOutcome | { readonly state: 'running' }> => {
342
+ ): Promise<ProviderTerminalOutcome> => {
398
343
  const terminal: ProviderTerminalOutcome = {
399
344
  state: outcome.state,
400
345
  ...(outcome.exitCode === undefined ? {} : { exitCode: outcome.exitCode }),
401
346
  ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }),
402
347
  }
348
+ if (outcome.iamReconcile === undefined) return terminal
403
349
  const failed: ProviderTerminalOutcome = { state: 'failed', ...(outcome.artifactState === undefined ? {} : { artifactState: outcome.artifactState }) }
404
- const reported = outcome.iamReconcile !== undefined
405
350
  if (outcome.dryRun === true) {
406
- if (!reported) return terminal
407
351
  await log('reconcile-schema refused: a dry run reported access')
408
352
  return failed
409
353
  }
410
- try {
411
- if (target.access === undefined && reported) {
412
- throw new InvalidIamReport('reported access, but Control approved no access for this environment')
413
- }
414
- // An approved contract reconciles its own schema once the deploy succeeded, whatever the runner reported.
415
- if (target.access !== undefined && outcome.state === 'succeeded') await applySchema(options, target, target.access.schema)
416
- } catch (error) {
417
- target.signal.throwIfAborted()
418
- await log(`reconcile-schema failed: ${error instanceof Error ? error.message : 'unknown error'}`)
419
- if (retryUnavailableIam && isTransientIamFailure(error)) return { state: 'running' }
354
+ if (access === undefined) {
355
+ await log('reconcile-schema failed: reported access, but Control approved no access for this environment')
420
356
  return failed
421
357
  }
422
358
  return terminal
423
359
  }
424
360
 
425
- const isTransientIamFailure = (error: unknown): boolean => {
426
- if (error instanceof InvalidIamReport) return false
427
- if (!(error instanceof ReconcileSchemaError)) return true
428
- return error.status >= 500 || error.status === 408 || error.status === 429
429
- }
430
-
431
361
  /** Build the Cloudflare control capability over its runner and source-resolution ports. */
432
362
  export const createCloudflareControlProvider = (options: CloudflareControlOptions): ControlProvider => ({
433
363
  id: 'cloudflare',
364
+ // The application's Worker forwards each request to its Durable Object with the environment's proxy secret.
365
+ applicationHopSecret: true,
366
+ // The environment's object serves Control's ops requests from the release that gets the composed row.
367
+ opsChannel: (access) => servesOps(access.checker),
434
368
  normalizeRegistration,
435
369
  applicationRoot: (source) => checkoutRelativeDirectory(source.workerDir),
436
370
  source: { binding: 'connection' },
@@ -469,15 +403,7 @@ export const createCloudflareControlProvider = (options: CloudflareControlOption
469
403
  }
470
404
  input.signal.throwIfAborted()
471
405
  if (input.dryRun) return outcome
472
- const target: IamReconcileTarget = {
473
- appId: input.app.id,
474
- env: input.environment.env,
475
- signal: input.signal,
476
- ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
477
- ...(input.environment.access === undefined ? {} : { access: input.environment.access }),
478
- }
479
- const log = async (line: string): Promise<void> => input.events.log(line)
480
- return settleOutcome(options, target, outcome, log, false)
406
+ return settleOutcome(input.environment.access, outcome, async (line) => input.events.log(line))
481
407
  },
482
408
  reconcile: async (input) => {
483
409
  input.signal.throwIfAborted()
@@ -485,19 +411,11 @@ export const createCloudflareControlProvider = (options: CloudflareControlOption
485
411
  if (recoverRun === undefined) return { state: 'running' }
486
412
  const recovery = await awaitWithSignal(input.signal, () => recoverRun(input.runId))
487
413
  if (recovery.state === 'running') return { state: 'running' }
488
- const target: IamReconcileTarget = {
489
- appId: input.environment.appId,
490
- env: input.environment.env,
491
- signal: input.signal,
492
- ...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
493
- ...(input.environment.access === undefined ? {} : { access: input.environment.access }),
494
- }
495
414
  const log = async (line: string): Promise<void> => {
496
415
  if (input.log === undefined) console.error(`run ${input.runId}: ${line}`)
497
416
  else await input.log(line)
498
417
  }
499
- const outcome = await settleOutcome(options, target, recovery, log, true)
500
- if (outcome.state === 'running') return outcome
418
+ const outcome = await settleOutcome(input.environment.access, recovery, log)
501
419
  return {
502
420
  state: outcome.state,
503
421
  ...(outcome.exitCode === undefined ? {} : { exitCode: outcome.exitCode }),
package/src/index.ts CHANGED
@@ -26,6 +26,6 @@ export type { CloudflareCloneSource, CloudflareControlOptions, CloudflareRunnerJ
26
26
  export { buildPlan, findMigratableDatabases, PLATFORM_RESOURCE_NAMES } from './plan'
27
27
  export type { CloudflareStep, CloudflareStepKind, MigratableDatabase } from './plan'
28
28
  export { type CloudflareDeployerOptions, type CloudflareDeployResult, type CloudflareDeployRun, createCloudflareDeployer } from './provider'
29
- export { createCloudflareProxyWorker, IAM_APPLICATION_ENTRYPOINT, iamServiceReference } from './proxy'
29
+ export { createCloudflareProxyWorker, IAM_APPLICATION_ENTRYPOINT, iamServiceReference, proxyManifestJson } from './proxy'
30
30
  export type { CloudflareProxyWorkerOptions } from './proxy'
31
31
  export { type AppSchemaParse, parseAppSchema } from './schema'
@@ -21,17 +21,20 @@ import {
21
21
  confirmations,
22
22
  detail,
23
23
  type EnvironmentConfig,
24
+ generateSigningKeys,
25
+ generateVaultKey,
24
26
  ghRepoExists,
25
27
  info,
26
28
  type InstallationEmail,
27
29
  ok,
28
30
  type ProtectionOutcome,
31
+ randomPxKey,
32
+ randomSecret,
29
33
  step,
30
34
  triggerPlatformWorkflow,
31
35
  url,
32
36
  warn,
33
37
  } from '@fabrika/installation-init'
34
- import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto'
35
38
  import { type CfAccount, type CfZone, findZone, listAccounts, selectAccount, verifyToken } from './cloudflare'
36
39
  import { envPath, fromEnv, openEnvFile, persistEnv } from './envfile'
37
40
  import { type InitInput, parseInitAccount, parseInitArgs, PLACEHOLDER_OIDC_CLIENT_ID, rerunCommand } from './init-options'
@@ -356,7 +359,7 @@ interface VaultKeyDependencies {
356
359
  const vaultKeyDependencies: VaultKeyDependencies = {
357
360
  source: ENVIRONMENT_SOURCE,
358
361
  persist: persistEnv,
359
- generate: () => randomBytes(32).toString('base64'),
362
+ generate: generateVaultKey,
360
363
  created: action,
361
364
  }
362
365
 
@@ -381,8 +384,8 @@ export async function ensureVaultKey(dependencies: VaultKeyDependencies = vaultK
381
384
  * Generate the operator-side provisioning key (the "seeded key"): a single opaque `px_` bearer, stored
382
385
  * once. IAM Stage 1 SEEDS it (the `FABRIKA_IAM_PROVISIONING_KEY` secret — `resolveCaller` admits a
383
386
  * bearer matching it as a synthetic admin) and fabrika Stage 2 USES it to authenticate schema reconciles.
384
- * Shaped like an IAM-native key (`px_` + 160 bits base64url). An operator who already has one can
385
- * pre-set `FABRIKA_IAM_PROVISIONING_KEY` in env and init reuses it.
387
+ * The same `px_` key a Zerops installation generates (`randomPxKey`, 256 bits). An operator who already has
388
+ * one can pre-set `FABRIKA_IAM_PROVISIONING_KEY` in env and init reuses it.
386
389
  */
387
390
  async function ensureProvisioningKey(): Promise<string> {
388
391
  step('Provisioning key (FABRIKA_IAM_PROVISIONING_KEY)')
@@ -392,7 +395,7 @@ async function ensureProvisioningKey(): Promise<string> {
392
395
  ok('Reusing the provisioning key from the installer env file (resume).')
393
396
  return existing
394
397
  }
395
- const key = `px_${randomBytes(20).toString('base64url')}`
398
+ const key = randomPxKey()
396
399
  await persistEnv('FABRIKA_IAM_PROVISIONING_KEY', key)
397
400
  ok('Provisioning key generated + saved to the installer env file.')
398
401
  detail('IAM Stage 1 seeds this as an admin credential; the control plane reconciles with it in Stage 2.')
@@ -407,7 +410,7 @@ async function ensureOperationsSyncKey(): Promise<string> {
407
410
  ok('Reusing OPERATIONS_SYNC_KEY from the installer env file (resume).')
408
411
  return existing
409
412
  }
410
- const key = randomBytes(32).toString('base64url')
413
+ const key = randomSecret()
411
414
  await persistEnv('OPERATIONS_SYNC_KEY', key)
412
415
  ok('Operations catalog key generated + saved to the installer env file.')
413
416
  return key
@@ -426,23 +429,13 @@ export async function ensureRunnerKey(): Promise<string> {
426
429
  ok('Reusing FABRIKA_RUNNER_KEY from the installer env file (resume).')
427
430
  return existing
428
431
  }
429
- const key = randomBytes(32).toString('base64url')
432
+ const key = randomSecret()
430
433
  await persistEnv('FABRIKA_RUNNER_KEY', key)
431
434
  ok('Runner key generated + saved to the installer env file.')
432
435
  detail('The pipeline pushes it to the control plane and the deploy runner as a Worker secret.')
433
436
  return key
434
437
  }
435
438
 
436
- /** One ES256 (EC P-256) private JWK with an RFC 7638 thumbprint `kid`, shaped exactly as IAM's
437
- * `Signer.fromPrivateJwks` loads it (index 0 = the active signer). */
438
- function generateEs256Jwk(): JsonWebKey & { kid: string } {
439
- const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })
440
- const jwk = privateKey.export({ format: 'jwk' })
441
- // RFC 7638 thumbprint over the canonical EC members, lexicographic order (crv, kty, x, y).
442
- const thumbprint = createHash('sha256').update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })).digest('base64url')
443
- return { ...jwk, kid: thumbprint, alg: 'ES256', use: 'sig' }
444
- }
445
-
446
439
  /**
447
440
  * Generate IAM's token-signing key (Stage 1): a JSON array with one ES256 private JWK. IAM
448
441
  * signs every token it issues with index 0 and publishes the public half in its JWKS. Stored once
@@ -457,7 +450,7 @@ async function ensureSigningKeys(): Promise<string> {
457
450
  ok('Reusing FABRIKA_IAM_SIGNING_KEYS from the installer env file (resume).')
458
451
  return existing
459
452
  }
460
- const keys = JSON.stringify([generateEs256Jwk()])
453
+ const keys = generateSigningKeys()
461
454
  await persistEnv('FABRIKA_IAM_SIGNING_KEYS', keys)
462
455
  ok('IAM signing key generated (1 × ES256) + saved to the installer env file.')
463
456
  return keys
@@ -1,4 +1,4 @@
1
- import { builtinEmailProviders } from '@fabrika/email/providers'
1
+ import { builtinEmailProviders, builtinEmailProviderVariables } from '@fabrika/email/providers'
2
2
  import { IAM_APP_ID, IAM_APP_SCHEMA } from '@fabrika/iam-contract'
3
3
  import type { InstallationCli, InstallationCommand } from '@fabrika/provider-contract/installation'
4
4
  import { resolve } from 'node:path'
@@ -9,9 +9,7 @@ import { defaultReconcileSchema } from '../schema'
9
9
  import { initCommand } from './init'
10
10
 
11
11
  const EMAIL_PROVIDERS = Object.keys(builtinEmailProviders).join(', ')
12
- const EMAIL_PROVIDER_VARIABLES = Object.values(builtinEmailProviders)
13
- .flatMap((provider) => provider.variables.map((variable) => variable.name))
14
- .join(', ')
12
+ const EMAIL_PROVIDER_VARIABLES = builtinEmailProviderVariables.map((variable) => variable.name).join(', ')
15
13
 
16
14
  const USAGE = `Cloudflare installation
17
15
 
@@ -7,6 +7,7 @@
7
7
  * base); `platform.yml` / `README.md` / `.gitignore` are CLI-owned and refreshed every run.
8
8
  */
9
9
 
10
+ import { builtinEmailProviders, builtinEmailProviderVariables } from '@fabrika/email/providers'
10
11
  import {
11
12
  INITIAL_SCAFFOLD_COMMIT_MESSAGE,
12
13
  type ProtectionOutcome,
@@ -43,10 +44,36 @@ export interface ScaffoldResult {
43
44
  branchProtection?: ProtectionOutcome
44
45
  }
45
46
 
46
- /** Render a template: replace every `{{ACCOUNT}}` token. (Account is the only placeholder today.) */
47
+ /**
48
+ * Render a template: replace every `{{ACCOUNT}}` token, and the mail placeholders with the built-in providers, so a
49
+ * provider added to the registry reaches the workflow and the README without a template edit.
50
+ */
47
51
  async function renderTemplate(name: string, account: string): Promise<string> {
48
52
  const raw = await Bun.file(resolve(TEMPLATES, name)).text()
49
- return raw.replaceAll('{{ACCOUNT}}', account)
53
+ return raw
54
+ .replaceAll('{{ACCOUNT}}', () => account)
55
+ .replaceAll('{{EMAIL_PROVIDER_NAMES}}', () => Object.keys(builtinEmailProviders).join('|'))
56
+ .replaceAll(/^\{\{EMAIL_PROVIDER_VARIABLES\}\}$/gm, () => emailProviderVariablesList())
57
+ .replaceAll(/^( *)# \{\{EMAIL_PROVIDER_ENV\}\}$/gm, (_line, indent: string) => emailProviderEnv(indent))
58
+ }
59
+
60
+ /** Each provider's variables, a credential from the Environment's secrets and the rest from its variables. */
61
+ function emailProviderEnv(indent: string): string {
62
+ return builtinEmailProviderVariables
63
+ .map((variable) => `${indent}${variable.name}: \${{ ${variable.secret ? 'secrets' : 'vars'}.${variable.name} }}`)
64
+ .join('\n')
65
+ }
66
+
67
+ /** The README's list: one line per provider, naming its variables and how each is stored. */
68
+ function emailProviderVariablesList(): string {
69
+ return Object.entries(builtinEmailProviders)
70
+ .map(([name, provider]) => {
71
+ const variables = provider.variables.map((variable) =>
72
+ `\`${variable.name}\` (${variable.secret ? 'secret' : 'variable'}${variable.required ? '' : ', optional'})`
73
+ )
74
+ return `- \`${name}\`: ${variables.join(', ')}`
75
+ })
76
+ .join('\n')
50
77
  }
51
78
 
52
79
  /** Write the file at `rel` under `dir` with `content`, creating parent dirs as needed. */
@@ -42,7 +42,7 @@ Run init with the Cloudflare API token in `CLOUDFLARE_API_TOKEN`:
42
42
  ```sh
43
43
  fabrika platform init --provider=cloudflare {{ACCOUNT}} \
44
44
  --console-host=<host> --operations-host=<host> --iam-host=<host> \
45
- --auth-methods=<oidc|password|oidc,password> --email-provider=<none|resend|smartemailing>
45
+ --auth-methods=<oidc|password|oidc,password> --email-provider=<none|{{EMAIL_PROVIDER_NAMES}}>
46
46
  ```
47
47
 
48
48
  `fabrika platform init --provider=cloudflare --help` lists the optional flags. It creates this repo,
@@ -59,15 +59,21 @@ To close the escape hatch once IAM grants you admin, set the `{{ACCOUNT}}` Envir
59
59
  IAM authentication methods are independent Environment switches: `FABRIKA_IAM_OIDC_ENABLED` and
60
60
  `FABRIKA_IAM_PASSWORD_ENABLED`. At least one must be `true`. Password enrollment is managed through
61
61
  IAM provisioning and its admin surface. Email delivery is optional; `FABRIKA_EMAIL_PROVIDER=none`
62
- keeps password enrollment and reset admin-driven. A provider (`resend` or `smartemailing`) also needs
63
- the sender variable `FABRIKA_EMAIL_FROM` (optionally `FABRIKA_EMAIL_FROM_NAME`) and its own variables:
64
- `FABRIKA_EMAIL_RESEND_API_KEY` as a secret for Resend; `FABRIKA_EMAIL_SMARTEMAILING_USERNAME` and
65
- `FABRIKA_EMAIL_SMARTEMAILING_API_KEY` as secrets and optionally `FABRIKA_EMAIL_SMARTEMAILING_TAG` as a
66
- variable for SmartEmailing. To change or rotate them, re-run `fabrika platform init` with the new values;
67
- it rewrites this Environment and triggers the workflow, which redeploys IAM.
68
-
69
- Switching provider leaves the old provider's values stored: init writes the new ones and deletes none. IAM
70
- reads only the selected provider's variables, but delete the old credentials so nothing holds them, for
62
+ keeps password enrollment and reset admin-driven. A provider also needs the sender variable
63
+ `FABRIKA_EMAIL_FROM` (optionally `FABRIKA_EMAIL_FROM_NAME`) and its own Environment secrets and variables:
64
+
65
+ {{EMAIL_PROVIDER_VARIABLES}}
66
+
67
+ The workflow hands the same set to IAM and to the control plane. The control plane hands it to every application
68
+ whose job declares `mailer: 'installation'`, at that application's deploy.
69
+
70
+ To change or rotate them, re-run `fabrika platform init` with the new values; it rewrites this Environment
71
+ and triggers the workflow, which redeploys IAM and the control plane. An application gets the new set at its next
72
+ deploy: redeploy each environment that sends installation mail with
73
+ `fabrika control deploy --app=<id> --env=<name>`, or **Deploy** in the console.
74
+
75
+ Switching provider leaves the old provider's values stored: init writes the new ones and deletes none. IAM and
76
+ the control plane read only the selected provider's variables, but delete the old credentials so nothing holds them, for
71
77
  example after leaving SmartEmailing:
72
78
 
73
79
  ```sh
@@ -78,6 +84,16 @@ gh variable delete FABRIKA_EMAIL_SMARTEMAILING_TAG --env {{ACCOUNT}}
78
84
 
79
85
  Remove the same names from the installer env file (init prints its path when it starts), or a later run of
80
86
  init resumes them.
87
+ IAM's and the control plane's Workers also keep the old provider's credentials as Worker secrets, which neither reads.
88
+ Delete each of them from both Workers, with the account's id in `CLOUDFLARE_ACCOUNT_ID` and its API token in
89
+ `CLOUDFLARE_API_TOKEN`:
90
+
91
+ ```sh
92
+ for worker in prod-propustka-worker prod-vozka; do
93
+ bunx wrangler secret delete FABRIKA_EMAIL_SMARTEMAILING_USERNAME --name "$worker"
94
+ bunx wrangler secret delete FABRIKA_EMAIL_SMARTEMAILING_API_KEY --name "$worker"
95
+ done
96
+ ```
81
97
 
82
98
  ## Routine redeploy or version bump
83
99
 
@@ -88,4 +104,6 @@ Both paths rebuild the account-owned runner image from the exact checkout select
88
104
 
89
105
  `fabrika.ref` is operator-owned. `fabrika platform init` creates it once and does not overwrite later version pins.
90
106
  A bump does not rewrite this workflow. Re-run `fabrika platform init --provider=cloudflare {{ACCOUNT}}` with the same
91
- flags to bring `.github/workflows/platform.yml` to the one the current CLI generates.
107
+ flags, with the CLI of the release `fabrika.ref` names, to bring `.github/workflows/platform.yml` to the one that release
108
+ generates. A change in what the workflow hands a stage (such as the mail transport the control plane holds) reaches
109
+ the account only this way.
@@ -140,17 +140,15 @@ jobs:
140
140
  FABRIKA_IAM_OIDC_CLIENT_ID: ${{ vars.FABRIKA_IAM_OIDC_CLIENT_ID }}
141
141
  FABRIKA_IAM_OIDC_SCOPES: ${{ vars.FABRIKA_IAM_OIDC_SCOPES }}
142
142
  FABRIKA_IAM_OIDC_REQUIRE_VERIFIED_EMAIL: ${{ vars.FABRIKA_IAM_OIDC_REQUIRE_VERIFIED_EMAIL }}
143
- # Every built-in mail provider's variables: IAM reads only the selected provider's, and an unset one is ''.
144
143
  FABRIKA_EMAIL_PROVIDER: ${{ vars.FABRIKA_EMAIL_PROVIDER }}
145
144
  FABRIKA_EMAIL_FROM: ${{ vars.FABRIKA_EMAIL_FROM }}
146
145
  FABRIKA_EMAIL_FROM_NAME: ${{ vars.FABRIKA_EMAIL_FROM_NAME }}
147
- FABRIKA_EMAIL_SMARTEMAILING_TAG: ${{ vars.FABRIKA_EMAIL_SMARTEMAILING_TAG }}
148
146
  FABRIKA_IAM_SIGNING_KEYS: ${{ secrets.FABRIKA_IAM_SIGNING_KEYS }}
149
147
  OIDC_CLIENT_SECRET: ${{ secrets.FABRIKA_IAM_OIDC_CLIENT_SECRET }}
150
- FABRIKA_EMAIL_RESEND_API_KEY: ${{ secrets.FABRIKA_EMAIL_RESEND_API_KEY }}
151
- FABRIKA_EMAIL_SMARTEMAILING_USERNAME: ${{ secrets.FABRIKA_EMAIL_SMARTEMAILING_USERNAME }}
152
- FABRIKA_EMAIL_SMARTEMAILING_API_KEY: ${{ secrets.FABRIKA_EMAIL_SMARTEMAILING_API_KEY }}
153
148
  FABRIKA_IAM_PROVISIONING_KEY: ${{ secrets.FABRIKA_IAM_PROVISIONING_KEY }}
149
+ # Every built-in mail provider's variables, written by init from the provider registry: IAM reads only the
150
+ # selected provider's, and an unset one is ''.
151
+ # {{EMAIL_PROVIDER_ENV}}
154
152
  # `platform deploy`, not `app deploy`: IAM's own Worker is a PLATFORM resource name, and only the
155
153
  # platform verb may name one. The single-component form deploys just this config.
156
154
  run: fabrika platform deploy --provider=cloudflare --env=prod --component-config=fabrika.config.ts
@@ -190,6 +188,12 @@ jobs:
190
188
  FABRIKA_IAM_ISSUER: ${{ vars.FABRIKA_IAM_ISSUER }}
191
189
  OPERATIONS_ARTIFACT_ORIGIN: https://${{ vars.OPERATIONS_HOSTNAME }}
192
190
  FABRIKA_CONTROL_BOOTSTRAP_ADMINS: ${{ vars.FABRIKA_CONTROL_BOOTSTRAP_ADMINS }}
191
+ # The installation's mail transport, the same set as IAM's: the control plane hands it to every application
192
+ # whose job declares `mailer: 'installation'`. Its credentials become Worker secrets of the control plane only.
193
+ FABRIKA_EMAIL_PROVIDER: ${{ vars.FABRIKA_EMAIL_PROVIDER }}
194
+ FABRIKA_EMAIL_FROM: ${{ vars.FABRIKA_EMAIL_FROM }}
195
+ FABRIKA_EMAIL_FROM_NAME: ${{ vars.FABRIKA_EMAIL_FROM_NAME }}
196
+ # {{EMAIL_PROVIDER_ENV}}
193
197
  run: |
194
198
  fabrika platform deploy --provider=cloudflare \
195
199
  --runner-config=packages/runner-cloudflare/fabrika-runner.config.ts \
@@ -0,0 +1,61 @@
1
+ import { isFrameworkVariableName } from '@fabrika/auth-core'
2
+ import type { ProviderManagedEnvironment } from '@fabrika/provider-contract'
3
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { z } from 'zod'
7
+
8
+ export interface ManagedSplit {
9
+ readonly vars: Readonly<Record<string, string>>
10
+ readonly secrets: Readonly<Record<string, string>>
11
+ }
12
+
13
+ /** The values a deploy writes: a credential as a Worker secret, any other as a plain var; a null value is not written. */
14
+ export const splitManagedEnvironment = (managed: ProviderManagedEnvironment): ManagedSplit => {
15
+ const vars: Record<string, string> = {}
16
+ const secrets: Record<string, string> = {}
17
+ for (const [name, { value, credential }] of Object.entries(managed)) {
18
+ if (value === null) continue
19
+ if (credential) secrets[name] = value
20
+ else vars[name] = value
21
+ }
22
+ return { vars, secrets }
23
+ }
24
+
25
+ /**
26
+ * Run `body` with the secrets in a JSON file only its owner reads, in a directory of its own, removed however `body`
27
+ * ends. `body` gets null when there is nothing to write.
28
+ */
29
+ export const withSecretsFile = async <T>(secrets: Readonly<Record<string, string>>, body: (path: string | null) => Promise<T>): Promise<T> => {
30
+ if (Object.keys(secrets).length === 0) return body(null)
31
+ const dir = await mkdtemp(join(tmpdir(), 'fabrika-secrets-'))
32
+ try {
33
+ const path = join(dir, 'secrets.json')
34
+ await writeFile(path, JSON.stringify(secrets), { mode: 0o600, flag: 'wx' })
35
+ return await body(path)
36
+ } finally {
37
+ await rm(dir, { recursive: true, force: true })
38
+ }
39
+ }
40
+
41
+ const secretListSchema = z.array(z.object({ name: z.string() }))
42
+
43
+ /** The names `wrangler secret list --format json` printed. */
44
+ export const parseSecretNames = (stdout: string): readonly string[] => {
45
+ let decoded: unknown
46
+ try {
47
+ decoded = JSON.parse(stdout)
48
+ } catch {
49
+ decoded = undefined
50
+ }
51
+ const list = secretListSchema.safeParse(decoded)
52
+ if (!list.success) throw new Error('wrangler secret list printed no readable list of secrets')
53
+ return list.data.map((secret) => secret.name)
54
+ }
55
+
56
+ /**
57
+ * The framework secrets a Worker still holds that this deploy no longer writes. Wider than `staleManagedVariables`: the
58
+ * executor writes no framework secret of its own, so any other one is stale.
59
+ */
60
+ export const staleManagedSecrets = (present: readonly string[], written: Readonly<Record<string, string>>): readonly string[] =>
61
+ present.filter((name) => isFrameworkVariableName(name) && !Object.hasOwn(written, name))
package/src/plan.ts CHANGED
@@ -68,11 +68,19 @@ export const PLATFORM_RESOURCE_NAMES: ReadonlySet<string> = new Set([
68
68
  'operations-ingest-dlq',
69
69
  ])
70
70
 
71
- export const buildPlan = (config: CloudflareAppConfig, worker: Worker): readonly CloudflareStep[] => {
71
+ const ENTRY_BUILD = '`fabrika app build --provider=cloudflare`'
72
+
73
+ /** `regeneratesEntry`: the release pins the generated entry, so the build step always runs, after `pipeline.build`. */
74
+ export const buildPlan = (config: CloudflareAppConfig, worker: Worker, regeneratesEntry: boolean): readonly CloudflareStep[] => {
72
75
  const steps: CloudflareStep[] = []
73
76
 
74
- if (config.pipeline?.build !== undefined) {
75
- steps.push({ id: 'build', kind: 'build', description: `Build the Worker (\`${config.pipeline.build}\`)` })
77
+ const build = config.pipeline?.build
78
+ if (build !== undefined && regeneratesEntry) {
79
+ steps.push({ id: 'build', kind: 'build', description: `Build the Worker (\`${build}\`), then regenerate its entry (${ENTRY_BUILD})` })
80
+ } else if (build !== undefined) {
81
+ steps.push({ id: 'build', kind: 'build', description: `Build the Worker (\`${build}\`)` })
82
+ } else if (regeneratesEntry) {
83
+ steps.push({ id: 'build', kind: 'build', description: `Regenerate the Worker's entry (${ENTRY_BUILD})` })
76
84
  }
77
85
 
78
86
  steps.push({ id: 'provision-resources', kind: 'provision-resources', description: 'Provision Cloudflare resources via oblaka' })