@fabrika/provider-cloudflare 0.6.0 → 0.8.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/provider-cloudflare",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,15 +42,15 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "zod": "^3.25.76",
45
- "@fabrika/app": "0.6.0",
46
- "@fabrika/auth": "0.6.0",
47
- "@fabrika/auth-core": "0.6.0",
48
- "@fabrika/check": "0.6.0",
49
- "@fabrika/email": "0.6.0",
50
- "@fabrika/iam-contract": "0.6.0",
51
- "@fabrika/installation-init": "0.6.0",
52
- "@fabrika/proxy-core": "0.6.0",
53
- "@fabrika/provider-contract": "0.6.0",
45
+ "@fabrika/app": "0.8.0",
46
+ "@fabrika/auth": "0.8.0",
47
+ "@fabrika/auth-core": "0.8.0",
48
+ "@fabrika/check": "0.8.0",
49
+ "@fabrika/email": "0.8.0",
50
+ "@fabrika/iam-contract": "0.8.0",
51
+ "@fabrika/installation-init": "0.8.0",
52
+ "@fabrika/proxy-core": "0.8.0",
53
+ "@fabrika/provider-contract": "0.8.0",
54
54
  "oblaka-iac": "^0.0.18"
55
55
  }
56
56
  }
package/src/command.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type AppEnvironment, type ContractArtifact, parseAppEnvironmentId } from '@fabrika/auth-core'
1
+ import { type AppEnvironment, parseAppEnvironmentId } from '@fabrika/auth-core'
2
2
  import { readFile } from 'node:fs/promises'
3
3
  import { z } from 'zod'
4
4
  import type { CloudflareAppConfig } from './authoring'
@@ -111,9 +111,9 @@ export const readApprovedAccess = async (path: string | undefined): Promise<Runn
111
111
  return access.data
112
112
  }
113
113
 
114
- /** The approved access as the deployer takes it: the contract Control read at the commit. */
115
- const approvedRun = (access: RunnerApprovedAccess | undefined): { readonly contract?: ContractArtifact } =>
116
- access === undefined ? {} : { contract: access.contract }
114
+ /** The approved access as the deployer takes it: the contract Control read at the commit, and its application's digest. */
115
+ const approvedRun = (access: RunnerApprovedAccess | undefined): { readonly approved?: RunnerApprovedAccess } =>
116
+ access === undefined ? {} : { approved: access }
117
117
 
118
118
  export interface LoadedCloudflareCommandConfig {
119
119
  readonly config: CloudflareAppConfig
package/src/control.ts CHANGED
@@ -3,7 +3,9 @@ import {
3
3
  type AppEnvironment,
4
4
  appEnvironmentId,
5
5
  type AppSchema,
6
+ FABRIKA_TOKEN_KEYS,
6
7
  isEmailTransportVariable,
8
+ isPlatformTransportVariable,
7
9
  isWorkloadKeyVariable,
8
10
  parseAppEnvironmentId,
9
11
  } from '@fabrika/auth-core'
@@ -295,16 +297,22 @@ const buildJob = async (options: CloudflareControlOptions, input: ProviderDeploy
295
297
  if (!input.dryRun && approvedAccess === undefined) {
296
298
  throw new Error('Cloudflare deploy requires the access Control approved for this environment')
297
299
  }
298
- // A job and a webhook need `@fabrika/db` on Postgres, which a Worker has not; their keys would only sit in a config.
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.
299
302
  const workloadKey = Object.keys(input.managedEnvironment).find(isWorkloadKeyVariable)
300
303
  if (workloadKey !== undefined) {
301
- throw new Error(`cloudflare: the contract declares a job or a webhook (${workloadKey}); they run on Zerops only`)
304
+ throw new Error(`cloudflare: the contract declares a job, a webhook or a public procedure (${workloadKey}); they run on Zerops only`)
302
305
  }
303
306
  // A dry run hands no workload key, and a mail credential must not land in a plain Worker var either way.
304
- const mailVariable = Object.keys(input.managedEnvironment).find(isEmailTransportVariable)
307
+ const mailVariable = Object.keys(input.managedEnvironment).find((name) => isEmailTransportVariable(name) || isPlatformTransportVariable(name))
305
308
  if (mailVariable !== undefined) {
306
309
  throw new Error(`cloudflare: the contract declares a job that sends mail through the installation (${mailVariable}); jobs run on Zerops only`)
307
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
+ }
308
316
  const source = await awaitWithSignal(input.signal, () => options.prepareClone(input.app.source, input.signal, input.sourceBinding))
309
317
  const listInstallationApps = options.installationApps
310
318
  const installationApps = listInstallationApps === undefined
package/src/provider.ts CHANGED
@@ -29,6 +29,7 @@ import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './
29
29
  import { configSchema } from './config-schema'
30
30
  import { buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
31
31
  import { createCloudflareProxyWorker } from './proxy'
32
+ import type { RunnerApprovedAccess } from './runner-protocol'
32
33
  import { defaultReconcileSchema } from './schema'
33
34
 
34
35
  const CANCELLED = 'deploy cancelled'
@@ -127,10 +128,16 @@ const withConnectorBindings = (authored: Worker, bindings: Readonly<Record<strin
127
128
  return replaceApplicationWorker(authored, configured)
128
129
  }
129
130
 
131
+ /** The contract a deployment serves, and the digest the application's own framework release computes for it. */
132
+ interface ServedContract {
133
+ readonly contract: ContractArtifact
134
+ readonly digest: string
135
+ }
136
+
130
137
  /** A contract application starts only as the contract it was deployed with (ADR-0022 rule 5), so the platform writes its digest. */
131
- const contractEnvironment = (managed: ProviderManagedEnvironment, contract: ContractArtifact | null): ProviderManagedEnvironment => {
132
- if (contract === null) return managed
133
- const digest = contractDigest(contract)
138
+ const contractEnvironment = (managed: ProviderManagedEnvironment, served: ServedContract | null): ProviderManagedEnvironment => {
139
+ if (served === null) return managed
140
+ const { digest } = served
134
141
  const sent = managed[FABRIKA_CONTRACT_DIGEST]
135
142
  if (sent !== undefined && sent !== null && sent !== digest) {
136
143
  throw new Error(`cloudflare: ${FABRIKA_CONTRACT_DIGEST} is \`${sent}\`, but the contract this deployment serves has digest \`${digest}\``)
@@ -156,7 +163,7 @@ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifa
156
163
  * The proxy Worker is the platform's (ADR-0048): built here, from this package's own entrypoint, around the
157
164
  * application Worker the config returns, never taken from the checkout. A config that returns a proxy is refused.
158
165
  */
159
- const platformProxied = (authored: Worker, contract: ContractArtifact, run: CloudflareDeployRun): Worker => {
166
+ const platformProxied = (authored: Worker, served: ServedContract, run: CloudflareDeployRun): Worker => {
160
167
  if (authored.options.bindings?.['APP'] !== undefined) {
161
168
  throw new Error(
162
169
  `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`,
@@ -173,7 +180,7 @@ const platformProxied = (authored: Worker, contract: ContractArtifact, run: Clou
173
180
  appHost: run.domain ?? 'localhost',
174
181
  ...(run.domain === undefined ? {} : { domain: run.domain }),
175
182
  ...(run.crossOrigins === undefined ? {} : { crossOrigins: run.crossOrigins }),
176
- endpoints: contractProxyTable(contract),
183
+ endpoints: contractProxyTable(served.contract, served.digest),
177
184
  ...operationsOrigin(run.managedEnvironment),
178
185
  iamUrl: run.managedEnvironment[FABRIKA_IAM_ISSUER] ?? '',
179
186
  })
@@ -427,10 +434,10 @@ export interface CloudflareDeployRun {
427
434
  /** Platform-owned runtime configuration, separate from operator-managed application vars. */
428
435
  readonly managedEnvironment: ProviderManagedEnvironment
429
436
  /**
430
- * The contract Control approved for this run (ADR-0050). Absent outside Control (a local deploy), the deployer reads
431
- * `fabrika.contract.ts` from the checkout, as Control does.
437
+ * The contract Control approved for this run (ADR-0050), with the digest the application's release computes. Absent
438
+ * outside Control (a local deploy), the deployer reads `fabrika.contract.ts` from the checkout, as Control does.
432
439
  */
433
- readonly contract?: ContractArtifact
440
+ readonly approved?: RunnerApprovedAccess
434
441
  /** Every Cloudflare deployment of the installation in Control's registry; a name of another application is refused. */
435
442
  readonly installationApps?: readonly AppEnvironment[]
436
443
  readonly dryRun: boolean
@@ -445,8 +452,15 @@ export interface CloudflareDeployResult {
445
452
  readonly steps: readonly DeployStepResult[]
446
453
  }
447
454
 
448
- const servedContract = async (cf: CloudflareCollaborators, cwd: string, approved: ContractArtifact | undefined): Promise<ContractArtifact | null> =>
449
- approved === undefined ? cf.readContract(cwd) : approved
455
+ const servedContract = async (
456
+ cf: CloudflareCollaborators,
457
+ cwd: string,
458
+ approved: RunnerApprovedAccess | undefined,
459
+ ): Promise<ServedContract | null> => {
460
+ if (approved !== undefined) return { contract: approved.contract, digest: approved.contractDigest }
461
+ const read = await cf.readContract(cwd)
462
+ return read === null ? null : { contract: read, digest: contractDigest(read) }
463
+ }
450
464
 
451
465
  export const createCloudflareDeployer = (options: CloudflareDeployerOptions) => async (run: CloudflareDeployRun): Promise<CloudflareDeployResult> => {
452
466
  const cf = options.collaborators ?? defaultCloudflareCollaborators
@@ -455,9 +469,10 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
455
469
  throw new Error(`Cloudflare config declares app "${loaded.config.id}", expected "${run.appId}"`)
456
470
  }
457
471
  const platformResources = options.platformResources ?? 'refuse'
458
- const contract = await servedContract(cf, loaded.cwd, run.contract)
472
+ const served = await servedContract(cf, loaded.cwd, run.approved)
473
+ const contract = served?.contract ?? null
459
474
  // Fabrika's own components (`allow`) are its trusted installation path; an application needs a contract.
460
- if (platformResources === 'refuse' && contract === null) {
475
+ if (platformResources === 'refuse' && served === null) {
461
476
  throw new Error('cloudflare: the checkout has no `fabrika.contract.ts`; Fabrika deploys an application only with a contract')
462
477
  }
463
478
  // Read once, before `resources()` runs the checkout's code again: nothing below reads the config's schema.
@@ -465,11 +480,11 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
465
480
  assertContractSchema(schema, contract)
466
481
  const authored = runnerWorkerGraph(loaded.config.resources({ env: run.env, domain: run.domain }))
467
482
  // Fabrika's own components compose their own proxies; every application gets the platform's.
468
- const served = platformResources === 'refuse' && contract !== null ? platformProxied(authored, contract, run) : authored
469
- if (platformResources === 'refuse') assertNoFrameworkVariables(loaded.config, applicationWorker(served), run)
483
+ const proxied = platformResources === 'refuse' && served !== null ? platformProxied(authored, served, run) : authored
484
+ if (platformResources === 'refuse') assertNoFrameworkVariables(loaded.config, applicationWorker(proxied), run)
470
485
  const connectors = platformResources === 'refuse' ? connectorBindings(contract) : {}
471
486
  const worker = withConnectorBindings(
472
- withManagedEnvironment(loaded.config, served, run, contractEnvironment(run.managedEnvironment, contract)),
487
+ withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served)),
473
488
  connectors,
474
489
  )
475
490
  const dir = workerDir(loaded.config, loaded.cwd)
@@ -480,11 +495,11 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
480
495
  platformResources,
481
496
  iamAppId: appEnvironmentId(run.appId, run.env),
482
497
  installation: run.installationApps ?? [],
483
- proxy: served === authored ? null : `${run.env}-${run.appId}-proxy`,
498
+ proxy: proxied === authored ? null : `${run.env}-${run.appId}-proxy`,
484
499
  connectors: Object.fromEntries(Object.entries(connectors).map(([binding, owner]) => [binding, remoteName(run.env, owner)])),
485
500
  frameworkVariables: {
486
501
  application: frameworkValues(applicationWorker(worker).options.vars),
487
- proxy: served === authored ? null : frameworkValues(worker.options.vars),
502
+ proxy: proxied === authored ? null : frameworkValues(worker.options.vars),
488
503
  },
489
504
  }
490
505
  assertStateNamespace(stateNamespace(loaded.config, run), platformResources)
@@ -1,4 +1,4 @@
1
- import { FABRIKA_HOP_HEADERS, parseEndpointHeader, rawRequestTarget } from '@fabrika/auth-core'
1
+ import { answersFile, type EndpointCache, FABRIKA_HOP_HEADERS, parseEndpointHeader, rawRequestTarget } from '@fabrika/auth-core'
2
2
  import type { DelegationIssuer, IamGateway, ProxyLogger, VerifyService } from '@fabrika/proxy-core'
3
3
  import {
4
4
  CLIENT_ADDRESS_HEADER,
@@ -7,6 +7,7 @@ import {
7
7
  DEFAULT_VERIFY_PATH,
8
8
  DELEGATION_HEADER,
9
9
  ENDPOINT_HEADER,
10
+ FORWARD_AUTHORIZATION_HEADER,
10
11
  FORWARDED_HOST_HEADER,
11
12
  FORWARDED_METHOD_HEADER,
12
13
  FORWARDED_PROTO_HEADER,
@@ -22,6 +23,7 @@ import {
22
23
  import {
23
24
  appFileTreatment,
24
25
  appHeaderPolicy,
26
+ applyAnswerCache,
25
27
  applyCrossOriginHeaders,
26
28
  applyFileTreatment,
27
29
  applyHeaderPolicy,
@@ -122,7 +124,9 @@ function unavailable(manifest: ProxyManifest | null): ProxyFetch {
122
124
  return (request) => {
123
125
  const app = manifest === null ? null : findApp(manifest, new URL(request.url))
124
126
  const answer = UNAVAILABLE.clone()
125
- return Promise.resolve(app === null || !isApplicationEntry(app) ? answer : withResponseHeaders(answer, contractAnswerHeaders(app)(null)))
127
+ return Promise.resolve(
128
+ app === null || !isApplicationEntry(app) ? answer : withResponseHeaders(answer, contractAnswerHeaders(app)(null, answer.status)),
129
+ )
126
130
  }
127
131
  }
128
132
 
@@ -165,7 +169,9 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
165
169
  const upstream = env[app.upstream]
166
170
  if (!isWorkerService(upstream)) {
167
171
  const unavailable = UNAVAILABLE.clone()
168
- return treatment === undefined ? unavailable : withResponseHeaders(unavailable, treatment(verification.headers.get(ENDPOINT_HEADER)))
172
+ return treatment === undefined
173
+ ? unavailable
174
+ : withResponseHeaders(unavailable, treatment(verification.headers.get(ENDPOINT_HEADER), unavailable.status))
169
175
  }
170
176
 
171
177
  // Built from the ORIGINAL headers, so it is stripped again here — the set above was applied to the
@@ -178,8 +184,10 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
178
184
  const value = verification.headers.get(header)
179
185
  if (value !== null && value !== '') upstreamHeaders.set(header, value)
180
186
  }
181
- // An anonymous endpoint mints no token, and the proxy forwards no key it read nothing from (ADR-0022 rule 3).
182
- if (isApplicationEntry(app) && !upstreamHeaders.has(PROXY_TOKEN_HEADER)) upstreamHeaders.delete('Authorization')
187
+ // An anonymous endpoint mints no token, and the proxy forwards no key it read nothing from (ADR-0022 rule 3), except
188
+ // the credential of a webhook row the decision marked to pass on.
189
+ const forwards = verification.headers.get(FORWARD_AUTHORIZATION_HEADER) === '1'
190
+ if (isApplicationEntry(app) && !upstreamHeaders.has(PROXY_TOKEN_HEADER) && !forwards) upstreamHeaders.delete('Authorization')
183
191
 
184
192
  let answer: Response
185
193
  try {
@@ -192,7 +200,7 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
192
200
  // The treatment deleted the application's own `Access-Control-*`; only the origin the decision admitted is set.
193
201
  const allowOrigin = verification.headers.get(ALLOW_ORIGIN_HEADER)
194
202
  return withResponseHeaders(answer, (headers) => {
195
- treatment(verification.headers.get(ENDPOINT_HEADER))(headers)
203
+ treatment(verification.headers.get(ENDPOINT_HEADER), answer.status)(headers)
196
204
  if (allowOrigin !== null) applyCrossOriginHeaders(headers, crossOriginHeaders(allowOrigin))
197
205
  })
198
206
  }
@@ -205,17 +213,24 @@ const ALLOW_ORIGIN_HEADER = 'Access-Control-Allow-Origin'
205
213
  * treatment for the download endpoint the decision asserted, the policy otherwise. The decision's own answers carry
206
214
  * them already.
207
215
  */
208
- type AnswerHeaders = (endpoint: string | null) => (headers: Headers) => void
216
+ type AnswerHeaders = (endpoint: string | null, status: number) => (headers: Headers) => void
209
217
 
210
218
  function contractAnswerHeaders(app: ContractProxyApp): AnswerHeaders {
211
219
  const policy: HeaderPolicy = appHeaderPolicy(app)
212
220
  const fileTreatment: HeaderPolicy = appFileTreatment(app)
213
- const downloads = new Set(app.endpoints.filter((row) => row.kind === 'download').map((row) => row.id))
214
- const withPolicy = (headers: Headers) => applyHeaderPolicy(headers, policy)
215
- const withFileTreatment = (headers: Headers) => applyFileTreatment(headers, fileTreatment)
216
- return (endpoint) => {
217
- const id = endpoint === null ? null : parseEndpointHeader(endpoint)?.id
218
- return id !== undefined && id !== null && downloads.has(id) ? withFileTreatment : withPolicy
221
+ const downloads = new Set(app.endpoints.filter(answersFile).map((row) => row.id))
222
+ const cached = new Map<string, EndpointCache>()
223
+ for (const row of app.endpoints) {
224
+ if ('cache' in row && row.cache !== undefined) cached.set(row.id, row.cache)
225
+ }
226
+ return (endpoint, status) => {
227
+ const id = endpoint === null ? null : (parseEndpointHeader(endpoint)?.id ?? null)
228
+ return (headers) => {
229
+ if (id !== null && downloads.has(id)) applyFileTreatment(headers, fileTreatment)
230
+ else applyHeaderPolicy(headers, policy)
231
+ const cache = id === null ? undefined : cached.get(id)
232
+ if (cache !== undefined) applyAnswerCache(headers, { cache }, status)
233
+ }
219
234
  }
220
235
  }
221
236
 
@@ -1,5 +1,5 @@
1
1
  import { contractArtifactSchema } from '@fabrika/app/contract'
2
- import { type ContractArtifact, contractDigest } from '@fabrika/auth-core'
2
+ import { type ContractArtifact, isDigest } from '@fabrika/auth-core'
3
3
  import { z } from 'zod'
4
4
 
5
5
  export const runnerStateSchema = z.enum(['pending', 'cloning', 'installing', 'deploying', 'succeeded', 'failed'])
@@ -26,8 +26,10 @@ export const INSTALLATION_APPS_ENV = 'FABRIKA_INSTALLATION_APPS'
26
26
  export const CROSS_ORIGINS_ENV = 'FABRIKA_CROSS_ORIGINS'
27
27
 
28
28
  /**
29
- * The access Control approved for a run (ADR-0050): the contract it read at the commit. The proxy table and
30
- * `FABRIKA_CONTRACT_DIGEST` follow this, never the checkout.
29
+ * The access Control approved for a run (ADR-0050): the contract it read at the commit, in this release's model, and
30
+ * the digest the application's own framework release computes for it. The proxy table and `FABRIKA_CONTRACT_DIGEST`
31
+ * follow this, never the checkout. The digest is not `contractDigest(contract)` when Control upcast the contract from
32
+ * an older release's artifact (ADR-0062), so the executor cannot recompute it and takes Control's.
31
33
  */
32
34
  export interface RunnerApprovedAccess {
33
35
  readonly kind: 'contract'
@@ -35,11 +37,16 @@ export interface RunnerApprovedAccess {
35
37
  readonly contractDigest: string
36
38
  }
37
39
 
38
- export const runnerApprovedAccessSchema = z.object({ kind: z.literal('contract'), contract: z.unknown(), contractDigest: z.string() }).strict()
40
+ export const runnerApprovedAccessSchema = z.object({
41
+ kind: z.literal('contract'),
42
+ contract: z.unknown(),
43
+ contractDigest: z.string().refine(isDigest),
44
+ })
45
+ .strict()
39
46
  .transform((access, context): RunnerApprovedAccess => {
40
47
  const contract = contractArtifactSchema.safeParse(access.contract)
41
- if (!contract.success || contractDigest(contract.data) !== access.contractDigest) {
42
- context.addIssue({ code: z.ZodIssueCode.custom, message: 'not a contract artifact its digest describes' })
48
+ if (!contract.success) {
49
+ context.addIssue({ code: z.ZodIssueCode.custom, message: 'not a contract artifact' })
43
50
  return z.NEVER
44
51
  }
45
52
  return { kind: 'contract', contract: contract.data, contractDigest: access.contractDigest }