@zabaca/zbc 0.4.0 → 0.6.1

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.
@@ -0,0 +1,512 @@
1
+ import { z } from 'zod'
2
+ import { defineModule } from '../../src/define-module'
3
+
4
+ /**
5
+ * cloudflare-email — provisions Cloudflare Email Service (public beta) for a
6
+ * domain: outbound sending (SPF/DKIM/DMARC/bounce-MX auto-provisioned) and/or
7
+ * inbound routing (literal rules + catch-all → forward / worker / drop).
8
+ *
9
+ * Unlike the `cloudflare` module (which shells out to wrangler), this module
10
+ * calls the Cloudflare REST API directly — wrangler has no surface for Email
11
+ * Routing / Email Sending onboarding. Same turso-style shape: token from
12
+ * ctx.secrets, idempotent list→create everywhere, console.log progress.
13
+ *
14
+ * Operational caveats (beta):
15
+ * - Email Sending requires a Workers Paid plan (403/10105 = not entitled).
16
+ * - The API token needs Email Routing Rules Edit + Zone Settings Edit (the
17
+ * routing enable/settings/DNS endpoints live under generic Zone Settings) +
18
+ * DNS Edit on the zone, and Email Sending Edit + Email Routing Addresses
19
+ * Edit on the account (10000 "Authentication error" = missing scope).
20
+ * - `forward` targets must be verified destination addresses; verification is
21
+ * a manual email click. apply creates the address (which sends the email)
22
+ * and fails with instructions — click the link, re-run apply.
23
+ * - Outbound cap 5 MiB per message; rate limits are unpublished. Pilot before
24
+ * pointing high-volume projects at it.
25
+ * - Sending onboarding adds an SPF record; if the (sub)domain already has one,
26
+ * merge them manually — two SPF records break SPF evaluation entirely.
27
+ */
28
+
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
99
+ }
100
+
101
+ /**
102
+ * A worker name: either a literal script name, or a `{ from, output }`
103
+ * reference into an imported instance's outputs (e.g. the cloudflare module
104
+ * emits `workerName`). References make the coupling refactor-safe — a rename
105
+ * in wrangler.jsonc flows through automatically, and a typo'd instance or
106
+ * output is a hard error at apply time instead of a dangling routing rule.
107
+ */
108
+ const workerRefSchema = z.union([
109
+ z.string(),
110
+ z.object({
111
+ /** Instance name — must be listed in this instance's `imports`. */
112
+ from: z.string(),
113
+ /** Which output of that instance holds the worker name. */
114
+ output: z.string(),
115
+ }),
116
+ ])
117
+
118
+ type WorkerRef = z.infer<typeof workerRefSchema>
119
+
120
+ /** 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 {
126
+ 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
140
+ }
141
+
142
+ /** A routing rule action target. */
143
+ const addressSchema = z.object({
144
+ /** Local part only — the domain comes from config.domain. */
145
+ localPart: z.string(),
146
+ action: z.enum(['forward', 'worker']),
147
+ /** forward: a verified destination address (email). */
148
+ destination: z.string().optional(),
149
+ /** worker: the script name, literal or `{ from, output }` import reference. */
150
+ workerName: workerRefSchema.optional(),
151
+ })
152
+
153
+ const catchAllSchema = z.object({
154
+ action: z.enum(['worker', 'forward', 'drop']),
155
+ /** worker: the script name, literal or `{ from, output }` import reference. */
156
+ workerName: workerRefSchema.optional(),
157
+ destination: z.string().optional(),
158
+ })
159
+
160
+ interface RoutingRule {
161
+ id: string
162
+ name?: string
163
+ enabled: boolean
164
+ matchers: Array<{ type: string; field?: string; value?: string }>
165
+ actions: Array<{ type: string; value?: string[] }>
166
+ }
167
+
168
+ interface SendingSubdomain {
169
+ tag: string
170
+ name: string
171
+ enabled: boolean
172
+ }
173
+
174
+ /** Managed-rule marker so destroy only removes rules this module created. */
175
+ const RULE_PREFIX = 'zbc:'
176
+
177
+ function ruleAction(
178
+ entry: { action: string; destination?: string; workerName?: WorkerRef },
179
+ imports: Record<string, unknown>,
180
+ fieldName: string,
181
+ ): { type: string; value?: string[] } {
182
+ if (entry.action === 'forward') {
183
+ if (!entry.destination) throw new Error(`${fieldName}: action "forward" requires a destination`)
184
+ return { type: 'forward', value: [entry.destination] }
185
+ }
186
+ if (entry.action === 'worker') {
187
+ if (!entry.workerName) throw new Error(`${fieldName}: action "worker" requires a workerName`)
188
+ return { type: 'worker', value: [resolveWorkerName(entry.workerName, imports, fieldName)] }
189
+ }
190
+ return { type: 'drop' }
191
+ }
192
+
193
+ /**
194
+ * Ensure a forward destination exists and is verified. Creating an address
195
+ * triggers Cloudflare's verification email; verification itself is a manual
196
+ * click we cannot automate — so fail with instructions and let the operator
197
+ * re-run apply.
198
+ */
199
+ async function ensureDestinationVerified(
200
+ token: string,
201
+ accountId: string,
202
+ email: string,
203
+ ): Promise<void> {
204
+ const addresses = await cfFetch<Array<{ email: string; verified?: string | null }>>(
205
+ token,
206
+ `/accounts/${accountId}/email/routing/addresses?per_page=50`,
207
+ )
208
+ const existing = addresses.find((a) => a.email.toLowerCase() === email.toLowerCase())
209
+ if (existing?.verified) return
210
+ if (!existing) {
211
+ await cfFetch(token, `/accounts/${accountId}/email/routing/addresses`, {
212
+ method: 'POST',
213
+ body: { email },
214
+ })
215
+ console.log(` Created destination address ${email} — verification email sent`)
216
+ }
217
+ throw new Error(
218
+ `Destination address ${email} is not verified yet. Cloudflare has emailed it a ` +
219
+ `verification link — click it, then re-run zbc apply.`,
220
+ )
221
+ }
222
+
223
+ export const cloudflareEmailModule = defineModule({
224
+ name: 'cloudflare-email',
225
+ configSchema: z.object({
226
+ /** Cloudflare account id (dashboard URL — not a secret). */
227
+ accountId: z.string(),
228
+ /** Zone id of the apex zone (e.g. cedarpad.com's zone). */
229
+ zoneId: z.string(),
230
+ /** Email domain — the zone apex or a subdomain of it (e.g. mail.cedarpad.com). */
231
+ domain: z.string(),
232
+ /** Onboard the domain for outbound sending (SPF/DKIM/DMARC/bounce-MX). */
233
+ enableSending: z.boolean().default(true),
234
+ /** Enable inbound routing (MX records) + rules below. */
235
+ enableRouting: z.boolean().default(false),
236
+ /** Catch-all rule for the domain. Omit to leave catch-all untouched. */
237
+ catchAll: catchAllSchema.optional(),
238
+ /** Literal-address rules (localPart @ domain). */
239
+ addresses: z.array(addressSchema).default([]),
240
+ }),
241
+ outputs: z.object({
242
+ sendingEnabled: z.boolean(),
243
+ routingEnabled: z.boolean(),
244
+ /** DNS record name+type → status (e.g. "MX mail.cedarpad.com": "active"). */
245
+ dnsStatus: z.record(z.string()),
246
+ /** Full email addresses with literal rules. */
247
+ addresses: z.array(z.string()),
248
+ accountId: z.string(),
249
+ domain: z.string(),
250
+ }),
251
+ async apply(config, ctx) {
252
+ const token = ctx.secrets['CLOUDFLARE_API_TOKEN']
253
+ if (!token) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
254
+
255
+ const { accountId, zoneId, domain } = config
256
+ const dnsStatus: Record<string, string> = {}
257
+ let sendingEnabled = false
258
+ let routingEnabled = false
259
+
260
+ // ── 1. Outbound sending: onboard the (sub)domain, surface DNS status ────
261
+ if (config.enableSending) {
262
+ const subdomains = await cfFetch<SendingSubdomain[]>(
263
+ token,
264
+ `/zones/${zoneId}/email/sending/subdomains`,
265
+ )
266
+ let sub = subdomains.find((s) => s.name === domain)
267
+ if (sub) {
268
+ console.log(` Sending: ${domain} already onboarded`)
269
+ } else {
270
+ sub = await cfFetch<SendingSubdomain>(token, `/zones/${zoneId}/email/sending/subdomains`, {
271
+ method: 'POST',
272
+ body: { name: domain },
273
+ })
274
+ console.log(` Sending: onboarded ${domain} (SPF/DKIM/DMARC/bounce-MX auto-provisioned)`)
275
+ }
276
+ sendingEnabled = true
277
+
278
+ // DNS record verification status. Field names are beta-era; read
279
+ // defensively and record whatever type/name/status the API returns.
280
+ try {
281
+ const dns = await cfFetch<unknown>(
282
+ token,
283
+ `/zones/${zoneId}/email/sending/subdomains/${sub.tag}/dns`,
284
+ )
285
+ const records: Array<Record<string, unknown>> = Array.isArray(dns)
286
+ ? (dns as Array<Record<string, unknown>>)
287
+ : (((dns as Record<string, unknown>)?.['records'] as Array<Record<string, unknown>>) ??
288
+ [])
289
+ for (const r of records) {
290
+ const key = `${String(r.type ?? 'record')} ${String(r.name ?? domain)}`
291
+ const status = String(r.status ?? r.state ?? 'unknown')
292
+ dnsStatus[key] = status
293
+ if (status !== 'active' && status !== 'verified' && status !== 'locked') {
294
+ console.log(` ⚠ Sending DNS pending: ${key} → ${status}`)
295
+ }
296
+ }
297
+ } catch (err) {
298
+ console.log(` ⚠ Could not read sending DNS status: ${(err as Error).message}`)
299
+ }
300
+ }
301
+
302
+ // ── 2. Inbound routing: enable, subdomain DNS, rules, catch-all ─────────
303
+ if (config.enableRouting) {
304
+ const settings = await cfFetch<{ enabled?: boolean; status?: string }>(
305
+ token,
306
+ `/zones/${zoneId}/email/routing`,
307
+ )
308
+ if (settings.enabled || settings.status === 'ready') {
309
+ console.log(` Routing: already enabled on zone`)
310
+ } else {
311
+ await cfFetch(token, `/zones/${zoneId}/email/routing/enable`, { method: 'POST' })
312
+ console.log(` Routing: enabled on zone (MX/SPF records locked in)`)
313
+ }
314
+ routingEnabled = true
315
+
316
+ // Subdomain routing: provision routing DNS for the subdomain itself
317
+ // (POST /email/routing/dns with the subdomain name). Idempotent: check
318
+ // first via the subdomain query param.
319
+ const zone = await cfFetch<{ name: string }>(token, `/zones/${zoneId}`)
320
+ if (domain !== zone.name) {
321
+ try {
322
+ const dns = await cfFetch<Array<Record<string, unknown>>>(
323
+ token,
324
+ `/zones/${zoneId}/email/routing/dns?subdomain=${encodeURIComponent(domain)}`,
325
+ )
326
+ const hasMx = Array.isArray(dns) && dns.some((r) => r.type === 'MX')
327
+ if (!hasMx) {
328
+ await cfFetch(token, `/zones/${zoneId}/email/routing/dns`, {
329
+ method: 'POST',
330
+ body: { name: domain },
331
+ })
332
+ console.log(` Routing: provisioned DNS for subdomain ${domain}`)
333
+ } else {
334
+ console.log(` Routing: subdomain ${domain} DNS already provisioned`)
335
+ }
336
+ } catch (err) {
337
+ // Some API versions only expose subdomain enrollment via POST; try it.
338
+ if (err instanceof CfError && err.status === 404) {
339
+ await cfFetch(token, `/zones/${zoneId}/email/routing/dns`, {
340
+ method: 'POST',
341
+ body: { name: domain },
342
+ })
343
+ console.log(` Routing: provisioned DNS for subdomain ${domain}`)
344
+ } else {
345
+ throw err
346
+ }
347
+ }
348
+ }
349
+
350
+ // Routing DNS status for the domain
351
+ try {
352
+ const routingDns = await cfFetch<Array<Record<string, unknown>>>(
353
+ token,
354
+ `/zones/${zoneId}/email/routing/dns${domain !== zone.name ? `?subdomain=${encodeURIComponent(domain)}` : ''}`,
355
+ )
356
+ for (const r of routingDns ?? []) {
357
+ dnsStatus[`${String(r.type ?? 'record')} ${String(r.name ?? domain)}`] = String(
358
+ r.status ?? 'unknown',
359
+ )
360
+ }
361
+ } catch {
362
+ // status endpoint variance — non-fatal
363
+ }
364
+
365
+ // Pre-verify every forward destination before touching rules.
366
+ const forwardTargets = new Set<string>()
367
+ for (const a of config.addresses) {
368
+ if (a.action === 'forward' && a.destination) forwardTargets.add(a.destination)
369
+ }
370
+ if (config.catchAll?.action === 'forward' && config.catchAll.destination) {
371
+ forwardTargets.add(config.catchAll.destination)
372
+ }
373
+ for (const dest of forwardTargets) {
374
+ await ensureDestinationVerified(token, accountId, dest)
375
+ }
376
+
377
+ // Upsert literal rules for each address.
378
+ const existingRules = await cfFetch<RoutingRule[]>(
379
+ token,
380
+ `/zones/${zoneId}/email/routing/rules?per_page=50`,
381
+ )
382
+ for (const entry of config.addresses) {
383
+ const email = `${entry.localPart}@${domain}`
384
+ const ruleName = `${RULE_PREFIX}${email}`
385
+ const body = {
386
+ name: ruleName,
387
+ enabled: true,
388
+ matchers: [{ type: 'literal', field: 'to', value: email }],
389
+ actions: [ruleAction(entry, ctx.imports, `addresses[${entry.localPart}]`)],
390
+ }
391
+ const existing = existingRules.find(
392
+ (r) =>
393
+ r.name === ruleName ||
394
+ r.matchers.some((m) => m.type === 'literal' && m.value === email),
395
+ )
396
+ if (existing) {
397
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/${existing.id}`, {
398
+ method: 'PUT',
399
+ body,
400
+ })
401
+ console.log(` Routing: updated rule for ${email} → ${entry.action}`)
402
+ } else {
403
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules`, { method: 'POST', body })
404
+ console.log(` Routing: created rule for ${email} → ${entry.action}`)
405
+ }
406
+ }
407
+
408
+ // Catch-all.
409
+ if (config.catchAll) {
410
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/catch_all`, {
411
+ method: 'PUT',
412
+ body: {
413
+ name: `${RULE_PREFIX}catch-all`,
414
+ enabled: true,
415
+ matchers: [{ type: 'all' }],
416
+ actions: [ruleAction(config.catchAll, ctx.imports, 'catchAll')],
417
+ },
418
+ })
419
+ console.log(` Routing: catch-all → ${config.catchAll.action}`)
420
+ }
421
+ }
422
+
423
+ const pending = Object.entries(dnsStatus).filter(
424
+ ([, s]) => s !== 'active' && s !== 'verified' && s !== 'locked',
425
+ )
426
+ if (pending.length > 0) {
427
+ console.log(
428
+ ` ⚠ ${pending.length} DNS record(s) not yet verified — mail may not flow until they are:`,
429
+ )
430
+ for (const [k, s] of pending) console.log(` ${k}: ${s}`)
431
+ }
432
+
433
+ return {
434
+ sendingEnabled,
435
+ routingEnabled,
436
+ dnsStatus,
437
+ addresses: config.addresses.map((a) => `${a.localPart}@${domain}`),
438
+ accountId,
439
+ domain,
440
+ }
441
+ },
442
+ async destroy(config, ctx) {
443
+ const token = ctx.secrets['CLOUDFLARE_API_TOKEN']
444
+ if (!token) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
445
+ const { zoneId, domain } = config
446
+
447
+ console.log(` ⚠ DESTROYING email config for ${domain} — mail for this domain WILL STOP.`)
448
+
449
+ // Remove managed rules (only ones this module named).
450
+ try {
451
+ const rules = await cfFetch<RoutingRule[]>(
452
+ token,
453
+ `/zones/${zoneId}/email/routing/rules?per_page=50`,
454
+ )
455
+ for (const r of rules) {
456
+ if (r.name?.startsWith(RULE_PREFIX)) {
457
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/${r.id}`, {
458
+ method: 'DELETE',
459
+ })
460
+ console.log(` Deleted rule ${r.name}`)
461
+ }
462
+ }
463
+ } catch (err) {
464
+ console.log(` Rule cleanup skipped: ${(err as Error).message}`)
465
+ }
466
+
467
+ // Reset catch-all to drop (catch_all can't be deleted, only redefined).
468
+ if (config.catchAll) {
469
+ try {
470
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/catch_all`, {
471
+ method: 'PUT',
472
+ body: {
473
+ name: `${RULE_PREFIX}catch-all`,
474
+ enabled: false,
475
+ matchers: [{ type: 'all' }],
476
+ actions: [{ type: 'drop' }],
477
+ },
478
+ })
479
+ console.log(` Catch-all disabled`)
480
+ } catch (err) {
481
+ console.log(` Catch-all reset skipped: ${(err as Error).message}`)
482
+ }
483
+ }
484
+
485
+ if (config.enableRouting) {
486
+ try {
487
+ await cfFetch(token, `/zones/${zoneId}/email/routing/disable`, { method: 'POST' })
488
+ console.log(` Routing disabled on zone`)
489
+ } catch (err) {
490
+ console.log(` Routing disable skipped: ${(err as Error).message}`)
491
+ }
492
+ }
493
+
494
+ if (config.enableSending) {
495
+ try {
496
+ const subdomains = await cfFetch<SendingSubdomain[]>(
497
+ token,
498
+ `/zones/${zoneId}/email/sending/subdomains`,
499
+ )
500
+ const sub = subdomains.find((s) => s.name === domain)
501
+ if (sub) {
502
+ await cfFetch(token, `/zones/${zoneId}/email/sending/subdomains/${sub.tag}`, {
503
+ method: 'DELETE',
504
+ })
505
+ console.log(` Sending subdomain ${domain} deleted`)
506
+ }
507
+ } catch (err) {
508
+ console.log(` Sending teardown skipped: ${(err as Error).message}`)
509
+ }
510
+ }
511
+ },
512
+ })
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "cloudflare-email",
3
+ "description": "Cloudflare Email Service (beta): outbound sending + inbound routing for a domain, via the REST API",
4
+ "files": [{ "path": "index.ts" }],
5
+ "dependencies": {
6
+ "zod": "^3.24.0"
7
+ },
8
+ "secrets": ["CLOUDFLARE_API_TOKEN"],
9
+ "signupUrl": "https://dash.cloudflare.com",
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."
12
+ }
@@ -37,9 +37,10 @@ jobs:
37
37
  STATUS=$?
38
38
  echo "$OUTPUT"
39
39
 
40
- # Pair each "Deployed:" URL with the most recent "→ vercel:<name>" header
40
+ # Pair each "Deployed:" URL with the most recent "→ <module>:<name>" header
41
+ # (module-agnostic: works for cloudflare and any future provider).
41
42
  LIST=$(echo "$OUTPUT" | awk '
42
- /^→ vercel:/{name=$2; sub(/vercel:/, "", name)}
43
+ /^→ /{name=$2; sub(/^[^:]*:/, "", name)}
43
44
  /Deployed:/{print "- **" name "**: " $NF}
44
45
  ')
45
46