The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as location from "@distilled.cloud/aws/location"; |
| 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, diffTags, hasAlchemyTags, type Tags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Redacted from "effect/Redacted"; |
| 11 | import * as EffectStream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { toTagRecord } from "./internal.ts"; |
| 14 | |
| 15 | export class LocationApiKeyUnexpectedResponse extends Data.TaggedError( |
| 16 | "LocationApiKeyUnexpectedResponse", |
| 17 | )<{ |
| 18 | readonly message: string; |
| 19 | readonly cause?: unknown; |
| 20 | }> {} |
| 21 | |
| 22 | /** |
| 23 | * What a Location API key is allowed to call. Keys authorize *unsigned* |
| 24 | * requests, so restrictions should be as narrow as possible. |
| 25 | */ |
| 26 | export interface ApiKeyRestrictions { |
| 27 | /** |
| 28 | * Allowed API actions, e.g. `["geo:GetMap*"]` or |
| 29 | * `["geo:SearchPlaceIndexForText"]`. Wildcards are allowed at the end of |
| 30 | * an action name. |
| 31 | */ |
| 32 | allowActions: string[]; |
| 33 | /** |
| 34 | * Allowed resource ARNs, e.g. a specific map's ARN or a wildcard like |
| 35 | * `arn:aws:geo:*:*:map/*`. |
| 36 | */ |
| 37 | allowResources: string[]; |
| 38 | /** |
| 39 | * Optional HTTP referer patterns the key may be used from, e.g. |
| 40 | * `["https://example.com/*"]`. |
| 41 | */ |
| 42 | allowReferers?: string[]; |
| 43 | } |
| 44 | |
| 45 | export interface ApiKeyProps { |
| 46 | /** |
| 47 | * Name of the API key. Immutable — changing it replaces the key. |
| 48 | * @default ${app}-${stage}-${id} |
| 49 | */ |
| 50 | keyName?: string; |
| 51 | /** |
| 52 | * The actions, resources, and referers the key is allowed to be used |
| 53 | * with. Updatable in place. |
| 54 | */ |
| 55 | restrictions: ApiKeyRestrictions; |
| 56 | /** |
| 57 | * Optional description of the API key. |
| 58 | */ |
| 59 | description?: string; |
| 60 | /** |
| 61 | * Expiry as an ISO-8601 timestamp, e.g. `"2027-01-01T00:00:00Z"`. |
| 62 | * Mutually exclusive with `noExpiry`. |
| 63 | */ |
| 64 | expireTime?: string; |
| 65 | /** |
| 66 | * Create the key without an expiry. |
| 67 | * @default true when `expireTime` is omitted |
| 68 | */ |
| 69 | noExpiry?: boolean; |
| 70 | /** |
| 71 | * Tags to associate with the API key. |
| 72 | */ |
| 73 | tags?: Record<string, string>; |
| 74 | } |
| 75 | |
| 76 | export interface ApiKey extends Resource< |
| 77 | "AWS.Location.ApiKey", |
| 78 | ApiKeyProps, |
| 79 | { |
| 80 | /** Physical name of the API key. */ |
| 81 | keyName: string; |
| 82 | /** ARN of the API key resource. */ |
| 83 | keyArn: string; |
| 84 | /** |
| 85 | * The key value clients send (`v1.public.…`). Wrapped in `Redacted` — |
| 86 | * unwrap with `Redacted.value(apiKey.key)` where the raw value is |
| 87 | * needed. |
| 88 | */ |
| 89 | key: Redacted.Redacted<string>; |
| 90 | /** Restrictions currently applied to the key. */ |
| 91 | restrictions: ApiKeyRestrictions; |
| 92 | /** Expiry timestamp (ISO-8601), if any. */ |
| 93 | expireTime: string | undefined; |
| 94 | /** Description of the API key. */ |
| 95 | description: string | undefined; |
| 96 | /** Tags currently associated with the key. */ |
| 97 | tags: Record<string, string>; |
| 98 | }, |
| 99 | never, |
| 100 | Providers |
| 101 | > {} |
| 102 | |
| 103 | /** |
| 104 | * An Amazon Location Service API key. API keys authorize **unsigned** |
| 105 | * requests (e.g. map tiles rendered directly in a browser) to a restricted |
| 106 | * set of Location actions and resources. The key name is immutable; |
| 107 | * restrictions, description, and expiry can be updated in place. |
| 108 | * |
| 109 | * The `key` attribute is the secret key value (`v1.public.…`) clients pass |
| 110 | * as the `key` query parameter; it is wrapped in `Redacted`. |
| 111 | * |
| 112 | * Availability: Amazon Location classic (V1) is closed to newer AWS |
| 113 | * accounts — `geo:CreateKey` is rejected service-side with an |
| 114 | * `AccessDeniedException` regardless of IAM policy. Accounts onboarded to |
| 115 | * Location before the V2 split can create keys normally. |
| 116 | * |
| 117 | * ### Creating API Keys |
| 118 | * **Example:** Map-Rendering Key for Browsers |
| 119 | * ```typescript |
| 120 | * import * as Location from "@alchemy.run/aws/Location"; |
| 121 | * |
| 122 | * const map = yield* Location.Map("SiteMap", { |
| 123 | * configuration: { style: "VectorEsriStreets" }, |
| 124 | * }); |
| 125 | * |
| 126 | * const key = yield* Location.ApiKey("SiteMapKey", { |
| 127 | * restrictions: { |
| 128 | * allowActions: ["geo:GetMap*"], |
| 129 | * allowResources: [map.mapArn], |
| 130 | * }, |
| 131 | * }); |
| 132 | * // Redacted.value(key.key) → "v1.public.…" — append as ?key=… to tile URLs |
| 133 | * ``` |
| 134 | * |
| 135 | * **Example:** Key with Referer Restrictions and Expiry |
| 136 | * ```typescript |
| 137 | * const key = yield* Location.ApiKey("WebKey", { |
| 138 | * restrictions: { |
| 139 | * allowActions: ["geo:GetMap*"], |
| 140 | * allowResources: ["arn:aws:geo:*:*:map/*"], |
| 141 | * allowReferers: ["https://example.com/*"], |
| 142 | * }, |
| 143 | * expireTime: "2027-01-01T00:00:00Z", |
| 144 | * }); |
| 145 | * ``` |
| 146 | * |
| 147 | * @resource |
| 148 | */ |
| 149 | export const ApiKey = Resource<ApiKey>("AWS.Location.ApiKey"); |
| 150 | |
| 151 | const createKeyName = (id: string, props: { keyName?: string | undefined }) => |
| 152 | Effect.gen(function* () { |
| 153 | if (props.keyName) return props.keyName; |
| 154 | return yield* createPhysicalName({ id, maxLength: 100 }); |
| 155 | }); |
| 156 | |
| 157 | const unredact = (value: string | Redacted.Redacted<string>): string => |
| 158 | Redacted.isRedacted(value) ? Redacted.value(value) : value; |
| 159 | |
| 160 | const toRestrictions = (restrictions: location.ApiKeyRestrictions): ApiKeyRestrictions => ({ |
| 161 | allowActions: [...restrictions.AllowActions], |
| 162 | allowResources: [...restrictions.AllowResources], |
| 163 | allowReferers: |
| 164 | restrictions.AllowReferers === undefined |
| 165 | ? undefined |
| 166 | : (restrictions.AllowReferers as (string | Redacted.Redacted<string>)[]).map(unredact), |
| 167 | }); |
| 168 | |
| 169 | /** Order-insensitive structural comparison of key restrictions. */ |
| 170 | const sameRestrictions = (a: ApiKeyRestrictions, b: ApiKeyRestrictions) => { |
| 171 | const norm = (r: ApiKeyRestrictions) => |
| 172 | JSON.stringify({ |
| 173 | actions: [...r.allowActions].sort(), |
| 174 | resources: [...r.allowResources].sort(), |
| 175 | referers: [...(r.allowReferers ?? [])].sort(), |
| 176 | }); |
| 177 | return norm(a) === norm(b); |
| 178 | }; |
| 179 | |
| 180 | const readKey = Effect.fn(function* (keyName: string) { |
| 181 | const found = yield* location |
| 182 | .describeKey({ KeyName: keyName }) |
| 183 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 184 | if (!found) return undefined; |
| 185 | return { |
| 186 | keyName: found.KeyName, |
| 187 | keyArn: found.KeyArn, |
| 188 | key: Redacted.make(unredact(found.Key)), |
| 189 | restrictions: toRestrictions(found.Restrictions), |
| 190 | expireTime: found.ExpireTime ? found.ExpireTime.toISOString() : undefined, |
| 191 | description: found.Description ? found.Description : undefined, |
| 192 | tags: toTagRecord(found.Tags), |
| 193 | } satisfies ApiKey["Attributes"]; |
| 194 | }); |
| 195 | |
| 196 | export const ApiKeyProvider = () => |
| 197 | Provider.effect( |
| 198 | ApiKey, |
| 199 | Effect.gen(function* () { |
| 200 | return { |
| 201 | stables: ["keyName", "keyArn", "key"], |
| 202 | list: () => |
| 203 | Effect.gen(function* () { |
| 204 | const names = yield* location.listKeys.pages({}).pipe( |
| 205 | EffectStream.runCollect, |
| 206 | Effect.map((chunk) => |
| 207 | Array.from(chunk).flatMap((page) => |
| 208 | (page.Entries ?? []).map((entry) => entry.KeyName), |
| 209 | ), |
| 210 | ), |
| 211 | ); |
| 212 | const hydrated = yield* Effect.forEach(names, (name) => readKey(name), { |
| 213 | concurrency: 10, |
| 214 | }); |
| 215 | return hydrated.filter((attrs): attrs is ApiKey["Attributes"] => attrs !== undefined); |
| 216 | }), |
| 217 | read: Effect.fn(function* ({ id, olds, output }) { |
| 218 | const keyName = output?.keyName ?? (yield* createKeyName(id, olds ?? {})); |
| 219 | const state = yield* readKey(keyName); |
| 220 | if (!state) return undefined; |
| 221 | return (yield* hasAlchemyTags(id, state.tags as Tags)) ? state : Unowned(state); |
| 222 | }), |
| 223 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 224 | if (!isResolved(news)) return; |
| 225 | const oldName = yield* createKeyName(id, olds); |
| 226 | const newName = yield* createKeyName(id, news); |
| 227 | if (oldName !== newName) { |
| 228 | return { action: "replace" } as const; |
| 229 | } |
| 230 | }), |
| 231 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 232 | const keyName = output?.keyName ?? (yield* createKeyName(id, news)); |
| 233 | const internalTags = yield* createInternalTags(id); |
| 234 | const desiredTags = { ...internalTags, ...news.tags }; |
| 235 | const desiredRestrictions: location.ApiKeyRestrictions = { |
| 236 | AllowActions: news.restrictions.allowActions, |
| 237 | AllowResources: news.restrictions.allowResources, |
| 238 | AllowReferers: news.restrictions.allowReferers, |
| 239 | }; |
| 240 | |
| 241 | let state = yield* readKey(keyName); |
| 242 | |
| 243 | if (state === undefined) { |
| 244 | yield* location |
| 245 | .createKey({ |
| 246 | KeyName: keyName, |
| 247 | Restrictions: desiredRestrictions, |
| 248 | Description: news.description, |
| 249 | ExpireTime: news.expireTime ? new Date(news.expireTime) : undefined, |
| 250 | NoExpiry: news.expireTime ? undefined : (news.noExpiry ?? true), |
| 251 | Tags: desiredTags, |
| 252 | }) |
| 253 | .pipe(Effect.catchTag("ConflictException", () => Effect.void)); |
| 254 | state = yield* readKey(keyName); |
| 255 | if (state === undefined) { |
| 256 | return yield* new LocationApiKeyUnexpectedResponse({ |
| 257 | message: `failed to read created API key ${keyName}`, |
| 258 | }); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | const desiredExpireTime = news.expireTime |
| 263 | ? new Date(news.expireTime).toISOString() |
| 264 | : undefined; |
| 265 | if ( |
| 266 | state.description !== (news.description ?? undefined) || |
| 267 | !sameRestrictions(state.restrictions, news.restrictions) || |
| 268 | (desiredExpireTime !== undefined && state.expireTime !== desiredExpireTime) |
| 269 | ) { |
| 270 | yield* location.updateKey({ |
| 271 | KeyName: keyName, |
| 272 | Description: news.description, |
| 273 | Restrictions: desiredRestrictions, |
| 274 | ExpireTime: desiredExpireTime ? new Date(desiredExpireTime) : undefined, |
| 275 | NoExpiry: desiredExpireTime ? undefined : true, |
| 276 | // Required to update a key that has been used recently. |
| 277 | ForceUpdate: true, |
| 278 | }); |
| 279 | } |
| 280 | |
| 281 | const { removed, upsert } = diffTags(state.tags, desiredTags); |
| 282 | if (removed.length > 0) { |
| 283 | yield* location.untagResource({ |
| 284 | ResourceArn: state.keyArn, |
| 285 | TagKeys: removed, |
| 286 | }); |
| 287 | } |
| 288 | if (upsert.length > 0) { |
| 289 | yield* location.tagResource({ |
| 290 | ResourceArn: state.keyArn, |
| 291 | Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 292 | }); |
| 293 | } |
| 294 | |
| 295 | yield* session.note(state.keyArn); |
| 296 | |
| 297 | const final = yield* readKey(keyName); |
| 298 | if (!final) { |
| 299 | return yield* new LocationApiKeyUnexpectedResponse({ |
| 300 | message: `failed to read reconciled API key ${keyName}`, |
| 301 | }); |
| 302 | } |
| 303 | return final; |
| 304 | }), |
| 305 | delete: Effect.fn(function* ({ output }) { |
| 306 | yield* location |
| 307 | .deleteKey({ KeyName: output.keyName, ForceDelete: true }) |
| 308 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 309 | }), |
| 310 | }; |
| 311 | }), |
| 312 | ); |