75 lines
2.2 KiB
JavaScript
75 lines
2.2 KiB
JavaScript
|
|
const DEFAULT_DEV_JWT_SECRET = "dev-secret-change-me";
|
||
|
|
const DEFAULT_DEV_ADMIN_PASSWORD = "changeme";
|
||
|
|
|
||
|
|
let warnedAboutJwtFallback = false;
|
||
|
|
let warnedAboutAdminFallback = false;
|
||
|
|
|
||
|
|
function isProductionLike() {
|
||
|
|
return String(process.env.NODE_ENV || "").toLowerCase() === "production";
|
||
|
|
}
|
||
|
|
|
||
|
|
function getJwtSecret() {
|
||
|
|
const configuredSecret = process.env.JWT_SECRET?.trim();
|
||
|
|
|
||
|
|
if (configuredSecret) {
|
||
|
|
if (isProductionLike() && configuredSecret === DEFAULT_DEV_JWT_SECRET) {
|
||
|
|
throw new Error("JWT_SECRET must not use the development fallback value in production");
|
||
|
|
}
|
||
|
|
if (isProductionLike() && configuredSecret.length < 32) {
|
||
|
|
throw new Error("JWT_SECRET must be at least 32 characters in production");
|
||
|
|
}
|
||
|
|
return configuredSecret;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (isProductionLike()) {
|
||
|
|
throw new Error("JWT_SECRET environment variable is required in production");
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!warnedAboutJwtFallback) {
|
||
|
|
console.warn("[security] JWT_SECRET not set; using development fallback secret");
|
||
|
|
warnedAboutJwtFallback = true;
|
||
|
|
}
|
||
|
|
|
||
|
|
return DEFAULT_DEV_JWT_SECRET;
|
||
|
|
}
|
||
|
|
|
||
|
|
function getDefaultAdminPassword(explicitPassword) {
|
||
|
|
const providedPassword = typeof explicitPassword === "string" ? explicitPassword.trim() : "";
|
||
|
|
const configuredPassword = providedPassword || process.env.DEFAULT_ADMIN_PASSWORD?.trim() || "";
|
||
|
|
|
||
|
|
if (configuredPassword) {
|
||
|
|
if (isProductionLike() && configuredPassword === DEFAULT_DEV_ADMIN_PASSWORD) {
|
||
|
|
throw new Error(
|
||
|
|
"DEFAULT_ADMIN_PASSWORD must not use the development fallback value in production",
|
||
|
|
);
|
||
|
|
}
|
||
|
|
return configuredPassword;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (isProductionLike()) {
|
||
|
|
throw new Error(
|
||
|
|
"DEFAULT_ADMIN_PASSWORD environment variable is required in production when bootstrapping the default admin account",
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!warnedAboutAdminFallback) {
|
||
|
|
console.warn("[security] DEFAULT_ADMIN_PASSWORD not set; using development fallback password");
|
||
|
|
warnedAboutAdminFallback = true;
|
||
|
|
}
|
||
|
|
|
||
|
|
return DEFAULT_DEV_ADMIN_PASSWORD;
|
||
|
|
}
|
||
|
|
|
||
|
|
function assertRuntimeSecurityConfig() {
|
||
|
|
getJwtSecret();
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = {
|
||
|
|
DEFAULT_DEV_ADMIN_PASSWORD,
|
||
|
|
DEFAULT_DEV_JWT_SECRET,
|
||
|
|
assertRuntimeSecurityConfig,
|
||
|
|
getDefaultAdminPassword,
|
||
|
|
getJwtSecret,
|
||
|
|
isProductionLike,
|
||
|
|
};
|