@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 384 lines 12.3 KB
Raw
1 import type * as WAFV2 from "@distilled.cloud/aws/wafv2";
2 import * as wafv2 from "@distilled.cloud/aws/wafv2";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { deepEqual, isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, createTagsList, hasAlchemyTags } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import type { Providers } from "../Providers.ts";
12 import {
13 fetchWafTags,
14 retryAssociatedItem,
15 retryOptimisticLock,
16 syncWafTags,
17 type WafScope,
18 withWafScope,
19 } from "./internal.ts";
20
21 export class WAFv2IPSetUnexpectedResponse extends Data.TaggedError("WAFv2IPSetUnexpectedResponse")<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 export interface IPSetProps {
27 /**
28 * Name of the IP set. Must match `^[\w\-]+$` and be 1-128 characters.
29 * Changing the name replaces the IP set.
30 * @default a physical name derived from the app, stage and logical ID
31 */
32 ipSetName?: string;
33 /**
34 * Scope of the IP set — `REGIONAL` (ambient region) or `CLOUDFRONT`
35 * (pinned to `us-east-1`). Must match the scope of the web ACLs and rule
36 * groups that reference it. Changing the scope replaces the IP set.
37 * @default "REGIONAL"
38 */
39 scope?: WafScope;
40 /**
41 * IP address version of the entries. Changing the version replaces the
42 * IP set.
43 * @default "IPV4"
44 */
45 ipAddressVersion?: WAFV2.IPAddressVersion;
46 /**
47 * IP addresses and ranges in CIDR notation (e.g. `192.0.2.44/32`,
48 * `2620:0:2d0:200::/64`). Mutable — updated in place.
49 */
50 addresses: string[];
51 /**
52 * Description of the IP set.
53 */
54 description?: string;
55 /**
56 * User-defined tags to apply to the IP set.
57 */
58 tags?: Record<string, string>;
59 }
60
61 export interface IPSet extends Resource<
62 "AWS.WAFv2.IPSet",
63 IPSetProps,
64 {
65 /**
66 * Name of the IP set.
67 */
68 ipSetName: string;
69 /**
70 * WAF-assigned unique ID of the IP set.
71 */
72 ipSetId: string;
73 /**
74 * ARN of the IP set — reference it from a rule's
75 * `IPSetReferenceStatement`.
76 */
77 ipSetArn: string;
78 /**
79 * Scope the IP set was created in.
80 */
81 scope: WafScope;
82 /**
83 * IP address version of the entries.
84 */
85 ipAddressVersion: WAFV2.IPAddressVersion;
86 /**
87 * Current addresses in the set.
88 */
89 addresses: string[];
90 },
91 never,
92 Providers
93 > {}
94
95 /**
96 * An AWS WAFv2 IP set — a named collection of IP addresses and CIDR ranges
97 * referenced from web ACL and rule group rules via
98 * `IPSetReferenceStatement`.
99 *
100 * ### Creating IP Sets
101 * **Example:** Block List of IPv4 Addresses
102 * ```typescript
103 * const blockList = yield* AWS.WAFv2.IPSet("BlockList", {
104 * addresses: ["192.0.2.44/32", "203.0.113.0/24"],
105 * });
106 * ```
107 *
108 * **Example:** Reference from a Web ACL Rule
109 * ```typescript
110 * const acl = yield* AWS.WAFv2.WebACL("Firewall", {
111 * rules: [
112 * {
113 * Name: "block-bad-ips",
114 * Priority: 0,
115 * Statement: {
116 * IPSetReferenceStatement: { ARN: blockList.ipSetArn },
117 * },
118 * Action: { Block: {} },
119 * VisibilityConfig: {
120 * SampledRequestsEnabled: true,
121 * CloudWatchMetricsEnabled: true,
122 * MetricName: "block-bad-ips",
123 * },
124 * },
125 * ],
126 * });
127 * ```
128 *
129 * @resource
130 */
131 export const IPSet = Resource<IPSet>("AWS.WAFv2.IPSet");
132
133 const defaultScope: WafScope = "REGIONAL";
134 const defaultIpVersion: WAFV2.IPAddressVersion = "IPV4";
135
136 const sortedAddresses = (addresses: readonly string[]) =>
137 [...addresses].sort((a, b) => a.localeCompare(b));
138
139 const toAttrs = (ipSet: WAFV2.IPSet, scope: WafScope) => ({
140 ipSetName: ipSet.Name,
141 ipSetId: ipSet.Id,
142 ipSetArn: ipSet.ARN,
143 scope,
144 ipAddressVersion: ipSet.IPAddressVersion,
145 addresses: [...ipSet.Addresses],
146 });
147
148 export const IPSetProvider = () =>
149 Provider.effect(
150 IPSet,
151 Effect.gen(function* () {
152 const createName = Effect.fn(function* (id: string, props: IPSetProps) {
153 return props.ipSetName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
154 });
155
156 const findIPSet = Effect.fn(function* (
157 scope: WafScope,
158 name: string,
159 cachedId: string | undefined,
160 ) {
161 if (cachedId !== undefined) {
162 const byId = yield* withWafScope(
163 scope,
164 wafv2
165 .getIPSet({ Name: name, Scope: scope, Id: cachedId })
166 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
167 );
168 if (byId?.IPSet) {
169 return byId;
170 }
171 }
172 let marker: string | undefined;
173 for (let page = 0; page < 20; page++) {
174 const listed = yield* withWafScope(
175 scope,
176 wafv2.listIPSets({ Scope: scope, NextMarker: marker, Limit: 100 }),
177 );
178 const summary = listed.IPSets?.find((s) => s.Name === name);
179 if (summary?.Id !== undefined) {
180 return yield* withWafScope(
181 scope,
182 wafv2
183 .getIPSet({ Name: name, Scope: scope, Id: summary.Id })
184 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
185 );
186 }
187 if (!listed.NextMarker || (listed.IPSets?.length ?? 0) === 0) {
188 break;
189 }
190 marker = listed.NextMarker;
191 }
192 return undefined;
193 });
194
195 const listScope = Effect.fn(function* (scope: WafScope) {
196 const rows: ReturnType<typeof toAttrs>[] = [];
197 let marker: string | undefined;
198 for (let page = 0; page < 50; page++) {
199 const listed = yield* withWafScope(
200 scope,
201 wafv2.listIPSets({ Scope: scope, NextMarker: marker, Limit: 100 }),
202 );
203 const summaries = listed.IPSets ?? [];
204 const details = yield* Effect.forEach(
205 summaries,
206 (summary) =>
207 summary.Name !== undefined && summary.Id !== undefined
208 ? withWafScope(
209 scope,
210 wafv2
211 .getIPSet({
212 Name: summary.Name,
213 Scope: scope,
214 Id: summary.Id,
215 })
216 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
217 )
218 : Effect.undefined,
219 { concurrency: 5 },
220 );
221 for (const detail of details) {
222 if (detail?.IPSet) {
223 rows.push(toAttrs(detail.IPSet, scope));
224 }
225 }
226 if (!listed.NextMarker || summaries.length === 0) {
227 break;
228 }
229 marker = listed.NextMarker;
230 }
231 return rows;
232 });
233
234 return {
235 stables: ["ipSetName", "ipSetId", "ipSetArn", "scope", "ipAddressVersion"],
236
237 list: () =>
238 Effect.gen(function* () {
239 const regional = yield* listScope("REGIONAL");
240 const cloudfront = yield* listScope("CLOUDFRONT");
241 return [...regional, ...cloudfront];
242 }),
243
244 diff: Effect.fn(function* ({ id, news, olds }) {
245 if (!isResolved(news)) return undefined;
246 const oldName = yield* createName(id, olds ?? { addresses: [] });
247 const newName = yield* createName(id, news);
248 if (
249 oldName !== newName ||
250 (olds?.scope ?? defaultScope) !== (news.scope ?? defaultScope) ||
251 (olds?.ipAddressVersion ?? defaultIpVersion) !==
252 (news.ipAddressVersion ?? defaultIpVersion)
253 ) {
254 return { action: "replace" } as const;
255 }
256 }),
257
258 read: Effect.fn(function* ({ id, olds, output }) {
259 const scope = output?.scope ?? olds?.scope ?? defaultScope;
260 const name = output?.ipSetName ?? (yield* createName(id, olds ?? { addresses: [] }));
261 const found = yield* findIPSet(scope, name, output?.ipSetId);
262 if (!found?.IPSet) {
263 return undefined;
264 }
265 const attrs = toAttrs(found.IPSet, scope);
266 const tags = yield* fetchWafTags(scope, found.IPSet.ARN);
267 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
268 }),
269
270 reconcile: Effect.fn(function* ({ id, news, output, session }) {
271 const scope = news.scope ?? defaultScope;
272 const name = output?.ipSetName ?? (yield* createName(id, news));
273 const internalTags = yield* createInternalTags(id);
274 const desiredTags = { ...news.tags, ...internalTags };
275
276 // 1. Observe.
277 let observed = yield* findIPSet(scope, name, output?.ipSetId);
278
279 // 2. Ensure — tolerate a duplicate-create race and re-read.
280 if (!observed?.IPSet) {
281 yield* withWafScope(
282 scope,
283 wafv2
284 .createIPSet({
285 Name: name,
286 Scope: scope,
287 IPAddressVersion: news.ipAddressVersion ?? defaultIpVersion,
288 Addresses: news.addresses,
289 Description: news.description,
290 Tags: createTagsList(desiredTags),
291 })
292 .pipe(Effect.catchTag("WAFDuplicateItemException", () => Effect.undefined)),
293 );
294 observed = yield* findIPSet(scope, name, undefined);
295 }
296
297 if (!observed?.IPSet) {
298 return yield* new WAFv2IPSetUnexpectedResponse({
299 message: `Failed to observe IPSet '${name}' after create`,
300 });
301 }
302
303 const ipSet = observed.IPSet;
304 yield* session.note(ipSet.ARN);
305
306 // 3. Sync addresses + description against OBSERVED state. WAF
307 // returns addresses in arbitrary order — compare as sets.
308 const drifted = !deepEqual(
309 {
310 Addresses: sortedAddresses(ipSet.Addresses),
311 Description: ipSet.Description,
312 },
313 {
314 Addresses: sortedAddresses(news.addresses),
315 Description: news.description,
316 },
317 { stripNullish: true },
318 );
319 if (drifted) {
320 yield* retryOptimisticLock(
321 Effect.gen(function* () {
322 const fresh = yield* findIPSet(scope, name, ipSet.Id);
323 if (!fresh?.IPSet || fresh.LockToken === undefined) {
324 return;
325 }
326 yield* withWafScope(
327 scope,
328 wafv2.updateIPSet({
329 Name: name,
330 Scope: scope,
331 Id: fresh.IPSet.Id,
332 Addresses: news.addresses,
333 Description: news.description,
334 LockToken: fresh.LockToken,
335 }),
336 );
337 }),
338 );
339 }
340
341 // 3b. Sync tags against OBSERVED cloud tags.
342 yield* syncWafTags(scope, ipSet.ARN, desiredTags);
343
344 // 4. Return fresh attributes.
345 return {
346 ...toAttrs(ipSet, scope),
347 addresses: [...news.addresses],
348 };
349 }),
350
351 delete: Effect.fn(function* ({ output }) {
352 const scope = output.scope;
353 // An IP set still referenced by a web ACL rule (deletion
354 // propagation) surfaces WAFAssociatedItemException — retry it.
355 yield* Effect.gen(function* () {
356 const found = yield* withWafScope(
357 scope,
358 wafv2
359 .getIPSet({
360 Name: output.ipSetName,
361 Scope: scope,
362 Id: output.ipSetId,
363 })
364 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
365 );
366 if (!found?.IPSet || found.LockToken === undefined) {
367 return;
368 }
369 yield* withWafScope(
370 scope,
371 wafv2
372 .deleteIPSet({
373 Name: output.ipSetName,
374 Scope: scope,
375 Id: output.ipSetId,
376 LockToken: found.LockToken,
377 })
378 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.void)),
379 );
380 }).pipe(retryOptimisticLock, retryAssociatedItem);
381 }),
382 };
383 }),
384 );