@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 326 lines 12.3 KB
Raw
1 import * as lcc from "@distilled.cloud/cloudflare/leaked-credential-checks";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
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 import { listAllZones } from "../Zone/lookup.ts";
12
13 const TypeId = "Cloudflare.LeakedCredentialCheck.Detection" as const;
14 type TypeId = typeof TypeId;
15
16 export interface LeakedCredentialDetectionProps {
17 /**
18 * Zone the custom detection belongs to. Stable — moving a detection
19 * between zones triggers a replacement.
20 */
21 zoneId: string;
22 /**
23 * Ruleset expression locating the username in the request, e.g.
24 * `lookup_json_string(http.request.body.raw, "user")`. Mutable —
25 * updated in place via PUT. At least one of `username`/`password`
26 * should be set.
27 */
28 username?: string;
29 /**
30 * Ruleset expression locating the password in the request, e.g.
31 * `lookup_json_string(http.request.body.raw, "secret")`. This is an
32 * expression over the request (not a secret value). Mutable — updated
33 * in place via PUT.
34 */
35 password?: string;
36 }
37
38 export interface LeakedCredentialDetectionAttributes {
39 /** Cloudflare-assigned identifier of the custom detection. */
40 detectionId: string;
41 /** Zone the detection belongs to. */
42 zoneId: string;
43 /** The username-locating ruleset expression, if set. */
44 username: string | undefined;
45 /** The password-locating ruleset expression, if set. */
46 password: string | undefined;
47 }
48
49 export type LeakedCredentialDetection = Resource<
50 TypeId,
51 LeakedCredentialDetectionProps,
52 LeakedCredentialDetectionAttributes,
53 never,
54 Providers
55 >;
56
57 /**
58 * A custom detection location for Cloudflare Leaked Credential Checks
59 * (`/zones/{zone_id}/leaked-credential-checks/detections`) — a pair of
60 * ruleset expressions telling the WAF where to find the username and
61 * password in your application's login requests, so credentials submitted
62 * in non-standard payloads can still be checked against breach data.
63 *
64 * Requires Leaked Credential Checks to be **enabled** on the zone (see
65 * {@link LeakedCredentialCheck}) — every detection operation fails with the
66 * typed `LeakedCredentialChecksDisabled` error otherwise. The number of
67 * custom detections is plan-gated — a zone over its quota fails creation
68 * with the typed `DetectionQuotaExceeded` error. Each username/password
69 * expression pair may exist only once per zone (`DetectionAlreadyExists`).
70 *
71 * Safety: detections carry no ownership markers. When there is no prior
72 * state, `read` scans the zone for an existing detection with the same
73 * expressions and reports it as `Unowned`, so the engine refuses to take
74 * it over unless `--adopt` (or `adopt(true)`) is set.
75 * ### Custom detection locations
76 * **Example:** Detect credentials in a JSON login body
77 * ```typescript
78 * const check = yield* Cloudflare.LeakedCredentialCheck.LeakedCredentialCheck("Lcc", {
79 * zoneId: zone.zoneId,
80 * });
81 *
82 * yield* Cloudflare.LeakedCredentialCheck.LeakedCredentialDetection("LoginBody", {
83 * // Reference the check's zoneId so the toggle deploys first.
84 * zoneId: check.zoneId,
85 * username: 'lookup_json_string(http.request.body.raw, "user")',
86 * password: 'lookup_json_string(http.request.body.raw, "secret")',
87 * });
88 * ```
89 *
90 * **Example:** Username-only detection
91 * ```typescript
92 * yield* Cloudflare.LeakedCredentialCheck.LeakedCredentialDetection("UsernameHeader", {
93 * zoneId: check.zoneId,
94 * username: 'http.request.headers["x-username"][0]',
95 * });
96 * ```
97 *
98 * @see https://developers.cloudflare.com/waf/detections/leaked-credentials/#custom-detection-locations
99 *
100 * @resource
101 * @product Leaked Credential Checks
102 * @category Application Security
103 */
104 export const LeakedCredentialDetection = Resource<LeakedCredentialDetection>(TypeId);
105
106 /**
107 * Creating a detection failed with `DetectionAlreadyExists`, but no detection
108 * with the same username/password expressions could be found on the zone.
109 */
110 export class DetectionConflictUnresolved extends Data.TaggedError("DetectionConflictUnresolved")<{
111 readonly zoneId: string;
112 }> {
113 override get message() {
114 return `Leaked credential detection reported as existing on zone ${this.zoneId} but was not found`;
115 }
116 }
117
118 /**
119 * Returns true if the given value is a LeakedCredentialDetection resource.
120 */
121 export const isLeakedCredentialDetection = (value: unknown): value is LeakedCredentialDetection =>
122 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
123
124 export const LeakedCredentialDetectionProvider = () =>
125 Provider.succeed(LeakedCredentialDetection, {
126 stables: ["detectionId", "zoneId"],
127
128 list: Effect.fn(function* () {
129 const { accountId } = yield* yield* CloudflareEnvironment;
130 // Detections live inside a zone (`/zones/{id}/.../detections`) with
131 // no account-wide enumeration API — fan out across every zone and
132 // exhaustively paginate the per-zone list.
133 const zones = yield* listAllZones(accountId);
134 const rows = yield* Effect.forEach(
135 zones,
136 (zone) =>
137 lcc.listDetections.pages({ zoneId: zone.id }).pipe(
138 Stream.runCollect,
139 Effect.map((chunk) =>
140 Array.from(chunk).flatMap((page) =>
141 (page.result ?? []).map((d): LeakedCredentialDetectionAttributes =>
142 toAttributes(zone.id, d),
143 ),
144 ),
145 ),
146 // Zones without the LCC toggle on refuse all detection reads;
147 // a freshly-minted scoped token can also 403 mid edge-
148 // propagation. Either way the zone contributes nothing.
149 Effect.catchTags({
150 LeakedCredentialChecksDisabled: (): Effect.Effect<
151 LeakedCredentialDetectionAttributes[]
152 > => Effect.succeed([]),
153 Forbidden: (): Effect.Effect<LeakedCredentialDetectionAttributes[]> =>
154 Effect.succeed([]),
155 }),
156 ),
157 { concurrency: 10 },
158 );
159 return rows.flat();
160 }),
161
162 diff: Effect.fn(function* ({ olds = {}, news, output }) {
163 const o = olds as LeakedCredentialDetectionProps;
164 const n = news as LeakedCredentialDetectionProps;
165 // zoneId is Input<string>; compare only once both sides are concrete.
166 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
167 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
168 return { action: "replace" } as const;
169 }
170 return undefined;
171 }),
172
173 read: Effect.fn(function* ({ output, olds }) {
174 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
175 if (!zoneId) return undefined;
176
177 // Owned path: refresh by our persisted detection id.
178 if (output?.detectionId) {
179 const observed = yield* getDetection(zoneId, output.detectionId);
180 if (observed) return toAttributes(zoneId, observed);
181 }
182
183 // Adoption path: a detection with these expressions may already
184 // exist on the zone. Detections carry no ownership markers, so we
185 // cannot prove we created it — brand it `Unowned` so the engine
186 // refuses to take over unless `adopt` is set.
187 const username = output?.username ?? olds?.username;
188 const password = output?.password ?? olds?.password;
189 if (username !== undefined || password !== undefined) {
190 const observed = yield* findByExpressions(zoneId, username, password);
191 if (observed) return Unowned(toAttributes(zoneId, observed));
192 }
193 return undefined;
194 }),
195
196 reconcile: Effect.fn(function* ({ news, output }) {
197 // Inputs have been resolved to concrete strings by Plan.
198 const zoneId = news.zoneId as string;
199
200 // 1. Observe — the detection id cached on `output` is a hint, not
201 // a guarantee: a missing detection falls through to the
202 // expression scan and then to create.
203 let observed = output?.detectionId
204 ? yield* getDetection(zoneId, output.detectionId)
205 : undefined;
206
207 // 2. Fall back to scanning the zone for an expression match.
208 // Ownership has already been verified upstream — `read` reports
209 // existing detections as `Unowned` and the engine gates takeover
210 // behind the adopt policy before reconcile ever runs.
211 if (!observed) {
212 observed = yield* findByExpressions(zoneId, news.username, news.password);
213 }
214
215 // 3. Ensure — create when missing. Requires the zone's Leaked
216 // Credential Checks toggle to be on; otherwise this fails with
217 // the typed `LeakedCredentialChecksDisabled` error.
218 // A concurrent create of the same expression pair races us to
219 // the typed `DetectionAlreadyExists` — re-observe and continue.
220 if (!observed) {
221 observed = yield* lcc
222 .createDetection({
223 zoneId,
224 username: news.username,
225 password: news.password,
226 })
227 .pipe(
228 Effect.map((d): ObservedDetection | undefined => d),
229 Effect.catchTag("DetectionAlreadyExists", () =>
230 findByExpressions(zoneId, news.username, news.password),
231 ),
232 );
233 if (!observed) {
234 return yield* new DetectionConflictUnresolved({ zoneId });
235 }
236 }
237
238 // 4. Sync — PUT only when the observed expressions differ.
239 const dirty =
240 (observed.username ?? undefined) !== news.username ||
241 (observed.password ?? undefined) !== news.password;
242 if (dirty) {
243 observed = yield* lcc.updateDetection({
244 zoneId,
245 detectionId: observed.id ?? "",
246 username: news.username,
247 password: news.password,
248 });
249 }
250
251 return toAttributes(zoneId, observed);
252 }),
253
254 delete: Effect.fn(function* ({ output }) {
255 yield* lcc
256 .deleteDetection({
257 zoneId: output.zoneId,
258 detectionId: output.detectionId,
259 })
260 .pipe(
261 // Already gone — idempotent re-delete after a crashed run.
262 Effect.catchTags({
263 DetectionNotFound: () => Effect.void,
264 // The zone's toggle was switched off out-of-band; the API
265 // refuses all detection operations then. The detection is
266 // unreachable either way — treat as converged.
267 LeakedCredentialChecksDisabled: () => Effect.void,
268 }),
269 );
270 }),
271 });
272
273 // ---------------------------------------------------------------------------
274 // API helpers
275 // ---------------------------------------------------------------------------
276
277 type ObservedDetection = {
278 id?: string | null;
279 username?: string | null;
280 password?: string | null;
281 };
282
283 /**
284 * Read a detection by id, mapping "gone" (`DetectionNotFound`, Cloudflare
285 * error code 11002) and "product off" (`LeakedCredentialChecksDisabled`,
286 * code 11001 — the API refuses all detection reads while the zone toggle is
287 * off) to `undefined`.
288 */
289 const getDetection = (zoneId: string, detectionId: string) =>
290 lcc.getDetection({ zoneId, detectionId }).pipe(
291 Effect.map((d): ObservedDetection | undefined => d),
292 Effect.catchTags({
293 DetectionNotFound: () => Effect.undefined,
294 LeakedCredentialChecksDisabled: () => Effect.undefined,
295 }),
296 );
297
298 /**
299 * Find a detection by exact username+password expression pair within the
300 * zone. Used for cold reads (state lost) and as the create fallback.
301 */
302 const findByExpressions = (
303 zoneId: string,
304 username: string | undefined,
305 password: string | undefined,
306 ) =>
307 lcc.listDetections.items({ zoneId }).pipe(
308 Stream.runCollect,
309 Effect.map((chunk) =>
310 Array.from(chunk).find(
311 (d): d is ObservedDetection =>
312 (d.username ?? undefined) === username && (d.password ?? undefined) === password,
313 ),
314 ),
315 Effect.catchTag("LeakedCredentialChecksDisabled", () => Effect.undefined),
316 );
317
318 const toAttributes = (
319 zoneId: string,
320 detection: ObservedDetection,
321 ): LeakedCredentialDetectionAttributes => ({
322 detectionId: detection.id ?? "",
323 zoneId,
324 username: detection.username ?? undefined,
325 password: detection.password ?? undefined,
326 });