@zabaca/zbc 0.12.0 → 0.14.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/CHANGELOG.md +174 -0
- package/package.json +6 -2
- package/src/commands/add.ts +13 -0
- package/src/commands/init.ts +1 -0
- package/src/engine/apply.ts +60 -21
- package/src/engine/destroy.ts +183 -14
- package/src/engine/discover.ts +1 -1
- package/src/engine/resolve.ts +56 -11
- package/src/utils/copy-template.ts +10 -0
- package/templates/apps/inbox/package.json +4 -2
- package/templates/apps/inbox/tsconfig.json +3 -1
- package/templates/apps/inbox/worker/api.ts +197 -0
- package/templates/apps/inbox/worker/commands.ts +299 -0
- package/templates/apps/inbox/worker/inbox-do.ts +53 -10
- package/templates/apps/inbox/worker/index.ts +15 -202
- package/templates/apps/inbox/worker/mcp.ts +49 -100
- package/templates/apps/walgit/CONTEXT.md +135 -0
- package/templates/apps/walgit/Dockerfile +40 -18
- package/templates/apps/walgit/README.md +518 -55
- package/templates/apps/walgit/e2e/README.md +100 -6
- package/templates/apps/walgit/e2e/harness.ts +262 -1
- package/templates/apps/walgit/e2e/live.ts +588 -0
- package/templates/apps/walgit/e2e/scenarios.ts +367 -5
- package/templates/apps/walgit/e2e/suite.ts +5 -5
- package/templates/apps/walgit/examples/watch.ts +209 -0
- package/templates/apps/walgit/package.json +12 -3
- package/templates/apps/walgit/registry.json +6 -11
- package/templates/apps/walgit/shared/capabilities.ts +189 -0
- package/templates/apps/walgit/shared/container-env.ts +114 -0
- package/templates/apps/walgit/shared/credentials.ts +81 -0
- package/templates/apps/walgit/shared/events.ts +277 -0
- package/templates/apps/walgit/shared/landing.ts +1241 -0
- package/templates/apps/walgit/shared/llms.ts +463 -0
- package/templates/apps/walgit/shared/outbox.ts +266 -0
- package/templates/apps/walgit/shared/policy.ts +59 -0
- package/templates/apps/walgit/shared/protocol.ts +197 -0
- package/templates/apps/walgit/shared/provenance.ts +154 -0
- package/templates/apps/walgit/shared/ref-cache.ts +181 -0
- package/templates/apps/walgit/shared/telemetry.ts +219 -0
- package/templates/apps/walgit/src/announce-main.ts +37 -0
- package/templates/apps/walgit/src/announce.ts +98 -0
- package/templates/apps/walgit/src/append-only.ts +112 -0
- package/templates/apps/walgit/src/cache.ts +172 -0
- package/templates/apps/walgit/src/cli.ts +493 -0
- package/templates/apps/walgit/src/compact.ts +25 -23
- package/templates/apps/walgit/src/delete-repo.ts +237 -0
- package/templates/apps/walgit/src/expire.ts +248 -0
- package/templates/apps/walgit/src/gc.ts +8 -16
- package/templates/apps/walgit/src/git-backend.ts +29 -0
- package/templates/apps/walgit/src/git.ts +78 -0
- package/templates/apps/walgit/src/hook-main.ts +259 -17
- package/templates/apps/walgit/src/hooks.ts +4 -3
- package/templates/apps/walgit/src/http.ts +237 -45
- package/templates/apps/walgit/src/instructions.ts +240 -0
- package/templates/apps/walgit/src/keys.ts +126 -0
- package/templates/apps/walgit/src/limits.ts +158 -0
- package/templates/apps/walgit/src/materialize.bench.ts +10 -10
- package/templates/apps/walgit/src/materialize.ts +48 -40
- package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
- package/templates/apps/walgit/src/orphans.ts +2 -5
- package/templates/apps/walgit/src/pending.ts +201 -0
- package/templates/apps/walgit/src/push-cert.ts +254 -0
- package/templates/apps/walgit/src/push.ts +233 -46
- package/templates/apps/walgit/src/reconcile.ts +5 -8
- package/templates/apps/walgit/src/repo.ts +22 -77
- package/templates/apps/walgit/src/server.ts +148 -26
- package/templates/apps/walgit/src/signers.ts +577 -0
- package/templates/apps/walgit/src/store-env.ts +5 -4
- package/templates/apps/walgit/src/store.ts +47 -24
- package/templates/apps/walgit/src/usage.ts +404 -0
- package/templates/apps/walgit/src/verify.ts +171 -0
- package/templates/apps/walgit/src/wal-index.ts +189 -11
- package/templates/apps/walgit/tsconfig.json +8 -2
- package/templates/apps/walgit/tsconfig.worker.json +24 -0
- package/templates/apps/walgit/worker/events-do.ts +259 -0
- package/templates/apps/walgit/worker/index.ts +572 -0
- package/templates/apps/walgit/wrangler.jsonc +95 -0
- package/templates/apps/warehouse/package.json +1 -1
- package/templates/infra/modules/cloudflare/index.ts +93 -67
- package/templates/infra/modules/cloudflare-access/index.ts +3 -3
- package/templates/infra/modules/cloudflare-api/index.ts +144 -32
- package/templates/infra/modules/cloudflare-api/registry.json +1 -1
- package/templates/infra/modules/cloudflare-email/index.ts +103 -144
- package/templates/infra/modules/cloudflare-email/registry.json +1 -1
- package/templates/infra/modules/cloudflare-token/index.ts +10 -30
- package/templates/infra/modules/cloudflare-token/registry.json +1 -1
- package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
- package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
- package/templates/infra/modules/fly/index.ts +158 -35
- package/templates/infra/modules/host-file/index.ts +6 -7
- package/templates/infra/modules/provision-core/index.ts +21 -15
- package/templates/infra/modules/r2/index.ts +38 -55
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/modules/remote-provision/index.ts +1 -3
- package/templates/infra/modules/turso/index.ts +45 -7
- package/templates/infra/modules/vm-provision/index.ts +10 -3
- package/templates/infra/package.json +1 -1
- package/templates/infra/src/context.ts +115 -0
- package/templates/infra/src/define-module.ts +8 -2
- package/templates/infra/src/index.ts +11 -1
- package/templates/infra/src/types.ts +72 -3
- package/src/commands/add-registry.test.ts +0 -92
- package/src/commands/secret.test.ts +0 -717
- package/src/commands/vendor-mode.test.ts +0 -183
- package/src/infra-types.ts +0 -38
- package/src/utils/subtree.test.ts +0 -127
- package/templates/apps/inbox/worker/send-op.ts +0 -174
- package/templates/apps/walgit/entrypoint.sh +0 -59
- package/templates/apps/walgit/fly.toml +0 -52
- package/templates/apps/walgit/src/ssh-shell.ts +0 -36
- package/templates/apps/walgit/sshd_config +0 -38
|
@@ -3,13 +3,14 @@ import * as fs from 'node:fs'
|
|
|
3
3
|
import { execSync, spawnSync } from 'node:child_process'
|
|
4
4
|
import { z } from 'zod'
|
|
5
5
|
import { defineModule } from '../../src/define-module'
|
|
6
|
+
import type { ApplyContext } from '../../src/types'
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* cloudflare — deploys a Cloudflare Worker (optionally with static assets, a
|
|
9
10
|
* Durable Object, and a Container) via `wrangler deploy`.
|
|
10
11
|
*
|
|
11
12
|
* This is a THIN orchestrator, the same shape as the turso module: `apply` runs
|
|
12
|
-
* on the operator machine, reads CF creds
|
|
13
|
+
* on the operator machine, reads CF creds through `ctx.secret`, runs an optional
|
|
13
14
|
* local build, then shells `wrangler deploy` in the package's own directory. The
|
|
14
15
|
* Worker TOPOLOGY (name, assets binding, durable_objects, containers,
|
|
15
16
|
* migrations) lives in that package's `wrangler.jsonc` — wrangler is the source
|
|
@@ -39,8 +40,8 @@ import { defineModule } from '../../src/define-module'
|
|
|
39
40
|
* IMPORT SYNC: `workerSecrets` and `workerVars` entries can be either a plain
|
|
40
41
|
* name (resolved from this environment's secrets.yaml, exactly as before) or a
|
|
41
42
|
* `{ name, from, output }` reference into an imported instance's outputs
|
|
42
|
-
* (`ctx.
|
|
43
|
-
* validated outputs). Secrets are pushed via `wrangler secret put`, piped
|
|
43
|
+
* (`ctx.output({ from, output }, field)`, resolved by the engine from that
|
|
44
|
+
* instance's validated outputs). Secrets are pushed via `wrangler secret put`, piped
|
|
44
45
|
* through stdin; vars are passed as `wrangler deploy --var KEY:VALUE`. The two
|
|
45
46
|
* are deliberately separate fields — a var is visible in `wrangler.jsonc`/the
|
|
46
47
|
* dashboard, a secret is not — so an imported value's exposure is an explicit
|
|
@@ -86,12 +87,30 @@ const buildSchema = z.object({
|
|
|
86
87
|
cwd: z.string().optional(),
|
|
87
88
|
})
|
|
88
89
|
|
|
90
|
+
/**
|
|
91
|
+
* The origin a route pattern answers on, for `deployUrl` when there is no
|
|
92
|
+
* workers.dev URL to report.
|
|
93
|
+
*
|
|
94
|
+
* Only a pattern whose host is a concrete hostname qualifies. A wildcard host
|
|
95
|
+
* (`*.example.com/*`) names a set rather than an address, and emitting
|
|
96
|
+
* `https://*.example.com` would hand a dependent a string that looks like a URL
|
|
97
|
+
* and resolves to nothing.
|
|
98
|
+
*/
|
|
99
|
+
export function routeUrl(routes: string[]): string {
|
|
100
|
+
for (const route of routes) {
|
|
101
|
+
const host = route.split('/')[0]
|
|
102
|
+
if (host && !host.includes('*') && host.includes('.')) return `https://${host}`
|
|
103
|
+
}
|
|
104
|
+
return ''
|
|
105
|
+
}
|
|
106
|
+
|
|
89
107
|
/**
|
|
90
108
|
* A worker secret/var entry: a plain name (resolved from this environment's
|
|
91
109
|
* secrets.yaml), a `{ name, value }` literal (vars that are per-instance
|
|
92
110
|
* config rather than secrets — e.g. DEFAULT_FROM — so a generic wrangler.jsonc
|
|
93
|
-
* needs no editing),
|
|
94
|
-
* instance's outputs (`ctx.
|
|
111
|
+
* needs no editing), a `{ name, from, output }` reference into an imported
|
|
112
|
+
* instance's outputs (`ctx.output`), or a `{ name, secret }`
|
|
113
|
+
* pair that exposes a secrets.yaml key under a different env var name.
|
|
95
114
|
*/
|
|
96
115
|
const workerValueSchema = z.union([
|
|
97
116
|
z.string(),
|
|
@@ -109,6 +128,21 @@ const workerValueSchema = z.union([
|
|
|
109
128
|
/** Which output of that instance to read. */
|
|
110
129
|
output: z.string(),
|
|
111
130
|
}),
|
|
131
|
+
z.object({
|
|
132
|
+
/** Env var name inside the Worker. */
|
|
133
|
+
name: z.string(),
|
|
134
|
+
/**
|
|
135
|
+
* A key in this environment's secrets.yaml, exposed under `name`.
|
|
136
|
+
*
|
|
137
|
+
* The plain-string form already reads a secret, but it forces the Worker's
|
|
138
|
+
* env var to be spelled exactly like the secret. An app whose interface
|
|
139
|
+
* says `WALGIT_S3_ACCESS_KEY_ID` cannot then read a credential filed as
|
|
140
|
+
* `WAREHOUSE_R2_ACCESS_KEY_ID` — and the alternative is a second copy of
|
|
141
|
+
* the same credential under a second name, which is one more thing to
|
|
142
|
+
* forget when it rotates. Same form, same reason, as the `fly` module's.
|
|
143
|
+
*/
|
|
144
|
+
secret: z.string(),
|
|
145
|
+
}),
|
|
112
146
|
])
|
|
113
147
|
|
|
114
148
|
type WorkerValueEntry = z.infer<typeof workerValueSchema>
|
|
@@ -116,36 +150,24 @@ type WorkerValueEntry = z.infer<typeof workerValueSchema>
|
|
|
116
150
|
/** Resolve a workerSecrets/workerVars entry to its `{ name, value }` pair. */
|
|
117
151
|
function resolveWorkerValue(
|
|
118
152
|
entry: WorkerValueEntry,
|
|
119
|
-
ctx:
|
|
153
|
+
ctx: ApplyContext,
|
|
120
154
|
fieldName: string,
|
|
121
155
|
): { name: string; value: string } {
|
|
122
156
|
if (typeof entry === 'string') {
|
|
123
|
-
|
|
124
|
-
if (!value) {
|
|
125
|
-
throw new Error(
|
|
126
|
-
`${fieldName} references "${entry}" but it's missing from this environment's secrets.yaml`,
|
|
127
|
-
)
|
|
128
|
-
}
|
|
129
|
-
return { name: entry, value }
|
|
157
|
+
return { name: entry, value: ctx.secret(entry, { field: fieldName }) }
|
|
130
158
|
}
|
|
131
159
|
|
|
132
160
|
if ('value' in entry) {
|
|
133
161
|
return { name: entry.name, value: entry.value }
|
|
134
162
|
}
|
|
135
163
|
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
)
|
|
141
|
-
}
|
|
142
|
-
const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
|
|
143
|
-
if (typeof value !== 'string') {
|
|
144
|
-
throw new Error(
|
|
145
|
-
`${fieldName} entry "${entry.name}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
|
|
146
|
-
)
|
|
164
|
+
const field = `${fieldName} entry "${entry.name}"`
|
|
165
|
+
|
|
166
|
+
if ('secret' in entry) {
|
|
167
|
+
return { name: entry.name, value: ctx.secret(entry.secret, { field }) }
|
|
147
168
|
}
|
|
148
|
-
|
|
169
|
+
|
|
170
|
+
return { name: entry.name, value: ctx.output(entry, field) }
|
|
149
171
|
}
|
|
150
172
|
|
|
151
173
|
/**
|
|
@@ -177,22 +199,13 @@ type R2BindingEntry = z.infer<typeof r2BindingSchema>
|
|
|
177
199
|
|
|
178
200
|
function resolveR2Binding(
|
|
179
201
|
entry: R2BindingEntry,
|
|
180
|
-
ctx:
|
|
202
|
+
ctx: ApplyContext,
|
|
181
203
|
): { binding: string; bucketName: string } {
|
|
182
204
|
if ('bucketName' in entry) return { binding: entry.binding, bucketName: entry.bucketName }
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
`r2Bindings entry "${entry.binding}" references instance "${entry.from}", which is not in this instance's imports`,
|
|
187
|
-
)
|
|
188
|
-
}
|
|
189
|
-
const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
|
|
190
|
-
if (typeof value !== 'string') {
|
|
191
|
-
throw new Error(
|
|
192
|
-
`r2Bindings entry "${entry.binding}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
|
|
193
|
-
)
|
|
205
|
+
return {
|
|
206
|
+
binding: entry.binding,
|
|
207
|
+
bucketName: ctx.output(entry, `r2Bindings entry "${entry.binding}"`),
|
|
194
208
|
}
|
|
195
|
-
return { binding: entry.binding, bucketName: value }
|
|
196
209
|
}
|
|
197
210
|
|
|
198
211
|
/** Strip line and block comments from JSONC, string-aware. */
|
|
@@ -333,8 +346,10 @@ export const cloudflareModule = defineModule({
|
|
|
333
346
|
/**
|
|
334
347
|
* Worker secrets to push after deploy. Each entry is either a plain name
|
|
335
348
|
* — a key in this environment's secrets.yaml, becoming a Worker secret
|
|
336
|
-
* binding of the same name (read at runtime as `env.<NAME>`) —
|
|
337
|
-
* `{ name,
|
|
349
|
+
* binding of the same name (read at runtime as `env.<NAME>`) — a
|
|
350
|
+
* `{ name, secret }` pair exposing a secrets.yaml key under a different
|
|
351
|
+
* name, or a `{ name, from, output }` reference into an imported
|
|
352
|
+
* instance's outputs.
|
|
338
353
|
* Pushed via `wrangler secret put` with the value piped through stdin.
|
|
339
354
|
*/
|
|
340
355
|
workerSecrets: z.array(workerValueSchema).default([]),
|
|
@@ -380,6 +395,26 @@ export const cloudflareModule = defineModule({
|
|
|
380
395
|
* `name` declared in wrangler.jsonc.
|
|
381
396
|
*/
|
|
382
397
|
workerName: z.string().optional(),
|
|
398
|
+
/**
|
|
399
|
+
* Hostname patterns this worker answers, e.g. `zbc.zabaca.com/*`, emitted
|
|
400
|
+
* as `--route`. The DNS record for the hostname is NOT created here: it
|
|
401
|
+
* belongs to a `cloudflare-zone` instance, and this instance should import
|
|
402
|
+
* that one so the record exists before the route is claimed.
|
|
403
|
+
*
|
|
404
|
+
* It lives in instance config rather than wrangler.jsonc, and that is the
|
|
405
|
+
* whole point. Preview PRs deploy the SAME wrangler.jsonc under a
|
|
406
|
+
* per-PR `workerName`, so a route declared in the file would be claimed by
|
|
407
|
+
* every preview deploy too — and a Cloudflare route is unique per zone, so
|
|
408
|
+
* the most recently deployed PR would take production's traffic, silently
|
|
409
|
+
* and with no error anywhere. A preview instance omits `routes` and keeps
|
|
410
|
+
* its `*.workers.dev` URL.
|
|
411
|
+
*
|
|
412
|
+
* Deliberately a route, not a wrangler "custom domain": a custom domain
|
|
413
|
+
* has wrangler create its own managed DNS record, which the zone module
|
|
414
|
+
* would then read as undeclared drift, and the two would argue on every
|
|
415
|
+
* apply.
|
|
416
|
+
*/
|
|
417
|
+
routes: z.array(z.string()).default([]),
|
|
383
418
|
}),
|
|
384
419
|
outputs: z.object({
|
|
385
420
|
deployUrl: z.string(),
|
|
@@ -396,10 +431,8 @@ export const cloudflareModule = defineModule({
|
|
|
396
431
|
// tokenValue) when `apiToken` is set, else secrets.yaml. Resolved before
|
|
397
432
|
// anything runs so a bad reference fails fast.
|
|
398
433
|
const apiToken = config.apiToken
|
|
399
|
-
?
|
|
400
|
-
|
|
401
|
-
: ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
402
|
-
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
434
|
+
? ctx.output(config.apiToken, 'apiToken')
|
|
435
|
+
: ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
403
436
|
|
|
404
437
|
const env: NodeJS.ProcessEnv = {
|
|
405
438
|
...process.env,
|
|
@@ -465,9 +498,10 @@ export const cloudflareModule = defineModule({
|
|
|
465
498
|
if (config.wranglerEnv) deployArgs.push('--env', config.wranglerEnv)
|
|
466
499
|
if (config.workerName) deployArgs.push('--name', config.workerName)
|
|
467
500
|
if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
|
|
501
|
+
for (const route of config.routes) deployArgs.push('--route', route)
|
|
468
502
|
for (const { name, value } of resolvedVars) deployArgs.push('--var', `${name}:${value}`)
|
|
469
503
|
console.log(
|
|
470
|
-
` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
|
|
504
|
+
` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${config.routes.length ? ` [routes: ${config.routes.join(', ')}]` : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
|
|
471
505
|
)
|
|
472
506
|
let out: string
|
|
473
507
|
try {
|
|
@@ -485,8 +519,13 @@ export const cloudflareModule = defineModule({
|
|
|
485
519
|
)
|
|
486
520
|
}
|
|
487
521
|
const workerName = deployedMatch[1]!
|
|
522
|
+
// A routed worker has no workers.dev URL to print: wrangler DISABLES the
|
|
523
|
+
// subdomain when routes are configured and `workers_dev` is not explicitly
|
|
524
|
+
// true, and prints the routes instead. Falling back to the first route
|
|
525
|
+
// keeps `deployUrl` meaning "where this worker answers" rather than going
|
|
526
|
+
// empty the moment an app gets a real hostname.
|
|
488
527
|
const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
|
|
489
|
-
const deployUrl = urlMatch?.[0] ??
|
|
528
|
+
const deployUrl = urlMatch?.[0] ?? routeUrl(config.routes)
|
|
490
529
|
console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
|
|
491
530
|
|
|
492
531
|
// 4. Push Worker secrets (after deploy: the script must exist first).
|
|
@@ -504,27 +543,14 @@ export const cloudflareModule = defineModule({
|
|
|
504
543
|
return { deployUrl, workerName }
|
|
505
544
|
},
|
|
506
545
|
async destroy(config, ctx) {
|
|
507
|
-
//
|
|
508
|
-
//
|
|
509
|
-
//
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
ctx,
|
|
516
|
-
'apiToken',
|
|
517
|
-
).value
|
|
518
|
-
} catch {
|
|
519
|
-
apiToken = undefined
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
apiToken ??= ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
523
|
-
if (!apiToken) {
|
|
524
|
-
throw new Error(
|
|
525
|
-
'Missing secret: CLOUDFLARE_API_TOKEN (the apiToken import is not available at destroy — keep a CLOUDFLARE_API_TOKEN in secrets.yaml for environments that destroy workers)',
|
|
526
|
-
)
|
|
527
|
-
}
|
|
546
|
+
// Resolved exactly the way `apply` resolves it. The engine applies the
|
|
547
|
+
// referenced instance on demand when a destroy asks for its output, so the
|
|
548
|
+
// twenty lines that used to live here — a swallowed catch around the
|
|
549
|
+
// reference and a silent fall back to secrets.yaml, because destroy was
|
|
550
|
+
// handed `imports: {}` — say nothing this line does not.
|
|
551
|
+
const apiToken = config.apiToken
|
|
552
|
+
? ctx.output(config.apiToken, 'apiToken')
|
|
553
|
+
: ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
528
554
|
const env: NodeJS.ProcessEnv = {
|
|
529
555
|
...process.env,
|
|
530
556
|
CLOUDFLARE_API_TOKEN: apiToken,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
|
-
import { cf
|
|
3
|
+
import { cf } from '../cloudflare-api'
|
|
4
4
|
|
|
5
5
|
// cloudflare-access — a Zero Trust application and the list of principals that
|
|
6
6
|
// may reach it, as repo state instead of dashboard state.
|
|
@@ -814,14 +814,14 @@ export const cloudflareAccessModule = defineModule({
|
|
|
814
814
|
changed: z.boolean(),
|
|
815
815
|
}),
|
|
816
816
|
async apply(config, ctx) {
|
|
817
|
-
const token =
|
|
817
|
+
const token = ctx.output(config.apiToken, 'apiToken')
|
|
818
818
|
const account = `/accounts/${config.accountId}`
|
|
819
819
|
const domain = normalizeDomain(config.domain)
|
|
820
820
|
|
|
821
821
|
// Resolved before anything is called, so a service token instance that is
|
|
822
822
|
// not imported fails while nothing has been touched.
|
|
823
823
|
const referencedTokenIds = config.serviceTokens.map((ref, index) =>
|
|
824
|
-
|
|
824
|
+
ctx.output(ref, `serviceTokens[${index}]`),
|
|
825
825
|
)
|
|
826
826
|
|
|
827
827
|
// 1. The organisation. Two fields off one endpoint, treated in OPPOSITE
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The parts of "talk to the Cloudflare API" that no module should own twice:
|
|
2
|
-
// the base URL, the envelope Cloudflare wraps every response in, and the
|
|
3
|
-
//
|
|
2
|
+
// the base URL, the envelope Cloudflare wraps every response in, and the two
|
|
3
|
+
// names its modules call to read a credential out of an imported instance's
|
|
4
|
+
// outputs (the rule itself is the engine's, in `../../src/context`).
|
|
4
5
|
//
|
|
5
6
|
// Extracted the way `provision-core` was extracted, and for the same reason its
|
|
6
7
|
// header gives. `cloudflare-zone` wrote these first; `cloudflare-tunnel` needed
|
|
@@ -9,8 +10,21 @@
|
|
|
9
10
|
// previous convention was a comment asking a human to notice, and by the time
|
|
10
11
|
// anybody counted the Cloudflare resolver was at four copies.
|
|
11
12
|
//
|
|
12
|
-
// The base URL is the load-bearing one. `
|
|
13
|
-
//
|
|
13
|
+
// The base URL below is the load-bearing one. Its `client/v4` is a version
|
|
14
|
+
// pin, not a protocol constant: the day it moves, it moves once — a promise
|
|
15
|
+
// that holds only while the string is written down in exactly one place, so it
|
|
16
|
+
// is deliberately absent from every comment in `modules/`, this one included.
|
|
17
|
+
//
|
|
18
|
+
// `cloudflare-email`, `cloudflare-token` and `r2` predated the extraction and
|
|
19
|
+
// carried private copies until 2026-09-02. Two of the copies knew things this
|
|
20
|
+
// file did not — that a body is not always JSON, and that a caller sometimes
|
|
21
|
+
// has to branch on the status — so they were folded in here (`CfError`, the
|
|
22
|
+
// non-JSON guard, `!res.ok`) rather than dropped on the way over. The only
|
|
23
|
+
// genuinely per-module part was naming which token scope was missing, and that
|
|
24
|
+
// is `CfOptions.hints`. `c9s/src/cf.ts` is a fifth copy and stays: it lives in
|
|
25
|
+
// a separate package and cannot import a template.
|
|
26
|
+
|
|
27
|
+
import { resolveOutput } from '../../src/context'
|
|
14
28
|
|
|
15
29
|
export const API = 'https://api.cloudflare.com/client/v4'
|
|
16
30
|
|
|
@@ -89,25 +103,129 @@ export function describeCfErrors(errors: unknown, status: number): string {
|
|
|
89
103
|
}
|
|
90
104
|
|
|
91
105
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
106
|
+
* A failed Cloudflare call, with the two facts a caller may need to branch on:
|
|
107
|
+
* the HTTP status, and every error code the envelope carried.
|
|
108
|
+
*
|
|
109
|
+
* `cloudflare-email` is why this is a class and not a bare `Error`: one of its
|
|
110
|
+
* routing endpoints answers 404 on a shape the module then retries as a POST,
|
|
111
|
+
* and `err.status === 404` is the only way to tell that apart from a real
|
|
112
|
+
* failure. Everything thrown from `cfRaw`/`cf` is a `CfError`, so `instanceof`
|
|
113
|
+
* is a safe narrowing at any call site — including the non-JSON case, where
|
|
114
|
+
* `codes` is empty because there was no envelope to read codes out of.
|
|
115
|
+
*/
|
|
116
|
+
export class CfError extends Error {
|
|
117
|
+
constructor(
|
|
118
|
+
readonly status: number,
|
|
119
|
+
readonly codes: number[],
|
|
120
|
+
message: string,
|
|
121
|
+
) {
|
|
122
|
+
super(message)
|
|
123
|
+
this.name = 'CfError'
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Did the envelope carry this error code? */
|
|
127
|
+
has(code: number): boolean {
|
|
128
|
+
return this.codes.includes(code)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Per-call options for `cf`/`cfRaw`. */
|
|
133
|
+
export interface CfOptions {
|
|
134
|
+
/**
|
|
135
|
+
* Per-code replacements for the thrown message — the module's scope hint.
|
|
136
|
+
*
|
|
137
|
+
* A 10000 "Authentication error" is the same fact for every module and a
|
|
138
|
+
* different instruction for each: `cloudflare-email` needs five token scopes
|
|
139
|
+
* named, `r2` needs one. That naming is the only genuinely per-module part of
|
|
140
|
+
* a Cloudflare failure, so it is the only hook here — the seam still throws
|
|
141
|
+
* `CfError` with the same status and codes, and only the text changes.
|
|
142
|
+
*
|
|
143
|
+
* When an envelope carries several hinted codes, the LOWEST code wins —
|
|
144
|
+
* deliberately, because the alternative is the order Cloudflare happened to
|
|
145
|
+
* list its errors in, and a module's operator-facing text must not depend on
|
|
146
|
+
* that. It also reproduces the copies this replaced, which tested their codes
|
|
147
|
+
* in a fixed order (`cloudflare-email` checked 10000 before 10105).
|
|
148
|
+
*/
|
|
149
|
+
hints?: Record<number, string>
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Every error code the envelope carried, as numbers.
|
|
154
|
+
*
|
|
155
|
+
* `code` is typed `number | string` because Cloudflare sends both spellings; a
|
|
156
|
+
* numeric string is the same code and is coerced, and anything else — a
|
|
157
|
+
* non-numeric string, a missing field, an entry that is not an object at all —
|
|
158
|
+
* is not a code and is dropped rather than surfaced as `NaN`.
|
|
159
|
+
*
|
|
160
|
+
* Pure; exported for tests.
|
|
161
|
+
*/
|
|
162
|
+
export function collectCfCodes(errors: unknown): number[] {
|
|
163
|
+
const entries = Array.isArray(errors) ? errors : []
|
|
164
|
+
const codes: number[] = []
|
|
165
|
+
for (const entry of entries) {
|
|
166
|
+
const raw = (entry as CfApiError | null | undefined)?.code
|
|
167
|
+
const code =
|
|
168
|
+
typeof raw === 'number'
|
|
169
|
+
? raw
|
|
170
|
+
: typeof raw === 'string' && raw.trim() !== ''
|
|
171
|
+
? Number(raw)
|
|
172
|
+
: Number.NaN
|
|
173
|
+
if (Number.isFinite(code)) codes.push(code)
|
|
174
|
+
}
|
|
175
|
+
return codes
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Call the API and return the WHOLE envelope; throw a `CfError` on failure.
|
|
180
|
+
* Callers that paginate need `result_info`, which is why this exists alongside
|
|
181
|
+
* `cf` rather than under it.
|
|
182
|
+
*
|
|
183
|
+
* Two things it refuses to assume, both learned from the private copies this
|
|
184
|
+
* replaced:
|
|
185
|
+
*
|
|
186
|
+
* - **The body is JSON.** A 5xx from Cloudflare's edge is an HTML page, and
|
|
187
|
+
* `res.json()` on it throws a parse error that names neither the call nor the
|
|
188
|
+
* status — the one moment a stack trace is least useful.
|
|
189
|
+
* - **`success` is the whole verdict.** It usually is, which is why the field
|
|
190
|
+
* exists; but a body that says `success: true` under a 4xx did not succeed,
|
|
191
|
+
* and returning its `result` hands the caller a shape it never checked.
|
|
95
192
|
*/
|
|
96
193
|
export async function cfRaw<T>(
|
|
97
194
|
token: string,
|
|
98
195
|
method: string,
|
|
99
196
|
path: string,
|
|
100
197
|
body?: unknown,
|
|
198
|
+
opts?: CfOptions,
|
|
101
199
|
): Promise<CfEnvelope<T>> {
|
|
102
200
|
const res = await fetch(`${API}${path}`, {
|
|
103
201
|
method,
|
|
104
202
|
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
105
203
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
106
204
|
})
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
205
|
+
let payload: CfEnvelope<T> | null
|
|
206
|
+
try {
|
|
207
|
+
payload = (await res.json()) as CfEnvelope<T> | null
|
|
208
|
+
} catch {
|
|
209
|
+
throw new CfError(
|
|
210
|
+
res.status,
|
|
211
|
+
[],
|
|
212
|
+
`Cloudflare API ${method} ${path}: HTTP ${res.status} (non-JSON body)`,
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
if (!res.ok || !payload?.success) {
|
|
216
|
+
const codes = collectCfCodes(payload?.errors)
|
|
217
|
+
// Scanned over the hints rather than over `codes`, so which one wins is the
|
|
218
|
+
// module's own ordering and not the API's — see `CfOptions.hints`.
|
|
219
|
+
const hinted = Object.keys(opts?.hints ?? {})
|
|
220
|
+
.map(Number)
|
|
221
|
+
.find((code) => codes.includes(code))
|
|
222
|
+
const hint = hinted === undefined ? undefined : opts?.hints?.[hinted]
|
|
223
|
+
throw new CfError(
|
|
224
|
+
res.status,
|
|
225
|
+
codes,
|
|
226
|
+
hint === undefined
|
|
227
|
+
? `Cloudflare API ${method} ${path} failed: ${describeCfErrors(payload?.errors, res.status)}`
|
|
228
|
+
: `Cloudflare API ${method} ${path} ${hint}`,
|
|
111
229
|
)
|
|
112
230
|
}
|
|
113
231
|
return payload
|
|
@@ -119,8 +237,9 @@ export async function cf<T>(
|
|
|
119
237
|
method: string,
|
|
120
238
|
path: string,
|
|
121
239
|
body?: unknown,
|
|
240
|
+
opts?: CfOptions,
|
|
122
241
|
): Promise<T> {
|
|
123
|
-
return (await cfRaw<T>(token, method, path, body)).result
|
|
242
|
+
return (await cfRaw<T>(token, method, path, body, opts)).result
|
|
124
243
|
}
|
|
125
244
|
|
|
126
245
|
/**
|
|
@@ -151,30 +270,23 @@ export function resolveApiToken(
|
|
|
151
270
|
* one that says `apiToken` for the third entry of `serviceTokens` sends the
|
|
152
271
|
* reader to the wrong line of an instance file.
|
|
153
272
|
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
273
|
+
* Both are now one line over `resolveOutput` — the rule and its three messages
|
|
274
|
+
* live in `../../src/context`, and a module inside an `apply`/`destroy` should
|
|
275
|
+
* say `ctx.output(ref, field)` instead, which every Cloudflare module in core
|
|
276
|
+
* now does. These stay because they take a raw imports record rather than a
|
|
277
|
+
* context, which is the only thing a caller outside an apply has, and because
|
|
278
|
+
* removing an exported name from a vendored library breaks whoever wrote their
|
|
279
|
+
* own Cloudflare module against it.
|
|
280
|
+
*
|
|
281
|
+
* Prefer `ctx.output` where you have a context: during a `destroy` it is the
|
|
282
|
+
* call that can still answer. `cloudflare-tunnel`'s teardown read `ctx.imports`
|
|
283
|
+
* through here and reported "which is not in this instance's imports" about an
|
|
284
|
+
* instance that WAS imported — the engine simply had not applied it.
|
|
158
285
|
*/
|
|
159
286
|
export function resolveRef(
|
|
160
287
|
ref: { from?: string; output?: string },
|
|
161
288
|
imports: Record<string, unknown>,
|
|
162
289
|
field: string,
|
|
163
290
|
): string {
|
|
164
|
-
|
|
165
|
-
throw new Error(`${field} must name both an instance (\`from\`) and an output (\`output\`)`)
|
|
166
|
-
}
|
|
167
|
-
const outputs = imports[ref.from]
|
|
168
|
-
if (outputs === undefined) {
|
|
169
|
-
throw new Error(
|
|
170
|
-
`${field} references instance "${ref.from}", which is not in this instance's imports`,
|
|
171
|
-
)
|
|
172
|
-
}
|
|
173
|
-
const value = (outputs as Record<string, unknown> | null)?.[ref.output]
|
|
174
|
-
if (typeof value !== 'string' || value === '') {
|
|
175
|
-
throw new Error(
|
|
176
|
-
`${field} references output "${ref.output}" on instance "${ref.from}", which doesn't emit it`,
|
|
177
|
-
)
|
|
178
|
-
}
|
|
179
|
-
return value
|
|
291
|
+
return resolveOutput(ref, imports, field)
|
|
180
292
|
}
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
],
|
|
9
9
|
"dependencies": {},
|
|
10
10
|
"secrets": [],
|
|
11
|
-
"instructions": "Not a module: it exports no defineModule. It is the library `cloudflare-access`, `cloudflare-tunnel`
|
|
11
|
+
"instructions": "Not a module: it exports no defineModule. It is the library every Cloudflare REST module imports as `../cloudflare-api` — `cloudflare-access`, `cloudflare-email`, `cloudflare-tunnel`, `cloudflare-token`, `cloudflare-zone` and `r2`. It exists because the same envelope-unwrapping had reached four copies in the contributing repo before anybody counted — `success`, `errors`, `result` is not hard, and that is exactly why it gets rewritten slightly differently every time. In COPY mode add it alongside whichever Cloudflare module you copied."
|
|
12
12
|
}
|