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

main
ts 166 lines 6.67 KB
Raw
1 import * as Neon from "@alchemy.run/neon";
2 import * as SQL from "@alchemy.run/sql/Postgres";
3 import * as Effect from "effect/Effect";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import * as Layer from "effect/Layer";
6 import { makeAuthenticate } from "./authenticate.ts";
7 import {
8 corsHeaders,
9 objectKey,
10 parseUpload,
11 serializeUploadRow,
12 UUID,
13 type UploadRecord,
14 } from "./policy.ts";
15 import { resources } from "./resources.ts";
16
17 export default class Api extends Neon.Function<Api>()(
18 "Api",
19 Effect.gen(function* () {
20 const { branch, auth, appOrigin } = yield* resources;
21 return {
22 branch,
23 main: import.meta.url,
24 env: {
25 AUTH_URL: auth.baseUrl,
26 AUTH_JWKS_URL: auth.jwksUrl,
27 APP_ORIGIN: appOrigin,
28 },
29 };
30 }),
31 Effect.gen(function* () {
32 const { branch, uploads, auth, settings } = yield* resources;
33 const connection = yield* Neon.ConnectAuth(auth);
34 const defaults = yield* Neon.ReadObject(settings);
35 const db = yield* Neon.Connect(branch);
36 const sql = yield* SQL.Postgres({ url: db.connectionString });
37 const files = yield* Neon.ReadWriteBucket(uploads);
38 const env = yield* Neon.FunctionEnvironment;
39 // Configuration only: the remote key set performs I/O lazily during verification.
40 const authenticate = yield* Effect.cached(
41 Effect.gen(function* () {
42 const baseUrl = yield* connection.baseUrl;
43 const jwksUrl = yield* connection.jwksUrl;
44 return yield* Effect.sync(() => makeAuthenticate(baseUrl, jwksUrl));
45 }),
46 );
47
48 yield* Neon.BucketEventSource(
49 uploads,
50 {
51 name: "ProcessUploads",
52 prefix: "incoming/",
53 },
54 Effect.fn(function* (event) {
55 const object = yield* files.head(event.objectKey);
56 if (!object) return yield* Effect.fail(new Error("Uploaded object is not readable yet"));
57 const bytes = object.ContentLength ?? 0;
58 // Record delivery and transition the row atomically; duplicate invocations do no work.
59 yield* sql`
60 WITH delivery AS (
61 INSERT INTO upload_events (invocation_id, object_key)
62 VALUES (${event.invocationId}, ${event.objectKey})
63 ON CONFLICT DO NOTHING RETURNING invocation_id
64 )
65 UPDATE uploads SET actual_bytes = ${bytes}, processed_at = now(),
66 status = CASE WHEN expected_bytes = ${bytes} AND content_type = ${object.ContentType ?? ""}
67 THEN 'ready' ELSE 'rejected' END
68 WHERE object_key = ${event.objectKey} AND EXISTS (SELECT 1 FROM delivery)
69 `;
70 }),
71 );
72
73 return {
74 fetch: Effect.gen(function* () {
75 const request = yield* Neon.FunctionRequest;
76 const headers = corsHeaders(request.headers.get("origin"), env.APP_ORIGIN);
77 if (!headers) return HttpServerResponse.text("Untrusted origin", { status: 403 });
78 const respond = (value: unknown, status = 200) =>
79 HttpServerResponse.json(value, { status, headers });
80 if (request.method === "OPTIONS") return HttpServerResponse.empty({ status: 204, headers });
81 const path = yield* Effect.sync(() => new URL(request.url).pathname);
82 if (path === "/health") return yield* respond({ ok: true, runtime: "effect" });
83 const verify = yield* authenticate;
84 const owner = yield* Effect.tryPromise(() => verify(request.headers.get("authorization")));
85 if (!owner)
86 return yield* respond(
87 {
88 error: "Sign in again: your token is missing, invalid, or expired.",
89 },
90 401,
91 );
92
93 if (path === "/api/settings" && request.method === "GET")
94 return yield* respond(yield* defaults.get());
95 if (path === "/api/me" && request.method === "GET")
96 return yield* respond({ userId: owner });
97 if (path === "/api/uploads" && request.method === "GET") {
98 const rows = yield* sql<UploadRecord>`
99 SELECT id, filename, object_key, content_type, expected_bytes, actual_bytes, status, created_at
100 FROM uploads WHERE owner_id = ${owner} ORDER BY created_at DESC LIMIT 100
101 `;
102 return yield* respond(yield* Effect.sync(() => rows.map(serializeUploadRow)));
103 }
104 if (path === "/api/uploads" && request.method === "POST") {
105 const json = yield* Effect.tryPromise(() => request.json()).pipe(
106 Effect.catch(() => Effect.succeed(undefined)),
107 );
108 const input = parseUpload(json);
109 if (!input)
110 return yield* respond(
111 {
112 error: "Choose a nonempty file up to 10 MiB with a valid content type.",
113 },
114 400,
115 );
116 const id = yield* Effect.sync(() => crypto.randomUUID());
117 const key = objectKey(owner, id);
118 const url = yield* files.presignPut(key, {
119 contentType: input.contentType,
120 expiresIn: 120,
121 });
122 yield* sql`
123 INSERT INTO uploads (id, owner_id, object_key, filename, content_type, expected_bytes)
124 VALUES (${id}, ${owner}, ${key}, ${input.filename}, ${input.contentType}, ${input.size})
125 `;
126 return yield* respond({ id, url, contentType: input.contentType }, 201);
127 }
128 const match = /^\/api\/uploads\/([^/]+)\/download$/.exec(path);
129 if (match && request.method === "GET") {
130 if (!UUID.test(match[1]!)) return yield* respond({ error: "Not found" }, 404);
131 const [row] =
132 yield* sql<UploadRecord>`SELECT * FROM uploads WHERE id = ${match[1]!} AND owner_id = ${owner}`;
133 if (!row) return yield* respond({ error: "Not found" }, 404);
134 if (row.status !== "ready")
135 return yield* respond({ error: "This upload is not ready to download." }, 409);
136 return yield* respond({
137 url: yield* files.presignGet(row.object_key, { expiresIn: 60 }),
138 });
139 }
140 return yield* respond({ error: "Not found" }, 404);
141 }).pipe(
142 Effect.catchCause(() =>
143 Effect.gen(function* () {
144 yield* Effect.logError("Upload API request failed");
145 const request = yield* Neon.FunctionRequest;
146 const headers = corsHeaders(request.headers.get("origin"), env.APP_ORIGIN);
147 return HttpServerResponse.text("Upload service unavailable. Retry the request.", {
148 status: 500,
149 headers,
150 });
151 }),
152 ),
153 ),
154 };
155 }).pipe(
156 Effect.provide(
157 Layer.mergeAll(
158 Neon.ConnectHttp,
159 Neon.ConnectAuthHttp,
160 Neon.ReadObjectHttp,
161 Neon.ReadWriteBucketHttp,
162 Neon.BucketEventSourceHttp,
163 ),
164 ),
165 ),
166 ) {}