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

main
ts 269 lines 9.57 KB
Raw
1 import * as emailSecurity from "@distilled.cloud/cloudflare/email-security";
2 import { Unowned } from "alchemy/AdoptPolicy";
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 * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const EmailSecurityTrustedDomainTypeId = "Cloudflare.Email.TrustedDomain" as const;
12 type EmailSecurityTrustedDomainTypeId = typeof EmailSecurityTrustedDomainTypeId;
13
14 export interface TrustedDomainProps {
15 /**
16 * The domain (or regular expression) to trust. The pattern is the
17 * entry's identity for cold-state recovery — a pre-existing entry with
18 * the same pattern is reported as unowned and only taken over when
19 * adoption is enabled.
20 */
21 pattern: string;
22 /**
23 * Prevents recently registered domains from triggering a Suspicious or
24 * Malicious disposition.
25 * @default false
26 */
27 isRecent?: boolean;
28 /**
29 * For partner or other approved domains with similar spelling to your
30 * connected domains — prevents the listed domains from triggering a
31 * Spoof disposition.
32 * @default false
33 */
34 isSimilarity?: boolean;
35 /**
36 * Whether `pattern` is a regular expression.
37 * @default false
38 */
39 isRegex?: boolean;
40 /**
41 * Free-form notes about the trusted domain.
42 */
43 comments?: string;
44 }
45
46 export interface TrustedDomainAttributes {
47 /** Cloudflare-assigned trusted domain identifier. */
48 trustedDomainId: string;
49 /** The account the entry belongs to. */
50 accountId: string;
51 /** The trusted domain pattern. */
52 pattern: string;
53 /** Whether recently registered domain protection is disabled. */
54 isRecent: boolean;
55 /** Whether lookalike/partner domain Spoof protection is disabled. */
56 isSimilarity: boolean;
57 /** Whether the pattern is a regular expression. */
58 isRegex: boolean;
59 /** Free-form notes about the entry, if set. */
60 comments: string | undefined;
61 /** ISO8601 creation timestamp. */
62 createdAt: string;
63 /** ISO8601 last-modified timestamp, if the entry has been modified. */
64 modifiedAt: string | undefined;
65 }
66
67 export type TrustedDomain = Resource<
68 EmailSecurityTrustedDomainTypeId,
69 TrustedDomainProps,
70 TrustedDomainAttributes,
71 never,
72 Providers
73 >;
74
75 /**
76 * A Cloudflare Email Security (Area 1) trusted domain — exempts a domain
77 * from recently-registered and lookalike (similarity) detections.
78 *
79 * All fields are mutable in place. Requires the Email Security enterprise
80 * add-on; accounts without the entitlement receive the typed
81 * `EmailSecurityNotEntitled` error.
82 * ### Trusting Domains
83 * **Example:** Trust a partner domain with similar spelling
84 * ```typescript
85 * yield* Cloudflare.Email.TrustedDomain("PartnerLookalike", {
86 * pattern: "examp1e-partner.com",
87 * isSimilarity: true,
88 * comments: "legitimate partner domain",
89 * });
90 * ```
91 *
92 * **Example:** Trust a recently registered domain
93 * ```typescript
94 * yield* Cloudflare.Email.TrustedDomain("NewSubsidiary", {
95 * pattern: "brand-new-subsidiary.example",
96 * isRecent: true,
97 * });
98 * ```
99 *
100 * @see https://developers.cloudflare.com/cloudflare-one/email-security/
101 *
102 * @resource
103 * @product Email Security
104 * @category Email
105 */
106 export const TrustedDomain = Resource<TrustedDomain>(EmailSecurityTrustedDomainTypeId, {
107 aliases: ["Cloudflare.EmailSecurity.TrustedDomain"],
108 });
109
110 /**
111 * Returns true if the given value is an TrustedDomain resource.
112 */
113 export const isTrustedDomain = (value: unknown): value is TrustedDomain =>
114 Predicate.hasProperty(value, "Type") && value.Type === EmailSecurityTrustedDomainTypeId;
115
116 export const TrustedDomainProvider = () =>
117 Provider.succeed(TrustedDomain, {
118 stables: ["trustedDomainId", "accountId", "createdAt"],
119
120 // Account-scoped collection. Exhaustively paginate the account's trusted
121 // domains and hydrate each into the `read` Attributes shape. Accounts
122 // without the Email Security add-on surface the typed
123 // `EmailSecurityNotEntitled` error — treat that as an empty enumeration.
124 list: Effect.fn(function* () {
125 const { accountId } = yield* yield* CloudflareEnvironment;
126 return yield* emailSecurity.listSettingTrustedDomains.pages({ accountId }).pipe(
127 Stream.runCollect,
128 Effect.map((chunk) =>
129 Array.from(chunk).flatMap((page) =>
130 (page.result ?? []).map((entry) => toAttributes(entry, accountId)),
131 ),
132 ),
133 // Email Security is a paid add-on gated by both account
134 // entitlement and token scope: an unentitled account answers
135 // `EmailSecurityNotEntitled`, while a credential lacking the
136 // Email Security scope (e.g. Cloudflare OAuth) answers a bare
137 // `Forbidden`. Neither can enumerate, so both mean "none
138 // visible" — matching `Domain.list()`. Returning `[]` is the
139 // safe direction for the callers of `list` (orphan detection
140 // never deletes what it cannot see).
141 Effect.catchTag(["EmailSecurityNotEntitled", "Forbidden"], () =>
142 Effect.succeed([] as TrustedDomainAttributes[]),
143 ),
144 );
145 }),
146
147 read: Effect.fn(function* ({ output, olds }) {
148 const { accountId } = yield* yield* CloudflareEnvironment;
149 const acct = output?.accountId ?? accountId;
150
151 // Owned path: refresh by the persisted entry id.
152 if (output?.trustedDomainId) {
153 const observed = yield* getTrustedDomain(acct, output.trustedDomainId);
154 if (observed) return toAttributes(observed, acct);
155 }
156
157 // Cold lookup: recover by pattern; matches are reported as `Unowned`
158 // so takeover is gated behind the adopt policy.
159 const pattern = output?.pattern ?? olds?.pattern;
160 if (pattern !== undefined) {
161 const observed = yield* findByPattern(acct, pattern);
162 if (observed) return Unowned(toAttributes(observed, acct));
163 }
164 return undefined;
165 }),
166
167 reconcile: Effect.fn(function* ({ news, output }) {
168 const { accountId } = yield* yield* CloudflareEnvironment;
169
170 // 1. Observe — id hint first, then pattern scan.
171 let observed = output?.trustedDomainId
172 ? yield* getTrustedDomain(accountId, output.trustedDomainId)
173 : undefined;
174 if (!observed) {
175 observed = yield* findByPattern(accountId, news.pattern);
176 }
177
178 // 2. Ensure — create when missing.
179 if (!observed) {
180 const created = yield* emailSecurity.createSettingTrustedDomain({
181 accountId,
182 pattern: news.pattern,
183 isRecent: news.isRecent ?? false,
184 isSimilarity: news.isSimilarity ?? false,
185 isRegex: news.isRegex ?? false,
186 comments: news.comments,
187 });
188 return toAttributes(created, accountId);
189 }
190
191 // 3. Sync — patch only on a delta.
192 const dirty =
193 (observed.pattern ?? "") !== news.pattern ||
194 (observed.isRecent ?? false) !== (news.isRecent ?? false) ||
195 (observed.isSimilarity ?? false) !== (news.isSimilarity ?? false) ||
196 (observed.isRegex ?? false) !== (news.isRegex ?? false) ||
197 (news.comments !== undefined && (observed.comments ?? "") !== news.comments);
198 if (!dirty) {
199 return toAttributes(observed, accountId);
200 }
201
202 const patched = yield* emailSecurity.patchSettingTrustedDomain({
203 accountId,
204 trustedDomainId: observed.id ?? "",
205 pattern: news.pattern,
206 isRecent: news.isRecent ?? false,
207 isSimilarity: news.isSimilarity ?? false,
208 isRegex: news.isRegex ?? false,
209 comments: news.comments,
210 });
211 return toAttributes(patched, accountId);
212 }),
213
214 delete: Effect.fn(function* ({ output }) {
215 yield* emailSecurity
216 .deleteSettingTrustedDomain({
217 accountId: output.accountId,
218 trustedDomainId: output.trustedDomainId,
219 })
220 .pipe(Effect.catchTag("TrustedDomainNotFound", () => Effect.void));
221 }),
222 });
223
224 type ObservedTrustedDomain = emailSecurity.GetSettingTrustedDomainResponse;
225
226 /**
227 * Read a trusted domain by id, mapping "gone" (`TrustedDomainNotFound`,
228 * HTTP 404) to `undefined`.
229 */
230 const getTrustedDomain = (accountId: string, trustedDomainId: string) =>
231 emailSecurity.getSettingTrustedDomain({ accountId, trustedDomainId }).pipe(
232 Effect.map((entry): ObservedTrustedDomain | undefined => entry),
233 Effect.catchTag("TrustedDomainNotFound", () => Effect.undefined),
234 );
235
236 /**
237 * Find a trusted domain by exact pattern. The `pattern` query filter is a
238 * server-side hint; the exact match is re-checked client-side. Picks the
239 * oldest match for determinism.
240 */
241 const findByPattern = (accountId: string, pattern: string) =>
242 emailSecurity.listSettingTrustedDomains.items({ accountId, pattern }).pipe(
243 Stream.runCollect,
244 Effect.map((chunk) =>
245 Array.from(chunk)
246 .filter((entry) => entry.pattern === pattern)
247 .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""))
248 .at(0),
249 ),
250 );
251
252 const toAttributes = (
253 entry:
254 | ObservedTrustedDomain
255 | emailSecurity.CreateSettingTrustedDomainResponse
256 | emailSecurity.PatchSettingTrustedDomainResponse
257 | emailSecurity.ListSettingTrustedDomainsResponse["result"][number],
258 accountId: string,
259 ): TrustedDomainAttributes => ({
260 trustedDomainId: entry.id ?? "",
261 accountId,
262 pattern: entry.pattern ?? "",
263 isRecent: entry.isRecent ?? false,
264 isSimilarity: entry.isSimilarity ?? false,
265 isRegex: entry.isRegex ?? false,
266 comments: entry.comments ?? undefined,
267 createdAt: entry.createdAt ?? "",
268 modifiedAt: entry.modifiedAt ?? undefined,
269 });