@fabrika/provider-cloudflare 0.9.0-dev.4 → 0.9.0-dev.5
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 +11 -10
- package/src/authoring.ts +56 -6
- package/src/bounds.ts +145 -4
- package/src/cli.ts +14 -0
- package/src/command.ts +29 -4
- package/src/contract-support.ts +235 -0
- package/src/control.ts +55 -118
- package/src/deploy-order.ts +35 -0
- package/src/index.ts +19 -3
- package/src/installation/init.ts +11 -18
- package/src/installation/installation.ts +2 -4
- package/src/installation/scaffold.ts +29 -2
- package/src/installation/templates/README.md +29 -11
- package/src/installation/templates/platform.yml +9 -5
- package/src/managed-secrets.ts +61 -0
- package/src/plan.ts +13 -3
- package/src/provider.ts +455 -64
- package/src/proxy-worker.ts +40 -16
- package/src/proxy.ts +48 -16
- package/src/runner-protocol.ts +35 -2
- package/src/spa-assets.ts +176 -0
- package/types/src/authoring.d.ts +27 -5
- package/types/src/bounds.d.ts +19 -0
- package/types/src/cli.d.ts +6 -0
- package/types/src/command.d.ts +8 -3
- package/types/src/contract-support.d.ts +80 -0
- package/types/src/control.d.ts +108 -69
- package/types/src/deploy-order.d.ts +8 -0
- package/types/src/index.d.ts +3 -3
- package/types/src/managed-secrets.d.ts +19 -0
- package/types/src/plan.d.ts +2 -1
- package/types/src/provider.d.ts +38 -1
- package/types/src/proxy-worker.d.ts +1 -0
- package/types/src/proxy.d.ts +21 -0
- package/types/src/runner-protocol.d.ts +32 -0
- package/types/src/spa-assets.d.ts +28 -0
package/src/proxy-worker.ts
CHANGED
|
@@ -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
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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 =
|
|
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
|
|
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 =
|
|
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
|
|
@@ -184,23 +191,27 @@ function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify:
|
|
|
184
191
|
const value = verification.headers.get(header)
|
|
185
192
|
if (value !== null && value !== '') upstreamHeaders.set(header, value)
|
|
186
193
|
}
|
|
187
|
-
//
|
|
188
|
-
// the
|
|
194
|
+
// A contract app never receives the caller's `px_` key (ADR-0022 rule 3): an anonymous endpoint mints no token and
|
|
195
|
+
// loses the header, a credentialed one gets the minted token in its place, and a webhook the decision marked keeps its own.
|
|
189
196
|
const forwards = verification.headers.get(FORWARD_AUTHORIZATION_HEADER) === '1'
|
|
190
|
-
|
|
197
|
+
const minted = upstreamHeaders.get(PROXY_TOKEN_HEADER)
|
|
198
|
+
if (isApplicationEntry(app) && !forwards) {
|
|
199
|
+
if (minted === null) upstreamHeaders.delete('Authorization')
|
|
200
|
+
else if (upstreamHeaders.has('Authorization')) upstreamHeaders.set('Authorization', `Bearer ${minted}`)
|
|
201
|
+
}
|
|
191
202
|
|
|
192
203
|
let answer: Response
|
|
193
204
|
try {
|
|
194
205
|
answer = await upstream.fetch(new Request(request, { headers: upstreamHeaders }))
|
|
195
206
|
} catch {
|
|
196
207
|
// Nothing of the error is answered or logged: it can carry the upstream request, a token header included.
|
|
197
|
-
answer =
|
|
208
|
+
answer = failure(502, 'bad gateway', request, download, manifest)
|
|
198
209
|
}
|
|
199
210
|
if (treatment === undefined) return answer
|
|
200
211
|
// The treatment deleted the application's own `Access-Control-*`; only the origin the decision admitted is set.
|
|
201
212
|
const allowOrigin = verification.headers.get(ALLOW_ORIGIN_HEADER)
|
|
202
213
|
return withResponseHeaders(answer, (headers) => {
|
|
203
|
-
treatment(
|
|
214
|
+
treatment(endpoint, answer.status)(headers)
|
|
204
215
|
if (allowOrigin !== null) applyCrossOriginHeaders(headers, crossOriginHeaders(allowOrigin))
|
|
205
216
|
})
|
|
206
217
|
}
|
|
@@ -234,6 +245,13 @@ function contractAnswerHeaders(app: ContractProxyApp): AnswerHeaders {
|
|
|
234
245
|
}
|
|
235
246
|
}
|
|
236
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
|
+
|
|
237
255
|
/** What only the decision may assert to the app; each is copied from an allow, the way Caddy's `copy_headers` does. */
|
|
238
256
|
const PROXY_ASSERTED_HEADERS = [PROXY_TOKEN_HEADER, REQUEST_ID_HEADER, ENDPOINT_HEADER, DELEGATION_HEADER]
|
|
239
257
|
|
|
@@ -292,8 +310,14 @@ function isObject(value: unknown): value is Record<string, unknown> {
|
|
|
292
310
|
return typeof value === 'object' && value !== null
|
|
293
311
|
}
|
|
294
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
|
+
|
|
295
319
|
export default {
|
|
296
320
|
fetch(request: Request, env: CloudflareProxyEnv): Promise<Response> {
|
|
297
|
-
return createCloudflareProxyHandler(env)(request)
|
|
321
|
+
return createCloudflareProxyHandler({ ...env, FABRIKA_PROXY_MANIFEST_JSON: BAKED_MANIFEST_JSON })(request)
|
|
298
322
|
},
|
|
299
323
|
}
|
package/src/proxy.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
+
contractProxyEntry,
|
|
2
3
|
type ContractProxyTable,
|
|
3
4
|
encodeProxyManifestJson,
|
|
4
5
|
type InstallationProxyTable,
|
|
@@ -7,6 +8,9 @@ import {
|
|
|
7
8
|
} from '@fabrika/proxy-core/manifest'
|
|
8
9
|
import { ServiceReference, Worker } from 'oblaka-iac'
|
|
9
10
|
|
|
11
|
+
/** A binding as oblaka configures it into a Worker's generated config. */
|
|
12
|
+
type Binding = Pick<ServiceReference, 'configureBinding'>
|
|
13
|
+
|
|
10
14
|
interface CloudflareProxyWorkerBase {
|
|
11
15
|
/** Name of the proxy Worker before the environment prefix is applied by oblaka. */
|
|
12
16
|
readonly name: string
|
|
@@ -47,6 +51,20 @@ export type CloudflareProxyWorkerOptions =
|
|
|
47
51
|
export const CLOUDFLARE_PROXY_WORKER_DIR: string = import.meta.dir
|
|
48
52
|
export const CLOUDFLARE_PROXY_WORKER_MAIN = './proxy-worker.ts'
|
|
49
53
|
|
|
54
|
+
/**
|
|
55
|
+
* The identifier the proxy Worker's bundle reads its manifest from. The generated config's `define` replaces it with
|
|
56
|
+
* the manifest as a string literal when wrangler bundles the Worker, so the table has no Worker variable's 5 KB cap.
|
|
57
|
+
*/
|
|
58
|
+
export const PROXY_MANIFEST_DEFINE = '__FABRIKA_PROXY_MANIFEST__'
|
|
59
|
+
|
|
60
|
+
/** The manifest JSON a proxy Worker built here carries, or null for any other Worker. */
|
|
61
|
+
export const proxyManifestJson = (worker: Worker): string | null => {
|
|
62
|
+
const literal = worker.options.define?.[PROXY_MANIFEST_DEFINE]
|
|
63
|
+
if (literal === undefined) return null
|
|
64
|
+
const value: unknown = JSON.parse(literal)
|
|
65
|
+
return typeof value === 'string' ? value : null
|
|
66
|
+
}
|
|
67
|
+
|
|
50
68
|
/** IAM's Worker: the one platform service an application binds, and only through the entrypoint below. */
|
|
51
69
|
export const IAM_SERVICE = 'propustka-worker'
|
|
52
70
|
|
|
@@ -56,6 +74,25 @@ export const IAM_APPLICATION_ENTRYPOINT = 'PropustkaApplication'
|
|
|
56
74
|
/** The `IAM` binding of an application Worker; a generated config that binds IAM any other way is refused. */
|
|
57
75
|
export const iamServiceReference = (): ServiceReference => new ServiceReference(IAM_SERVICE, IAM_APPLICATION_ENTRYPOINT)
|
|
58
76
|
|
|
77
|
+
/**
|
|
78
|
+
* The deployer's `IAM` binding: what the Worker declared, with the IAM service entry's `props` naming the deployment's
|
|
79
|
+
* IAM application id. IAM reads it as `ctx.props.app`, the transport identity of a call over the binding, as the
|
|
80
|
+
* membership transport key is over HTTP (ADR-0067 §3). An application cannot choose it: the deployer writes it, and the
|
|
81
|
+
* bounds refuse an IAM binding that names any other application.
|
|
82
|
+
*/
|
|
83
|
+
export class IamApplicationReference implements Binding {
|
|
84
|
+
constructor(
|
|
85
|
+
private readonly app: string,
|
|
86
|
+
private readonly declared: Binding = iamServiceReference(),
|
|
87
|
+
) {}
|
|
88
|
+
|
|
89
|
+
configureBinding(args: Parameters<Binding['configureBinding']>[0]): ReturnType<Binding['configureBinding']> {
|
|
90
|
+
const config = this.declared.configureBinding(args)
|
|
91
|
+
const services = (config.services ?? []).map((entry) => entry.binding === args.binding ? { ...entry, props: { app: this.app } } : entry)
|
|
92
|
+
return { ...config, services }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
59
96
|
/**
|
|
60
97
|
* Build the Cloudflare side of the accepted proxy topology: the public Worker owns the route and
|
|
61
98
|
* binds the private application Worker. IAM remains a global service binding.
|
|
@@ -83,6 +120,9 @@ export function createCloudflareProxyWorker(options: CloudflareProxyWorkerOption
|
|
|
83
120
|
const manifest: ProxyManifest = { apps: [proxyApp(placement, options)] }
|
|
84
121
|
const domain = options.domain?.trim()
|
|
85
122
|
|
|
123
|
+
const iam = new ServiceReference(options.iamService ?? IAM_SERVICE, IAM_APPLICATION_ENTRYPOINT)
|
|
124
|
+
// An application's proxy names its application to IAM, as the application Worker's binding does; a platform
|
|
125
|
+
// service's proxy is trusted composition and calls no operation that is pinned to an application.
|
|
86
126
|
return new Worker({
|
|
87
127
|
dir: CLOUDFLARE_PROXY_WORKER_DIR,
|
|
88
128
|
name: options.name,
|
|
@@ -91,12 +131,10 @@ export function createCloudflareProxyWorker(options: CloudflareProxyWorkerOption
|
|
|
91
131
|
compatibility_date: '2025-05-25',
|
|
92
132
|
routes: domain === undefined || domain === '' ? [] : [{ pattern: domain, custom_domain: true }],
|
|
93
133
|
observability: { logs: { enabled: true, invocation_logs: false } },
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
FABRIKA_IAM_ISSUER: options.iamUrl ?? '',
|
|
97
|
-
},
|
|
134
|
+
define: { [PROXY_MANIFEST_DEFINE]: JSON.stringify(encodeProxyManifestJson(manifest)) },
|
|
135
|
+
vars: { FABRIKA_IAM_ISSUER: options.iamUrl ?? '' },
|
|
98
136
|
bindings: {
|
|
99
|
-
IAM: new
|
|
137
|
+
IAM: options.installation === undefined ? new IamApplicationReference(options.appId, iam) : iam,
|
|
100
138
|
APP: options.app,
|
|
101
139
|
},
|
|
102
140
|
})
|
|
@@ -110,16 +148,10 @@ function proxyApp(placement: Pick<ProxyApp, 'id' | 'hosts' | 'upstream' | 'schem
|
|
|
110
148
|
const { installation, endpoints, reservedPrefixes } = options.installation
|
|
111
149
|
return { ...placement, installation, endpoints, reservedPrefixes }
|
|
112
150
|
}
|
|
113
|
-
|
|
114
|
-
const operationsOrigin = options.operationsOrigin
|
|
115
|
-
const crossOrigins = options.crossOrigins ?? []
|
|
116
|
-
return {
|
|
151
|
+
return contractProxyEntry({
|
|
117
152
|
...placement,
|
|
118
|
-
endpoints,
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
...(operationsOrigin === undefined ? {} : { operationsOrigin }),
|
|
123
|
-
...(crossOrigins.length === 0 ? {} : { crossOrigins: [...crossOrigins] }),
|
|
124
|
-
}
|
|
153
|
+
table: options.endpoints,
|
|
154
|
+
...(options.operationsOrigin === undefined ? {} : { operationsOrigin: options.operationsOrigin }),
|
|
155
|
+
...(options.crossOrigins === undefined ? {} : { crossOrigins: options.crossOrigins }),
|
|
156
|
+
})
|
|
125
157
|
}
|
package/src/runner-protocol.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { contractArtifactSchema } from '@fabrika/app/contract'
|
|
2
|
-
import { type ContractArtifact, isDigest } from '@fabrika/auth-core'
|
|
2
|
+
import { type ContractArtifact, isDigest, parseApplicationObjects } from '@fabrika/auth-core'
|
|
3
|
+
import { FRAMEWORK_RELEASE_PATTERN } from '@fabrika/provider-contract'
|
|
3
4
|
import { z } from 'zod'
|
|
4
5
|
|
|
5
6
|
export const runnerStateSchema = z.enum(['pending', 'cloning', 'installing', 'deploying', 'succeeded', 'failed'])
|
|
@@ -25,6 +26,25 @@ export const INSTALLATION_APPS_ENV = 'FABRIKA_INSTALLATION_APPS'
|
|
|
25
26
|
/** The executor's copy of `CloudflareRunnerJob.crossOrigins`: a JSON array of the environment's exact origins. */
|
|
26
27
|
export const CROSS_ORIGINS_ENV = 'FABRIKA_CROSS_ORIGINS'
|
|
27
28
|
|
|
29
|
+
/** The executor's copy of `CloudflareRunnerJob.operationsOrigin`: the origin of the environment's Operations ingest. */
|
|
30
|
+
export const OPERATIONS_ORIGIN_ENV = 'FABRIKA_OPERATIONS_ORIGIN'
|
|
31
|
+
|
|
32
|
+
/** The executor's copy of `CloudflareRunnerJob.applicationObjects`: JSON `{ object, objects }`, the pointer Control records. */
|
|
33
|
+
export const APPLICATION_OBJECTS_ENV = 'FABRIKA_RUNNER_APPLICATION_OBJECTS'
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The serving object and the listed objects as the job and the executor carry them: the shape `parseApplicationObjects`
|
|
37
|
+
* accepts, so a pointer the application would refuse never reaches a deploy.
|
|
38
|
+
*/
|
|
39
|
+
export const applicationObjectsSchema = z.object({ object: z.string(), objects: z.array(z.string()) }).strict().transform((value, ctx) => {
|
|
40
|
+
const parsed = parseApplicationObjects(value.object, value.objects.join(','))
|
|
41
|
+
if (parsed === null) {
|
|
42
|
+
ctx.addIssue({ code: 'custom', message: 'not a valid serving object and object list' })
|
|
43
|
+
return z.NEVER
|
|
44
|
+
}
|
|
45
|
+
return parsed
|
|
46
|
+
})
|
|
47
|
+
|
|
28
48
|
/**
|
|
29
49
|
* The access Control approved for a run (ADR-0050): the contract it read at the commit, in this release's model, and
|
|
30
50
|
* the digest the application's own framework release computes for it. The proxy table and `FABRIKA_CONTRACT_DIGEST`
|
|
@@ -35,12 +55,20 @@ export interface RunnerApprovedAccess {
|
|
|
35
55
|
readonly kind: 'contract'
|
|
36
56
|
readonly contract: ContractArtifact
|
|
37
57
|
readonly contractDigest: string
|
|
58
|
+
/**
|
|
59
|
+
* The framework release the application pins (`applicationRelease`), which every release gate of the deployer reads:
|
|
60
|
+
* the Durable Object from 0.9, the stateless Worker before it. An older Control sends its reader's
|
|
61
|
+
* release here, a newer patch of the same minor. Absent from a Control older than the runner, which deploys the
|
|
62
|
+
* older shape.
|
|
63
|
+
*/
|
|
64
|
+
readonly framework?: string
|
|
38
65
|
}
|
|
39
66
|
|
|
40
67
|
export const runnerApprovedAccessSchema = z.object({
|
|
41
68
|
kind: z.literal('contract'),
|
|
42
69
|
contract: z.unknown(),
|
|
43
70
|
contractDigest: z.string().refine(isDigest),
|
|
71
|
+
framework: z.string().regex(FRAMEWORK_RELEASE_PATTERN).optional(),
|
|
44
72
|
})
|
|
45
73
|
.strict()
|
|
46
74
|
.transform((access, context): RunnerApprovedAccess => {
|
|
@@ -49,7 +77,12 @@ export const runnerApprovedAccessSchema = z.object({
|
|
|
49
77
|
context.addIssue({ code: z.ZodIssueCode.custom, message: 'not a contract artifact' })
|
|
50
78
|
return z.NEVER
|
|
51
79
|
}
|
|
52
|
-
return {
|
|
80
|
+
return {
|
|
81
|
+
kind: 'contract',
|
|
82
|
+
contract: contract.data,
|
|
83
|
+
contractDigest: access.contractDigest,
|
|
84
|
+
...(access.framework === undefined ? {} : { framework: access.framework }),
|
|
85
|
+
}
|
|
53
86
|
})
|
|
54
87
|
|
|
55
88
|
/** Where the runner leaves the job's `RunnerApprovedAccess` as JSON for the executor — beside the checkout, never inside it. */
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// The SPA files of a contract application on Cloudflare. Workers Assets gives a Worker one directory, and a contract may
|
|
2
|
+
// declare several SPA and link mounts, each with a build directory of its own, so the deploy stages every mount's files
|
|
3
|
+
// into one directory that mirrors the request paths (`/admin/app.js` is `admin/app.js`), and the application's object
|
|
4
|
+
// serves a mount's paths from it (`bindingAssets` of `@fabrika/app`).
|
|
5
|
+
|
|
6
|
+
import { CLOUDFLARE_ASSETS_BINDING } from '@fabrika/app/build'
|
|
7
|
+
import type { ContractArtifact } from '@fabrika/auth-core'
|
|
8
|
+
import ignore, { type Ignore } from 'ignore'
|
|
9
|
+
import type { Stats } from 'node:fs'
|
|
10
|
+
import { copyFile, lstat, mkdir, readdir, readFile, rm } from 'node:fs/promises'
|
|
11
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
12
|
+
|
|
13
|
+
/** Where the deploy stages the mounts' files, beside the generated `wrangler.jsonc` of the application Worker. */
|
|
14
|
+
export const SPA_ASSETS_DIRECTORY = 'fabrika/assets'
|
|
15
|
+
|
|
16
|
+
/** The `assets` the platform writes into an application Worker that declares none and has a mount with files. */
|
|
17
|
+
export const SPA_ASSETS = { directory: SPA_ASSETS_DIRECTORY, binding: CLOUDFLARE_ASSETS_BINDING, run_worker_first: true } as const
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The files Workers Assets reads as its own configuration at the root of the directory: a build that wrote them would
|
|
21
|
+
* steer the platform's asset routing and headers, so they are never staged.
|
|
22
|
+
*/
|
|
23
|
+
const ASSET_CONFIG_PATHS: ReadonlySet<string> = new Set(['/_headers', '/_redirects', '/.assetsignore'])
|
|
24
|
+
|
|
25
|
+
/** A mount's own ignore file, read as wrangler reads the one at the root of an `assets.directory`. */
|
|
26
|
+
const ASSETS_IGNORE_FILE = '.assetsignore'
|
|
27
|
+
|
|
28
|
+
/** Version control metadata, never staged under any name or depth, whatever a mount's ignore file says. */
|
|
29
|
+
const VCS_NAMES: ReadonlySet<string> = new Set(['.git', '.hg', '.svn', '.bzr'])
|
|
30
|
+
|
|
31
|
+
/** A ceiling on the staging walk, as on the check of a published directory. */
|
|
32
|
+
const MAX_ASSET_ENTRIES = 50_000
|
|
33
|
+
|
|
34
|
+
/** A mount that serves files: its prefix, and its build directory relative to the application's root. */
|
|
35
|
+
export interface AssetMount {
|
|
36
|
+
readonly name: string
|
|
37
|
+
readonly prefix: string
|
|
38
|
+
readonly dir: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Every SPA and link mount of the contract with the directory its files come from, the most specific prefix first. */
|
|
42
|
+
export const assetMounts = (contract: ContractArtifact): readonly AssetMount[] =>
|
|
43
|
+
Object.entries(contract.mounts)
|
|
44
|
+
.flatMap(([name, mount]): AssetMount[] =>
|
|
45
|
+
mount.kind === 'spa'
|
|
46
|
+
? [{ name, prefix: mount.prefix, dir: mount.dir }]
|
|
47
|
+
: mount.kind === 'link'
|
|
48
|
+
? [{ name, prefix: mount.prefix, dir: mount.spa }]
|
|
49
|
+
: []
|
|
50
|
+
)
|
|
51
|
+
.sort((left, right) => right.prefix.length - left.prefix.length || (left.prefix < right.prefix ? -1 : left.prefix > right.prefix ? 1 : 0))
|
|
52
|
+
|
|
53
|
+
/** The request path of `file` (relative, `/`-separated) of the mount at `prefix`. */
|
|
54
|
+
const requestPath = (prefix: string, file: string): string => (prefix === '/' ? `/${file}` : `${prefix}/${file}`)
|
|
55
|
+
|
|
56
|
+
/** Whether `path` is the mount at `prefix` or lies below it: the proxy routes it there, never to a shorter prefix. */
|
|
57
|
+
const isUnder = (path: string, prefix: string): boolean => prefix !== '/' && (path === prefix || path.startsWith(`${prefix}/`))
|
|
58
|
+
|
|
59
|
+
const lstatOrNull = async (path: string): Promise<Stats | null> => {
|
|
60
|
+
try {
|
|
61
|
+
return await lstat(path)
|
|
62
|
+
} catch (err) {
|
|
63
|
+
const code: unknown = err instanceof Error ? Reflect.get(err, 'code') : undefined
|
|
64
|
+
if (code === 'ENOENT' || code === 'ENOTDIR') return null
|
|
65
|
+
throw err
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Whether some segment of `relativePath` below `base` is a symbolic link, from the first segment to the last. `resolve`
|
|
71
|
+
* only reads the text, so `x/etc` with `x -> /` passes it; this reads the disk. A segment that does not exist ends it.
|
|
72
|
+
*/
|
|
73
|
+
const linkOnPath = async (base: string, relativePath: string): Promise<string | null> => {
|
|
74
|
+
let current = base
|
|
75
|
+
for (const segment of relativePath.split('/').filter((part) => part !== '' && part !== '.')) {
|
|
76
|
+
current = join(current, segment)
|
|
77
|
+
const stats = await lstatOrNull(current)
|
|
78
|
+
if (stats === null) return null
|
|
79
|
+
if (stats.isSymbolicLink()) return relative(base, current)
|
|
80
|
+
}
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The mount's `.assetsignore` with wrangler's semantics (the `ignore` package, gitignore syntax, relative to the mount's
|
|
86
|
+
* directory), which also ignores the file itself. Workers Assets reads only the one at the root of the uploaded
|
|
87
|
+
* directory, so the deploy applies each mount's before it stages anything: a build excludes its files as it would with
|
|
88
|
+
* its own `assets`.
|
|
89
|
+
*/
|
|
90
|
+
const mountIgnore = async (source: string, refuse: (detail: string) => Error): Promise<Ignore> => {
|
|
91
|
+
const rules = ignore().add(`/${ASSETS_IGNORE_FILE}`)
|
|
92
|
+
const path = join(source, ASSETS_IGNORE_FILE)
|
|
93
|
+
const stats = await lstatOrNull(path)
|
|
94
|
+
if (stats === null) return rules
|
|
95
|
+
if (!stats.isFile()) throw refuse(`contains \`${ASSETS_IGNORE_FILE}\`, which is not a regular file`)
|
|
96
|
+
return rules.add(await readFile(path, 'utf8'))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const isWithin = (root: string, path: string): boolean => {
|
|
100
|
+
const between = relative(root, path)
|
|
101
|
+
return between === '' || (!between.startsWith('..') && !isAbsolute(between))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Copy each mount's build directory under `root` into `target` at its prefix, after removing whatever `target` held. A
|
|
106
|
+
* file of a mount that lies under a longer mount's prefix is that mount's path, so it is left out; a source map is never
|
|
107
|
+
* served (the platform build uploads it to Operations), so it is left out too, and so is Workers Assets' own
|
|
108
|
+
* configuration at the root (`ASSET_CONFIG_PATHS`), what the mount's `.assetsignore` excludes, and version control
|
|
109
|
+
* metadata (`VCS_NAMES`) at any depth. A mount whose directory is missing, a symbolic link anywhere on
|
|
110
|
+
* its path or in its tree, or anything but a regular file or a directory is refused: the staged tree is uploaded
|
|
111
|
+
* publicly, and a link would publish its target. `target` is `SPA_ASSETS_DIRECTORY` under `base`, with no link on the
|
|
112
|
+
* way either. Returns how many files it staged.
|
|
113
|
+
*/
|
|
114
|
+
export const stageSpaAssets = async (mounts: readonly AssetMount[], root: string, base: string): Promise<number> => {
|
|
115
|
+
const target = resolve(base, SPA_ASSETS_DIRECTORY)
|
|
116
|
+
const targetLink = await linkOnPath(base, SPA_ASSETS_DIRECTORY)
|
|
117
|
+
if (targetLink !== null) {
|
|
118
|
+
throw new Error(`cloudflare: \`${targetLink}\` is a symbolic link, and the deploy stages the SPA files into \`${SPA_ASSETS_DIRECTORY}\``)
|
|
119
|
+
}
|
|
120
|
+
const sources = mounts.map((mount) => {
|
|
121
|
+
const source = resolve(root, mount.dir)
|
|
122
|
+
const segments = mount.dir.split('/')
|
|
123
|
+
if (isAbsolute(mount.dir) || segments.includes('..') || segments.includes('.git') || !isWithin(root, source) || source === root) {
|
|
124
|
+
throw new Error(`cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which is no directory inside the application`)
|
|
125
|
+
}
|
|
126
|
+
if (isWithin(source, target) || isWithin(target, source)) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which overlaps \`${SPA_ASSETS_DIRECTORY}\`, where the deploy stages the SPA files`,
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
return { mount, source }
|
|
132
|
+
})
|
|
133
|
+
await rm(target, { recursive: true, force: true })
|
|
134
|
+
await mkdir(target, { recursive: true })
|
|
135
|
+
let entries = 0
|
|
136
|
+
let staged = 0
|
|
137
|
+
for (const { mount, source } of sources) {
|
|
138
|
+
const refuse = (detail: string): Error => new Error(`cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which ${detail}`)
|
|
139
|
+
const link = await linkOnPath(root, mount.dir)
|
|
140
|
+
if (link !== null) throw refuse(`passes \`${link}\`, a symbolic link; the deploy would publish its target`)
|
|
141
|
+
const stats = await lstatOrNull(source)
|
|
142
|
+
if (stats === null) {
|
|
143
|
+
throw refuse('the build did not produce; build it in `pipeline.build`')
|
|
144
|
+
}
|
|
145
|
+
if (!stats.isDirectory()) {
|
|
146
|
+
throw refuse(stats.isSymbolicLink() ? 'is a symbolic link; the deploy would publish its target' : 'is not a directory')
|
|
147
|
+
}
|
|
148
|
+
const ignored = await mountIgnore(source, refuse)
|
|
149
|
+
const longer = mounts.filter((other) => other.prefix.length > mount.prefix.length).map((other) => other.prefix)
|
|
150
|
+
const walk = async (prefix: string): Promise<void> => {
|
|
151
|
+
for (const name of (await readdir(join(source, prefix))).sort()) {
|
|
152
|
+
entries += 1
|
|
153
|
+
if (entries > MAX_ASSET_ENTRIES) throw refuse(`holds more than ${MAX_ASSET_ENTRIES} entries with the other mounts`)
|
|
154
|
+
const file = prefix === '' ? name : `${prefix}/${name}`
|
|
155
|
+
const path = requestPath(mount.prefix, file)
|
|
156
|
+
if (VCS_NAMES.has(name) || longer.some((other) => isUnder(path, other)) || ASSET_CONFIG_PATHS.has(path)) continue
|
|
157
|
+
const entry = await lstat(join(source, file))
|
|
158
|
+
// The trailing `/` is how the matcher tells a directory, so `secret/` excludes the directory and all below it.
|
|
159
|
+
if (ignored.ignores(entry.isDirectory() ? `${file}/` : file)) continue
|
|
160
|
+
if (entry.isSymbolicLink()) throw refuse(`contains \`${file}\`, a symbolic link; the deploy would publish its target`)
|
|
161
|
+
if (entry.isDirectory()) {
|
|
162
|
+
await walk(file)
|
|
163
|
+
} else if (!entry.isFile()) {
|
|
164
|
+
throw refuse(`contains \`${file}\`, which is neither a regular file nor a directory`)
|
|
165
|
+
} else if (!file.endsWith('.map')) {
|
|
166
|
+
const destination = join(target, path.slice(1))
|
|
167
|
+
await mkdir(dirname(destination), { recursive: true })
|
|
168
|
+
await copyFile(join(source, file), destination)
|
|
169
|
+
staged += 1
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
await walk('')
|
|
174
|
+
}
|
|
175
|
+
return staged
|
|
176
|
+
}
|
package/types/src/authoring.d.ts
CHANGED
|
@@ -1,17 +1,39 @@
|
|
|
1
1
|
import { type AppConfigBase, type ProviderAuthoredApp } from '@fabrika/provider-contract';
|
|
2
|
-
import
|
|
2
|
+
import { Worker } from 'oblaka-iac';
|
|
3
3
|
/** Inputs used to materialize one environment's Cloudflare resource graph. */
|
|
4
4
|
export interface ResourceContext {
|
|
5
5
|
readonly env: string;
|
|
6
6
|
readonly domain?: string;
|
|
7
7
|
}
|
|
8
|
+
/** What an author may set on the application Worker `defineApp` builds; everything else is fixed by the platform. */
|
|
9
|
+
export interface ApplicationWorkerOptions {
|
|
10
|
+
/** The application's own bindings, beside `IAM`, which is always the platform's. */
|
|
11
|
+
readonly bindings?: Worker['options']['bindings'];
|
|
12
|
+
readonly compatibility_date?: string;
|
|
13
|
+
readonly compatibility_flags?: Worker['options']['compatibility_flags'];
|
|
14
|
+
}
|
|
15
|
+
/** A Cloudflare app config as `fabrika.config.ts` writes it. */
|
|
16
|
+
export type CloudflareAppConfigInput = AppConfigBase & ({
|
|
17
|
+
/**
|
|
18
|
+
* The application Worker, for a config that composes its own. The deployer builds the proxy Worker in front of it
|
|
19
|
+
* from the contract (ADR-0048); never return one.
|
|
20
|
+
*/
|
|
21
|
+
readonly resources: (ctx: ResourceContext) => Worker;
|
|
22
|
+
readonly worker?: never;
|
|
23
|
+
} | {
|
|
24
|
+
readonly resources?: never;
|
|
25
|
+
/** Without `resources`, `defineApp` builds the application Worker from these and the platform's fixed values. */
|
|
26
|
+
readonly worker?: ApplicationWorkerOptions;
|
|
27
|
+
});
|
|
8
28
|
/** A Cloudflare app config loaded from `fabrika.config.ts` inside the runner checkout. */
|
|
9
|
-
export interface
|
|
10
|
-
/** The application Worker. The deployer builds the proxy Worker in front of it from the contract (ADR-0048)
|
|
29
|
+
export interface CloudflareAppConfig extends AppConfigBase, ProviderAuthoredApp<'cloudflare'> {
|
|
30
|
+
/** The application Worker. The deployer builds the proxy Worker in front of it from the contract (ADR-0048). */
|
|
11
31
|
readonly resources: (ctx: ResourceContext) => Worker;
|
|
12
32
|
}
|
|
13
|
-
|
|
14
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Validate the app id and fill in the application Worker when the config composes none. The result always carries
|
|
35
|
+
* `resources`, because a runner narrows a loaded config with `isCloudflareAppConfig`, which requires it.
|
|
36
|
+
*/
|
|
15
37
|
export declare function defineApp(config: CloudflareAppConfigInput): CloudflareAppConfig;
|
|
16
38
|
/** Narrow an imported module default without trusting code from the checkout. */
|
|
17
39
|
export declare const isCloudflareAppConfig: (value: unknown) => value is CloudflareAppConfig;
|
package/types/src/bounds.d.ts
CHANGED
|
@@ -29,6 +29,25 @@ export interface DeploymentBounds {
|
|
|
29
29
|
readonly application: Readonly<Record<string, string>>;
|
|
30
30
|
readonly proxy: Readonly<Record<string, string>> | null;
|
|
31
31
|
};
|
|
32
|
+
/** The `define` literal of the manifest the deployer baked into its proxy Worker, or null when it built none. */
|
|
33
|
+
readonly proxyManifest: string | null;
|
|
34
|
+
/** What the platform gives a contract application's Worker (ADR-0065), or null outside one. */
|
|
35
|
+
readonly application: ApplicationRuntime | null;
|
|
36
|
+
}
|
|
37
|
+
/** The Durable Object, files bucket and cron trigger of a contract application's Worker; the application authors none of them. */
|
|
38
|
+
export interface ApplicationRuntime {
|
|
39
|
+
/** The remote name of the environment's files bucket. */
|
|
40
|
+
readonly filesBucket: string;
|
|
41
|
+
/**
|
|
42
|
+
* The cron triggers the Worker carries when the contract has a job or a file kind, else an empty list: the hourly repair
|
|
43
|
+
* tick of a release that serves alarms, otherwise the minute tick.
|
|
44
|
+
*/
|
|
45
|
+
readonly crons: readonly string[];
|
|
46
|
+
/**
|
|
47
|
+
* The absolute path of the entry the deploy regenerates, which the Worker's `main` must name (`pinsGeneratedEntry`), or
|
|
48
|
+
* null for a release whose Worker keeps its authored `main`.
|
|
49
|
+
*/
|
|
50
|
+
readonly entry: string | null;
|
|
32
51
|
}
|
|
33
52
|
/** The framework variables among a Worker's `vars`, as the deployer wrote them. */
|
|
34
53
|
export declare const frameworkValues: (vars: Readonly<Record<string, unknown>> | undefined) => Record<string, string>;
|
package/types/src/cli.d.ts
CHANGED
|
@@ -1,2 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
+
import type { AppCli } from '@fabrika/provider-contract/app-cli';
|
|
2
3
|
export declare const runCloudflareCli: (argv: readonly string[]) => Promise<void>;
|
|
4
|
+
/**
|
|
5
|
+
* What `fabrika app build` and `app deploy` run for an application on Cloudflare. A contract application's build is its
|
|
6
|
+
* generated Worker entry, which the `fabrika` command writes; there is nothing else to build.
|
|
7
|
+
*/
|
|
8
|
+
export declare const appCli: AppCli;
|
package/types/src/command.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { type AppEnvironment } from '@fabrika/auth-core';
|
|
1
|
+
import { type AppEnvironment, type ApplicationObjects } from '@fabrika/auth-core';
|
|
2
2
|
import type { CloudflareAppConfig } from './authoring';
|
|
3
3
|
import { type CloudflareDeployResult, type PlatformIamTarget } from './provider';
|
|
4
4
|
import { type RunnerApprovedAccess } from './runner-protocol';
|
|
5
5
|
/**
|
|
6
|
-
* Decode `FABRIKA_IAM_RETURN_ORIGINS`, the comma-separated set the
|
|
7
|
-
* deploy
|
|
6
|
+
* Decode `FABRIKA_IAM_RETURN_ORIGINS`, the comma-separated set the installation's workflow hands the
|
|
7
|
+
* platform's own deploy (ADR-0022). Undefined for an absent or empty value, so a deploy with nothing to
|
|
8
8
|
* project leaves IAM's registry alone rather than clearing it. Part of the executor's environment
|
|
9
9
|
* contract, exported for the test that pins it; not part of the package's public surface.
|
|
10
10
|
*/
|
|
@@ -14,6 +14,11 @@ export declare const parseReturnOrigins: (raw: string | undefined) => readonly s
|
|
|
14
14
|
* empty; anything malformed fails the deploy, and the proxy manifest's own parser judges each origin.
|
|
15
15
|
*/
|
|
16
16
|
export declare const parseCrossOrigins: (raw: string | undefined) => readonly string[] | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Decode `FABRIKA_RUNNER_APPLICATION_OBJECTS`, the pointer Control recorded, as the runner writes it. Undefined when
|
|
19
|
+
* absent, and the deployer writes its defaults; anything malformed fails the deploy rather than move ordinary traffic.
|
|
20
|
+
*/
|
|
21
|
+
export declare const parseApplicationObjectsEnvironment: (raw: string | undefined) => ApplicationObjects | undefined;
|
|
17
22
|
/**
|
|
18
23
|
* Decode `FABRIKA_INSTALLATION_APPS`, the Cloudflare deployments Control registered, as the runner writes it.
|
|
19
24
|
* Undefined when absent; anything malformed fails the deploy rather than dropping the refusal it feeds.
|