@fabrika/provider-cloudflare 0.3.3 → 0.4.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/src/provider.ts CHANGED
@@ -1,10 +1,34 @@
1
+ import {
2
+ type AppEnvironment,
3
+ appEnvironmentId,
4
+ type AppSchema,
5
+ connectVariables,
6
+ type ContractArtifact,
7
+ contractDigest,
8
+ FABRIKA_CONTRACT_DIGEST,
9
+ FABRIKA_IAM_ISSUER,
10
+ isFrameworkVariableName,
11
+ } from '@fabrika/auth-core'
1
12
  import { type DeployStepResult, type ProviderManagedEnvironment, runSteps } from '@fabrika/provider-contract'
13
+ import { isPolicyOrigin } from '@fabrika/proxy-core/headers'
14
+ import { contractProxyTable } from '@fabrika/proxy-core/manifest'
2
15
  import { dirname, resolve } from 'node:path'
3
- import { type GeneratedConfig, Worker } from 'oblaka-iac'
16
+ import { type GeneratedConfig, ServiceReference, Worker } from 'oblaka-iac'
4
17
  import { assertLiteralAssets } from './assets'
5
18
  import type { CloudflareAppConfig } from './authoring'
19
+ import {
20
+ assertGeneratedConfigs,
21
+ assertGeneration,
22
+ assertStateNamespace,
23
+ type DeploymentBounds,
24
+ frameworkValues,
25
+ generateWranglerConfigs,
26
+ } from './bounds'
27
+ import { runnerWorkerGraph } from './checkout'
6
28
  import { type CloudflareCollaborators, defaultCloudflareCollaborators } from './collaborators'
7
- import { assertAuthoredGraph, buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
29
+ import { configSchema } from './config-schema'
30
+ import { buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
31
+ import { createCloudflareProxyWorker } from './proxy'
8
32
 
9
33
  const CANCELLED = 'deploy cancelled'
10
34
 
@@ -34,8 +58,26 @@ const assertRunning = (signal: AbortSignal): void => {
34
58
  }
35
59
  }
36
60
 
37
- const withManagedEnvironment = (config: CloudflareAppConfig, authored: Worker, run: CloudflareDeployRun): Worker => {
38
- const managed = run.managedEnvironment
61
+ /** An application never names a variable only the platform writes, whether or not this deploy writes it. */
62
+ const assertNoFrameworkVariables = (config: CloudflareAppConfig, application: Worker, run: CloudflareDeployRun): void => {
63
+ const authored = [
64
+ ...(config.pipeline?.vars ?? []),
65
+ ...Object.keys(application.options.vars ?? {}),
66
+ ...Object.keys(application.options.bindings ?? {}),
67
+ ...Object.keys(run.vars),
68
+ ]
69
+ const reserved = authored.find(isFrameworkVariableName)
70
+ if (reserved !== undefined) {
71
+ throw new Error(`cloudflare: application variable \`${reserved}\` is managed by Fabrika`)
72
+ }
73
+ }
74
+
75
+ const withManagedEnvironment = (
76
+ config: CloudflareAppConfig,
77
+ authored: Worker,
78
+ run: CloudflareDeployRun,
79
+ managed: ProviderManagedEnvironment,
80
+ ): Worker => {
39
81
  const present: Record<string, string> = {}
40
82
  const declared = new Set(config.pipeline?.vars ?? [])
41
83
  const application = applicationWorker(authored)
@@ -56,6 +98,100 @@ const withManagedEnvironment = (config: CloudflareAppConfig, authored: Worker, r
56
98
  return replaceApplicationWorker(authored, configured)
57
99
  }
58
100
 
101
+ /** The proxy Worker the platform builds for application `appId`, before oblaka's environment prefix. */
102
+ const proxyWorkerName = (appId: string): string => `${appId}-proxy`
103
+
104
+ /** The remote name oblaka gives a Worker named `name` in `env`. */
105
+ const remoteName = (env: string, name: string): string => (env === 'local' ? name : `${env}-${name}`)
106
+
107
+ /**
108
+ * Each connector import's `FABRIKA_CONNECT_<IMPORT>` service binding, to the owner's proxy Worker in the same
109
+ * environment, by binding name; the owner's proxy enforces the export (ADR-0022), so no binding reaches its application.
110
+ */
111
+ const connectorBindings = (contract: ContractArtifact | null): Readonly<Record<string, string>> =>
112
+ Object.fromEntries(
113
+ Object.entries(contract?.imports ?? {}).map(([name, imported]) => [connectVariables(name).binding, proxyWorkerName(imported.app)]),
114
+ )
115
+
116
+ const withConnectorBindings = (authored: Worker, bindings: Readonly<Record<string, string>>): Worker => {
117
+ if (Object.keys(bindings).length === 0) return authored
118
+ const application = applicationWorker(authored)
119
+ const configured = new Worker({
120
+ ...application.options,
121
+ bindings: {
122
+ ...(application.options.bindings ?? {}),
123
+ ...Object.fromEntries(Object.entries(bindings).map(([binding, worker]) => [binding, new ServiceReference(worker)])),
124
+ },
125
+ })
126
+ return replaceApplicationWorker(authored, configured)
127
+ }
128
+
129
+ /** A contract application starts only as the contract it was deployed with (ADR-0022 rule 5), so the platform writes its digest. */
130
+ const contractEnvironment = (managed: ProviderManagedEnvironment, contract: ContractArtifact | null): ProviderManagedEnvironment => {
131
+ if (contract === null) return managed
132
+ const digest = contractDigest(contract)
133
+ const sent = managed[FABRIKA_CONTRACT_DIGEST]
134
+ if (sent !== undefined && sent !== null && sent !== digest) {
135
+ throw new Error(`cloudflare: ${FABRIKA_CONTRACT_DIGEST} is \`${sent}\`, but the contract this deployment serves has digest \`${digest}\``)
136
+ }
137
+ return { ...managed, [FABRIKA_CONTRACT_DIGEST]: digest }
138
+ }
139
+
140
+ /**
141
+ * The lock-down follows the contract, not the config: a contract whose IAM schema does not say `contract: true`, or a
142
+ * platform service's schema that does, would leave the proxy and IAM deciding under different rules.
143
+ */
144
+ const assertContractSchema = (schema: AppSchema | null, contract: ContractArtifact | null): void => {
145
+ const declared = schema?.contract === true
146
+ if (contract === null && declared) {
147
+ throw new Error('cloudflare: the IAM schema says `contract: true`, but the checkout has no `fabrika.contract.ts`')
148
+ }
149
+ if (contract !== null && !declared) {
150
+ throw new Error('cloudflare: this deployment serves a contract, so its IAM schema is `schemaFromContract(artifact)` (`contract: true`)')
151
+ }
152
+ }
153
+
154
+ /**
155
+ * The proxy Worker is the platform's (ADR-0048): built here, from this package's own entrypoint, around the
156
+ * application Worker the config returns, never taken from the checkout. A config that returns a proxy is refused.
157
+ */
158
+ const platformProxied = (authored: Worker, contract: ContractArtifact, run: CloudflareDeployRun): Worker => {
159
+ if (authored.options.bindings?.['APP'] !== undefined) {
160
+ throw new Error(
161
+ `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`,
162
+ )
163
+ }
164
+ const name = proxyWorkerName(run.appId)
165
+ if (authored.options.name === name) {
166
+ throw new Error(`cloudflare: application Worker \`${name}\` takes the name of the proxy Worker the platform builds; rename it`)
167
+ }
168
+ return createCloudflareProxyWorker({
169
+ name,
170
+ app: authored,
171
+ appId: appEnvironmentId(run.appId, run.env),
172
+ appHost: run.domain ?? 'localhost',
173
+ ...(run.domain === undefined ? {} : { domain: run.domain }),
174
+ endpoints: contractProxyTable(contract),
175
+ ...operationsOrigin(run.managedEnvironment),
176
+ iamUrl: run.managedEnvironment[FABRIKA_IAM_ISSUER] ?? '',
177
+ })
178
+ }
179
+
180
+ /** The ingest origin of the application's Operations DSN: the proxy's `connect-src` admits it, as the framework's does. */
181
+ const operationsOrigin = (managed: ProviderManagedEnvironment): { readonly operationsOrigin?: string } => {
182
+ const dsn = managed['FABRIKA_OPERATIONS_DSN']
183
+ if (dsn === undefined || dsn === null) return {}
184
+ let origin: string
185
+ try {
186
+ origin = new URL(dsn).origin
187
+ } catch {
188
+ origin = ''
189
+ }
190
+ // The DSN carries the ingest key, so the message names the variable and never its value.
191
+ if (!isPolicyOrigin(origin, ['https:', 'http:'])) throw new Error('cloudflare: FABRIKA_OPERATIONS_DSN is not an http(s) URL with a literal host')
192
+ return { operationsOrigin: origin }
193
+ }
194
+
59
195
  const applicationWorker = (worker: Worker): Worker => {
60
196
  const child = worker.options.bindings?.['APP']
61
197
  return child instanceof Worker ? applicationWorker(child) : worker
@@ -93,12 +229,15 @@ const migrationBinding = (binding: string): string => {
93
229
 
94
230
  interface StepEnv {
95
231
  readonly config: CloudflareAppConfig
232
+ /** The IAM schema read before the checkout's `resources()` ran (`configSchema`). */
233
+ readonly schema: AppSchema | null
96
234
  readonly run: CloudflareDeployRun
97
235
  readonly credentials: CloudflareCredentials
98
236
  readonly worker: Worker
99
237
  readonly dir: string
100
238
  readonly cf: CloudflareCollaborators
101
239
  readonly platformResources: 'refuse' | 'allow'
240
+ readonly bounds: DeploymentBounds
102
241
  generatedConfigs: readonly GeneratedConfig[]
103
242
  }
104
243
 
@@ -158,12 +297,9 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
158
297
  }
159
298
  case 'deploy-worker': {
160
299
  const configs = env.generatedConfigs
161
- // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
162
- const assertAssets = async (configDir: string): Promise<void> => {
163
- if (env.platformResources === 'refuse') await assertLiteralAssets(worker, dir, configDir)
164
- }
300
+ // The configs oblaka wrote, not the generation checked before the run: a stateful binding can emit differently twice.
301
+ assertGeneratedConfigs(configs, env.bounds)
165
302
  if (configs.length === 0) {
166
- await assertAssets(dir)
167
303
  if (dryRun) {
168
304
  run.log(` [dry-run] would run: wrangler deploy in ${dir}`)
169
305
  return
@@ -175,7 +311,8 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
175
311
  }
176
312
  for (const generated of configs) {
177
313
  const generatedDir = dirname(resolve(dir, generated.path))
178
- await assertAssets(generatedDir)
314
+ // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
315
+ if (env.platformResources === 'refuse') await assertLiteralAssets(generated, generatedDir)
179
316
  if (dryRun) {
180
317
  run.log(` [dry-run] would run: wrangler deploy in ${generatedDir}`)
181
318
  continue
@@ -187,7 +324,8 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
187
324
  return
188
325
  }
189
326
  case 'reconcile-schema': {
190
- if (config.schema === undefined) return
327
+ const schema = env.schema
328
+ if (schema === null) return
191
329
  const returnOrigins = run.returnOrigins !== undefined && run.returnOrigins.length > 0 ? run.returnOrigins : undefined
192
330
  if (dryRun) {
193
331
  run.log(` [dry-run] would report the authz schema for \`${config.id}\` to the control plane`)
@@ -199,7 +337,7 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
199
337
  assertRunning(signal)
200
338
  // The reconcile itself happens in the CONTROL plane, which holds IAM's admin key; this
201
339
  // container runs the checkout's own code and never sees it (ADR-0022).
202
- await cf.writeOutcome({ iamReconcile: { app: config.id, schemaJson: JSON.stringify(config.schema) } })
340
+ await cf.writeOutcome({ iamReconcile: { app: config.id, schemaJson: JSON.stringify(schema) } })
203
341
  return
204
342
  }
205
343
  case 'sync-secrets': {
@@ -244,7 +382,7 @@ export interface CloudflareDeployRun {
244
382
  readonly appId: string
245
383
  readonly env: string
246
384
  readonly domain?: string
247
- /** Every origin IAM may hand this app a session at; app-wide, because IAM's registry is keyed by app id. */
385
+ /** Every origin IAM may hand this environment a session at, registered under `<app>@<env>`. */
248
386
  readonly returnOrigins?: readonly string[]
249
387
  readonly cwd: string
250
388
  readonly configPath: string
@@ -253,6 +391,13 @@ export interface CloudflareDeployRun {
253
391
  readonly vars: Readonly<Record<string, string>>
254
392
  /** Platform-owned runtime configuration, separate from operator-managed application vars. */
255
393
  readonly managedEnvironment: ProviderManagedEnvironment
394
+ /**
395
+ * The contract Control approved for this run (ADR-0050). Absent outside Control (a local deploy), the deployer reads
396
+ * `fabrika.contract.ts` from the checkout, as Control does.
397
+ */
398
+ readonly contract?: ContractArtifact
399
+ /** Every Cloudflare deployment of the installation in Control's registry; a name of another application is refused. */
400
+ readonly installationApps?: readonly AppEnvironment[]
256
401
  readonly dryRun: boolean
257
402
  readonly signal: AbortSignal
258
403
  readonly log: (line: string) => void
@@ -265,32 +410,60 @@ export interface CloudflareDeployResult {
265
410
  readonly steps: readonly DeployStepResult[]
266
411
  }
267
412
 
413
+ const servedContract = async (cf: CloudflareCollaborators, cwd: string, approved: ContractArtifact | undefined): Promise<ContractArtifact | null> =>
414
+ approved === undefined ? cf.readContract(cwd) : approved
415
+
268
416
  export const createCloudflareDeployer = (options: CloudflareDeployerOptions) => async (run: CloudflareDeployRun): Promise<CloudflareDeployResult> => {
269
417
  const cf = options.collaborators ?? defaultCloudflareCollaborators
270
418
  const loaded = await cf.loadConfig(run.cwd, run.configPath)
271
419
  if (loaded.config.id !== run.appId) {
272
420
  throw new Error(`Cloudflare config declares app "${loaded.config.id}", expected "${run.appId}"`)
273
421
  }
274
- const worker = withManagedEnvironment(
275
- loaded.config,
276
- loaded.config.resources({ env: run.env, domain: run.domain }),
277
- run,
278
- )
279
422
  const platformResources = options.platformResources ?? 'refuse'
280
- assertAuthoredGraph(worker, {
423
+ const contract = await servedContract(cf, loaded.cwd, run.contract)
424
+ // Fabrika's own components (`allow`) are its trusted installation path; an application needs a contract.
425
+ if (platformResources === 'refuse' && contract === null) {
426
+ throw new Error('cloudflare: the checkout has no `fabrika.contract.ts`; Fabrika deploys an application only with a contract')
427
+ }
428
+ // Read once, before `resources()` runs the checkout's code again: nothing below reads the config's schema.
429
+ const schema = configSchema(loaded.config)
430
+ assertContractSchema(schema, contract)
431
+ const authored = runnerWorkerGraph(loaded.config.resources({ env: run.env, domain: run.domain }))
432
+ // Fabrika's own components compose their own proxies; every application gets the platform's.
433
+ const served = platformResources === 'refuse' && contract !== null ? platformProxied(authored, contract, run) : authored
434
+ if (platformResources === 'refuse') assertNoFrameworkVariables(loaded.config, applicationWorker(served), run)
435
+ const connectors = platformResources === 'refuse' ? connectorBindings(contract) : {}
436
+ const worker = withConnectorBindings(
437
+ withManagedEnvironment(loaded.config, served, run, contractEnvironment(run.managedEnvironment, contract)),
438
+ connectors,
439
+ )
440
+ const dir = workerDir(loaded.config, loaded.cwd)
441
+ const bounds: DeploymentBounds = {
281
442
  env: run.env,
282
443
  ...(run.domain === undefined ? {} : { domain: run.domain }),
283
- stateNamespace: stateNamespace(loaded.config, run),
444
+ cwd: dir,
284
445
  platformResources,
285
- })
446
+ iamAppId: appEnvironmentId(run.appId, run.env),
447
+ installation: run.installationApps ?? [],
448
+ proxy: served === authored ? null : `${run.env}-${run.appId}-proxy`,
449
+ connectors: Object.fromEntries(Object.entries(connectors).map(([binding, owner]) => [binding, remoteName(run.env, owner)])),
450
+ frameworkVariables: {
451
+ application: frameworkValues(applicationWorker(worker).options.vars),
452
+ proxy: served === authored ? null : frameworkValues(worker.options.vars),
453
+ },
454
+ }
455
+ assertStateNamespace(stateNamespace(loaded.config, run), platformResources)
456
+ assertGeneration(await generateWranglerConfigs(worker, run.env), bounds)
286
457
  const env: StepEnv = {
287
458
  config: loaded.config,
459
+ schema,
288
460
  run,
289
461
  credentials: { accountId: options.accountId, apiToken: options.apiToken },
290
462
  worker,
291
- dir: workerDir(loaded.config, loaded.cwd),
463
+ dir,
292
464
  cf,
293
465
  platformResources,
466
+ bounds,
294
467
  generatedConfigs: [],
295
468
  }
296
469
  const result = await runSteps(buildPlan(loaded.config, worker), run, (step) => runStep(step, env))
@@ -1,20 +1,32 @@
1
- import type { IamGateway, ProxyLogger, VerifyService } from '@fabrika/proxy-core'
1
+ import { FABRIKA_HOP_HEADERS, parseEndpointHeader, rawRequestTarget } from '@fabrika/auth-core'
2
+ import type { DelegationIssuer, IamGateway, ProxyLogger, VerifyService } from '@fabrika/proxy-core'
2
3
  import {
3
4
  CLIENT_ADDRESS_HEADER,
4
5
  consoleLogger,
5
6
  createVerifyService,
6
7
  DEFAULT_VERIFY_PATH,
8
+ DELEGATION_HEADER,
9
+ ENDPOINT_HEADER,
7
10
  FORWARDED_HOST_HEADER,
8
11
  FORWARDED_METHOD_HEADER,
9
12
  FORWARDED_PROTO_HEADER,
10
13
  FORWARDED_URI_HEADER,
11
14
  MemoryTokenCache,
15
+ OAUTH_METADATA_VERIFY_PATH,
12
16
  PROXY_TOKEN_HEADER,
13
17
  REQUEST_ID_HEADER,
14
18
  stripFabrikaCookies,
15
19
  UNTRUSTED_FORWARD_HEADERS,
16
20
  } from '@fabrika/proxy-core'
17
- import { parseProxyManifestJson, type ProxyApp, type ProxyManifest } from '@fabrika/proxy-core/manifest'
21
+ import {
22
+ appFileTreatment,
23
+ appHeaderPolicy,
24
+ applyFileTreatment,
25
+ applyHeaderPolicy,
26
+ type HeaderPolicy,
27
+ withResponseHeaders,
28
+ } from '@fabrika/proxy-core/headers'
29
+ import { type ContractProxyApp, isApplicationEntry, parseProxyManifestJson, type ProxyApp, type ProxyManifest } from '@fabrika/proxy-core/manifest'
18
30
 
19
31
  /**
20
32
  * Cloudflare's managed client address — this composition's answer to "who is the client".
@@ -75,13 +87,12 @@ function canonicalIssuer(raw: string | undefined): string | null {
75
87
  /** Factory exported for Lopata and unit tests; production uses the default Worker fetch below. */
76
88
  export function createCloudflareProxyHandler(env: CloudflareProxyEnv, logger: ProxyLogger = consoleLogger): ProxyFetch {
77
89
  const manifestJson = env.FABRIKA_PROXY_MANIFEST_JSON ?? ''
90
+ const parsed = manifestJson === '' ? null : parseProxyManifestJson(manifestJson)
91
+ const manifest = parsed !== null && validManifest(parsed) ? parsed : null
78
92
  const canonical = canonicalIssuer(env.FABRIKA_IAM_ISSUER)
79
- if (!isIamGateway(env.IAM) || manifestJson === '' || canonical === null) return () => Promise.resolve(UNAVAILABLE.clone())
93
+ if (!isIamGateway(env.IAM) || manifest === null || canonical === null) return unavailable(manifest)
80
94
  const issuer = canonical
81
95
 
82
- const manifest = parseProxyManifestJson(manifestJson)
83
- if (manifest === null || !validManifest(manifest)) return () => Promise.resolve(UNAVAILABLE.clone())
84
-
85
96
  if (cached?.manifestJson === manifestJson && cached.iam === env.IAM && cached.issuer === issuer) {
86
97
  return cached.handler
87
98
  }
@@ -92,15 +103,35 @@ export function createCloudflareProxyHandler(env: CloudflareProxyEnv, logger: Pr
92
103
  issuer,
93
104
  cache: new MemoryTokenCache(),
94
105
  logger,
106
+ // Until IAM's binding serves `requestDelegation`, no delegation grant is obtained here.
107
+ delegations: isDelegationIssuer(env.IAM) ? env.IAM : null,
95
108
  })
96
109
  const handler = proxyHandler(env, manifest, verify)
97
110
  cached = { manifestJson, iam: env.IAM, issuer, handler }
98
111
  return handler
99
112
  }
100
113
 
114
+ /**
115
+ * The fixed 503 of a Worker that cannot serve. A host the manifest still names as an application gets that
116
+ * application's treatment, its transport header included; without a usable manifest no host is known.
117
+ */
118
+ function unavailable(manifest: ProxyManifest | null): ProxyFetch {
119
+ return (request) => {
120
+ const app = manifest === null ? null : findApp(manifest, new URL(request.url))
121
+ const answer = UNAVAILABLE.clone()
122
+ return Promise.resolve(app === null || !isApplicationEntry(app) ? answer : withResponseHeaders(answer, contractAnswerHeaders(app)(null)))
123
+ }
124
+ }
125
+
101
126
  function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify: VerifyService): ProxyFetch {
127
+ const answerHeaders = new Map<string, AnswerHeaders>()
128
+ for (const app of manifest.apps) {
129
+ if (isApplicationEntry(app)) answerHeaders.set(app.id, contractAnswerHeaders(app))
130
+ }
102
131
  return async (request) => {
103
132
  const url = new URL(request.url)
133
+ const app = findApp(manifest, url)
134
+ const isMetadata = app !== null && isOAuthMetadataPath(app, url)
104
135
  const clientAddress = request.headers.get(CLOUDFLARE_CLIENT_ADDRESS_HEADER)
105
136
  const headers = new Headers(request.headers)
106
137
  // The same strips the generated Caddy route does: a client may assert neither the injected token,
@@ -108,23 +139,29 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
108
139
  // on. The first two come back from the decision; the third is re-derived below from the edge.
109
140
  stripClientAsserted(headers)
110
141
  headers.set(FORWARDED_METHOD_HEADER, request.method)
111
- headers.set(FORWARDED_URI_HEADER, `${url.pathname}${url.search}`)
142
+ // The RAW target, so the decision's canonical-path check sees what the upstream will receive:
143
+ // `url.pathname` has already had its dot segments resolved.
144
+ const target = rawRequestTarget(request.url)
145
+ headers.set(FORWARDED_URI_HEADER, `${target.pathname}${target.search}`)
112
146
  headers.set(FORWARDED_HOST_HEADER, url.host)
113
147
  headers.set(FORWARDED_PROTO_HEADER, url.protocol === 'http:' ? 'http' : 'https')
114
148
  if (clientAddress !== null && clientAddress !== '') headers.set(CLIENT_ADDRESS_HEADER, clientAddress)
115
149
 
116
150
  const verification = await verify(
117
- new Request(`https://fabrika-proxy.internal${DEFAULT_VERIFY_PATH}`, {
151
+ new Request(`https://fabrika-proxy.internal${isMetadata ? OAUTH_METADATA_VERIFY_PATH : DEFAULT_VERIFY_PATH}`, {
118
152
  method: 'GET',
119
153
  headers,
120
154
  }),
121
155
  )
122
- if (!verification.ok) return verification
156
+ if (!verification.ok || isMetadata) return verification
123
157
 
124
- const app = findApp(manifest, url)
125
158
  if (app === null) return new Response('not found', { status: 404 })
159
+ const treatment = answerHeaders.get(app.id)
126
160
  const upstream = env[app.upstream]
127
- if (!isWorkerService(upstream)) return UNAVAILABLE.clone()
161
+ if (!isWorkerService(upstream)) {
162
+ const unavailable = UNAVAILABLE.clone()
163
+ return treatment === undefined ? unavailable : withResponseHeaders(unavailable, treatment(verification.headers.get(ENDPOINT_HEADER)))
164
+ }
128
165
 
129
166
  // Built from the ORIGINAL headers, so it is stripped again here — the set above was applied to the
130
167
  // verify subrequest, not to this one.
@@ -132,20 +169,50 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
132
169
  stripClientAsserted(upstreamHeaders)
133
170
  stripFabrikaCookies(upstreamHeaders)
134
171
  if (clientAddress !== null && clientAddress !== '') upstreamHeaders.set(CLIENT_ADDRESS_HEADER, clientAddress)
135
- const token = verification.headers.get(PROXY_TOKEN_HEADER)
136
- if (token !== null && token !== '') upstreamHeaders.set(PROXY_TOKEN_HEADER, token)
137
- const requestId = verification.headers.get(REQUEST_ID_HEADER)
138
- if (requestId !== null && requestId !== '') upstreamHeaders.set(REQUEST_ID_HEADER, requestId)
172
+ for (const header of PROXY_ASSERTED_HEADERS) {
173
+ const value = verification.headers.get(header)
174
+ if (value !== null && value !== '') upstreamHeaders.set(header, value)
175
+ }
176
+ // An anonymous endpoint mints no token, and the proxy forwards no key it read nothing from (ADR-0022 rule 3).
177
+ if (isApplicationEntry(app) && !upstreamHeaders.has(PROXY_TOKEN_HEADER)) upstreamHeaders.delete('Authorization')
139
178
 
140
- return upstream.fetch(new Request(request, { headers: upstreamHeaders }))
179
+ let answer: Response
180
+ try {
181
+ answer = await upstream.fetch(new Request(request, { headers: upstreamHeaders }))
182
+ } catch {
183
+ // Nothing of the error is answered or logged: it can carry the upstream request, a token header included.
184
+ answer = new Response('bad gateway', { status: 502, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' } })
185
+ }
186
+ return treatment === undefined ? answer : withResponseHeaders(answer, treatment(verification.headers.get(ENDPOINT_HEADER)))
141
187
  }
142
188
  }
143
189
 
190
+ /**
191
+ * What a contract application's answer is given, replacing whatever the application set (ADR-0022): the file
192
+ * treatment for the download endpoint the decision asserted, the policy otherwise. The decision's own answers carry
193
+ * them already.
194
+ */
195
+ type AnswerHeaders = (endpoint: string | null) => (headers: Headers) => void
196
+
197
+ function contractAnswerHeaders(app: ContractProxyApp): AnswerHeaders {
198
+ const policy: HeaderPolicy = appHeaderPolicy(app)
199
+ const fileTreatment: HeaderPolicy = appFileTreatment(app)
200
+ const downloads = new Set(app.endpoints.filter((row) => row.kind === 'download').map((row) => row.id))
201
+ const withPolicy = (headers: Headers) => applyHeaderPolicy(headers, policy)
202
+ const withFileTreatment = (headers: Headers) => applyFileTreatment(headers, fileTreatment)
203
+ return (endpoint) => {
204
+ const id = endpoint === null ? null : parseEndpointHeader(endpoint)?.id
205
+ return id !== undefined && id !== null && downloads.has(id) ? withFileTreatment : withPolicy
206
+ }
207
+ }
208
+
209
+ /** What only the decision may assert to the app; each is copied from an allow, the way Caddy's `copy_headers` does. */
210
+ const PROXY_ASSERTED_HEADERS = [PROXY_TOKEN_HEADER, REQUEST_ID_HEADER, ENDPOINT_HEADER, DELEGATION_HEADER]
211
+
144
212
  /** Delete every header only this hop may assert, so nothing downstream can read a caller's version. */
145
213
  function stripClientAsserted(headers: Headers): void {
146
- headers.delete(PROXY_TOKEN_HEADER)
214
+ for (const header of FABRIKA_HOP_HEADERS) headers.delete(header)
147
215
  headers.delete(REQUEST_ID_HEADER)
148
- headers.delete(CLIENT_ADDRESS_HEADER)
149
216
  for (const header of UNTRUSTED_FORWARD_HEADERS) headers.delete(header)
150
217
  }
151
218
 
@@ -155,6 +222,16 @@ function findApp(manifest: ProxyManifest, url: URL): ProxyApp | null {
155
222
  return manifest.apps.find((app) => app.hosts.includes(host) || app.hosts.includes(hostname)) ?? null
156
223
  }
157
224
 
225
+ /**
226
+ * Mirrors the generated Caddy metadata route, whose `path` matcher ignores case: such a request is
227
+ * answered by the metadata endpoint, which compares exactly and 404s a mismatch, and never reaches the endpoint table.
228
+ */
229
+ function isOAuthMetadataPath(app: ProxyApp, url: URL): boolean {
230
+ if (isApplicationEntry(app)) return false
231
+ const path = url.pathname.toLowerCase()
232
+ return app.oauthResources?.some((resource) => new URL(resource.resourceMetadata).pathname.toLowerCase() === path) ?? false
233
+ }
234
+
158
235
  function validManifest(manifest: ProxyManifest): boolean {
159
236
  const hosts = new Set<string>()
160
237
  for (const app of manifest.apps) {
@@ -175,6 +252,10 @@ function isIamGateway(value: unknown): value is IamGateway {
175
252
  && typeof value['getJwks'] === 'function'
176
253
  }
177
254
 
255
+ function isDelegationIssuer(value: unknown): value is DelegationIssuer {
256
+ return isObject(value) && typeof value['requestDelegation'] === 'function'
257
+ }
258
+
178
259
  function isWorkerService(value: unknown): value is WorkerService {
179
260
  return isObject(value) && typeof value['fetch'] === 'function'
180
261
  }
package/src/proxy.ts CHANGED
@@ -1,8 +1,13 @@
1
- import type { AppGates } from '@fabrika/auth'
2
- import { encodeProxyManifestJson, type ProxyManifest } from '@fabrika/proxy-core/manifest'
1
+ import {
2
+ type ContractProxyTable,
3
+ encodeProxyManifestJson,
4
+ type InstallationProxyTable,
5
+ type ProxyApp,
6
+ type ProxyManifest,
7
+ } from '@fabrika/proxy-core/manifest'
3
8
  import { ServiceReference, Worker } from 'oblaka-iac'
4
9
 
5
- export interface CloudflareProxyWorkerOptions {
10
+ interface CloudflareProxyWorkerBase {
6
11
  /** Name of the proxy Worker before the environment prefix is applied by oblaka. */
7
12
  readonly name: string
8
13
  /** The application Worker. It must not have a public route of its own. */
@@ -11,8 +16,6 @@ export interface CloudflareProxyWorkerOptions {
11
16
  readonly appId: string
12
17
  /** Host matched by the proxy manifest. Use the public custom domain when one exists. */
13
18
  readonly appHost: string
14
- /** Ordered gate rules evaluated by the shared proxy authorizer. */
15
- readonly gates: AppGates
16
19
  /** Optional Cloudflare custom domain for the proxy Worker. */
17
20
  readonly domain?: string
18
21
  /** IAM service name. The global default is the platform IAM Worker. */
@@ -21,6 +24,36 @@ export interface CloudflareProxyWorkerOptions {
21
24
  readonly iamUrl?: string
22
25
  }
23
26
 
27
+ interface CloudflareContractProxyOptions {
28
+ readonly endpoints: ContractProxyTable
29
+ readonly installation?: never
30
+ /** The Operations ingest origin a contract application's `connect-src` admits, from its managed DSN. */
31
+ readonly operationsOrigin?: string
32
+ }
33
+
34
+ /**
35
+ * What the proxy enforces: a contract application's endpoint table (`contractProxyTable(artifact)`) or an installation
36
+ * service's table (`serviceProxyTable(service, …)`). Exactly one. The deployer passes only the first; `installation`
37
+ * is written by the platform's own service configs, which is what makes the marker trusted composition (ADR-0022
38
+ * "Installation entries").
39
+ */
40
+ export type CloudflareProxyWorkerOptions =
41
+ | (CloudflareProxyWorkerBase & CloudflareContractProxyOptions)
42
+ | (CloudflareProxyWorkerBase & { readonly installation: InstallationProxyTable; readonly endpoints?: never })
43
+
44
+ /** Where `createCloudflareProxyWorker` points its Worker: the deployer builds every application's proxy from here. */
45
+ export const CLOUDFLARE_PROXY_WORKER_DIR: string = import.meta.dir
46
+ export const CLOUDFLARE_PROXY_WORKER_MAIN = './proxy-worker.ts'
47
+
48
+ /** IAM's Worker: the one platform service an application binds, and only through the entrypoint below. */
49
+ export const IAM_SERVICE = 'propustka-worker'
50
+
51
+ /** IAM's narrow `WorkerEntrypoint`, which carries neither key issuing nor device approval (`packages/iam/src/index.ts`). */
52
+ export const IAM_APPLICATION_ENTRYPOINT = 'PropustkaApplication'
53
+
54
+ /** The `IAM` binding of an application Worker; a generated config that binds IAM any other way is refused. */
55
+ export const iamServiceReference = (): ServiceReference => new ServiceReference(IAM_SERVICE, IAM_APPLICATION_ENTRYPOINT)
56
+
24
57
  /**
25
58
  * Build the Cloudflare side of the accepted proxy topology: the public Worker owns the route and
26
59
  * binds the private application Worker. IAM remains a global service binding.
@@ -37,23 +70,21 @@ export function createCloudflareProxyWorker(options: CloudflareProxyWorkerOption
37
70
  }
38
71
 
39
72
  const local = options.appHost === 'localhost'
40
- const manifest: ProxyManifest = {
41
- apps: [{
42
- id: options.appId,
43
- hosts: local ? ['localhost', '127.0.0.1'] : [options.appHost],
44
- upstream: 'APP',
45
- gates: options.gates,
46
- // Cloudflare terminates TLS at the edge and a route is always https; only a localhost
47
- // binding is reached over plain HTTP.
48
- scheme: local ? 'http' : 'https',
49
- }],
50
- }
73
+ const placement = {
74
+ id: options.appId,
75
+ hosts: local ? ['localhost', '127.0.0.1'] : [options.appHost],
76
+ upstream: 'APP',
77
+ // Cloudflare terminates TLS at the edge and a route is always https; only a localhost
78
+ // binding is reached over plain HTTP.
79
+ scheme: local ? 'http' : 'https',
80
+ } satisfies Pick<ProxyApp, 'id' | 'hosts' | 'upstream' | 'scheme'>
81
+ const manifest: ProxyManifest = { apps: [proxyApp(placement, options)] }
51
82
  const domain = options.domain?.trim()
52
83
 
53
84
  return new Worker({
54
- dir: import.meta.dir,
85
+ dir: CLOUDFLARE_PROXY_WORKER_DIR,
55
86
  name: options.name,
56
- main: './proxy-worker.ts',
87
+ main: CLOUDFLARE_PROXY_WORKER_MAIN,
57
88
  compatibility_flags: ['nodejs_compat'],
58
89
  compatibility_date: '2025-05-25',
59
90
  routes: domain === undefined || domain === '' ? [] : [{ pattern: domain, custom_domain: true }],
@@ -63,8 +94,21 @@ export function createCloudflareProxyWorker(options: CloudflareProxyWorkerOption
63
94
  FABRIKA_IAM_ISSUER: options.iamUrl ?? '',
64
95
  },
65
96
  bindings: {
66
- IAM: new ServiceReference(options.iamService ?? 'propustka-worker'),
97
+ IAM: new ServiceReference(options.iamService ?? IAM_SERVICE, IAM_APPLICATION_ENTRYPOINT),
67
98
  APP: options.app,
68
99
  },
69
100
  })
70
101
  }
102
+
103
+ function proxyApp(placement: Pick<ProxyApp, 'id' | 'hosts' | 'upstream' | 'scheme'>, options: CloudflareProxyWorkerOptions): ProxyApp {
104
+ // A config written before the gates were removed is refused, never served unprotected.
105
+ if ('gates' in options) throw new Error('cloudflare proxy: `gates` is gone; an application is protected by its endpoint table')
106
+ if (options.installation !== undefined) {
107
+ if (options.endpoints !== undefined) throw new Error('cloudflare proxy carries exactly one of an endpoint table or an installation table')
108
+ const { installation, endpoints, reservedPrefixes } = options.installation
109
+ return { ...placement, installation, endpoints, reservedPrefixes }
110
+ }
111
+ const { endpoints, reservedPrefixes, snapshot, csp } = options.endpoints
112
+ const operationsOrigin = options.operationsOrigin
113
+ return { ...placement, endpoints, reservedPrefixes, snapshot, csp, ...(operationsOrigin === undefined ? {} : { operationsOrigin }) }
114
+ }