Skip to content

Commit

Permalink
fix: return proper response on CORS error
Browse files Browse the repository at this point in the history
  • Loading branch information
arcoraven committed Dec 4, 2024
1 parent a52a717 commit a083850
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
5 changes: 1 addition & 4 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import fastify, { type FastifyInstance } from "fastify";
import * as fs from "node:fs";
import path from "node:path";
import { URL } from "node:url";
import { getConfig } from "../utils/cache/getConfig";
import { clearCacheCron } from "../utils/cron/clearCacheCron";
import { env } from "../utils/env";
import { logger } from "../utils/logger";
Expand Down Expand Up @@ -72,13 +71,11 @@ export const initServer = async () => {
...(env.ENABLE_HTTPS ? httpsObject : {}),
}).withTypeProvider<TypeBoxTypeProvider>();

const config = await getConfig();

// Configure middleware
withErrorHandler(server);
withRequestLogs(server);
withSecurityHeaders(server);
withCors(server, config);
withCors(server);
withRateLimit(server);
withEnforceEngineMode(server);
withServerUsageReporting(server);
Expand Down
13 changes: 10 additions & 3 deletions src/server/middleware/cors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { FastifyInstance } from "fastify";
import type { ParsedConfig } from "../../schema/config";
import { getConfig } from "../../utils/cache/getConfig";
import { ADMIN_QUEUES_BASEPATH } from "./adminRoutes";

const STANDARD_METHODS = "GET,POST,DELETE,PUT,PATCH,HEAD,PUT,PATCH,POST,DELETE";
Expand All @@ -9,7 +9,7 @@ const DEFAULT_ALLOWED_HEADERS = [
"ngrok-skip-browser-warning",
];

export function withCors(server: FastifyInstance, config: ParsedConfig) {
export function withCors(server: FastifyInstance) {
server.addHook("onRequest", async (request, reply) => {
const origin = request.headers.origin;

Expand All @@ -29,13 +29,20 @@ export function withCors(server: FastifyInstance, config: ParsedConfig) {
return;
}

const config = await getConfig();
const allowedOrigins = config.accessControlAllowOrigin
.split(",")
.map(sanitizeOrigin);

// Always set `Vary: Origin` to prevent caching issues even on invalid origins.
reply.header("Vary", "Origin");

console.log("[DEBUG] allowedOrigins:", allowedOrigins);
console.log(
"[DEBUG] isAllowedOrigin(origin, allowedOrigins):",
isAllowedOrigin(origin, allowedOrigins),
);

if (isAllowedOrigin(origin, allowedOrigins)) {
// Set CORS headers if valid origin.
reply.header("Access-Control-Allow-Origin", origin);
Expand All @@ -56,7 +63,7 @@ export function withCors(server: FastifyInstance, config: ParsedConfig) {
return;
}
} else {
reply.code(403).send({ error: "Invalid origin" });
// reply.code(403).send({ error: "Invalid origin" });
return;
}
});
Expand Down

0 comments on commit a083850

Please sign in to comment.