41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import cors from "cors";
|
|
import { config } from "../config.js";
|
|
|
|
const PRODUCTION_ORIGINS = [
|
|
"https://performancewest.net",
|
|
"https://www.performancewest.net",
|
|
"https://dev.performancewest.net",
|
|
"http://192.168.7.4:4322",
|
|
];
|
|
|
|
const DEV_ORIGINS = [
|
|
"http://localhost:4322",
|
|
"http://localhost:3001",
|
|
"http://127.0.0.1:4322",
|
|
"http://127.0.0.1:3001",
|
|
];
|
|
|
|
// In dev mode, also allow any origin on common dev ports (LAN access)
|
|
const isDev = config.nodeEnv !== "production";
|
|
|
|
const allowedOrigins =
|
|
config.nodeEnv === "production"
|
|
? PRODUCTION_ORIGINS
|
|
: [...PRODUCTION_ORIGINS, ...DEV_ORIGINS];
|
|
|
|
export const corsMiddleware = cors({
|
|
origin: (origin, cb) => {
|
|
// Allow requests with no origin (server-to-server, curl, etc.)
|
|
if (!origin) { cb(null, true); return; }
|
|
if (allowedOrigins.includes(origin)) { cb(null, true); return; }
|
|
// In dev mode, allow any origin on known dev ports (LAN access from other machines)
|
|
if (isDev && /^http:\/\/[\d.]+:(4322|3001)$/.test(origin)) { cb(null, true); return; }
|
|
if (isDev && /^http:\/\/192\.168\./.test(origin)) { cb(null, true); return; }
|
|
cb(new Error(`Origin ${origin} not allowed by CORS`));
|
|
},
|
|
methods: ["GET", "POST", "PUT", "PATCH", "OPTIONS"],
|
|
allowedHeaders: ["Content-Type", "Authorization"],
|
|
exposedHeaders: ["RateLimit-Limit", "RateLimit-Remaining", "RateLimit-Reset"],
|
|
credentials: true,
|
|
maxAge: 86_400,
|
|
});
|