@fabrika/provider-cloudflare 0.8.2 → 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 (43) 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/templates/README.md +21 -4
  10. package/src/installation/templates/platform.yml +6 -0
  11. package/src/managed-secrets.ts +61 -0
  12. package/src/plan.ts +11 -3
  13. package/src/provider.ts +277 -54
  14. package/src/proxy-worker.ts +33 -13
  15. package/src/proxy.ts +48 -16
  16. package/src/runner-protocol.ts +16 -1
  17. package/types/src/assets.d.ts +8 -0
  18. package/types/src/authoring.d.ts +17 -0
  19. package/types/src/bounds.d.ts +81 -0
  20. package/types/src/checkout.d.ts +7 -0
  21. package/types/src/cli-args.d.ts +25 -0
  22. package/types/src/cli.d.ts +8 -0
  23. package/types/src/codec.d.ts +8 -0
  24. package/types/src/collaborators.d.ts +52 -0
  25. package/types/src/command.d.ts +49 -0
  26. package/types/src/config-schema.d.ts +9 -0
  27. package/types/src/contract-support.d.ts +39 -0
  28. package/types/src/control.d.ts +468 -0
  29. package/types/src/index.d.ts +18 -0
  30. package/types/src/installation/cloudflare.d.ts +40 -0
  31. package/types/src/installation/envfile.d.ts +39 -0
  32. package/types/src/installation/index.d.ts +2 -0
  33. package/types/src/installation/init-options.d.ts +59 -0
  34. package/types/src/installation/init.d.ts +114 -0
  35. package/types/src/installation/installation.d.ts +2 -0
  36. package/types/src/installation/scaffold.d.ts +39 -0
  37. package/types/src/managed-secrets.d.ts +19 -0
  38. package/types/src/plan.d.ts +21 -0
  39. package/types/src/provider.d.ts +58 -0
  40. package/types/src/proxy-worker.d.ts +15 -0
  41. package/types/src/proxy.d.ts +72 -0
  42. package/types/src/runner-protocol.d.ts +121 -0
  43. package/types/src/schema.d.ts +17 -0
package/src/provider.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_APPLICATION_CLASS, CLOUDFLARE_FILES_BINDING, GENERATED_ENTRY_FILE } from '@fabrika/app/build'
1
2
  import {
2
3
  type AppEnvironment,
3
4
  appEnvironmentId,
@@ -5,18 +6,25 @@ import {
5
6
  connectVariables,
6
7
  type ContractArtifact,
7
8
  contractDigest,
9
+ DEFAULT_APPLICATION_OBJECT,
10
+ FABRIKA_APPLICATION_OBJECT,
11
+ FABRIKA_APPLICATION_OBJECTS,
8
12
  FABRIKA_CONTRACT_DIGEST,
9
13
  FABRIKA_IAM_ISSUER,
10
14
  isFrameworkVariableName,
15
+ isManagedCredential,
16
+ managedValue,
11
17
  } from '@fabrika/auth-core'
12
18
  import { type DeployStepResult, type ProviderManagedEnvironment, runSteps, type SchemaReconciler } from '@fabrika/provider-contract'
13
19
  import { isPolicyOrigin } from '@fabrika/proxy-core/headers'
14
20
  import { contractProxyTable } from '@fabrika/proxy-core/manifest'
15
- import { dirname, resolve } from 'node:path'
16
- import { type GeneratedConfig, ServiceReference, Worker } from 'oblaka-iac'
21
+ import { stat } from 'node:fs/promises'
22
+ import { basename, dirname, isAbsolute, relative, resolve } from 'node:path'
23
+ import { DurableObject, type GeneratedConfig, R2Bucket, ServiceReference, Worker } from 'oblaka-iac'
17
24
  import { assertLiteralAssets } from './assets'
18
25
  import type { CloudflareAppConfig } from './authoring'
19
26
  import {
27
+ type ApplicationRuntime,
20
28
  assertGeneratedConfigs,
21
29
  assertGeneration,
22
30
  assertStateNamespace,
@@ -27,8 +35,10 @@ import {
27
35
  import { runnerWorkerGraph } from './checkout'
28
36
  import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
29
37
  import { configSchema } from './config-schema'
38
+ import { assertCloudflareContract, needsMinuteTick, pinsGeneratedEntry, runsInObject, servesOps } from './contract-support'
39
+ import { parseSecretNames, splitManagedEnvironment, staleManagedSecrets, withSecretsFile } from './managed-secrets'
30
40
  import { buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
31
- import { createCloudflareProxyWorker } from './proxy'
41
+ import { createCloudflareProxyWorker, IamApplicationReference, PROXY_MANIFEST_DEFINE } from './proxy'
32
42
  import type { RunnerApprovedAccess } from './runner-protocol'
33
43
  import { defaultReconcileSchema } from './schema'
34
44
 
@@ -60,43 +70,176 @@ const assertRunning = (signal: AbortSignal): void => {
60
70
  }
61
71
  }
62
72
 
73
+ /** The bindings the platform writes into a contract application's Worker (ADR-0065). */
74
+ const PLATFORM_BINDINGS: ReadonlySet<string> = new Set([CLOUDFLARE_APPLICATION_BINDING, CLOUDFLARE_FILES_BINDING])
75
+
63
76
  /** An application never names a variable only the platform writes, whether or not this deploy writes it. */
64
77
  const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: CloudflareDeployRun): void => {
65
78
  const authored = [
66
79
  ...(config.pipeline?.vars ?? []),
80
+ ...(config.pipeline?.secrets ?? []),
67
81
  ...Object.keys(application.options.vars ?? {}),
68
82
  ...Object.keys(application.options.bindings ?? {}),
69
83
  ...Object.keys(run.vars),
84
+ ...Object.keys(run.secrets),
70
85
  ]
71
- const reserved = authored.find(isFrameworkVariableName)
86
+ const reserved = authored.find((name) => isFrameworkVariableName(name) || PLATFORM_BINDINGS.has(name))
72
87
  if (reserved !== undefined) {
73
88
  throw new Error(`cloudflare: application variable \`${reserved}\` is managed by Fabrika`)
74
89
  }
90
+ if (application.options.triggers !== undefined) {
91
+ throw new Error(`cloudflare: application Worker \`${application.options.name}\` sets \`triggers\`; the platform writes its cron triggers`)
92
+ }
75
93
  }
76
94
 
95
+ /**
96
+ * Write the managed values into the application Worker: the public ones as vars, and the credentials as Worker secrets
97
+ * the deploy uploads with the version (`withSecretsFile`), never as plain text in a generated config.
98
+ */
77
99
  const withManagedEnvironment = (
78
100
  config: CloudflareAppConfig,
79
101
  authored: Worker,
80
102
  run: CloudflareDeployRun,
81
103
  managed: ProviderManagedEnvironment,
82
- ): Worker => {
83
- const present: Record<string, string> = {}
84
- const declared = new Set(config.pipeline?.vars ?? [])
104
+ ): { readonly worker: Worker; readonly secrets: Readonly<Record<string, string>> } => {
105
+ const declared = new Set([...(config.pipeline?.vars ?? []), ...(config.pipeline?.secrets ?? [])])
85
106
  const application = applicationWorker(authored)
86
- for (const [name, value] of Object.entries(managed)) {
87
- if (declared.has(name) || application.options.vars?.[name] !== undefined || run.vars[name] !== undefined) {
107
+ for (const name of Object.keys(managed)) {
108
+ if (
109
+ declared.has(name) || application.options.vars?.[name] !== undefined || run.vars[name] !== undefined || run.secrets[name] !== undefined
110
+ ) {
88
111
  throw new Error(`cloudflare: application variable \`${name}\` is managed by Fabrika`)
89
112
  }
90
- if (value !== null) present[name] = value
91
113
  }
92
- if (Object.keys(present).length === 0) return authored
114
+ const { vars, secrets } = splitManagedEnvironment(managed)
115
+ if (Object.keys(vars).length === 0) return { worker: authored, secrets }
93
116
  const configured = new Worker({
94
117
  ...application.options,
95
118
  vars: {
96
119
  ...(application.options.vars ?? {}),
97
- ...present,
120
+ ...vars,
98
121
  },
99
122
  })
123
+ return { worker: replaceApplicationWorker(authored, configured), secrets }
124
+ }
125
+
126
+ /** R2's bucket names: 3 to 63 lowercase letters, digits and hyphens, starting and ending with a letter or a digit. */
127
+ const R2_BUCKET_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/
128
+
129
+ /** The environment's files bucket, before oblaka's environment prefix. */
130
+ const filesBucketName = (appId: string): string => `${appId}-files`
131
+
132
+ /** The remote name oblaka gives the files bucket; it prefixes a bucket with the environment, `local` included. */
133
+ const filesBucketRemote = (run: CloudflareDeployRun): string => {
134
+ const remote = `${run.env}-${filesBucketName(run.appId)}`
135
+ if (!R2_BUCKET_NAME.test(remote)) {
136
+ throw new Error(
137
+ `cloudflare: the files bucket \`${remote}\` of \`${run.appId}@${run.env}\` is not a valid R2 bucket name; shorten the app id or the environment`,
138
+ )
139
+ }
140
+ return remote
141
+ }
142
+
143
+ const MINUTE_TICK = '* * * * *'
144
+
145
+ /** What the platform gives a contract application's Worker; the deployer writes exactly this and the bounds check it. */
146
+ const applicationRuntime = (run: CloudflareDeployRun, contract: ContractArtifact, entry: string | null): ApplicationRuntime => ({
147
+ filesBucket: filesBucketRemote(run),
148
+ crons: needsMinuteTick(contract) ? [MINUTE_TICK] : [],
149
+ entry,
150
+ })
151
+
152
+ /** Where `fabrika app build` runs: the application directory, beside its config and contract, and the config it reads. */
153
+ interface EntryBuild {
154
+ readonly cwd: string
155
+ readonly config: string
156
+ /** The directory the runner installed the checkout's dependencies in; the CLI is looked for no higher. */
157
+ readonly root: string
158
+ }
159
+
160
+ /** The application's own CLI, where the checkout's `bun install` links it, as the Zerops build runs it. */
161
+ const APPLICATION_CLI = ['node_modules', '.bin', 'fabrika']
162
+
163
+ const ENTRY_BUILD_ARGS = ['app', 'build', '--provider=cloudflare']
164
+
165
+ /** All the CLI gets of the executor's environment: what Bun needs to run, as the generated tests of `fabrika db` get. */
166
+ const ENTRY_BUILD_VARIABLES: readonly string[] = ['PATH', 'HOME', 'TMPDIR']
167
+
168
+ const isFile = async (path: string): Promise<boolean> => {
169
+ try {
170
+ return (await stat(path)).isFile()
171
+ } catch {
172
+ return false
173
+ }
174
+ }
175
+
176
+ /** The first `node_modules/.bin/fabrika` from the application directory up to `root`: a workspace links it at its root. */
177
+ const applicationCli = async ({ cwd, root }: EntryBuild): Promise<string> => {
178
+ for (let dir = cwd; isWithin(root, dir); dir = dirname(dir)) {
179
+ const candidate = resolve(dir, ...APPLICATION_CLI)
180
+ if (await isFile(candidate)) return candidate
181
+ if (dir === root) break
182
+ }
183
+ throw new Error(
184
+ `fabrika app build: no \`${APPLICATION_CLI.join('/')}\` from \`${cwd}\` up to \`${root}\`; the application installs \`@fabrika/cli\``,
185
+ )
186
+ }
187
+
188
+ const isWithin = (root: string, dir: string): boolean => {
189
+ const path = relative(root, dir)
190
+ return path === '' || (!path.startsWith('..') && !isAbsolute(path))
191
+ }
192
+
193
+ /**
194
+ * The executor's environment carries the application's and the managed secrets, and the CLI is checkout code whose
195
+ * failed output reaches the log: it inherits nothing and gets only `ENTRY_BUILD_VARIABLES`.
196
+ */
197
+ const entryBuildEnvironment = (): { readonly env: Record<string, string>; readonly omitEnv: readonly string[] } => {
198
+ const env: Record<string, string> = {}
199
+ for (const name of ENTRY_BUILD_VARIABLES) {
200
+ const value = process.env[name]
201
+ if (value !== undefined) env[name] = value
202
+ }
203
+ return { env, omitEnv: Object.keys(process.env) }
204
+ }
205
+
206
+ /** Regenerate the entry and the inlined migrations from the checkout, with the application's own release of the CLI. */
207
+ const buildEntry = async (build: EntryBuild, run: CloudflareDeployRun, cf: CloudflareCollaborators): Promise<void> => {
208
+ const args = [...ENTRY_BUILD_ARGS, `--config=${build.config}`]
209
+ if (run.dryRun) {
210
+ run.log(` [dry-run] would run: fabrika ${args.join(' ')} in ${build.cwd}`)
211
+ return
212
+ }
213
+ assertRunning(run.signal)
214
+ const command = await applicationCli(build)
215
+ const result = await cf.runCommand({ command, args, cwd: build.cwd, ...entryBuildEnvironment(), signal: run.signal })
216
+ if (result.exitCode !== 0) throw commandError('fabrika app build', result)
217
+ }
218
+
219
+ /** The object variables of a release that serves ops (ADR-0069): ordinary traffic and ops requests reach `application`. */
220
+ const OBJECT_VARIABLES: Readonly<Record<string, string>> = {
221
+ [FABRIKA_APPLICATION_OBJECT]: DEFAULT_APPLICATION_OBJECT,
222
+ [FABRIKA_APPLICATION_OBJECTS]: DEFAULT_APPLICATION_OBJECT,
223
+ }
224
+
225
+ /**
226
+ * Bind the application's Durable Object, which runs the application over its SQLite, the environment's files bucket,
227
+ * and the minute tick (ADR-0065), and on a release that serves ops name its objects. The object is bound first, so
228
+ * oblaka numbers its migration `v0001` whatever else the application binds, and the tag never moves.
229
+ */
230
+ const withApplicationRuntime = (authored: Worker, run: CloudflareDeployRun, runtime: ApplicationRuntime, ops: boolean): Worker => {
231
+ const application = applicationWorker(authored)
232
+ const configured = new Worker({
233
+ ...application.options,
234
+ ...(ops ? { vars: { ...(application.options.vars ?? {}), ...OBJECT_VARIABLES } } : {}),
235
+ bindings: {
236
+ [CLOUDFLARE_APPLICATION_BINDING]: new DurableObject({ name: `${run.appId}-application`, className: CLOUDFLARE_APPLICATION_CLASS }),
237
+ ...(application.options.bindings ?? {}),
238
+ [CLOUDFLARE_FILES_BINDING]: new R2Bucket({ name: filesBucketName(run.appId) }),
239
+ },
240
+ // Always written: wrangler leaves a Worker's schedules alone when `triggers` is absent, and clears them on `[]`.
241
+ triggers: { crons: [...runtime.crons] },
242
+ })
100
243
  return replaceApplicationWorker(authored, configured)
101
244
  }
102
245
 
@@ -115,6 +258,19 @@ const connectorBindings = (contract: ContractArtifact | null): Readonly<Record<s
115
258
  Object.entries(contract?.imports ?? {}).map(([name, imported]) => [connectVariables(name).binding, proxyWorkerName(imported.app)]),
116
259
  )
117
260
 
261
+ /** The application Worker's `IAM` binding, written by the deployer so that it names this deployment (ADR-0067 §3). */
262
+ const withIamIdentity = (authored: Worker, iamAppId: string): Worker => {
263
+ const application = applicationWorker(authored)
264
+ const declared = application.options.bindings?.['IAM']
265
+ // A resource under the name is no IAM binding; oblaka provisions it, and the bounds check whatever it emits.
266
+ if (declared === undefined || 'getId' in declared) return authored
267
+ const configured = new Worker({
268
+ ...application.options,
269
+ bindings: { ...application.options.bindings, IAM: new IamApplicationReference(iamAppId, declared) },
270
+ })
271
+ return replaceApplicationWorker(authored, configured)
272
+ }
273
+
118
274
  const withConnectorBindings = (authored: Worker, bindings: Readonly<Record<string, string>>): Worker => {
119
275
  if (Object.keys(bindings).length === 0) return authored
120
276
  const application = applicationWorker(authored)
@@ -134,15 +290,13 @@ interface ServedContract {
134
290
  readonly digest: string
135
291
  }
136
292
 
137
- /** A contract application starts only as the contract it was deployed with (ADR-0022 rule 5), so the platform writes its digest. */
293
+ /**
294
+ * A contract application starts only as the contract it was deployed with (ADR-0022 rule 5), so the platform writes its
295
+ * digest. Control never hands one: `parseManagedEnvironment` refuses the name.
296
+ */
138
297
  const contractEnvironment = (managed: ProviderManagedEnvironment, served: ServedContract | null): ProviderManagedEnvironment => {
139
298
  if (served === null) return managed
140
- const { digest } = served
141
- const sent = managed[FABRIKA_CONTRACT_DIGEST]
142
- if (sent !== undefined && sent !== null && sent !== digest) {
143
- throw new Error(`cloudflare: ${FABRIKA_CONTRACT_DIGEST} is \`${sent}\`, but the contract this deployment serves has digest \`${digest}\``)
144
- }
145
- return { ...managed, [FABRIKA_CONTRACT_DIGEST]: digest }
299
+ return { ...managed, [FABRIKA_CONTRACT_DIGEST]: { value: served.digest, credential: isManagedCredential(FABRIKA_CONTRACT_DIGEST) } }
146
300
  }
147
301
 
148
302
  /**
@@ -162,8 +316,9 @@ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifa
162
316
  /**
163
317
  * The proxy Worker is the platform's (ADR-0048): built here, from this package's own entrypoint, around the
164
318
  * application Worker the config returns, never taken from the checkout. A config that returns a proxy is refused.
319
+ * `ops` adds Control's ops row to the table.
165
320
  */
166
- const platformProxied = (authored: Worker, served: ServedContract, run: CloudflareDeployRun): Worker => {
321
+ const platformProxied = (authored: Worker, served: ServedContract, run: CloudflareDeployRun, ops: boolean): Worker => {
167
322
  if (authored.options.bindings?.['APP'] !== undefined) {
168
323
  throw new Error(
169
324
  `cloudflare: \`resources\` returns the Worker \`${authored.options.name}\` binding \`APP\`, a proxy of its own; return the application Worker, and the platform builds the proxy Worker from its contract`,
@@ -180,16 +335,18 @@ const platformProxied = (authored: Worker, served: ServedContract, run: Cloudfla
180
335
  appHost: run.domain ?? 'localhost',
181
336
  ...(run.domain === undefined ? {} : { domain: run.domain }),
182
337
  ...(run.crossOrigins === undefined ? {} : { crossOrigins: run.crossOrigins }),
183
- endpoints: contractProxyTable(served.contract, served.digest),
184
- ...operationsOrigin(run.managedEnvironment),
185
- iamUrl: run.managedEnvironment[FABRIKA_IAM_ISSUER] ?? '',
338
+ endpoints: contractProxyTable(served.contract, served.digest, { ops }),
339
+ ...operationsOrigin(run),
340
+ iamUrl: managedValue(run.managedEnvironment, FABRIKA_IAM_ISSUER) ?? '',
186
341
  })
187
342
  }
188
343
 
189
- /** The ingest origin of the application's Operations DSN: the proxy's `connect-src` admits it, as the framework's does. */
190
- const operationsOrigin = (managed: ProviderManagedEnvironment): { readonly operationsOrigin?: string } => {
191
- const dsn = managed['FABRIKA_OPERATIONS_DSN']
192
- if (dsn === undefined || dsn === null) return {}
344
+ /** The origin of the environment's Operations ingest, which the proxy's `connect-src` admits, as the framework's does. */
345
+ const operationsOrigin = (run: CloudflareDeployRun): { readonly operationsOrigin?: string } => {
346
+ if (run.operationsOrigin !== undefined) return { operationsOrigin: run.operationsOrigin }
347
+ // A job from an older Control names no origin; derive it from the DSN until no release in the window omits it.
348
+ const dsn = managedValue(run.managedEnvironment, 'FABRIKA_OPERATIONS_DSN')
349
+ if (dsn === null) return {}
193
350
  let origin: string
194
351
  try {
195
352
  origin = new URL(dsn).origin
@@ -249,9 +406,64 @@ interface StepEnv {
249
406
  readonly platformIam: PlatformIamTarget | undefined
250
407
  readonly reconcileSchema: SchemaReconciler
251
408
  readonly bounds: DeploymentBounds
409
+ /** The managed credentials the application Worker's version is uploaded with, as Worker secrets. */
410
+ readonly managedSecrets: Readonly<Record<string, string>>
411
+ /** Where the build step regenerates the entry, after `pipeline.build`; null for a release that keeps its authored `main`. */
412
+ readonly entryBuild: EntryBuild | null
252
413
  generatedConfigs: readonly GeneratedConfig[]
253
414
  }
254
415
 
416
+ /**
417
+ * `wrangler deploy`, with the managed secrets uploaded in the same version when there are any, so the version never
418
+ * serves without them, and a plain var of the same name an older release wrote goes with the old version.
419
+ */
420
+ const wranglerDeploy = async (env: StepEnv, cwd: string, secrets: Readonly<Record<string, string>>): Promise<void> => {
421
+ const { run, credentials, cf } = env
422
+ const names = Object.keys(secrets)
423
+ if (run.dryRun) {
424
+ run.log(` [dry-run] would run: wrangler deploy${names.length === 0 ? '' : ` with the secrets ${names.join(', ')}`} in ${cwd}`)
425
+ return
426
+ }
427
+ assertRunning(run.signal)
428
+ await withSecretsFile(secrets, async (path) => {
429
+ const args = path === null ? ['deploy'] : ['deploy', '--secrets-file', path]
430
+ const result = await cf.runCommand({ command: 'wrangler', args, cwd, env: wranglerEnv(credentials), signal: run.signal })
431
+ if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
432
+ })
433
+ }
434
+
435
+ /** Delete the framework secrets the application Worker holds that this deploy no longer writes, as Zerops removes them. */
436
+ const deleteStaleSecrets = async (env: StepEnv, cwd: string): Promise<void> => {
437
+ const { run, credentials, cf } = env
438
+ if (run.dryRun) {
439
+ run.log(` [dry-run] would delete the managed secrets this deploy no longer writes in ${cwd}`)
440
+ return
441
+ }
442
+ assertRunning(run.signal)
443
+ const listed = await cf.runCommand({
444
+ command: 'wrangler',
445
+ args: ['secret', 'list', '--format', 'json'],
446
+ cwd,
447
+ env: wranglerEnv(credentials),
448
+ signal: run.signal,
449
+ })
450
+ if (listed.exitCode !== 0) throw commandError('wrangler secret list', listed)
451
+ for (const name of staleManagedSecrets(parseSecretNames(listed.stdout), env.managedSecrets)) {
452
+ assertRunning(run.signal)
453
+ // A piped stdin keeps wrangler non-interactive, so its confirmation takes its fallback answer.
454
+ const result = await cf.runCommand({
455
+ command: 'wrangler',
456
+ args: ['secret', 'delete', name],
457
+ cwd,
458
+ env: wranglerEnv(credentials),
459
+ stdin: '',
460
+ signal: run.signal,
461
+ })
462
+ if (result.exitCode !== 0) throw commandError(`wrangler secret delete ${name}`, result)
463
+ run.log(` deleted the managed secret ${name}, which this deploy no longer writes`)
464
+ }
465
+ }
466
+
255
467
  const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
256
468
  const { config, run, credentials, worker, dir, cf } = env
257
469
  const { signal, dryRun } = run
@@ -259,14 +471,14 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
259
471
  switch (spec.kind) {
260
472
  case 'build': {
261
473
  const build = config.pipeline?.build
262
- if (build === undefined) return
263
- if (dryRun) {
474
+ if (build !== undefined && dryRun) {
264
475
  run.log(` [dry-run] would run build: \`${build}\` in ${dir}`)
265
- return
476
+ } else if (build !== undefined) {
477
+ assertRunning(signal)
478
+ const result = await cf.runCommand({ command: 'sh', args: ['-c', build], cwd: dir, omitEnv: PLATFORM_CREDENTIAL_NAMES, signal })
479
+ if (result.exitCode !== 0) throw commandError(`build (\`${build}\`)`, result)
266
480
  }
267
- assertRunning(signal)
268
- const result = await cf.runCommand({ command: 'sh', args: ['-c', build], cwd: dir, omitEnv: PLATFORM_CREDENTIAL_NAMES, signal })
269
- if (result.exitCode !== 0) throw commandError(`build (\`${build}\`)`, result)
481
+ if (env.entryBuild !== null) await buildEntry(env.entryBuild, run, cf)
270
482
  return
271
483
  }
272
484
  case 'provision-resources': {
@@ -311,26 +523,18 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
311
523
  // The configs oblaka wrote, not the generation checked before the run: a stateful binding can emit differently twice.
312
524
  assertGeneratedConfigs(configs, env.bounds)
313
525
  if (configs.length === 0) {
314
- if (dryRun) {
315
- run.log(` [dry-run] would run: wrangler deploy in ${dir}`)
316
- return
317
- }
318
- assertRunning(signal)
319
- const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: dir, env: wranglerEnv(credentials), signal })
320
- if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
526
+ await wranglerDeploy(env, dir, env.managedSecrets)
321
527
  return
322
528
  }
529
+ const application = `${run.env}-${applicationWorker(worker).options.name}`
323
530
  for (const generated of configs) {
324
531
  const generatedDir = dirname(resolve(dir, generated.path))
325
532
  // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
326
533
  if (env.platformResources === 'refuse') await assertLiteralAssets(generated, generatedDir)
327
- if (dryRun) {
328
- run.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
329
- continue
330
- }
331
- assertRunning(signal)
332
- const result = await cf.runCommand({ command: 'wrangler', args: ['deploy'], cwd: generatedDir, env: wranglerEnv(credentials), signal })
333
- if (result.exitCode !== 0) throw commandError('wrangler deploy', result)
534
+ const isApplication = generated.config.name === application
535
+ await wranglerDeploy(env, generatedDir, isApplication ? env.managedSecrets : {})
536
+ // A platform component's own secrets carry framework names (IAM's mail transport), so only an application's are swept.
537
+ if (isApplication && env.platformResources === 'refuse') await deleteStaleSecrets(env, generatedDir)
334
538
  }
335
539
  return
336
540
  }
@@ -424,6 +628,8 @@ export interface CloudflareDeployRun {
424
628
  readonly domain?: string
425
629
  /** The environment's cross-origin list from Control's registry (ADR-0022); the proxy Worker's manifest entry lists it. */
426
630
  readonly crossOrigins?: readonly string[]
631
+ /** The origin of the environment's Operations ingest, from Control; the proxy Worker's `connect-src` admits it. */
632
+ readonly operationsOrigin?: string
427
633
  /** Every origin IAM may hand this environment a session at, registered under `<app>@<env>`. */
428
634
  readonly returnOrigins?: readonly string[]
429
635
  readonly cwd: string
@@ -475,18 +681,29 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
475
681
  if (platformResources === 'refuse' && served === null) {
476
682
  throw new Error('cloudflare: the checkout has no `fabrika.contract.ts`; Fabrika deploys an application only with a contract')
477
683
  }
684
+ if (platformResources === 'refuse' && contract !== null) assertCloudflareContract(contract)
478
685
  // Read once, before `resources()` runs the checkout's code again: nothing below reads the config's schema.
479
686
  const schema = configSchema(loaded.config)
480
687
  assertContractSchema(schema, contract)
481
688
  const authored = runnerWorkerGraph(loaded.config.resources({ env: run.env, domain: run.domain }))
482
- // Fabrika's own components compose their own proxies; every application gets the platform's.
483
- const proxied = platformResources === 'refuse' && served !== null ? platformProxied(authored, served, run) : authored
689
+ // Only a release Control named pins the entry or serves ops; a local deploy names none and keeps its authored `main`.
690
+ const release = run.approved?.framework
691
+ const opsRelease = release !== undefined && servesOps(release)
692
+ // Fabrika's own components compose their own proxies; every application gets the platform's. Without a domain no
693
+ // Custom Domain carries the ops channel, so the proxy gets no ops row (ADR-0069).
694
+ const proxied = platformResources === 'refuse' && served !== null
695
+ ? platformProxied(authored, served, run, opsRelease && run.domain !== undefined)
696
+ : authored
484
697
  if (platformResources === 'refuse') assertNoFrameworkVariables(loaded.config, applicationWorker(proxied), run)
485
698
  const connectors = platformResources === 'refuse' ? connectorBindings(contract) : {}
486
- const worker = withConnectorBindings(
487
- withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served)),
488
- connectors,
489
- )
699
+ // An older release's entry exports no object, and a Control older than the runner names no release (ADR-0062).
700
+ const objectRuntime = run.approved === undefined || (run.approved.framework !== undefined && runsInObject(run.approved.framework))
701
+ const entry = release !== undefined && pinsGeneratedEntry(release) ? resolve(loaded.cwd, GENERATED_ENTRY_FILE) : null
702
+ const runtime = platformResources === 'refuse' && contract !== null && objectRuntime ? applicationRuntime(run, contract, entry) : null
703
+ const managed = withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served))
704
+ const identified = platformResources === 'refuse' ? withIamIdentity(managed.worker, appEnvironmentId(run.appId, run.env)) : managed.worker
705
+ const connected = withConnectorBindings(identified, connectors)
706
+ const worker = runtime === null ? connected : withApplicationRuntime(connected, run, runtime, opsRelease)
490
707
  const dir = workerDir(loaded.config, loaded.cwd)
491
708
  const bounds: DeploymentBounds = {
492
709
  env: run.env,
@@ -501,6 +718,8 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
501
718
  application: frameworkValues(applicationWorker(worker).options.vars),
502
719
  proxy: proxied === authored ? null : frameworkValues(worker.options.vars),
503
720
  },
721
+ proxyManifest: proxied === authored ? null : (worker.options.define?.[PROXY_MANIFEST_DEFINE] ?? null),
722
+ application: runtime,
504
723
  }
505
724
  assertStateNamespace(stateNamespace(loaded.config, run), platformResources)
506
725
  assertGeneration(await generateWranglerConfigs(worker, run.env), bounds)
@@ -516,8 +735,12 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
516
735
  platformIam: options.platformIam,
517
736
  reconcileSchema: options.reconcileSchema ?? defaultReconcileSchema,
518
737
  bounds,
738
+ managedSecrets: managed.secrets,
739
+ entryBuild: runtime !== null && runtime.entry !== null
740
+ ? { cwd: loaded.cwd, config: basename(resolve(run.cwd, run.configPath)), root: resolve(run.cwd) }
741
+ : null,
519
742
  generatedConfigs: [],
520
743
  }
521
- const result = await runSteps(buildPlan(loaded.config, worker), run, (step) => runStep(step, env))
744
+ const result = await runSteps(buildPlan(loaded.config, worker, env.entryBuild !== null), run, (step) => runStep(step, env))
522
745
  return { appId: run.appId, env: run.env, ...result }
523
746
  }
@@ -7,11 +7,14 @@ import {
7
7
  DEFAULT_VERIFY_PATH,
8
8
  DELEGATION_HEADER,
9
9
  ENDPOINT_HEADER,
10
+ errorAnswer,
11
+ type ErrorPageStatus,
10
12
  FORWARD_AUTHORIZATION_HEADER,
11
13
  FORWARDED_HOST_HEADER,
12
14
  FORWARDED_METHOD_HEADER,
13
15
  FORWARDED_PROTO_HEADER,
14
16
  FORWARDED_URI_HEADER,
17
+ isPageNavigation,
15
18
  MemoryTokenCache,
16
19
  OAUTH_METADATA_VERIFY_PATH,
17
20
  PREFLIGHT_HEADER,
@@ -49,6 +52,7 @@ const CLOUDFLARE_CLIENT_ADDRESS_HEADER = 'CF-Connecting-IP'
49
52
 
50
53
  export interface CloudflareProxyEnv {
51
54
  readonly IAM?: unknown
55
+ /** The manifest JSON the handler serves; the deployed Worker passes the one baked into its bundle. */
52
56
  readonly FABRIKA_PROXY_MANIFEST_JSON?: string
53
57
  readonly FABRIKA_IAM_ISSUER?: string
54
58
  readonly [binding: string]: unknown
@@ -60,10 +64,13 @@ interface WorkerService {
60
64
 
61
65
  type ProxyFetch = (request: Request) => Promise<Response>
62
66
 
63
- const UNAVAILABLE = new Response('proxy unavailable', {
64
- status: 503,
65
- headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
66
- })
67
+ /**
68
+ * A failure the Worker answers itself: the status's page to a navigation that does not select a download endpoint
69
+ * (whose file treatment would save the page as a file), its fixed text to everything else.
70
+ */
71
+ function failure(status: ErrorPageStatus, text: string, request: Request, download: boolean, manifest: ProxyManifest | null): Response {
72
+ return errorAnswer(status, text, !download && isPageNavigation(request.headers), manifest?.brand ?? null)
73
+ }
67
74
 
68
75
  let cached: {
69
76
  readonly manifestJson: string
@@ -123,7 +130,7 @@ export function createCloudflareProxyHandler(env: CloudflareProxyEnv, logger: Pr
123
130
  function unavailable(manifest: ProxyManifest | null): ProxyFetch {
124
131
  return (request) => {
125
132
  const app = manifest === null ? null : findApp(manifest, new URL(request.url))
126
- const answer = UNAVAILABLE.clone()
133
+ const answer = failure(503, 'proxy unavailable', request, false, manifest)
127
134
  return Promise.resolve(
128
135
  app === null || !isApplicationEntry(app) ? answer : withResponseHeaders(answer, contractAnswerHeaders(app)(null, answer.status)),
129
136
  )
@@ -164,14 +171,14 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
164
171
  // An admitted preflight: the decision's 2xx is the whole answer, and the application never sees the request.
165
172
  if (verification.headers.get(PREFLIGHT_HEADER) === '1') return withResponseHeaders(verification, (headers) => headers.delete(PREFLIGHT_HEADER))
166
173
 
167
- if (app === null) return new Response('not found', { status: 404 })
174
+ if (app === null) return failure(404, 'not found', request, false, manifest)
168
175
  const treatment = answerHeaders.get(app.id)
176
+ const endpoint = verification.headers.get(ENDPOINT_HEADER)
177
+ const download = selectsDownload(app, endpoint)
169
178
  const upstream = env[app.upstream]
170
179
  if (!isWorkerService(upstream)) {
171
- const unavailable = UNAVAILABLE.clone()
172
- return treatment === undefined
173
- ? unavailable
174
- : withResponseHeaders(unavailable, treatment(verification.headers.get(ENDPOINT_HEADER), unavailable.status))
180
+ const unavailable = failure(503, 'proxy unavailable', request, download, manifest)
181
+ return treatment === undefined ? unavailable : withResponseHeaders(unavailable, treatment(endpoint, unavailable.status))
175
182
  }
176
183
 
177
184
  // Built from the ORIGINAL headers, so it is stripped again here — the set above was applied to the
@@ -198,13 +205,13 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
198
205
  answer = await upstream.fetch(new Request(request, { headers: upstreamHeaders }))
199
206
  } catch {
200
207
  // Nothing of the error is answered or logged: it can carry the upstream request, a token header included.
201
- answer = new Response('bad gateway', { status: 502, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' } })
208
+ answer = failure(502, 'bad gateway', request, download, manifest)
202
209
  }
203
210
  if (treatment === undefined) return answer
204
211
  // The treatment deleted the application's own `Access-Control-*`; only the origin the decision admitted is set.
205
212
  const allowOrigin = verification.headers.get(ALLOW_ORIGIN_HEADER)
206
213
  return withResponseHeaders(answer, (headers) => {
207
- treatment(verification.headers.get(ENDPOINT_HEADER), answer.status)(headers)
214
+ treatment(endpoint, answer.status)(headers)
208
215
  if (allowOrigin !== null) applyCrossOriginHeaders(headers, crossOriginHeaders(allowOrigin))
209
216
  })
210
217
  }
@@ -238,6 +245,13 @@ function contractAnswerHeaders(app: ContractProxyApp): AnswerHeaders {
238
245
  }
239
246
  }
240
247
 
248
+ /** Whether the decision selected a download endpoint of a contract application. */
249
+ function selectsDownload(app: ProxyApp, endpoint: string | null): boolean {
250
+ if (!isApplicationEntry(app) || endpoint === null) return false
251
+ const id = parseEndpointHeader(endpoint)?.id
252
+ return app.endpoints.some((row) => row.kind === 'download' && row.id === id)
253
+ }
254
+
241
255
  /** What only the decision may assert to the app; each is copied from an allow, the way Caddy's `copy_headers` does. */
242
256
  const PROXY_ASSERTED_HEADERS = [PROXY_TOKEN_HEADER, REQUEST_ID_HEADER, ENDPOINT_HEADER, DELEGATION_HEADER]
243
257
 
@@ -296,8 +310,14 @@ function isObject(value: unknown): value is Record<string, unknown> {
296
310
  return typeof value === 'object' && value !== null
297
311
  }
298
312
 
313
+ /** Replaced with the manifest's string literal when wrangler bundles the Worker (`PROXY_MANIFEST_DEFINE` in `./proxy`). */
314
+ declare const __FABRIKA_PROXY_MANIFEST__: string | undefined
315
+
316
+ // `typeof` reads an identifier no bundle defined without throwing: an unbaked bundle serves its fixed 503.
317
+ const BAKED_MANIFEST_JSON: string = typeof __FABRIKA_PROXY_MANIFEST__ === 'string' ? __FABRIKA_PROXY_MANIFEST__ : ''
318
+
299
319
  export default {
300
320
  fetch(request: Request, env: CloudflareProxyEnv): Promise<Response> {
301
- return createCloudflareProxyHandler(env)(request)
321
+ return createCloudflareProxyHandler({ ...env, FABRIKA_PROXY_MANIFEST_JSON: BAKED_MANIFEST_JSON })(request)
302
322
  },
303
323
  }