Skip to content

Commit a6726ef

Browse files
committed
fixing CORS
1 parent 2b32055 commit a6726ef

2 files changed

Lines changed: 40 additions & 3 deletions

File tree

api/.env.example

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
PORT=8787
22

33
# Comma-separated origins allowed to call this API from the browser.
4-
ALLOWED_ORIGINS=https://ziongospelministry.org,http://127.0.0.1:4177,http://localhost:4177
4+
ALLOWED_ORIGINS=https://ziongospelministry.org,https://www.ziongospelministry.org,http://127.0.0.1:4177,http://localhost:4177
55

66
# SMTP settings for outgoing mail.
77
SMTP_HOST=smtp.gmail.com

api/server.js

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const app = express();
77
const port = Number(process.env.PORT || 8787);
88
const defaultAllowedOrigins = [
99
"https://ziongospelministry.org",
10+
"https://www.ziongospelministry.org",
1011
"http://127.0.0.1:4177",
1112
"http://localhost:4177"
1213
];
@@ -18,13 +19,49 @@ const allowedOrigins = String(process.env.ALLOWED_ORIGINS || "")
1819

1920
const origins = allowedOrigins.length ? allowedOrigins : defaultAllowedOrigins;
2021

22+
function normalizeOrigin(value) {
23+
try {
24+
const url = new URL(value);
25+
return `${url.protocol}//${url.host}`.toLowerCase();
26+
} catch (_err) {
27+
return "";
28+
}
29+
}
30+
31+
function addWwwVariant(origin) {
32+
try {
33+
const url = new URL(origin);
34+
if (url.hostname.startsWith("www.")) return origin;
35+
if (url.hostname === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(url.hostname)) return origin;
36+
url.hostname = `www.${url.hostname}`;
37+
return `${url.protocol}//${url.host}`.toLowerCase();
38+
} catch (_err) {
39+
return origin;
40+
}
41+
}
42+
43+
const normalizedOriginSet = new Set();
44+
origins.forEach((origin) => {
45+
const normalized = normalizeOrigin(origin);
46+
if (!normalized) return;
47+
normalizedOriginSet.add(normalized);
48+
normalizedOriginSet.add(addWwwVariant(normalized));
49+
});
50+
2151
app.use(cors({
2252
origin(origin, callback) {
23-
if (!origin || origins.includes(origin)) {
53+
if (!origin) {
2454
callback(null, true);
2555
return;
2656
}
27-
callback(new Error("Origin not allowed"));
57+
58+
const normalizedRequestOrigin = normalizeOrigin(origin);
59+
if (normalizedOriginSet.has(normalizedRequestOrigin)) {
60+
callback(null, true);
61+
return;
62+
}
63+
64+
callback(new Error(`Origin not allowed: ${origin}`));
2865
}
2966
}));
3067

0 commit comments

Comments
 (0)