fix cors not handling multi origins

This commit is contained in:
2025-06-03 13:33:25 +00:00
parent e36be5f1f4
commit 610649b08f

View File

@@ -2,7 +2,7 @@ import { HttpError } from "./error.ts"
type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "OPTIONS" | "PATCH" type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "OPTIONS" | "PATCH"
const ALLOWED_ORIGINS = ["http://localhost:5173"] const ALLOWED_ORIGINS = ["http://localhost:5173", "http://127.0.0.1:5173"]
function httpHandler<Route extends string>( function httpHandler<Route extends string>(
handler: (request: Bun.BunRequest<Route>) => Promise<Response>, handler: (request: Bun.BunRequest<Route>) => Promise<Response>,
@@ -23,7 +23,8 @@ function httpHandler<Route extends string>(
response = new Response(undefined, { status: 500 }) response = new Response(undefined, { status: 500 })
} }
} }
for (const origin of ALLOWED_ORIGINS) { const origin = request.headers.get("Origin")
if (origin && ALLOWED_ORIGINS.includes(origin)) {
response.headers.set("Access-Control-Allow-Origin", origin) response.headers.set("Access-Control-Allow-Origin", origin)
} }
response.headers.set("Access-Control-Allow-Credentials", "true") response.headers.set("Access-Control-Allow-Credentials", "true")
@@ -35,16 +36,21 @@ function preflightHandler<Route extends string>({
allowedMethods, allowedMethods,
allowedHeaders, allowedHeaders,
}: { allowedMethods: HttpMethod[]; allowedHeaders: string[] }) { }: { allowedMethods: HttpMethod[]; allowedHeaders: string[] }) {
return async (request: Bun.BunRequest<Route>) => return async (request: Bun.BunRequest<Route>) => {
new Response(undefined, { const origin = request.headers.get("Origin")
const headers: Record<string, string> = {
"Access-Control-Allow-Methods": allowedMethods.join(", "),
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers": allowedHeaders.join(", "),
}
if (origin && ALLOWED_ORIGINS.includes(origin)) {
headers["Access-Control-Allow-Origin"] = origin
}
return new Response(undefined, {
status: 200, status: 200,
headers: { headers,
"Access-Control-Allow-Origin": ALLOWED_ORIGINS.join(", "),
"Access-Control-Allow-Methods": allowedMethods.join(", "),
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers": allowedHeaders.join(", "),
},
}) })
}
} }
export { httpHandler, preflightHandler } export { httpHandler, preflightHandler }