The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as cloudfront from "@distilled.cloud/aws/cloudfront"; |
| 2 | import { 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 * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Redacted from "effect/Redacted"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { extractValue } from "./common.ts"; |
| 14 | |
| 15 | export class PublicKeyConflict extends Data.TaggedError("PublicKeyConflict")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | export class PublicKeyUnexpectedResponse extends Data.TaggedError("PublicKeyUnexpectedResponse")<{ |
| 21 | readonly message: string; |
| 22 | readonly cause?: unknown; |
| 23 | }> {} |
| 24 | |
| 25 | export interface PublicKeyProps { |
| 26 | /** |
| 27 | * Name of the public key. If omitted, a deterministic name is generated. |
| 28 | * |
| 29 | * Names must be unique per AWS account. Changing the name triggers |
| 30 | * a replacement. |
| 31 | */ |
| 32 | name?: string; |
| 33 | /** |
| 34 | * PEM-encoded public key body. Changing the key material triggers a |
| 35 | * replacement (CloudFront does not allow rotating an existing public |
| 36 | * key in place). |
| 37 | */ |
| 38 | encodedKey: Redacted.Redacted<string> | string; |
| 39 | /** |
| 40 | * Optional comment describing the key. |
| 41 | */ |
| 42 | comment?: string; |
| 43 | } |
| 44 | |
| 45 | export interface PublicKey extends Resource< |
| 46 | "AWS.CloudFront.PublicKey", |
| 47 | PublicKeyProps, |
| 48 | { |
| 49 | /** |
| 50 | * CloudFront-assigned public key identifier. Used by KeyGroups to |
| 51 | * reference the key. |
| 52 | */ |
| 53 | publicKeyId: string; |
| 54 | /** |
| 55 | * Name of the public key. |
| 56 | */ |
| 57 | name: string; |
| 58 | /** |
| 59 | * PEM-encoded public key body. |
| 60 | */ |
| 61 | encodedKey: string; |
| 62 | /** |
| 63 | * Caller reference used at create time. Stable across updates. |
| 64 | */ |
| 65 | callerReference: string; |
| 66 | /** |
| 67 | * Most recent entity tag for update/delete operations. |
| 68 | */ |
| 69 | etag: string | undefined; |
| 70 | /** |
| 71 | * Current comment on the key. |
| 72 | */ |
| 73 | comment: string | undefined; |
| 74 | }, |
| 75 | never, |
| 76 | Providers |
| 77 | > {} |
| 78 | |
| 79 | /** |
| 80 | * A CloudFront public key. |
| 81 | * |
| 82 | * Public keys are uploaded ahead of being grouped into a {@link KeyGroup} and |
| 83 | * used by Distributions for signed URL or signed cookie verification. |
| 84 | * |
| 85 | * The key body is immutable after creation — changing `encodedKey` triggers |
| 86 | * a replacement (CloudFront returns no API to rotate a key in place). |
| 87 | * ### Creating Public Keys |
| 88 | * **Example:** PEM-encoded RSA public key |
| 89 | * ```typescript |
| 90 | * const key = yield* PublicKey("SignedUrlKey", { |
| 91 | * encodedKey: Redacted.make(yield* fs.readFileString("./public_key.pem")), |
| 92 | * comment: "RSA-2048 signed URL key for /private", |
| 93 | * }); |
| 94 | * ``` |
| 95 | * |
| 96 | * @resource |
| 97 | */ |
| 98 | export const PublicKey = Resource<PublicKey>("AWS.CloudFront.PublicKey"); |
| 99 | |
| 100 | export const PublicKeyProvider = () => |
| 101 | Provider.effect( |
| 102 | PublicKey, |
| 103 | Effect.gen(function* () { |
| 104 | const getById = Effect.fn(function* (id: string) { |
| 105 | const config = yield* cloudfront |
| 106 | .getPublicKeyConfig({ Id: id }) |
| 107 | .pipe(Effect.catchTag("NoSuchPublicKey", () => Effect.undefined)); |
| 108 | if (!config?.PublicKeyConfig) return undefined; |
| 109 | return { config: config.PublicKeyConfig, etag: config.ETag }; |
| 110 | }); |
| 111 | |
| 112 | const getByName = Effect.fn(function* (name: string) { |
| 113 | const summary = yield* cloudfront.listPublicKeys.pages({}).pipe( |
| 114 | Stream.map((page) => page.PublicKeyList?.Items ?? []), |
| 115 | Stream.flattenIterable, |
| 116 | Stream.filter((item) => item.Name === name), |
| 117 | Stream.runHead, |
| 118 | Effect.map(Option.getOrUndefined), |
| 119 | ); |
| 120 | if (!summary?.Id) return undefined; |
| 121 | return yield* getById(summary.Id).pipe( |
| 122 | Effect.map((found) => (found ? { id: summary.Id, ...found } : undefined)), |
| 123 | ); |
| 124 | }); |
| 125 | |
| 126 | const buildConfig = ( |
| 127 | name: string, |
| 128 | callerReference: string, |
| 129 | props: PublicKeyProps, |
| 130 | ): cloudfront.PublicKeyConfig => ({ |
| 131 | Name: name, |
| 132 | CallerReference: callerReference, |
| 133 | EncodedKey: extractValue(props.encodedKey), |
| 134 | Comment: props.comment, |
| 135 | }); |
| 136 | |
| 137 | const toAttrs = ( |
| 138 | id: string, |
| 139 | config: cloudfront.PublicKeyConfig, |
| 140 | etag: string | undefined, |
| 141 | ) => ({ |
| 142 | publicKeyId: id, |
| 143 | name: config.Name, |
| 144 | encodedKey: config.EncodedKey, |
| 145 | callerReference: config.CallerReference, |
| 146 | etag, |
| 147 | comment: config.Comment, |
| 148 | }); |
| 149 | |
| 150 | return { |
| 151 | stables: ["publicKeyId", "callerReference"], |
| 152 | list: () => |
| 153 | Effect.gen(function* () { |
| 154 | // CloudFront is global (no region). `listPublicKeys` summaries lack |
| 155 | // CallerReference/ETag, so fetch each key's full config via |
| 156 | // `getById` to produce the same Attributes shape `read` returns. |
| 157 | const ids = yield* cloudfront.listPublicKeys.pages({}).pipe( |
| 158 | Stream.runCollect, |
| 159 | Effect.map((chunk) => |
| 160 | Array.from(chunk).flatMap((page) => |
| 161 | (page.PublicKeyList?.Items ?? []).map((item) => item.Id), |
| 162 | ), |
| 163 | ), |
| 164 | ); |
| 165 | const rows = yield* Effect.forEach( |
| 166 | ids, |
| 167 | (publicKeyId) => |
| 168 | getById(publicKeyId).pipe( |
| 169 | Effect.map((found) => |
| 170 | found ? toAttrs(publicKeyId, found.config, found.etag) : undefined, |
| 171 | ), |
| 172 | ), |
| 173 | { concurrency: 10 }, |
| 174 | ); |
| 175 | return rows.filter((row) => row !== undefined); |
| 176 | }), |
| 177 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 178 | if (!isResolved(news)) return undefined; |
| 179 | if ((yield* createName(id, olds ?? {})) !== (yield* createName(id, news))) { |
| 180 | return { action: "replace" } as const; |
| 181 | } |
| 182 | // Compare only when the old key is known — an Output-valued |
| 183 | // `encodedKey` doesn't survive a `creating`-state round-trip (it |
| 184 | // deserializes as `undefined`). |
| 185 | if ( |
| 186 | olds.encodedKey !== undefined && |
| 187 | isResolved(olds.encodedKey) && |
| 188 | extractValue(olds.encodedKey) !== extractValue(news.encodedKey) |
| 189 | ) { |
| 190 | return { action: "replace" } as const; |
| 191 | } |
| 192 | }), |
| 193 | read: Effect.fn(function* ({ id, olds, output }) { |
| 194 | if (output?.publicKeyId) { |
| 195 | const found = yield* getById(output.publicKeyId); |
| 196 | if (found) return toAttrs(output.publicKeyId, found.config, found.etag); |
| 197 | } |
| 198 | const name = yield* createName(id, olds ?? {}); |
| 199 | const found = yield* getByName(name); |
| 200 | if (!found) return undefined; |
| 201 | return toAttrs(found.id, found.config, found.etag); |
| 202 | }), |
| 203 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 204 | const name = yield* createName(id, news); |
| 205 | |
| 206 | // Observe — locate the public key by id (cached on `output`) |
| 207 | // or by name. Trust observed cloud state, not stale `olds`. |
| 208 | let observed = output?.publicKeyId |
| 209 | ? yield* getById(output.publicKeyId).pipe( |
| 210 | Effect.map((found) => (found ? { id: output.publicKeyId, ...found } : undefined)), |
| 211 | ) |
| 212 | : undefined; |
| 213 | if (!observed) { |
| 214 | observed = yield* getByName(name); |
| 215 | } |
| 216 | |
| 217 | // Ensure — create the public key if it's missing. Tolerate |
| 218 | // `PublicKeyAlreadyExists` (race with a peer reconciler). |
| 219 | if (!observed) { |
| 220 | const callerReference = name; |
| 221 | const created = yield* cloudfront |
| 222 | .createPublicKey({ |
| 223 | PublicKeyConfig: buildConfig(name, callerReference, news), |
| 224 | }) |
| 225 | .pipe( |
| 226 | Effect.catchTag("PublicKeyAlreadyExists", () => |
| 227 | getByName(name).pipe( |
| 228 | Effect.flatMap((existing) => |
| 229 | existing |
| 230 | ? Effect.succeed({ |
| 231 | PublicKey: { |
| 232 | Id: existing.id, |
| 233 | CreatedTime: new Date(), |
| 234 | PublicKeyConfig: existing.config, |
| 235 | }, |
| 236 | ETag: existing.etag, |
| 237 | Location: undefined, |
| 238 | }) |
| 239 | : Effect.fail( |
| 240 | new PublicKeyConflict({ |
| 241 | message: `Public key '${name}' already exists but could not be recovered`, |
| 242 | }), |
| 243 | ), |
| 244 | ), |
| 245 | ), |
| 246 | ), |
| 247 | ); |
| 248 | if (!created.PublicKey?.Id) { |
| 249 | return yield* new PublicKeyUnexpectedResponse({ |
| 250 | message: "createPublicKey returned no identifier", |
| 251 | }); |
| 252 | } |
| 253 | yield* session.note(created.PublicKey.Id); |
| 254 | return toAttrs(created.PublicKey.Id, created.PublicKey.PublicKeyConfig, created.ETag); |
| 255 | } |
| 256 | |
| 257 | // Sync — patch the comment via `updatePublicKey`. The key body |
| 258 | // is immutable (replacement is forced in `diff`), and the |
| 259 | // CallerReference is observed from the live config rather than |
| 260 | // re-derived. The freshly observed ETag handles optimistic |
| 261 | // concurrency. |
| 262 | const updated = yield* cloudfront.updatePublicKey({ |
| 263 | Id: observed.id, |
| 264 | IfMatch: observed.etag, |
| 265 | PublicKeyConfig: buildConfig( |
| 266 | observed.config.Name, |
| 267 | observed.config.CallerReference, |
| 268 | news, |
| 269 | ), |
| 270 | }); |
| 271 | if (!updated.PublicKey?.Id) { |
| 272 | return yield* new PublicKeyUnexpectedResponse({ |
| 273 | message: "updatePublicKey returned no identifier", |
| 274 | }); |
| 275 | } |
| 276 | yield* session.note(observed.id); |
| 277 | return toAttrs(updated.PublicKey.Id, updated.PublicKey.PublicKeyConfig, updated.ETag); |
| 278 | }), |
| 279 | delete: Effect.fn(function* ({ output }) { |
| 280 | const current = yield* getById(output.publicKeyId); |
| 281 | if (!current) return; |
| 282 | yield* cloudfront |
| 283 | .deletePublicKey({ |
| 284 | Id: output.publicKeyId, |
| 285 | IfMatch: current.etag, |
| 286 | }) |
| 287 | .pipe( |
| 288 | Effect.catchTag("NoSuchPublicKey", () => Effect.void), |
| 289 | // Key groups and their public keys are independent resources in |
| 290 | // the engine graph, so their deletes may be scheduled together. |
| 291 | // CloudFront can continue reporting the key as associated for a |
| 292 | // short period after the group is deleted. Treat that typed |
| 293 | // dependency violation as eventual consistency, while keeping |
| 294 | // every other error immediately visible. |
| 295 | Effect.retry({ |
| 296 | while: (error) => error._tag === "PublicKeyInUse", |
| 297 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]), |
| 298 | }), |
| 299 | ); |
| 300 | }), |
| 301 | }; |
| 302 | }), |
| 303 | ); |
| 304 | |
| 305 | const createName = (id: string, props: PublicKeyProps) => |
| 306 | props.name |
| 307 | ? Effect.succeed(props.name) |
| 308 | : createPhysicalName({ id, maxLength: 128, lowercase: true }); |