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

main
ts 263 lines 9.72 KB
Raw
1 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { AccountID } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { RegionID } from "../Region.ts";
13
14 export type TrustStoreArn =
15 `arn:aws:elasticloadbalancing:${RegionID}:${AccountID}:truststore/${string}`;
16
17 export interface TrustStoreProps {
18 /** The trust store name. If omitted, a unique name is generated. Changing it replaces the trust store. */
19 name?: string;
20 /** The S3 bucket holding the CA certificate bundle (PEM). */
21 caCertificatesBundleS3Bucket: string;
22 /** The S3 key of the CA certificate bundle. */
23 caCertificatesBundleS3Key: string;
24 /** The S3 object version of the CA certificate bundle. */
25 caCertificatesBundleS3ObjectVersion?: string;
26 /** Tags to apply to the trust store. */
27 tags?: Record<string, string>;
28 }
29
30 export interface TrustStore extends Resource<
31 "AWS.ELBv2.TrustStore",
32 TrustStoreProps,
33 {
34 /** The ARN of the trust store. */
35 trustStoreArn: TrustStoreArn;
36 /** The name of the trust store. */
37 name: string;
38 /** The status of the trust store (`ACTIVE` or `CREATING`). */
39 status: string;
40 /** The number of CA certificates in the trust store's bundle. */
41 numberOfCaCertificates: number;
42 /** The tags applied to the trust store. */
43 tags: Record<string, string>;
44 },
45 never,
46 Providers
47 > {}
48
49 /**
50 * An ELBv2 trust store. A trust store holds the CA certificate bundle used by
51 * an HTTPS listener configured for mutual TLS (mTLS) `verify` mode to validate
52 * client certificates.
53 * ### Creating a Trust Store
54 * **Example:** Basic trust store from an S3 CA bundle
55 * ```typescript
56 * const trustStore = yield* TrustStore("mtls", {
57 * caCertificatesBundleS3Bucket: "my-ca-bundles",
58 * caCertificatesBundleS3Key: "ca-bundle.pem",
59 * });
60 * ```
61 *
62 * **Example:** Using a trust store on an mTLS listener
63 * ```typescript
64 * const listener = yield* Listener("https", {
65 * loadBalancerArn: lb.loadBalancerArn,
66 * port: 443,
67 * protocol: "HTTPS",
68 * certificates: [certArn],
69 * mutualAuthentication: {
70 * mode: "verify",
71 * trustStoreArn: trustStore.trustStoreArn,
72 * },
73 * defaultActions: [
74 * { type: "forward", targetGroups: [{ targetGroupArn: tg.targetGroupArn }] },
75 * ],
76 * });
77 * ```
78 *
79 * @resource
80 */
81 export const TrustStore = Resource<TrustStore>("AWS.ELBv2.TrustStore");
82
83 export const TrustStoreProvider = () =>
84 Provider.effect(
85 TrustStore,
86 Effect.gen(function* () {
87 const toName = (id: string, props: { name?: string } = {}) =>
88 props.name
89 ? Effect.succeed(props.name)
90 : createPhysicalName({ id, maxLength: 32, lowercase: true });
91
92 const observedTags = (arn: string) =>
93 Effect.gen(function* () {
94 const tagDescriptions = yield* elbv2.describeTags({
95 ResourceArns: [arn],
96 });
97 return Object.fromEntries(
98 (tagDescriptions.TagDescriptions?.[0]?.Tags ?? [])
99 .filter(
100 (t): t is { Key: string; Value: string } =>
101 typeof t.Key === "string" && typeof t.Value === "string",
102 )
103 .map((t) => [t.Key, t.Value]),
104 );
105 });
106
107 return {
108 stables: ["trustStoreArn", "name"],
109 diff: Effect.fn(function* ({ id, olds, news }) {
110 if (!isResolved(news)) return;
111 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
112 return { action: "replace" } as const;
113 }
114 }),
115 read: Effect.fn(function* ({ output }) {
116 if (!output) {
117 return undefined;
118 }
119 const described = yield* elbv2
120 .describeTrustStores({
121 TrustStoreArns: [output.trustStoreArn],
122 })
123 .pipe(Effect.catchTag("TrustStoreNotFoundException", () => Effect.undefined));
124 const trustStore = described?.TrustStores?.[0];
125 if (!trustStore?.TrustStoreArn) {
126 return undefined;
127 }
128 return {
129 ...output,
130 name: trustStore.Name!,
131 status: trustStore.Status!,
132 numberOfCaCertificates: trustStore.NumberOfCaCertificates ?? 0,
133 };
134 }),
135 list: () =>
136 Effect.gen(function* () {
137 const trustStores = yield* elbv2.describeTrustStores.pages({}).pipe(
138 Stream.runCollect,
139 Effect.map((chunk) =>
140 Array.from(chunk).flatMap((page) =>
141 (page.TrustStores ?? []).filter(
142 (ts): ts is elbv2.TrustStore & { TrustStoreArn: string } =>
143 ts.TrustStoreArn != null,
144 ),
145 ),
146 ),
147 );
148 return yield* Effect.forEach(
149 trustStores,
150 (ts) =>
151 Effect.gen(function* () {
152 const tags = yield* observedTags(ts.TrustStoreArn).pipe(
153 Effect.catchTag("TrustStoreNotFoundException", () =>
154 Effect.succeed({} as Record<string, string>),
155 ),
156 );
157 return {
158 trustStoreArn: ts.TrustStoreArn as TrustStoreArn,
159 name: ts.Name!,
160 status: ts.Status!,
161 numberOfCaCertificates: ts.NumberOfCaCertificates ?? 0,
162 tags,
163 };
164 }),
165 { concurrency: 10 },
166 );
167 }),
168 reconcile: Effect.fn(function* ({ id, news, session }) {
169 const name = yield* toName(id, news);
170 const desiredTags = {
171 ...(yield* createInternalTags(id)),
172 ...news.tags,
173 };
174
175 // Observe — look up by deterministic name.
176 const described = yield* elbv2
177 .describeTrustStores({ Names: [name] })
178 .pipe(Effect.catchTag("TrustStoreNotFoundException", () => Effect.undefined));
179 let trustStore = described?.TrustStores?.[0];
180
181 // Ensure — create if missing.
182 if (!trustStore?.TrustStoreArn) {
183 const created = yield* elbv2.createTrustStore({
184 Name: name,
185 CaCertificatesBundleS3Bucket: news.caCertificatesBundleS3Bucket,
186 CaCertificatesBundleS3Key: news.caCertificatesBundleS3Key,
187 CaCertificatesBundleS3ObjectVersion: news.caCertificatesBundleS3ObjectVersion,
188 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
189 Key,
190 Value,
191 })),
192 });
193 trustStore = created.TrustStores?.[0];
194 if (!trustStore?.TrustStoreArn) {
195 return yield* Effect.die(new Error("createTrustStore returned no trust store"));
196 }
197 } else {
198 // Sync the CA bundle in place.
199 const modified = yield* elbv2.modifyTrustStore({
200 TrustStoreArn: trustStore.TrustStoreArn,
201 CaCertificatesBundleS3Bucket: news.caCertificatesBundleS3Bucket,
202 CaCertificatesBundleS3Key: news.caCertificatesBundleS3Key,
203 CaCertificatesBundleS3ObjectVersion: news.caCertificatesBundleS3ObjectVersion,
204 });
205 trustStore = modified.TrustStores?.[0] ?? trustStore;
206 }
207
208 const trustStoreArn = trustStore.TrustStoreArn as TrustStoreArn;
209
210 // Wait until the trust store is ACTIVE (bundle validation completes).
211 const active = yield* elbv2.describeTrustStores({ TrustStoreArns: [trustStoreArn] }).pipe(
212 Effect.map((res) => res.TrustStores?.[0]),
213 Effect.repeat({
214 schedule: Schedule.spaced("3 seconds"),
215 until: (ts) => ts?.Status === "ACTIVE",
216 times: 10,
217 }),
218 );
219
220 // Sync tags — diff observed cloud tags against desired.
221 const observed = yield* observedTags(trustStoreArn);
222 const { removed, upsert } = diffTags(observed, desiredTags);
223 if (upsert.length > 0) {
224 yield* elbv2.addTags({
225 ResourceArns: [trustStoreArn],
226 Tags: upsert,
227 });
228 }
229 if (removed.length > 0) {
230 yield* elbv2.removeTags({
231 ResourceArns: [trustStoreArn],
232 TagKeys: removed,
233 });
234 }
235
236 yield* session.note(trustStoreArn);
237 return {
238 trustStoreArn,
239 name: trustStore.Name!,
240 status: active?.Status ?? trustStore.Status!,
241 numberOfCaCertificates:
242 active?.NumberOfCaCertificates ?? trustStore.NumberOfCaCertificates ?? 0,
243 tags: desiredTags,
244 };
245 }),
246 delete: Effect.fn(function* ({ output }) {
247 yield* elbv2.deleteTrustStore({ TrustStoreArn: output.trustStoreArn }).pipe(
248 // In-use trust stores must wait for the listener to detach; the
249 // engine deletes dependents first, but retry briefly for the
250 // eventual-consistency window.
251 Effect.retry({
252 while: (e) => e._tag === "TrustStoreInUseException",
253 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(8)]),
254 }),
255 Effect.catchTags({
256 TrustStoreNotFoundException: () => Effect.void,
257 TrustStoreInUseException: () => Effect.void,
258 }),
259 );
260 }),
261 };
262 }),
263 );