@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, 06:00 UTC

main
ts 373 lines 12.5 KB
Raw
1 import * as turnstile from "@distilled.cloud/cloudflare/turnstile";
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 Redacted from "effect/Redacted";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.Turnstile.Widget" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Rendering / interaction mode of a Turnstile widget.
18 */
19 export type WidgetMode = "managed" | "non-interactive" | "invisible";
20
21 /**
22 * Region a Turnstile widget can be served from. Cannot be changed after
23 * creation.
24 */
25 export type WidgetRegion = "world" | "china";
26
27 /**
28 * Clearance level granted when the widget is embedded on a Cloudflare zone.
29 */
30 export type ClearanceLevel = "no_clearance" | "jschallenge" | "managed" | "interactive";
31
32 export type WidgetProps = {
33 /**
34 * Human readable widget name. Not unique. If omitted, a unique name is
35 * generated from the app, stage, and logical ID.
36 * @default ${app}-${stage}-${id}
37 */
38 name?: string;
39 /**
40 * Hostnames the widget is allowed to run on (e.g. `example.com`).
41 * Subdomains are covered automatically.
42 */
43 domains: string[];
44 /**
45 * Widget mode: `managed` (Cloudflare decides if an interaction is
46 * required), `non-interactive` (never requires interaction), or
47 * `invisible` (no visible widget).
48 */
49 mode: WidgetMode;
50 /**
51 * Region where this widget can be used. Cannot be changed after creation —
52 * updating this property triggers a replacement.
53 * @default "world"
54 */
55 region?: WidgetRegion;
56 /**
57 * If `true`, Cloudflare issues computationally expensive challenges in
58 * response to malicious bots (Enterprise only).
59 * @default false
60 */
61 botFightMode?: boolean;
62 /**
63 * If Turnstile is embedded on a Cloudflare site and the widget should
64 * grant challenge clearance, this setting determines the clearance level.
65 * @default "no_clearance"
66 */
67 clearanceLevel?: ClearanceLevel;
68 /**
69 * Return the Ephemeral ID in `/siteverify` responses (Enterprise only).
70 * @default false
71 */
72 ephemeralId?: boolean;
73 /**
74 * Do not show any Cloudflare branding on the widget (Enterprise only).
75 * @default false
76 */
77 offlabel?: boolean;
78 };
79
80 export type WidgetAttributes = {
81 /**
82 * Widget item identifier tag. This is the public sitekey embedded in HTML.
83 */
84 sitekey: string;
85 /**
86 * Secret key for this widget, used server-side with the
87 * `/turnstile/v0/siteverify` endpoint.
88 */
89 secret: Redacted.Redacted<string>;
90 /**
91 * The Cloudflare account the widget belongs to.
92 */
93 accountId: string;
94 /**
95 * Human readable widget name.
96 */
97 name: string;
98 /**
99 * Hostnames the widget is allowed to run on.
100 */
101 domains: string[];
102 /**
103 * Widget mode.
104 */
105 mode: WidgetMode;
106 /**
107 * Region where this widget can be used.
108 */
109 region: WidgetRegion;
110 /**
111 * Whether bot fight mode is enabled (Enterprise only).
112 */
113 botFightMode: boolean;
114 /**
115 * Clearance level granted on Cloudflare zones.
116 */
117 clearanceLevel: ClearanceLevel;
118 /**
119 * Whether the Ephemeral ID is returned in `/siteverify` (Enterprise only).
120 */
121 ephemeralId: boolean;
122 /**
123 * Whether Cloudflare branding is hidden (Enterprise only).
124 */
125 offlabel: boolean;
126 /**
127 * When the widget was created.
128 */
129 createdOn: string;
130 /**
131 * When the widget was last modified.
132 */
133 modifiedOn: string;
134 };
135
136 export type Widget = Resource<TypeId, WidgetProps, WidgetAttributes, never, Providers>;
137
138 /**
139 * A Cloudflare Turnstile widget — Cloudflare's CAPTCHA alternative.
140 *
141 * A widget is identified by its auto-assigned `sitekey` (the public key you
142 * embed in HTML) and produces a `secret` used server-side against the
143 * `/turnstile/v0/siteverify` endpoint. Name, domains, mode, and clearance
144 * settings are all mutable in place; only `region` forces a replacement.
145 * ### Creating a Widget
146 * **Example:** Managed widget
147 * ```typescript
148 * const widget = yield* Cloudflare.Turnstile.Widget("signup-form", {
149 * domains: ["example.com"],
150 * mode: "managed",
151 * });
152 * ```
153 *
154 * **Example:** Invisible widget with an explicit name
155 * ```typescript
156 * const widget = yield* Cloudflare.Turnstile.Widget("api-guard", {
157 * name: "api-guard",
158 * domains: ["example.com", "app.example.com"],
159 * mode: "invisible",
160 * });
161 * ```
162 *
163 * ### Using the keys
164 * **Example:** Embedding the sitekey and verifying tokens
165 * ```typescript
166 * // The sitekey is public — render it in your HTML:
167 * const sitekey = widget.sitekey;
168 *
169 * // The secret is redacted — pass it to your server-side verifier:
170 * const secret = widget.secret; // Redacted<string>
171 * ```
172 *
173 * @see https://developers.cloudflare.com/turnstile/
174 *
175 * @resource
176 * @product Turnstile
177 * @category Application Security
178 */
179 export const Widget = Resource<Widget>(TypeId);
180
181 /**
182 * Returns true if the given value is a Widget resource.
183 */
184 export const isWidget = (value: unknown): value is Widget =>
185 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
186
187 export const WidgetProvider = () =>
188 Provider.succeed(Widget, {
189 stables: ["sitekey", "accountId", "region", "createdOn"],
190 diff: Effect.fn(function* ({ olds, news, output }) {
191 const { accountId } = yield* yield* CloudflareEnvironment;
192 if (!isResolved(news)) return undefined;
193 if ((output?.accountId ?? accountId) !== accountId) {
194 return { action: "replace" } as const;
195 }
196 // Region cannot be changed after creation.
197 const oldRegion = output?.region ?? olds?.region ?? "world";
198 if ((news.region ?? "world") !== oldRegion) {
199 return { action: "replace" } as const;
200 }
201 return undefined;
202 }),
203 read: Effect.fn(function* ({ id, output, olds }) {
204 const { accountId } = yield* yield* CloudflareEnvironment;
205 const acct = output?.accountId ?? accountId;
206
207 if (output?.sitekey) {
208 const observed = yield* getWidget(acct, output.sitekey);
209 return observed ? toAttributes(observed, acct) : undefined;
210 }
211 // Cold read — recover from lost state by matching the deterministic
212 // physical name. Names are not unique on Cloudflare's side; an exact
213 // match on our generated/explicit name is the best identity we have.
214 const name = yield* createWidgetName(id, olds?.name);
215 const match = yield* findByName(acct, name);
216 if (match) {
217 const observed = yield* getWidget(acct, match.sitekey);
218 return observed ? toAttributes(observed, acct) : undefined;
219 }
220 return undefined;
221 }),
222 reconcile: Effect.fn(function* ({ id, news, output }) {
223 const { accountId } = yield* yield* CloudflareEnvironment;
224 const name = yield* createWidgetName(id, news.name);
225
226 // Observe — the sitekey cached on `output` is a hint, not a
227 // guarantee: a 404 falls through to "missing" and we recreate.
228 const observed = output?.sitekey
229 ? yield* getWidget(output.accountId ?? accountId, output.sitekey)
230 : undefined;
231
232 if (!observed) {
233 // Ensure — greenfield (or out-of-band delete): create with the
234 // full desired body. Names are not unique so there is no
235 // AlreadyExists race to tolerate.
236 const created = yield* turnstile.createWidget({
237 accountId,
238 name,
239 domains: news.domains,
240 mode: news.mode,
241 region: news.region,
242 botFightMode: news.botFightMode,
243 clearanceLevel: news.clearanceLevel,
244 ephemeralId: news.ephemeralId,
245 offlabel: news.offlabel,
246 });
247 return toAttributes(created, accountId);
248 }
249
250 // Sync — diff observed cloud state against desired; the update API
251 // is a PUT that requires the full body, so send everything, but
252 // skip the call entirely on a no-op.
253 const desired = {
254 name,
255 domains: news.domains,
256 mode: news.mode,
257 botFightMode: news.botFightMode ?? observedBool(observed.botFightMode),
258 clearanceLevel: news.clearanceLevel ?? (observed.clearanceLevel as ClearanceLevel),
259 ephemeralId: news.ephemeralId ?? observedBool(observed.ephemeralId),
260 offlabel: news.offlabel ?? observedBool(observed.offlabel),
261 };
262 const dirty =
263 observed.name !== desired.name ||
264 observed.mode !== desired.mode ||
265 !sameDomains(observed.domains, desired.domains) ||
266 (news.botFightMode !== undefined && observed.botFightMode !== news.botFightMode) ||
267 (news.clearanceLevel !== undefined && observed.clearanceLevel !== news.clearanceLevel) ||
268 (news.ephemeralId !== undefined && observed.ephemeralId !== news.ephemeralId) ||
269 (news.offlabel !== undefined && observed.offlabel !== news.offlabel);
270
271 if (!dirty) {
272 return toAttributes(observed, observed.accountId);
273 }
274
275 const updated = yield* turnstile.updateWidget({
276 accountId: observed.accountId,
277 sitekey: observed.sitekey,
278 ...desired,
279 });
280 return toAttributes(updated, observed.accountId);
281 }),
282 delete: Effect.fn(function* ({ output }) {
283 yield* turnstile
284 .deleteWidget({
285 accountId: output.accountId,
286 sitekey: output.sitekey,
287 })
288 .pipe(Effect.catchTag("WidgetNotFound", () => Effect.void));
289 }),
290 list: Effect.fn(function* () {
291 const { accountId } = yield* yield* CloudflareEnvironment;
292 // Enumerate every widget in the account, paginating exhaustively.
293 const pages = yield* turnstile.listWidgets.pages({ accountId }).pipe(Stream.runCollect);
294 const sitekeys = Array.from(pages).flatMap((page) =>
295 (page.result ?? []).map((w) => w.sitekey),
296 );
297 // The list payload omits the write-only `secret`, so hydrate each
298 // widget via `getWidget` to produce the exact `read` Attributes
299 // shape. A widget deleted between list and get surfaces as
300 // `WidgetNotFound` (mapped to `undefined` by `getWidget`).
301 const rows = yield* Effect.forEach(
302 sitekeys,
303 (sitekey) =>
304 getWidget(accountId, sitekey).pipe(
305 Effect.map((w) => (w ? toAttributes(w, accountId) : undefined)),
306 ),
307 { concurrency: 10 },
308 );
309 return rows.filter((row): row is WidgetAttributes => row !== undefined);
310 }),
311 });
312
313 type ObservedWidget = turnstile.GetWidgetResponse & { accountId: string };
314
315 /**
316 * Read a widget by sitekey, mapping "gone" (`WidgetNotFound`, Cloudflare
317 * error code 10404) to `undefined`.
318 */
319 const getWidget = (accountId: string, sitekey: string) =>
320 turnstile.getWidget({ accountId, sitekey }).pipe(
321 Effect.map((w): ObservedWidget => ({ ...w, accountId })),
322 Effect.catchTag("WidgetNotFound", () => Effect.undefined),
323 );
324
325 /**
326 * Find a widget by exact name. Cloudflare's `filter` is a case-insensitive
327 * substring match, so re-check exactly client-side. If several widgets carry
328 * the same name, pick the oldest for determinism.
329 */
330 const findByName = (accountId: string, name: string) =>
331 turnstile.listWidgets.items({ accountId, filter: `name:${name}` }).pipe(
332 Stream.filter((w) => w.name === name),
333 Stream.runCollect,
334 Effect.map((chunk) =>
335 Array.from(chunk)
336 .sort((a, b) => a.createdOn.localeCompare(b.createdOn))
337 .at(0),
338 ),
339 );
340
341 const createWidgetName = (id: string, name: string | undefined) =>
342 Effect.gen(function* () {
343 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
344 });
345
346 const observedBool = (value: boolean | undefined) => value ?? false;
347
348 const sameDomains = (observed: readonly string[], desired: readonly string[]) =>
349 observed.length === desired.length &&
350 [...observed].sort().join(",") === [...desired].sort().join(",");
351
352 const toAttributes = (
353 widget:
354 | turnstile.GetWidgetResponse
355 | turnstile.CreateWidgetResponse
356 | turnstile.UpdateWidgetResponse,
357 accountId: string,
358 ): WidgetAttributes => ({
359 sitekey: widget.sitekey,
360 secret: Redacted.make(widget.secret),
361 accountId,
362 name: widget.name,
363 // Distilled widens generated string enums to open unions (`string & {}`).
364 domains: [...widget.domains],
365 mode: widget.mode as WidgetMode,
366 region: widget.region as WidgetRegion,
367 botFightMode: widget.botFightMode,
368 clearanceLevel: widget.clearanceLevel as ClearanceLevel,
369 ephemeralId: widget.ephemeralId,
370 offlabel: widget.offlabel,
371 createdOn: widget.createdOn,
372 modifiedOn: widget.modifiedOn,
373 });