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

main
ts 209 lines 7.15 KB
Raw
1 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
2 import type * as WAFV2 from "@distilled.cloud/aws/wafv2";
3 import * as wafv2 from "@distilled.cloud/aws/wafv2";
4 import { diffTags } from "alchemy/Tags";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7
8 /**
9 * Scope of a WAFv2 resource.
10 *
11 * - `REGIONAL` — protects regional resources (ALB, API Gateway, AppSync,
12 * Cognito user pool, App Runner, Verified Access) and follows the ambient
13 * AWS region.
14 * - `CLOUDFRONT` — protects CloudFront distributions and must live in
15 * `us-east-1`; the providers pin the region automatically.
16 */
17 export type WafScope = "REGIONAL" | "CLOUDFRONT";
18
19 const CLOUDFRONT_REGION = "us-east-1" as const;
20
21 /**
22 * WAFv2 `CLOUDFRONT`-scoped resources exist exclusively in `us-east-1`
23 * (like ACM certificates for CloudFront). Pin the distilled `Region`
24 * service for CLOUDFRONT scope; REGIONAL scope follows the ambient region.
25 *
26 * `AwsRegion`'s service value is an `Effect<RegionName>` (see
27 * `@distilled.cloud/aws/Region`), so it must be provided as an effect, not a
28 * bare string.
29 *
30 * @internal
31 */
32 export const withWafScope = <A, E, R>(
33 scope: WafScope,
34 effect: Effect.Effect<A, E, R>,
35 ): Effect.Effect<A, E, R> =>
36 scope === "CLOUDFRONT"
37 ? effect.pipe(Effect.provideService(AwsRegion, Effect.succeed(CLOUDFRONT_REGION)))
38 : effect;
39
40 /**
41 * WAFv2 mutations (update/delete) use `LockToken` optimistic concurrency.
42 * The caller re-reads the entity (obtaining a fresh `LockToken`) inside
43 * `self`, so retrying the whole effect on `WAFOptimisticLockException`
44 * converges after concurrent writers.
45 *
46 * Explicitly typed: inlining `Effect.retry` with options in provider
47 * lifecycle code widens the provider layer to `unknown` in declaration emit.
48 *
49 * @internal
50 */
51 export const retryOptimisticLock = <A, E extends { _tag: string }, R>(
52 self: Effect.Effect<A, E, R>,
53 ): Effect.Effect<A, E, R> =>
54 Effect.retry(self, {
55 while: (e) => e._tag === "WAFOptimisticLockException",
56 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(8)]),
57 });
58
59 /**
60 * WAF changes take "a few seconds to a number of minutes" to propagate.
61 * A freshly created web ACL (or rule group) referenced by another call —
62 * or a freshly created protected resource (e.g. a Cognito user pool) that
63 * WAF cannot "retrieve" yet — surfaces `WAFUnavailableEntityException`
64 * until propagation completes. Retry it on a bounded schedule (~90s
65 * total); fresh Cognito user pools routinely need more than 40s.
66 *
67 * @internal
68 */
69 export const retryUnavailableEntity = <A, E extends { _tag: string }, R>(
70 self: Effect.Effect<A, E, R>,
71 ): Effect.Effect<A, E, R> =>
72 Effect.retry(self, {
73 while: (e) => e._tag === "WAFUnavailableEntityException",
74 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(30)]),
75 });
76
77 /**
78 * Like {@link retryUnavailableEntity} but with a ~150s budget. Associating
79 * a web ACL with a freshly created protected resource (Cognito user pool,
80 * ALB, …) surfaces `WAFUnavailableEntityException` until the resource
81 * propagates to WAF — observed to routinely exceed 90s for new Cognito
82 * user pools (Terraform retries this for 5 minutes).
83 *
84 * @internal
85 */
86 export const retryUnavailableEntityLong = <A, E extends { _tag: string }, R>(
87 self: Effect.Effect<A, E, R>,
88 ): Effect.Effect<A, E, R> =>
89 Effect.retry(self, {
90 while: (e) => e._tag === "WAFUnavailableEntityException",
91 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(50)]),
92 });
93
94 /**
95 * Deleting a web ACL shortly after its association was removed can surface
96 * `WAFAssociatedItemException` until disassociation propagates. Retry it
97 * (and propagation-flavored unavailability) on a bounded schedule (~30s).
98 *
99 * @internal
100 */
101 export const retryAssociatedItem = <A, E extends { _tag: string }, R>(
102 self: Effect.Effect<A, E, R>,
103 ): Effect.Effect<A, E, R> =>
104 Effect.retry(self, {
105 while: (e) =>
106 e._tag === "WAFAssociatedItemException" || e._tag === "WAFUnavailableEntityException",
107 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
108 });
109
110 /**
111 * Read the observed tags of a WAFv2 entity as a plain record.
112 *
113 * @internal
114 */
115 export const fetchWafTags = Effect.fn(function* (scope: WafScope, resourceArn: string) {
116 const tags: Record<string, string> = {};
117 let marker: string | undefined;
118 // WAF tag sets are small; bound pagination defensively.
119 for (let page = 0; page < 10; page++) {
120 const response = yield* withWafScope(
121 scope,
122 wafv2.listTagsForResource({
123 ResourceARN: resourceArn,
124 NextMarker: marker,
125 Limit: 100,
126 }),
127 );
128 const list = response.TagInfoForResource?.TagList ?? [];
129 for (const tag of list) {
130 tags[tag.Key] = tag.Value;
131 }
132 // WAF returns an empty-string NextMarker on the terminal page.
133 if (!response.NextMarker || list.length === 0) {
134 break;
135 }
136 marker = response.NextMarker;
137 }
138 return tags;
139 });
140
141 /**
142 * Sync a WAFv2 entity's tags to the desired set by diffing against the
143 * OBSERVED cloud tags (never `olds`/`output`).
144 *
145 * @internal
146 */
147 export const syncWafTags = Effect.fn(function* (
148 scope: WafScope,
149 resourceArn: string,
150 desiredTags: Record<string, string>,
151 ) {
152 const observed = yield* fetchWafTags(scope, resourceArn);
153 const { removed, upsert } = diffTags(observed, desiredTags);
154 if (upsert.length > 0) {
155 yield* withWafScope(scope, wafv2.tagResource({ ResourceARN: resourceArn, Tags: upsert }));
156 }
157 if (removed.length > 0) {
158 yield* withWafScope(scope, wafv2.untagResource({ ResourceARN: resourceArn, TagKeys: removed }));
159 }
160 });
161
162 /**
163 * Restore `ByteMatchStatement.SearchString` blobs inside a rule tree.
164 *
165 * Resource props survive the engine's plan/state serialization as plain
166 * JSON, so a `Uint8Array` SearchString arrives at the provider as an
167 * index-keyed object (`{ "0": 47, ... }`) or a number array. Distilled
168 * requires a real `Uint8Array` to base64-encode the blob on the wire, so
169 * walk the (recursive) statement tree and coerce every SearchString back.
170 *
171 * @internal
172 */
173 export const normalizeWafRules = (rules: WAFV2.Rule[] | undefined): WAFV2.Rule[] =>
174 (rules ?? []).map((rule) => normalizeRuleValue(rule) as WAFV2.Rule);
175
176 const normalizeRuleValue = (value: unknown): unknown => {
177 if (value instanceof Uint8Array) {
178 return value;
179 }
180 if (Array.isArray(value)) {
181 return value.map(normalizeRuleValue);
182 }
183 if (value !== null && typeof value === "object") {
184 return Object.fromEntries(
185 Object.entries(value).map(([key, nested]) => [
186 key,
187 key === "SearchString" ? toSearchString(nested) : normalizeRuleValue(nested),
188 ]),
189 );
190 }
191 return value;
192 };
193
194 const toSearchString = (value: unknown): Uint8Array => {
195 if (value instanceof Uint8Array) {
196 return value;
197 }
198 if (typeof value === "string") {
199 return new TextEncoder().encode(value);
200 }
201 if (Array.isArray(value)) {
202 return Uint8Array.from(value as number[]);
203 }
204 if (value !== null && typeof value === "object") {
205 // Index-keyed object — integer keys iterate in ascending order.
206 return Uint8Array.from(Object.values(value as Record<string, number>));
207 }
208 return new Uint8Array();
209 };