@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 407 lines 14.9 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Predicate from "effect/Predicate";
6 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
7 import type { Providers } from "../Providers.ts";
8
9 const TypeId = "Cloudflare.Gateway.Configuration" as const;
10 type TypeId = typeof TypeId;
11
12 /**
13 * The Gateway account settings blocks this resource can manage. Only the
14 * blocks you declare are patched (and captured for restore-on-destroy);
15 * everything else on the account configuration is left untouched.
16 */
17 export interface ConfigurationSettings {
18 /** Activity logging master toggle for the account. */
19 activityLog?: { enabled?: boolean };
20 /** Anti-virus scanning of file downloads/uploads. */
21 antivirus?: {
22 /** Scan on file download. */
23 enabledDownloadPhase?: boolean;
24 /** Scan on file upload. */
25 enabledUploadPhase?: boolean;
26 /** Block requests for files that cannot be scanned. */
27 failClosed?: boolean;
28 /** Block-page notification settings shown when a file is blocked. */
29 notificationSettings?: {
30 enabled?: boolean;
31 includeContext?: boolean;
32 msg?: string;
33 supportUrl?: string;
34 };
35 };
36 /** Custom block page configuration. */
37 blockPage?: {
38 /** Background color in hex (e.g. `#1f2937`). */
39 backgroundColor?: string;
40 /** Enable the custom block page (disabled shows the default page). */
41 enabled?: boolean;
42 /** Footer text. */
43 footerText?: string;
44 /** Header text. */
45 headerText?: string;
46 /** Include rule/policy context on the page. */
47 includeContext?: boolean;
48 /** URL of a logo image to display. */
49 logoPath?: string;
50 /** Admin email shown as a mailto: link. */
51 mailtoAddress?: string;
52 /** Subject prefilled in the mailto: link. */
53 mailtoSubject?: string;
54 /** Block page mode. */
55 mode?: "" | "customized_block_page" | "redirect_uri";
56 /** Block page name. */
57 name?: string;
58 /** Hide the Cloudflare footer. */
59 suppressFooter?: boolean;
60 /** Redirect URI when `mode` is `redirect_uri`. */
61 targetUri?: string;
62 };
63 /** HTTP body scanning behaviour. */
64 bodyScanning?: { inspectionMode?: "deep" | "shallow" };
65 /** Clientless browser isolation. */
66 browserIsolation?: {
67 nonIdentityEnabled?: boolean;
68 urlBrowserIsolationEnabled?: boolean;
69 };
70 /**
71 * The Gateway-managed certificate used for TLS interception. Reference
72 * a `Cloudflare.Gateway.Certificate`'s `certificateId` here.
73 */
74 certificate?: { id: string };
75 /** Match on both email aliases and the primary address. */
76 extendedEmailMatching?: { enabled?: boolean };
77 /** FIPS-compliant TLS-only enforcement. */
78 fips?: { tls?: boolean };
79 /** Host selector (egress by hostname) support. */
80 hostSelector?: { enabled?: boolean };
81 /** Traffic inspection mode. */
82 inspection?: { mode?: "static" | "dynamic" };
83 /** Detect protocols on the initial bytes of a connection. */
84 protocolDetection?: { enabled?: boolean };
85 /** File sandboxing. */
86 sandbox?: { enabled?: boolean; fallbackAction?: "allow" | "block" };
87 /** TLS decryption (required for HTTP inspection). */
88 tlsDecrypt?: { enabled?: boolean };
89 }
90
91 export type ConfigurationBlockKey = keyof ConfigurationSettings;
92
93 export interface ConfigurationProps {
94 /**
95 * The settings blocks to manage. Reconcile patches only the declared
96 * blocks (Cloudflare PATCH semantics — undeclared blocks are never
97 * touched), and destroy restores each declared block to the value it
98 * had before Alchemy first managed it.
99 */
100 settings: ConfigurationSettings;
101 }
102
103 /**
104 * A captured snapshot of the managed settings blocks as observed on
105 * Cloudflare before Alchemy first patched them. `null` records a block
106 * that was absent at capture time.
107 */
108 export type ConfigurationSnapshot = Partial<Record<ConfigurationBlockKey, unknown>>;
109
110 export interface ConfigurationAttributes {
111 /** Account that owns the Gateway configuration singleton. */
112 accountId: string;
113 /** The full observed Gateway settings after reconciliation. */
114 settings: unknown;
115 /**
116 * The managed blocks' pre-management values, restored on destroy so
117 * deleting the resource puts the account back the way it was found.
118 */
119 initialSettings: ConfigurationSnapshot;
120 /** ISO8601 creation timestamp of the configuration. */
121 createdAt: string | undefined;
122 /** ISO8601 last-update timestamp of the configuration. */
123 updatedAt: string | undefined;
124 }
125
126 export type Configuration = Resource<
127 TypeId,
128 ConfigurationProps,
129 ConfigurationAttributes,
130 never,
131 Providers
132 >;
133
134 /**
135 * Manages the **singleton** Cloudflare Zero Trust **Gateway configuration**
136 * for an account (`/accounts/{accountId}/gateway/configuration`) —
137 * account-wide settings like activity logging, TLS decryption, the block
138 * page, anti-virus scanning, and browser isolation.
139 *
140 * The singleton always exists, so reconcile patches only the settings
141 * blocks you declare and never clobbers unmanaged blocks. The
142 * pre-management value of each managed block is captured on first touch
143 * and restored on destroy (capture-and-restore). Blocks that were unset
144 * before Alchemy managed them cannot be restored (Cloudflare's API has no
145 * way to unset a block) — destroy leaves the last managed value and logs
146 * a warning.
147 * ### Managing Gateway settings
148 * **Example:** Enable activity logging and TLS decryption
149 * ```typescript
150 * yield* Cloudflare.Gateway.Configuration("Gateway", {
151 * settings: {
152 * activityLog: { enabled: true },
153 * tlsDecrypt: { enabled: true },
154 * },
155 * });
156 * ```
157 *
158 * **Example:** Custom block page
159 * ```typescript
160 * yield* Cloudflare.Gateway.Configuration("Gateway", {
161 * settings: {
162 * blockPage: {
163 * enabled: true,
164 * headerText: "Blocked by IT",
165 * footerText: "Contact support@example.com",
166 * backgroundColor: "#1f2937",
167 * },
168 * },
169 * });
170 * ```
171 *
172 * ### TLS interception
173 * **Example:** Use a Gateway certificate for inspection
174 * ```typescript
175 * const cert = yield* Cloudflare.Gateway.Certificate("InspectionCa", {});
176 * yield* Cloudflare.Gateway.Configuration("Gateway", {
177 * settings: {
178 * tlsDecrypt: { enabled: true },
179 * certificate: { id: cert.certificateId },
180 * },
181 * });
182 * ```
183 *
184 * @see https://developers.cloudflare.com/cloudflare-one/policies/gateway/
185 *
186 * @resource
187 * @product Gateway
188 * @category Cloudflare One (Zero Trust)
189 */
190 export const Configuration = Resource<Configuration>(TypeId);
191
192 /**
193 * Returns true if the given value is a Configuration resource.
194 */
195 export const isConfiguration = (value: unknown): value is Configuration =>
196 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
197
198 export const ConfigurationProvider = () =>
199 Provider.succeed(Configuration, {
200 nuke: { singleton: true },
201 stables: ["accountId", "initialSettings", "createdAt"],
202
203 // Account-wide singleton: the Gateway configuration always exists for
204 // the ambient account, so enumeration is a single read returning a
205 // one-element array. There is no prior management context, so the
206 // restore snapshot is empty.
207 list: Effect.fn(function* () {
208 const { accountId } = yield* yield* CloudflareEnvironment;
209 const observed = yield* zeroTrust.getGatewayConfiguration({
210 accountId,
211 });
212 return [toAttributes(accountId, observed, {})];
213 }),
214
215 read: Effect.fn(function* ({ output, olds }) {
216 const { accountId } = yield* yield* CloudflareEnvironment;
217 const acct = output?.accountId ?? accountId;
218 const observed = yield* zeroTrust.getGatewayConfiguration({
219 accountId: acct,
220 });
221 // The singleton always exists with account defaults — there is
222 // nothing to "own", so a cold read adopts freely. The observed
223 // blocks at adoption time become the restore target.
224 const managed = managedKeys(olds?.settings ?? {});
225 const initialSettings =
226 output?.initialSettings ?? captureBlocks(observed.settings ?? {}, managed);
227 return toAttributes(acct, observed, initialSettings);
228 }),
229
230 reconcile: Effect.fn(function* ({ news, output }) {
231 const { accountId } = yield* yield* CloudflareEnvironment;
232 const desired = (news.settings ?? {}) as ConfigurationSettings;
233 const managed = managedKeys(desired);
234
235 // 1. Observe — the singleton always exists; read its live state.
236 const observed = yield* zeroTrust.getGatewayConfiguration({ accountId });
237 const observedSettings = (observed.settings ?? {}) as Record<string, unknown>;
238
239 // 2. Capture — pre-management values for every managed block,
240 // restored on destroy. Blocks newly managed by this update are
241 // captured now; previously captured blocks keep their original
242 // snapshot.
243 const initialSettings: ConfigurationSnapshot = {
244 ...captureBlocks(observedSettings, managed),
245 ...output?.initialSettings,
246 };
247
248 // 3. Sync — patch only when a declared block diverges from the
249 // observed state; skip the API entirely on a no-op. PATCH
250 // replaces each provided block wholly and leaves the rest alone.
251 const dirty = managed.some((key) => !subsetEquals(desired[key], observedSettings[key]));
252 if (!dirty) {
253 return toAttributes(accountId, observed, initialSettings);
254 }
255 yield* zeroTrust.patchGatewayConfiguration({
256 accountId,
257 settings: pickBlocks(
258 desired,
259 managed,
260 ) as zeroTrust.PatchGatewayConfigurationRequest["settings"],
261 });
262
263 // 4. Return — re-read so attrs reflect post-sync truth.
264 const final = yield* zeroTrust.getGatewayConfiguration({ accountId });
265 return toAttributes(accountId, final, initialSettings);
266 }),
267
268 delete: Effect.fn(function* ({ output }) {
269 const { accountId, initialSettings } = output;
270 const managed = Object.keys(initialSettings) as ConfigurationBlockKey[];
271 if (managed.length === 0) return;
272 // Observe — restore only the blocks that still diverge from their
273 // captured pre-management value (idempotent re-delete).
274 const observed = yield* zeroTrust.getGatewayConfiguration({ accountId });
275 const observedSettings = (observed.settings ?? {}) as Record<string, unknown>;
276 const restore: Record<string, unknown> = {};
277 for (const key of managed) {
278 const initial = sanitizeBlock(initialSettings[key]);
279 const current = sanitizeBlock(observedSettings[key]);
280 if (deepEquals(initial ?? null, current ?? null)) continue;
281 if (initial === undefined) {
282 // The block was absent before we managed it. Cloudflare's PATCH
283 // ignores `null` blocks, so an absent block cannot be restored —
284 // the last managed value is left in place.
285 yield* Effect.logWarning(
286 `Gateway configuration block "${key}" was unset before Alchemy managed it and cannot be restored; leaving the current value in place.`,
287 );
288 continue;
289 }
290 restore[key] = initial;
291 }
292 if (Object.keys(restore).length === 0) return;
293 yield* zeroTrust.patchGatewayConfiguration({
294 accountId,
295 settings: restore as zeroTrust.PatchGatewayConfigurationRequest["settings"],
296 });
297 }),
298 });
299
300 const managedKeys = (settings: ConfigurationSettings): ConfigurationBlockKey[] =>
301 (Object.keys(settings) as ConfigurationBlockKey[]).filter((key) => settings[key] !== undefined);
302
303 /**
304 * Capture the observed value of each managed block (read-only fields
305 * stripped so the snapshot can be patched straight back). Absent blocks
306 * are recorded as `null`; they cannot be restored on destroy because
307 * Cloudflare's PATCH ignores `null` blocks.
308 */
309 const captureBlocks = (
310 observedSettings: Partial<Record<ConfigurationBlockKey, unknown>>,
311 keys: ConfigurationBlockKey[],
312 ): ConfigurationSnapshot => {
313 const snapshot: ConfigurationSnapshot = {};
314 for (const key of keys) {
315 snapshot[key] = sanitizeBlock(observedSettings[key]) ?? null;
316 }
317 return snapshot;
318 };
319
320 const pickBlocks = (
321 settings: ConfigurationSettings,
322 keys: ConfigurationBlockKey[],
323 ): Record<string, unknown> => {
324 const picked: Record<string, unknown> = {};
325 for (const key of keys) picked[key] = settings[key];
326 return picked;
327 };
328
329 /**
330 * Read-only fields Cloudflare reports on settings blocks that the PATCH
331 * endpoint does not accept back.
332 */
333 const READ_ONLY_FIELDS = new Set([
334 "readOnly",
335 "sourceAccount",
336 "version",
337 "bindingStatus",
338 "updatedAt",
339 ]);
340
341 /**
342 * Strip read-only fields and `null`-valued leaves from an observed block
343 * so it can be compared with (and patched back as) a desired block.
344 */
345 const sanitizeBlock = (block: unknown): unknown => {
346 if (block === null || block === undefined) return undefined;
347 if (Array.isArray(block)) return block.map(sanitizeBlock);
348 if (typeof block === "object") {
349 const out: Record<string, unknown> = {};
350 for (const [k, v] of Object.entries(block as Record<string, unknown>)) {
351 if (READ_ONLY_FIELDS.has(k)) continue;
352 if (v === null || v === undefined) continue;
353 out[k] = sanitizeBlock(v);
354 }
355 return out;
356 }
357 return block;
358 };
359
360 /**
361 * True when every field declared in `desired` matches `observed`
362 * (recursively). Fields the user did not declare are ignored, so an
363 * observed block carrying extra server-side fields still counts as
364 * converged.
365 */
366 const subsetEquals = (desired: unknown, observed: unknown): boolean => {
367 if (desired === undefined) return true;
368 if (desired !== null && typeof desired === "object" && !Array.isArray(desired)) {
369 if (observed === null || observed === undefined) return false;
370 if (typeof observed !== "object" || Array.isArray(observed)) return false;
371 return Object.entries(desired as Record<string, unknown>).every(([k, v]) =>
372 subsetEquals(v, (observed as Record<string, unknown>)[k]),
373 );
374 }
375 return deepEquals(desired, observed ?? null);
376 };
377
378 const deepEquals = (a: unknown, b: unknown): boolean => {
379 if (a === b) return true;
380 if (a === null || b === null) return false;
381 if (Array.isArray(a) || Array.isArray(b)) {
382 if (!Array.isArray(a) || !Array.isArray(b)) return false;
383 if (a.length !== b.length) return false;
384 return a.every((v, i) => deepEquals(v, b[i]));
385 }
386 if (typeof a === "object" && typeof b === "object") {
387 const ak = Object.keys(a as Record<string, unknown>);
388 const bk = Object.keys(b as Record<string, unknown>);
389 if (ak.length !== bk.length) return false;
390 return ak.every((k) =>
391 deepEquals((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),
392 );
393 }
394 return false;
395 };
396
397 const toAttributes = (
398 accountId: string,
399 observed: zeroTrust.GetGatewayConfigurationResponse,
400 initialSettings: ConfigurationSnapshot,
401 ): ConfigurationAttributes => ({
402 accountId,
403 settings: observed.settings ?? {},
404 initialSettings,
405 createdAt: observed.createdAt ?? undefined,
406 updatedAt: observed.updatedAt ?? undefined,
407 });