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

main
ts 254 lines 9.09 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.Logging" as const;
10 type TypeId = typeof TypeId;
11
12 /**
13 * Per-rule-type logging toggles.
14 */
15 export interface LoggingRuleSettings {
16 /** Log all requests of this type, regardless of rule matches. */
17 logAll?: boolean;
18 /** Log only requests blocked by a rule. */
19 logBlocks?: boolean;
20 }
21
22 /**
23 * A snapshot of the account's Gateway logging settings as observed on
24 * Cloudflare. Captured before Alchemy first writes the singleton and
25 * restored on destroy.
26 */
27 export interface LoggingSnapshot {
28 /** Whether PII is redacted from activity logs. */
29 redactPii?: boolean;
30 /** Logging settings for DNS queries. */
31 dns?: LoggingRuleSettings;
32 /** Logging settings for HTTP requests. */
33 http?: LoggingRuleSettings;
34 /** Logging settings for layer-4 (network) sessions. */
35 l4?: LoggingRuleSettings;
36 }
37
38 export interface LoggingProps {
39 /**
40 * Redact personally identifiable information from activity logging
41 * (PII fields include source IP, user email, user ID, device ID, URL,
42 * referrer, and user agent).
43 */
44 redactPii?: boolean;
45 /**
46 * Logging settings per rule type. Only the rule types (and fields) you
47 * declare are converged; everything else keeps its current value.
48 */
49 settingsByRuleType?: {
50 /** Logging settings for DNS queries. */
51 dns?: LoggingRuleSettings;
52 /** Logging settings for HTTP requests. */
53 http?: LoggingRuleSettings;
54 /** Logging settings for layer-4 (network) sessions. */
55 l4?: LoggingRuleSettings;
56 };
57 }
58
59 export type LoggingAttributes = LoggingSnapshot & {
60 /** Account that owns the Gateway logging singleton. */
61 accountId: string;
62 /**
63 * The logging settings the account had before Alchemy first wrote
64 * them. Restored (via PUT) on destroy, so deleting the resource puts
65 * the account back the way it was found.
66 */
67 initialSettings: LoggingSnapshot;
68 };
69
70 export type Logging = Resource<TypeId, LoggingProps, LoggingAttributes, never, Providers>;
71
72 /**
73 * Manages the **singleton** Cloudflare Zero Trust **Gateway logging
74 * settings** for an account (`/accounts/{accountId}/gateway/logging`) —
75 * PII redaction and per-rule-type (DNS / HTTP / L4) activity-log toggles.
76 *
77 * The singleton always exists, so reconcile converges only the fields you
78 * declare (merging them over the observed state before the PUT, since the
79 * API is PUT-only). The pre-management snapshot is captured on first touch
80 * and restored on destroy (capture-and-restore).
81 * ### Managing logging settings
82 * **Example:** Log everything, keep PII
83 * ```typescript
84 * yield* Cloudflare.Gateway.Logging("Logging", {
85 * redactPii: false,
86 * settingsByRuleType: {
87 * dns: { logAll: true, logBlocks: true },
88 * http: { logAll: true, logBlocks: true },
89 * l4: { logAll: true, logBlocks: true },
90 * },
91 * });
92 * ```
93 *
94 * **Example:** Only log blocked DNS queries, redacting PII
95 * ```typescript
96 * yield* Cloudflare.Gateway.Logging("Logging", {
97 * redactPii: true,
98 * settingsByRuleType: {
99 * dns: { logAll: false, logBlocks: true },
100 * },
101 * });
102 * ```
103 *
104 * @see https://developers.cloudflare.com/cloudflare-one/insights/logs/gateway-logs/
105 *
106 * @resource
107 * @product Gateway
108 * @category Cloudflare One (Zero Trust)
109 */
110 export const Logging = Resource<Logging>(TypeId);
111
112 /**
113 * Returns true if the given value is a Logging resource.
114 */
115 export const isLogging = (value: unknown): value is Logging =>
116 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
117
118 export const LoggingProvider = () =>
119 Provider.succeed(Logging, {
120 nuke: { singleton: true },
121 stables: ["accountId", "initialSettings"],
122
123 list: Effect.fn(function* () {
124 const { accountId } = yield* yield* CloudflareEnvironment;
125 // Account singleton — there is no enumeration API; the Gateway
126 // logging settings object always exists for the account. Mirror
127 // `read`: observe the single instance and return it as a
128 // one-element array (its observed snapshot is its own
129 // `initialSettings`, since nothing is being managed).
130 const observed = yield* observeLogging(accountId);
131 return [toAttributes(accountId, observed, observed)];
132 }),
133
134 read: Effect.fn(function* ({ output }) {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136 const acct = output?.accountId ?? accountId;
137 const observed = yield* observeLogging(acct);
138 // The singleton always exists with account defaults — there is
139 // nothing to "own", so a cold read adopts freely. The observed
140 // snapshot at adoption time becomes the restore target.
141 const initialSettings = output?.initialSettings ?? observed;
142 return toAttributes(acct, observed, initialSettings);
143 }),
144
145 reconcile: Effect.fn(function* ({ news, output }) {
146 const { accountId } = yield* yield* CloudflareEnvironment;
147
148 // 1. Observe — the singleton always exists; read its live state.
149 const observed = yield* observeLogging(accountId);
150
151 // 2. Capture — the pre-management snapshot, restored on destroy.
152 const initialSettings = output?.initialSettings ?? observed;
153
154 // 3. Sync — merge the declared fields over the observed state and
155 // PUT only when something actually changes (the API has no
156 // PATCH, so the merge keeps undeclared fields at their current
157 // values).
158 const desired = mergeSnapshot(observed, {
159 redactPii: news.redactPii,
160 dns: news.settingsByRuleType?.dns,
161 http: news.settingsByRuleType?.http,
162 l4: news.settingsByRuleType?.l4,
163 });
164 if (sameSnapshot(observed, desired)) {
165 return toAttributes(accountId, observed, initialSettings);
166 }
167 yield* putLogging(accountId, desired);
168
169 // 4. Return — re-read so attrs reflect post-sync truth.
170 const final = yield* observeLogging(accountId);
171 return toAttributes(accountId, final, initialSettings);
172 }),
173
174 delete: Effect.fn(function* ({ output }) {
175 const { accountId, initialSettings } = output;
176 // Observe — skip the restore when the account already matches the
177 // captured snapshot (idempotent re-delete after a crashed run).
178 const observed = yield* observeLogging(accountId);
179 if (sameSnapshot(observed, initialSettings)) return;
180 yield* putLogging(accountId, initialSettings);
181 }),
182 });
183
184 /**
185 * Read the live logging settings, normalized to a `null`-free snapshot.
186 */
187 const observeLogging = (accountId: string) =>
188 zeroTrust.getGatewayLogging({ accountId }).pipe(
189 Effect.map((s): LoggingSnapshot => {
190 const snapshot: LoggingSnapshot = {};
191 if (s.redactPii != null) snapshot.redactPii = s.redactPii;
192 const byType = s.settingsByRuleType ?? undefined;
193 for (const key of RULE_TYPES) {
194 const block = byType?.[key];
195 if (block == null) continue;
196 const rule: LoggingRuleSettings = {};
197 if (block.logAll != null) rule.logAll = block.logAll;
198 if (block.logBlocks != null) rule.logBlocks = block.logBlocks;
199 snapshot[key] = rule;
200 }
201 return snapshot;
202 }),
203 );
204
205 const putLogging = (accountId: string, snapshot: LoggingSnapshot) =>
206 zeroTrust.putGatewayLogging({
207 accountId,
208 ...(snapshot.redactPii !== undefined ? { redactPii: snapshot.redactPii } : {}),
209 settingsByRuleType: {
210 ...(snapshot.dns !== undefined ? { dns: snapshot.dns } : {}),
211 ...(snapshot.http !== undefined ? { http: snapshot.http } : {}),
212 ...(snapshot.l4 !== undefined ? { l4: snapshot.l4 } : {}),
213 },
214 });
215
216 const RULE_TYPES = ["dns", "http", "l4"] as const;
217
218 /**
219 * Overlay the declared (non-undefined) fields onto the observed snapshot,
220 * merging per-rule-type blocks field-by-field.
221 */
222 const mergeSnapshot = (observed: LoggingSnapshot, declared: LoggingSnapshot): LoggingSnapshot => {
223 const merged: LoggingSnapshot =
224 observed.redactPii !== undefined ? { redactPii: observed.redactPii } : {};
225 if (declared.redactPii !== undefined) merged.redactPii = declared.redactPii;
226 for (const key of RULE_TYPES) {
227 const base = observed[key];
228 const over = declared[key];
229 if (base === undefined && over === undefined) continue;
230 const rule: LoggingRuleSettings = { ...base };
231 if (over?.logAll !== undefined) rule.logAll = over.logAll;
232 if (over?.logBlocks !== undefined) rule.logBlocks = over.logBlocks;
233 merged[key] = rule;
234 }
235 return merged;
236 };
237
238 const sameSnapshot = (a: LoggingSnapshot, b: LoggingSnapshot): boolean =>
239 a.redactPii === b.redactPii &&
240 RULE_TYPES.every(
241 (key) =>
242 (a[key]?.logAll ?? undefined) === (b[key]?.logAll ?? undefined) &&
243 (a[key]?.logBlocks ?? undefined) === (b[key]?.logBlocks ?? undefined),
244 );
245
246 const toAttributes = (
247 accountId: string,
248 observed: LoggingSnapshot,
249 initialSettings: LoggingSnapshot,
250 ): LoggingAttributes => ({
251 ...observed,
252 accountId,
253 initialSettings,
254 });