Skip to content

Commit

Permalink
Update cors
Browse files Browse the repository at this point in the history
  • Loading branch information
ragokan committed Sep 5, 2024
1 parent 3e158a7 commit 854bf02
Showing 1 changed file with 35 additions and 8 deletions.
43 changes: 35 additions & 8 deletions packages/server/src/handlers/cors.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { __BuiltRoute } from "src/router/types.ts";
import { matchAll } from "../matchers/constants.ts";
import { createHandler } from "./index.ts";
import { __BunicornContext } from "src/context/base.ts";

export interface CorsHandlerArgs {
origins?: string[];
allowCredentials?: boolean;
allowedHeaders?: string[];
}

export default function corsHandler(args: CorsHandlerArgs = {}) {
const { origins, allowCredentials } = args;
const { origins, allowCredentials, allowedHeaders } = args;
const originRegexes = origins?.map(origin => new RegExp(origin));

return createHandler(app => {
Expand All @@ -18,7 +21,11 @@ export default function corsHandler(args: CorsHandlerArgs = {}) {
regexp: new RegExp(`^${matchAll}`),
async handler(ctx) {
if (!originRegexes) {
return getSuccessResponse({ allowCredentials });
return getSuccessResponse({
allowCredentials,
allowedHeaders,
request: ctx.request
});
}
const origin = ctx.request.headers.get("Origin");
if (!origin) {
Expand All @@ -28,23 +35,43 @@ export default function corsHandler(args: CorsHandlerArgs = {}) {
if (!match) {
return getFailureResponse();
}
return getSuccessResponse({ origins: [origin], allowCredentials });
return getSuccessResponse({
allowCredentials,
allowedHeaders,
request: ctx.request
});
}
} satisfies __BuiltRoute);

app.addMiddleware(ctx => {
const origin = ctx.request.headers.get("Origin");
if (origin) {
ctx.setHeader("Access-Control-Allow-Origin", origin);
}
if (allowCredentials) {
ctx.setHeader("Access-Control-Allow-Credentials", "true");
}
});
});
}

function getSuccessResponse({
origins,
allowCredentials
allowCredentials,
allowedHeaders,
request
}: {
origins?: string[];
allowCredentials?: boolean;
allowedHeaders?: string[];
request: Request;
}) {
const headers: HeadersInit = {
"Access-Control-Allow-Origin": origins ? origins.join(", ") : "*",
"Access-Control-Allow-Origin": request.headers.get("Origin") ?? "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
"Access-Control-Allow-Headers":
allowedHeaders?.join(", ") ??
request.headers.get("Access-Control-Request-Headers") ??
"*",
Vary: "*"
};
if (allowCredentials) {
headers["Access-Control-Allow-Credentials"] = "true";
Expand Down

0 comments on commit 854bf02

Please sign in to comment.