@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, 04:45 UTC

main
ts 202 lines 7.49 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, Links } from "./resources.ts";
6
7 /** Base62 so codes stay short and URL-safe. */
8 const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
9
10 const newCode = () =>
11 Array.from(
12 crypto.getRandomValues(new Uint8Array(7)),
13 (byte) => ALPHABET[byte % ALPHABET.length],
14 ).join("");
15
16 /**
17 * Cloud Run terminates TLS at its front end and forwards plain HTTP, so
18 * the public origin comes from the forwarded headers.
19 */
20 const publicOrigin = (request: HttpServerRequest) =>
21 `${request.headers["x-forwarded-proto"] ?? "https"}://${request.headers.host}`;
22
23 /** Constant-time comparison so response timing does not leak the key. */
24 const sameKey = (expected: string, given: string | undefined) => {
25 if (given === undefined || given.length !== expected.length) return false;
26 let diff = 0;
27 for (let index = 0; index < expected.length; index++) {
28 diff |= expected.charCodeAt(index) ^ given.charCodeAt(index);
29 }
30 return diff === 0;
31 };
32
33 interface Link {
34 url: string;
35 clicks: number;
36 createdAt: string;
37 }
38
39 /**
40 * A link shortener on Cloud Run.
41 *
42 * This is the shape of most GCP web services: one Cloud Run container,
43 * Firestore for state, Secret Manager for the credential the container
44 * needs at runtime. Nothing is wired by hand — each `yield*` of a binding
45 * grants the matching IAM role on the service's runtime service account
46 * and injects whatever the call needs into the revision.
47 *
48 * - `POST /links` — mint a code for a URL (requires `x-api-key`).
49 * - `GET /l/:code` — redirect and count the click.
50 * - `GET /links/:code` — read the link back.
51 * - `DELETE /links/:code` — retire a code (requires `x-api-key`).
52 *
53 * `invokerIamDisabled: true` makes the service publicly reachable, which
54 * a link shortener has to be. Drop it and Cloud Run requires a signed
55 * Google identity token on every request.
56 */
57 export default class Api extends GCP.Function<Api>()(
58 "Api",
59 {
60 main: import.meta.url,
61 invokerIamDisabled: true,
62 },
63 Effect.gen(function* () {
64 const links = yield* Links;
65 const apiKey = yield* ApiKey;
66
67 // Each binding grants the runtime service account one role:
68 // datastore.user on the project, under an IAM Condition naming only
69 // this database, and secretmanager.secretAccessor on the API key
70 // secret only.
71 const db = yield* GCP.Firestore.ReadWriteDatabase(links);
72 const key = yield* GCP.SecretManager.ReadSecret(apiKey);
73
74 const readLink = (code: string) =>
75 db.get(`links/${code}`).pipe(
76 Effect.map((document): Link | undefined => {
77 // `get` answers `undefined` for a missing document, and fields
78 // come back as plain JavaScript values.
79 const { url, clicks, createdAt } = document?.fields ?? {};
80 if (typeof url !== "string") return undefined;
81 return {
82 url,
83 clicks: typeof clicks === "number" ? clicks : 0,
84 createdAt: createdAt instanceof Date ? createdAt.toISOString() : "",
85 };
86 }),
87 Effect.orDie,
88 );
89
90 /**
91 * Secret Manager holds the key; the container reads the `latest`
92 * version on demand. Until someone adds a version the API cannot
93 * authenticate anyone, so say so instead of failing open.
94 */
95 const authorize = (request: HttpServerRequest) =>
96 key.access().pipe(
97 Effect.map((expected) => {
98 if (expected === undefined) return "unconfigured" as const;
99 return sameKey(expected, request.headers["x-api-key"])
100 ? ("ok" as const)
101 : ("denied" as const);
102 }),
103 Effect.orDie,
104 );
105
106 return {
107 fetch: Effect.gen(function* () {
108 const request = yield* HttpServerRequest;
109 const url = new URL(request.originalUrl);
110 const segments = url.pathname.split("/").filter(Boolean);
111
112 if (request.method === "GET" && segments.length === 0) {
113 return HttpServerResponse.text("ok");
114 }
115
116 // Mint a code. 62^7 keeps collisions rare, and `create` makes
117 // them harmless.
118 if (request.method === "POST" && url.pathname === "/links") {
119 const auth = yield* authorize(request);
120 if (auth !== "ok") {
121 return yield* HttpServerResponse.json(
122 {
123 error:
124 auth === "unconfigured"
125 ? "no api key version has been added to the secret"
126 : "invalid api key",
127 },
128 { status: auth === "unconfigured" ? 503 : 401 },
129 );
130 }
131
132 const body = (yield* request.json) as { url?: string };
133 if (!body.url) {
134 return yield* HttpServerResponse.json({ error: "url is required" }, { status: 400 });
135 }
136
137 // `create` fails with DocumentAlreadyExists instead of
138 // overwriting, so a collision just mints another code.
139 const code = yield* Effect.suspend(() => {
140 const code = newCode();
141 return db
142 .create(`links/${code}`, {
143 url: body.url,
144 clicks: 0,
145 createdAt: new Date(),
146 })
147 .pipe(Effect.as(code));
148 }).pipe(
149 Effect.retry({
150 while: (error) => error._tag === "GCP.Firestore.DocumentAlreadyExists",
151 times: 3,
152 }),
153 Effect.orDie,
154 );
155
156 return yield* HttpServerResponse.json(
157 { code, shortUrl: `${publicOrigin(request)}/l/${code}` },
158 { status: 201 },
159 );
160 }
161
162 // Follow a link. The click counter is a read-modify-write, which
163 // is fine for a counter nobody bills on; a Firestore transaction
164 // is the answer when the count has to be exact.
165 if (request.method === "GET" && segments[0] === "l" && segments[1]) {
166 const link = yield* readLink(segments[1]);
167 if (link === undefined) {
168 return yield* HttpServerResponse.json({ error: "unknown code" }, { status: 404 });
169 }
170
171 // `update` writes only the keys it is given.
172 yield* db.update(`links/${segments[1]}`, { clicks: link.clicks + 1 }).pipe(Effect.orDie);
173
174 return HttpServerResponse.empty({
175 status: 302,
176 headers: { location: link.url },
177 });
178 }
179
180 if (request.method === "GET" && segments[0] === "links" && segments[1]) {
181 const link = yield* readLink(segments[1]);
182 if (link === undefined) {
183 return yield* HttpServerResponse.json({ error: "unknown code" }, { status: 404 });
184 }
185 return yield* HttpServerResponse.json({ code: segments[1], ...link });
186 }
187
188 if (request.method === "DELETE" && segments[0] === "links" && segments[1]) {
189 const auth = yield* authorize(request);
190 if (auth !== "ok") {
191 return yield* HttpServerResponse.json({ error: "invalid api key" }, { status: 401 });
192 }
193 // Deleting a missing document succeeds.
194 yield* db.delete(`links/${segments[1]}`).pipe(Effect.orDie);
195 return HttpServerResponse.empty({ status: 204 });
196 }
197
198 return yield* HttpServerResponse.json({ error: "not found" }, { status: 404 });
199 }),
200 };
201 }).pipe(Effect.provide([GCP.Firestore.ReadWriteDatabaseHttp, GCP.SecretManager.ReadSecretHttp])),
202 ) {}