@fabrika/provider-cloudflare 0.3.2 → 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/package.json +8 -6
- package/src/assets.ts +16 -38
- package/src/authoring.ts +1 -0
- package/src/bounds.ts +434 -0
- package/src/checkout.ts +48 -0
- package/src/collaborators.ts +29 -2
- package/src/command.ts +54 -0
- package/src/config-schema.ts +26 -0
- package/src/control.ts +91 -51
- package/src/index.ts +6 -3
- package/src/installation/installation.ts +1 -1
- package/src/plan.ts +1 -192
- package/src/provider.ts +195 -22
- package/src/proxy-worker.ts +99 -18
- package/src/proxy.ts +63 -19
- package/src/runner-protocol.ts +28 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/provider-cloudflare",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,11 +42,13 @@
|
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"zod": "^3.25.76",
|
|
45
|
-
"@fabrika/
|
|
46
|
-
"@fabrika/auth
|
|
47
|
-
"@fabrika/
|
|
48
|
-
"@fabrika/
|
|
49
|
-
"@fabrika/
|
|
45
|
+
"@fabrika/app": "^0.4.0",
|
|
46
|
+
"@fabrika/auth": "^0.4.0",
|
|
47
|
+
"@fabrika/auth-core": "^0.4.0",
|
|
48
|
+
"@fabrika/check": "^0.4.0",
|
|
49
|
+
"@fabrika/installation-init": "^0.4.0",
|
|
50
|
+
"@fabrika/proxy-core": "^0.4.0",
|
|
51
|
+
"@fabrika/provider-contract": "^0.4.0",
|
|
50
52
|
"oblaka-iac": "^0.0.18"
|
|
51
53
|
}
|
|
52
54
|
}
|
package/src/assets.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { Stats } from 'node:fs'
|
|
2
2
|
import { lstat, readdir } from 'node:fs/promises'
|
|
3
3
|
import { resolve } from 'node:path'
|
|
4
|
-
import {
|
|
4
|
+
import type { GeneratedConfig } from 'oblaka-iac'
|
|
5
|
+
import { assetDirectory } from './bounds'
|
|
5
6
|
|
|
6
7
|
/** A ceiling on the walk, so a checkout cannot turn the check itself into the denial of service. */
|
|
7
8
|
const MAX_ASSET_ENTRIES = 50_000
|
|
@@ -17,27 +18,6 @@ const lstatOrNull = async (path: string): Promise<Stats | null> => {
|
|
|
17
18
|
}
|
|
18
19
|
}
|
|
19
20
|
|
|
20
|
-
const graphWorkers = (root: Worker): readonly Worker[] => {
|
|
21
|
-
const workers = new Set<Worker>()
|
|
22
|
-
const visit = (worker: Worker): void => {
|
|
23
|
-
if (workers.has(worker)) return
|
|
24
|
-
workers.add(worker)
|
|
25
|
-
for (const value of Object.values(worker.options.bindings ?? {})) {
|
|
26
|
-
if (value instanceof Worker) visit(value)
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
visit(root)
|
|
30
|
-
return [...workers]
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** `assertBoundedAssets` has already bounded the value; this only needs to find it. */
|
|
34
|
-
const assetDirectory = (worker: Worker): string | null => {
|
|
35
|
-
const assets: unknown = worker.options.assets
|
|
36
|
-
if (typeof assets !== 'object' || assets === null) return null
|
|
37
|
-
const directory: unknown = Reflect.get(assets, 'directory')
|
|
38
|
-
return typeof directory === 'string' && directory !== '' ? directory : null
|
|
39
|
-
}
|
|
40
|
-
|
|
41
21
|
interface WalkBudget {
|
|
42
22
|
count: number
|
|
43
23
|
}
|
|
@@ -66,22 +46,20 @@ const walk = async (base: string, prefix: string, budget: WalkBudget, refuse: Re
|
|
|
66
46
|
/**
|
|
67
47
|
* wrangler `stat`s each asset rather than `lstat`ing it, so a committed symlink to `/proc/self/environ`
|
|
68
48
|
* (the deploy's own environment holds the account token) or to `.git/config` uploads publicly. Call this
|
|
69
|
-
* per `wrangler deploy` spawn, for the
|
|
70
|
-
*
|
|
49
|
+
* per `wrangler deploy` spawn, for the config that spawn reads: the checkout's own build step runs between
|
|
50
|
+
* `open()` and the deploy, so that spawn is the only moment the tree is final.
|
|
71
51
|
*/
|
|
72
|
-
export const assertLiteralAssets = async (
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
throw refuse('is a symbolic link; wrangler follows it and would publish its target')
|
|
83
|
-
}
|
|
84
|
-
if (!stats.isDirectory()) continue
|
|
85
|
-
await walk(base, '', { count: 0 }, refuse)
|
|
52
|
+
export const assertLiteralAssets = async (generated: GeneratedConfig, configDir: string): Promise<void> => {
|
|
53
|
+
const directory = assetDirectory(generated)
|
|
54
|
+
if (directory === null) return
|
|
55
|
+
const base = resolve(configDir, directory)
|
|
56
|
+
const refuse = (detail: string): Error =>
|
|
57
|
+
new Error(`cloudflare: Worker \`${generated.config.name ?? generated.path}\` assets directory \`${directory}\` ${detail}`)
|
|
58
|
+
const stats = await lstatOrNull(base)
|
|
59
|
+
if (stats === null) return
|
|
60
|
+
if (stats.isSymbolicLink()) {
|
|
61
|
+
throw refuse('is a symbolic link; wrangler follows it and would publish its target')
|
|
86
62
|
}
|
|
63
|
+
if (!stats.isDirectory()) return
|
|
64
|
+
await walk(base, '', { count: 0 }, refuse)
|
|
87
65
|
}
|
package/src/authoring.ts
CHANGED
|
@@ -9,6 +9,7 @@ export interface ResourceContext {
|
|
|
9
9
|
|
|
10
10
|
/** A Cloudflare app config loaded from `fabrika.config.ts` inside the runner checkout. */
|
|
11
11
|
export interface CloudflareAppConfigInput extends AppConfigBase {
|
|
12
|
+
/** The application Worker. The deployer builds the proxy Worker in front of it from the contract (ADR-0048); never return one. */
|
|
12
13
|
readonly resources: (ctx: ResourceContext) => Worker
|
|
13
14
|
}
|
|
14
15
|
|
package/src/bounds.ts
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { type AppEnvironment, FRAMEWORK_VARIABLE_NAMES, isFrameworkVariableName, parseAppEnvironmentId } from '@fabrika/auth-core'
|
|
2
|
+
import { isProxyHost } from '@fabrika/proxy-core/manifest'
|
|
3
|
+
import { resolve } from 'node:path'
|
|
4
|
+
import type { GeneratedConfig, Worker } from 'oblaka-iac'
|
|
5
|
+
import { CloudflareClient } from 'oblaka-iac/src/client'
|
|
6
|
+
import { ResourceProcessor } from 'oblaka-iac/src/commands/resource-processor'
|
|
7
|
+
import { PLATFORM_RESOURCE_NAMES } from './plan'
|
|
8
|
+
import { CLOUDFLARE_PROXY_WORKER_DIR, IAM_APPLICATION_ENTRYPOINT, IAM_SERVICE } from './proxy'
|
|
9
|
+
|
|
10
|
+
type WranglerConfig = GeneratedConfig['config']
|
|
11
|
+
|
|
12
|
+
/** What a deployment may claim on the account. The generated wrangler configs are checked against it. */
|
|
13
|
+
export interface DeploymentBounds {
|
|
14
|
+
/** The environment oblaka provisions into. Every remote name is `${env}-${name}`. */
|
|
15
|
+
readonly env: string
|
|
16
|
+
/** The one hostname this environment may route; a route on any other host belongs to another app. */
|
|
17
|
+
readonly domain?: string
|
|
18
|
+
/** The directory a generated config's relative `path` is resolved against: the deploy's worker directory. */
|
|
19
|
+
readonly cwd: string
|
|
20
|
+
/** Fabrika deploying its own components is the one caller allowed to name a platform resource. */
|
|
21
|
+
readonly platformResources: 'refuse' | 'allow'
|
|
22
|
+
/** The IAM application id `<app>@<env>` of the deployment. */
|
|
23
|
+
readonly iamAppId: string
|
|
24
|
+
/** Every Cloudflare deployment of the installation in Control's registry; their names are refused. Empty outside a run. */
|
|
25
|
+
readonly installation: readonly AppEnvironment[]
|
|
26
|
+
/** The remote name of the proxy Worker the deployer built, or null when it built none. */
|
|
27
|
+
readonly proxy: string | null
|
|
28
|
+
/**
|
|
29
|
+
* The service binding the deployer wrote for each connector import (`FABRIKA_CONNECT_<IMPORT>`), by binding name, to
|
|
30
|
+
* the remote name of the owner's proxy Worker. These are the only bindings to another application's Worker.
|
|
31
|
+
*/
|
|
32
|
+
readonly connectors: Readonly<Record<string, string>>
|
|
33
|
+
/**
|
|
34
|
+
* The value of every framework variable the platform wrote into each Worker; a generated config must carry exactly
|
|
35
|
+
* these. `proxy` is null when the deployer built no proxy.
|
|
36
|
+
*/
|
|
37
|
+
readonly frameworkVariables: {
|
|
38
|
+
readonly application: Readonly<Record<string, string>>
|
|
39
|
+
readonly proxy: Readonly<Record<string, string>> | null
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The framework variables among a Worker's `vars`, as the deployer wrote them. */
|
|
44
|
+
export const frameworkValues = (vars: Readonly<Record<string, unknown>> | undefined): Record<string, string> => {
|
|
45
|
+
const values: Record<string, string> = {}
|
|
46
|
+
for (const [name, value] of Object.entries(vars ?? {})) {
|
|
47
|
+
if (isFrameworkVariableName(name) && typeof value === 'string') values[name] = value
|
|
48
|
+
}
|
|
49
|
+
return values
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Where the proxy Worker the deployer builds has its generated config: the runner's own copy of this package. */
|
|
53
|
+
const PROXY_CONFIG_PATH = resolve(CLOUDFLARE_PROXY_WORKER_DIR, 'wrangler.jsonc')
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Every key a generated config may carry. Each one either names nothing, or names a resource the checks below read.
|
|
57
|
+
* Fail closed: a key not listed here (`build`, `site`, `tail_consumers`, a new binding kind) is refused until reviewed.
|
|
58
|
+
*/
|
|
59
|
+
const CONFIG_KEYS: ReadonlySet<string> = new Set([
|
|
60
|
+
'name',
|
|
61
|
+
'main',
|
|
62
|
+
'compatibility_date',
|
|
63
|
+
'compatibility_flags',
|
|
64
|
+
'observability',
|
|
65
|
+
'routes',
|
|
66
|
+
'workers_dev',
|
|
67
|
+
'preview_urls',
|
|
68
|
+
'triggers',
|
|
69
|
+
'vars',
|
|
70
|
+
'assets',
|
|
71
|
+
'migrations',
|
|
72
|
+
'services',
|
|
73
|
+
'd1_databases',
|
|
74
|
+
'kv_namespaces',
|
|
75
|
+
'r2_buckets',
|
|
76
|
+
'queues',
|
|
77
|
+
'durable_objects',
|
|
78
|
+
'containers',
|
|
79
|
+
'workflows',
|
|
80
|
+
])
|
|
81
|
+
|
|
82
|
+
/** Everything wrangler reads out of `assets`. `directory` is the only one that names a path. */
|
|
83
|
+
const ASSETS_KEYS: ReadonlySet<string> = new Set(['binding', 'directory', 'html_handling', 'not_found_handling', 'run_worker_first'])
|
|
84
|
+
|
|
85
|
+
const RESOURCE_LABELS: Readonly<Record<string, string>> = {
|
|
86
|
+
worker: 'Worker',
|
|
87
|
+
d1_database: 'D1 database',
|
|
88
|
+
kv_namespace: 'KV namespace',
|
|
89
|
+
r2_bucket: 'R2 bucket',
|
|
90
|
+
queue: 'queue',
|
|
91
|
+
container: 'container',
|
|
92
|
+
workflow: 'workflow',
|
|
93
|
+
vectorize_index: 'Vectorize index',
|
|
94
|
+
analytics_engine: 'Analytics Engine dataset',
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** One resource oblaka would apply: the name it was declared under, the remote name it adopts, and its generated id. */
|
|
98
|
+
export interface GeneratedResource {
|
|
99
|
+
readonly kind: string
|
|
100
|
+
readonly name: string
|
|
101
|
+
readonly remote: string
|
|
102
|
+
readonly id: string | null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ConfigGeneration {
|
|
106
|
+
readonly configs: readonly GeneratedConfig[]
|
|
107
|
+
readonly resources: readonly GeneratedResource[]
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const stateId = (state: unknown): string | null => {
|
|
111
|
+
const id: unknown = typeof state === 'object' && state !== null ? Reflect.get(state, 'id') : undefined
|
|
112
|
+
return typeof id === 'string' ? id : null
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Generate the wrangler configs of a graph with oblaka's own processor, before any Cloudflare call: every resource is
|
|
117
|
+
* applied in dry-run mode with a client that refuses to authenticate, and nothing is written to disk.
|
|
118
|
+
*/
|
|
119
|
+
export const generateWranglerConfigs = async (definition: Worker, env: string): Promise<ConfigGeneration> => {
|
|
120
|
+
const client = new CloudflareClient({
|
|
121
|
+
accountId: '',
|
|
122
|
+
getToken: () => Promise.reject(new Error('cloudflare: the config generation run makes no Cloudflare call')),
|
|
123
|
+
})
|
|
124
|
+
const resources: GeneratedResource[] = []
|
|
125
|
+
const processor = new ResourceProcessor({
|
|
126
|
+
applyResource: async (resource) => {
|
|
127
|
+
const state = await resource.apply({ dryRun: true, context: { env, client } })
|
|
128
|
+
const { resource: kind, id: name } = resource.getId()
|
|
129
|
+
resources.push({ kind, name, remote: `${env}-${name}`, id: stateId(state) })
|
|
130
|
+
return state
|
|
131
|
+
},
|
|
132
|
+
}, async () => {})
|
|
133
|
+
return { configs: await processor.process({ definition, env }), resources }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The deployment being deployed, and every Cloudflare deployment of the installation in Control's registry. */
|
|
137
|
+
interface ApplicationNames {
|
|
138
|
+
readonly self: AppEnvironment
|
|
139
|
+
readonly installation: readonly AppEnvironment[]
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const applicationNames = ({ env, iamAppId, installation }: DeploymentBounds): ApplicationNames => {
|
|
143
|
+
const self = parseAppEnvironmentId(iamAppId)
|
|
144
|
+
if (self === null || self.env !== env) {
|
|
145
|
+
throw new Error(`cloudflare: \`${iamAppId}\` is not the application id of environment \`${env}\``)
|
|
146
|
+
}
|
|
147
|
+
return { self, installation }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The other application whose names `remote` falls under, or null. oblaka adopts `${env}-${name}`, and an application's
|
|
152
|
+
* names are `${env}-${app}` and `${env}-${app}-…`. The longest prefix decides, so `notes-admin` keeps its own names
|
|
153
|
+
* from `notes`; a prefix that two applications share is refused.
|
|
154
|
+
*/
|
|
155
|
+
const foreignApplication = (remote: string, { self, installation }: ApplicationNames): AppEnvironment | null => {
|
|
156
|
+
let longest = 0
|
|
157
|
+
let owner: AppEnvironment | null = null
|
|
158
|
+
for (const deployment of [self, ...installation]) {
|
|
159
|
+
const prefix = `${deployment.env}-${deployment.app}`
|
|
160
|
+
if (remote !== prefix && !remote.startsWith(`${prefix}-`)) continue
|
|
161
|
+
if (prefix.length > longest) {
|
|
162
|
+
longest = prefix.length
|
|
163
|
+
owner = deployment
|
|
164
|
+
} else if (prefix.length === longest && deployment.app !== self.app) {
|
|
165
|
+
owner = deployment
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return owner === null || owner.app === self.app ? null : owner
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* An env name may contain `-`, so env `prod-propustka` + Worker `worker` lands on IAM's `prod-propustka-worker`: a
|
|
173
|
+
* remote name that equals or ends with `-<platform name>` is a platform resource, wherever the env/name split falls.
|
|
174
|
+
*/
|
|
175
|
+
const platformRemoteName = (remote: string): string | null => {
|
|
176
|
+
for (const platform of PLATFORM_RESOURCE_NAMES) {
|
|
177
|
+
if (remote === platform || remote.endsWith(`-${platform}`)) return platform
|
|
178
|
+
}
|
|
179
|
+
return null
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** `subject` reads as the start of the refusal: "Worker `demo` binds service" or "D1 database `db` becomes". */
|
|
183
|
+
const assertOwnRemote = (subject: string, remote: unknown, names: ApplicationNames): void => {
|
|
184
|
+
if (typeof remote !== 'string' || remote === '') {
|
|
185
|
+
throw new Error(`cloudflare: ${subject} a name that cannot be read, so it cannot be checked`)
|
|
186
|
+
}
|
|
187
|
+
const platform = platformRemoteName(remote)
|
|
188
|
+
if (platform !== null) {
|
|
189
|
+
throw new Error(`cloudflare: ${subject} \`${remote}\`, which would take over the Fabrika platform resource \`${platform}\``)
|
|
190
|
+
}
|
|
191
|
+
const owner = foreignApplication(remote, names)
|
|
192
|
+
if (owner !== null) {
|
|
193
|
+
throw new Error(
|
|
194
|
+
`cloudflare: ${subject} \`${remote}\`, a name of application \`${owner.app}\` (environment \`${owner.env}\`); an application binds only its own resources`,
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const entries = (value: unknown, worker: string, key: string): readonly unknown[] => {
|
|
200
|
+
if (value === undefined) return []
|
|
201
|
+
if (!Array.isArray(value)) throw new Error(`cloudflare: Worker \`${worker}\` emits unreadable \`${key}\`, which cannot be checked`)
|
|
202
|
+
return value
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const field = (entry: unknown, name: string): unknown => typeof entry === 'object' && entry !== null ? Reflect.get(entry, name) : undefined
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The one platform service an application may bind is IAM, and only at `IAM_APPLICATION_ENTRYPOINT`: the default
|
|
209
|
+
* export issues keys and approves devices. Another application's Worker is never bound.
|
|
210
|
+
*/
|
|
211
|
+
const assertServices = (worker: string, config: WranglerConfig, names: ApplicationNames, connectors: Readonly<Record<string, string>>): void => {
|
|
212
|
+
const env = names.self.env
|
|
213
|
+
const iam = env === 'local' ? IAM_SERVICE : `${env}-${IAM_SERVICE}`
|
|
214
|
+
for (const entry of entries(config.services, worker, 'services')) {
|
|
215
|
+
const service = field(entry, 'service')
|
|
216
|
+
const entrypoint = field(entry, 'entrypoint')
|
|
217
|
+
const binding = field(entry, 'binding')
|
|
218
|
+
const owner = typeof binding === 'string' && Object.hasOwn(connectors, binding) ? connectors[binding] : undefined
|
|
219
|
+
if (owner !== undefined && service === owner && entrypoint === undefined) {
|
|
220
|
+
continue
|
|
221
|
+
}
|
|
222
|
+
if (service === iam) {
|
|
223
|
+
if (entrypoint !== IAM_APPLICATION_ENTRYPOINT) {
|
|
224
|
+
const bound = entrypoint === undefined ? 'its default entrypoint' : `entrypoint \`${String(entrypoint)}\``
|
|
225
|
+
throw new Error(
|
|
226
|
+
`cloudflare: Worker \`${worker}\` binds \`${service}\` to ${bound}; an application binds \`${IAM_APPLICATION_ENTRYPOINT}\` (use \`iamServiceReference()\`)`,
|
|
227
|
+
)
|
|
228
|
+
}
|
|
229
|
+
continue
|
|
230
|
+
}
|
|
231
|
+
assertOwnRemote(`Worker \`${worker}\` binds service`, service, names)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Every remote name a config's bindings carry, beside the services. */
|
|
236
|
+
const assertResourceBindings = (worker: string, config: WranglerConfig, names: ApplicationNames): void => {
|
|
237
|
+
const binds = (kind: string, remote: unknown): void => assertOwnRemote(`Worker \`${worker}\` binds ${kind}`, remote, names)
|
|
238
|
+
for (const entry of entries(config.d1_databases, worker, 'd1_databases')) binds('D1 database', field(entry, 'database_name'))
|
|
239
|
+
for (const entry of entries(config.r2_buckets, worker, 'r2_buckets')) binds('R2 bucket', field(entry, 'bucket_name'))
|
|
240
|
+
for (const entry of entries(config.containers, worker, 'containers')) binds('container', field(entry, 'name'))
|
|
241
|
+
for (const entry of entries(config.workflows, worker, 'workflows')) {
|
|
242
|
+
binds('workflow', field(entry, 'name'))
|
|
243
|
+
const script = field(entry, 'script_name')
|
|
244
|
+
if (script !== undefined) binds('the workflow script', script)
|
|
245
|
+
}
|
|
246
|
+
const queues = config.queues
|
|
247
|
+
for (const entry of entries(queues?.producers, worker, 'queues.producers')) binds('queue', field(entry, 'queue'))
|
|
248
|
+
for (const entry of entries(queues?.consumers, worker, 'queues.consumers')) {
|
|
249
|
+
binds('queue', field(entry, 'queue'))
|
|
250
|
+
const deadLetter = field(entry, 'dead_letter_queue')
|
|
251
|
+
if (deadLetter !== undefined) binds('dead-letter queue', deadLetter)
|
|
252
|
+
}
|
|
253
|
+
for (const entry of entries(config.durable_objects?.bindings, worker, 'durable_objects.bindings')) {
|
|
254
|
+
const script = field(entry, 'script_name')
|
|
255
|
+
if (script !== undefined) binds('the Durable Object script', script)
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* `assets.directory` is resolved against the generated `wrangler.jsonc`'s own directory and uploaded PUBLICLY: wrangler
|
|
261
|
+
* walks it and ignores only `.assetsignore`/`_redirects`/`_headers`, so `.` would publish the checkout's `.git/config`.
|
|
262
|
+
*/
|
|
263
|
+
const isContainedAssetDirectory = (value: unknown): value is string => {
|
|
264
|
+
if (typeof value !== 'string' || value.startsWith('/')) return false
|
|
265
|
+
const segments = value.split('/')
|
|
266
|
+
if (segments.includes('..') || segments.includes('.git')) return false
|
|
267
|
+
return segments.some((segment) => segment !== '' && segment !== '.')
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const assertBoundedAssets = (worker: string, assets: unknown): void => {
|
|
271
|
+
if (assets === undefined) return
|
|
272
|
+
if (typeof assets !== 'object' || assets === null || Array.isArray(assets)) {
|
|
273
|
+
throw new Error(`cloudflare: Worker \`${worker}\` sets \`assets\` to something that is not an object`)
|
|
274
|
+
}
|
|
275
|
+
for (const key of Object.keys(assets)) {
|
|
276
|
+
if (!ASSETS_KEYS.has(key)) {
|
|
277
|
+
throw new Error(`cloudflare: Worker \`${worker}\` sets \`assets.${key}\`, which an app may not configure`)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const directory: unknown = Reflect.get(assets, 'directory')
|
|
281
|
+
if (!isContainedAssetDirectory(directory)) {
|
|
282
|
+
throw new Error(
|
|
283
|
+
`cloudflare: Worker \`${worker}\` sets \`assets.directory\` to \`${
|
|
284
|
+
typeof directory === 'string' ? directory : '(not a string)'
|
|
285
|
+
}\`; it must be a relative path strictly inside the worker directory, with no \`..\` or \`.git\` segment`,
|
|
286
|
+
)
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* An application Worker is reachable only through its proxy's service binding (ADR-0048), so nothing may route it, and
|
|
292
|
+
* `workers.dev` and preview URLs must be off: Cloudflare enables both by default.
|
|
293
|
+
*/
|
|
294
|
+
const assertUnexposed = (worker: string, config: WranglerConfig): void => {
|
|
295
|
+
const routes: unknown = config.routes
|
|
296
|
+
if (routes !== undefined && !(Array.isArray(routes) && routes.length === 0)) {
|
|
297
|
+
throw new Error(`cloudflare: application Worker \`${worker}\` declares \`routes\`; only its proxy Worker is routed (omit it or set \`[]\`)`)
|
|
298
|
+
}
|
|
299
|
+
if (config.workers_dev !== false) {
|
|
300
|
+
throw new Error(
|
|
301
|
+
`cloudflare: application Worker \`${worker}\` leaves \`workers_dev\` on; it would be public on workers.dev (set \`workers_dev: false\`)`,
|
|
302
|
+
)
|
|
303
|
+
}
|
|
304
|
+
if (config.preview_urls !== false) {
|
|
305
|
+
throw new Error(
|
|
306
|
+
`cloudflare: application Worker \`${worker}\` leaves \`preview_urls\` on; every version would be public on workers.dev (set \`preview_urls: false\`)`,
|
|
307
|
+
)
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const routeHostname = (route: unknown): string | null => {
|
|
312
|
+
const pattern = typeof route === 'string' ? route : field(route, 'pattern')
|
|
313
|
+
if (typeof pattern !== 'string') return null
|
|
314
|
+
const host = pattern.split('/')[0]
|
|
315
|
+
return host === undefined ? null : host.toLowerCase()
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const assertRoutedHere = (worker: string, config: WranglerConfig, bounds: DeploymentBounds): void => {
|
|
319
|
+
for (const route of entries(config.routes, worker, 'routes')) {
|
|
320
|
+
const host = routeHostname(route)
|
|
321
|
+
if (host === null || !isProxyHost(host) || host !== bounds.domain?.toLowerCase()) {
|
|
322
|
+
throw new Error(`cloudflare: Worker \`${worker}\` routes \`${host ?? '(unreadable)'}\`, which is not this environment's domain`)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* A binding's `configureBinding` writes the generated config after the deployer injected its values, so the config is
|
|
329
|
+
* where a framework variable is checked: present exactly when the platform wrote it, and with the platform's value.
|
|
330
|
+
*/
|
|
331
|
+
const assertFrameworkVariables = (worker: string, vars: unknown, expected: Readonly<Record<string, string>>): void => {
|
|
332
|
+
if (vars !== undefined && (typeof vars !== 'object' || vars === null || Array.isArray(vars))) {
|
|
333
|
+
throw new Error(`cloudflare: Worker \`${worker}\` emits unreadable \`vars\`, which cannot be checked`)
|
|
334
|
+
}
|
|
335
|
+
const written = Object.keys(vars ?? {}).filter(isFrameworkVariableName)
|
|
336
|
+
for (const name of new Set([...FRAMEWORK_VARIABLE_NAMES, ...Object.keys(expected), ...written])) {
|
|
337
|
+
const actual: unknown = vars === undefined ? undefined : Reflect.get(vars, name)
|
|
338
|
+
if (actual !== expected[name]) {
|
|
339
|
+
throw new Error(`cloudflare: Worker \`${worker}\` sets \`${name}\` to a value Fabrika did not write; it is managed by Fabrika`)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const isPlatformProxy = (generated: GeneratedConfig, bounds: DeploymentBounds): boolean =>
|
|
345
|
+
bounds.proxy !== null && generated.config.name === bounds.proxy && resolve(bounds.cwd, generated.path) === PROXY_CONFIG_PATH
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Check the wrangler configs oblaka generated — what `wrangler deploy` reads, whatever objects emitted them — before
|
|
349
|
+
* provisioning and again before the deploy. Only the proxy Worker the deployer built is routed; every other config is
|
|
350
|
+
* an application Worker, and there is exactly one of those.
|
|
351
|
+
*/
|
|
352
|
+
export const assertGeneratedConfigs = (configs: readonly GeneratedConfig[], bounds: DeploymentBounds): void => {
|
|
353
|
+
if (bounds.platformResources === 'allow') {
|
|
354
|
+
for (const generated of configs) assertRoutedHere(generated.config.name ?? generated.path, generated.config, bounds)
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
const names = applicationNames(bounds)
|
|
358
|
+
if (configs.length === 0) {
|
|
359
|
+
throw new Error('cloudflare: oblaka generated no wrangler config, so there is nothing that can be checked')
|
|
360
|
+
}
|
|
361
|
+
const applications = configs.filter((generated) => !isPlatformProxy(generated, bounds))
|
|
362
|
+
if (applications.length > 1) {
|
|
363
|
+
const extra = applications.slice(1).map((generated) => `\`${generated.config.name ?? generated.path}\``).join(', ')
|
|
364
|
+
throw new Error(`cloudflare: config declares Worker ${extra}; only the application Worker and its proxy are deployable`)
|
|
365
|
+
}
|
|
366
|
+
for (const generated of configs) {
|
|
367
|
+
const config = generated.config
|
|
368
|
+
const worker = config.name ?? generated.path
|
|
369
|
+
for (const key of Object.keys(config)) {
|
|
370
|
+
if (!CONFIG_KEYS.has(key)) {
|
|
371
|
+
throw new Error(`cloudflare: Worker \`${worker}\` sets \`${key}\`, which an app may not configure; declare resources in \`bindings\``)
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
assertOwnRemote('the Worker is named', config.name, names)
|
|
375
|
+
assertServices(worker, config, names, isPlatformProxy(generated, bounds) ? {} : bounds.connectors)
|
|
376
|
+
assertResourceBindings(worker, config, names)
|
|
377
|
+
assertBoundedAssets(worker, config.assets)
|
|
378
|
+
if (isPlatformProxy(generated, bounds)) {
|
|
379
|
+
assertRoutedHere(worker, config, bounds)
|
|
380
|
+
assertFrameworkVariables(worker, config.vars, bounds.frameworkVariables.proxy ?? {})
|
|
381
|
+
continue
|
|
382
|
+
}
|
|
383
|
+
if (resolve(bounds.cwd, generated.path) === PROXY_CONFIG_PATH) {
|
|
384
|
+
throw new Error(`cloudflare: Worker \`${worker}\` lives in the directory of the proxy Worker the platform builds`)
|
|
385
|
+
}
|
|
386
|
+
assertUnexposed(worker, config)
|
|
387
|
+
assertFrameworkVariables(worker, config.vars, bounds.frameworkVariables.application)
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** The ids a resource of this generation run was given; a literal id in a config would bind something else by id. */
|
|
392
|
+
const assertGeneratedIds = (generation: ConfigGeneration): void => {
|
|
393
|
+
const ids = new Set(generation.resources.map((resource) => resource.id).filter((id) => id !== null))
|
|
394
|
+
for (const generated of generation.configs) {
|
|
395
|
+
const worker = generated.config.name ?? generated.path
|
|
396
|
+
const bound = (kind: string, id: unknown): void => {
|
|
397
|
+
if (typeof id !== 'string' || !ids.has(id)) {
|
|
398
|
+
throw new Error(`cloudflare: Worker \`${worker}\` binds a ${kind} by an id no resource of this deployment declares`)
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
for (const entry of entries(generated.config.d1_databases, worker, 'd1_databases')) bound('D1 database', field(entry, 'database_id'))
|
|
402
|
+
for (const entry of entries(generated.config.kv_namespaces, worker, 'kv_namespaces')) bound('KV namespace', field(entry, 'id'))
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* The generation run's checks: every generated config, every resource oblaka would apply by the remote name it adopts
|
|
408
|
+
* (a KV namespace's config carries only its id), and every id-bound binding against the ids the run handed out.
|
|
409
|
+
*/
|
|
410
|
+
export const assertGeneration = (generation: ConfigGeneration, bounds: DeploymentBounds): void => {
|
|
411
|
+
if (bounds.platformResources === 'refuse') {
|
|
412
|
+
const names = applicationNames(bounds)
|
|
413
|
+
for (const resource of generation.resources) {
|
|
414
|
+
// A Durable Object class lives inside its script and adopts no account-wide name.
|
|
415
|
+
if (resource.kind === 'durable_object') continue
|
|
416
|
+
assertOwnRemote(`${RESOURCE_LABELS[resource.kind] ?? resource.kind} \`${resource.name}\` becomes`, resource.remote, names)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
assertGeneratedConfigs(generation.configs, bounds)
|
|
420
|
+
if (bounds.platformResources === 'refuse') assertGeneratedIds(generation)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** The KV namespace oblaka keeps deploy state in is the ONE name it uses verbatim (`KVStateStorage`): no env prefix. */
|
|
424
|
+
export const assertStateNamespace = (stateNamespace: string, platformResources: 'refuse' | 'allow'): void => {
|
|
425
|
+
if (platformResources === 'refuse' && PLATFORM_RESOURCE_NAMES.has(stateNamespace)) {
|
|
426
|
+
throw new Error(`cloudflare: state namespace \`${stateNamespace}\` is a Fabrika platform resource and cannot be used by an app`)
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** The `assets.directory` of a generated config, relative to the config's own directory, once it has been bounded. */
|
|
431
|
+
export const assetDirectory = (generated: GeneratedConfig): string | null => {
|
|
432
|
+
const directory = field(generated.config.assets, 'directory')
|
|
433
|
+
return typeof directory === 'string' && directory !== '' ? directory : null
|
|
434
|
+
}
|
package/src/checkout.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Worker } from 'oblaka-iac'
|
|
2
|
+
|
|
3
|
+
type Binding = Worker['options']['bindings'][string]
|
|
4
|
+
|
|
5
|
+
/** A checkout installs its own `oblaka-iac`, so its Workers are recognised by oblaka's resource kind, never `instanceof`. */
|
|
6
|
+
const isWorkerResource = (value: unknown): value is object => {
|
|
7
|
+
if (typeof value !== 'object' || value === null) return false
|
|
8
|
+
const getId: unknown = Reflect.get(value, 'getId')
|
|
9
|
+
if (typeof getId !== 'function') return false
|
|
10
|
+
const id: unknown = Reflect.apply(getId, value, [])
|
|
11
|
+
return typeof id === 'object' && id !== null && Reflect.get(id, 'resource') === 'worker'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const isBinding = (value: unknown): value is Binding =>
|
|
15
|
+
typeof value === 'object' && value !== null && typeof Reflect.get(value, 'configureBinding') === 'function'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Rebuild the Worker graph a checkout's config returned out of this package's own `Worker` class, so oblaka's
|
|
19
|
+
* processor and the deployer see one class whichever `oblaka-iac` the checkout installed. Every option is carried
|
|
20
|
+
* over as it is; the generated configs are what is checked. Other bindings stay the checkout's objects.
|
|
21
|
+
*/
|
|
22
|
+
export const runnerWorkerGraph = (value: unknown, path: readonly unknown[] = []): Worker => {
|
|
23
|
+
if (!isWorkerResource(value)) {
|
|
24
|
+
throw new Error('cloudflare: `resources` must return an oblaka `Worker`')
|
|
25
|
+
}
|
|
26
|
+
if (path.includes(value)) {
|
|
27
|
+
throw new Error('cloudflare: the Worker graph binds a Worker that binds itself back')
|
|
28
|
+
}
|
|
29
|
+
const options: unknown = Reflect.get(value, 'options')
|
|
30
|
+
const name: unknown = typeof options === 'object' && options !== null ? Reflect.get(options, 'name') : undefined
|
|
31
|
+
const dir: unknown = typeof options === 'object' && options !== null ? Reflect.get(options, 'dir') : undefined
|
|
32
|
+
if (typeof options !== 'object' || options === null || typeof name !== 'string' || typeof dir !== 'string') {
|
|
33
|
+
throw new Error('cloudflare: a Worker of the config has no readable `name` and `dir`')
|
|
34
|
+
}
|
|
35
|
+
const authored: unknown = Reflect.get(options, 'bindings')
|
|
36
|
+
const bindings: Record<string, Binding> = {}
|
|
37
|
+
for (const [key, binding] of Object.entries(typeof authored === 'object' && authored !== null ? authored : {})) {
|
|
38
|
+
const resolved: unknown = binding
|
|
39
|
+
if (isWorkerResource(resolved)) bindings[key] = runnerWorkerGraph(resolved, [...path, value])
|
|
40
|
+
else if (isBinding(resolved)) bindings[key] = resolved
|
|
41
|
+
else throw new Error(`cloudflare: Worker \`${name}\` binding \`${key}\` is not an oblaka binding`)
|
|
42
|
+
}
|
|
43
|
+
const worker = new Worker({ dir, name, compatibility_flags: [], bindings })
|
|
44
|
+
for (const [key, option] of Object.entries(options)) {
|
|
45
|
+
if (key !== 'bindings') Reflect.set(worker.options, key, option)
|
|
46
|
+
}
|
|
47
|
+
return worker
|
|
48
|
+
}
|
package/src/collaborators.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import type { ContractArtifact } from '@fabrika/auth-core'
|
|
2
|
+
import { CONTRACT_FILE, readApplicationTree } from '@fabrika/check'
|
|
3
|
+
import { readContractSource } from '@fabrika/check/contract'
|
|
1
4
|
import type { SchemaReconciler } from '@fabrika/provider-contract'
|
|
2
|
-
import { writeFile } from 'node:fs/promises'
|
|
3
|
-
import { resolve } from 'node:path'
|
|
5
|
+
import { lstat, writeFile } from 'node:fs/promises'
|
|
6
|
+
import { join, resolve } from 'node:path'
|
|
4
7
|
import { type Definition, deploy as oblakaDeploy, type DeployResult as OblakaDeployResult } from 'oblaka-iac'
|
|
5
8
|
import { type CloudflareAppConfig, isCloudflareAppConfig } from './authoring'
|
|
6
9
|
import { RUNNER_OUTCOME_FILE_ENV, type RunnerOutcomeFile } from './runner-protocol'
|
|
@@ -46,8 +49,12 @@ export interface LoadedCloudflareConfig {
|
|
|
46
49
|
|
|
47
50
|
export type CloudflareConfigLoader = (cwd: string, configPath: string) => Promise<LoadedCloudflareConfig>
|
|
48
51
|
|
|
52
|
+
/** The contract an application root declares, or null when it has no `fabrika.contract.ts`. */
|
|
53
|
+
export type ContractReader = (root: string) => Promise<ContractArtifact | null>
|
|
54
|
+
|
|
49
55
|
export interface CloudflareCollaborators {
|
|
50
56
|
readonly loadConfig: CloudflareConfigLoader
|
|
57
|
+
readonly readContract: ContractReader
|
|
51
58
|
readonly runCommand: CommandRunner
|
|
52
59
|
readonly provision: OblakaProvisioner
|
|
53
60
|
readonly writeOutcome: OutcomeWriter
|
|
@@ -67,6 +74,25 @@ const defaultLoadConfig: CloudflareConfigLoader = async (cwd, configPath) => {
|
|
|
67
74
|
return { config: loaded.config, cwd: loaded.cwd }
|
|
68
75
|
}
|
|
69
76
|
|
|
77
|
+
const isMissingFile = (error: unknown): boolean => error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Read the contract from the checkout's text with the static reader Control runs at the commit (ADR-0005): nothing
|
|
81
|
+
* is executed. A `fabrika.contract.ts` that is not a regular file is refused, so a link cannot hide the contract.
|
|
82
|
+
*/
|
|
83
|
+
const defaultReadContract: ContractReader = async (root) => {
|
|
84
|
+
const entry = await lstat(join(root, CONTRACT_FILE)).catch((error: unknown) => {
|
|
85
|
+
if (isMissingFile(error)) return null
|
|
86
|
+
throw error
|
|
87
|
+
})
|
|
88
|
+
if (entry === null) return null
|
|
89
|
+
if (!entry.isFile()) {
|
|
90
|
+
throw new Error(`cloudflare: \`${CONTRACT_FILE}\` is not a regular file`)
|
|
91
|
+
}
|
|
92
|
+
const tree = await readApplicationTree(root)
|
|
93
|
+
return readContractSource(tree.files)
|
|
94
|
+
}
|
|
95
|
+
|
|
70
96
|
const childEnvironment = (spec: CommandSpec): Record<string, string | undefined> => {
|
|
71
97
|
const inherited: Record<string, string | undefined> = { ...process.env }
|
|
72
98
|
for (const name of spec.omitEnv ?? []) {
|
|
@@ -123,6 +149,7 @@ const defaultWriteOutcome: OutcomeWriter = async (outcome) => {
|
|
|
123
149
|
|
|
124
150
|
export const defaultCloudflareCollaborators: CloudflareCollaborators = {
|
|
125
151
|
loadConfig: defaultLoadConfig,
|
|
152
|
+
readContract: defaultReadContract,
|
|
126
153
|
runCommand: defaultRunCommand,
|
|
127
154
|
provision: defaultProvision,
|
|
128
155
|
writeOutcome: defaultWriteOutcome,
|