@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 279 lines 10.6 KB
Raw
1 import * as pageShield from "@distilled.cloud/cloudflare/page-shield";
2 import { isResolved } from "alchemy/Diff";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.PageShield.Settings" as const;
12 type TypeId = typeof TypeId;
13
14 export interface SettingsProps {
15 /**
16 * Zone whose Page Shield configuration is managed. Stable — changing
17 * the zone triggers a replacement (the old zone's configuration is
18 * restored to the values it had before Alchemy managed it).
19 */
20 zoneId: string;
21 /**
22 * Whether Page Shield (client-side script monitoring) is enabled on
23 * the zone. The resource exists to turn the feature on, so this
24 * defaults to `true`. Mutable — updated in place.
25 * @default true
26 */
27 enabled?: boolean;
28 /**
29 * When true, CSP reports are sent to Cloudflare's own reporting
30 * endpoint (`https://csp-reporting.cloudflare.com/...`) instead of
31 * the zone's `/cdn-cgi/script_monitor/report` path. Mutable.
32 *
33 * Setting this to `false` requires the dedicated-domain-reporting
34 * entitlement — on non-entitled zones the write fails with the typed
35 * `NotEntitled` error.
36 * @default true
37 */
38 useCloudflareReportingEndpoint?: boolean;
39 /**
40 * When true, the paths associated with connection URLs are also
41 * analyzed (not just the host). Mutable.
42 *
43 * Setting this to `true` requires the connection-monitor entitlement
44 * (Business/Enterprise) — on non-entitled zones the write fails with
45 * the typed `NotEntitled` error.
46 * @default false
47 */
48 useConnectionUrlPath?: boolean;
49 }
50
51 export interface SettingsAttributes {
52 /** Zone the configuration belongs to. */
53 zoneId: string;
54 /** Whether Page Shield is enabled. */
55 enabled: boolean;
56 /** Whether CSP reports are sent to Cloudflare's reporting endpoint. */
57 useCloudflareReportingEndpoint: boolean;
58 /** Whether connection URL paths are analyzed. */
59 useConnectionUrlPath: boolean;
60 /** When the Page Shield configuration was last updated. */
61 updatedAt: string;
62 /**
63 * The `enabled` flag the zone had before Alchemy first touched the
64 * configuration. Restored on destroy.
65 */
66 initialEnabled: boolean;
67 /**
68 * The `useCloudflareReportingEndpoint` flag the zone had before
69 * Alchemy first touched the configuration. Restored on destroy.
70 */
71 initialUseCloudflareReportingEndpoint: boolean;
72 /**
73 * The `useConnectionUrlPath` flag the zone had before Alchemy first
74 * touched the configuration. Restored on destroy.
75 */
76 initialUseConnectionUrlPath: boolean;
77 }
78
79 export type Settings = Resource<TypeId, SettingsProps, SettingsAttributes, never, Providers>;
80
81 /**
82 * The Page Shield configuration of a Cloudflare zone
83 * (`/zones/{zone_id}/page_shield`).
84 *
85 * Page Shield monitors the JavaScript and connections loaded by your
86 * visitors' browsers to detect supply-chain attacks (e.g. Magecart). The
87 * configuration is a zone **singleton** — it always exists (default
88 * disabled), so this resource never creates or deletes anything physical.
89 * Reconcile PUTs the configuration when the observed flags differ from the
90 * desired ones; destroy restores the flags the zone had before Alchemy
91 * first managed them.
92 *
93 * Script/connection *monitoring data* requires a Business or Enterprise
94 * zone plan, but the configuration endpoints themselves accept reads and
95 * `enabled` writes on lower plans. Setting `useConnectionUrlPath: true`
96 * or `useCloudflareReportingEndpoint: false` on a non-entitled zone fails
97 * with the typed `NotEntitled` error.
98 *
99 * Only one `Settings` resource per zone makes sense — two
100 * instances managing the same zone would fight over the singleton.
101 * ### Managing Page Shield
102 * **Example:** Enable Page Shield on a zone
103 * ```typescript
104 * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" });
105 *
106 * yield* Cloudflare.PageShield.Settings("PageShield", {
107 * zoneId: zone.zoneId,
108 * });
109 * ```
110 *
111 * **Example:** Analyze connection URL paths too
112 * ```typescript
113 * yield* Cloudflare.PageShield.Settings("PageShield", {
114 * zoneId: zone.zoneId,
115 * useConnectionUrlPath: true,
116 * });
117 * ```
118 *
119 * **Example:** Report CSP violations to the zone instead of Cloudflare
120 * ```typescript
121 * yield* Cloudflare.PageShield.Settings("PageShield", {
122 * zoneId: zone.zoneId,
123 * useCloudflareReportingEndpoint: false,
124 * });
125 * ```
126 *
127 * @see https://developers.cloudflare.com/page-shield/
128 *
129 * @resource
130 * @product Page Shield
131 * @category Application Security
132 */
133 export const Settings = Resource<Settings>(TypeId);
134
135 /**
136 * Returns true if the given value is a Settings resource.
137 */
138 export const isSettings = (value: unknown): value is Settings =>
139 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
140
141 interface DesiredSettings {
142 enabled: boolean;
143 useCloudflareReportingEndpoint: boolean;
144 useConnectionUrlPath: boolean;
145 }
146
147 const desiredSettings = (props: SettingsProps): DesiredSettings => ({
148 enabled: props.enabled ?? true,
149 useCloudflareReportingEndpoint: props.useCloudflareReportingEndpoint ?? true,
150 useConnectionUrlPath: props.useConnectionUrlPath ?? false,
151 });
152
153 export const SettingsProvider = () =>
154 Provider.succeed(Settings, {
155 nuke: { singleton: true },
156 stables: [
157 "zoneId",
158 "initialEnabled",
159 "initialUseCloudflareReportingEndpoint",
160 "initialUseConnectionUrlPath",
161 ],
162
163 list: Effect.fn(function* () {
164 const { accountId } = yield* yield* CloudflareEnvironment;
165 // No account-wide API for this zone singleton — enumerate every
166 // zone in the account and read its configuration (every zone has
167 // one, defaulting to disabled).
168 const allZones = yield* listAllZones(accountId);
169 const rows = yield* Effect.forEach(
170 allZones.map((zone) => zone.id),
171 (zoneId) =>
172 pageShield.getPageShield({ zoneId }).pipe(
173 // On a cold enumeration the observed flags are the zone's
174 // current state and double as the `initial*` baseline.
175 Effect.map((observed) => toAttributes(zoneId, observed, observed)),
176 // Zones the scoped token can't read (partial / restricted)
177 // reject with the typed `Forbidden` error; skip them.
178 Effect.catchTag("Forbidden", () => Effect.undefined),
179 ),
180 { concurrency: 10 },
181 );
182 return rows.filter((row): row is SettingsAttributes => row !== undefined);
183 }),
184
185 diff: Effect.fn(function* ({ news, output }) {
186 if (!isResolved(news)) return undefined;
187 // zoneId is the singleton's identity — moving the resource to a
188 // different zone replaces it (restoring the old zone on delete).
189 if (output !== undefined && output.zoneId !== news.zoneId) {
190 return { action: "replace" } as const;
191 }
192 return undefined;
193 }),
194
195 read: Effect.fn(function* ({ output, olds }) {
196 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
197 if (!zoneId) return undefined;
198 const observed = yield* pageShield.getPageShield({ zoneId });
199 // The configuration is a singleton that always exists with a
200 // Cloudflare default — there is nothing to "own", so a cold read
201 // adopts freely (never `Unowned`). The observed flags at adoption
202 // time become the `initial*` values restored on destroy.
203 const initial: DesiredSettings =
204 output !== undefined
205 ? {
206 enabled: output.initialEnabled,
207 useCloudflareReportingEndpoint: output.initialUseCloudflareReportingEndpoint,
208 useConnectionUrlPath: output.initialUseConnectionUrlPath,
209 }
210 : observed;
211 return toAttributes(zoneId, observed, initial);
212 }),
213
214 reconcile: Effect.fn(function* ({ news, output }) {
215 // Inputs have been resolved to concrete strings by Plan.
216 const zoneId = news.zoneId as string;
217
218 // 1. Observe — the configuration always exists; read its live state.
219 const observed = yield* pageShield.getPageShield({ zoneId });
220
221 // 2. Capture — the pre-management flags, restored on destroy.
222 // `output` (including an adoption read) already carries them;
223 // otherwise this is our first touch and the observed flags are
224 // the zone's original.
225 const initial: DesiredSettings =
226 output !== undefined
227 ? {
228 enabled: output.initialEnabled,
229 useCloudflareReportingEndpoint: output.initialUseCloudflareReportingEndpoint,
230 useConnectionUrlPath: output.initialUseConnectionUrlPath,
231 }
232 : observed;
233
234 // 3. Sync — PUT the full desired body only when something differs.
235 const desired = desiredSettings(news);
236 if (sameSettings(observed, desired)) {
237 return toAttributes(zoneId, observed, initial);
238 }
239 const updated = yield* pageShield.putPageShield({
240 zoneId,
241 ...desired,
242 });
243 return toAttributes(zoneId, updated, initial);
244 }),
245
246 delete: Effect.fn(function* ({ output }) {
247 const { zoneId } = output;
248 const initial: DesiredSettings = {
249 enabled: output.initialEnabled,
250 useCloudflareReportingEndpoint: output.initialUseCloudflareReportingEndpoint,
251 useConnectionUrlPath: output.initialUseConnectionUrlPath,
252 };
253 // Observe, then restore the pre-management flags; skip the call
254 // when they already match (idempotent re-delete after a crash).
255 const observed = yield* pageShield.getPageShield({ zoneId });
256 if (sameSettings(observed, initial)) return;
257 yield* pageShield.putPageShield({ zoneId, ...initial });
258 }),
259 });
260
261 const sameSettings = (a: DesiredSettings, b: DesiredSettings): boolean =>
262 a.enabled === b.enabled &&
263 a.useCloudflareReportingEndpoint === b.useCloudflareReportingEndpoint &&
264 a.useConnectionUrlPath === b.useConnectionUrlPath;
265
266 const toAttributes = (
267 zoneId: string,
268 observed: pageShield.GetPageShieldResponse | pageShield.PutPageShieldResponse,
269 initial: DesiredSettings,
270 ): SettingsAttributes => ({
271 zoneId,
272 enabled: observed.enabled,
273 useCloudflareReportingEndpoint: observed.useCloudflareReportingEndpoint,
274 useConnectionUrlPath: observed.useConnectionUrlPath,
275 updatedAt: observed.updatedAt,
276 initialEnabled: initial.enabled,
277 initialUseCloudflareReportingEndpoint: initial.useCloudflareReportingEndpoint,
278 initialUseConnectionUrlPath: initial.useConnectionUrlPath,
279 });