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

main
ts 336 lines 10.1 KB
Raw
1 import * as recaptchaenterprise from "@distilled.cloud/gcp/recaptchaenterprise_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 firewallNameOf,
12 lastSegment,
13 sameText,
14 toGeneratedPath,
15 updateMaskOf,
16 getFirewallPolicy,
17 } from "./internal.ts";
18
19 export type FirewallActionSetHeader = {
20 /**
21 * Header name to set on the request.
22 */
23 key?: string;
24 /**
25 * Header value to set on the request.
26 */
27 value?: string;
28 };
29
30 export type FirewallActionSubstitute = {
31 /**
32 * Relative path to serve instead of the original request path.
33 */
34 path?: string;
35 };
36
37 export type FirewallAction = {
38 /**
39 * Allow the request. Terminal.
40 */
41 allow?: Record<string, never> | {};
42 /**
43 * Deny the request. Terminal.
44 */
45 block?: Record<string, never> | {};
46 /**
47 * Include the reCAPTCHA JavaScript on the page. Non-terminal.
48 */
49 includeRecaptchaScript?: Record<string, never> | {};
50 /**
51 * Redirect to a reCAPTCHA challenge page. Terminal.
52 */
53 redirect?: Record<string, never> | {};
54 /**
55 * Attach a request header. Non-terminal.
56 */
57 setHeader?: FirewallActionSetHeader;
58 /**
59 * Serve a different path. Terminal.
60 */
61 substitute?: FirewallActionSubstitute;
62 };
63
64 export type FirewallpolicyProps = {
65 /**
66 * Server-assigned policy id (the `{firewallpolicy}` segment of
67 * `projects/{project}/firewallpolicies/{firewallpolicy}`). Immutable —
68 * changing it replaces the policy.
69 */
70 firewallpolicyId?: string;
71 /**
72 * Request path glob this policy matches (max 200 characters). If
73 * omitted, a unique `/alc/{name}` path is generated.
74 */
75 path?: string;
76 /**
77 * Human-readable description (max 256 characters).
78 */
79 description?: string;
80 /**
81 * CEL condition. The policy applies when this evaluates to true and
82 * the path matches. Max 500 characters.
83 */
84 condition?: string;
85 /**
86 * Actions to take. At most one terminal action (`allow`, `block`,
87 * `redirect`, `substitute`). Up to 16 actions.
88 * @default [{ allow: {} }]
89 */
90 actions?: FirewallAction[];
91 };
92
93 export type Firewallpolicy = Resource<
94 "GCP.RecaptchaEnterprise.Firewallpolicy",
95 FirewallpolicyProps,
96 {
97 /** Full resource name `projects/{project}/firewallpolicies/{id}`. */
98 name: string;
99 /** Server-assigned policy id (last path segment). */
100 firewallpolicyId: string;
101 /** Project id used when the policy was reconciled. */
102 project: string;
103 /** Path glob this policy matches. */
104 path: string | undefined;
105 /** Policy description. */
106 description: string | undefined;
107 /** CEL condition, if set. */
108 condition: string | undefined;
109 /** Configured actions. */
110 actions: FirewallAction[];
111 },
112 never,
113 Providers
114 >;
115
116 /**
117 * A reCAPTCHA Enterprise firewall policy.
118 *
119 * Policies have no labels field and a server-assigned id, so only a
120 * recorded policy can be read back. The policy id is assigned by Google —
121 * changing `firewallpolicyId` replaces the policy. Path, description,
122 * condition, and actions update in place.
123 *
124 * ### Creating a Policy
125 * **Example:** Allow a login path
126 * ```typescript
127 * const policy = yield* GCP.RecaptchaEnterprise.Firewallpolicy("Login", {
128 * path: "/login",
129 * description: "allow login",
130 * actions: [{ allow: {} }],
131 * });
132 * ```
133 *
134 * **Example:** Block with a CEL condition
135 * ```typescript
136 * const policy = yield* GCP.RecaptchaEnterprise.Firewallpolicy("Bot", {
137 * path: "/checkout",
138 * condition: "true",
139 * actions: [{ block: {} }],
140 * });
141 * ```
142 *
143 * ### Updating a Policy
144 * **Example:** Change the path and action
145 * ```typescript
146 * // Same logical id as before; only the changed props differ.
147 * const policy = yield* GCP.RecaptchaEnterprise.Firewallpolicy("Login", {
148 * path: "/signin",
149 * description: "allow sign-in",
150 * actions: [{ allow: {} }],
151 * });
152 * ```
153 *
154 * @resource
155 * @category RecaptchaEnterprise
156 */
157 export const Firewallpolicy = Resource<Firewallpolicy>("GCP.RecaptchaEnterprise.Firewallpolicy");
158
159 export class FirewallpolicyNotResolved extends Data.TaggedError(
160 "GCP.RecaptchaEnterprise.FirewallpolicyNotResolved",
161 )<{
162 resourceName: string;
163 }> {}
164
165 const DEFAULT_ACTIONS: FirewallAction[] = [{ allow: {} }];
166
167 const emptyAction = (value: unknown) => (value === undefined ? undefined : {});
168
169 const toAction = (
170 action: recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1FirewallAction | FirewallAction,
171 ): FirewallAction => ({
172 allow: emptyAction(action.allow),
173 block: emptyAction(action.block),
174 includeRecaptchaScript: emptyAction(action.includeRecaptchaScript),
175 redirect: emptyAction(action.redirect),
176 setHeader:
177 action.setHeader === undefined
178 ? undefined
179 : {
180 key: action.setHeader.key,
181 value: action.setHeader.value,
182 },
183 substitute: action.substitute === undefined ? undefined : { path: action.substitute.path },
184 });
185
186 const compactAction = (action: FirewallAction): FirewallAction => {
187 const next: FirewallAction = {};
188 if (action.allow !== undefined) next.allow = {};
189 if (action.block !== undefined) next.block = {};
190 if (action.includeRecaptchaScript !== undefined) {
191 next.includeRecaptchaScript = {};
192 }
193 if (action.redirect !== undefined) next.redirect = {};
194 if (action.setHeader !== undefined) next.setHeader = action.setHeader;
195 if (action.substitute !== undefined) next.substitute = action.substitute;
196 return next;
197 };
198
199 const toActions = (
200 actions:
201 | readonly (
202 | recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1FirewallAction
203 | FirewallAction
204 )[]
205 | undefined,
206 ): FirewallAction[] => (actions ?? []).map((action) => toAction(action));
207
208 const desiredActions = (news: FirewallpolicyProps): FirewallAction[] =>
209 (news.actions ?? DEFAULT_ACTIONS).map(compactAction);
210
211 const actionsFingerprint = (actions: readonly FirewallAction[]) =>
212 JSON.stringify(actions.map(compactAction));
213
214 const toAttrs = (
215 policy: recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1FirewallPolicy,
216 project: string,
217 ) => {
218 const name = policy.name ?? "";
219 return {
220 name,
221 firewallpolicyId: lastSegment(name),
222 project,
223 path: policy.path,
224 description: policy.description,
225 condition: policy.condition,
226 actions: toActions(policy.actions),
227 };
228 };
229
230 const toBody = (
231 path: string,
232 description: string | undefined,
233 condition: string | undefined,
234 actions: FirewallAction[],
235 ): recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1FirewallPolicy => ({
236 path,
237 description,
238 condition,
239 actions,
240 });
241
242 export const FirewallpolicyProvider = () =>
243 Provider.succeed(Firewallpolicy, {
244 stables: ["name", "firewallpolicyId", "project"],
245
246 diff: Effect.fn(function* ({ news, olds, output }) {
247 if (!isResolved(news)) return undefined;
248 const previousId = olds?.firewallpolicyId ?? output?.firewallpolicyId;
249 if (
250 news.firewallpolicyId !== undefined &&
251 previousId !== undefined &&
252 news.firewallpolicyId !== previousId
253 ) {
254 return { action: "replace" as const, deleteFirst: false };
255 }
256 return undefined;
257 }),
258
259 read: Effect.fn(function* ({ olds, output }) {
260 const env = yield* GcpEnvironment.current;
261 // Server-assigned id: only a recorded policy can be observed.
262 const name =
263 output?.name ??
264 (olds?.firewallpolicyId !== undefined
265 ? firewallNameOf(env.project, olds.firewallpolicyId)
266 : "");
267 const existing = yield* getFirewallPolicy(name);
268 if (existing === undefined) return undefined;
269 const attrs = toAttrs(existing, env.project);
270 return output !== undefined ? attrs : Unowned(attrs);
271 }),
272
273 reconcile: Effect.fn(function* ({ id, news, output }) {
274 const env = yield* GcpEnvironment.current;
275 const description = news.description;
276 const path = yield* toGeneratedPath(id, news.path);
277 const actions = desiredActions(news);
278 const condition = news.condition;
279 const lookupName =
280 output?.name ??
281 (news.firewallpolicyId !== undefined
282 ? firewallNameOf(env.project, news.firewallpolicyId)
283 : output?.firewallpolicyId !== undefined
284 ? firewallNameOf(env.project, output.firewallpolicyId)
285 : "");
286
287 let current = yield* getFirewallPolicy(lookupName);
288
289 if (current === undefined) {
290 const created = yield* recaptchaenterprise
291 .createProjectsFirewallpolicies({
292 parent: `projects/${env.project}`,
293 body: toBody(path, description, condition, actions),
294 })
295 .pipe(Effect.catchTag("Conflict", () => getFirewallPolicy(lookupName)));
296 current = created ?? undefined;
297 }
298
299 if (current === undefined) {
300 return yield* new FirewallpolicyNotResolved({
301 resourceName: lookupName.length > 0 ? lookupName : path,
302 });
303 }
304
305 const name = current.name ?? lookupName;
306 const pathChanged = !sameText(current.path, path);
307 const descriptionChanged = !sameText(current.description, description);
308 const conditionChanged = !sameText(current.condition, condition);
309 const actionsChanged =
310 actionsFingerprint(toActions(current.actions)) !== actionsFingerprint(actions);
311
312 const updateMask = updateMaskOf(
313 pathChanged ? "path" : undefined,
314 descriptionChanged ? "description" : undefined,
315 conditionChanged ? "condition" : undefined,
316 actionsChanged ? "actions" : undefined,
317 );
318
319 if (updateMask.length > 0) {
320 current = yield* recaptchaenterprise.patchProjectsFirewallpolicies({
321 name,
322 updateMask,
323 body: { ...toBody(path, description, condition, actions), name },
324 });
325 }
326
327 return toAttrs(current, env.project);
328 }),
329
330 delete: Effect.fn(function* ({ output }) {
331 if (output.name.length === 0) return;
332 yield* recaptchaenterprise
333 .deleteProjectsFirewallpolicies({ name: output.name })
334 .pipe(Effect.catchTag("NotFound", () => Effect.void));
335 }),
336 });