The best way to control Claude Code, Codex and more from any computer or phone

main
ts 196 lines 7.31 KB
Raw
1 import * as dns from "@distilled.cloud/cloudflare/dns";
2 import * as emailRouting from "@distilled.cloud/cloudflare/email-routing";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { listAllZones } from "../Zone/lookup.ts";
13
14 const RoutingSubdomainTypeId = "Cloudflare.Email.RoutingSubdomain" as const;
15 type RoutingSubdomainTypeId = typeof RoutingSubdomainTypeId;
16
17 export interface RoutingSubdomainProps {
18 /**
19 * Zone the subdomain belongs to. Email Routing must be enabled on the zone
20 * (see {@link Routing}).
21 *
22 * Stable — moving the subdomain to another zone triggers a replacement.
23 */
24 zoneId: string;
25 /**
26 * The fully-qualified subdomain to receive mail on (e.g.
27 * `in.example.com`). Must be within the zone.
28 *
29 * Stable — a rename is a delete + create.
30 */
31 name: string;
32 }
33
34 export interface RoutingSubdomainAttributes {
35 /** Zone the subdomain belongs to. */
36 zoneId: string;
37 /** The subdomain receiving mail. */
38 name: string;
39 /** The Email Routing MX hosts the subdomain's records point at. */
40 mx: string[];
41 }
42
43 export type RoutingSubdomain = Resource<
44 RoutingSubdomainTypeId,
45 RoutingSubdomainProps,
46 RoutingSubdomainAttributes,
47 never,
48 Providers
49 >;
50
51 /**
52 * Extends Email Routing on a zone to one of its subdomains, so literal
53 * routing rules (see {@link Rule}) can match addresses on it, as the
54 * dashboard's Email Routing > Settings > Subdomains does. Cloudflare adds and
55 * locks the subdomain's MX and SPF records. Catch-all rules stay apex-only.
56 *
57 * Deleting it unlocks and removes the subdomain's Email Routing records
58 * only. It never disables Email Routing on the zone: the zone-level
59 * `DELETE /email/routing/dns` takes no subdomain and would turn routing off
60 * for the apex too.
61 *
62 * Safety: Email Routing records carry no ownership markers. When there is no
63 * prior state, `read` reports a subdomain that already routes mail as
64 * `Unowned`, so the engine refuses to take it over unless `--adopt` (or
65 * `adopt(true)`) is set.
66 *
67 * ### Receiving on a subdomain
68 * **Example:** Route `docs@in.example.com` to a Worker
69 * ```typescript
70 * const routing = yield* Cloudflare.Email.Routing("Routing", {
71 * zone: "example.com",
72 * });
73 * yield* Cloudflare.Email.RoutingSubdomain("Inbound", {
74 * zoneId: routing.zoneId,
75 * name: "in.example.com",
76 * });
77 * ```
78 *
79 * @see https://developers.cloudflare.com/email-service/configuration/subdomains/
80 *
81 * @resource
82 * @product Email
83 * @category Email
84 */
85 export const RoutingSubdomain = Resource<RoutingSubdomain>(RoutingSubdomainTypeId);
86
87 /**
88 * Returns true if the given value is a RoutingSubdomain resource.
89 */
90 export const isRoutingSubdomain = (value: unknown): value is RoutingSubdomain =>
91 Predicate.hasProperty(value, "Type") && value.Type === RoutingSubdomainTypeId;
92
93 export const RoutingSubdomainProvider = () =>
94 Provider.succeed(RoutingSubdomain, {
95 stables: ["zoneId", "name"],
96
97 list: Effect.fn(function* () {
98 const { accountId } = yield* yield* CloudflareEnvironment;
99 // No API lists routing subdomains: a subdomain routes mail when it has
100 // Email Routing MX records, so scan each zone's MX records for names
101 // other than the apex.
102 const zones = yield* listAllZones(accountId);
103 const rows = yield* Effect.forEach(
104 zones,
105 (zone) =>
106 dns.listRecords.items({ zoneId: zone.id, type: "MX" }).pipe(
107 Stream.filter((record) => isRoutingMx(record.content) && record.name !== zone.name),
108 Stream.runCollect,
109 Effect.map((chunk) => groupByName(zone.id, Array.from(chunk))),
110 Effect.catchTag("Forbidden", () => Effect.succeed([])),
111 ),
112 { concurrency: 10 },
113 );
114 return rows.flat();
115 }),
116
117 diff: Effect.fn(function* ({ news, output }) {
118 if (!output || !isResolved(news)) return undefined;
119 if (news.zoneId !== output.zoneId || news.name !== output.name) {
120 return { action: "replace" } as const;
121 }
122 return undefined;
123 }),
124
125 read: Effect.fn(function* ({ output, olds }) {
126 const zoneId = output?.zoneId ?? olds?.zoneId;
127 const name = output?.name ?? olds?.name;
128 if (!zoneId || !name) return undefined;
129 const mx = yield* routingMxOf(zoneId, name);
130 if (mx.length === 0) return undefined;
131 const observed = { zoneId, name, mx };
132 return output ? observed : Unowned(observed);
133 }),
134
135 reconcile: Effect.fn(function* ({ news }) {
136 const zoneId = news.zoneId;
137 // Observe, then ensure: a subdomain already routing mail needs nothing.
138 const existing = yield* routingMxOf(zoneId, news.name);
139 if (existing.length > 0) return { zoneId, name: news.name, mx: existing };
140 yield* emailRouting.createDns({ zoneId, name: news.name });
141 return { zoneId, name: news.name, mx: yield* routingMxOf(zoneId, news.name) };
142 }),
143
144 delete: Effect.fn(function* ({ output }) {
145 const { zoneId, name } = output;
146 // Unlock the subdomain's records, then remove the Email Routing ones at
147 // this exact name. Idempotent: nothing left to remove is success.
148 yield* emailRouting
149 .patchDns({ zoneId, name })
150 .pipe(Effect.catchTag("EmailRoutingSubdomainNotFound", () => Effect.void));
151 const records = yield* dns.listRecords.items({ zoneId, name: { exact: name } }).pipe(
152 Stream.filter(
153 (record) =>
154 (record.type === "MX" && isRoutingMx(record.content)) ||
155 (record.type === "TXT" && isRoutingSpf(record.content)),
156 ),
157 Stream.runCollect,
158 );
159 yield* Effect.forEach(
160 Array.from(records),
161 (record) => dns.deleteRecord({ zoneId, dnsRecordId: record.id }),
162 { concurrency: 3, discard: true },
163 );
164 }),
165 });
166
167 // ---------------------------------------------------------------------------
168 // API helpers
169 // ---------------------------------------------------------------------------
170
171 /** Email Routing's inbound hosts: `route1.mx.cloudflare.net` to `route3`. */
172 const isRoutingMx = (content: string | null | undefined) =>
173 /^route\d+\.mx\.cloudflare\.net\.?$/iu.test(content ?? "");
174
175 /** The SPF record Email Routing adds beside its MX records. */
176 const isRoutingSpf = (content: string | null | undefined) =>
177 (content ?? "").includes("include:_spf.mx.cloudflare.net");
178
179 const routingMxOf = (zoneId: string, name: string) =>
180 dns.listRecords.items({ zoneId, name: { exact: name }, type: "MX" }).pipe(
181 Stream.filter((record) => isRoutingMx(record.content)),
182 Stream.map((record) => record.content ?? ""),
183 Stream.runCollect,
184 Effect.map((chunk) => Array.from(chunk).sort()),
185 );
186
187 const groupByName = (
188 zoneId: string,
189 records: ReadonlyArray<{ readonly name: string; readonly content?: string | null }>,
190 ): RoutingSubdomainAttributes[] => {
191 const byName = new Map<string, string[]>();
192 for (const record of records) {
193 byName.set(record.name, [...(byName.get(record.name) ?? []), record.content ?? ""]);
194 }
195 return [...byName].map(([name, mx]) => ({ zoneId, name, mx: mx.sort() }));
196 };