refactor(config): enforce runtime auth secret policy

This commit is contained in:
2026-03-30 23:40:00 +02:00
parent 7bcc831b5c
commit a7362f17bd
8 changed files with 181 additions and 8 deletions
+68
View File
@@ -0,0 +1,68 @@
const DISALLOWED_PRODUCTION_SECRETS = new Set([
"dev-secret-change-in-production",
"changeme",
"change-me",
"default",
"secret",
]);
type RuntimeEnv = Partial<Record<string, string | undefined>>;
function readEnvValue(env: RuntimeEnv, ...names: string[]): string | null {
for (const name of names) {
const value = env[name]?.trim();
if (value) {
return value;
}
}
return null;
}
function isProductionLike(env: RuntimeEnv): boolean {
return (env.NODE_ENV ?? "").trim() === "production";
}
function isLocalhost(hostname: string): boolean {
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
}
export function getRuntimeEnvViolations(env: RuntimeEnv = process.env): string[] {
if (!isProductionLike(env)) {
return [];
}
const violations: string[] = [];
const authSecret = readEnvValue(env, "AUTH_SECRET", "NEXTAUTH_SECRET");
const authUrl = readEnvValue(env, "AUTH_URL", "NEXTAUTH_URL");
if (!authSecret) {
violations.push("AUTH_SECRET or NEXTAUTH_SECRET must be set in production.");
} else if (DISALLOWED_PRODUCTION_SECRETS.has(authSecret)) {
violations.push("AUTH_SECRET or NEXTAUTH_SECRET must not use a known development placeholder in production.");
}
if (!authUrl) {
violations.push("AUTH_URL or NEXTAUTH_URL must be set in production.");
} else {
try {
const parsed = new URL(authUrl);
if (parsed.protocol !== "https:" && !isLocalhost(parsed.hostname)) {
violations.push("AUTH_URL or NEXTAUTH_URL must use https in production.");
}
} catch {
violations.push("AUTH_URL or NEXTAUTH_URL must be a valid URL in production.");
}
}
return violations;
}
export function assertSecureRuntimeEnv(env: RuntimeEnv = process.env): void {
const violations = getRuntimeEnvViolations(env);
if (violations.length === 0) {
return;
}
throw new Error(`Invalid production runtime configuration: ${violations.join(" ")}`);
}