@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 06:00 UTC

main
ts 135 lines 5.06 KB
Raw
1 import * as GCP from "@alchemy.run/gcp";
2 import * as Effect from "effect/Effect";
3 import { HttpServerRequest } from "effect/http/HttpServerRequest";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import { ApiKey, DataKey } from "./resources.ts";
6
7 /** Constant-time comparison so response timing does not leak the key. */
8 const sameKey = (expected: string, given: string | undefined) => {
9 if (given === undefined || given.length !== expected.length) return false;
10 let diff = 0;
11 for (let index = 0; index < expected.length; index++) {
12 diff |= expected.charCodeAt(index) ^ given.charCodeAt(index);
13 }
14 return diff === 0;
15 };
16
17 const toBase64 = (text: string) => Effect.sync(() => Buffer.from(text, "utf8").toString("base64"));
18
19 const fromBase64 = (data: string) =>
20 Effect.sync(() => Buffer.from(data, "base64").toString("utf8"));
21
22 const error = (status: number, message: string) =>
23 HttpServerResponse.json({ error: message }, { status });
24
25 /**
26 * Encryption as a service on Cloud Run.
27 *
28 * Callers never hold key material: `/encrypt` hands plaintext to Cloud KMS
29 * and returns the ciphertext, `/decrypt` does the reverse. Both routes are
30 * gated by an API key the service reads from Secret Manager per request,
31 * so rotating the key is `gcloud secrets versions add` — no redeploy.
32 *
33 * - `POST /encrypt` — `{ plaintext }` → `{ ciphertext }` (base64).
34 * - `POST /decrypt` — `{ ciphertext }` → `{ plaintext }`.
35 *
36 * Each binding grants one role on the service's runtime service account,
37 * scoped to the one resource it was bound to.
38 */
39 export default class Api extends GCP.Function<Api>()(
40 "Api",
41 {
42 main: import.meta.url,
43 invokerIamDisabled: true,
44 },
45 Effect.gen(function* () {
46 const dataKey = yield* DataKey;
47 const apiKey = yield* ApiKey;
48
49 // roles/cloudkms.cryptoKeyEncrypter / cryptoKeyDecrypter on DataKey.
50 const encrypt = yield* GCP.KMS.Encrypt(dataKey);
51 const decrypt = yield* GCP.KMS.Decrypt(dataKey);
52 // roles/secretmanager.secretAccessor on ApiKey.
53 const apiKeySecret = yield* GCP.SecretManager.ReadSecret(apiKey);
54
55 /**
56 * Read the `latest` version on every call so a rotated key takes
57 * effect immediately. With no version yet the API refuses everyone
58 * instead of failing open.
59 */
60 const authorize = (request: HttpServerRequest) =>
61 apiKeySecret.access().pipe(
62 Effect.map((expected) =>
63 expected === undefined
64 ? ("unconfigured" as const)
65 : sameKey(expected, request.headers["x-api-key"])
66 ? ("ok" as const)
67 : ("denied" as const),
68 ),
69 Effect.orDie,
70 );
71
72 const readField = (request: HttpServerRequest, field: string) =>
73 request.json.pipe(
74 Effect.map((body) => {
75 const value = (body as Record<string, unknown> | null)?.[field];
76 return typeof value === "string" && value.length > 0 ? value : undefined;
77 }),
78 Effect.catch(() => Effect.succeed(undefined)),
79 );
80
81 return {
82 fetch: Effect.gen(function* () {
83 const request = yield* HttpServerRequest;
84 const { pathname } = new URL(request.originalUrl);
85
86 if (request.method === "GET" && pathname === "/") {
87 return HttpServerResponse.text("ok");
88 }
89
90 const route =
91 request.method === "POST" && (pathname === "/encrypt" || pathname === "/decrypt")
92 ? pathname
93 : undefined;
94 if (route === undefined) return yield* error(404, "not found");
95
96 const auth = yield* authorize(request);
97 if (auth === "unconfigured") {
98 return yield* error(503, "no api key version has been added to the secret");
99 }
100 if (auth === "denied") return yield* error(401, "invalid api key");
101
102 if (route === "/encrypt") {
103 const plaintext = yield* readField(request, "plaintext");
104 if (plaintext === undefined) {
105 return yield* error(400, "plaintext is required");
106 }
107 const { ciphertext } = yield* encrypt({
108 body: { plaintext: yield* toBase64(plaintext) },
109 }).pipe(Effect.orDie);
110 return yield* HttpServerResponse.json({ ciphertext });
111 }
112
113 const ciphertext = yield* readField(request, "ciphertext");
114 if (ciphertext === undefined) {
115 return yield* error(400, "ciphertext is required");
116 }
117 // KMS rejects ciphertext it did not produce (or that was tampered
118 // with) as a bad request; that is the caller's fault, not ours.
119 const decrypted = yield* decrypt({ body: { ciphertext } }).pipe(
120 Effect.map((response) => response.plaintext),
121 Effect.catchTag("BadRequest", () => Effect.succeed(null)),
122 Effect.orDie,
123 );
124 if (decrypted === null) {
125 return yield* error(400, "ciphertext could not be decrypted");
126 }
127 return yield* HttpServerResponse.json({
128 plaintext: yield* fromBase64(decrypted ?? ""),
129 });
130 }),
131 };
132 }).pipe(
133 Effect.provide([GCP.KMS.EncryptHttp, GCP.KMS.DecryptHttp, GCP.SecretManager.ReadSecretHttp]),
134 ),
135 ) {}