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

main
ts 144 lines 5.86 KB
Raw
1 import {
2 GetObjectCommand,
3 HeadObjectCommand,
4 PutObjectCommand,
5 S3Client,
6 } from "@aws-sdk/client-s3";
7 import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
8 import { neon } from "@neondatabase/serverless";
9 import { makeAuthenticate } from "./authenticate.ts";
10 import { corsHeaders, objectKey, parseUpload, UUID } from "./policy.ts";
11
12 const sql = neon(process.env.DATABASE_URL!);
13 const bucket = process.env.UPLOAD_BUCKET!;
14 const storage = new S3Client({
15 endpoint: process.env.AWS_ENDPOINT_URL_S3!,
16 region: process.env.AWS_REGION!,
17 forcePathStyle: true,
18 credentials: {
19 accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
20 secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
21 },
22 });
23 const authenticate = makeAuthenticate(process.env.AUTH_URL!, process.env.AUTH_JWKS_URL!);
24
25 async function processUpload(request: Request) {
26 if (request.method !== "POST") return new Response(null, { status: 405 });
27 const invocation = request.headers.get("x-neon-trigger-invocation-id");
28 if (!invocation) return new Response("Missing Neon trigger attestation", { status: 403 });
29 const event = await request.json().catch(() => undefined);
30 if (
31 event?.version !== 1 ||
32 event?.trigger?.type !== "storage_object_created" ||
33 event?.trigger?.name !== (process.env.TRIGGER_NAME ?? "ProcessUploads") ||
34 event?.data?.bucket_name !== bucket ||
35 typeof event?.data?.object_key !== "string" ||
36 !event.data.object_key.startsWith("incoming/")
37 ) {
38 return new Response("Invalid object event", { status: 400 });
39 }
40 if (event.invocation_id !== invocation)
41 return new Response("Invocation mismatch", { status: 403 });
42 // Neon strips caller-supplied X-Neon-* headers at its edge. This is not a local-server trust boundary.
43 const object = await storage.send(
44 new HeadObjectCommand({ Bucket: bucket, Key: event.data.object_key }),
45 );
46 const bytes = object.ContentLength ?? 0;
47 await sql`
48 WITH delivery AS (
49 INSERT INTO upload_events (invocation_id, object_key)
50 VALUES (${invocation}, ${event.data.object_key})
51 ON CONFLICT DO NOTHING RETURNING invocation_id
52 )
53 UPDATE uploads SET actual_bytes = ${bytes}, processed_at = now(),
54 status = CASE WHEN expected_bytes = ${bytes} AND content_type = ${object.ContentType ?? ""}
55 THEN 'ready' ELSE 'rejected' END
56 WHERE object_key = ${event.data.object_key} AND EXISTS (SELECT 1 FROM delivery)
57 `;
58 return new Response(null, { status: 204 });
59 }
60
61 export default {
62 async fetch(request: Request) {
63 const path = new URL(request.url).pathname;
64 const headers = corsHeaders(request.headers.get("origin"), process.env.APP_ORIGIN);
65 try {
66 if (path === "/jobs/upload") return await processUpload(request);
67 if (!headers) return new Response("Untrusted origin", { status: 403 });
68 const respond = (value: unknown, status = 200) => Response.json(value, { status, headers });
69 if (request.method === "OPTIONS") return new Response(null, { status: 204, headers });
70 if (path === "/health") return respond({ ok: true, runtime: "native" });
71 const owner = await authenticate(request.headers.get("authorization"));
72 if (!owner)
73 return respond(
74 {
75 error: "Sign in again: your token is missing, invalid, or expired.",
76 },
77 401,
78 );
79 if (path === "/api/me" && request.method === "GET") return respond({ userId: owner });
80 if (path === "/api/settings" && request.method === "GET") {
81 const settings = await storage.send(
82 new GetObjectCommand({ Bucket: bucket, Key: "config/settings.json" }),
83 );
84 return respond(JSON.parse((await settings.Body?.transformToString()) ?? "null"));
85 }
86 if (path === "/api/uploads" && request.method === "GET") {
87 return respond(
88 await sql`
89 SELECT id, filename, object_key, content_type, expected_bytes, actual_bytes, status, created_at
90 FROM uploads WHERE owner_id = ${owner} ORDER BY created_at DESC LIMIT 100
91 `,
92 );
93 }
94 if (path === "/api/uploads" && request.method === "POST") {
95 const input = parseUpload(await request.json().catch(() => undefined));
96 if (!input)
97 return respond(
98 {
99 error: "Choose a nonempty file up to 10 MiB with a valid content type.",
100 },
101 400,
102 );
103 const id = crypto.randomUUID();
104 const key = objectKey(owner, id);
105 const url = await getSignedUrl(
106 storage,
107 new PutObjectCommand({
108 Bucket: bucket,
109 Key: key,
110 ContentType: input.contentType,
111 }),
112 { expiresIn: 120 },
113 );
114 await sql`
115 INSERT INTO uploads (id, owner_id, object_key, filename, content_type, expected_bytes)
116 VALUES (${id}, ${owner}, ${key}, ${input.filename}, ${input.contentType}, ${input.size})
117 `;
118 return respond({ id, url, contentType: input.contentType }, 201);
119 }
120 const match = /^\/api\/uploads\/([^/]+)\/download$/.exec(path);
121 if (match && request.method === "GET") {
122 if (!UUID.test(match[1]!)) return respond({ error: "Not found" }, 404);
123 const [row] =
124 await sql`SELECT * FROM uploads WHERE id = ${match[1]!} AND owner_id = ${owner}`;
125 if (!row) return respond({ error: "Not found" }, 404);
126 if (row.status !== "ready")
127 return respond({ error: "This upload is not ready to download." }, 409);
128 const url = await getSignedUrl(
129 storage,
130 new GetObjectCommand({ Bucket: bucket, Key: row.object_key }),
131 { expiresIn: 60 },
132 );
133 return respond({ url });
134 }
135 return respond({ error: "Not found" }, 404);
136 } catch {
137 console.error("Upload API request failed");
138 return new Response("Upload service unavailable. Retry the request.", {
139 status: 500,
140 headers,
141 });
142 }
143 },
144 };