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, 04:45 UTC
| 1 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 2 | import * as SecretsManager from "@alchemy.run/aws/SecretsManager"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 5 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Redacted from "effect/Redacted"; |
| 8 | import * as Result from "effect/Result"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import path from "pathe"; |
| 11 | |
| 12 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 13 | |
| 14 | // Secrets Manager marks values as sensitive, so the distilled client can hand |
| 15 | // them back either raw or wrapped in `Redacted` — unwrap for JSON transport. |
| 16 | const unwrapString = (value: string | Redacted.Redacted<string> | undefined): string | undefined => |
| 17 | value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value); |
| 18 | |
| 19 | const unwrapBinary = ( |
| 20 | value: Uint8Array | Redacted.Redacted<Uint8Array> | undefined, |
| 21 | ): Uint8Array | undefined => |
| 22 | value === undefined ? undefined : value instanceof Uint8Array ? value : Redacted.value(value); |
| 23 | |
| 24 | export class SecretsManagerTestFunction extends Lambda.Function<Lambda.Function>()( |
| 25 | "SecretsManagerTestFunction", |
| 26 | ) {} |
| 27 | |
| 28 | export default SecretsManagerTestFunction.make( |
| 29 | { |
| 30 | main, |
| 31 | functionUrl: true, |
| 32 | }, |
| 33 | Effect.gen(function* () { |
| 34 | const stringSecret = yield* SecretsManager.Secret("StringSecret", { |
| 35 | description: "alchemy binding fixture (string value)", |
| 36 | secretString: Redacted.make("alchemy-sm-fixture-value"), |
| 37 | }); |
| 38 | // Created without an initial value: the binary round-trip is driven |
| 39 | // entirely through the PutSecretValue/GetSecretValue bindings. |
| 40 | const binarySecret = yield* SecretsManager.Secret("BinarySecret", { |
| 41 | description: "alchemy binding fixture (binary value)", |
| 42 | }); |
| 43 | // Rotated by this function itself via the RotationEventSource below. |
| 44 | const rotationSecret = yield* SecretsManager.Secret("RotationSecret", { |
| 45 | description: "alchemy binding fixture (rotated value)", |
| 46 | secretString: Redacted.make("alchemy-sm-rotation-initial"), |
| 47 | }); |
| 48 | |
| 49 | const getStringSecret = yield* SecretsManager.GetSecretValue(stringSecret); |
| 50 | const putStringSecret = yield* SecretsManager.PutSecretValue(stringSecret); |
| 51 | const getBinarySecret = yield* SecretsManager.GetSecretValue(binarySecret); |
| 52 | const putBinarySecret = yield* SecretsManager.PutSecretValue(binarySecret); |
| 53 | const describeStringSecret = yield* SecretsManager.DescribeSecret(stringSecret); |
| 54 | const getRandomPassword = yield* SecretsManager.GetRandomPassword(); |
| 55 | const listSecrets = yield* SecretsManager.ListSecrets(); |
| 56 | const listStringVersions = yield* SecretsManager.ListSecretVersionIds(stringSecret); |
| 57 | const batchGetSecrets = yield* SecretsManager.BatchGetSecretValue([ |
| 58 | stringSecret, |
| 59 | rotationSecret, |
| 60 | ]); |
| 61 | |
| 62 | // Rotation-protocol bindings for the rotation secret. |
| 63 | const getRotationValue = yield* SecretsManager.GetSecretValue(rotationSecret); |
| 64 | const putRotationValue = yield* SecretsManager.PutSecretValue(rotationSecret); |
| 65 | const describeRotationSecret = yield* SecretsManager.DescribeSecret(rotationSecret); |
| 66 | const updateRotationStage = yield* SecretsManager.UpdateSecretVersionStage(rotationSecret); |
| 67 | const listRotationVersions = yield* SecretsManager.ListSecretVersionIds(rotationSecret); |
| 68 | const rotateRotationSecret = yield* SecretsManager.RotateSecret(rotationSecret); |
| 69 | |
| 70 | // Register this function as the rotation function for the rotation |
| 71 | // secret. The handler implements the 4-step protocol against the secret |
| 72 | // itself (self-contained: no downstream system to `setSecret`/`testSecret`). |
| 73 | yield* SecretsManager.onSecretRotation( |
| 74 | rotationSecret, |
| 75 | { rotationRules: { scheduleExpression: "rate(4 hours)" } }, |
| 76 | (event) => |
| 77 | Effect.gen(function* () { |
| 78 | if (event.Step === "createSecret") { |
| 79 | // Idempotent: skip if the pending version already exists. |
| 80 | const versions = yield* listRotationVersions({ |
| 81 | IncludeDeprecated: true, |
| 82 | }); |
| 83 | const exists = (versions.Versions ?? []).some( |
| 84 | (version) => version.VersionId === event.ClientRequestToken, |
| 85 | ); |
| 86 | if (!exists) { |
| 87 | const generated = yield* getRandomPassword({ |
| 88 | PasswordLength: 24, |
| 89 | ExcludePunctuation: true, |
| 90 | }); |
| 91 | const password = unwrapString(generated.RandomPassword) ?? ""; |
| 92 | yield* putRotationValue({ |
| 93 | ClientRequestToken: event.ClientRequestToken, |
| 94 | SecretString: `alchemy-sm-rotated-${password}`, |
| 95 | VersionStages: ["AWSPENDING"], |
| 96 | }); |
| 97 | } |
| 98 | } else if (event.Step === "finishSecret") { |
| 99 | const described = yield* describeRotationSecret(); |
| 100 | const stages = described.VersionIdsToStages ?? {}; |
| 101 | const currentVersion = Object.entries(stages).find(([, labels]) => |
| 102 | (labels ?? []).includes("AWSCURRENT"), |
| 103 | )?.[0]; |
| 104 | if (currentVersion !== event.ClientRequestToken) { |
| 105 | yield* updateRotationStage({ |
| 106 | VersionStage: "AWSCURRENT", |
| 107 | MoveToVersionId: event.ClientRequestToken, |
| 108 | RemoveFromVersionId: currentVersion, |
| 109 | }); |
| 110 | } |
| 111 | } |
| 112 | // setSecret / testSecret: nothing to apply or verify — the secret |
| 113 | // is self-contained. |
| 114 | }).pipe( |
| 115 | // Secrets Manager runs a validation invocation right after the |
| 116 | // rotation schedule is configured at deploy time — the freshly |
| 117 | // attached role policies may not have propagated yet. A failed |
| 118 | // validation wedges the rotation "in progress", so retry through |
| 119 | // the IAM-propagation window (bounded). |
| 120 | Effect.retry({ |
| 121 | while: (e): boolean => e._tag === "AccessDeniedException", |
| 122 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]), |
| 123 | }), |
| 124 | Effect.asVoid, |
| 125 | Effect.orDie, |
| 126 | ), |
| 127 | ); |
| 128 | |
| 129 | return { |
| 130 | fetch: Effect.gen(function* () { |
| 131 | const request = yield* HttpServerRequest; |
| 132 | const url = new URL(request.originalUrl); |
| 133 | const pathname = url.pathname; |
| 134 | |
| 135 | if (request.method === "GET" && pathname === "/string-value") { |
| 136 | const result = yield* getStringSecret(); |
| 137 | return yield* HttpServerResponse.json({ |
| 138 | name: result.Name, |
| 139 | arn: result.ARN, |
| 140 | versionId: result.VersionId, |
| 141 | secretString: unwrapString(result.SecretString), |
| 142 | }); |
| 143 | } |
| 144 | |
| 145 | if (request.method === "POST" && pathname === "/put-string") { |
| 146 | const body = (yield* request.json) as unknown as { value: string }; |
| 147 | const result = yield* putStringSecret({ SecretString: body.value }); |
| 148 | return yield* HttpServerResponse.json({ |
| 149 | versionId: result.VersionId, |
| 150 | }); |
| 151 | } |
| 152 | |
| 153 | if (request.method === "POST" && pathname === "/put-binary") { |
| 154 | const body = (yield* request.json) as unknown as { base64: string }; |
| 155 | const bytes = yield* Effect.sync( |
| 156 | () => new Uint8Array(Buffer.from(body.base64, "base64")), |
| 157 | ); |
| 158 | const result = yield* putBinarySecret({ SecretBinary: bytes }); |
| 159 | return yield* HttpServerResponse.json({ |
| 160 | versionId: result.VersionId, |
| 161 | }); |
| 162 | } |
| 163 | |
| 164 | if (request.method === "GET" && pathname === "/binary-value") { |
| 165 | const result = yield* getBinarySecret(); |
| 166 | const bytes = unwrapBinary(result.SecretBinary); |
| 167 | const base64 = bytes |
| 168 | ? yield* Effect.sync(() => Buffer.from(bytes).toString("base64")) |
| 169 | : undefined; |
| 170 | return yield* HttpServerResponse.json({ |
| 171 | versionId: result.VersionId, |
| 172 | secretString: unwrapString(result.SecretString), |
| 173 | base64, |
| 174 | }); |
| 175 | } |
| 176 | |
| 177 | if (request.method === "GET" && pathname === "/describe") { |
| 178 | const result = yield* describeStringSecret(); |
| 179 | return yield* HttpServerResponse.json({ |
| 180 | name: result.Name, |
| 181 | arn: result.ARN, |
| 182 | description: result.Description, |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | if (request.method === "GET" && pathname === "/random-password") { |
| 187 | const length = Number(url.searchParams.get("length") ?? "24"); |
| 188 | const result = yield* getRandomPassword({ |
| 189 | PasswordLength: length, |
| 190 | ExcludePunctuation: true, |
| 191 | }); |
| 192 | return yield* HttpServerResponse.json({ |
| 193 | password: unwrapString(result.RandomPassword), |
| 194 | }); |
| 195 | } |
| 196 | |
| 197 | if (request.method === "GET" && pathname === "/list") { |
| 198 | const name = url.searchParams.get("name"); |
| 199 | if (!name) { |
| 200 | return HttpServerResponse.text("Missing name", { status: 400 }); |
| 201 | } |
| 202 | const result = yield* listSecrets({ |
| 203 | Filters: [{ Key: "name", Values: [name] }], |
| 204 | }); |
| 205 | return yield* HttpServerResponse.json({ |
| 206 | names: (result.SecretList ?? []).map((entry) => entry.Name), |
| 207 | }); |
| 208 | } |
| 209 | |
| 210 | if (request.method === "GET" && pathname === "/versions") { |
| 211 | const result = yield* listStringVersions({ |
| 212 | IncludeDeprecated: true, |
| 213 | }); |
| 214 | return yield* HttpServerResponse.json({ |
| 215 | versions: (result.Versions ?? []).map((version) => ({ |
| 216 | versionId: version.VersionId, |
| 217 | stages: version.VersionStages ?? [], |
| 218 | })), |
| 219 | }); |
| 220 | } |
| 221 | |
| 222 | if (request.method === "GET" && pathname === "/batch") { |
| 223 | const result = yield* batchGetSecrets(); |
| 224 | return yield* HttpServerResponse.json({ |
| 225 | values: (result.SecretValues ?? []) |
| 226 | .map((entry) => ({ |
| 227 | name: entry.Name, |
| 228 | secretString: unwrapString(entry.SecretString), |
| 229 | })) |
| 230 | .sort((a, b) => (a.name ?? "").localeCompare(b.name ?? "")), |
| 231 | errors: (result.Errors ?? []).map((error) => error.ErrorCode), |
| 232 | }); |
| 233 | } |
| 234 | |
| 235 | if (request.method === "POST" && pathname === "/rotate") { |
| 236 | // Error-transparent: surface the typed failure to the test as a |
| 237 | // 409 body instead of an opaque 500 from `orDie`. |
| 238 | const result = yield* Effect.result(rotateRotationSecret()); |
| 239 | if (Result.isFailure(result)) { |
| 240 | return yield* HttpServerResponse.json( |
| 241 | { |
| 242 | error: result.failure._tag, |
| 243 | message: |
| 244 | (result.failure as { Message?: string }).Message ?? |
| 245 | (result.failure as { message?: string }).message, |
| 246 | }, |
| 247 | { status: 409 }, |
| 248 | ); |
| 249 | } |
| 250 | return yield* HttpServerResponse.json({ |
| 251 | versionId: result.success.VersionId, |
| 252 | }); |
| 253 | } |
| 254 | |
| 255 | if (request.method === "GET" && pathname === "/rotation-value") { |
| 256 | const result = yield* Effect.result(getRotationValue()); |
| 257 | if (Result.isFailure(result)) { |
| 258 | return yield* HttpServerResponse.json( |
| 259 | { |
| 260 | error: result.failure._tag, |
| 261 | message: |
| 262 | (result.failure as { Message?: string }).Message ?? |
| 263 | (result.failure as { message?: string }).message, |
| 264 | }, |
| 265 | { status: 409 }, |
| 266 | ); |
| 267 | } |
| 268 | return yield* HttpServerResponse.json({ |
| 269 | versionId: result.success.VersionId, |
| 270 | secretString: unwrapString(result.success.SecretString), |
| 271 | }); |
| 272 | } |
| 273 | |
| 274 | if (request.method === "GET" && pathname === "/rotation-status") { |
| 275 | const result = yield* describeRotationSecret(); |
| 276 | return yield* HttpServerResponse.json({ |
| 277 | rotationEnabled: result.RotationEnabled === true, |
| 278 | lastRotated: result.LastRotatedDate, |
| 279 | }); |
| 280 | } |
| 281 | |
| 282 | return yield* HttpServerResponse.json( |
| 283 | { |
| 284 | error: "Not found", |
| 285 | method: request.method, |
| 286 | pathname, |
| 287 | }, |
| 288 | { status: 404 }, |
| 289 | ); |
| 290 | }).pipe(Effect.orDie), |
| 291 | }; |
| 292 | }).pipe( |
| 293 | Effect.provide( |
| 294 | Layer.mergeAll( |
| 295 | SecretsManager.GetSecretValueHttp, |
| 296 | SecretsManager.PutSecretValueHttp, |
| 297 | SecretsManager.DescribeSecretHttp, |
| 298 | SecretsManager.GetRandomPasswordHttp, |
| 299 | SecretsManager.ListSecretsHttp, |
| 300 | SecretsManager.ListSecretVersionIdsHttp, |
| 301 | SecretsManager.BatchGetSecretValueHttp, |
| 302 | SecretsManager.UpdateSecretVersionStageHttp, |
| 303 | SecretsManager.RotateSecretHttp, |
| 304 | Lambda.SecretRotationEventSource, |
| 305 | ), |
| 306 | ), |
| 307 | ), |
| 308 | ); |