diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 136018b..3609b62 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -1,5 +1,5 @@ import { Elysia } from "elysia"; -import { cors } from "@elysiajs/cors"; + import { ingest } from "./routes/pings"; import { monitors } from "./routes/monitors"; import { account } from "./routes/auth"; @@ -7,14 +7,6 @@ import { internal } from "./routes/internal"; import { migrate } from "./db"; await migrate(); -const CORS_ORIGIN = process.env.CORS_ORIGINS?.split(",") ?? ["https://pingql.com"]; - -const CORS_HEADERS = { - "access-control-allow-credentials": "true", - "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS", - "access-control-allow-headers": "Content-Type, Authorization", -}; - const SECURITY_HEADERS = { "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", @@ -24,25 +16,22 @@ const SECURITY_HEADERS = { }; const app = new Elysia() - // Security headers on all responses - .onAfterHandle(({ set }) => { + .onAfterHandle(({ set, request }) => { Object.assign(set.headers, SECURITY_HEADERS); + const origin = request.headers.get("origin") || "*"; + set.headers["access-control-allow-origin"] = origin; + set.headers["access-control-allow-credentials"] = "true"; + set.headers["access-control-allow-methods"] = "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"; + set.headers["access-control-allow-headers"] = "Content-Type, Authorization"; }) - .use(cors({ - origin: CORS_ORIGIN, - credentials: true, - allowedHeaders: ["Content-Type", "Authorization"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - preflight: true, - })) - // Explicit OPTIONS handler for cross-origin preflight - .options("/*", ({ request }) => { - const origin = request.headers.get("origin") ?? ""; - const allowed = CORS_ORIGIN.includes(origin) ? origin : CORS_ORIGIN[0]; - return new Response(null, { - status: 204, - headers: { ...CORS_HEADERS, "access-control-allow-origin": allowed }, - }); + .options("/*", ({ set, request }) => { + const origin = request.headers.get("origin") || "*"; + set.headers["access-control-allow-origin"] = origin; + set.headers["access-control-allow-credentials"] = "true"; + set.headers["access-control-allow-methods"] = "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"; + set.headers["access-control-allow-headers"] = "Content-Type, Authorization"; + set.status = 204; + return null; }) .get("/", () => ({ name: "PingQL API",