@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 296 lines 11 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, createTagsList, diffTags, hasTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import type { Providers } from "../Providers.ts";
11
12 export type KeyPairId<ID extends string = string> = `key-${ID}`;
13
14 /** Key algorithm for a generated EC2 key pair. */
15 export type KeyPairType = "rsa" | "ed25519";
16
17 /** Private-key file format for a generated EC2 key pair. */
18 export type KeyPairFormat = "pem" | "ppk";
19
20 export interface KeyPairProps {
21 /**
22 * Name of the key pair. If omitted, a unique name is generated from the
23 * stack, stage, and logical id. Changing it replaces the key pair.
24 */
25 keyName?: string;
26 /**
27 * Algorithm used when Alchemy generates the key pair. Ignored when
28 * {@link publicKeyMaterial} is supplied (an imported key keeps its own type).
29 * Changing it replaces the key pair.
30 * @default "rsa"
31 */
32 keyType?: KeyPairType;
33 /**
34 * Format of the returned private key material. Only meaningful when Alchemy
35 * generates the key pair. Changing it replaces the key pair.
36 * @default "pem"
37 */
38 keyFormat?: KeyPairFormat;
39 /**
40 * Public key material (PEM or OpenSSH) to import instead of generating a new
41 * key pair. When set, AWS stores only the public key — no `privateKey` is
42 * returned. Changing it replaces the key pair.
43 */
44 publicKeyMaterial?: string;
45 /**
46 * Tags to assign to the key pair. Merged with the alchemy auto-tags.
47 */
48 tags?: Record<string, string>;
49 }
50
51 export interface KeyPair extends Resource<
52 "AWS.EC2.KeyPair",
53 KeyPairProps,
54 {
55 /** The ID of the key pair (e.g. `key-0123456789abcdef0`). */
56 keyPairId: KeyPairId;
57 /** The name of the key pair. */
58 keyName: string;
59 /** SHA-1/MD5 fingerprint of the key pair. */
60 keyFingerprint: string;
61 /** The algorithm of the key pair. */
62 keyType: KeyPairType;
63 /**
64 * The unencrypted PEM/PPK private key material. Only present when Alchemy
65 * generated the key pair (not when {@link KeyPairProps.publicKeyMaterial}
66 * was imported). AWS returns this exactly once, at create time; it is then
67 * persisted as a secret in alchemy state.
68 */
69 privateKey?: Redacted.Redacted<string>;
70 },
71 never,
72 Providers
73 > {}
74
75 /**
76 * An EC2 key pair used to grant SSH access to instances launched with its
77 * `keyName`.
78 *
79 * By default Alchemy asks EC2 to generate the key pair and captures the
80 * private key (returned only once, at create time) as a secret in state. Pass
81 * {@link KeyPairProps.publicKeyMaterial} to import your own public key instead,
82 * in which case no private key is stored.
83 *
84 * ### Creating a Key Pair
85 * **Example:** Generated key pair
86 * ```typescript
87 * const keyPair = yield* AWS.EC2.KeyPair("DeployKey", {
88 * keyType: "ed25519",
89 * });
90 * // keyPair.keyName -> pass to AWS.EC2.Instance({ keyName })
91 * // keyPair.privateKey -> Redacted<string> (the PEM private key)
92 * ```
93 *
94 * **Example:** Imported public key
95 * ```typescript
96 * const keyPair = yield* AWS.EC2.KeyPair("ImportedKey", {
97 * publicKeyMaterial: "ssh-ed25519 AAAAC3Nz... user@host",
98 * });
99 * ```
100 *
101 * @resource
102 */
103 export const KeyPair = Resource<KeyPair>("AWS.EC2.KeyPair");
104
105 const toKeyName = (id: string, props: { keyName?: string } = {}) =>
106 props.keyName ? Effect.succeed(props.keyName) : createPhysicalName({ id, maxLength: 255 });
107
108 const asRedacted = (
109 material: string | Redacted.Redacted<string> | undefined,
110 ): Redacted.Redacted<string> | undefined =>
111 material === undefined
112 ? undefined
113 : Redacted.isRedacted(material)
114 ? material
115 : Redacted.make(material);
116
117 export const KeyPairProvider = () =>
118 Provider.effect(
119 KeyPair,
120 Effect.gen(function* () {
121 const describeByName = (keyName: string) =>
122 ec2.describeKeyPairs({ KeyNames: [keyName] }).pipe(
123 Effect.catchTag("InvalidKeyPair.NotFound", () => Effect.succeed({ KeyPairs: [] })),
124 Effect.map((r) => r.KeyPairs?.[0]),
125 );
126
127 return {
128 stables: ["keyPairId", "keyName", "keyType"],
129
130 // Generated key pairs are immutable except for tags. A changed name /
131 // type / format / imported material means a different key pair.
132 diff: Effect.fn(function* ({ id, olds, news }) {
133 if (!isResolved(news)) return;
134 const oldName = yield* toKeyName(id, olds ?? {});
135 const newName = yield* toKeyName(id, news);
136 if (
137 oldName !== newName ||
138 (olds?.keyType ?? "rsa") !== (news.keyType ?? "rsa") ||
139 (olds?.keyFormat ?? "pem") !== (news.keyFormat ?? "pem") ||
140 olds?.publicKeyMaterial !== news.publicKeyMaterial
141 ) {
142 return { action: "replace" } as const;
143 }
144 }),
145
146 read: Effect.fn(function* ({ id, olds, output }) {
147 const keyName = output?.keyName ?? (yield* toKeyName(id, olds ?? {}));
148 const info = yield* describeByName(keyName);
149 if (!info?.KeyPairId) return undefined;
150 const tags = yield* createInternalTags(id);
151 const observedTags: Record<string, string | undefined> = Object.fromEntries(
152 (info.Tags ?? []).map((t) => [t.Key ?? "", t.Value]),
153 );
154 if (!hasTags(tags, observedTags)) {
155 // Exists but unbranded — let the engine gate adoption behind --adopt.
156 return Unowned({
157 keyPairId: info.KeyPairId as KeyPairId,
158 keyName: info.KeyName ?? keyName,
159 keyFingerprint: info.KeyFingerprint ?? "",
160 keyType: (info.KeyType ?? "rsa") as KeyPairType,
161 // Private key is only available at create time; keep any cached
162 // copy from prior state.
163 privateKey: output?.privateKey,
164 });
165 }
166 return {
167 keyPairId: info.KeyPairId as KeyPairId,
168 keyName: info.KeyName ?? keyName,
169 keyFingerprint: info.KeyFingerprint ?? output?.keyFingerprint ?? "",
170 keyType: (info.KeyType ?? output?.keyType ?? "rsa") as KeyPairType,
171 privateKey: output?.privateKey,
172 };
173 }),
174
175 list: () =>
176 Effect.gen(function* () {
177 const result = yield* ec2.describeKeyPairs({});
178 return (result.KeyPairs ?? [])
179 .filter(
180 (
181 kp,
182 ): kp is ec2.KeyPairInfo & {
183 KeyPairId: string;
184 KeyName: string;
185 } => kp.KeyPairId != null && kp.KeyName != null,
186 )
187 .filter((kp) => (kp.Tags ?? []).some((t) => t.Key === "alchemy::stack"))
188 .map((kp) => ({
189 keyPairId: kp.KeyPairId as KeyPairId,
190 keyName: kp.KeyName,
191 keyFingerprint: kp.KeyFingerprint ?? "",
192 keyType: (kp.KeyType ?? "rsa") as KeyPairType,
193 privateKey: undefined,
194 }));
195 }),
196
197 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
198 const keyName = output?.keyName ?? (yield* toKeyName(id, news));
199 const internalTags = yield* createInternalTags(id);
200 const desiredTags = { ...internalTags, ...news.tags };
201
202 // Observe — is the key pair already present?
203 let info = yield* describeByName(keyName);
204 let privateKey = output?.privateKey;
205
206 // Ensure — import or generate when missing.
207 if (!info?.KeyPairId) {
208 if (news.publicKeyMaterial !== undefined) {
209 const imported = yield* ec2
210 .importKeyPair({
211 KeyName: keyName,
212 PublicKeyMaterial: new TextEncoder().encode(news.publicKeyMaterial),
213 TagSpecifications: [
214 {
215 ResourceType: "key-pair",
216 Tags: createTagsList(desiredTags),
217 },
218 ],
219 })
220 .pipe(Effect.catchTag("InvalidKeyPair.Duplicate", () => Effect.undefined));
221 if (imported?.KeyPairId) {
222 info = {
223 KeyPairId: imported.KeyPairId,
224 KeyName: imported.KeyName,
225 KeyFingerprint: imported.KeyFingerprint,
226 KeyType: "rsa",
227 };
228 } else {
229 info = yield* describeByName(keyName);
230 }
231 } else {
232 const created = yield* ec2
233 .createKeyPair({
234 KeyName: keyName,
235 KeyType: news.keyType ?? "rsa",
236 KeyFormat: news.keyFormat ?? "pem",
237 TagSpecifications: [
238 {
239 ResourceType: "key-pair",
240 Tags: createTagsList(desiredTags),
241 },
242 ],
243 })
244 .pipe(Effect.catchTag("InvalidKeyPair.Duplicate", () => Effect.undefined));
245 if (created?.KeyPairId) {
246 privateKey = asRedacted(created.KeyMaterial) ?? privateKey;
247 info = {
248 KeyPairId: created.KeyPairId,
249 KeyName: created.KeyName,
250 KeyFingerprint: created.KeyFingerprint,
251 KeyType: (news.keyType ?? "rsa") as KeyPairType,
252 };
253 } else {
254 info = yield* describeByName(keyName);
255 }
256 }
257 }
258
259 if (!info?.KeyPairId) {
260 return yield* Effect.die(new Error(`Failed to resolve EC2 key pair '${keyName}'`));
261 }
262 const keyPairId = info.KeyPairId as KeyPairId;
263
264 // Sync tags — observed cloud tags vs desired.
265 const observedTags = Object.fromEntries(
266 (info.Tags ?? []).map((t) => [t.Key!, t.Value!]),
267 ) as Record<string, string>;
268 const { removed, upsert } = diffTags(observedTags, desiredTags);
269 if (removed.length > 0) {
270 yield* ec2.deleteTags({
271 Resources: [keyPairId],
272 Tags: removed.map((key) => ({ Key: key })),
273 });
274 }
275 if (upsert.length > 0) {
276 yield* ec2.createTags({ Resources: [keyPairId], Tags: upsert });
277 }
278
279 yield* session.note(`Key pair ${keyName} (${keyPairId})`);
280 return {
281 keyPairId,
282 keyName: info.KeyName ?? keyName,
283 keyFingerprint: info.KeyFingerprint ?? "",
284 keyType: (info.KeyType ?? news.keyType ?? "rsa") as KeyPairType,
285 privateKey,
286 };
287 }),
288
289 delete: Effect.fn(function* ({ output }) {
290 // `deleteKeyPair` is idempotent — deleting a missing key pair
291 // succeeds, so there is no NotFound error to catch.
292 yield* ec2.deleteKeyPair({ KeyPairId: output.keyPairId });
293 }),
294 };
295 }),
296 );