/home/techb158/cosmic.abdallabala.com/src/security
Edit: /home/techb158/cosmic.abdallabala.com/src/security/securityHeaders.js (2341B)
const crypto = require("crypto");
function getRequestId(req) {
return req.headers["x-request-id"] || crypto.randomBytes(8).toString("hex");
}
function isHttpsRequest(req, config) {
if (req.socket && req.socket.encrypted) return true;
if (config.trustProxy) {
const proto = req.headers["x-forwarded-proto"];
if (proto && String(proto).split(",")[0].trim() === "https") return true;
}
return false;
}
function buildContentSecurityPolicy(config) {
const frameAncestors = config.frameAncestors && config.frameAncestors.length ? config.frameAncestors.join(" ") : "'self'";
return [
"default-src 'self'",
"base-uri 'self'",
"object-src 'none'",
"frame-ancestors " + frameAncestors,
"form-action 'self'",
"img-src 'self' data:",
"style-src 'self' 'unsafe-inline'",
"script-src 'self'",
"connect-src 'self'"
].join("; ");
}
function buildSecurityHeaders(req, config) {
const headers = {
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"X-Frame-Options": "SAMEORIGIN",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
"Cross-Origin-Opener-Policy": "same-origin",
"X-Request-Id": getRequestId(req)
};
if (config.securityHeadersEnabled) {
headers["Content-Security-Policy"] = buildContentSecurityPolicy(config);
}
if (config.hstsEnabled && isHttpsRequest(req, config)) {
headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains";
}
return headers;
}
function buildCorsHeaders(req, config) {
const origin = req.headers.origin;
if (!origin || !config.allowedOrigins || !config.allowedOrigins.length) return {};
if (!config.allowedOrigins.includes(origin)) return {};
return {
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Credentials": "true",
"Vary": "Origin",
"Access-Control-Allow-Headers": "Content-Type, X-Cosmic-User-Id, X-Request-Id",
"Access-Control-Allow-Methods": "GET,POST,PATCH,DELETE,OPTIONS"
};
}
function withCommonHeaders(req, config, headers = {}) {
return Object.assign({}, buildSecurityHeaders(req, config), buildCorsHeaders(req, config), headers);
}
module.exports = {
getRequestId,
isHttpsRequest,
buildContentSecurityPolicy,
buildSecurityHeaders,
buildCorsHeaders,
withCommonHeaders
};