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

main
ts 252 lines 8.32 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Dlp.Entry" as const;
13 type TypeId = typeof TypeId;
14
15 export interface EntryProps {
16 /**
17 * Name of the entry. If omitted, a unique name is generated from the
18 * app, stage, and logical ID.
19 * @default ${app}-${stage}-${id}
20 */
21 name?: string;
22 /**
23 * Whether the entry participates in scans.
24 * @default true
25 */
26 enabled?: boolean;
27 /**
28 * The detection pattern.
29 */
30 pattern: {
31 /** The regular expression to match. */
32 regex: string;
33 /** Optional checksum validation applied to matches. */
34 validation?: "luhn";
35 };
36 /**
37 * Optional description of the entry.
38 */
39 description?: string;
40 /**
41 * The custom DLP profile to attach the entry to at create time.
42 * Immutable — changing it triggers a replacement.
43 */
44 profileId?: string;
45 }
46
47 export type EntryAttributes = {
48 /** API UUID of the entry. */
49 entryId: string;
50 /** Account that owns the entry. */
51 accountId: string;
52 /** Observed entry name. */
53 name: string;
54 /** Whether the entry participates in scans. */
55 enabled: boolean;
56 /** Observed detection pattern. */
57 pattern: { regex: string; validation: "luhn" | (string & {}) | undefined };
58 /** The profile the entry is attached to, if any. */
59 profileId: string | undefined;
60 };
61
62 export type Entry = Resource<TypeId, EntryProps, EntryAttributes, never, Providers>;
63
64 /**
65 * A Cloudflare Zero Trust **DLP custom entry** — a standalone regular-
66 * expression detection that can be attached to a custom DLP profile.
67 * Use it when entries are managed independently of the
68 * {@link Profile} that groups them.
69 *
70 * Requires the Cloudflare DLP entitlement (a paid Zero Trust add-on);
71 * accounts without it receive the typed `Forbidden` error on all writes.
72 * ### Creating a DLP entry
73 * **Example:** Attach a regex entry to a profile
74 * ```typescript
75 * const entry = yield* Cloudflare.Dlp.Entry("EmployeeId", {
76 * pattern: { regex: "EMP-[0-9]{6}" },
77 * profileId: profile.profileId,
78 * });
79 * ```
80 *
81 * **Example:** Luhn-validated card entry
82 * ```typescript
83 * const card = yield* Cloudflare.Dlp.Entry("CardNumber", {
84 * pattern: { regex: "[0-9]{13,16}", validation: "luhn" },
85 * profileId: profile.profileId,
86 * });
87 * ```
88 *
89 * @see https://developers.cloudflare.com/cloudflare-one/policies/data-loss-prevention/dlp-profiles/
90 *
91 * @resource
92 * @product DLP
93 * @category Cloudflare One (Zero Trust)
94 */
95 export const Entry = Resource<Entry>(TypeId);
96
97 /**
98 * Returns true if the given value is a Entry resource.
99 */
100 export const isEntry = (value: unknown): value is Entry =>
101 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
102
103 export const EntryProvider = () =>
104 Provider.succeed(Entry, {
105 stables: ["entryId", "accountId", "profileId"],
106
107 diff: Effect.fn(function* ({ olds, news, output }) {
108 if (!isResolved(news)) return undefined;
109 // The profile association is set at create time only — replace
110 // when it changes.
111 const oldProfileId = output?.profileId ?? olds?.profileId;
112 if (oldProfileId !== undefined && oldProfileId !== news.profileId) {
113 return { action: "replace" } as const;
114 }
115 return undefined;
116 }),
117
118 read: Effect.fn(function* ({ output }) {
119 const { accountId } = yield* yield* CloudflareEnvironment;
120 const acct = output?.accountId ?? accountId;
121
122 // Entries are only refreshed by id; without a persisted id there is
123 // nothing safe to adopt (the entitlement is account-gated).
124 if (!output?.entryId) return undefined;
125 const observed = yield* observeEntry(acct, output.entryId);
126 return observed ? toAttributes(observed, acct) : undefined;
127 }),
128
129 // Account collection: enumerate every custom DLP entry in the account
130 // (GET /accounts/{id}/dlp/entries), exhaustively paginated. The list
131 // response is a union of entry variants; only the `custom` variant is
132 // an alchemy-managed Entry, so we narrow to it and hydrate into the
133 // exact `read` Attributes shape.
134 list: Effect.fn(function* () {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136 return yield* zeroTrust.listDlpEntryCustoms.pages({ accountId }).pipe(
137 Stream.runCollect,
138 Effect.map((chunk) =>
139 Array.from(chunk).flatMap((page) =>
140 (page.result ?? [])
141 .filter(
142 (entry): entry is zeroTrust.DlpEntriesListResultItemCase0 =>
143 "type" in entry && entry.type === "custom",
144 )
145 .map((entry) => toAttributes(entry, accountId)),
146 ),
147 ),
148 );
149 }),
150
151 reconcile: Effect.fn(function* ({ id, news, output }) {
152 const { accountId } = yield* yield* CloudflareEnvironment;
153 const name = yield* createEntryName(id, news.name);
154
155 // 1. Observe.
156 const observed = output?.entryId ? yield* observeEntry(accountId, output.entryId) : undefined;
157
158 // 2. Ensure — create when missing.
159 if (!observed) {
160 const created = yield* zeroTrust.createDlpEntryCustom({
161 accountId,
162 name,
163 enabled: news.enabled ?? true,
164 pattern: encodePattern(news.pattern),
165 ...(news.description !== undefined ? { description: news.description } : {}),
166 ...(news.profileId !== undefined ? { profileId: news.profileId } : {}),
167 });
168 return toAttributes(created, accountId);
169 }
170
171 // 3. Sync — PUT the full desired state when the observed state
172 // differs; skip the call on a no-op.
173 const dirty =
174 observed.name !== name ||
175 observed.enabled !== (news.enabled ?? true) ||
176 observed.pattern.regex !== news.pattern.regex ||
177 (observed.pattern.validation ?? undefined) !== news.pattern.validation;
178 if (!dirty) {
179 return toAttributes(observed, accountId);
180 }
181 const updated = yield* zeroTrust.updateDlpEntryCustom({
182 accountId,
183 entryId: observed.id,
184 name,
185 enabled: news.enabled ?? true,
186 pattern: encodePattern(news.pattern),
187 ...(news.description !== undefined ? { description: news.description } : {}),
188 });
189 return toAttributes(updated, accountId);
190 }),
191
192 delete: Effect.fn(function* ({ output }) {
193 yield* zeroTrust
194 .deleteDlpEntryCustom({
195 accountId: output.accountId,
196 entryId: output.entryId,
197 })
198 .pipe(Effect.catchTag("DlpEntryNotFound", () => Effect.void));
199 }),
200 });
201
202 /**
203 * Structural shape shared by the custom variant of get/create/update
204 * responses.
205 */
206 type ObservedEntry = {
207 id: string;
208 enabled: boolean;
209 name: string;
210 pattern: { regex: string; validation?: "luhn" | (string & {}) | null };
211 description?: string | null;
212 profileId?: string | null;
213 };
214
215 /**
216 * Read an entry by id, mapping "gone" to `undefined` and narrowing to
217 * the `custom` variant of the response union.
218 */
219 const observeEntry = (accountId: string, entryId: string) =>
220 zeroTrust.getDlpEntryCustom({ accountId, entryId }).pipe(
221 Effect.map((entry) =>
222 "type" in entry && entry.type === "custom"
223 ? (entry as zeroTrust.DlpEntriesGetResultCase0)
224 : undefined,
225 ),
226 Effect.catchTag("DlpEntryNotFound", () => Effect.undefined),
227 );
228
229 const createEntryName = (id: string, name: string | undefined) =>
230 Effect.gen(function* () {
231 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
232 });
233
234 const encodePattern = (pattern: {
235 regex: string;
236 validation?: "luhn";
237 }): { regex: string; validation?: "luhn" } => ({
238 regex: pattern.regex,
239 ...(pattern.validation !== undefined ? { validation: pattern.validation } : {}),
240 });
241
242 const toAttributes = (entry: ObservedEntry, accountId: string): EntryAttributes => ({
243 entryId: entry.id,
244 accountId,
245 name: entry.name,
246 enabled: entry.enabled,
247 pattern: {
248 regex: entry.pattern.regex,
249 validation: entry.pattern.validation ?? undefined,
250 },
251 profileId: entry.profileId ?? undefined,
252 });