The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as kms from "@distilled.cloud/aws/kms"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import * as AWSBindings from "../AWSBindings.ts"; |
| 5 | import { keyLabel, keyPolicyStatement, type KeyLike } from "./KeyBinding.ts"; |
| 6 | import { ReEncrypt, type ReEncryptRequest } from "./ReEncrypt.ts"; |
| 7 | |
| 8 | /** |
| 9 | * Bespoke (not scaffolded): ReEncrypt spans two keys — `kms:ReEncryptTo` on |
| 10 | * the destination and `kms:ReEncryptFrom` on the source — and injects |
| 11 | * `DestinationKeyId` (plus `SourceKeyId` when a source key is bound). |
| 12 | */ |
| 13 | export const ReEncryptHttp = Layer.effect( |
| 14 | ReEncrypt, |
| 15 | Effect.gen(function* () { |
| 16 | const bind = yield* AWSBindings.Bind; |
| 17 | const reEncrypt = yield* AWSBindings.withCredentials(kms.reEncrypt); |
| 18 | |
| 19 | return Effect.fn(function* (destination: KeyLike, source?: KeyLike) { |
| 20 | const from = source ?? destination; |
| 21 | const DestinationKeyId = |
| 22 | typeof destination === "string" |
| 23 | ? Effect.succeed<string>(destination) |
| 24 | : yield* destination.keyId; |
| 25 | const SourceKeyId = |
| 26 | typeof from === "string" ? Effect.succeed<string>(from) : yield* from.keyId; |
| 27 | if (!globalThis.__ALCHEMY_RUNTIME__) { |
| 28 | yield* bind`AWS.KMS.ReEncrypt(${destination}, ${from})`({ |
| 29 | policyStatements: |
| 30 | source === undefined |
| 31 | ? [keyPolicyStatement(["kms:ReEncryptFrom", "kms:ReEncryptTo"], destination)] |
| 32 | : [ |
| 33 | keyPolicyStatement("kms:ReEncryptTo", destination), |
| 34 | keyPolicyStatement("kms:ReEncryptFrom", from), |
| 35 | ], |
| 36 | }); |
| 37 | } |
| 38 | return Effect.fn(`AWS.KMS.ReEncrypt(${keyLabel(destination)})`)(function* ( |
| 39 | request: ReEncryptRequest, |
| 40 | ) { |
| 41 | const destinationKeyId = yield* DestinationKeyId; |
| 42 | // Always pin the source key (AWS best practice for symmetric |
| 43 | // ciphertexts) — and required for alias-bound IAM, where the |
| 44 | // `kms:RequestAlias` condition only matches when the alias appears |
| 45 | // in the request. |
| 46 | const sourceKeyId = yield* SourceKeyId; |
| 47 | return yield* reEncrypt({ |
| 48 | ...request, |
| 49 | SourceKeyId: sourceKeyId, |
| 50 | DestinationKeyId: destinationKeyId, |
| 51 | }); |
| 52 | }); |
| 53 | }); |
| 54 | }), |
| 55 | ); |