@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 259 lines 8.67 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 import type { PatternType } from "./AllowPolicy.ts";
11
12 const EmailSecurityBlockSenderTypeId = "Cloudflare.Email.BlockSender" as const;
13 type EmailSecurityBlockSenderTypeId = typeof EmailSecurityBlockSenderTypeId;
14
15 export interface BlockSenderProps {
16 /**
17 * The email address, domain, IP, or regular expression to block.
18 * The pattern is the entry's identity for cold-state recovery — a
19 * pre-existing entry with the same pattern is reported as unowned and
20 * only taken over when adoption is enabled.
21 */
22 pattern: string;
23 /**
24 * Type of pattern matching.
25 */
26 patternType: PatternType;
27 /**
28 * Whether `pattern` is a regular expression.
29 * @default false
30 */
31 isRegex?: boolean;
32 /**
33 * Free-form notes about the blocked sender.
34 */
35 comments?: string;
36 }
37
38 export interface BlockSenderAttributes {
39 /** Cloudflare-assigned blocked sender pattern identifier. */
40 blockSenderId: string;
41 /** The account the entry belongs to. */
42 accountId: string;
43 /** The blocked pattern. */
44 pattern: string;
45 /** Type of pattern matching. */
46 patternType: PatternType;
47 /** Whether the pattern is a regular expression. */
48 isRegex: boolean;
49 /** Free-form notes about the entry, if set. */
50 comments: string | undefined;
51 /** ISO8601 creation timestamp. */
52 createdAt: string;
53 /** ISO8601 last-modified timestamp, if the entry has been modified. */
54 modifiedAt: string | undefined;
55 }
56
57 export type BlockSender = Resource<
58 EmailSecurityBlockSenderTypeId,
59 BlockSenderProps,
60 BlockSenderAttributes,
61 never,
62 Providers
63 >;
64
65 /**
66 * A Cloudflare Email Security (Area 1) blocked sender — messages matching
67 * the pattern are blocked before delivery.
68 *
69 * All fields are mutable in place. Requires the Email Security enterprise
70 * add-on; accounts without the entitlement receive the typed
71 * `EmailSecurityNotEntitled` error.
72 * ### Blocking Senders
73 * **Example:** Block a single email address
74 * ```typescript
75 * yield* Cloudflare.Email.BlockSender("KnownPhisher", {
76 * pattern: "phisher@malicious.example.com",
77 * patternType: "EMAIL",
78 * comments: "reported in incident 1234",
79 * });
80 * ```
81 *
82 * **Example:** Block a whole sending domain
83 * ```typescript
84 * yield* Cloudflare.Email.BlockSender("SpamDomain", {
85 * pattern: "spam-source.example.net",
86 * patternType: "DOMAIN",
87 * });
88 * ```
89 *
90 * **Example:** Block by regular expression
91 * ```typescript
92 * yield* Cloudflare.Email.BlockSender("LookalikeSenders", {
93 * pattern: ".*@examp1e\\.com$",
94 * patternType: "EMAIL",
95 * isRegex: true,
96 * });
97 * ```
98 *
99 * @see https://developers.cloudflare.com/cloudflare-one/email-security/
100 *
101 * @resource
102 * @product Email Security
103 * @category Email
104 */
105 export const BlockSender = Resource<BlockSender>(EmailSecurityBlockSenderTypeId, {
106 aliases: ["Cloudflare.EmailSecurity.BlockSender"],
107 });
108
109 /**
110 * Returns true if the given value is an BlockSender resource.
111 */
112 export const isBlockSender = (value: unknown): value is BlockSender =>
113 Predicate.hasProperty(value, "Type") && value.Type === EmailSecurityBlockSenderTypeId;
114
115 export const BlockSenderProvider = () =>
116 Provider.succeed(BlockSender, {
117 stables: ["blockSenderId", "accountId", "createdAt"],
118
119 read: Effect.fn(function* ({ output, olds }) {
120 const { accountId } = yield* yield* CloudflareEnvironment;
121 const acct = output?.accountId ?? accountId;
122
123 // Owned path: refresh by the persisted entry id.
124 if (output?.blockSenderId) {
125 const observed = yield* getBlockSender(acct, output.blockSenderId);
126 if (observed) return toAttributes(observed, acct);
127 }
128
129 // Cold lookup: recover by pattern; matches are reported as `Unowned`
130 // so takeover is gated behind the adopt policy.
131 const pattern = output?.pattern ?? olds?.pattern;
132 if (pattern !== undefined) {
133 const observed = yield* findByPattern(acct, pattern);
134 if (observed) return Unowned(toAttributes(observed, acct));
135 }
136 return undefined;
137 }),
138
139 reconcile: Effect.fn(function* ({ news, output }) {
140 const { accountId } = yield* yield* CloudflareEnvironment;
141
142 // 1. Observe — id hint first, then pattern scan.
143 let observed = output?.blockSenderId
144 ? yield* getBlockSender(accountId, output.blockSenderId)
145 : undefined;
146 if (!observed) {
147 observed = yield* findByPattern(accountId, news.pattern);
148 }
149
150 // 2. Ensure — create when missing.
151 if (!observed) {
152 const created = yield* emailSecurity.createSettingBlockSender({
153 accountId,
154 pattern: news.pattern,
155 patternType: news.patternType,
156 isRegex: news.isRegex ?? false,
157 comments: news.comments,
158 });
159 return toAttributes(created, accountId);
160 }
161
162 // 3. Sync — patch only on a delta.
163 const dirty =
164 (observed.pattern ?? "") !== news.pattern ||
165 (observed.patternType ?? "") !== news.patternType ||
166 (observed.isRegex ?? false) !== (news.isRegex ?? false) ||
167 (news.comments !== undefined && (observed.comments ?? "") !== news.comments);
168 if (!dirty) {
169 return toAttributes(observed, accountId);
170 }
171
172 const patched = yield* emailSecurity.patchSettingBlockSender({
173 accountId,
174 patternId: observed.id ?? "",
175 pattern: news.pattern,
176 patternType: news.patternType,
177 isRegex: news.isRegex ?? false,
178 comments: news.comments,
179 });
180 return toAttributes(patched, accountId);
181 }),
182
183 delete: Effect.fn(function* ({ output }) {
184 yield* emailSecurity
185 .deleteSettingBlockSender({
186 accountId: output.accountId,
187 patternId: output.blockSenderId,
188 })
189 .pipe(Effect.catchTag("BlockSenderNotFound", () => Effect.void));
190 }),
191
192 // Account collection: enumerate every blocked sender in the ambient
193 // account, exhaustively paginating. Each list item already carries the
194 // full entry shape, so it hydrates directly into `read`'s Attributes with
195 // no per-item follow-up. Email Security is a paid add-on, so accounts
196 // without the entitlement (or without permission) have nothing to
197 // enumerate and yield an empty array.
198 list: Effect.fn(function* () {
199 const { accountId } = yield* yield* CloudflareEnvironment;
200 return yield* emailSecurity.listSettingBlockSenders.pages({ accountId }).pipe(
201 Stream.runCollect,
202 Effect.map((chunk) =>
203 Array.from(chunk).flatMap((page) =>
204 (page.result ?? []).map((entry) => toAttributes(entry, accountId)),
205 ),
206 ),
207 Effect.catchTags({
208 EmailSecurityNotEntitled: () => Effect.succeed([]),
209 Forbidden: () => Effect.succeed([]),
210 }),
211 );
212 }),
213 });
214
215 type ObservedBlockSender = emailSecurity.GetSettingBlockSenderResponse;
216
217 /**
218 * Read a blocked sender by id, mapping "gone" (`BlockSenderNotFound`,
219 * HTTP 404) to `undefined`.
220 */
221 const getBlockSender = (accountId: string, patternId: string) =>
222 emailSecurity.getSettingBlockSender({ accountId, patternId }).pipe(
223 Effect.map((entry): ObservedBlockSender | undefined => entry),
224 Effect.catchTag("BlockSenderNotFound", () => Effect.undefined),
225 );
226
227 /**
228 * Find a blocked sender by exact pattern. The `pattern` query filter is a
229 * server-side hint; the exact match is re-checked client-side. Picks the
230 * oldest match for determinism.
231 */
232 const findByPattern = (accountId: string, pattern: string) =>
233 emailSecurity.listSettingBlockSenders.items({ accountId, pattern }).pipe(
234 Stream.runCollect,
235 Effect.map((chunk) =>
236 Array.from(chunk)
237 .filter((entry) => entry.pattern === pattern)
238 .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""))
239 .at(0),
240 ),
241 );
242
243 const toAttributes = (
244 entry:
245 | ObservedBlockSender
246 | emailSecurity.CreateSettingBlockSenderResponse
247 | emailSecurity.PatchSettingBlockSenderResponse
248 | emailSecurity.ListSettingBlockSendersResponse["result"][number],
249 accountId: string,
250 ): BlockSenderAttributes => ({
251 blockSenderId: entry.id ?? "",
252 accountId,
253 pattern: entry.pattern ?? "",
254 patternType: (entry.patternType ?? "EMAIL") as PatternType,
255 isRegex: entry.isRegex ?? false,
256 comments: entry.comments ?? undefined,
257 createdAt: entry.createdAt ?? "",
258 modifiedAt: entry.modifiedAt ?? undefined,
259 });