@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 213 lines 6.63 KB
Raw
1 import * as kms from "@distilled.cloud/aws/kms";
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 * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment, type AccountID } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { RegionID } from "../Region.ts";
13 import type { KeyId } from "./Key.ts";
14
15 export type AliasName = `alias/${string}`;
16 export type AliasArn = `arn:aws:kms:${RegionID}:${AccountID}:${AliasName}`;
17
18 export interface AliasProps {
19 /**
20 * Alias name. Must begin with `alias/`. If omitted, Alchemy generates one.
21 */
22 aliasName?: AliasName;
23 /**
24 * Target KMS key ID or ARN for this alias.
25 */
26 targetKeyId: KeyId;
27 }
28
29 export interface Alias extends Resource<
30 "AWS.KMS.Alias",
31 AliasProps,
32 {
33 aliasName: AliasName;
34 aliasArn: AliasArn;
35 targetKeyId: KeyId;
36 },
37 never,
38 Providers
39 > {}
40
41 /**
42 * An AWS KMS alias that points to a customer managed key.
43 *
44 * ### Creating Aliases
45 * **Example:** Alias for a Key
46 * ```typescript
47 * import * as KMS from "@alchemy.run/aws/KMS";
48 *
49 * const key = yield* KMS.Key("AppKey");
50 * const alias = yield* KMS.Alias("AppAlias", {
51 * aliasName: "alias/app",
52 * targetKeyId: key.keyId,
53 * });
54 * ```
55 */
56 export const Alias = Resource<Alias>("AWS.KMS.Alias");
57
58 export const AliasProvider = () =>
59 Provider.succeed(Alias, {
60 stables: ["aliasName", "aliasArn"],
61 list: () =>
62 Effect.gen(function* () {
63 const aliases = yield* kms.listAliases.pages({}).pipe(
64 Stream.runCollect,
65 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Aliases ?? [])),
66 );
67
68 return aliases
69 .filter(
70 (
71 alias,
72 ): alias is kms.AliasListEntry & {
73 AliasName: AliasName;
74 AliasArn: AliasArn;
75 TargetKeyId: KeyId;
76 } =>
77 isCustomerAlias(alias.AliasName) &&
78 alias.AliasArn !== undefined &&
79 alias.TargetKeyId !== undefined,
80 )
81 .map((alias) => ({
82 aliasName: alias.AliasName,
83 aliasArn: alias.AliasArn,
84 targetKeyId: alias.TargetKeyId,
85 }));
86 }),
87 read: Effect.fn(function* ({ id, olds, output }) {
88 const aliasName = output?.aliasName ?? (yield* toAliasName(id, olds ?? {}));
89 const state = yield* readAlias(aliasName);
90 if (!state) return undefined;
91 return output ? state : Unowned(state);
92 }),
93 diff: Effect.fn(function* ({ id, news, olds = {} }) {
94 if (!isResolved(news)) return;
95 if ((yield* toAliasName(id, news)) !== (yield* toAliasName(id, olds))) {
96 return { action: "replace" } as const;
97 }
98 }),
99 reconcile: Effect.fn(function* ({ id, news, output, session }) {
100 const aliasName = output?.aliasName ?? (yield* toAliasName(id, news));
101 const targetKeyId = yield* resolveTargetKeyId(news.targetKeyId);
102 let state = yield* readAlias(aliasName);
103
104 if (!state) {
105 yield* kms
106 .createAlias({
107 AliasName: aliasName,
108 TargetKeyId: targetKeyId,
109 })
110 .pipe(
111 Effect.retry({
112 while: isKmsEventuallyConsistent,
113 schedule: kmsRetrySchedule,
114 }),
115 Effect.catchTag("AlreadyExistsException", () => Effect.void),
116 );
117 state = yield* readAlias(aliasName);
118 }
119
120 if (state?.targetKeyId !== targetKeyId) {
121 yield* kms
122 .updateAlias({
123 AliasName: aliasName,
124 TargetKeyId: targetKeyId,
125 })
126 .pipe(
127 Effect.retry({
128 while: isKmsEventuallyConsistent,
129 schedule: kmsRetrySchedule,
130 }),
131 );
132 state = yield* readAlias(aliasName);
133 }
134
135 if (!state) {
136 return yield* Effect.die(new Error(`failed to read KMS alias ${aliasName}`));
137 }
138
139 yield* session.note(`KMS alias ${aliasName}`);
140 return state;
141 }),
142 delete: Effect.fn(function* ({ output, session }) {
143 yield* kms
144 .deleteAlias({
145 AliasName: output.aliasName,
146 })
147 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
148
149 const remaining = yield* Effect.repeat(readAlias(output.aliasName), {
150 schedule: Schedule.fixed("250 millis"),
151 until: (alias) => alias === undefined,
152 times: 20,
153 });
154 if (remaining !== undefined) {
155 return yield* Effect.die(
156 new Error(`KMS alias ${output.aliasName} remained observable after delete`),
157 );
158 }
159 yield* session.note(`Deleted KMS alias ${output.aliasName}`);
160 }),
161 });
162
163 const toAliasName = Effect.fn(function* (id: string, props: { aliasName?: AliasName }) {
164 if (props.aliasName) {
165 return props.aliasName;
166 }
167
168 return `alias/${yield* createPhysicalName({
169 id,
170 maxLength: 256 - "alias/".length,
171 })}` as AliasName;
172 });
173
174 const readAlias = Effect.fn(function* (aliasName: AliasName) {
175 const alias = yield* findAlias(aliasName);
176 if (!alias?.AliasName || !alias.TargetKeyId) return undefined;
177
178 return {
179 aliasName: alias.AliasName as AliasName,
180 aliasArn: (alias.AliasArn ?? (yield* aliasArn(aliasName))) as AliasArn,
181 targetKeyId: alias.TargetKeyId,
182 };
183 });
184
185 const findAlias = Effect.fn(function* (aliasName: AliasName) {
186 const aliases = yield* kms.listAliases.pages({}).pipe(
187 Stream.runCollect,
188 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Aliases ?? [])),
189 );
190
191 return aliases.find((alias) => alias.AliasName === aliasName);
192 });
193
194 const aliasArn = Effect.fn(function* (aliasName: AliasName) {
195 const { accountId, region } = yield* AWSEnvironment.current;
196 return `arn:aws:kms:${region}:${accountId}:${aliasName}` as AliasArn;
197 });
198
199 const resolveTargetKeyId = Effect.fn(function* (targetKeyId: string) {
200 const described = yield* kms.describeKey({ KeyId: targetKeyId });
201 return described.KeyMetadata?.KeyId!;
202 });
203
204 const isCustomerAlias = (aliasName: string | undefined): aliasName is AliasName =>
205 aliasName !== undefined && aliasName.startsWith("alias/") && !aliasName.startsWith("alias/aws/");
206
207 const isKmsEventuallyConsistent = (error: { _tag: string }) =>
208 error._tag === "DependencyTimeoutException" ||
209 error._tag === "KMSInternalException" ||
210 error._tag === "KMSInvalidStateException" ||
211 error._tag === "NotFoundException";
212
213 const kmsRetrySchedule = Schedule.max([Schedule.exponential(250), Schedule.recurs(7)]);