The best way to control Claude Code, Codex and more from any computer or phone

main
ts 388 lines 15.5 KB
Raw
1 import crypto from "node:crypto";
2 import * as AWS from "@alchemy.run/aws";
3 import * as kms from "@distilled.cloud/aws/kms";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9
10 /**
11 * Standing test key aliases — see the header comment in `Bindings.test.ts`.
12 * The keys behind these aliases are acquired out-of-band by the test's
13 * `beforeAll` (reclaiming the previous run's pending-deletion keys when
14 * possible) and released in `afterAll` by deleting the aliases and
15 * scheduling the keys for deletion (7-day minimum window — KMS's terminal
16 * "deleted" state; pending-deletion keys are not billed). A passing run
17 * therefore leaves no aliases and no enabled keys behind.
18 */
19 export const STANDING_KEY_ALIAS = "alias/alchemy-test-kms-bindings" as const;
20 export const STANDING_HMAC_KEY_ALIAS = "alias/alchemy-test-bindings-hmac" as const;
21 export const STANDING_SIGNING_KEY_ALIAS = "alias/alchemy-test-bindings-sign" as const;
22 export const STANDING_AGREEMENT_KEY_ALIAS = "alias/alchemy-test-bindings-ecdh" as const;
23
24 export class KMSTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
25 "KMSTestFunction",
26 ) {}
27
28 const fromBase64 = (value: string) =>
29 Effect.sync(() => new Uint8Array(Buffer.from(value, "base64")));
30
31 const toBase64 = (value: Uint8Array) => Effect.sync(() => Buffer.from(value).toString("base64"));
32
33 const unwrapSensitive = (
34 value: Uint8Array | Redacted.Redacted<Uint8Array> | undefined,
35 ): Uint8Array | undefined =>
36 value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value;
37
38 export default KMSTestFunction.make(
39 {
40 main: import.meta.url,
41 functionUrl: true,
42 },
43 Effect.gen(function* () {
44 // Symmetric encryption key
45 const encrypt = yield* AWS.KMS.Encrypt(STANDING_KEY_ALIAS);
46 const decrypt = yield* AWS.KMS.Decrypt(STANDING_KEY_ALIAS);
47 const generateDataKey = yield* AWS.KMS.GenerateDataKey(STANDING_KEY_ALIAS);
48 const generateDataKeyWithoutPlaintext =
49 yield* AWS.KMS.GenerateDataKeyWithoutPlaintext(STANDING_KEY_ALIAS);
50 const generateDataKeyPair = yield* AWS.KMS.GenerateDataKeyPair(STANDING_KEY_ALIAS);
51 const generateDataKeyPairWithoutPlaintext =
52 yield* AWS.KMS.GenerateDataKeyPairWithoutPlaintext(STANDING_KEY_ALIAS);
53 const reEncrypt = yield* AWS.KMS.ReEncrypt(STANDING_KEY_ALIAS);
54 const describeKey = yield* AWS.KMS.DescribeKey(STANDING_KEY_ALIAS);
55 // HMAC key
56 const generateMac = yield* AWS.KMS.GenerateMac(STANDING_HMAC_KEY_ALIAS);
57 const verifyMac = yield* AWS.KMS.VerifyMac(STANDING_HMAC_KEY_ALIAS);
58 // Asymmetric signing key
59 const sign = yield* AWS.KMS.Sign(STANDING_SIGNING_KEY_ALIAS);
60 const verify = yield* AWS.KMS.Verify(STANDING_SIGNING_KEY_ALIAS);
61 const getSigningPublicKey = yield* AWS.KMS.GetPublicKey(STANDING_SIGNING_KEY_ALIAS);
62 // ECDH key-agreement key
63 const deriveSharedSecret = yield* AWS.KMS.DeriveSharedSecret(STANDING_AGREEMENT_KEY_ALIAS);
64 const getAgreementPublicKey = yield* AWS.KMS.GetPublicKey(STANDING_AGREEMENT_KEY_ALIAS);
65 // Account-level (not key-scoped)
66 const generateRandom = yield* AWS.KMS.GenerateRandom();
67 // Deliberately NOT a binding: used by /unauthorized to prove the Lambda
68 // role received ONLY the bound kms actions (least privilege).
69 const getKeyRotationStatus = yield* kms.getKeyRotationStatus;
70
71 return {
72 fetch: Effect.gen(function* () {
73 const request = yield* HttpServerRequest;
74 const url = new URL(request.originalUrl);
75 const pathname = url.pathname;
76
77 if (request.method === "GET" && pathname === "/ready") {
78 return yield* HttpServerResponse.json({ ok: true });
79 }
80
81 if (request.method === "POST" && pathname === "/encrypt") {
82 const body = (yield* request.json) as {
83 plaintextBase64: string;
84 context?: Record<string, string>;
85 };
86 const result = yield* encrypt({
87 Plaintext: yield* fromBase64(body.plaintextBase64),
88 EncryptionContext: body.context,
89 });
90 return yield* HttpServerResponse.json({
91 keyId: result.KeyId,
92 ciphertextBase64: result.CiphertextBlob
93 ? yield* toBase64(result.CiphertextBlob)
94 : undefined,
95 });
96 }
97
98 if (request.method === "POST" && pathname === "/decrypt") {
99 const body = (yield* request.json) as {
100 ciphertextBase64: string;
101 context?: Record<string, string>;
102 };
103 const ciphertext = yield* fromBase64(body.ciphertextBase64);
104 const result = yield* decrypt({
105 CiphertextBlob: ciphertext,
106 EncryptionContext: body.context,
107 }).pipe(
108 Effect.match({
109 onFailure: (error) => ({
110 ok: false as const,
111 error: error._tag,
112 }),
113 onSuccess: (response) => ({
114 ok: true as const,
115 keyId: response.KeyId,
116 plaintext: unwrapSensitive(response.Plaintext),
117 }),
118 }),
119 );
120 if (!result.ok) {
121 return yield* HttpServerResponse.json(result);
122 }
123 return yield* HttpServerResponse.json({
124 ok: true,
125 keyId: result.keyId,
126 plaintextBase64: result.plaintext ? yield* toBase64(result.plaintext) : undefined,
127 });
128 }
129
130 if (request.method === "POST" && pathname === "/generate-data-key") {
131 const result = yield* generateDataKey({ KeySpec: "AES_256" });
132 const plaintext = unwrapSensitive(result.Plaintext);
133 return yield* HttpServerResponse.json({
134 keyId: result.KeyId,
135 plaintextBase64: plaintext ? yield* toBase64(plaintext) : undefined,
136 ciphertextBase64: result.CiphertextBlob
137 ? yield* toBase64(result.CiphertextBlob)
138 : undefined,
139 });
140 }
141
142 if (request.method === "POST" && pathname === "/generate-data-key-without-plaintext") {
143 const result = yield* generateDataKeyWithoutPlaintext({
144 KeySpec: "AES_256",
145 });
146 return yield* HttpServerResponse.json({
147 keyId: result.KeyId,
148 ciphertextBase64: result.CiphertextBlob
149 ? yield* toBase64(result.CiphertextBlob)
150 : undefined,
151 });
152 }
153
154 if (request.method === "POST" && pathname === "/generate-data-key-pair") {
155 const result = yield* generateDataKeyPair({
156 KeyPairSpec: "ECC_NIST_P256",
157 });
158 const privateKeyPlaintext = unwrapSensitive(result.PrivateKeyPlaintext);
159 return yield* HttpServerResponse.json({
160 keyId: result.KeyId,
161 keyPairSpec: result.KeyPairSpec,
162 publicKeyBase64: result.PublicKey ? yield* toBase64(result.PublicKey) : undefined,
163 privateKeyPlaintextBase64: privateKeyPlaintext
164 ? yield* toBase64(privateKeyPlaintext)
165 : undefined,
166 privateKeyCiphertextBase64: result.PrivateKeyCiphertextBlob
167 ? yield* toBase64(result.PrivateKeyCiphertextBlob)
168 : undefined,
169 });
170 }
171
172 if (request.method === "POST" && pathname === "/generate-data-key-pair-without-plaintext") {
173 const result = yield* generateDataKeyPairWithoutPlaintext({
174 KeyPairSpec: "ECC_NIST_P256",
175 });
176 return yield* HttpServerResponse.json({
177 keyId: result.KeyId,
178 publicKeyBase64: result.PublicKey ? yield* toBase64(result.PublicKey) : undefined,
179 privateKeyCiphertextBase64: result.PrivateKeyCiphertextBlob
180 ? yield* toBase64(result.PrivateKeyCiphertextBlob)
181 : undefined,
182 });
183 }
184
185 if (request.method === "POST" && pathname === "/re-encrypt") {
186 const body = (yield* request.json) as {
187 ciphertextBase64: string;
188 sourceContext?: Record<string, string>;
189 destinationContext?: Record<string, string>;
190 };
191 const result = yield* reEncrypt({
192 CiphertextBlob: yield* fromBase64(body.ciphertextBase64),
193 SourceEncryptionContext: body.sourceContext,
194 DestinationEncryptionContext: body.destinationContext,
195 });
196 return yield* HttpServerResponse.json({
197 keyId: result.KeyId,
198 sourceKeyId: result.SourceKeyId,
199 ciphertextBase64: result.CiphertextBlob
200 ? yield* toBase64(result.CiphertextBlob)
201 : undefined,
202 });
203 }
204
205 if (request.method === "GET" && pathname === "/describe-key") {
206 const result = yield* describeKey();
207 return yield* HttpServerResponse.json({
208 keyId: result.KeyMetadata?.KeyId,
209 keySpec: result.KeyMetadata?.KeySpec,
210 keyState: result.KeyMetadata?.KeyState,
211 });
212 }
213
214 if (request.method === "POST" && pathname === "/mac") {
215 const body = (yield* request.json) as { messageBase64: string };
216 const result = yield* generateMac({
217 Message: yield* fromBase64(body.messageBase64),
218 MacAlgorithm: "HMAC_SHA_256",
219 });
220 return yield* HttpServerResponse.json({
221 keyId: result.KeyId,
222 macBase64: result.Mac ? yield* toBase64(result.Mac) : undefined,
223 });
224 }
225
226 if (request.method === "POST" && pathname === "/verify-mac") {
227 const body = (yield* request.json) as {
228 messageBase64: string;
229 macBase64: string;
230 };
231 const result = yield* verifyMac({
232 Message: yield* fromBase64(body.messageBase64),
233 Mac: yield* fromBase64(body.macBase64),
234 MacAlgorithm: "HMAC_SHA_256",
235 }).pipe(
236 Effect.match({
237 onFailure: (error) => ({
238 ok: false as const,
239 error: error._tag,
240 }),
241 onSuccess: (response) => ({
242 ok: true as const,
243 macValid: response.MacValid,
244 }),
245 }),
246 );
247 return yield* HttpServerResponse.json(result);
248 }
249
250 if (request.method === "POST" && pathname === "/sign") {
251 const body = (yield* request.json) as { messageBase64: string };
252 const result = yield* sign({
253 Message: yield* fromBase64(body.messageBase64),
254 SigningAlgorithm: "ECDSA_SHA_256",
255 });
256 return yield* HttpServerResponse.json({
257 keyId: result.KeyId,
258 signatureBase64: result.Signature ? yield* toBase64(result.Signature) : undefined,
259 });
260 }
261
262 if (request.method === "POST" && pathname === "/verify") {
263 const body = (yield* request.json) as {
264 messageBase64: string;
265 signatureBase64: string;
266 };
267 const result = yield* verify({
268 Message: yield* fromBase64(body.messageBase64),
269 Signature: yield* fromBase64(body.signatureBase64),
270 SigningAlgorithm: "ECDSA_SHA_256",
271 }).pipe(
272 Effect.match({
273 onFailure: (error) => ({
274 ok: false as const,
275 error: error._tag,
276 }),
277 onSuccess: (response) => ({
278 ok: true as const,
279 signatureValid: response.SignatureValid,
280 }),
281 }),
282 );
283 return yield* HttpServerResponse.json(result);
284 }
285
286 if (request.method === "GET" && pathname === "/public-key") {
287 const result = yield* getSigningPublicKey();
288 return yield* HttpServerResponse.json({
289 keyId: result.KeyId,
290 keyUsage: result.KeyUsage,
291 publicKeyBase64: result.PublicKey ? yield* toBase64(result.PublicKey) : undefined,
292 signingAlgorithms: result.SigningAlgorithms,
293 });
294 }
295
296 if (request.method === "POST" && pathname === "/derive-shared-secret") {
297 // Generate an ephemeral local P-256 key pair, run ECDH inside KMS
298 // against the local public key, then recompute the shared secret
299 // locally against the KMS key's public key. Both sides must agree.
300 const localPair = yield* Effect.sync(() =>
301 crypto.generateKeyPairSync("ec", { namedCurve: "prime256v1" }),
302 );
303 const localPublicDer = yield* Effect.sync(
304 () => new Uint8Array(localPair.publicKey.export({ type: "spki", format: "der" })),
305 );
306 const kmsResult = yield* deriveSharedSecret({
307 KeyAgreementAlgorithm: "ECDH",
308 PublicKey: localPublicDer,
309 });
310 const kmsShared = unwrapSensitive(kmsResult.SharedSecret);
311 const kmsPublic = yield* getAgreementPublicKey();
312 const localShared = kmsPublic.PublicKey
313 ? yield* Effect.sync(() =>
314 crypto.diffieHellman({
315 privateKey: localPair.privateKey,
316 publicKey: crypto.createPublicKey({
317 key: Buffer.from(kmsPublic.PublicKey!),
318 format: "der",
319 type: "spki",
320 }),
321 }),
322 )
323 : undefined;
324 return yield* HttpServerResponse.json({
325 keyId: kmsResult.KeyId,
326 byteLength: kmsShared?.length,
327 match:
328 kmsShared !== undefined &&
329 localShared !== undefined &&
330 Buffer.from(kmsShared).equals(localShared),
331 });
332 }
333
334 if (request.method === "POST" && pathname === "/random") {
335 const result = yield* generateRandom({ NumberOfBytes: 32 });
336 const bytes = unwrapSensitive(result.Plaintext);
337 return yield* HttpServerResponse.json({
338 randomBase64: bytes ? yield* toBase64(bytes) : undefined,
339 });
340 }
341
342 if (request.method === "GET" && pathname === "/unauthorized") {
343 // kms:GetKeyRotationStatus is not bound — the role must reject it.
344 // The API only accepts a key id/ARN (not an alias), so resolve the
345 // real key id through the bound DescribeKey first.
346 const described = yield* describeKey();
347 const result = yield* getKeyRotationStatus({
348 KeyId: described.KeyMetadata!.KeyId,
349 }).pipe(
350 Effect.match({
351 onFailure: (error) => ({
352 ok: false as const,
353 error: error._tag,
354 }),
355 onSuccess: () => ({ ok: true as const }),
356 }),
357 );
358 return yield* HttpServerResponse.json(result);
359 }
360
361 return yield* HttpServerResponse.json(
362 { error: "Not found", method: request.method, pathname },
363 { status: 404 },
364 );
365 }).pipe(Effect.orDie),
366 };
367 }).pipe(
368 Effect.provide(
369 Layer.mergeAll(
370 AWS.KMS.DecryptHttp,
371 AWS.KMS.EncryptHttp,
372 AWS.KMS.GenerateDataKeyHttp,
373 AWS.KMS.GenerateDataKeyWithoutPlaintextHttp,
374 AWS.KMS.GenerateDataKeyPairHttp,
375 AWS.KMS.GenerateDataKeyPairWithoutPlaintextHttp,
376 AWS.KMS.ReEncryptHttp,
377 AWS.KMS.DescribeKeyHttp,
378 AWS.KMS.GenerateMacHttp,
379 AWS.KMS.VerifyMacHttp,
380 AWS.KMS.SignHttp,
381 AWS.KMS.VerifyHttp,
382 AWS.KMS.GetPublicKeyHttp,
383 AWS.KMS.DeriveSharedSecretHttp,
384 AWS.KMS.GenerateRandomHttp,
385 ),
386 ),
387 ),
388 );