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

main
ts 272 lines 9.94 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 EmailSecurityImpersonationRegistryEntryTypeId =
12 "Cloudflare.Email.ImpersonationRegistryEntry" as const;
13 type EmailSecurityImpersonationRegistryEntryTypeId =
14 typeof EmailSecurityImpersonationRegistryEntryTypeId;
15
16 export interface ImpersonationRegistryEntryProps {
17 /**
18 * The display name to protect (e.g. a VIP's name as it appears in the
19 * `From` header). Together with `email` it forms the entry's identity
20 * for cold-state recovery.
21 */
22 name: string;
23 /**
24 * The legitimate email address (or regular expression) for the display
25 * name. Messages using the display name from a different address are
26 * flagged as impersonation/BEC.
27 */
28 email: string;
29 /**
30 * Whether `email` is a regular expression.
31 * @default false
32 */
33 isEmailRegex?: boolean;
34 /**
35 * Free-form notes about the entry.
36 */
37 comments?: string;
38 }
39
40 export interface ImpersonationRegistryEntryAttributes {
41 /** Cloudflare-assigned impersonation registry entry identifier. */
42 entryId: string;
43 /** The account the entry belongs to. */
44 accountId: string;
45 /** The protected display name. */
46 name: string;
47 /** The legitimate email address (or regex). */
48 email: string;
49 /** Whether the email is a regular expression. */
50 isEmailRegex: boolean;
51 /** Free-form notes about the entry, if set. */
52 comments: string | undefined;
53 /**
54 * Where the entry came from. Manually created entries are
55 * `A1S_INTERNAL`; directory-synced entries carry the integration's
56 * provenance.
57 */
58 provenance: string | undefined;
59 /** ISO8601 creation timestamp. */
60 createdAt: string;
61 /** ISO8601 last-modified timestamp, if the entry has been modified. */
62 modifiedAt: string | undefined;
63 }
64
65 export type ImpersonationRegistryEntry = Resource<
66 EmailSecurityImpersonationRegistryEntryTypeId,
67 ImpersonationRegistryEntryProps,
68 ImpersonationRegistryEntryAttributes,
69 never,
70 Providers
71 >;
72
73 /**
74 * A Cloudflare Email Security (Area 1) impersonation registry entry —
75 * maps a protected display name (e.g. a VIP) to their legitimate email
76 * address for BEC/impersonation detection.
77 *
78 * All fields are mutable in place. Directory-synced fields
79 * (`directory_id`, `directory_node_id`, `provenance`) are managed by
80 * Office365/Google integrations and are not exposed as inputs. Requires
81 * the Email Security enterprise add-on; accounts without the entitlement
82 * receive the typed `EmailSecurityNotEntitled` error.
83 * ### Registering Protected Identities
84 * **Example:** Protect an executive's display name
85 * ```typescript
86 * yield* Cloudflare.Email.ImpersonationRegistryEntry("Ceo", {
87 * name: "Jane Smith",
88 * email: "jane.smith@example.com",
89 * comments: "CEO — high-value BEC target",
90 * });
91 * ```
92 *
93 * **Example:** Match several legitimate addresses with a regex
94 * ```typescript
95 * yield* Cloudflare.Email.ImpersonationRegistryEntry("Finance", {
96 * name: "Accounts Payable",
97 * email: "^ap(-[a-z]+)?@example\\.com$",
98 * isEmailRegex: true,
99 * });
100 * ```
101 *
102 * @see https://developers.cloudflare.com/cloudflare-one/email-security/
103 *
104 * @resource
105 * @product Email Security
106 * @category Email
107 */
108 export const ImpersonationRegistryEntry = Resource<ImpersonationRegistryEntry>(
109 EmailSecurityImpersonationRegistryEntryTypeId,
110 { aliases: ["Cloudflare.EmailSecurity.ImpersonationRegistryEntry"] },
111 );
112
113 /**
114 * Returns true if the given value is an
115 * ImpersonationRegistryEntry resource.
116 */
117 export const isImpersonationRegistryEntry = (value: unknown): value is ImpersonationRegistryEntry =>
118 Predicate.hasProperty(value, "Type") &&
119 value.Type === EmailSecurityImpersonationRegistryEntryTypeId;
120
121 export const ImpersonationRegistryEntryProvider = () =>
122 Provider.succeed(ImpersonationRegistryEntry, {
123 stables: ["entryId", "accountId", "createdAt"],
124
125 // Account collection: exhaustively paginate the account-scoped registry
126 // list and hydrate each row into the exact `read` Attributes shape.
127 // Accounts without the Email Security add-on return the typed
128 // `EmailSecurityNotEntitled` error → treat as an empty registry.
129 list: Effect.fn(function* () {
130 const { accountId } = yield* yield* CloudflareEnvironment;
131 return yield* emailSecurity.listSettingImpersonationRegistries.pages({ accountId }).pipe(
132 Stream.runCollect,
133 Effect.map((chunk) =>
134 Array.from(chunk).flatMap((page) =>
135 (page.result ?? []).map((entry) => toAttributes(entry, accountId)),
136 ),
137 ),
138 // Email Security is a paid add-on gated by both account
139 // entitlement and token scope: an unentitled account answers
140 // `EmailSecurityNotEntitled`, while a credential lacking the
141 // Email Security scope (e.g. Cloudflare OAuth) answers a bare
142 // `Forbidden`. Neither can enumerate, so both mean "none
143 // visible" — matching `Domain.list()`. Returning `[]` is the
144 // safe direction for the callers of `list` (orphan detection
145 // never deletes what it cannot see).
146 Effect.catchTag(["EmailSecurityNotEntitled", "Forbidden"], () =>
147 Effect.succeed([] as ImpersonationRegistryEntryAttributes[]),
148 ),
149 );
150 }),
151
152 read: Effect.fn(function* ({ output, olds }) {
153 const { accountId } = yield* yield* CloudflareEnvironment;
154 const acct = output?.accountId ?? accountId;
155
156 // Owned path: refresh by the persisted entry id.
157 if (output?.entryId) {
158 const observed = yield* getEntry(acct, output.entryId);
159 if (observed) return toAttributes(observed, acct);
160 }
161
162 // Cold lookup: recover by exact name + email; matches are reported
163 // as `Unowned` so takeover is gated behind the adopt policy.
164 const name = output?.name ?? olds?.name;
165 const email = output?.email ?? olds?.email;
166 if (name !== undefined && email !== undefined) {
167 const observed = yield* findByIdentity(acct, name, email);
168 if (observed) return Unowned(toAttributes(observed, acct));
169 }
170 return undefined;
171 }),
172
173 reconcile: Effect.fn(function* ({ news, output }) {
174 const { accountId } = yield* yield* CloudflareEnvironment;
175
176 // 1. Observe — id hint first, then identity scan.
177 let observed = output?.entryId ? yield* getEntry(accountId, output.entryId) : undefined;
178 if (!observed) {
179 observed = yield* findByIdentity(accountId, news.name, news.email);
180 }
181
182 // 2. Ensure — create when missing.
183 if (!observed) {
184 const created = yield* emailSecurity.createSettingImpersonationRegistry({
185 accountId,
186 name: news.name,
187 email: news.email,
188 isEmailRegex: news.isEmailRegex ?? false,
189 comments: news.comments,
190 });
191 return toAttributes(created, accountId);
192 }
193
194 // 3. Sync — patch only on a delta.
195 const dirty =
196 (observed.name ?? "") !== news.name ||
197 (observed.email ?? "") !== news.email ||
198 (observed.isEmailRegex ?? false) !== (news.isEmailRegex ?? false) ||
199 (news.comments !== undefined && (observed.comments ?? "") !== news.comments);
200 if (!dirty) {
201 return toAttributes(observed, accountId);
202 }
203
204 const patched = yield* emailSecurity.patchSettingImpersonationRegistry({
205 accountId,
206 impersonationRegistryId: observed.id ?? "",
207 name: news.name,
208 email: news.email,
209 isEmailRegex: news.isEmailRegex ?? false,
210 comments: news.comments,
211 });
212 return toAttributes(patched, accountId);
213 }),
214
215 delete: Effect.fn(function* ({ output }) {
216 yield* emailSecurity
217 .deleteSettingImpersonationRegistry({
218 accountId: output.accountId,
219 impersonationRegistryId: output.entryId,
220 })
221 .pipe(Effect.catchTag("ImpersonationRegistryEntryNotFound", () => Effect.void));
222 }),
223 });
224
225 type ObservedEntry = emailSecurity.GetSettingImpersonationRegistryResponse;
226
227 /**
228 * Read an impersonation registry entry by id, mapping "gone"
229 * (`ImpersonationRegistryEntryNotFound`, HTTP 404) to `undefined`.
230 */
231 const getEntry = (accountId: string, impersonationRegistryId: string) =>
232 emailSecurity.getSettingImpersonationRegistry({ accountId, impersonationRegistryId }).pipe(
233 Effect.map((entry): ObservedEntry | undefined => entry),
234 Effect.catchTag("ImpersonationRegistryEntryNotFound", () => Effect.undefined),
235 );
236
237 /**
238 * Find an entry by exact display name + email. The `search` query is a
239 * server-side hint; the exact match is re-checked client-side. Picks the
240 * oldest match for determinism.
241 */
242 const findByIdentity = (accountId: string, name: string, email: string) =>
243 emailSecurity.listSettingImpersonationRegistries.items({ accountId, search: email }).pipe(
244 Stream.runCollect,
245 Effect.map((chunk) =>
246 Array.from(chunk)
247 .filter((entry) => entry.name === name && entry.email === email)
248 .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""))
249 .at(0),
250 ),
251 );
252
253 type ListedEntry = emailSecurity.ListSettingImpersonationRegistriesResponse["result"][number];
254
255 const toAttributes = (
256 entry:
257 | ObservedEntry
258 | emailSecurity.CreateSettingImpersonationRegistryResponse
259 | emailSecurity.PatchSettingImpersonationRegistryResponse
260 | ListedEntry,
261 accountId: string,
262 ): ImpersonationRegistryEntryAttributes => ({
263 entryId: entry.id ?? "",
264 accountId,
265 name: entry.name ?? "",
266 email: entry.email ?? "",
267 isEmailRegex: entry.isEmailRegex ?? false,
268 comments: entry.comments ?? undefined,
269 provenance: entry.provenance ?? undefined,
270 createdAt: entry.createdAt ?? "",
271 modifiedAt: entry.modifiedAt ?? undefined,
272 });