300 lines
10 KiB
TypeScript
300 lines
10 KiB
TypeScript
import { getEnvVariableDefinition, validateEnv } from "./index.js";
|
|
import { getDomainRoutingConfig } from "./routing.js";
|
|
import type { EnvRecord, RequiredWebConfigOptions, WebConfig, WebConfigDiagnostic, WebConfigErrorDetails, WebConfigOptions, WebConfigResult } from "./types.js";
|
|
|
|
const DEFAULT_APP_NAME = "ToolController";
|
|
const DEFAULT_NODE_ENV = "development";
|
|
const DEFAULT_LISTEN_HOST = "0.0.0.0";
|
|
const DEFAULT_LISTEN_PORT = 3000;
|
|
const MIN_PORT = 1;
|
|
const MAX_PORT = 65535;
|
|
const MIN_MAGIC_LINK_TOKEN_TTL_MINUTES = 1;
|
|
|
|
export class WebConfigError extends Error {
|
|
readonly diagnostics: WebConfigDiagnostic[];
|
|
|
|
constructor(diagnostics: readonly WebConfigDiagnostic[]) {
|
|
super(formatWebConfigErrorMessage(diagnostics));
|
|
this.name = "WebConfigError";
|
|
this.diagnostics = diagnostics.map(redactDiagnostic);
|
|
}
|
|
|
|
get details(): WebConfigErrorDetails {
|
|
return {
|
|
diagnostics: this.diagnostics,
|
|
};
|
|
}
|
|
}
|
|
|
|
export function loadRequiredWebConfig(env: EnvRecord = process.env, options: RequiredWebConfigOptions = {}): WebConfig {
|
|
const result = loadWebConfig(env, options);
|
|
if (result.ok) {
|
|
return result.config;
|
|
}
|
|
|
|
throw new WebConfigError(result.diagnostics);
|
|
}
|
|
|
|
export function loadWebConfig(env: EnvRecord = process.env, options: WebConfigOptions = {}): WebConfigResult {
|
|
const nodeEnv = options.nodeEnv ?? env.NODE_ENV ?? DEFAULT_NODE_ENV;
|
|
const routing = getDomainRoutingConfig({ ...env, NODE_ENV: nodeEnv });
|
|
const portResult = normalizeListenPort(env.PORT);
|
|
const magicLinkResult = normalizeMagicLinkConfig(env);
|
|
const diagnostics: WebConfigDiagnostic[] = [
|
|
...toDiagnostics(
|
|
validateEnv(env, {
|
|
target: "web",
|
|
nodeEnv,
|
|
includeOptionalProviders: options.includeOptionalProviders,
|
|
extraRequired: options.extraRequired,
|
|
}).missing
|
|
),
|
|
];
|
|
|
|
if (portResult.diagnostic) {
|
|
diagnostics.push(portResult.diagnostic);
|
|
}
|
|
if (magicLinkResult.diagnostic) {
|
|
diagnostics.push(magicLinkResult.diagnostic);
|
|
}
|
|
diagnostics.push(...validateSecretStrength(env, nodeEnv));
|
|
|
|
const config: WebConfig = {
|
|
appName: env.APP_NAME?.trim() || DEFAULT_APP_NAME,
|
|
nodeEnv,
|
|
sessionSecret: present(env.SESSION_SECRET),
|
|
listen: {
|
|
host: env.HOST?.trim() || DEFAULT_LISTEN_HOST,
|
|
port: portResult.port,
|
|
},
|
|
routing,
|
|
webhooksUrl: present(env.WEBHOOKS_URL),
|
|
stripe: {
|
|
secretKey: present(env.STRIPE_SK),
|
|
webhookSigningSecret: present(env.STRIPE_WEBHOOK_SIGNING_SECRET),
|
|
},
|
|
crisp: {
|
|
chatWebsiteId: present(env.CRISP_CHAT_WEBSITE_ID),
|
|
},
|
|
captcha: {
|
|
instanceUrl: present(env.MCAPTCHA_INSTANCE_URL),
|
|
loginSiteKey: present(env.MCAPTCHA_SITEKEY_LOGIN),
|
|
},
|
|
analytics: {
|
|
// EU-Sterilisation (R-P1a): Google-Analytics-Einbindung entfernt; nur First-Party-Analytics-Token bleibt.
|
|
token: present(env.ANALYTICS_TOKEN),
|
|
},
|
|
novu: {
|
|
apiKey: present(env.NOTIFICATIONS_NOVU_API_KEY),
|
|
},
|
|
mailjet: {
|
|
apiKey: present(env.MAILJET_API_KEY),
|
|
secretKey: present(env.MAILJET_SECRET_KEY),
|
|
fromEmail: present(env.MAILJET_FROM_EMAIL),
|
|
fromName: present(env.MAILJET_FROM_NAME),
|
|
},
|
|
ipProviders: {
|
|
ipstackApiKey: present(env.IPSTACK_API_KEY),
|
|
ipapiIsApiKey: present(env.IPAPIIS_API_KEY),
|
|
},
|
|
ipGeo: {
|
|
hashPepper: present(env.IP_HASH_PEPPER),
|
|
dbPath: present(env.GEOIP_DB_PATH),
|
|
},
|
|
portalServer: {
|
|
url: present(env.PORTAL_SERVER_URL),
|
|
flyToken: present(env.PORTAL_SERVER_FLY_TOKEN),
|
|
},
|
|
magicLink: magicLinkResult.config,
|
|
storage: {
|
|
provider: normalizeStorageProvider(env.STORAGE_PROVIDER),
|
|
fallbackProvider: normalizeStorageFallbackProvider(env.STORAGE_FALLBACK_PROVIDER),
|
|
endpoint: present(env.STORAGE_ENDPOINT),
|
|
region: present(env.STORAGE_REGION),
|
|
bucket: present(env.STORAGE_BUCKET),
|
|
accessKeyId: present(env.STORAGE_ACCESS_KEY_ID),
|
|
secretAccessKey: present(env.STORAGE_SECRET_ACCESS_KEY),
|
|
sessionToken: present(env.STORAGE_SESSION_TOKEN),
|
|
publicBaseUrl: present(env.STORAGE_PUBLIC_BASE_URL),
|
|
forcePathStyle: present(env.STORAGE_FORCE_PATH_STYLE),
|
|
localRoot: present(env.STORAGE_LOCAL_ROOT),
|
|
localPublicBaseUrl: present(env.STORAGE_LOCAL_PUBLIC_BASE_URL),
|
|
},
|
|
cryptoSecret: present(env.CRYPTO_SECRET),
|
|
apiAccessToken: present(env.API_ACCESS_TOKEN),
|
|
jwtSecret: present(env.JWT_SECRET),
|
|
demoUser: nodeEnv === "development" ? present(env.DEMO_USER) : undefined,
|
|
supportEmail: present(env.SUPPORT_EMAIL),
|
|
companyName: present(env.COMPANY_NAME),
|
|
companyAddress: present(env.COMPANY_ADDRESS),
|
|
contactFormspreeEndpoint: present(env.INTEGRATIONS_CONTACT_FORMSPREE),
|
|
};
|
|
|
|
return {
|
|
ok: diagnostics.length === 0,
|
|
config,
|
|
diagnostics,
|
|
};
|
|
}
|
|
|
|
function normalizeStorageProvider(value: string | undefined): "s3" | "local" | undefined {
|
|
const normalized = value?.trim().toLowerCase();
|
|
if (normalized === "s3" || normalized === "local") {
|
|
return normalized;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function normalizeStorageFallbackProvider(value: string | undefined): "s3" | "local" | undefined {
|
|
const normalized = value?.trim().toLowerCase();
|
|
if (normalized === "s3" || normalized === "local") {
|
|
return normalized;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function normalizeListenPort(value: string | undefined): { port: number; diagnostic?: WebConfigDiagnostic } {
|
|
const trimmed = value?.trim();
|
|
if (!trimmed) {
|
|
return { port: DEFAULT_LISTEN_PORT };
|
|
}
|
|
|
|
const parsed = Number(trimmed);
|
|
if (!Number.isInteger(parsed) || parsed < MIN_PORT || parsed > MAX_PORT) {
|
|
return {
|
|
port: DEFAULT_LISTEN_PORT,
|
|
diagnostic: {
|
|
code: "invalid-port",
|
|
name: "PORT",
|
|
classification: getEnvVariableDefinition("PORT")?.classification,
|
|
message: "PORT must be an integer between 1 and 65535. Falling back to 3000.",
|
|
},
|
|
};
|
|
}
|
|
|
|
return { port: parsed };
|
|
}
|
|
|
|
function normalizeMagicLinkConfig(env: EnvRecord): { config: WebConfig["magicLink"]; diagnostic?: WebConfigDiagnostic } {
|
|
const enabledResult = normalizeMagicLinkEnabled(env.AUTH_MAGIC_LINK_ENABLED);
|
|
const ttlResult = normalizeMagicLinkTokenTtlMinutes(env.AUTH_MAGIC_LINK_TOKEN_TTL_MINUTES);
|
|
const enabled = enabledResult.enabled && !ttlResult.diagnostic;
|
|
|
|
return {
|
|
config: {
|
|
enabled,
|
|
tokenTtlMinutes: enabled ? ttlResult.tokenTtlMinutes : undefined,
|
|
},
|
|
diagnostic: enabledResult.diagnostic ?? ttlResult.diagnostic,
|
|
};
|
|
}
|
|
|
|
function normalizeMagicLinkEnabled(value: string | undefined): { enabled: boolean; diagnostic?: WebConfigDiagnostic } {
|
|
const trimmed = value?.trim().toLowerCase();
|
|
if (!trimmed) {
|
|
return { enabled: false };
|
|
}
|
|
if (["1", "true", "yes", "on"].includes(trimmed)) {
|
|
return { enabled: true };
|
|
}
|
|
if (["0", "false", "no", "off"].includes(trimmed)) {
|
|
return { enabled: false };
|
|
}
|
|
|
|
return {
|
|
enabled: false,
|
|
diagnostic: {
|
|
code: "invalid-boolean",
|
|
name: "AUTH_MAGIC_LINK_ENABLED",
|
|
classification: getEnvVariableDefinition("AUTH_MAGIC_LINK_ENABLED")?.classification,
|
|
message: "AUTH_MAGIC_LINK_ENABLED must be a boolean-like value. Magic-Link auth remains disabled.",
|
|
},
|
|
};
|
|
}
|
|
|
|
function normalizeMagicLinkTokenTtlMinutes(value: string | undefined): { tokenTtlMinutes?: number; diagnostic?: WebConfigDiagnostic } {
|
|
const trimmed = value?.trim();
|
|
if (!trimmed) {
|
|
return {};
|
|
}
|
|
|
|
const parsed = Number(trimmed);
|
|
if (!Number.isInteger(parsed) || parsed < MIN_MAGIC_LINK_TOKEN_TTL_MINUTES) {
|
|
return {
|
|
diagnostic: {
|
|
code: "invalid-duration",
|
|
name: "AUTH_MAGIC_LINK_TOKEN_TTL_MINUTES",
|
|
classification: getEnvVariableDefinition("AUTH_MAGIC_LINK_TOKEN_TTL_MINUTES")?.classification,
|
|
message: "AUTH_MAGIC_LINK_TOKEN_TTL_MINUTES must be a positive integer. Magic-Link auth remains disabled.",
|
|
},
|
|
};
|
|
}
|
|
|
|
return { tokenTtlMinutes: parsed };
|
|
}
|
|
|
|
const MIN_SECRET_LENGTH = 32;
|
|
const STRENGTH_CHECKED_SECRETS = ["SESSION_SECRET", "CRYPTO_SECRET", "JWT_SECRET", "API_ACCESS_TOKEN"] as const;
|
|
|
|
// Production-only secret hardening. Missing required secrets are already
|
|
// reported by validateEnv; here we additionally fail closed when a secret is
|
|
// PRESENT but too weak (< 32 chars) or when SESSION_SECRET and CRYPTO_SECRET are
|
|
// reused for both purposes. Non-production envs (placeholders in .env.test etc.)
|
|
// are intentionally exempt.
|
|
function validateSecretStrength(env: EnvRecord, nodeEnv: string): WebConfigDiagnostic[] {
|
|
if (nodeEnv !== "production") {
|
|
return [];
|
|
}
|
|
const diagnostics: WebConfigDiagnostic[] = [];
|
|
for (const name of STRENGTH_CHECKED_SECRETS) {
|
|
const value = present(env[name]);
|
|
if (value && value.length < MIN_SECRET_LENGTH) {
|
|
diagnostics.push({
|
|
code: "weak-secret",
|
|
name,
|
|
classification: getEnvVariableDefinition(name)?.classification,
|
|
message: `${name} must be at least ${MIN_SECRET_LENGTH} characters in production (generate with \`openssl rand -hex 32\`).`,
|
|
});
|
|
}
|
|
}
|
|
const sessionSecret = present(env.SESSION_SECRET);
|
|
const cryptoSecret = present(env.CRYPTO_SECRET);
|
|
if (sessionSecret && cryptoSecret && sessionSecret === cryptoSecret) {
|
|
diagnostics.push({
|
|
code: "weak-secret",
|
|
name: "CRYPTO_SECRET",
|
|
classification: getEnvVariableDefinition("CRYPTO_SECRET")?.classification,
|
|
message: "CRYPTO_SECRET must not be identical to SESSION_SECRET; use independent random values.",
|
|
});
|
|
}
|
|
return diagnostics;
|
|
}
|
|
|
|
function toDiagnostics(issues: ReturnType<typeof validateEnv>["missing"]): WebConfigDiagnostic[] {
|
|
return issues.map((issue) => ({
|
|
code: "missing-required",
|
|
name: issue.name,
|
|
classification: issue.classification,
|
|
message: issue.message,
|
|
}));
|
|
}
|
|
|
|
function formatWebConfigErrorMessage(diagnostics: readonly WebConfigDiagnostic[]): string {
|
|
const summary = diagnostics.map((diagnostic) => `${diagnostic.name}:${diagnostic.code}`).join(", ");
|
|
return `Invalid web configuration (${summary}).`;
|
|
}
|
|
|
|
function redactDiagnostic(diagnostic: WebConfigDiagnostic): WebConfigDiagnostic {
|
|
return {
|
|
code: diagnostic.code,
|
|
name: diagnostic.name,
|
|
classification: diagnostic.classification,
|
|
message: diagnostic.message,
|
|
};
|
|
}
|
|
|
|
function present(value: string | undefined): string | undefined {
|
|
const trimmed = value?.trim();
|
|
return trimmed ? trimmed : undefined;
|
|
}
|