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

main
ts 348 lines 11.8 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { createPhysicalName } from "alchemy/PhysicalName";
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 TypeId = "Cloudflare.Dlp.Profile" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * A detection entry defined inline on the profile — a regular expression
16 * the DLP engine scans for.
17 */
18 export interface ProfileEntry {
19 /** Name of the entry. Unique within the profile. */
20 name: string;
21 /** Whether the entry participates in scans. */
22 enabled: boolean;
23 /** The detection pattern. */
24 pattern: {
25 /** The regular expression to match. */
26 regex: string;
27 /** Optional checksum validation applied to matches. */
28 validation?: "luhn";
29 };
30 /** Optional description of the entry. */
31 description?: string;
32 }
33
34 export interface ProfileProps {
35 /**
36 * Name of the profile. If omitted, a unique name is generated from the
37 * app, stage, and logical ID.
38 * @default ${app}-${stage}-${id}
39 */
40 name?: string;
41 /**
42 * The description of the profile.
43 */
44 description?: string;
45 /**
46 * Related DLP policies will trigger when the match count exceeds this
47 * number.
48 * @default 0
49 */
50 allowedMatchCount?: number;
51 /**
52 * Whether to scan images via OCR.
53 */
54 ocrEnabled?: boolean;
55 /**
56 * Confidence threshold applied to AI-context detections
57 * (`low` | `medium` | `high` | `very_high`).
58 */
59 confidenceThreshold?: string;
60 /**
61 * Custom detection entries owned by this profile. Synced declaratively:
62 * entries are matched to observed entries by name; entries removed from
63 * this list are deleted from the profile.
64 */
65 entries?: ProfileEntry[];
66 }
67
68 export type ProfileAttributes = {
69 /** API UUID of the profile. */
70 profileId: string;
71 /** Account that owns the profile. */
72 accountId: string;
73 /** Observed profile name. */
74 name: string;
75 /** Observed description, if any. */
76 description: string | undefined;
77 /** Observed allowed match count. */
78 allowedMatchCount: number;
79 /** Whether OCR scanning is enabled. */
80 ocrEnabled: boolean;
81 /** Ids of the custom entries owned by the profile, keyed by name. */
82 entryIds: Record<string, string>;
83 };
84
85 export type Profile = Resource<TypeId, ProfileProps, ProfileAttributes, never, Providers>;
86
87 /**
88 * A Cloudflare Zero Trust **DLP custom profile** — a named collection of
89 * detection entries (regular expressions) that Gateway HTTP policies and
90 * CASB integrations reference to detect sensitive data in transit.
91 *
92 * Requires the Cloudflare DLP entitlement (a paid Zero Trust add-on);
93 * accounts without it receive the typed `Forbidden` error on all writes.
94 * ### Creating a DLP profile
95 * **Example:** Profile with a custom regex entry
96 * ```typescript
97 * const profile = yield* Cloudflare.Dlp.Profile("EmployeeIds", {
98 * description: "Detects internal employee identifiers",
99 * allowedMatchCount: 0,
100 * entries: [
101 * {
102 * name: "employee-id",
103 * enabled: true,
104 * pattern: { regex: "EMP-[0-9]{6}" },
105 * },
106 * ],
107 * });
108 * ```
109 *
110 * **Example:** Credit-card-like entry with Luhn validation
111 * ```typescript
112 * const cards = yield* Cloudflare.Dlp.Profile("Cards", {
113 * entries: [
114 * {
115 * name: "card-number",
116 * enabled: true,
117 * pattern: { regex: "[0-9]{13,16}", validation: "luhn" },
118 * },
119 * ],
120 * });
121 * ```
122 *
123 * @see https://developers.cloudflare.com/cloudflare-one/policies/data-loss-prevention/dlp-profiles/
124 *
125 * @resource
126 * @product DLP
127 * @category Cloudflare One (Zero Trust)
128 */
129 export const Profile = Resource<Profile>(TypeId);
130
131 /**
132 * Returns true if the given value is a Profile resource.
133 */
134 export const isProfile = (value: unknown): value is Profile =>
135 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
136
137 export const ProfileProvider = () =>
138 Provider.succeed(Profile, {
139 stables: ["profileId", "accountId"],
140
141 read: Effect.fn(function* ({ output }) {
142 const { accountId } = yield* yield* CloudflareEnvironment;
143 const acct = output?.accountId ?? accountId;
144
145 // DLP profiles are only refreshed by id; without a persisted id
146 // there is nothing safe to adopt (names are not guaranteed unique
147 // and the entitlement is account-gated).
148 if (!output?.profileId) return undefined;
149 const observed = yield* observeProfile(acct, output.profileId);
150 return observed ? toAttributes(observed, acct) : undefined;
151 }),
152
153 reconcile: Effect.fn(function* ({ id, news, output }) {
154 const { accountId } = yield* yield* CloudflareEnvironment;
155 const name = yield* createProfileName(id, news.name);
156
157 // 1. Observe.
158 const observed = output?.profileId
159 ? yield* observeProfile(accountId, output.profileId)
160 : undefined;
161
162 // 2. Ensure — create with the full desired state when missing.
163 if (!observed) {
164 const created = yield* zeroTrust.createDlpProfileCustom({
165 accountId,
166 name,
167 ...(news.description !== undefined ? { description: news.description } : {}),
168 ...(news.allowedMatchCount !== undefined
169 ? { allowedMatchCount: news.allowedMatchCount }
170 : {}),
171 ...(news.ocrEnabled !== undefined ? { ocrEnabled: news.ocrEnabled } : {}),
172 ...(news.confidenceThreshold !== undefined
173 ? { confidenceThreshold: news.confidenceThreshold }
174 : {}),
175 ...(news.entries !== undefined ? { entries: news.entries.map(encodeNewEntry) } : {}),
176 });
177 const createdCustom = narrowCustom(created);
178 return toAttributes(createdCustom, accountId);
179 }
180
181 // 3. Sync — PUT the full desired state when the observed state
182 // differs. Observed entries are matched to desired entries by
183 // name so existing entry ids are preserved.
184 const dirty =
185 observed.name !== name ||
186 (observed.description ?? undefined) !== news.description ||
187 observed.allowedMatchCount !== (news.allowedMatchCount ?? 0) ||
188 observed.ocrEnabled !== (news.ocrEnabled ?? false) ||
189 (news.confidenceThreshold !== undefined &&
190 (observed.confidenceThreshold ?? undefined) !== news.confidenceThreshold) ||
191 !sameEntries(observed, news.entries);
192 if (!dirty) {
193 return toAttributes(observed, accountId);
194 }
195 const observedIds = entryIdsByName(observed);
196 const updated = yield* zeroTrust.updateDlpProfileCustom({
197 accountId,
198 profileId: observed.id,
199 name,
200 description: news.description ?? null,
201 allowedMatchCount: news.allowedMatchCount ?? 0,
202 ocrEnabled: news.ocrEnabled ?? false,
203 ...(news.confidenceThreshold !== undefined
204 ? { confidenceThreshold: news.confidenceThreshold }
205 : {}),
206 ...(news.entries !== undefined
207 ? {
208 entries: news.entries.map((entry) => {
209 const entryId = observedIds[entry.name];
210 return entryId !== undefined
211 ? { ...encodeNewEntry(entry), entryId }
212 : encodeNewEntry(entry);
213 }),
214 }
215 : {}),
216 });
217 return toAttributes(narrowCustom(updated), accountId);
218 }),
219
220 delete: Effect.fn(function* ({ output }) {
221 yield* zeroTrust
222 .deleteDlpProfileCustom({
223 accountId: output.accountId,
224 profileId: output.profileId,
225 })
226 .pipe(Effect.catchTag("DlpProfileNotFound", () => Effect.void));
227 }),
228
229 // Account-scoped collection (pattern b): enumerate every custom DLP
230 // profile via the account profiles list, then hydrate each by id into
231 // the exact `read` Attributes shape so list items are delete-ready.
232 // The list endpoint also returns predefined / integration profiles —
233 // only `custom` profiles are modelled by this resource, so the rest
234 // are filtered out.
235 list: Effect.fn(function* () {
236 const { accountId } = yield* yield* CloudflareEnvironment;
237
238 const profileIds = yield* zeroTrust.listDlpProfiles.pages({ accountId }).pipe(
239 Stream.runCollect,
240 Effect.map((chunk) =>
241 Array.from(chunk).flatMap((page) =>
242 (page.result ?? []).flatMap((profile) =>
243 profile.type === "custom" ? [profile.id] : [],
244 ),
245 ),
246 ),
247 );
248
249 const rows = yield* Effect.forEach(
250 profileIds,
251 (profileId) =>
252 observeProfile(accountId, profileId).pipe(
253 Effect.map((observed) => (observed ? toAttributes(observed, accountId) : undefined)),
254 ),
255 { concurrency: 10 },
256 );
257
258 return rows.filter((row): row is ProfileAttributes => row !== undefined);
259 }),
260 });
261
262 /**
263 * The custom-profile member of the DLP profile response union.
264 */
265 type ObservedCustomProfile = Extract<zeroTrust.GetDlpProfileCustomResponse, { type: "custom" }>;
266
267 /**
268 * Narrow a profile response union to its `custom` member. Create/update
269 * on the custom endpoint always return a custom profile; a different
270 * shape would be a Cloudflare contract break, so fall back to a minimal
271 * empty view rather than crash the engine.
272 */
273 const narrowCustom = (
274 profile: zeroTrust.GetDlpProfileCustomResponse,
275 ): ObservedCustomProfile | undefined =>
276 "type" in profile && profile.type === "custom" ? profile : undefined;
277
278 /**
279 * Read a profile by id, mapping "gone" to `undefined` and narrowing to
280 * the custom variant.
281 */
282 const observeProfile = (accountId: string, profileId: string) =>
283 zeroTrust.getDlpProfileCustom({ accountId, profileId }).pipe(
284 Effect.map(narrowCustom),
285 Effect.catchTag("DlpProfileNotFound", () => Effect.undefined),
286 );
287
288 const createProfileName = (id: string, name: string | undefined) =>
289 Effect.gen(function* () {
290 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
291 });
292
293 const encodeNewEntry = (
294 entry: ProfileEntry,
295 ): {
296 enabled: boolean;
297 name: string;
298 pattern: { regex: string; validation?: "luhn" };
299 description?: string | null;
300 } => ({
301 enabled: entry.enabled,
302 name: entry.name,
303 pattern: {
304 regex: entry.pattern.regex,
305 ...(entry.pattern.validation !== undefined ? { validation: entry.pattern.validation } : {}),
306 },
307 ...(entry.description !== undefined ? { description: entry.description } : {}),
308 });
309
310 /**
311 * Custom regex entries observed on the profile, keyed by name.
312 */
313 const customEntries = (profile: ObservedCustomProfile | undefined) =>
314 (profile?.entries ?? []).flatMap((entry) => (entry.type === "custom" ? [entry] : []));
315
316 const entryIdsByName = (profile: ObservedCustomProfile | undefined): Record<string, string> =>
317 Object.fromEntries(customEntries(profile).map((e) => [e.name, e.id]));
318
319 const sameEntries = (
320 observed: ObservedCustomProfile,
321 desired: ProfileEntry[] | undefined,
322 ): boolean => {
323 if (desired === undefined) return true;
324 const observedByName = new Map(customEntries(observed).map((e) => [e.name, e]));
325 if (observedByName.size !== desired.length) return false;
326 return desired.every((entry) => {
327 const live = observedByName.get(entry.name);
328 return (
329 live !== undefined &&
330 live.enabled === entry.enabled &&
331 live.pattern.regex === entry.pattern.regex &&
332 (live.pattern.validation ?? undefined) === entry.pattern.validation
333 );
334 });
335 };
336
337 const toAttributes = (
338 profile: ObservedCustomProfile | undefined,
339 accountId: string,
340 ): ProfileAttributes => ({
341 profileId: profile?.id ?? "",
342 accountId,
343 name: profile?.name ?? "",
344 description: profile?.description ?? undefined,
345 allowedMatchCount: profile?.allowedMatchCount ?? 0,
346 ocrEnabled: profile?.ocrEnabled ?? false,
347 entryIds: entryIdsByName(profile),
348 });