@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 509 lines 19.6 KB
Raw
1 import * as kms from "@distilled.cloud/aws/kms";
2 import * as ssm from "@distilled.cloud/aws/ssm";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Redacted from "effect/Redacted";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import { AWSEnvironment } from "../Environment.ts";
15 import type { Providers } from "../Providers.ts";
16
17 /**
18 * The kind of value the parameter stores.
19 *
20 * - `String` — plain text value (the default).
21 * - `StringList` — comma-separated list of values.
22 * - `SecureString` — value encrypted at rest with a KMS key.
23 */
24 export type ParameterType = "String" | "StringList" | "SecureString";
25
26 /**
27 * The parameter tier. `Standard` parameters are free (up to 10,000 per
28 * account, 4 KB values). `Advanced` parameters cost money but allow larger
29 * values (8 KB), higher counts, and parameter policies. `Intelligent-Tiering`
30 * lets Systems Manager pick the tier per request.
31 */
32 export type ParameterTier = "Standard" | "Advanced" | "Intelligent-Tiering";
33
34 export interface ParameterProps {
35 /**
36 * The fully qualified name of the parameter (may be a hierarchical path
37 * such as `/my-app/prod/db-url`). If omitted, a deterministic physical
38 * name is generated from the app, stage, and logical ID.
39 */
40 name?: string;
41 /**
42 * The type of the parameter.
43 * @default "String"
44 */
45 type?: ParameterType;
46 /**
47 * The parameter value. Accepts a plain string or a `Redacted` string —
48 * use `Redacted.make(...)` for `SecureString` values so they never leak
49 * into logs.
50 */
51 value: string | Redacted.Redacted<string>;
52 /**
53 * Description of the parameter.
54 */
55 description?: string;
56 /**
57 * The parameter tier. Note: downgrading an `Advanced` parameter back to
58 * `Standard` is not supported by the API and triggers a replacement.
59 * @default "Standard"
60 */
61 tier?: ParameterTier;
62 /**
63 * The KMS key ID, alias (e.g. `alias/my-key`), or ARN used to encrypt a
64 * `SecureString` parameter. Only valid when `type` is `SecureString`.
65 * @default "alias/aws/ssm" (the AWS-managed key)
66 */
67 keyId?: string;
68 /**
69 * A regular expression the parameter value must match, e.g. `^\d+$`.
70 */
71 allowedPattern?: string;
72 /**
73 * The data type for a `String` parameter. Use `aws:ec2:image` to have
74 * Systems Manager validate the value is a valid AMI ID.
75 * @default "text"
76 */
77 dataType?: "text" | "aws:ec2:image" | "aws:ssm:integration";
78 /**
79 * Tags to apply to the parameter. Merged with internal Alchemy tags.
80 */
81 tags?: Record<string, string>;
82 }
83
84 export interface Parameter extends Resource<
85 "AWS.SSM.Parameter",
86 ParameterProps,
87 {
88 parameterName: string;
89 parameterArn: string;
90 type: ParameterType;
91 version: number;
92 /**
93 * The ARN of the KMS key that encrypts this parameter. Defined only for
94 * `SecureString` parameters (resolved from `keyId`, defaulting to the
95 * AWS-managed `alias/aws/ssm` key). Bindings use it to grant
96 * `kms:Decrypt` for `WithDecryption` reads.
97 */
98 keyArn: string | undefined;
99 /**
100 * The declared description, tier, allowed pattern and data type, and
101 * the tags, as observed. Lets `alchemy drift` detect out-of-band
102 * changes.
103 */
104 configuration?: {
105 description?: string;
106 tier?: string;
107 allowedPattern?: string;
108 dataType?: string;
109 tags: Record<string, string>;
110 };
111 },
112 never,
113 Providers
114 > {}
115
116 /**
117 * An AWS Systems Manager (SSM) Parameter Store parameter.
118 *
119 * `Parameter` owns the lifecycle of a `String`, `StringList`, or
120 * `SecureString` parameter. A parameter name is auto-generated from the app,
121 * stage, and logical ID unless you provide one explicitly. Standard-tier
122 * parameters are free, making them ideal for configuration values, feature
123 * flags, and small secrets.
124 * ### Creating Parameters
125 * **Example:** String Parameter
126 * ```typescript
127 * import * as SSM from "@alchemy.run/aws/SSM";
128 *
129 * const config = yield* SSM.Parameter("DatabaseUrl", {
130 * value: "postgres://db.example.com:5432/app",
131 * });
132 * ```
133 *
134 * **Example:** StringList Parameter
135 * ```typescript
136 * const subnets = yield* SSM.Parameter("AllowedOrigins", {
137 * type: "StringList",
138 * value: "https://a.example.com,https://b.example.com",
139 * });
140 * ```
141 *
142 * **Example:** Parameter with a Hierarchical Name
143 * ```typescript
144 * const param = yield* SSM.Parameter("DbUrl", {
145 * name: "/my-app/prod/db-url",
146 * value: "postgres://db.example.com:5432/app",
147 * });
148 * ```
149 *
150 * ### SecureString Parameters
151 * **Example:** Encrypted with the AWS-managed key
152 * ```typescript
153 * import * as Redacted from "effect/Redacted";
154 *
155 * const apiKey = yield* SSM.Parameter("ApiKey", {
156 * type: "SecureString",
157 * value: Redacted.make("super-secret-value"),
158 * });
159 * ```
160 *
161 * **Example:** Encrypted with a customer-managed KMS key
162 * ```typescript
163 * const key = yield* KMS.Key("SecretsKey");
164 * const apiKey = yield* SSM.Parameter("ApiKey", {
165 * type: "SecureString",
166 * value: Redacted.make("super-secret-value"),
167 * keyId: key.keyId,
168 * });
169 * ```
170 *
171 * ### Validation
172 * **Example:** Constrain values with an allowed pattern
173 * ```typescript
174 * const port = yield* SSM.Parameter("Port", {
175 * value: "5432",
176 * allowedPattern: "^\\d+$",
177 * });
178 * ```
179 *
180 * ### Reading Parameters at Runtime
181 * Bind read operations in the init phase and use them in runtime handlers.
182 *
183 * **Example:** Read a parameter from a handler
184 * ```typescript
185 * // init
186 * const getParameter = yield* SSM.GetParameter(config);
187 *
188 * return {
189 * fetch: Effect.gen(function* () {
190 * // runtime
191 * const result = yield* getParameter({ WithDecryption: true });
192 * return HttpServerResponse.text(String(result.Parameter?.Value));
193 * }),
194 * };
195 * ```
196 *
197 * @resource
198 */
199 export const Parameter = Resource<Parameter>("AWS.SSM.Parameter");
200
201 /** Normalize a plain or redacted parameter value to its plain string. */
202 const toPlainValue = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
203 value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value);
204
205 const toTagRecord = (
206 tags: ReadonlyArray<{ Key?: string; Value?: string }> | undefined,
207 ): Record<string, string> =>
208 Object.fromEntries(
209 (tags ?? [])
210 .filter(
211 (tag): tag is { Key: string; Value: string } =>
212 typeof tag.Key === "string" && typeof tag.Value === "string",
213 )
214 .map((tag) => [tag.Key, tag.Value]),
215 );
216
217 const parameterArnOf = (region: string, accountId: string, name: string) =>
218 `arn:aws:ssm:${region}:${accountId}:parameter${name.startsWith("/") ? "" : "/"}${name}`;
219
220 export const ParameterProvider = () =>
221 Provider.effect(
222 Parameter,
223 Effect.gen(function* () {
224 const createName = Effect.fn(function* (id: string, props: Pick<ParameterProps, "name">) {
225 if (props.name) return props.name;
226 const generated = yield* createPhysicalName({ id, maxLength: 128 });
227 // SSM rejects parameter names prefixed with "aws" or "ssm"
228 // (case-insensitive) with a ValidationException. Stack names like
229 // "SSMBindings" would otherwise produce invalid physical names, so
230 // deterministically prefix those.
231 return /^(aws|ssm)/i.test(generated) ? `p-${generated}` : generated;
232 });
233
234 // DescribeParameters is the only API that surfaces tier, description,
235 // allowedPattern, and the KMS key id. It is eventually consistent, so
236 // treat an absent result as "no metadata yet" rather than "missing".
237 const describeByName = Effect.fn(function* (name: string) {
238 return yield* ssm.describeParameters
239 .pages({
240 ParameterFilters: [{ Key: "Name", Option: "Equals", Values: [name] }],
241 })
242 .pipe(
243 Stream.map((page) => page.Parameters ?? []),
244 Stream.flattenIterable,
245 Stream.runHead,
246 Effect.map(Option.getOrUndefined),
247 );
248 });
249
250 // Resolve a key id/alias/ARN to the key ARN for the `keyArn` attribute.
251 // The AWS-managed `alias/aws/ssm` key is created lazily on first use,
252 // so tolerate NotFound as "not resolvable yet".
253 const resolveKeyArn = Effect.fn(function* (keyId: string | undefined) {
254 return yield* kms.describeKey({ KeyId: keyId ?? "alias/aws/ssm" }).pipe(
255 Effect.map((r) => r.KeyMetadata?.Arn),
256 Effect.catchTag("NotFoundException", () => Effect.undefined),
257 );
258 });
259
260 const fetchObservedTags = Effect.fn(function* (name: string) {
261 return yield* ssm.listTagsForResource({ ResourceType: "Parameter", ResourceId: name }).pipe(
262 Effect.map((r) => toTagRecord(r.TagList)),
263 // A just-created (or just-deleted) parameter can transiently
264 // surface InvalidResourceId; treat as "no tags observed".
265 Effect.catchTag("InvalidResourceId", () => Effect.succeed({} as Record<string, string>)),
266 );
267 });
268
269 return Parameter.Provider.of({
270 stables: ["parameterName", "parameterArn"],
271
272 list: () =>
273 Effect.gen(function* () {
274 const { accountId, region } = yield* AWSEnvironment.current;
275 const pages = yield* ssm.describeParameters.pages({}).pipe(Stream.runCollect);
276 const metas = Array.from(pages).flatMap((page) => page.Parameters ?? []);
277 return yield* Effect.forEach(
278 metas.filter((m): m is typeof m & { Name: string } => m.Name != null),
279 (m) =>
280 Effect.gen(function* () {
281 const type = (m.Type ?? "String") as ParameterType;
282 const keyArn =
283 type === "SecureString"
284 ? yield* resolveKeyArn(m.KeyId).pipe(Effect.orElseSucceed(() => undefined))
285 : undefined;
286 return {
287 parameterName: m.Name,
288 parameterArn: m.ARN ?? parameterArnOf(region, accountId, m.Name),
289 type,
290 version: m.Version ?? 1,
291 keyArn,
292 };
293 }),
294 { concurrency: 5 },
295 );
296 }),
297
298 read: Effect.fn(function* ({ id, olds, output }) {
299 const { accountId, region } = yield* AWSEnvironment.current;
300 const name = output?.parameterName ?? (yield* createName(id, olds ?? {}));
301 const found = yield* ssm.getParameter({ Name: name }).pipe(
302 Effect.map((r) => r.Parameter),
303 Effect.catchTag("ParameterNotFound", () => Effect.undefined),
304 );
305 if (!found) return undefined;
306 const type = (found.Type ?? "String") as ParameterType;
307 const meta = yield* describeByName(name).pipe(Effect.orElseSucceed(() => undefined));
308 const keyArn =
309 type === "SecureString"
310 ? yield* resolveKeyArn(meta?.KeyId).pipe(Effect.orElseSucceed(() => undefined))
311 : undefined;
312 const tags = yield* fetchObservedTags(name).pipe(
313 Effect.orElseSucceed(() => ({}) as Record<string, string>),
314 );
315 // Metadata reconcile only writes when declared is only observed
316 // when declared.
317 const attrs = {
318 parameterName: name,
319 parameterArn: found.ARN ?? parameterArnOf(region, accountId, name),
320 type,
321 version: found.Version ?? 1,
322 keyArn,
323 configuration: {
324 description: olds?.description === undefined ? undefined : meta?.Description,
325 tier: olds?.tier === undefined ? undefined : meta?.Tier,
326 allowedPattern: olds?.allowedPattern === undefined ? undefined : meta?.AllowedPattern,
327 dataType: olds?.dataType === undefined ? undefined : (meta?.DataType ?? "text"),
328 tags,
329 },
330 };
331 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
332 }),
333
334 diff: Effect.fn(function* ({ id, news, olds }) {
335 if (!isResolved(news)) return undefined;
336 const oldName = yield* createName(id, olds ?? {});
337 const newName = yield* createName(id, news ?? {});
338 if (oldName !== newName) {
339 return { action: "replace" } as const;
340 }
341 // The API cannot downgrade an Advanced parameter back to Standard —
342 // the only way to converge is delete + recreate.
343 const oldTier = olds?.tier ?? "Standard";
344 const newTier = news?.tier ?? "Standard";
345 if (oldTier === "Advanced" && newTier === "Standard") {
346 return { action: "replace" } as const;
347 }
348 // Type changes (String <-> SecureString etc.) are mutable via
349 // PutParameter Overwrite=true, so fall through to default update.
350 }),
351
352 reconcile: Effect.fn(function* ({ id, news, output, session }) {
353 const { accountId, region } = yield* AWSEnvironment.current;
354 const name = output?.parameterName ?? (yield* createName(id, news));
355 const parameterArn = parameterArnOf(region, accountId, name);
356 const desiredType = news.type ?? "String";
357 const desiredValue = toPlainValue(news.value)!;
358 const internalTags = yield* createInternalTags(id);
359 const desiredTags = { ...news.tags, ...internalTags };
360
361 // 1. OBSERVE — cloud state is authoritative. `output` is only a
362 // cache of the physical name; if the parameter was deleted
363 // out-of-band we fall through to create.
364 const observed = yield* ssm.getParameter({ Name: name, WithDecryption: true }).pipe(
365 Effect.map((r) => r.Parameter),
366 Effect.catchTag("ParameterNotFound", () => Effect.undefined),
367 );
368
369 let version: number | undefined;
370
371 if (observed === undefined) {
372 // 2. ENSURE — create with tags in one call. PutParameter rejects
373 // Tags together with Overwrite, so if a concurrent reconciler
374 // won the race we fall back to an overwrite put (the tag sync
375 // below converges tags).
376 version = yield* ssm
377 .putParameter({
378 Name: name,
379 Value: news.value,
380 Type: desiredType,
381 Description: news.description,
382 KeyId: news.keyId,
383 AllowedPattern: news.allowedPattern,
384 Tier: news.tier,
385 DataType: news.dataType,
386 Tags: createTagsList(desiredTags),
387 })
388 .pipe(
389 Effect.map((r) => r.Version),
390 Effect.catchTag("ParameterAlreadyExists", () =>
391 ssm
392 .putParameter({
393 Name: name,
394 Value: news.value,
395 Type: desiredType,
396 Description: news.description,
397 KeyId: news.keyId,
398 AllowedPattern: news.allowedPattern,
399 Tier: news.tier,
400 DataType: news.dataType,
401 Overwrite: true,
402 })
403 .pipe(Effect.map((r) => r.Version)),
404 ),
405 );
406 } else {
407 // 3. SYNC — diff observed cloud state against desired and only
408 // call PutParameter when something actually drifted.
409 // DescribeParameters carries the metadata GetParameter omits
410 // (tier, description, allowedPattern, KMS key id); it is
411 // eventually consistent so an absent record just means "can't
412 // prove a no-op" and we overwrite.
413 const meta = yield* describeByName(name).pipe(Effect.orElseSucceed(() => undefined));
414 const drift =
415 toPlainValue(observed.Value) !== desiredValue ||
416 (observed.Type ?? "String") !== desiredType ||
417 (news.description !== undefined && meta?.Description !== news.description) ||
418 (news.allowedPattern !== undefined && meta?.AllowedPattern !== news.allowedPattern) ||
419 (news.tier !== undefined && meta?.Tier !== news.tier) ||
420 (news.dataType !== undefined && (meta?.DataType ?? "text") !== news.dataType) ||
421 (desiredType === "SecureString" &&
422 news.keyId !== undefined &&
423 meta?.KeyId !== news.keyId);
424 if (drift) {
425 version = yield* ssm
426 .putParameter({
427 Name: name,
428 Value: news.value,
429 Type: desiredType,
430 Description: news.description,
431 KeyId: news.keyId,
432 AllowedPattern: news.allowedPattern,
433 Tier: news.tier,
434 DataType: news.dataType,
435 Overwrite: true,
436 })
437 .pipe(Effect.map((r) => r.Version));
438 } else {
439 version = observed.Version;
440 }
441 }
442
443 // 3b. SYNC TAGS — diff against OBSERVED cloud tags (never olds or
444 // output) so adoption converges. Internal Alchemy tags always
445 // win over user tags.
446 const observedTags = yield* fetchObservedTags(name);
447 const { upsert, removed } = diffTags(observedTags, desiredTags);
448 if (upsert.length > 0) {
449 yield* ssm
450 .addTagsToResource({
451 ResourceType: "Parameter",
452 ResourceId: name,
453 Tags: upsert,
454 })
455 .pipe(
456 Effect.retry({
457 while: (e) => e._tag === "TooManyUpdates" || e._tag === "InvalidResourceId",
458 schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(5)]),
459 }),
460 );
461 }
462 if (removed.length > 0) {
463 yield* ssm
464 .removeTagsFromResource({
465 ResourceType: "Parameter",
466 ResourceId: name,
467 TagKeys: removed,
468 })
469 .pipe(
470 Effect.retry({
471 while: (e) => e._tag === "TooManyUpdates",
472 schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(5)]),
473 }),
474 );
475 }
476
477 // 4. RETURN — resolve the encryption key ARN after the put so a
478 // first SecureString write has already materialized the
479 // AWS-managed alias/aws/ssm key.
480 const keyArn =
481 desiredType === "SecureString" ? yield* resolveKeyArn(news.keyId) : undefined;
482
483 yield* session.note(parameterArn);
484 return {
485 parameterName: name,
486 parameterArn,
487 type: desiredType,
488 version: version ?? 1,
489 keyArn,
490 // Either already observed equal, or just written by the put
491 // above (DescribeParameters lags writes, so it is not re-read).
492 configuration: {
493 description: news.description,
494 tier: news.tier,
495 allowedPattern: news.allowedPattern,
496 dataType: news.dataType,
497 tags: desiredTags,
498 },
499 };
500 }),
501
502 delete: Effect.fn(function* ({ output }) {
503 yield* ssm
504 .deleteParameter({ Name: output.parameterName })
505 .pipe(Effect.catchTag("ParameterNotFound", () => Effect.void));
506 }),
507 });
508 }),
509 );