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

main
ts 425 lines 15.3 KB
Raw
1 import * as emailRouting from "@distilled.cloud/cloudflare/email-routing";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { resolveZoneId, type Reference } from "../Zone/index.ts";
13 import { listAllZones } from "../Zone/lookup.ts";
14 import { retryWorkerScriptNotFound } from "./retry.ts";
15
16 export type Matcher = { type: "all" } | { type: "literal"; field: "to"; value: string };
17
18 export type Action =
19 | { type: "drop" }
20 | { type: "forward"; value: string[] }
21 | { type: "worker"; value: string[] };
22
23 export type RuleProps = {
24 /**
25 * Zone the rule lives on.
26 */
27 zone: Reference;
28 /**
29 * Display name for the rule.
30 */
31 name?: string;
32 /**
33 * Whether the rule is active. Disabled rules are evaluated last and
34 * effectively skipped.
35 *
36 * @default true
37 */
38 enabled?: boolean;
39 /**
40 * Lower priority numbers run first.
41 *
42 * @default 0
43 */
44 priority?: number;
45 /**
46 * Matchers that define which inbound emails trigger this rule.
47 *
48 * A sole `{ type: "all" }` matcher is the zone catch-all, which is a
49 * per-zone singleton owned by `Cloudflare.Email.CatchAll` — declaring
50 * it here fails with `CatchAllRuleNotSupported`.
51 */
52 matchers: Matcher[];
53 /**
54 * Actions to take for matched emails.
55 */
56 actions: Action[];
57 };
58
59 export type Rule = Resource<
60 "Cloudflare.Email.Rule",
61 RuleProps,
62 {
63 ruleId: string;
64 zoneId: string;
65 name: string;
66 enabled: boolean;
67 priority: number;
68 matchers: Matcher[];
69 actions: Action[];
70 },
71 never,
72 Providers
73 >;
74
75 /**
76 * Raised when `Cloudflare.Email.Rule` is declared with a sole
77 * `{ type: "all" }` matcher. Cloudflare models the zone catch-all as a
78 * singleton behind `PUT /zones/{zone_id}/email/routing/rules/catch_all`
79 * and rejects creating a second one through the ordinary rule endpoint
80 * (`Conflict: Invalid rule operation`). Use `Cloudflare.Email.CatchAll`.
81 */
82 export class CatchAllRuleNotSupported extends Data.TaggedError("CatchAllRuleNotSupported")<{
83 message: string;
84 }> {}
85
86 /**
87 * A Cloudflare Email Routing rule.
88 *
89 * Rules forward inbound mail matching `matchers` to the listed actions
90 * (forward to a verified destination, drop, or hand off to a Worker).
91 *
92 * Safety: routing rules carry no ownership markers. When there is no
93 * prior state, `read` scans the zone for an existing non-catch-all rule
94 * with the same matchers and reports it as `Unowned`, so the engine
95 * refuses to take it over unless `--adopt` (or `adopt(true)`) is set.
96 * The zone catch-all is excluded from that scan — it is owned by
97 * `Email.CatchAll`.
98 * ### Forwarding Mail
99 * **Example:** Forward `info@` to a verified destination
100 * ```typescript
101 * const rule = yield* Cloudflare.Email.Rule("InfoForward", {
102 * zone: "example.com",
103 * matchers: [{ type: "literal", field: "to", value: "info@example.com" }],
104 * actions: [{ type: "forward", value: ["ops@example.com"] }],
105 * });
106 * ```
107 *
108 * ### Catch-all mail
109 * The zone catch-all is a per-zone singleton managed by
110 * `Cloudflare.Email.CatchAll` (PUT `/rules/catch_all`). Declaring
111 * `matchers: [{ type: "all" }]` on a Rule fails with
112 * `CatchAllRuleNotSupported` — Cloudflare rejects creating a second
113 * catch-all through the ordinary rule endpoint.
114 *
115 * **Example:** Use CatchAll for unmatched mail
116 * ```typescript
117 * yield* Cloudflare.Email.CatchAll("CatchAll", {
118 * zone: "example.com",
119 * actions: [{ type: "drop" }],
120 * });
121 * ```
122 *
123 * @resource
124 * @product Email
125 * @category Email
126 */
127 export const Rule = Resource<Rule>("Cloudflare.Email.Rule", {
128 aliases: ["Cloudflare.EmailRule"],
129 });
130
131 export const RuleProvider = () =>
132 Provider.succeed(Rule, {
133 stables: ["ruleId", "zoneId"],
134 list: Effect.fn(function* () {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136 // Email routing rules are zone-scoped (`/zones/{id}/email/routing/rules`)
137 // with no account-wide enumeration API — fan out over every zone and
138 // exhaustively paginate each zone's rules.
139 const zones = yield* listAllZones(accountId);
140 const rows = yield* Effect.forEach(
141 zones,
142 (zone) =>
143 emailRouting.listRules.pages({ zoneId: zone.id }).pipe(
144 Stream.runCollect,
145 Effect.map((chunk) =>
146 Array.from(chunk).flatMap((page) =>
147 (page.result ?? [])
148 // Cloudflare returns the zone's catch-all rule in this list,
149 // but it's a managed singleton (owned by `CatchAll`, via
150 // `/rules/catch_all`) and rejects deletion through the regular
151 // rule endpoint ("Invalid rule operation"). Identify it by its
152 // sole `{ type: "all" }` matcher and exclude it.
153 .filter((rule) => !isCatchAllRule(rule))
154 .map((rule) => normalize(rule, zone.id)),
155 ),
156 ),
157 // Zones without email routing (or otherwise non-routable) reject
158 // the route; skip them rather than failing the whole listing.
159 Effect.catchTag("InvalidRoute", () => Effect.succeed([])),
160 ),
161 { concurrency: 10 },
162 );
163 return rows.flat();
164 }),
165 diff: Effect.fn(function* ({ news, output }) {
166 if (!output) return undefined;
167 if (!isResolved(news)) return undefined;
168 const zoneId = yield* resolve(news.zone);
169 if (zoneId !== output.zoneId) {
170 return { action: "replace" } as const;
171 }
172 return undefined;
173 }),
174 read: Effect.fn(function* ({ output, olds }) {
175 const zoneId =
176 output?.zoneId ?? (olds?.zone !== undefined ? yield* resolve(olds.zone) : undefined);
177 if (!zoneId) return undefined;
178
179 // Owned path: refresh by our persisted rule id. A catch-all id is
180 // treated as missing — that singleton is owned by `CatchAll`.
181 if (output?.ruleId) {
182 const observed = yield* observeById(zoneId, output.ruleId);
183 if (observed) return observed;
184 }
185
186 // Adoption path: Cloudflare uniqueness is by matcher shape, and
187 // rules carry no ownership markers, so brand a match `Unowned`.
188 // Never adopt the zone catch-all this way.
189 const matchers = output?.matchers ?? asMatchers(olds?.matchers);
190 if (matchers && !isCatchAllMatchers(matchers)) {
191 const observed = yield* findByMatchers(zoneId, matchers);
192 if (observed) return Unowned(observed);
193 }
194 return undefined;
195 }),
196 reconcile: Effect.fn(function* ({ news, output }) {
197 const zoneId = output?.zoneId ?? (yield* resolve(news.zone));
198 const desired = toDesired(news);
199
200 // The zone catch-all is a singleton behind `/rules/catch_all`.
201 // Creating it as an ordinary rule 409s ("Invalid rule operation")
202 // and deleting it through the rule endpoint does the same — refuse
203 // before any write and point at `Email.CatchAll`.
204 if (isCatchAllMatchers(desired.matchers)) {
205 return yield* new CatchAllRuleNotSupported({
206 message:
207 'Cloudflare.Email.Rule cannot manage the zone catch-all (matchers: [{ type: "all" }]). ' +
208 "Cloudflare models that as a per-zone singleton behind PUT /zones/{zone_id}/email/routing/rules/catch_all. " +
209 "Use Cloudflare.Email.CatchAll instead.",
210 });
211 }
212
213 // 1. Observe — cached id is a hint, not a guarantee the rule still
214 // exists. A missing id falls through to the matcher scan.
215 let observed = output?.ruleId ? yield* observeById(zoneId, output.ruleId) : undefined;
216
217 // 2. Fall back to scanning the zone for the same matchers.
218 // `read` brands an existing match `Unowned` so the engine can
219 // gate takeover behind adopt — but plan skips that probe when
220 // props are still unresolved (e.g. `zone: routing.zoneId` from
221 // a sibling created in the same deploy). In that case this scan
222 // is the AlreadyExists race: Cloudflare rejects a second rule
223 // with the same literal matchers, so converging on the match is
224 // the same as catching Conflict and re-listing.
225 if (!observed) {
226 observed = yield* findByMatchers(zoneId, desired.matchers);
227 }
228
229 // 3. Ensure — create when missing. The rejected call creates
230 // nothing, so a Worker-script retry cannot duplicate the rule.
231 if (!observed) {
232 const created = yield* emailRouting
233 .createRule({
234 zoneId,
235 actions: desired.actions.map(toActionBody),
236 matchers: desired.matchers.map(toMatcherBody),
237 enabled: desired.enabled,
238 name: desired.name,
239 priority: desired.priority,
240 })
241 .pipe(retryWorkerScriptNotFound);
242 observed = normalize(created, zoneId);
243 }
244
245 // 4. Sync — PUT the full desired body when observed state drifts.
246 if (!sameRule(observed, desired)) {
247 const updated = yield* emailRouting
248 .updateRule({
249 zoneId,
250 ruleIdentifier: observed.ruleId,
251 actions: desired.actions.map(toActionBody),
252 matchers: desired.matchers.map(toMatcherBody),
253 enabled: desired.enabled,
254 name: desired.name,
255 priority: desired.priority,
256 })
257 .pipe(retryWorkerScriptNotFound);
258 observed = normalize(updated, zoneId);
259 }
260
261 return observed;
262 }),
263 delete: Effect.fn(function* ({ output }) {
264 if (!output?.ruleId) return;
265 // Never attempt to delete the zone catch-all through this endpoint
266 // — Cloudflare rejects it with "Invalid rule operation".
267 if (isCatchAllMatchers(output.matchers)) return;
268 // Idempotent: a rule that's already gone is success. Any other error
269 // (e.g. a 409 because email routing is disabled) must surface so the
270 // engine reports the failure instead of falsely claiming deletion.
271 yield* emailRouting
272 .deleteRule({
273 zoneId: output.zoneId,
274 ruleIdentifier: output.ruleId,
275 })
276 .pipe(Effect.catchTag("EmailRoutingRuleNotFound", () => Effect.void));
277 }),
278 });
279
280 /**
281 * The zone catch-all rule is surfaced by `listRules` but is a managed
282 * singleton — its sole matcher is `{ type: "all" }`. It can only be mutated
283 * via `/rules/catch_all` (the `CatchAll` resource), so it must be
284 * excluded from the deletable `Rule` enumeration.
285 */
286 const isCatchAllRule = (rule: { matchers?: { type: string }[] | null }): boolean =>
287 (rule.matchers ?? []).length === 1 && rule.matchers?.[0]?.type === "all";
288
289 const isCatchAllMatchers = (matchers: Matcher[]): boolean =>
290 matchers.length === 1 && matchers[0]?.type === "all";
291
292 // `olds.matchers` may still be unresolved Inputs after stripUnresolved;
293 // only treat a concrete array as matcher identity for the adoption scan.
294 const asMatchers = (value: unknown): Matcher[] | undefined =>
295 Array.isArray(value) ? (value as Matcher[]) : undefined;
296
297 type RuleAttributes = {
298 ruleId: string;
299 zoneId: string;
300 name: string;
301 enabled: boolean;
302 priority: number;
303 matchers: Matcher[];
304 actions: Action[];
305 };
306
307 const toDesired = (news: RuleProps): Omit<RuleAttributes, "ruleId" | "zoneId"> => ({
308 name: news.name ?? "",
309 enabled: news.enabled ?? true,
310 priority: news.priority ?? 0,
311 matchers: news.matchers.map((m): Matcher =>
312 m.type === "all" ? { type: "all" } : { type: "literal", field: "to", value: m.value },
313 ),
314 actions: news.actions.map((a): Action =>
315 a.type === "drop"
316 ? { type: "drop" }
317 : a.type === "forward"
318 ? { type: "forward", value: a.value }
319 : { type: "worker", value: a.value },
320 ),
321 });
322
323 const toMatcherBody = (m: Matcher) =>
324 m.type === "all"
325 ? { type: "all" as const }
326 : { type: "literal" as const, field: "to" as const, value: m.value };
327
328 const toActionBody = (a: Action) =>
329 a.type === "drop" ? { type: a.type } : { type: a.type, value: a.value };
330
331 const matchersEqual = (a: Matcher[], b: Matcher[]): boolean =>
332 a.length === b.length &&
333 a.every((x, i) => {
334 const y = b[i]!;
335 if (x.type !== y.type) return false;
336 if (x.type === "all") return true;
337 return y.type === "literal" && x.field === y.field && x.value === y.value;
338 });
339
340 const actionsEqual = (a: Action[], b: Action[]): boolean =>
341 a.length === b.length &&
342 a.every((x, i) => {
343 const y = b[i]!;
344 if (x.type !== y.type) return false;
345 const xv = x.type === "drop" ? [] : x.value;
346 const yv = y.type === "drop" ? [] : y.value;
347 return xv.length === yv.length && xv.every((v, j) => v === yv[j]);
348 });
349
350 const sameRule = (
351 observed: RuleAttributes,
352 desired: Omit<RuleAttributes, "ruleId" | "zoneId">,
353 ): boolean =>
354 observed.enabled === desired.enabled &&
355 observed.name === desired.name &&
356 observed.priority === desired.priority &&
357 matchersEqual(observed.matchers, desired.matchers) &&
358 actionsEqual(observed.actions, desired.actions);
359
360 const normalize = (
361 rule: {
362 id?: string | null;
363 name?: string | null;
364 enabled?: boolean | null;
365 priority?: number | null;
366 // Distilled widened generated string enums to open unions (`string & {}`);
367 // the runtime values are still the known variants, narrowed below.
368 matchers?:
369 | {
370 type: string;
371 field?: string | null;
372 value?: string | null;
373 }[]
374 | null;
375 actions?: { type: string; value?: string[] | null }[] | null;
376 },
377 zoneId: string,
378 ): RuleAttributes => ({
379 ruleId: rule.id ?? "",
380 zoneId,
381 name: rule.name ?? "",
382 enabled: rule.enabled ?? true,
383 priority: rule.priority ?? 0,
384 matchers: (rule.matchers ?? []).map((m): Matcher =>
385 m.type === "all" ? { type: "all" } : { type: "literal", field: "to", value: m.value ?? "" },
386 ),
387 actions: (rule.actions ?? []).map((a): Action =>
388 a.type === "drop"
389 ? { type: "drop" }
390 : a.type === "forward"
391 ? { type: "forward", value: a.value ?? [] }
392 : { type: "worker", value: a.value ?? [] },
393 ),
394 });
395
396 const observeById = (zoneId: string, ruleId: string) =>
397 emailRouting.getRule({ zoneId, ruleIdentifier: ruleId }).pipe(
398 Effect.map((rule) => (isCatchAllRule(rule) ? undefined : normalize(rule, zoneId))),
399 Effect.catchTag(["EmailRoutingRuleNotFound", "Forbidden"], () => Effect.undefined),
400 );
401
402 /**
403 * Locate an existing non-catch-all rule by matcher identity. Cloudflare
404 * rejects a second catch-all and treats matcher shape as the rule's
405 * identity, so a match is the same logical rule.
406 */
407 const findByMatchers = (zoneId: string, matchers: Matcher[]) =>
408 emailRouting.listRules.items({ zoneId }).pipe(
409 Stream.filter(
410 (rule) => !isCatchAllRule(rule) && matchersEqual(normalize(rule, zoneId).matchers, matchers),
411 ),
412 Stream.runHead,
413 Effect.map(Option.getOrUndefined),
414 Effect.map((rule) => (rule ? normalize(rule, zoneId) : undefined)),
415 Effect.catchTag("InvalidRoute", () => Effect.undefined),
416 );
417
418 const resolve = Effect.fn(function* (zone: Reference) {
419 const { accountId } = yield* yield* CloudflareEnvironment;
420 return yield* resolveZoneId({
421 accountId,
422 zone,
423 hostname: typeof zone === "string" ? zone : (zone.name ?? ""),
424 });
425 });