diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 8dde7eb..61c372e 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -15,22 +15,7 @@ const SECURITY_HEADERS = { "Referrer-Policy": "strict-origin-when-cross-origin", }; -const CORS_HEADERS: Record = { - "access-control-allow-credentials": "true", - "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS", - "access-control-allow-headers": "Content-Type, Authorization", -}; - -const app = new Elysia() - .onRequest(({ request, set }) => { - const origin = request.headers.get("origin") || "*"; - set.headers["access-control-allow-origin"] = origin; - Object.assign(set.headers, CORS_HEADERS, SECURITY_HEADERS); - if (request.method === "OPTIONS") { - set.status = 204; - return new Response(null, { status: 204, headers: { ...CORS_HEADERS, ...SECURITY_HEADERS, "access-control-allow-origin": origin } }); - } - }) +const elysia = new Elysia() .get("/", () => ({ name: "PingQL API", version: "1", @@ -39,7 +24,31 @@ const app = new Elysia() .use(account) .use(monitors) .use(ingest) - .use(internal) - .listen(3001); + .use(internal); -console.log(`PingQL API running at http://localhost:${app.server?.port}`); +// Wrap Elysia with Bun.serve to guarantee CORS + security headers on every response +const server = Bun.serve({ + port: 3001, + async fetch(req) { + const origin = req.headers.get("origin") || "*"; + const corsHeaders: Record = { + "access-control-allow-origin": origin, + "access-control-allow-credentials": "true", + "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS", + "access-control-allow-headers": "Content-Type, Authorization", + ...SECURITY_HEADERS, + }; + + if (req.method === "OPTIONS") { + return new Response(null, { status: 204, headers: corsHeaders }); + } + + const res = await elysia.handle(req); + for (const [k, v] of Object.entries(corsHeaders)) { + res.headers.set(k, v); + } + return res; + }, +}); + +console.log(`PingQL API running at http://localhost:${server.port}`);