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

main
ts 333 lines 11.9 KB
Raw
1 import * as emailRouting from "@distilled.cloud/cloudflare/email-routing";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { resolveZoneId, type Reference } from "../Zone/index.ts";
10 import { listAllZones } from "../Zone/lookup.ts";
11 import { retryWorkerScriptNotFound } from "./retry.ts";
12 import type { Action } from "./Rule.ts";
13
14 const CatchAllTypeId = "Cloudflare.Email.CatchAll" as const;
15 type CatchAllTypeId = typeof CatchAllTypeId;
16
17 export type CatchAllProps = {
18 /**
19 * Zone whose catch-all rule to manage. Accepts a zone id, a zone name
20 * (`example.com`), or a `{ zoneId, name? }` object. Stable — the
21 * catch-all rule is a per-zone singleton, so changing the zone triggers
22 * a replacement (the old zone's catch-all is restored to the state it
23 * had before Alchemy managed it).
24 */
25 zone: Reference;
26 /**
27 * Display name for the catch-all rule. When omitted, the current name
28 * on the rule is left untouched.
29 */
30 name?: string;
31 /**
32 * Whether the catch-all rule is active.
33 *
34 * @default true
35 */
36 enabled?: boolean;
37 /**
38 * Actions to take for emails that match no other routing rule
39 * (`drop`, `forward` to verified destination addresses, or `worker`).
40 * Matchers are fixed to `[{ type: "all" }]` by the API.
41 */
42 actions: Action[];
43 };
44
45 export type CatchAllAttributes = {
46 /** Routing rule identifier of the zone's catch-all rule. */
47 ruleId: string;
48 /** Zone the catch-all rule belongs to. */
49 zoneId: string;
50 /** Display name of the catch-all rule. */
51 name: string;
52 /** Whether the catch-all rule is active. */
53 enabled: boolean;
54 /** Actions taken for emails that match no other routing rule. */
55 actions: Action[];
56 /**
57 * The name the catch-all rule had before Alchemy first managed it.
58 * Restored on destroy.
59 */
60 initialName: string;
61 /**
62 * Whether the catch-all rule was enabled before Alchemy first managed
63 * it. Restored on destroy.
64 */
65 initialEnabled: boolean;
66 /**
67 * The actions the catch-all rule had before Alchemy first managed it.
68 * Restored on destroy.
69 */
70 initialActions: Action[];
71 };
72
73 export type CatchAll = Resource<
74 CatchAllTypeId,
75 CatchAllProps,
76 CatchAllAttributes,
77 never,
78 Providers
79 >;
80
81 /**
82 * The Cloudflare Email Routing catch-all rule for a zone.
83 *
84 * The catch-all rule handles every inbound email that no other routing
85 * rule matched. It is a per-zone singleton — once Email Routing is enabled
86 * the rule always exists (disabled, dropping mail, by default), so this
87 * resource never creates or deletes anything physical. Reconcile `PUT`s the
88 * desired configuration; destroy restores the configuration the rule had
89 * before Alchemy first managed it.
90 *
91 * Email Routing must be enabled on the zone first (see
92 * `Cloudflare.Email.Routing`), and `forward` actions require the destination
93 * address to be verified (see `Cloudflare.Email.Address`).
94 * ### Catching unmatched mail
95 * **Example:** Forward everything else to a verified destination
96 * ```typescript
97 * const routing = yield* Cloudflare.Email.Routing("Routing", {
98 * zone: "example.com",
99 * });
100 *
101 * yield* Cloudflare.Email.CatchAll("CatchAll", {
102 * zone: routing.zoneId,
103 * actions: [{ type: "forward", value: ["ops@example.com"] }],
104 * });
105 * ```
106 *
107 * **Example:** Silently drop unmatched mail
108 * ```typescript
109 * yield* Cloudflare.Email.CatchAll("DropTheRest", {
110 * zone: routing.zoneId,
111 * name: "drop unmatched",
112 * actions: [{ type: "drop" }],
113 * });
114 * ```
115 *
116 * ### Workers
117 * **Example:** Hand unmatched mail to an email Worker
118 * ```typescript
119 * yield* Cloudflare.Email.CatchAll("CatchAllWorker", {
120 * zone: routing.zoneId,
121 * actions: [{ type: "worker", value: ["my-email-worker"] }],
122 * });
123 * ```
124 *
125 * @resource
126 * @product Email
127 * @category Email
128 */
129 export const CatchAll = Resource<CatchAll>(CatchAllTypeId, {
130 aliases: ["Cloudflare.EmailCatchAll"],
131 });
132
133 /**
134 * Returns true if the given value is an CatchAll resource.
135 */
136 export const isCatchAll = (value: unknown): value is CatchAll =>
137 Predicate.hasProperty(value, "Type") && value.Type === CatchAllTypeId;
138
139 export const CatchAllProvider = () =>
140 Provider.succeed(CatchAll, {
141 nuke: { singleton: true },
142 stables: ["ruleId", "zoneId", "initialName", "initialEnabled", "initialActions"],
143
144 list: Effect.fn(function* () {
145 const { accountId } = yield* yield* CloudflareEnvironment;
146 // The catch-all rule is a per-zone singleton with no account-wide
147 // enumeration API — enumerate every zone and read its rule. The
148 // observed state at read time is the initial* baseline.
149 const allZones = yield* listAllZones(accountId);
150 const rows = yield* Effect.forEach(
151 allZones.map((zone) => zone.id),
152 (zoneId) =>
153 emailRouting.getRuleCatchAll({ zoneId }).pipe(
154 Effect.map((observed) => toAttributes(zoneId, observed, observedInitial(observed))),
155 // Zones without Email Routing enabled (or that the token can no
156 // longer see) reject the route; skip them.
157 Effect.catchTag("Forbidden", () => Effect.undefined),
158 ),
159 { concurrency: 10 },
160 );
161 return rows.filter((row): row is CatchAllAttributes => row !== undefined);
162 }),
163
164 diff: Effect.fn(function* ({ news, output }) {
165 if (!output) return undefined;
166 if (!isResolved(news)) return undefined;
167 const zoneId = yield* resolve(news.zone);
168 if (zoneId !== output.zoneId) {
169 // Different zone = different singleton.
170 return { action: "replace" } as const;
171 }
172 return undefined;
173 }),
174
175 read: Effect.fn(function* ({ output, olds }) {
176 const zoneId =
177 // `olds.zone` may be `undefined` when a `creating` row was persisted
178 // before upstream Outputs resolved — report "not found" then.
179 output?.zoneId ?? (olds?.zone !== undefined ? yield* resolve(olds.zone) : undefined);
180 if (!zoneId) return undefined;
181 const observed = yield* emailRouting.getRuleCatchAll({ zoneId }).pipe(
182 // Zone deleted out-of-band (or the token can no longer see it) —
183 // the catch-all rule is gone with it.
184 Effect.catchTag("Forbidden", () => Effect.undefined),
185 );
186 if (observed === undefined) return undefined;
187 // The catch-all rule is a singleton that always exists once Email
188 // Routing is enabled — there is nothing to "own", so a cold read
189 // adopts freely (never `Unowned`). The observed state at adoption
190 // time becomes the initial* baseline restored on destroy.
191 const initial = output ?? observedInitial(observed);
192 return toAttributes(zoneId, observed, initial);
193 }),
194
195 reconcile: Effect.fn(function* ({ news, output }) {
196 // 1. Observe — the catch-all rule always exists once Email Routing
197 // is enabled on the zone; read its live state.
198 const zoneId = output?.zoneId ?? (yield* resolve(news.zone));
199 const observed = yield* emailRouting.getRuleCatchAll({ zoneId });
200
201 // 2. Capture — the pre-management state, restored on destroy.
202 // `output` (including an adoption read) already carries it;
203 // otherwise this is our first touch and the observed state is
204 // the zone's original.
205 const initial = output ?? observedInitial(observed);
206
207 // 3. Sync — PUT only when the observed state differs from desired.
208 const desiredEnabled = news.enabled ?? true;
209 const desiredName = news.name ?? observed.name ?? "";
210 if (
211 (observed.enabled ?? false) === desiredEnabled &&
212 (observed.name ?? "") === desiredName &&
213 actionsEqual(normalizeActions(observed.actions), news.actions)
214 ) {
215 return toAttributes(zoneId, observed, initial);
216 }
217 const result = yield* emailRouting
218 .putRuleCatchAll({
219 zoneId,
220 matchers: [{ type: "all" }],
221 actions: news.actions.map((a) =>
222 a.type === "drop" ? { type: a.type } : { type: a.type, value: a.value },
223 ),
224 enabled: desiredEnabled,
225 name: desiredName,
226 })
227 .pipe(retryWorkerScriptNotFound);
228 return toAttributes(zoneId, result, initial);
229 }),
230
231 delete: Effect.fn(function* ({ output }) {
232 const { zoneId, initialName, initialEnabled, initialActions } = output;
233 // Observe — if the zone itself is gone, so is the catch-all rule.
234 const observed = yield* emailRouting
235 .getRuleCatchAll({ zoneId })
236 .pipe(Effect.catchTag("Forbidden", () => Effect.undefined));
237 if (observed === undefined) return;
238 // Restore the pre-management state; skip the call when it already
239 // matches (idempotent re-delete after a crashed run).
240 if (
241 (observed.enabled ?? false) === initialEnabled &&
242 (observed.name ?? "") === initialName &&
243 actionsEqual(normalizeActions(observed.actions), initialActions)
244 ) {
245 return;
246 }
247 yield* emailRouting
248 .putRuleCatchAll({
249 zoneId,
250 matchers: [{ type: "all" }],
251 actions: initialActions.map((a) =>
252 a.type === "drop" ? { type: a.type } : { type: a.type, value: a.value },
253 ),
254 enabled: initialEnabled,
255 name: initialName,
256 })
257 .pipe(
258 Effect.catchTag("Forbidden", () => Effect.void),
259 // The captured action may name something that no longer exists:
260 // an unverified/removed destination address, or — after the
261 // Worker it pointed at was replaced or deleted — a missing
262 // script. Neither is retryable and neither should strand the
263 // destroy, so fall back to the Cloudflare default (disabled,
264 // drop) instead of failing.
265 Effect.catchTag(["DestinationNotVerified", "WorkerScriptNotFound"], () =>
266 emailRouting
267 .putRuleCatchAll({
268 zoneId,
269 matchers: [{ type: "all" }],
270 actions: [{ type: "drop" }],
271 enabled: false,
272 name: initialName,
273 })
274 .pipe(Effect.catchTag("Forbidden", () => Effect.void)),
275 ),
276 );
277 }),
278 });
279
280 type ObservedCatchAll = emailRouting.GetRuleCatchAllResponse | emailRouting.PutRuleCatchAllResponse;
281
282 const normalizeActions = (actions: ObservedCatchAll["actions"]): Action[] =>
283 (actions ?? []).map((a): Action =>
284 a.type === "drop"
285 ? { type: "drop" }
286 : a.type === "forward"
287 ? { type: "forward", value: [...(a.value ?? [])] }
288 : { type: "worker", value: [...(a.value ?? [])] },
289 );
290
291 const actionsEqual = (a: Action[], b: Action[]): boolean =>
292 a.length === b.length &&
293 a.every((x, i) => {
294 const y = b[i]!;
295 if (x.type !== y.type) return false;
296 const xv = x.type === "drop" ? [] : x.value;
297 const yv = y.type === "drop" ? [] : y.value;
298 return xv.length === yv.length && xv.every((v, j) => v === yv[j]);
299 });
300
301 const observedInitial = (observed: ObservedCatchAll) => ({
302 initialName: observed.name ?? "",
303 initialEnabled: observed.enabled ?? false,
304 initialActions: normalizeActions(observed.actions),
305 });
306
307 const toAttributes = (
308 zoneId: string,
309 observed: ObservedCatchAll,
310 initial: {
311 initialName: string;
312 initialEnabled: boolean;
313 initialActions: Action[];
314 },
315 ): CatchAllAttributes => ({
316 ruleId: observed.id ?? "",
317 zoneId,
318 name: observed.name ?? "",
319 enabled: observed.enabled ?? false,
320 actions: normalizeActions(observed.actions),
321 initialName: initial.initialName,
322 initialEnabled: initial.initialEnabled,
323 initialActions: initial.initialActions,
324 });
325
326 const resolve = Effect.fn(function* (zone: Reference) {
327 const { accountId } = yield* yield* CloudflareEnvironment;
328 return yield* resolveZoneId({
329 accountId,
330 zone,
331 hostname: typeof zone === "string" ? zone : (zone.name ?? ""),
332 });
333 });