The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as emailSecurity from "@distilled.cloud/cloudflare/email-security"; |
| 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 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 | |
| 13 | export class EmailDomainInvalidProps extends Data.TaggedError("EmailDomainInvalidProps")<{ |
| 14 | readonly message: string; |
| 15 | readonly cause?: unknown; |
| 16 | }> {} |
| 17 | |
| 18 | const EmailSecurityDomainTypeId = "Cloudflare.Email.Domain" as const; |
| 19 | type EmailSecurityDomainTypeId = typeof EmailSecurityDomainTypeId; |
| 20 | |
| 21 | /** |
| 22 | * Delivery modes a domain accepts messages through. |
| 23 | */ |
| 24 | export type DeliveryMode = "DIRECT" | "BCC" | "JOURNAL" | "API" | "RETRO_SCAN"; |
| 25 | |
| 26 | /** |
| 27 | * Message dispositions that can be dropped before delivery. |
| 28 | */ |
| 29 | export type DropDisposition = |
| 30 | | "MALICIOUS" |
| 31 | | "MALICIOUS-BEC" |
| 32 | | "SUSPICIOUS" |
| 33 | | "SPOOF" |
| 34 | | "SPAM" |
| 35 | | "BULK" |
| 36 | | "ENCRYPTED" |
| 37 | | "EXTERNAL" |
| 38 | | "UNKNOWN" |
| 39 | | "NONE"; |
| 40 | |
| 41 | export interface DomainProps { |
| 42 | /** |
| 43 | * The fully-qualified domain name of a domain that is **already |
| 44 | * onboarded** to Email Security (via MX/BCC/journal or an API |
| 45 | * integration). Domains cannot be created via the API — onboarding |
| 46 | * happens in the Email Security dashboard. The domain name is the |
| 47 | * resource's identity — changing it triggers a replacement (re-adopting |
| 48 | * a different domain). |
| 49 | */ |
| 50 | domain: string; |
| 51 | /** |
| 52 | * Delivery modes the domain accepts messages through. |
| 53 | */ |
| 54 | allowedDeliveryModes?: DeliveryMode[]; |
| 55 | /** |
| 56 | * Message dispositions that are dropped before delivery. |
| 57 | */ |
| 58 | dropDispositions?: DropDisposition[]; |
| 59 | /** |
| 60 | * IP/CIDR restrictions for inbound delivery. |
| 61 | */ |
| 62 | ipRestrictions?: string[]; |
| 63 | /** |
| 64 | * Folder messages are scanned in for API-deployed domains. |
| 65 | */ |
| 66 | folder?: "AllItems" | "Inbox"; |
| 67 | /** |
| 68 | * The API integration (e.g. Office 365) the domain is associated with. |
| 69 | */ |
| 70 | integrationId?: string; |
| 71 | /** |
| 72 | * Number of message hops to look back when determining the original |
| 73 | * sender. |
| 74 | */ |
| 75 | lookbackHops?: number; |
| 76 | /** |
| 77 | * Require TLS for inbound mail. |
| 78 | */ |
| 79 | requireTlsInbound?: boolean; |
| 80 | /** |
| 81 | * Require TLS for outbound (onward) delivery. |
| 82 | */ |
| 83 | requireTlsOutbound?: boolean; |
| 84 | /** |
| 85 | * Onward delivery host for the domain. |
| 86 | */ |
| 87 | transport?: string; |
| 88 | } |
| 89 | |
| 90 | export interface DomainAttributes { |
| 91 | /** Cloudflare-assigned domain identifier. */ |
| 92 | domainId: string; |
| 93 | /** The account the domain belongs to. */ |
| 94 | accountId: string; |
| 95 | /** The fully-qualified domain name. */ |
| 96 | domain: string; |
| 97 | /** Domain authorization status, if reported. */ |
| 98 | authorization: { authorized: boolean; timestamp: string } | undefined; |
| 99 | /** Delivery modes the domain accepts messages through. */ |
| 100 | allowedDeliveryModes: DeliveryMode[]; |
| 101 | /** Message dispositions dropped before delivery. */ |
| 102 | dropDispositions: DropDisposition[]; |
| 103 | /** IP/CIDR restrictions for inbound delivery. */ |
| 104 | ipRestrictions: string[]; |
| 105 | /** Folder messages are scanned in for API-deployed domains. */ |
| 106 | folder: "AllItems" | "Inbox" | undefined; |
| 107 | /** The API integration the domain is associated with, if any. */ |
| 108 | integrationId: string | undefined; |
| 109 | /** Number of lookback hops, if configured. */ |
| 110 | lookbackHops: number | undefined; |
| 111 | /** Whether TLS is required for inbound mail. */ |
| 112 | requireTlsInbound: boolean | undefined; |
| 113 | /** Whether TLS is required for outbound delivery. */ |
| 114 | requireTlsOutbound: boolean | undefined; |
| 115 | /** Onward delivery host. */ |
| 116 | transport: string; |
| 117 | /** Office 365 tenant id for API-deployed domains, if any. */ |
| 118 | o365TenantId: string | undefined; |
| 119 | /** Regions the domain's mail is processed in. */ |
| 120 | regions: string[]; |
| 121 | /** ISO8601 creation timestamp. */ |
| 122 | createdAt: string; |
| 123 | /** ISO8601 last-modified timestamp, if the domain has been modified. */ |
| 124 | modifiedAt: string | undefined; |
| 125 | } |
| 126 | |
| 127 | export type Domain = Resource< |
| 128 | EmailSecurityDomainTypeId, |
| 129 | DomainProps, |
| 130 | DomainAttributes, |
| 131 | never, |
| 132 | Providers |
| 133 | >; |
| 134 | |
| 135 | /** |
| 136 | * A Cloudflare Email Security (Area 1) domain's settings. |
| 137 | * |
| 138 | * Domains cannot be created via the API — they appear when the domain is |
| 139 | * onboarded to Email Security (MX/BCC/journal or an API integration) in |
| 140 | * the dashboard. This resource **adopts and configures** an existing |
| 141 | * domain: `read` finds it by name and reports it as unowned, so taking it |
| 142 | * under management is gated behind `--adopt` (or `adopt(true)`). |
| 143 | * |
| 144 | * :::warning |
| 145 | * **Destroying this resource offboards the domain from Email Security** |
| 146 | * (the underlying API call is `DELETE .../settings/domains/{id}`). Mail |
| 147 | * flow for the domain is no longer scanned afterwards. Plan destroys with |
| 148 | * care. |
| 149 | * ::: |
| 150 | * |
| 151 | * Requires the Email Security enterprise add-on; accounts without the |
| 152 | * entitlement receive the typed `EmailSecurityNotEntitled` error. |
| 153 | * ### Configuring a Domain |
| 154 | * **Example:** Drop malicious mail before delivery |
| 155 | * ```typescript |
| 156 | * yield* Cloudflare.Email.Domain("MailDomain", { |
| 157 | * domain: "example.com", |
| 158 | * dropDispositions: ["MALICIOUS", "SPOOF"], |
| 159 | * }); |
| 160 | * ``` |
| 161 | * |
| 162 | * **Example:** Restrict inbound delivery and require TLS |
| 163 | * ```typescript |
| 164 | * yield* Cloudflare.Email.Domain("MailDomain", { |
| 165 | * domain: "example.com", |
| 166 | * ipRestrictions: ["203.0.113.0/24"], |
| 167 | * requireTlsInbound: true, |
| 168 | * requireTlsOutbound: true, |
| 169 | * transport: "mx.example.com", |
| 170 | * }); |
| 171 | * ``` |
| 172 | * |
| 173 | * @see https://developers.cloudflare.com/cloudflare-one/email-security/ |
| 174 | * |
| 175 | * @resource |
| 176 | * @product Email Security |
| 177 | * @category Email |
| 178 | */ |
| 179 | export const Domain = Resource<Domain>(EmailSecurityDomainTypeId, { |
| 180 | aliases: ["Cloudflare.EmailSecurity.Domain"], |
| 181 | }); |
| 182 | |
| 183 | /** |
| 184 | * Returns true if the given value is an Domain resource. |
| 185 | */ |
| 186 | export const isDomain = (value: unknown): value is Domain => |
| 187 | Predicate.hasProperty(value, "Type") && value.Type === EmailSecurityDomainTypeId; |
| 188 | |
| 189 | export const DomainProvider = () => |
| 190 | Provider.succeed(Domain, { |
| 191 | stables: ["domainId", "accountId", "domain", "o365TenantId", "createdAt"], |
| 192 | |
| 193 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 194 | if (!isResolved(news)) return undefined; |
| 195 | // The domain name is the resource's identity — changing it means |
| 196 | // re-adopting a different onboarded domain. |
| 197 | const oldDomain = output?.domain ?? olds?.domain; |
| 198 | if (oldDomain !== undefined && oldDomain !== news.domain) { |
| 199 | return { action: "replace" } as const; |
| 200 | } |
| 201 | return undefined; |
| 202 | }), |
| 203 | |
| 204 | read: Effect.fn(function* ({ output, olds }) { |
| 205 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 206 | const acct = output?.accountId ?? accountId; |
| 207 | |
| 208 | // Owned path: refresh by the persisted domain id. |
| 209 | if (output?.domainId) { |
| 210 | const observed = yield* getDomain(acct, output.domainId); |
| 211 | if (observed) return toAttributes(observed, acct); |
| 212 | } |
| 213 | |
| 214 | // Cold lookup: the domain pre-exists (onboarded in the dashboard) and |
| 215 | // carries no ownership markers — report it `Unowned` so taking it |
| 216 | // under management is gated behind the adopt policy. |
| 217 | const domain = output?.domain ?? olds?.domain; |
| 218 | if (domain !== undefined) { |
| 219 | const observed = yield* findByName(acct, domain); |
| 220 | if (observed) return Unowned(toAttributes(observed, acct)); |
| 221 | } |
| 222 | return undefined; |
| 223 | }), |
| 224 | |
| 225 | reconcile: Effect.fn(function* ({ news, output }) { |
| 226 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 227 | |
| 228 | // 1. Observe — the domain must already be onboarded; the API cannot |
| 229 | // create one. |
| 230 | let observed = output?.domainId ? yield* getDomain(accountId, output.domainId) : undefined; |
| 231 | if (!observed) { |
| 232 | observed = yield* findByName(accountId, news.domain); |
| 233 | } |
| 234 | if (!observed) { |
| 235 | return yield* new EmailDomainInvalidProps({ |
| 236 | message: |
| 237 | `Domain "${news.domain}" is not onboarded to Email Security on ` + |
| 238 | `account ${accountId}. Cloudflare.Email.Domain only ` + |
| 239 | `manages settings on an existing domain — onboard the domain ` + |
| 240 | `in the Email Security dashboard first.`, |
| 241 | }); |
| 242 | } |
| 243 | |
| 244 | // 2. Sync — diff observed settings against the declared props and |
| 245 | // patch only on a delta. Omitted props are left untouched. |
| 246 | const delta = settingsDelta(observed, news); |
| 247 | if (delta === undefined) { |
| 248 | return toAttributes(observed, accountId); |
| 249 | } |
| 250 | const patched = yield* emailSecurity.patchSettingDomain({ |
| 251 | accountId, |
| 252 | domainId: observed.id ?? "", |
| 253 | ...delta, |
| 254 | }); |
| 255 | return toAttributes(patched, accountId); |
| 256 | }), |
| 257 | |
| 258 | delete: Effect.fn(function* ({ output }) { |
| 259 | // DESTRUCTIVE: this offboards the domain from Email Security — its |
| 260 | // mail flow is no longer scanned. Already-gone is success. |
| 261 | yield* emailSecurity |
| 262 | .deleteSettingDomain({ |
| 263 | accountId: output.accountId, |
| 264 | domainId: output.domainId, |
| 265 | }) |
| 266 | .pipe(Effect.catchTag("EmailSecurityDomainNotFound", () => Effect.void)); |
| 267 | }), |
| 268 | |
| 269 | // Account-scoped collection: enumerate every onboarded domain via the |
| 270 | // paginated account-level list API and hydrate each into the exact |
| 271 | // `read` Attributes shape. Accounts without the Email Security add-on |
| 272 | // (`EmailSecurityNotEntitled`) or lacking access (`Forbidden`) have |
| 273 | // nothing to enumerate — return []. |
| 274 | list: Effect.fn(function* () { |
| 275 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 276 | return yield* emailSecurity.listSettingDomains.pages({ accountId }).pipe( |
| 277 | Stream.runCollect, |
| 278 | Effect.map((chunk) => |
| 279 | Array.from(chunk).flatMap((page) => |
| 280 | (page.result ?? []).map((d) => toAttributes(d as ObservedDomain, accountId)), |
| 281 | ), |
| 282 | ), |
| 283 | Effect.catchTag(["EmailSecurityNotEntitled", "Forbidden"], () => |
| 284 | Effect.succeed([] as DomainAttributes[]), |
| 285 | ), |
| 286 | ); |
| 287 | }), |
| 288 | }); |
| 289 | |
| 290 | type ObservedDomain = emailSecurity.GetSettingDomainResponse; |
| 291 | |
| 292 | /** |
| 293 | * Read a domain by id, mapping "gone" (`EmailSecurityDomainNotFound`, |
| 294 | * HTTP 404) to `undefined`. |
| 295 | */ |
| 296 | const getDomain = (accountId: string, domainId: string) => |
| 297 | emailSecurity.getSettingDomain({ accountId, domainId }).pipe( |
| 298 | Effect.map((domain): ObservedDomain | undefined => domain), |
| 299 | Effect.catchTag("EmailSecurityDomainNotFound", () => Effect.undefined), |
| 300 | ); |
| 301 | |
| 302 | /** |
| 303 | * Find an onboarded domain by exact name. |
| 304 | */ |
| 305 | const findByName = (accountId: string, domain: string) => |
| 306 | emailSecurity.listSettingDomains.items({ accountId, domain: [domain] }).pipe( |
| 307 | Stream.runCollect, |
| 308 | Effect.map((chunk) => Array.from(chunk).find((d): d is ObservedDomain => d.domain === domain)), |
| 309 | ); |
| 310 | |
| 311 | const sameArray = (observed: readonly string[] | null | undefined, desired: readonly string[]) => { |
| 312 | const a = [...(observed ?? [])].sort(); |
| 313 | const b = [...desired].sort(); |
| 314 | return a.length === b.length && a.join(",") === b.join(","); |
| 315 | }; |
| 316 | |
| 317 | /** |
| 318 | * Diff observed domain settings against desired props. Only fields that |
| 319 | * are explicitly declared (not `undefined`) participate. Returns |
| 320 | * `undefined` when nothing needs to change, so the PATCH can be skipped |
| 321 | * entirely. Inputs have been resolved to concrete values by Plan. |
| 322 | */ |
| 323 | const settingsDelta = ( |
| 324 | observed: ObservedDomain, |
| 325 | news: DomainProps, |
| 326 | ): Omit<emailSecurity.PatchSettingDomainRequest, "accountId" | "domainId"> | undefined => { |
| 327 | const delta: Omit<emailSecurity.PatchSettingDomainRequest, "accountId" | "domainId"> = {}; |
| 328 | let dirty = false; |
| 329 | if ( |
| 330 | news.allowedDeliveryModes !== undefined && |
| 331 | !sameArray(observed.allowedDeliveryModes, news.allowedDeliveryModes) |
| 332 | ) { |
| 333 | delta.allowedDeliveryModes = news.allowedDeliveryModes; |
| 334 | dirty = true; |
| 335 | } |
| 336 | if ( |
| 337 | news.dropDispositions !== undefined && |
| 338 | !sameArray(observed.dropDispositions, news.dropDispositions) |
| 339 | ) { |
| 340 | delta.dropDispositions = news.dropDispositions; |
| 341 | dirty = true; |
| 342 | } |
| 343 | if ( |
| 344 | news.ipRestrictions !== undefined && |
| 345 | !sameArray(observed.ipRestrictions, news.ipRestrictions) |
| 346 | ) { |
| 347 | delta.ipRestrictions = news.ipRestrictions; |
| 348 | dirty = true; |
| 349 | } |
| 350 | if (news.folder !== undefined && (observed.folder ?? "") !== news.folder) { |
| 351 | delta.folder = news.folder; |
| 352 | dirty = true; |
| 353 | } |
| 354 | const integrationId = news.integrationId as string | undefined; |
| 355 | if (integrationId !== undefined && (observed.integrationId ?? "") !== integrationId) { |
| 356 | delta.integrationId = integrationId; |
| 357 | dirty = true; |
| 358 | } |
| 359 | if (news.lookbackHops !== undefined && observed.lookbackHops !== news.lookbackHops) { |
| 360 | delta.lookbackHops = news.lookbackHops; |
| 361 | dirty = true; |
| 362 | } |
| 363 | if ( |
| 364 | news.requireTlsInbound !== undefined && |
| 365 | (observed.requireTlsInbound ?? false) !== news.requireTlsInbound |
| 366 | ) { |
| 367 | delta.requireTlsInbound = news.requireTlsInbound; |
| 368 | dirty = true; |
| 369 | } |
| 370 | if ( |
| 371 | news.requireTlsOutbound !== undefined && |
| 372 | (observed.requireTlsOutbound ?? false) !== news.requireTlsOutbound |
| 373 | ) { |
| 374 | delta.requireTlsOutbound = news.requireTlsOutbound; |
| 375 | dirty = true; |
| 376 | } |
| 377 | if (news.transport !== undefined && (observed.transport ?? "") !== news.transport) { |
| 378 | delta.transport = news.transport; |
| 379 | dirty = true; |
| 380 | } |
| 381 | return dirty ? delta : undefined; |
| 382 | }; |
| 383 | |
| 384 | const toAttributes = ( |
| 385 | domain: ObservedDomain | emailSecurity.PatchSettingDomainResponse, |
| 386 | accountId: string, |
| 387 | ): DomainAttributes => ({ |
| 388 | domainId: domain.id ?? "", |
| 389 | accountId, |
| 390 | domain: domain.domain ?? "", |
| 391 | authorization: domain.authorization |
| 392 | ? { |
| 393 | authorized: domain.authorization.authorized, |
| 394 | timestamp: domain.authorization.timestamp, |
| 395 | } |
| 396 | : undefined, |
| 397 | allowedDeliveryModes: [...(domain.allowedDeliveryModes ?? [])] as DeliveryMode[], |
| 398 | dropDispositions: [...(domain.dropDispositions ?? [])] as DropDisposition[], |
| 399 | ipRestrictions: [...(domain.ipRestrictions ?? [])], |
| 400 | folder: (domain.folder ?? undefined) as "AllItems" | "Inbox" | undefined, |
| 401 | integrationId: domain.integrationId ?? undefined, |
| 402 | lookbackHops: domain.lookbackHops ?? undefined, |
| 403 | requireTlsInbound: domain.requireTlsInbound ?? undefined, |
| 404 | requireTlsOutbound: domain.requireTlsOutbound ?? undefined, |
| 405 | transport: domain.transport ?? "", |
| 406 | o365TenantId: domain.o365TenantId ?? undefined, |
| 407 | regions: [...(domain.regions ?? [])], |
| 408 | createdAt: domain.createdAt ?? "", |
| 409 | modifiedAt: domain.modifiedAt ?? undefined, |
| 410 | }); |