@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
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
|
+
import type { ApplyContext } from '../../src/types'
|
|
4
|
+
import { CfError, cf, type CfOptions } from '../cloudflare-api'
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
7
|
* cloudflare-email — provisions Cloudflare Email Service (public beta) for a
|
|
@@ -9,7 +11,7 @@ import { defineModule } from '../../src/define-module'
|
|
|
9
11
|
* Unlike the `cloudflare` module (which shells out to wrangler), this module
|
|
10
12
|
* calls the Cloudflare REST API directly — wrangler has no surface for Email
|
|
11
13
|
* Routing / Email Sending onboarding. Same turso-style shape: token from
|
|
12
|
-
* ctx.
|
|
14
|
+
* ctx.secret, idempotent list→create everywhere, console.log progress.
|
|
13
15
|
*
|
|
14
16
|
* Operational caveats (beta):
|
|
15
17
|
* - Email Sending requires a Workers Paid plan (403/10105 = not entitled).
|
|
@@ -26,76 +28,25 @@ import { defineModule } from '../../src/define-module'
|
|
|
26
28
|
* merge them manually — two SPF records break SPF evaluation entirely.
|
|
27
29
|
*/
|
|
28
30
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
async function cfFetch<T>(
|
|
51
|
-
token: string,
|
|
52
|
-
path: string,
|
|
53
|
-
init?: { method?: string; body?: unknown },
|
|
54
|
-
): Promise<T> {
|
|
55
|
-
const res = await fetch(`${API}${path}`, {
|
|
56
|
-
method: init?.method ?? 'GET',
|
|
57
|
-
headers: {
|
|
58
|
-
Authorization: `Bearer ${token}`,
|
|
59
|
-
'Content-Type': 'application/json',
|
|
60
|
-
},
|
|
61
|
-
body: init?.body === undefined ? undefined : JSON.stringify(init.body),
|
|
62
|
-
})
|
|
63
|
-
let envelope: CfEnvelope<T>
|
|
64
|
-
try {
|
|
65
|
-
envelope = (await res.json()) as CfEnvelope<T>
|
|
66
|
-
} catch {
|
|
67
|
-
throw new CfError(res.status, [], `Cloudflare API ${path}: HTTP ${res.status} (non-JSON body)`)
|
|
68
|
-
}
|
|
69
|
-
if (!res.ok || !envelope.success) {
|
|
70
|
-
const codes = (envelope.errors ?? []).map((e) => e.code)
|
|
71
|
-
const detail = (envelope.errors ?? []).map((e) => `${e.code}: ${e.message}`).join('; ')
|
|
72
|
-
if (codes.includes(10000)) {
|
|
73
|
-
throw new CfError(
|
|
74
|
-
res.status,
|
|
75
|
-
codes,
|
|
76
|
-
`Cloudflare API ${path} rejected the token (10000 Authentication error). ` +
|
|
77
|
-
`CLOUDFLARE_API_TOKEN is likely missing a scope — it needs: ` +
|
|
78
|
-
`Zone → Email Routing Rules: Edit, Zone → Zone Settings: Edit (the routing ` +
|
|
79
|
-
`enable/settings/DNS endpoints live under generic Zone Settings), Zone → DNS: Edit, ` +
|
|
80
|
-
`Account → Email Sending: Edit, Account → Email Routing Addresses: Edit. Edit the token at ` +
|
|
81
|
-
`https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
82
|
-
)
|
|
83
|
-
}
|
|
84
|
-
if (codes.includes(10105)) {
|
|
85
|
-
throw new CfError(
|
|
86
|
-
res.status,
|
|
87
|
-
codes,
|
|
88
|
-
`Cloudflare API ${path}: account not entitled to Email Sending (10105). ` +
|
|
89
|
-
`Email Sending requires a Workers Paid plan — upgrade the account, then re-run zbc apply.`,
|
|
90
|
-
)
|
|
91
|
-
}
|
|
92
|
-
throw new CfError(
|
|
93
|
-
res.status,
|
|
94
|
-
codes,
|
|
95
|
-
`Cloudflare API ${path} failed (HTTP ${res.status}): ${detail}`,
|
|
96
|
-
)
|
|
97
|
-
}
|
|
98
|
-
return envelope.result
|
|
31
|
+
/**
|
|
32
|
+
* Named per-code guidance for this module's calls — the one genuinely
|
|
33
|
+
* per-module part of a Cloudflare failure, and the reason `CfOptions.hints`
|
|
34
|
+
* exists. Everything else about the envelope (the base URL, the error shapes,
|
|
35
|
+
* the non-JSON guard, the typed throw) is `../cloudflare-api`'s.
|
|
36
|
+
*/
|
|
37
|
+
const OPTS: CfOptions = {
|
|
38
|
+
hints: {
|
|
39
|
+
10000:
|
|
40
|
+
`rejected the token (10000 Authentication error). ` +
|
|
41
|
+
`CLOUDFLARE_API_TOKEN is likely missing a scope — it needs: ` +
|
|
42
|
+
`Zone → Email Routing Rules: Edit, Zone → Zone Settings: Edit (the routing ` +
|
|
43
|
+
`enable/settings/DNS endpoints live under generic Zone Settings), Zone → DNS: Edit, ` +
|
|
44
|
+
`Account → Email Sending: Edit, Account → Email Routing Addresses: Edit. Edit the token at ` +
|
|
45
|
+
`https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
46
|
+
10105:
|
|
47
|
+
`failed: the account is not entitled to Email Sending (10105). ` +
|
|
48
|
+
`Email Sending requires a Workers Paid plan — upgrade the account, then re-run zbc apply.`,
|
|
49
|
+
},
|
|
99
50
|
}
|
|
100
51
|
|
|
101
52
|
/**
|
|
@@ -118,25 +69,9 @@ const workerRefSchema = z.union([
|
|
|
118
69
|
type WorkerRef = z.infer<typeof workerRefSchema>
|
|
119
70
|
|
|
120
71
|
/** Resolve a worker-name entry to its literal string. */
|
|
121
|
-
function resolveWorkerName(
|
|
122
|
-
ref: WorkerRef,
|
|
123
|
-
imports: Record<string, unknown>,
|
|
124
|
-
fieldName: string,
|
|
125
|
-
): string {
|
|
72
|
+
function resolveWorkerName(ref: WorkerRef, ctx: ApplyContext, fieldName: string): string {
|
|
126
73
|
if (typeof ref === 'string') return ref
|
|
127
|
-
|
|
128
|
-
if (instanceOutputs === undefined) {
|
|
129
|
-
throw new Error(
|
|
130
|
-
`${fieldName} references instance "${ref.from}", which is not in this instance's imports`,
|
|
131
|
-
)
|
|
132
|
-
}
|
|
133
|
-
const value = (instanceOutputs as Record<string, unknown> | null)?.[ref.output]
|
|
134
|
-
if (typeof value !== 'string') {
|
|
135
|
-
throw new Error(
|
|
136
|
-
`${fieldName} references output "${ref.output}" on instance "${ref.from}", which doesn't emit it`,
|
|
137
|
-
)
|
|
138
|
-
}
|
|
139
|
-
return value
|
|
74
|
+
return ctx.output(ref, fieldName)
|
|
140
75
|
}
|
|
141
76
|
|
|
142
77
|
/** A routing rule action target. */
|
|
@@ -176,7 +111,7 @@ const RULE_PREFIX = 'zbc:'
|
|
|
176
111
|
|
|
177
112
|
function ruleAction(
|
|
178
113
|
entry: { action: string; destination?: string; workerName?: WorkerRef },
|
|
179
|
-
|
|
114
|
+
ctx: ApplyContext,
|
|
180
115
|
fieldName: string,
|
|
181
116
|
): { type: string; value?: string[] } {
|
|
182
117
|
if (entry.action === 'forward') {
|
|
@@ -185,7 +120,7 @@ function ruleAction(
|
|
|
185
120
|
}
|
|
186
121
|
if (entry.action === 'worker') {
|
|
187
122
|
if (!entry.workerName) throw new Error(`${fieldName}: action "worker" requires a workerName`)
|
|
188
|
-
return { type: 'worker', value: [resolveWorkerName(entry.workerName,
|
|
123
|
+
return { type: 'worker', value: [resolveWorkerName(entry.workerName, ctx, fieldName)] }
|
|
189
124
|
}
|
|
190
125
|
return { type: 'drop' }
|
|
191
126
|
}
|
|
@@ -201,17 +136,17 @@ async function ensureDestinationVerified(
|
|
|
201
136
|
accountId: string,
|
|
202
137
|
email: string,
|
|
203
138
|
): Promise<void> {
|
|
204
|
-
const addresses = await
|
|
139
|
+
const addresses = await cf<Array<{ email: string; verified?: string | null }>>(
|
|
205
140
|
token,
|
|
141
|
+
'GET',
|
|
206
142
|
`/accounts/${accountId}/email/routing/addresses?per_page=50`,
|
|
143
|
+
undefined,
|
|
144
|
+
OPTS,
|
|
207
145
|
)
|
|
208
146
|
const existing = addresses.find((a) => a.email.toLowerCase() === email.toLowerCase())
|
|
209
147
|
if (existing?.verified) return
|
|
210
148
|
if (!existing) {
|
|
211
|
-
await
|
|
212
|
-
method: 'POST',
|
|
213
|
-
body: { email },
|
|
214
|
-
})
|
|
149
|
+
await cf(token, 'POST', `/accounts/${accountId}/email/routing/addresses`, { email }, OPTS)
|
|
215
150
|
console.log(` Created destination address ${email} — verification email sent`)
|
|
216
151
|
}
|
|
217
152
|
throw new Error(
|
|
@@ -305,8 +240,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
305
240
|
domain: z.string(),
|
|
306
241
|
}),
|
|
307
242
|
async apply(config, ctx) {
|
|
308
|
-
const token = ctx.
|
|
309
|
-
if (!token) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
243
|
+
const token = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
310
244
|
|
|
311
245
|
const { accountId, zoneId, domain } = config
|
|
312
246
|
const dnsStatus: Record<string, string> = {}
|
|
@@ -315,18 +249,24 @@ export const cloudflareEmailModule = defineModule({
|
|
|
315
249
|
|
|
316
250
|
// ── 1. Outbound sending: onboard the (sub)domain, surface DNS status ────
|
|
317
251
|
if (config.enableSending) {
|
|
318
|
-
const subdomains = await
|
|
252
|
+
const subdomains = await cf<SendingSubdomain[]>(
|
|
319
253
|
token,
|
|
254
|
+
'GET',
|
|
320
255
|
`/zones/${zoneId}/email/sending/subdomains`,
|
|
256
|
+
undefined,
|
|
257
|
+
OPTS,
|
|
321
258
|
)
|
|
322
259
|
let sub = subdomains.find((s) => s.name === domain)
|
|
323
260
|
if (sub) {
|
|
324
261
|
console.log(` Sending: ${domain} already onboarded`)
|
|
325
262
|
} else {
|
|
326
|
-
sub = await
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
263
|
+
sub = await cf<SendingSubdomain>(
|
|
264
|
+
token,
|
|
265
|
+
'POST',
|
|
266
|
+
`/zones/${zoneId}/email/sending/subdomains`,
|
|
267
|
+
{ name: domain },
|
|
268
|
+
OPTS,
|
|
269
|
+
)
|
|
330
270
|
console.log(` Sending: onboarded ${domain} (SPF/DKIM/DMARC/bounce-MX auto-provisioned)`)
|
|
331
271
|
}
|
|
332
272
|
sendingEnabled = true
|
|
@@ -334,9 +274,12 @@ export const cloudflareEmailModule = defineModule({
|
|
|
334
274
|
// DNS record verification status. Field names are beta-era; read
|
|
335
275
|
// defensively and record whatever type/name/status the API returns.
|
|
336
276
|
try {
|
|
337
|
-
const dns = await
|
|
277
|
+
const dns = await cf<unknown>(
|
|
338
278
|
token,
|
|
279
|
+
'GET',
|
|
339
280
|
`/zones/${zoneId}/email/sending/subdomains/${sub.tag}/dns`,
|
|
281
|
+
undefined,
|
|
282
|
+
OPTS,
|
|
340
283
|
)
|
|
341
284
|
const records: Array<Record<string, unknown>> = Array.isArray(dns)
|
|
342
285
|
? (dns as Array<Record<string, unknown>>)
|
|
@@ -362,14 +305,17 @@ export const cloudflareEmailModule = defineModule({
|
|
|
362
305
|
|
|
363
306
|
// ── 2. Inbound routing: enable, subdomain DNS, rules, catch-all ─────────
|
|
364
307
|
if (config.enableRouting) {
|
|
365
|
-
const settings = await
|
|
308
|
+
const settings = await cf<{ enabled?: boolean; status?: string }>(
|
|
366
309
|
token,
|
|
310
|
+
'GET',
|
|
367
311
|
`/zones/${zoneId}/email/routing`,
|
|
312
|
+
undefined,
|
|
313
|
+
OPTS,
|
|
368
314
|
)
|
|
369
315
|
if (settings.enabled || settings.status === 'ready') {
|
|
370
316
|
console.log(` Routing: already enabled on zone`)
|
|
371
317
|
} else {
|
|
372
|
-
await
|
|
318
|
+
await cf(token, 'POST', `/zones/${zoneId}/email/routing/enable`, undefined, OPTS)
|
|
373
319
|
console.log(` Routing: enabled on zone (MX/SPF records locked in)`)
|
|
374
320
|
}
|
|
375
321
|
routingEnabled = true
|
|
@@ -377,19 +323,19 @@ export const cloudflareEmailModule = defineModule({
|
|
|
377
323
|
// Subdomain routing: provision routing DNS for the subdomain itself
|
|
378
324
|
// (POST /email/routing/dns with the subdomain name). Idempotent: check
|
|
379
325
|
// first via the subdomain query param.
|
|
380
|
-
const zone = await
|
|
326
|
+
const zone = await cf<{ name: string }>(token, 'GET', `/zones/${zoneId}`, undefined, OPTS)
|
|
381
327
|
if (domain !== zone.name) {
|
|
382
328
|
try {
|
|
383
|
-
const dns = await
|
|
329
|
+
const dns = await cf<Array<Record<string, unknown>>>(
|
|
384
330
|
token,
|
|
331
|
+
'GET',
|
|
385
332
|
`/zones/${zoneId}/email/routing/dns?subdomain=${encodeURIComponent(domain)}`,
|
|
333
|
+
undefined,
|
|
334
|
+
OPTS,
|
|
386
335
|
)
|
|
387
336
|
const hasMx = Array.isArray(dns) && dns.some((r) => r.type === 'MX')
|
|
388
337
|
if (!hasMx) {
|
|
389
|
-
await
|
|
390
|
-
method: 'POST',
|
|
391
|
-
body: { name: domain },
|
|
392
|
-
})
|
|
338
|
+
await cf(token, 'POST', `/zones/${zoneId}/email/routing/dns`, { name: domain }, OPTS)
|
|
393
339
|
console.log(` Routing: provisioned DNS for subdomain ${domain}`)
|
|
394
340
|
} else {
|
|
395
341
|
console.log(` Routing: subdomain ${domain} DNS already provisioned`)
|
|
@@ -397,10 +343,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
397
343
|
} catch (err) {
|
|
398
344
|
// Some API versions only expose subdomain enrollment via POST; try it.
|
|
399
345
|
if (err instanceof CfError && err.status === 404) {
|
|
400
|
-
await
|
|
401
|
-
method: 'POST',
|
|
402
|
-
body: { name: domain },
|
|
403
|
-
})
|
|
346
|
+
await cf(token, 'POST', `/zones/${zoneId}/email/routing/dns`, { name: domain }, OPTS)
|
|
404
347
|
console.log(` Routing: provisioned DNS for subdomain ${domain}`)
|
|
405
348
|
} else {
|
|
406
349
|
throw err
|
|
@@ -410,9 +353,12 @@ export const cloudflareEmailModule = defineModule({
|
|
|
410
353
|
|
|
411
354
|
// Routing DNS status for the domain
|
|
412
355
|
try {
|
|
413
|
-
const routingDns = await
|
|
356
|
+
const routingDns = await cf<Array<Record<string, unknown>>>(
|
|
414
357
|
token,
|
|
358
|
+
'GET',
|
|
415
359
|
`/zones/${zoneId}/email/routing/dns${domain !== zone.name ? `?subdomain=${encodeURIComponent(domain)}` : ''}`,
|
|
360
|
+
undefined,
|
|
361
|
+
OPTS,
|
|
416
362
|
)
|
|
417
363
|
for (const r of routingDns ?? []) {
|
|
418
364
|
dnsStatus[`${String(r.type ?? 'record')} ${String(r.name ?? domain)}`] = String(
|
|
@@ -436,9 +382,12 @@ export const cloudflareEmailModule = defineModule({
|
|
|
436
382
|
}
|
|
437
383
|
|
|
438
384
|
// Upsert literal rules for each address.
|
|
439
|
-
const existingRules = await
|
|
385
|
+
const existingRules = await cf<RoutingRule[]>(
|
|
440
386
|
token,
|
|
387
|
+
'GET',
|
|
441
388
|
`/zones/${zoneId}/email/routing/rules?per_page=50`,
|
|
389
|
+
undefined,
|
|
390
|
+
OPTS,
|
|
442
391
|
)
|
|
443
392
|
for (const entry of config.addresses) {
|
|
444
393
|
const email = `${entry.localPart}@${domain}`
|
|
@@ -447,7 +396,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
447
396
|
name: ruleName,
|
|
448
397
|
enabled: true,
|
|
449
398
|
matchers: [{ type: 'literal', field: 'to', value: email }],
|
|
450
|
-
actions: [ruleAction(entry, ctx
|
|
399
|
+
actions: [ruleAction(entry, ctx, `addresses[${entry.localPart}]`)],
|
|
451
400
|
}
|
|
452
401
|
const existing = existingRules.find(
|
|
453
402
|
(r) =>
|
|
@@ -455,28 +404,28 @@ export const cloudflareEmailModule = defineModule({
|
|
|
455
404
|
r.matchers.some((m) => m.type === 'literal' && m.value === email),
|
|
456
405
|
)
|
|
457
406
|
if (existing) {
|
|
458
|
-
await
|
|
459
|
-
method: 'PUT',
|
|
460
|
-
body,
|
|
461
|
-
})
|
|
407
|
+
await cf(token, 'PUT', `/zones/${zoneId}/email/routing/rules/${existing.id}`, body, OPTS)
|
|
462
408
|
console.log(` Routing: updated rule for ${email} → ${entry.action}`)
|
|
463
409
|
} else {
|
|
464
|
-
await
|
|
410
|
+
await cf(token, 'POST', `/zones/${zoneId}/email/routing/rules`, body, OPTS)
|
|
465
411
|
console.log(` Routing: created rule for ${email} → ${entry.action}`)
|
|
466
412
|
}
|
|
467
413
|
}
|
|
468
414
|
|
|
469
415
|
// Catch-all.
|
|
470
416
|
if (config.catchAll) {
|
|
471
|
-
await
|
|
472
|
-
|
|
473
|
-
|
|
417
|
+
await cf(
|
|
418
|
+
token,
|
|
419
|
+
'PUT',
|
|
420
|
+
`/zones/${zoneId}/email/routing/rules/catch_all`,
|
|
421
|
+
{
|
|
474
422
|
name: `${RULE_PREFIX}catch-all`,
|
|
475
423
|
enabled: true,
|
|
476
424
|
matchers: [{ type: 'all' }],
|
|
477
|
-
actions: [ruleAction(config.catchAll, ctx
|
|
425
|
+
actions: [ruleAction(config.catchAll, ctx, 'catchAll')],
|
|
478
426
|
},
|
|
479
|
-
|
|
427
|
+
OPTS,
|
|
428
|
+
)
|
|
480
429
|
console.log(` Routing: catch-all → ${config.catchAll.action}`)
|
|
481
430
|
}
|
|
482
431
|
}
|
|
@@ -501,23 +450,23 @@ export const cloudflareEmailModule = defineModule({
|
|
|
501
450
|
}
|
|
502
451
|
},
|
|
503
452
|
async destroy(config, ctx) {
|
|
504
|
-
const token = ctx.
|
|
505
|
-
if (!token) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
453
|
+
const token = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
506
454
|
const { zoneId, domain } = config
|
|
507
455
|
|
|
508
456
|
console.log(` ⚠ DESTROYING email config for ${domain} — mail for this domain WILL STOP.`)
|
|
509
457
|
|
|
510
458
|
// Remove managed rules (only ones this module named).
|
|
511
459
|
try {
|
|
512
|
-
const rules = await
|
|
460
|
+
const rules = await cf<RoutingRule[]>(
|
|
513
461
|
token,
|
|
462
|
+
'GET',
|
|
514
463
|
`/zones/${zoneId}/email/routing/rules?per_page=50`,
|
|
464
|
+
undefined,
|
|
465
|
+
OPTS,
|
|
515
466
|
)
|
|
516
467
|
for (const r of rules) {
|
|
517
468
|
if (r.name?.startsWith(RULE_PREFIX)) {
|
|
518
|
-
await
|
|
519
|
-
method: 'DELETE',
|
|
520
|
-
})
|
|
469
|
+
await cf(token, 'DELETE', `/zones/${zoneId}/email/routing/rules/${r.id}`, undefined, OPTS)
|
|
521
470
|
console.log(` Deleted rule ${r.name}`)
|
|
522
471
|
}
|
|
523
472
|
}
|
|
@@ -528,15 +477,18 @@ export const cloudflareEmailModule = defineModule({
|
|
|
528
477
|
// Reset catch-all to drop (catch_all can't be deleted, only redefined).
|
|
529
478
|
if (config.catchAll) {
|
|
530
479
|
try {
|
|
531
|
-
await
|
|
532
|
-
|
|
533
|
-
|
|
480
|
+
await cf(
|
|
481
|
+
token,
|
|
482
|
+
'PUT',
|
|
483
|
+
`/zones/${zoneId}/email/routing/rules/catch_all`,
|
|
484
|
+
{
|
|
534
485
|
name: `${RULE_PREFIX}catch-all`,
|
|
535
486
|
enabled: false,
|
|
536
487
|
matchers: [{ type: 'all' }],
|
|
537
488
|
actions: [{ type: 'drop' }],
|
|
538
489
|
},
|
|
539
|
-
|
|
490
|
+
OPTS,
|
|
491
|
+
)
|
|
540
492
|
console.log(` Catch-all disabled`)
|
|
541
493
|
} catch (err) {
|
|
542
494
|
console.log(` Catch-all reset skipped: ${(err as Error).message}`)
|
|
@@ -545,7 +497,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
545
497
|
|
|
546
498
|
if (config.enableRouting) {
|
|
547
499
|
try {
|
|
548
|
-
await
|
|
500
|
+
await cf(token, 'POST', `/zones/${zoneId}/email/routing/disable`, undefined, OPTS)
|
|
549
501
|
console.log(` Routing disabled on zone`)
|
|
550
502
|
} catch (err) {
|
|
551
503
|
console.log(` Routing disable skipped: ${(err as Error).message}`)
|
|
@@ -554,15 +506,22 @@ export const cloudflareEmailModule = defineModule({
|
|
|
554
506
|
|
|
555
507
|
if (config.enableSending) {
|
|
556
508
|
try {
|
|
557
|
-
const subdomains = await
|
|
509
|
+
const subdomains = await cf<SendingSubdomain[]>(
|
|
558
510
|
token,
|
|
511
|
+
'GET',
|
|
559
512
|
`/zones/${zoneId}/email/sending/subdomains`,
|
|
513
|
+
undefined,
|
|
514
|
+
OPTS,
|
|
560
515
|
)
|
|
561
516
|
const sub = subdomains.find((s) => s.name === domain)
|
|
562
517
|
if (sub) {
|
|
563
|
-
await
|
|
564
|
-
|
|
565
|
-
|
|
518
|
+
await cf(
|
|
519
|
+
token,
|
|
520
|
+
'DELETE',
|
|
521
|
+
`/zones/${zoneId}/email/sending/subdomains/${sub.tag}`,
|
|
522
|
+
undefined,
|
|
523
|
+
OPTS,
|
|
524
|
+
)
|
|
566
525
|
console.log(` Sending subdomain ${domain} deleted`)
|
|
567
526
|
}
|
|
568
527
|
} catch (err) {
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
9
9
|
"signupUrl": "https://dash.cloudflare.com",
|
|
10
10
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
11
|
-
"instructions": "Reuses CLOUDFLARE_API_TOKEN from secrets.yaml, but the token needs extra scopes: Zone > Email Routing Rules: Edit, Zone > Zone Settings: Edit (the routing enable/settings/DNS endpoints require it), Zone > DNS: Edit, Account > Email Sending: Edit, and Account > Email Routing Addresses: Edit. Email Sending requires a Workers Paid plan (API error 10105 = not entitled). Caveats: the service is in public beta with unpublished rate limits (pilot before high-volume use); outbound messages are capped at 5 MiB total; onboarding adds an SPF record, so if the domain already has one you must merge them manually (two SPF records break SPF); 'forward' destinations require a manual email-click verification — apply sends the verification email, then fails with instructions until you click it and re-run."
|
|
11
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Reuses CLOUDFLARE_API_TOKEN from secrets.yaml, but the token needs extra scopes: Zone > Email Routing Rules: Edit, Zone > Zone Settings: Edit (the routing enable/settings/DNS endpoints require it), Zone > DNS: Edit, Account > Email Sending: Edit, and Account > Email Routing Addresses: Edit. Email Sending requires a Workers Paid plan (API error 10105 = not entitled). Caveats: the service is in public beta with unpublished rate limits (pilot before high-volume use); outbound messages are capped at 5 MiB total; onboarding adds an SPF record, so if the domain already has one you must merge them manually (two SPF records break SPF); 'forward' destinations require a manual email-click verification — apply sends the verification email, then fails with instructions until you click it and re-run. In COPY mode run `zbc add cloudflare-api` too."
|
|
12
12
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
2
|
import { z } from 'zod'
|
|
3
3
|
import { defineModule } from '../../src/define-module'
|
|
4
|
+
import { cf } from '../cloudflare-api'
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* cloudflare-token — mints scoped Cloudflare API tokens from ONE root
|
|
@@ -29,34 +30,15 @@ import { defineModule } from '../../src/define-module'
|
|
|
29
30
|
* policy — restricted to `zones` when given (names resolved via GET /zones),
|
|
30
31
|
* else all zones of the account. Account-scoped groups land on an account
|
|
31
32
|
* policy. Unknown names/zones are hard errors before anything mutates.
|
|
33
|
+
*
|
|
34
|
+
* The REST envelope is `../cloudflare-api`'s, not this module's. The private
|
|
35
|
+
* copy that lived here typed `errors` as `{message: string}` — the exact claim
|
|
36
|
+
* the seam's header documents as false, and the reason a `{code, error}`
|
|
37
|
+
* failure used to arrive as a bare `HTTP 403`. Note this module's token comes
|
|
38
|
+
* from secrets.yaml rather than an import, so `resolveApiToken` does not apply
|
|
39
|
+
* to it; only `cf` does.
|
|
32
40
|
*/
|
|
33
41
|
|
|
34
|
-
const API = 'https://api.cloudflare.com/client/v4'
|
|
35
|
-
|
|
36
|
-
interface CfEnvelope<T> {
|
|
37
|
-
success: boolean
|
|
38
|
-
errors: Array<{ message: string }>
|
|
39
|
-
result: T
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** Call the CF API; unwrap the envelope; throw the API's message on failure. */
|
|
43
|
-
async function cf<T>(rootToken: string, method: string, path: string, body?: unknown): Promise<T> {
|
|
44
|
-
const res = await fetch(`${API}${path}`, {
|
|
45
|
-
method,
|
|
46
|
-
headers: {
|
|
47
|
-
Authorization: `Bearer ${rootToken}`,
|
|
48
|
-
'Content-Type': 'application/json',
|
|
49
|
-
},
|
|
50
|
-
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
51
|
-
})
|
|
52
|
-
const payload = (await res.json()) as CfEnvelope<T>
|
|
53
|
-
if (!payload.success) {
|
|
54
|
-
const messages = payload.errors?.map((e) => e.message).join('; ') || `HTTP ${res.status}`
|
|
55
|
-
throw new Error(`Cloudflare API ${method} ${path} failed: ${messages}`)
|
|
56
|
-
}
|
|
57
|
-
return payload.result
|
|
58
|
-
}
|
|
59
|
-
|
|
60
42
|
export interface PermissionGroup {
|
|
61
43
|
id: string
|
|
62
44
|
name: string
|
|
@@ -169,8 +151,7 @@ export const cloudflareTokenModule = defineModule({
|
|
|
169
151
|
s3SecretAccessKey: z.string(),
|
|
170
152
|
}),
|
|
171
153
|
async apply(config, ctx) {
|
|
172
|
-
const rootToken = ctx.
|
|
173
|
-
if (!rootToken) throw new Error('Missing secret: CLOUDFLARE_ROOT_TOKEN')
|
|
154
|
+
const rootToken = ctx.secret('CLOUDFLARE_ROOT_TOKEN')
|
|
174
155
|
|
|
175
156
|
// 1. Resolve permission names → group ids. Fail fast before any mutation.
|
|
176
157
|
const available = await cf<PermissionGroup[]>(
|
|
@@ -251,8 +232,7 @@ export const cloudflareTokenModule = defineModule({
|
|
|
251
232
|
return { tokenId, tokenValue, ...deriveS3Credentials(tokenId, tokenValue) }
|
|
252
233
|
},
|
|
253
234
|
async destroy(config, ctx) {
|
|
254
|
-
const rootToken = ctx.
|
|
255
|
-
if (!rootToken) throw new Error('Missing secret: CLOUDFLARE_ROOT_TOKEN')
|
|
235
|
+
const rootToken = ctx.secret('CLOUDFLARE_ROOT_TOKEN')
|
|
256
236
|
const existing = await findTokenByName(rootToken, config.accountId, config.tokenName)
|
|
257
237
|
if (!existing) {
|
|
258
238
|
console.log(` Token "${config.tokenName}" already absent`)
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
"secrets": ["CLOUDFLARE_ROOT_TOKEN"],
|
|
9
9
|
"signupUrl": "https://dash.cloudflare.com/sign-up",
|
|
10
10
|
"tokenUrl": "https://dash.cloudflare.com/?to=/:account/api-tokens",
|
|
11
|
-
"instructions": "Create ONE account-owned root token in the dashboard (Manage Account → API Tokens) with 'Account API Tokens Write' — plus 'Zone Read' if instances use `zones` — and put it in secrets.yaml as CLOUDFLARE_ROOT_TOKEN. Instances mint per-purpose tokens by permission-group NAME (as listed by GET /accounts/{id}/tokens/permission_groups). The minted value is ROLLED on every apply and exists only in memory: consume it downstream via imports (`{ name, from, output: 'tokenValue' }`), never store it, and never hand it to a human for local use (mint them a separate named token instead). Tokens with R2 permissions also emit s3AccessKeyId/s3SecretAccessKey (access key = token id, secret = sha256 of the value)."
|
|
11
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Create ONE account-owned root token in the dashboard (Manage Account → API Tokens) with 'Account API Tokens Write' — plus 'Zone Read' if instances use `zones` — and put it in secrets.yaml as CLOUDFLARE_ROOT_TOKEN. Instances mint per-purpose tokens by permission-group NAME (as listed by GET /accounts/{id}/tokens/permission_groups). The minted value is ROLLED on every apply and exists only in memory: consume it downstream via imports (`{ name, from, output: 'tokenValue' }`), never store it, and never hand it to a human for local use (mint them a separate named token instead). Tokens with R2 permissions also emit s3AccessKeyId/s3SecretAccessKey (access key = token id, secret = sha256 of the value). In COPY mode run `zbc add cloudflare-api` too."
|
|
12
12
|
}
|
|
@@ -2,7 +2,7 @@ import * as fs from 'node:fs'
|
|
|
2
2
|
import * as path from 'node:path'
|
|
3
3
|
import { z } from 'zod'
|
|
4
4
|
import { defineModule } from '../../src/define-module'
|
|
5
|
-
import { cf
|
|
5
|
+
import { cf } from '../cloudflare-api'
|
|
6
6
|
|
|
7
7
|
// cloudflare-tunnel — a remotely-managed Cloudflare Tunnel as repo state: the
|
|
8
8
|
// tunnel itself, its ingress rules, the DNS records that point at it, and the
|
|
@@ -258,7 +258,7 @@ export const cloudflareTunnelModule = defineModule({
|
|
|
258
258
|
changed: z.boolean(),
|
|
259
259
|
}),
|
|
260
260
|
async apply(config, ctx) {
|
|
261
|
-
const token =
|
|
261
|
+
const token = ctx.output(config.apiToken, 'apiToken')
|
|
262
262
|
assertHostnamesInZone(config.ingress, config.zone)
|
|
263
263
|
|
|
264
264
|
// 1. Converge the tunnel by name. `is_deleted=false` matters: Cloudflare
|
|
@@ -418,7 +418,7 @@ export const cloudflareTunnelModule = defineModule({
|
|
|
418
418
|
}
|
|
419
419
|
},
|
|
420
420
|
async destroy(config, ctx) {
|
|
421
|
-
const token =
|
|
421
|
+
const token = ctx.output(config.apiToken, 'apiToken')
|
|
422
422
|
const found = await cf<CfTunnel[]>(
|
|
423
423
|
token,
|
|
424
424
|
'GET',
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
|
-
import { cf, cfRaw
|
|
3
|
+
import { cf, cfRaw } from '../cloudflare-api'
|
|
4
4
|
|
|
5
5
|
// cloudflare-zone — a DNS zone's records as repo state instead of dashboard
|
|
6
6
|
// state. CLAUDE.md names Cloudflare DNS as off-box state we own; `cloudflare-token`
|
|
@@ -468,7 +468,7 @@ export const cloudflareZoneModule = defineModule({
|
|
|
468
468
|
changed: z.boolean(),
|
|
469
469
|
}),
|
|
470
470
|
async apply(config, ctx) {
|
|
471
|
-
const token =
|
|
471
|
+
const token = ctx.output(config.apiToken, 'apiToken')
|
|
472
472
|
|
|
473
473
|
// 1. Resolve the zone, and refuse a zone that lives somewhere else.
|
|
474
474
|
const zones = await cf<
|