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

main
ts 252 lines 8.46 KB
Raw
1 import * as cloudhsm from "@distilled.cloud/aws/cloudhsm-v2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { findClusterById } from "./internal.ts";
11
12 export class HsmNotReady extends Data.TaggedError("HsmNotReady")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export class HsmUnexpectedResponse extends Data.TaggedError("HsmUnexpectedResponse")<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface HsmProps {
23 /**
24 * ID of the {@link Cluster} the HSM is created in. Changing the cluster
25 * replaces the HSM.
26 */
27 clusterId: string;
28 /**
29 * Availability Zone the HSM is placed into, e.g. `"us-west-2a"`. Must be
30 * one of the AZs covered by the cluster's subnets. Changing the AZ
31 * replaces the HSM.
32 */
33 availabilityZone: string;
34 /**
35 * IP address for the HSM's elastic network interface. Must be free in the
36 * subnet of the chosen Availability Zone. Changing the address replaces
37 * the HSM.
38 * @default an address picked by AWS from the subnet
39 */
40 ipAddress?: string;
41 }
42
43 export interface Hsm extends Resource<
44 "AWS.CloudHSMV2.Hsm",
45 HsmProps,
46 {
47 /**
48 * The unique identifier of the HSM.
49 */
50 hsmId: string;
51 /**
52 * The cluster the HSM belongs to.
53 */
54 clusterId: string;
55 /**
56 * The Availability Zone the HSM was placed in.
57 */
58 availabilityZone: string | undefined;
59 /**
60 * The subnet the HSM's ENI lives in.
61 */
62 subnetId: string | undefined;
63 /**
64 * The elastic network interface attached to the HSM.
65 */
66 eniId: string | undefined;
67 /**
68 * The IP address of the HSM's ENI.
69 */
70 eniIp: string | undefined;
71 /**
72 * Current state of the HSM (e.g. `ACTIVE`).
73 */
74 state: string;
75 },
76 never,
77 Providers
78 > {}
79
80 /**
81 * A hardware security module (HSM) inside an AWS CloudHSM {@link Cluster}.
82 *
83 * HSMs take roughly 10-20 minutes to provision and are billed hourly while
84 * they exist. The cluster must be in the `UNINITIALIZED`, `ACTIVE`, or
85 * `DEGRADED` state to accept a new HSM. Destroy HSMs you are not using.
86 * ### Creating an HSM
87 * **Example:** HSM in a Cluster's Availability Zone
88 * ```typescript
89 * const hsm = yield* Hsm("Primary", {
90 * clusterId: cluster.clusterId,
91 * availabilityZone: "us-west-2a",
92 * });
93 * ```
94 *
95 * **Example:** HSM with a Fixed ENI Address
96 * ```typescript
97 * const hsm = yield* Hsm("Primary", {
98 * clusterId: cluster.clusterId,
99 * availabilityZone: "us-west-2a",
100 * ipAddress: "10.0.1.20",
101 * });
102 * ```
103 *
104 * @resource
105 */
106 export const Hsm = Resource<Hsm>("AWS.CloudHSMV2.Hsm");
107
108 export const HsmProvider = () =>
109 Provider.effect(
110 Hsm,
111 Effect.gen(function* () {
112 // HSMs are enumerated through their cluster — describeClusters embeds
113 // each cluster's Hsms.
114 const findHsm = Effect.fn(function* (clusterId: string, hsmId: string) {
115 const cluster = yield* findClusterById(clusterId);
116 return cluster?.Hsms?.find((hsm) => hsm.HsmId === hsmId && hsm.State !== "DELETED");
117 });
118
119 // Bounded readiness wait. HSM provisioning typically completes in
120 // 10-20 minutes; budget ~25 min (100 * 15s).
121 const waitForActive = Effect.fn(function* (clusterId: string, hsmId: string) {
122 const policy = Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(100)]);
123 return yield* findHsm(clusterId, hsmId).pipe(
124 Effect.flatMap((hsm) => {
125 if (hsm === undefined) {
126 return Effect.fail(
127 new HsmNotReady({ message: `HSM '${hsmId}' not found in cluster '${clusterId}'` }),
128 );
129 }
130 if (hsm.State !== "ACTIVE") {
131 return Effect.fail(
132 new HsmNotReady({ message: `HSM '${hsmId}' not active (state: ${hsm.State})` }),
133 );
134 }
135 return Effect.succeed(hsm);
136 }),
137 Effect.retry({ schedule: policy }),
138 );
139 });
140
141 // Bounded wait-until-gone after delete initiation (~15 min = 60 * 15s).
142 // The whole cluster disappearing counts as gone too.
143 const waitUntilGone = Effect.fn(function* (clusterId: string, hsmId: string) {
144 const policy = Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]);
145 yield* findHsm(clusterId, hsmId).pipe(
146 Effect.flatMap((hsm) =>
147 hsm === undefined
148 ? Effect.void
149 : Effect.fail(
150 new HsmNotReady({
151 message: `HSM '${hsmId}' still deleting (state: ${hsm.State})`,
152 }),
153 ),
154 ),
155 Effect.retry({ schedule: policy }),
156 );
157 });
158
159 const toAttrs = Effect.fn(function* (hsm: cloudhsm.Hsm) {
160 if (!hsm.ClusterId) {
161 return yield* new HsmUnexpectedResponse({
162 message: `HSM '${hsm.HsmId}' is missing its ClusterId`,
163 });
164 }
165 return {
166 hsmId: hsm.HsmId,
167 clusterId: hsm.ClusterId,
168 availabilityZone: hsm.AvailabilityZone,
169 subnetId: hsm.SubnetId,
170 eniId: hsm.EniId,
171 eniIp: hsm.EniIp,
172 state: hsm.State ?? "ACTIVE",
173 };
174 });
175
176 return {
177 stables: ["hsmId", "clusterId", "availabilityZone"],
178
179 diff: Effect.fn(function* ({ olds, news }) {
180 if (!isResolved(news)) return undefined;
181 const n = news ?? { clusterId: "", availabilityZone: "" };
182 const o = olds ?? { clusterId: "", availabilityZone: "" };
183 // Every HSM property is create-only.
184 if (n.clusterId !== o.clusterId) {
185 return { action: "replace" } as const;
186 }
187 if (n.availabilityZone !== o.availabilityZone) {
188 return { action: "replace" } as const;
189 }
190 if (n.ipAddress !== o.ipAddress) {
191 return { action: "replace" } as const;
192 }
193 }),
194
195 read: Effect.fn(function* ({ output }) {
196 // HSMs have no name, no tags, and an auto-assigned id — without a
197 // cached id there is nothing to correlate on.
198 if (output === undefined) return undefined;
199 const hsm = yield* findHsm(output.clusterId, output.hsmId);
200 if (hsm === undefined) return undefined;
201 return yield* toAttrs(hsm);
202 }),
203
204 reconcile: Effect.fn(function* ({ news, output, session }) {
205 const props = news!;
206
207 // 1. Observe — the cached id is only a hint; the cluster's HSM
208 // list is authoritative.
209 let observed = output ? yield* findHsm(output.clusterId, output.hsmId) : undefined;
210
211 // 2. Ensure — create if missing.
212 if (observed === undefined) {
213 const created = yield* cloudhsm.createHsm({
214 ClusterId: props.clusterId,
215 AvailabilityZone: props.availabilityZone,
216 IpAddress: props.ipAddress,
217 });
218 observed = created.Hsm;
219 }
220 const hsmId = observed?.HsmId;
221 if (!hsmId) {
222 return yield* new HsmUnexpectedResponse({ message: "CreateHsm returned no HsmId" });
223 }
224
225 // 3. Wait for the HSM to become ACTIVE (nothing else is mutable).
226 const active = yield* waitForActive(props.clusterId, hsmId);
227
228 yield* session.note(hsmId);
229 return yield* toAttrs(active);
230 }),
231
232 delete: Effect.fn(function* ({ output }) {
233 yield* cloudhsm
234 .deleteHsm({ ClusterId: output.clusterId, HsmId: output.hsmId })
235 .pipe(Effect.catchTag("CloudHsmResourceNotFoundException", () => Effect.void));
236 // Deletion is asynchronous and the parent cluster cannot be
237 // deleted until the HSM is gone — wait it out (bounded).
238 yield* waitUntilGone(output.clusterId, output.hsmId);
239 }),
240
241 list: () =>
242 Effect.gen(function* () {
243 const pages = yield* cloudhsm.describeClusters.pages({}).pipe(Stream.runCollect);
244 const hsms = Array.from(pages)
245 .flatMap((page) => page.Clusters ?? [])
246 .flatMap((cluster) => cluster.Hsms ?? [])
247 .filter((hsm) => hsm.State !== "DELETED");
248 return yield* Effect.forEach(hsms, (hsm) => toAttrs(hsm));
249 }),
250 };
251 }),
252 );