The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ag from "@distilled.cloud/aws/api-gateway"; |
| 2 | import { deepEqual, 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, hasAlchemyTags, tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Redacted from "effect/Redacted"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { AWSEnvironment } from "../Environment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { apiKeyArn, syncTags } from "./common.ts"; |
| 13 | |
| 14 | export interface ApiKeyProps { |
| 15 | /** |
| 16 | * Friendly name for the API key. |
| 17 | * |
| 18 | * If omitted, Alchemy generates a deterministic physical name from the |
| 19 | * stack, stage, logical ID, and instance ID. |
| 20 | */ |
| 21 | name?: string; |
| 22 | /** |
| 23 | * Human-readable description shown in API Gateway. |
| 24 | */ |
| 25 | description?: string; |
| 26 | /** |
| 27 | * Whether clients can use the key. |
| 28 | * |
| 29 | * @default true |
| 30 | */ |
| 31 | enabled?: boolean; |
| 32 | /** |
| 33 | * Appends a distinct suffix to the generated key value when AWS generates it. |
| 34 | */ |
| 35 | generateDistinctId?: boolean; |
| 36 | /** |
| 37 | * Write-only value when creating; never stored in resource state or outputs. |
| 38 | * Wrap with `Redacted.make` so state encoding preserves redaction. |
| 39 | */ |
| 40 | value?: Redacted.Redacted<string>; |
| 41 | /** |
| 42 | * Stage associations to attach directly to this API key. |
| 43 | */ |
| 44 | stageKeys?: ag.StageKey[]; |
| 45 | /** |
| 46 | * External customer identifier associated with the key. |
| 47 | */ |
| 48 | customerId?: string; |
| 49 | /** |
| 50 | * User-defined tags. Alchemy internal tags are merged automatically. |
| 51 | */ |
| 52 | tags?: Record<string, string>; |
| 53 | } |
| 54 | |
| 55 | /** @resource */ |
| 56 | export interface ApiKey extends Resource< |
| 57 | "AWS.ApiGateway.ApiKey", |
| 58 | ApiKeyProps, |
| 59 | { |
| 60 | id: string; |
| 61 | name: string | undefined; |
| 62 | enabled: boolean | undefined; |
| 63 | tags: Record<string, string>; |
| 64 | }, |
| 65 | never, |
| 66 | Providers |
| 67 | > {} |
| 68 | |
| 69 | /** |
| 70 | * API Gateway API key for usage plans and `apiKeyRequired` methods. |
| 71 | * |
| 72 | * ### API keys |
| 73 | * **Example:** Generated key |
| 74 | * ```typescript |
| 75 | * const key = yield* ApiGateway.ApiKey("PartnerKey", { |
| 76 | * generateDistinctId: true, |
| 77 | * }); |
| 78 | * ``` |
| 79 | */ |
| 80 | const ApiKeyResource = Resource<ApiKey>("AWS.ApiGateway.ApiKey"); |
| 81 | |
| 82 | export { ApiKeyResource as ApiKey }; |
| 83 | |
| 84 | const resolvedValue = (value: Redacted.Redacted<string> | undefined) => |
| 85 | value ? Redacted.value(value) : undefined; |
| 86 | |
| 87 | const generatedName = (id: string, props: ApiKeyProps) => |
| 88 | props.name |
| 89 | ? Effect.succeed(props.name) |
| 90 | : createPhysicalName({ |
| 91 | id, |
| 92 | maxLength: 128, |
| 93 | }); |
| 94 | |
| 95 | const readByName = Effect.fn(function* (id: string, name: string) { |
| 96 | const keys = yield* ag.getApiKeys |
| 97 | .items({ nameQuery: name, limit: 500, includeValues: false }) |
| 98 | .pipe(Stream.runCollect); |
| 99 | |
| 100 | for (const key of keys) { |
| 101 | if (key.name !== name || !key.id) continue; |
| 102 | if (yield* hasAlchemyTags(id, key.tags)) { |
| 103 | return key; |
| 104 | } |
| 105 | } |
| 106 | return undefined; |
| 107 | }); |
| 108 | |
| 109 | export const ApiKeyProvider = () => |
| 110 | Provider.effect( |
| 111 | ApiKeyResource, |
| 112 | Effect.gen(function* () { |
| 113 | return { |
| 114 | stables: ["id"] as const, |
| 115 | diff: Effect.fn(function* ({ news: newsIn, olds }) { |
| 116 | if (!isResolved(newsIn)) return; |
| 117 | const news = newsIn as ApiKeyProps; |
| 118 | if ( |
| 119 | // API Gateway never returns the key value after create, so rotating |
| 120 | // a user-supplied value is modeled as replacement instead of patch. |
| 121 | resolvedValue(news.value) !== resolvedValue(olds.value) || |
| 122 | news.customerId !== olds.customerId |
| 123 | ) { |
| 124 | return { action: "replace" } as const; |
| 125 | } |
| 126 | }), |
| 127 | read: Effect.fn(function* ({ output }) { |
| 128 | if (!output?.id) return undefined; |
| 129 | const k = yield* ag |
| 130 | .getApiKey({ apiKey: output.id, includeValue: false }) |
| 131 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)); |
| 132 | if (!k?.id) return undefined; |
| 133 | return { |
| 134 | id: k.id, |
| 135 | name: k.name, |
| 136 | enabled: k.enabled, |
| 137 | tags: tagRecord(k.tags), |
| 138 | }; |
| 139 | }), |
| 140 | list: () => |
| 141 | ag.getApiKeys.pages({ limit: 500, includeValues: false }).pipe( |
| 142 | Stream.runCollect, |
| 143 | Effect.map((chunk) => |
| 144 | Array.from(chunk).flatMap((page) => |
| 145 | (page.items ?? []) |
| 146 | .filter((k): k is ag.ApiKey & { id: string } => !!k.id) |
| 147 | .map((k) => ({ |
| 148 | id: k.id, |
| 149 | name: k.name, |
| 150 | enabled: k.enabled, |
| 151 | tags: tagRecord(k.tags), |
| 152 | })), |
| 153 | ), |
| 154 | ), |
| 155 | ), |
| 156 | reconcile: Effect.fn(function* ({ id, news: newsIn, output, session }) { |
| 157 | const { region } = yield* AWSEnvironment.current; |
| 158 | if (!isResolved(newsIn)) { |
| 159 | return yield* Effect.die("ApiKey props were not resolved"); |
| 160 | } |
| 161 | const news = newsIn as ApiKeyProps; |
| 162 | const name = yield* generatedName(id, news); |
| 163 | const internalTags = yield* createInternalTags(id); |
| 164 | const desiredTags = { ...news.tags, ...internalTags }; |
| 165 | |
| 166 | // Observe — find the API key. We try the cached id first, fall |
| 167 | // back to scanning by name with the alchemy ownership filter so |
| 168 | // the reconciler converges after an out-of-band recreate or an |
| 169 | // adoption that bypassed our id cache. |
| 170 | let observed = output?.id |
| 171 | ? yield* ag |
| 172 | .getApiKey({ apiKey: output.id, includeValue: false }) |
| 173 | .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined)) |
| 174 | : undefined; |
| 175 | if (!observed?.id) { |
| 176 | observed = yield* readByName(id, name); |
| 177 | } |
| 178 | |
| 179 | // Ensure — create if missing. Tolerate `ConflictException` as a |
| 180 | // race with a peer reconciler or a stray key with the same name: |
| 181 | // re-look up by name and treat the alchemy-owned hit as observed. |
| 182 | if (!observed?.id) { |
| 183 | const created = yield* ag |
| 184 | .createApiKey({ |
| 185 | name, |
| 186 | description: news.description, |
| 187 | enabled: news.enabled, |
| 188 | generateDistinctId: news.generateDistinctId, |
| 189 | // Distilled's CreateApiKeyRequest.value is SensitiveString — |
| 190 | // it accepts the Redacted directly and unwraps on encode, so |
| 191 | // the plaintext never passes through alchemy code. |
| 192 | value: news.value, |
| 193 | stageKeys: news.stageKeys, |
| 194 | customerId: news.customerId, |
| 195 | tags: desiredTags, |
| 196 | }) |
| 197 | .pipe( |
| 198 | Effect.catchTag("ConflictException", () => |
| 199 | Effect.gen(function* () { |
| 200 | const existing = yield* readByName(id, name); |
| 201 | if (existing) return existing; |
| 202 | return yield* ag.ConflictException.make({ |
| 203 | message: `API key '${name}' already exists and is not managed by alchemy`, |
| 204 | }); |
| 205 | }), |
| 206 | ), |
| 207 | ); |
| 208 | if (!created.id) return yield* Effect.die("createApiKey missing id"); |
| 209 | yield* session.note(`Created API key ${created.id}`); |
| 210 | observed = yield* ag.getApiKey({ |
| 211 | apiKey: created.id, |
| 212 | includeValue: false, |
| 213 | }); |
| 214 | } |
| 215 | |
| 216 | const apiKeyId = observed.id!; |
| 217 | |
| 218 | // Sync mutable scalar fields — observed ↔ desired patch list. |
| 219 | const patches: ag.PatchOperation[] = []; |
| 220 | if (news.name !== undefined && news.name !== observed.name) { |
| 221 | patches.push({ |
| 222 | op: "replace", |
| 223 | path: "/name", |
| 224 | value: news.name, |
| 225 | }); |
| 226 | } |
| 227 | if (news.description !== undefined && news.description !== observed.description) { |
| 228 | patches.push({ |
| 229 | op: "replace", |
| 230 | path: "/description", |
| 231 | value: news.description, |
| 232 | }); |
| 233 | } |
| 234 | if (news.enabled !== undefined && news.enabled !== observed.enabled) { |
| 235 | patches.push({ |
| 236 | op: "replace", |
| 237 | path: "/enabled", |
| 238 | value: String(news.enabled), |
| 239 | }); |
| 240 | } |
| 241 | if (patches.length > 0) { |
| 242 | yield* ag.updateApiKey({ |
| 243 | apiKey: apiKeyId, |
| 244 | patchOperations: patches, |
| 245 | }); |
| 246 | } |
| 247 | |
| 248 | // Sync tags — diff observed cloud tags against desired so adoption |
| 249 | // converges without fighting whatever tag set was already there. |
| 250 | const observedTags = tagRecord(observed.tags); |
| 251 | if (!deepEqual(observedTags, desiredTags)) { |
| 252 | yield* syncTags({ |
| 253 | resourceArn: apiKeyArn(region, apiKeyId), |
| 254 | oldTags: observedTags, |
| 255 | newTags: desiredTags, |
| 256 | }); |
| 257 | } |
| 258 | |
| 259 | yield* session.note(`Reconciled API key ${apiKeyId}`); |
| 260 | const final = yield* ag.getApiKey({ |
| 261 | apiKey: apiKeyId, |
| 262 | includeValue: false, |
| 263 | }); |
| 264 | if (!final.id) return yield* Effect.die("getApiKey missing id"); |
| 265 | return { |
| 266 | id: final.id, |
| 267 | name: final.name, |
| 268 | enabled: final.enabled, |
| 269 | tags: tagRecord(final.tags), |
| 270 | }; |
| 271 | }), |
| 272 | delete: Effect.fn(function* ({ output, session }) { |
| 273 | yield* ag |
| 274 | .deleteApiKey({ apiKey: output.id }) |
| 275 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)); |
| 276 | yield* session.note(`Deleted API key ${output.id}`); |
| 277 | }), |
| 278 | }; |
| 279 | }), |
| 280 | ); |