@zabaca/zbc 0.4.0 → 0.6.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.
@@ -0,0 +1,469 @@
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
+ /** A routing rule action target. */
102
+ const addressSchema = z.object({
103
+ /** Local part only — the domain comes from config.domain. */
104
+ localPart: z.string(),
105
+ action: z.enum(['forward', 'worker']),
106
+ /** forward: a verified destination address (email). */
107
+ destination: z.string().optional(),
108
+ /** worker: the deployed Worker script name. */
109
+ workerName: z.string().optional(),
110
+ })
111
+
112
+ const catchAllSchema = z.object({
113
+ action: z.enum(['worker', 'forward', 'drop']),
114
+ workerName: z.string().optional(),
115
+ destination: z.string().optional(),
116
+ })
117
+
118
+ interface RoutingRule {
119
+ id: string
120
+ name?: string
121
+ enabled: boolean
122
+ matchers: Array<{ type: string; field?: string; value?: string }>
123
+ actions: Array<{ type: string; value?: string[] }>
124
+ }
125
+
126
+ interface SendingSubdomain {
127
+ tag: string
128
+ name: string
129
+ enabled: boolean
130
+ }
131
+
132
+ /** Managed-rule marker so destroy only removes rules this module created. */
133
+ const RULE_PREFIX = 'zbc:'
134
+
135
+ function ruleAction(entry: { action: string; destination?: string; workerName?: string }): {
136
+ type: string
137
+ value?: string[]
138
+ } {
139
+ if (entry.action === 'forward') {
140
+ if (!entry.destination) throw new Error(`action "forward" requires a destination`)
141
+ return { type: 'forward', value: [entry.destination] }
142
+ }
143
+ if (entry.action === 'worker') {
144
+ if (!entry.workerName) throw new Error(`action "worker" requires a workerName`)
145
+ return { type: 'worker', value: [entry.workerName] }
146
+ }
147
+ return { type: 'drop' }
148
+ }
149
+
150
+ /**
151
+ * Ensure a forward destination exists and is verified. Creating an address
152
+ * triggers Cloudflare's verification email; verification itself is a manual
153
+ * click we cannot automate — so fail with instructions and let the operator
154
+ * re-run apply.
155
+ */
156
+ async function ensureDestinationVerified(
157
+ token: string,
158
+ accountId: string,
159
+ email: string,
160
+ ): Promise<void> {
161
+ const addresses = await cfFetch<Array<{ email: string; verified?: string | null }>>(
162
+ token,
163
+ `/accounts/${accountId}/email/routing/addresses?per_page=50`,
164
+ )
165
+ const existing = addresses.find((a) => a.email.toLowerCase() === email.toLowerCase())
166
+ if (existing?.verified) return
167
+ if (!existing) {
168
+ await cfFetch(token, `/accounts/${accountId}/email/routing/addresses`, {
169
+ method: 'POST',
170
+ body: { email },
171
+ })
172
+ console.log(` Created destination address ${email} — verification email sent`)
173
+ }
174
+ throw new Error(
175
+ `Destination address ${email} is not verified yet. Cloudflare has emailed it a ` +
176
+ `verification link — click it, then re-run zbc apply.`,
177
+ )
178
+ }
179
+
180
+ export const cloudflareEmailModule = defineModule({
181
+ name: 'cloudflare-email',
182
+ configSchema: z.object({
183
+ /** Cloudflare account id (dashboard URL — not a secret). */
184
+ accountId: z.string(),
185
+ /** Zone id of the apex zone (e.g. cedarpad.com's zone). */
186
+ zoneId: z.string(),
187
+ /** Email domain — the zone apex or a subdomain of it (e.g. mail.cedarpad.com). */
188
+ domain: z.string(),
189
+ /** Onboard the domain for outbound sending (SPF/DKIM/DMARC/bounce-MX). */
190
+ enableSending: z.boolean().default(true),
191
+ /** Enable inbound routing (MX records) + rules below. */
192
+ enableRouting: z.boolean().default(false),
193
+ /** Catch-all rule for the domain. Omit to leave catch-all untouched. */
194
+ catchAll: catchAllSchema.optional(),
195
+ /** Literal-address rules (localPart @ domain). */
196
+ addresses: z.array(addressSchema).default([]),
197
+ }),
198
+ outputs: z.object({
199
+ sendingEnabled: z.boolean(),
200
+ routingEnabled: z.boolean(),
201
+ /** DNS record name+type → status (e.g. "MX mail.cedarpad.com": "active"). */
202
+ dnsStatus: z.record(z.string()),
203
+ /** Full email addresses with literal rules. */
204
+ addresses: z.array(z.string()),
205
+ accountId: z.string(),
206
+ domain: z.string(),
207
+ }),
208
+ async apply(config, ctx) {
209
+ const token = ctx.secrets['CLOUDFLARE_API_TOKEN']
210
+ if (!token) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
211
+
212
+ const { accountId, zoneId, domain } = config
213
+ const dnsStatus: Record<string, string> = {}
214
+ let sendingEnabled = false
215
+ let routingEnabled = false
216
+
217
+ // ── 1. Outbound sending: onboard the (sub)domain, surface DNS status ────
218
+ if (config.enableSending) {
219
+ const subdomains = await cfFetch<SendingSubdomain[]>(
220
+ token,
221
+ `/zones/${zoneId}/email/sending/subdomains`,
222
+ )
223
+ let sub = subdomains.find((s) => s.name === domain)
224
+ if (sub) {
225
+ console.log(` Sending: ${domain} already onboarded`)
226
+ } else {
227
+ sub = await cfFetch<SendingSubdomain>(token, `/zones/${zoneId}/email/sending/subdomains`, {
228
+ method: 'POST',
229
+ body: { name: domain },
230
+ })
231
+ console.log(` Sending: onboarded ${domain} (SPF/DKIM/DMARC/bounce-MX auto-provisioned)`)
232
+ }
233
+ sendingEnabled = true
234
+
235
+ // DNS record verification status. Field names are beta-era; read
236
+ // defensively and record whatever type/name/status the API returns.
237
+ try {
238
+ const dns = await cfFetch<unknown>(
239
+ token,
240
+ `/zones/${zoneId}/email/sending/subdomains/${sub.tag}/dns`,
241
+ )
242
+ const records: Array<Record<string, unknown>> = Array.isArray(dns)
243
+ ? (dns as Array<Record<string, unknown>>)
244
+ : (((dns as Record<string, unknown>)?.['records'] as Array<Record<string, unknown>>) ??
245
+ [])
246
+ for (const r of records) {
247
+ const key = `${String(r.type ?? 'record')} ${String(r.name ?? domain)}`
248
+ const status = String(r.status ?? r.state ?? 'unknown')
249
+ dnsStatus[key] = status
250
+ if (status !== 'active' && status !== 'verified' && status !== 'locked') {
251
+ console.log(` ⚠ Sending DNS pending: ${key} → ${status}`)
252
+ }
253
+ }
254
+ } catch (err) {
255
+ console.log(` ⚠ Could not read sending DNS status: ${(err as Error).message}`)
256
+ }
257
+ }
258
+
259
+ // ── 2. Inbound routing: enable, subdomain DNS, rules, catch-all ─────────
260
+ if (config.enableRouting) {
261
+ const settings = await cfFetch<{ enabled?: boolean; status?: string }>(
262
+ token,
263
+ `/zones/${zoneId}/email/routing`,
264
+ )
265
+ if (settings.enabled || settings.status === 'ready') {
266
+ console.log(` Routing: already enabled on zone`)
267
+ } else {
268
+ await cfFetch(token, `/zones/${zoneId}/email/routing/enable`, { method: 'POST' })
269
+ console.log(` Routing: enabled on zone (MX/SPF records locked in)`)
270
+ }
271
+ routingEnabled = true
272
+
273
+ // Subdomain routing: provision routing DNS for the subdomain itself
274
+ // (POST /email/routing/dns with the subdomain name). Idempotent: check
275
+ // first via the subdomain query param.
276
+ const zone = await cfFetch<{ name: string }>(token, `/zones/${zoneId}`)
277
+ if (domain !== zone.name) {
278
+ try {
279
+ const dns = await cfFetch<Array<Record<string, unknown>>>(
280
+ token,
281
+ `/zones/${zoneId}/email/routing/dns?subdomain=${encodeURIComponent(domain)}`,
282
+ )
283
+ const hasMx = Array.isArray(dns) && dns.some((r) => r.type === 'MX')
284
+ if (!hasMx) {
285
+ await cfFetch(token, `/zones/${zoneId}/email/routing/dns`, {
286
+ method: 'POST',
287
+ body: { name: domain },
288
+ })
289
+ console.log(` Routing: provisioned DNS for subdomain ${domain}`)
290
+ } else {
291
+ console.log(` Routing: subdomain ${domain} DNS already provisioned`)
292
+ }
293
+ } catch (err) {
294
+ // Some API versions only expose subdomain enrollment via POST; try it.
295
+ if (err instanceof CfError && err.status === 404) {
296
+ await cfFetch(token, `/zones/${zoneId}/email/routing/dns`, {
297
+ method: 'POST',
298
+ body: { name: domain },
299
+ })
300
+ console.log(` Routing: provisioned DNS for subdomain ${domain}`)
301
+ } else {
302
+ throw err
303
+ }
304
+ }
305
+ }
306
+
307
+ // Routing DNS status for the domain
308
+ try {
309
+ const routingDns = await cfFetch<Array<Record<string, unknown>>>(
310
+ token,
311
+ `/zones/${zoneId}/email/routing/dns${domain !== zone.name ? `?subdomain=${encodeURIComponent(domain)}` : ''}`,
312
+ )
313
+ for (const r of routingDns ?? []) {
314
+ dnsStatus[`${String(r.type ?? 'record')} ${String(r.name ?? domain)}`] = String(
315
+ r.status ?? 'unknown',
316
+ )
317
+ }
318
+ } catch {
319
+ // status endpoint variance — non-fatal
320
+ }
321
+
322
+ // Pre-verify every forward destination before touching rules.
323
+ const forwardTargets = new Set<string>()
324
+ for (const a of config.addresses) {
325
+ if (a.action === 'forward' && a.destination) forwardTargets.add(a.destination)
326
+ }
327
+ if (config.catchAll?.action === 'forward' && config.catchAll.destination) {
328
+ forwardTargets.add(config.catchAll.destination)
329
+ }
330
+ for (const dest of forwardTargets) {
331
+ await ensureDestinationVerified(token, accountId, dest)
332
+ }
333
+
334
+ // Upsert literal rules for each address.
335
+ const existingRules = await cfFetch<RoutingRule[]>(
336
+ token,
337
+ `/zones/${zoneId}/email/routing/rules?per_page=50`,
338
+ )
339
+ for (const entry of config.addresses) {
340
+ const email = `${entry.localPart}@${domain}`
341
+ const ruleName = `${RULE_PREFIX}${email}`
342
+ const body = {
343
+ name: ruleName,
344
+ enabled: true,
345
+ matchers: [{ type: 'literal', field: 'to', value: email }],
346
+ actions: [ruleAction(entry)],
347
+ }
348
+ const existing = existingRules.find(
349
+ (r) =>
350
+ r.name === ruleName ||
351
+ r.matchers.some((m) => m.type === 'literal' && m.value === email),
352
+ )
353
+ if (existing) {
354
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/${existing.id}`, {
355
+ method: 'PUT',
356
+ body,
357
+ })
358
+ console.log(` Routing: updated rule for ${email} → ${entry.action}`)
359
+ } else {
360
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules`, { method: 'POST', body })
361
+ console.log(` Routing: created rule for ${email} → ${entry.action}`)
362
+ }
363
+ }
364
+
365
+ // Catch-all.
366
+ if (config.catchAll) {
367
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/catch_all`, {
368
+ method: 'PUT',
369
+ body: {
370
+ name: `${RULE_PREFIX}catch-all`,
371
+ enabled: true,
372
+ matchers: [{ type: 'all' }],
373
+ actions: [ruleAction(config.catchAll)],
374
+ },
375
+ })
376
+ console.log(` Routing: catch-all → ${config.catchAll.action}`)
377
+ }
378
+ }
379
+
380
+ const pending = Object.entries(dnsStatus).filter(
381
+ ([, s]) => s !== 'active' && s !== 'verified' && s !== 'locked',
382
+ )
383
+ if (pending.length > 0) {
384
+ console.log(
385
+ ` ⚠ ${pending.length} DNS record(s) not yet verified — mail may not flow until they are:`,
386
+ )
387
+ for (const [k, s] of pending) console.log(` ${k}: ${s}`)
388
+ }
389
+
390
+ return {
391
+ sendingEnabled,
392
+ routingEnabled,
393
+ dnsStatus,
394
+ addresses: config.addresses.map((a) => `${a.localPart}@${domain}`),
395
+ accountId,
396
+ domain,
397
+ }
398
+ },
399
+ async destroy(config, ctx) {
400
+ const token = ctx.secrets['CLOUDFLARE_API_TOKEN']
401
+ if (!token) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
402
+ const { zoneId, domain } = config
403
+
404
+ console.log(` ⚠ DESTROYING email config for ${domain} — mail for this domain WILL STOP.`)
405
+
406
+ // Remove managed rules (only ones this module named).
407
+ try {
408
+ const rules = await cfFetch<RoutingRule[]>(
409
+ token,
410
+ `/zones/${zoneId}/email/routing/rules?per_page=50`,
411
+ )
412
+ for (const r of rules) {
413
+ if (r.name?.startsWith(RULE_PREFIX)) {
414
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/${r.id}`, {
415
+ method: 'DELETE',
416
+ })
417
+ console.log(` Deleted rule ${r.name}`)
418
+ }
419
+ }
420
+ } catch (err) {
421
+ console.log(` Rule cleanup skipped: ${(err as Error).message}`)
422
+ }
423
+
424
+ // Reset catch-all to drop (catch_all can't be deleted, only redefined).
425
+ if (config.catchAll) {
426
+ try {
427
+ await cfFetch(token, `/zones/${zoneId}/email/routing/rules/catch_all`, {
428
+ method: 'PUT',
429
+ body: {
430
+ name: `${RULE_PREFIX}catch-all`,
431
+ enabled: false,
432
+ matchers: [{ type: 'all' }],
433
+ actions: [{ type: 'drop' }],
434
+ },
435
+ })
436
+ console.log(` Catch-all disabled`)
437
+ } catch (err) {
438
+ console.log(` Catch-all reset skipped: ${(err as Error).message}`)
439
+ }
440
+ }
441
+
442
+ if (config.enableRouting) {
443
+ try {
444
+ await cfFetch(token, `/zones/${zoneId}/email/routing/disable`, { method: 'POST' })
445
+ console.log(` Routing disabled on zone`)
446
+ } catch (err) {
447
+ console.log(` Routing disable skipped: ${(err as Error).message}`)
448
+ }
449
+ }
450
+
451
+ if (config.enableSending) {
452
+ try {
453
+ const subdomains = await cfFetch<SendingSubdomain[]>(
454
+ token,
455
+ `/zones/${zoneId}/email/sending/subdomains`,
456
+ )
457
+ const sub = subdomains.find((s) => s.name === domain)
458
+ if (sub) {
459
+ await cfFetch(token, `/zones/${zoneId}/email/sending/subdomains/${sub.tag}`, {
460
+ method: 'DELETE',
461
+ })
462
+ console.log(` Sending subdomain ${domain} deleted`)
463
+ }
464
+ } catch (err) {
465
+ console.log(` Sending teardown skipped: ${(err as Error).message}`)
466
+ }
467
+ }
468
+ },
469
+ })
@@ -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