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