@zabaca/zbc 0.13.0 → 0.15.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +117 -6
  2. package/package.json +5 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/apply.ts +33 -9
  5. package/src/commands/destroy.ts +1 -1
  6. package/src/commands/init.ts +1 -0
  7. package/src/engine/apply.ts +110 -22
  8. package/src/engine/destroy.ts +183 -14
  9. package/src/engine/discover.ts +1 -1
  10. package/src/engine/resolve.ts +113 -14
  11. package/src/utils/copy-template.ts +10 -0
  12. package/templates/CLAUDE.md +1 -1
  13. package/templates/apps/inbox/package.json +3 -1
  14. package/templates/apps/inbox/tsconfig.json +3 -1
  15. package/templates/apps/inbox/worker/api.ts +197 -0
  16. package/templates/apps/inbox/worker/commands.ts +299 -0
  17. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  18. package/templates/apps/inbox/worker/index.ts +15 -202
  19. package/templates/apps/inbox/worker/mcp.ts +49 -100
  20. package/templates/infra/modules/cloudflare/index.ts +29 -73
  21. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  22. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  23. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  24. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  25. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  26. package/templates/infra/modules/cloudflare-token/index.ts +10 -32
  27. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  28. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  29. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  30. package/templates/infra/modules/fly/index.ts +17 -42
  31. package/templates/infra/modules/fly/registry.json +1 -1
  32. package/templates/infra/modules/host-file/index.ts +6 -7
  33. package/templates/infra/modules/provision-core/index.ts +21 -15
  34. package/templates/infra/modules/r2/index.ts +40 -71
  35. package/templates/infra/modules/r2/registry.json +1 -1
  36. package/templates/infra/modules/remote-provision/index.ts +1 -3
  37. package/templates/infra/modules/turso/index.ts +2 -15
  38. package/templates/infra/modules/vm-provision/index.ts +10 -3
  39. package/templates/infra/src/context.ts +115 -0
  40. package/templates/infra/src/define-module.ts +41 -2
  41. package/templates/infra/src/index.ts +11 -1
  42. package/templates/infra/src/types.ts +85 -3
  43. package/src/commands/add-registry.test.ts +0 -92
  44. package/src/commands/secret.test.ts +0 -717
  45. package/src/commands/vendor-mode.test.ts +0 -183
  46. package/src/infra-types.ts +0 -38
  47. package/src/utils/subtree.test.ts +0 -127
  48. package/templates/apps/inbox/worker/send-op.ts +0 -174
@@ -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.secrets, idempotent list→create everywhere, console.log progress.
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
- const API = 'https://api.cloudflare.com/client/v4'
30
-
31
- interface CfEnvelope<T> {
32
- success: boolean
33
- errors: Array<{ code: number; message: string }>
34
- result: T
35
- }
36
-
37
- class CfError extends Error {
38
- constructor(
39
- public status: number,
40
- public codes: number[],
41
- message: string,
42
- ) {
43
- super(message)
44
- }
45
- has(code: number): boolean {
46
- return this.codes.includes(code)
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
- const instanceOutputs = imports[ref.from]
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
- imports: Record<string, unknown>,
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, imports, fieldName)] }
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 cfFetch<Array<{ email: string; verified?: string | null }>>(
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 cfFetch(token, `/accounts/${accountId}/email/routing/addresses`, {
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.secrets['CLOUDFLARE_API_TOKEN']
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 cfFetch<SendingSubdomain[]>(
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 cfFetch<SendingSubdomain>(token, `/zones/${zoneId}/email/sending/subdomains`, {
327
- method: 'POST',
328
- body: { name: domain },
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 cfFetch<unknown>(
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 cfFetch<{ enabled?: boolean; status?: string }>(
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 cfFetch(token, `/zones/${zoneId}/email/routing/enable`, { method: 'POST' })
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 cfFetch<{ name: string }>(token, `/zones/${zoneId}`)
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 cfFetch<Array<Record<string, unknown>>>(
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 cfFetch(token, `/zones/${zoneId}/email/routing/dns`, {
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 cfFetch(token, `/zones/${zoneId}/email/routing/dns`, {
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 cfFetch<Array<Record<string, unknown>>>(
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 cfFetch<RoutingRule[]>(
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.imports, `addresses[${entry.localPart}]`)],
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 cfFetch(token, `/zones/${zoneId}/email/routing/rules/${existing.id}`, {
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 cfFetch(token, `/zones/${zoneId}/email/routing/rules`, { method: 'POST', body })
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 cfFetch(token, `/zones/${zoneId}/email/routing/rules/catch_all`, {
472
- method: 'PUT',
473
- body: {
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.imports, 'catchAll')],
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.secrets['CLOUDFLARE_API_TOKEN']
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 cfFetch<RoutingRule[]>(
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 cfFetch(token, `/zones/${zoneId}/email/routing/rules/${r.id}`, {
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 cfFetch(token, `/zones/${zoneId}/email/routing/rules/catch_all`, {
532
- method: 'PUT',
533
- body: {
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 cfFetch(token, `/zones/${zoneId}/email/routing/disable`, { method: 'POST' })
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 cfFetch<SendingSubdomain[]>(
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 cfFetch(token, `/zones/${zoneId}/email/sending/subdomains/${sub.tag}`, {
564
- method: 'DELETE',
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
@@ -156,8 +138,6 @@ export const cloudflareTokenModule = defineModule({
156
138
  * to grant zone-scoped groups on all zones of the account.
157
139
  */
158
140
  zones: z.array(z.string()).default([]),
159
- /** Destroy+recreate on every apply (per-PR preview tokens). */
160
- ephemeral: z.boolean().default(false),
161
141
  }),
162
142
  outputs: z.object({
163
143
  tokenId: z.string(),
@@ -169,8 +149,7 @@ export const cloudflareTokenModule = defineModule({
169
149
  s3SecretAccessKey: z.string(),
170
150
  }),
171
151
  async apply(config, ctx) {
172
- const rootToken = ctx.secrets['CLOUDFLARE_ROOT_TOKEN']
173
- if (!rootToken) throw new Error('Missing secret: CLOUDFLARE_ROOT_TOKEN')
152
+ const rootToken = ctx.secret('CLOUDFLARE_ROOT_TOKEN')
174
153
 
175
154
  // 1. Resolve permission names → group ids. Fail fast before any mutation.
176
155
  const available = await cf<PermissionGroup[]>(
@@ -251,8 +230,7 @@ export const cloudflareTokenModule = defineModule({
251
230
  return { tokenId, tokenValue, ...deriveS3Credentials(tokenId, tokenValue) }
252
231
  },
253
232
  async destroy(config, ctx) {
254
- const rootToken = ctx.secrets['CLOUDFLARE_ROOT_TOKEN']
255
- if (!rootToken) throw new Error('Missing secret: CLOUDFLARE_ROOT_TOKEN')
233
+ const rootToken = ctx.secret('CLOUDFLARE_ROOT_TOKEN')
256
234
  const existing = await findTokenByName(rootToken, config.accountId, config.tokenName)
257
235
  if (!existing) {
258
236
  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, resolveApiToken } from '../cloudflare-api'
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 = resolveApiToken(config.apiToken, ctx.imports)
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 = resolveApiToken(config.apiToken, ctx.imports)
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, resolveApiToken } from '../cloudflare-api'
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 = resolveApiToken(config.apiToken, ctx.imports)
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<