743 lines
28 KiB
TypeScript
743 lines
28 KiB
TypeScript
import { EnabledLocalesConfigError, parseEnabledLocales } from "@hivegrid/i18n/locales";
|
|
import { getEnvVariableDefinition, validateEnv } from "./index.js";
|
|
import { getDomainRoutingConfig, normalizeHostForProtocol } from "./routing.js";
|
|
import { normalizeGdprExportSseCKey } from "./gdpr-export-storage.js";
|
|
import type {
|
|
EnvRecord,
|
|
RequiredWebConfigOptions,
|
|
WebConfig,
|
|
WebConfigDiagnostic,
|
|
WebConfigErrorDetails,
|
|
WebConfigOptions,
|
|
WebConfigResult,
|
|
WebRuntimeSurface,
|
|
} from "./types.js";
|
|
|
|
const DEFAULT_APP_NAME = "HiveGrid";
|
|
const DEFAULT_NODE_ENV = "development";
|
|
const DEFAULT_LISTEN_HOST = "0.0.0.0";
|
|
const DEFAULT_LISTEN_PORT = 3000;
|
|
const DEFAULT_LAGO_TIMEOUT_MS = 10_000;
|
|
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000;
|
|
const MIN_PORT = 1;
|
|
const MAX_PORT = 65535;
|
|
const MIN_MAGIC_LINK_TOKEN_TTL_MINUTES = 1;
|
|
const UNKNOWN_REVISION = "unknown";
|
|
const FULL_GIT_SHA_PATTERN = /^[0-9a-f]{40}$/;
|
|
const PORTAL_EXCLUDED_REQUIRED_ENV_NAMES = new Set([
|
|
"SESSION_SECRET",
|
|
"AUDIT_CHAIN_SECRET",
|
|
"WEB_APP_HOST",
|
|
"ADMIN_APP_HOST",
|
|
"API_HOST",
|
|
"CRYPTO_SECRET",
|
|
"ADMIN_CONNECTION_MASTER_KEY",
|
|
"API_ACCESS_TOKEN",
|
|
"JWT_SECRET",
|
|
"WEB_PUSH_VAPID_PUBLIC_KEY",
|
|
]);
|
|
|
|
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 surfaceResult = normalizeRuntimeSurface(env.WEB_RUNTIME_SURFACE, nodeEnv);
|
|
const runtimeSurface = surfaceResult.surface;
|
|
const routing = getDomainRoutingConfig({ ...env, NODE_ENV: nodeEnv });
|
|
const portResult = normalizeListenPort(env.PORT);
|
|
const magicLinkResult = normalizeMagicLinkConfig(env);
|
|
const i18nResult = normalizeEnabledLocales(env.I18N_ENABLED_LOCALES, nodeEnv, env.SENTRY_ENVIRONMENT);
|
|
const validationIssues = validateEnv(env, {
|
|
target: "web",
|
|
nodeEnv,
|
|
includeOptionalProviders: options.includeOptionalProviders,
|
|
extraRequired: options.extraRequired,
|
|
}).missing;
|
|
const diagnostics: WebConfigDiagnostic[] = [
|
|
...toDiagnostics(runtimeSurface === "portal" ? validationIssues.filter((issue) => !PORTAL_EXCLUDED_REQUIRED_ENV_NAMES.has(issue.name)) : validationIssues),
|
|
];
|
|
|
|
if (surfaceResult.diagnostic) {
|
|
diagnostics.push(surfaceResult.diagnostic);
|
|
}
|
|
diagnostics.push(...validateSurfaceBoundary(env, nodeEnv, runtimeSurface));
|
|
diagnostics.push(...validatePortalAuthDependencies(env, nodeEnv, runtimeSurface));
|
|
diagnostics.push(...validateWebRedisDependency(env, nodeEnv));
|
|
|
|
if (portResult.diagnostic) {
|
|
diagnostics.push(portResult.diagnostic);
|
|
}
|
|
if (magicLinkResult.diagnostic) {
|
|
diagnostics.push(magicLinkResult.diagnostic);
|
|
}
|
|
if (i18nResult.diagnostic) {
|
|
diagnostics.push(i18nResult.diagnostic);
|
|
}
|
|
diagnostics.push(...validateReleaseRevision(env.APP_REVISION, nodeEnv));
|
|
diagnostics.push(...validateSecretStrength(env, nodeEnv, runtimeSurface));
|
|
diagnostics.push(...validateGdprExportStorageContract(env, nodeEnv));
|
|
|
|
const config: WebConfig = {
|
|
appName: env.APP_NAME?.trim() || DEFAULT_APP_NAME,
|
|
nodeEnv,
|
|
runtimeSurface,
|
|
releaseRevision: present(env.APP_REVISION) ?? UNKNOWN_REVISION,
|
|
i18n: {
|
|
enabledLocales: i18nResult.enabledLocales,
|
|
},
|
|
sessionSecret: runtimeSurface !== "portal" ? present(env.SESSION_SECRET) : undefined,
|
|
portalSessionSecret: runtimeSurface === "portal" ? present(env.PORTAL_SESSION_SECRET) : undefined,
|
|
listen: {
|
|
host: env.HOST?.trim() || DEFAULT_LISTEN_HOST,
|
|
port: portResult.port,
|
|
},
|
|
routing,
|
|
webhooksUrl: present(env.WEBHOOKS_URL),
|
|
crisp: {
|
|
chatWebsiteId: present(env.CRISP_CHAT_WEBSITE_ID),
|
|
},
|
|
captcha: {
|
|
provider: present(env.CAPTCHA_PROVIDER)?.toLowerCase() === "cap" ? "cap" : "mcaptcha",
|
|
instanceUrl: present(env.CAPTCHA_PROVIDER)?.toLowerCase() === "cap" ? present(env.CAP_INSTANCE_URL) : present(env.MCAPTCHA_INSTANCE_URL),
|
|
loginSiteKey: present(env.CAPTCHA_PROVIDER)?.toLowerCase() === "cap" ? present(env.CAP_SITEKEY_LOGIN) : 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),
|
|
},
|
|
webPush: {
|
|
vapidPublicKey: present(env.WEB_PUSH_VAPID_PUBLIC_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),
|
|
},
|
|
adminEmail:
|
|
runtimeSurface !== "portal"
|
|
? {
|
|
bccCapabilitySecret: present(
|
|
env.ADMIN_EMAIL_BCC_CAPABILITY_SECRET
|
|
),
|
|
bccInboundDomain:
|
|
present(env.ADMIN_EMAIL_BCC_INBOUND_DOMAIN) ??
|
|
`bcc.${routing.appBaseDomain.split(":")[0]}`,
|
|
}
|
|
: undefined,
|
|
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),
|
|
},
|
|
lago: {
|
|
apiUrl: present(env.LAGO_API_URL),
|
|
apiKey: present(env.LAGO_API_KEY),
|
|
webhookSecret: present(env.LAGO_WEBHOOK_SECRET),
|
|
timeoutMs: normalizePositiveInteger(env.LAGO_TIMEOUT_MS, DEFAULT_LAGO_TIMEOUT_MS),
|
|
},
|
|
mollie: {
|
|
apiKey: present(env.MOLLIE_API_KEY),
|
|
profileId: present(env.MOLLIE_PROFILE_ID),
|
|
timeoutMs: normalizePositiveInteger(env.MOLLIE_TIMEOUT_MS, DEFAULT_MOLLIE_TIMEOUT_MS),
|
|
},
|
|
aircall: {
|
|
clientId: present(env.AIRCALL_CLIENT_ID),
|
|
clientSecret: present(env.AIRCALL_CLIENT_SECRET),
|
|
redirectUri: present(env.AIRCALL_REDIRECT_URI),
|
|
webhookUrl: present(env.AIRCALL_WEBHOOK_URL),
|
|
},
|
|
hallopetra: {
|
|
webhookUrl: present(env.HALLOPETRA_WEBHOOK_URL),
|
|
},
|
|
kwp: {
|
|
clientId: present(env.KWP_OAUTH_CLIENT_ID),
|
|
clientSecret: present(env.KWP_OAUTH_CLIENT_SECRET),
|
|
scopes: present(env.KWP_OAUTH_SCOPES),
|
|
customerCode: present(env.KWP_CUSTOMER_CODE),
|
|
oidcIssuer: present(env.KWP_OIDC_ISSUER),
|
|
hiveGridTenantId: present(env.KWP_HIVEGRID_TENANT_ID),
|
|
mandant: present(env.KWP_MANDANT),
|
|
},
|
|
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),
|
|
gdprExportSseCKey: present(env.GDPR_EXPORT_SSE_C_KEY_BASE64),
|
|
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 normalizeEnabledLocales(value: string | undefined, nodeEnv: string, sentryEnvironment: string | undefined) {
|
|
const allowReviewLocales = nodeEnv !== "production" || sentryEnvironment?.trim().toLowerCase() === "staging";
|
|
try {
|
|
return { enabledLocales: parseEnabledLocales(value, { allowReviewLocales }) };
|
|
} catch (error) {
|
|
if (!(error instanceof EnabledLocalesConfigError)) throw error;
|
|
return {
|
|
enabledLocales: parseEnabledLocales(undefined),
|
|
diagnostic: {
|
|
code: "invalid-enum" as const,
|
|
name: "I18N_ENABLED_LOCALES",
|
|
classification: getEnvVariableDefinition("I18N_ENABLED_LOCALES")?.classification,
|
|
message: error.message,
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
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 normalizePositiveInteger(value: string | undefined, defaultValue: number): number {
|
|
const trimmed = present(value);
|
|
if (trimmed === undefined) {
|
|
return defaultValue;
|
|
}
|
|
const parsed = Number(trimmed);
|
|
return Number.isInteger(parsed) && parsed > 0 ? parsed : defaultValue;
|
|
}
|
|
|
|
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 MAX_METRICS_TOKEN_BYTES = 512;
|
|
const STRENGTH_CHECKED_SECRETS = [
|
|
"SESSION_SECRET",
|
|
"CRYPTO_SECRET",
|
|
"ADMIN_CONNECTION_MASTER_KEY",
|
|
"JWT_SECRET",
|
|
"API_ACCESS_TOKEN",
|
|
"AUDIT_CHAIN_SECRET",
|
|
"METRICS_TOKEN",
|
|
"API_KEY_HASH_SECRET",
|
|
"MCP_OAUTH_TOKEN_HASH_SECRET",
|
|
"ADMIN_EMAIL_BCC_CAPABILITY_SECRET",
|
|
] 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 bytes) 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, runtimeSurface: WebRuntimeSurface): WebConfigDiagnostic[] {
|
|
if (nodeEnv !== "production") {
|
|
return [];
|
|
}
|
|
const diagnostics: WebConfigDiagnostic[] = [];
|
|
const checkedSecrets = runtimeSurface === "portal" ? ["PORTAL_SESSION_SECRET"] : STRENGTH_CHECKED_SECRETS;
|
|
for (const name of checkedSecrets) {
|
|
const value = present(env[name]);
|
|
const byteLength = value ? Buffer.byteLength(value, "utf8") : 0;
|
|
if (value && (byteLength < MIN_SECRET_LENGTH || (name === "METRICS_TOKEN" && byteLength > MAX_METRICS_TOKEN_BYTES))) {
|
|
diagnostics.push({
|
|
code: "weak-secret",
|
|
name,
|
|
classification: getEnvVariableDefinition(name)?.classification,
|
|
message:
|
|
name === "METRICS_TOKEN"
|
|
? `METRICS_TOKEN must contain ${MIN_SECRET_LENGTH}..${MAX_METRICS_TOKEN_BYTES} bytes in production.`
|
|
: `${name} must be at least ${MIN_SECRET_LENGTH} bytes in production (generate with \`openssl rand -hex 32\`).`,
|
|
});
|
|
}
|
|
}
|
|
const sessionSecret = runtimeSurface !== "portal" ? present(env.SESSION_SECRET) : undefined;
|
|
const cryptoSecret = present(env.CRYPTO_SECRET);
|
|
const adminConnectionMasterKey = present(env.ADMIN_CONNECTION_MASTER_KEY);
|
|
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.",
|
|
});
|
|
}
|
|
if (
|
|
adminConnectionMasterKey &&
|
|
(adminConnectionMasterKey === sessionSecret ||
|
|
adminConnectionMasterKey === cryptoSecret)
|
|
) {
|
|
diagnostics.push({
|
|
code: "weak-secret",
|
|
name: "ADMIN_CONNECTION_MASTER_KEY",
|
|
classification: getEnvVariableDefinition(
|
|
"ADMIN_CONNECTION_MASTER_KEY"
|
|
)?.classification,
|
|
message:
|
|
"ADMIN_CONNECTION_MASTER_KEY must be independent from SESSION_SECRET and CRYPTO_SECRET.",
|
|
});
|
|
}
|
|
return diagnostics;
|
|
}
|
|
|
|
function validateGdprExportStorageContract(env: EnvRecord, nodeEnv: string): WebConfigDiagnostic[] {
|
|
const diagnostics: WebConfigDiagnostic[] = [];
|
|
if (nodeEnv === "production") {
|
|
for (const name of ["STORAGE_ENDPOINT", "STORAGE_REGION", "STORAGE_BUCKET", "STORAGE_ACCESS_KEY_ID", "STORAGE_SECRET_ACCESS_KEY"] as const) {
|
|
if (!present(env[name])) {
|
|
diagnostics.push({
|
|
code: "missing-required",
|
|
name,
|
|
classification: getEnvVariableDefinition(name)?.classification,
|
|
message: `${name} is required for encrypted GDPR export downloads in production.`,
|
|
});
|
|
}
|
|
}
|
|
const endpoint = present(env.STORAGE_ENDPOINT);
|
|
if (endpoint) {
|
|
try {
|
|
if (new URL(endpoint).protocol !== "https:") throw new Error("invalid protocol");
|
|
} catch {
|
|
diagnostics.push({
|
|
code: "invalid-url",
|
|
name: "STORAGE_ENDPOINT",
|
|
classification: getEnvVariableDefinition("STORAGE_ENDPOINT")?.classification,
|
|
message: "STORAGE_ENDPOINT must be a valid HTTPS URL for encrypted GDPR export downloads in production.",
|
|
});
|
|
}
|
|
}
|
|
}
|
|
const rawValue = env.GDPR_EXPORT_SSE_C_KEY_BASE64;
|
|
const value = present(rawValue);
|
|
if (nodeEnv === "production" && typeof rawValue === "string" && rawValue.length > 0 && !value) {
|
|
diagnostics.push({
|
|
code: "missing-required",
|
|
name: "GDPR_EXPORT_SSE_C_KEY_BASE64",
|
|
classification: getEnvVariableDefinition("GDPR_EXPORT_SSE_C_KEY_BASE64")?.classification,
|
|
message: "GDPR_EXPORT_SSE_C_KEY_BASE64 is required for encrypted GDPR export downloads in production.",
|
|
});
|
|
}
|
|
if (value && !normalizeGdprExportSseCKey(value)) {
|
|
diagnostics.push({
|
|
code: "weak-secret",
|
|
name: "GDPR_EXPORT_SSE_C_KEY_BASE64",
|
|
classification: getEnvVariableDefinition("GDPR_EXPORT_SSE_C_KEY_BASE64")?.classification,
|
|
message: "GDPR_EXPORT_SSE_C_KEY_BASE64 must be canonical base64 encoding of exactly 32 random bytes.",
|
|
});
|
|
}
|
|
return diagnostics;
|
|
}
|
|
|
|
function normalizeRuntimeSurface(value: string | undefined, nodeEnv: string): { surface: WebRuntimeSurface; diagnostic?: WebConfigDiagnostic } {
|
|
const normalized = value?.trim().toLowerCase();
|
|
if (normalized === "core" || normalized === "admin" || normalized === "portal") {
|
|
return { surface: normalized };
|
|
}
|
|
if (!normalized && nodeEnv !== "production") {
|
|
return { surface: "core" };
|
|
}
|
|
return {
|
|
surface: "core",
|
|
diagnostic: {
|
|
code: normalized ? "invalid-enum" : "missing-required",
|
|
name: "WEB_RUNTIME_SURFACE",
|
|
classification: getEnvVariableDefinition("WEB_RUNTIME_SURFACE")?.classification,
|
|
message: "WEB_RUNTIME_SURFACE must be explicitly set to core, admin, or portal in production.",
|
|
},
|
|
};
|
|
}
|
|
|
|
function validateSurfaceBoundary(env: EnvRecord, nodeEnv: string, runtimeSurface: WebRuntimeSurface): WebConfigDiagnostic[] {
|
|
const diagnostics: WebConfigDiagnostic[] = [];
|
|
const forbiddenSecret = runtimeSurface === "portal" ? "SESSION_SECRET" : "PORTAL_SESSION_SECRET";
|
|
|
|
if (runtimeSurface === "portal" && !present(env.PORTAL_SESSION_SECRET)) {
|
|
diagnostics.push({
|
|
code: "missing-required",
|
|
name: "PORTAL_SESSION_SECRET",
|
|
classification: getEnvVariableDefinition("PORTAL_SESSION_SECRET")?.classification,
|
|
message: "PORTAL_SESSION_SECRET is required for the portal web runtime surface.",
|
|
});
|
|
}
|
|
if (env[forbiddenSecret] !== undefined) {
|
|
diagnostics.push({
|
|
code: "forbidden",
|
|
name: forbiddenSecret,
|
|
classification: getEnvVariableDefinition(forbiddenSecret)?.classification,
|
|
message: `${forbiddenSecret} is forbidden for the selected web runtime surface.`,
|
|
});
|
|
}
|
|
if (nodeEnv === "production" && !present(env.PORTAL_APP_HOST)) {
|
|
diagnostics.push({
|
|
code: "missing-required",
|
|
name: "PORTAL_APP_HOST",
|
|
classification: getEnvVariableDefinition("PORTAL_APP_HOST")?.classification,
|
|
message: "PORTAL_APP_HOST is required for production web runtimes.",
|
|
});
|
|
}
|
|
const portalHost = present(env.PORTAL_APP_HOST);
|
|
const routing = getDomainRoutingConfig(env);
|
|
const normalizedPortalHost = normalizeHostForProtocol(portalHost, routing.protocol);
|
|
if (portalHost && !normalizedPortalHost) {
|
|
diagnostics.push({
|
|
code: "invalid-host",
|
|
name: "PORTAL_APP_HOST",
|
|
classification: getEnvVariableDefinition("PORTAL_APP_HOST")?.classification,
|
|
message: "PORTAL_APP_HOST must contain a valid canonical host.",
|
|
});
|
|
}
|
|
if (nodeEnv === "production" && runtimeSurface === "portal" && routing.protocol !== "https" && !isLoopbackHost(routing.portalAppHost)) {
|
|
diagnostics.push({
|
|
code: "invalid-enum",
|
|
name: "APP_PROTOCOL",
|
|
classification: getEnvVariableDefinition("APP_PROTOCOL")?.classification,
|
|
message: "APP_PROTOCOL must be https for a public production portal runtime.",
|
|
});
|
|
}
|
|
const boundaryHosts = [
|
|
["APP_BASE_DOMAIN", routing.appBaseDomain],
|
|
["WEB_APP_HOST", routing.webAppHost],
|
|
["ADMIN_APP_HOST", routing.adminAppHost],
|
|
["API_HOST", routing.apiHost],
|
|
] as const;
|
|
const conflictingHostName = normalizedPortalHost
|
|
? boundaryHosts.find(([, host]) => normalizeHostForProtocol(host, routing.protocol) === normalizedPortalHost)?.[0]
|
|
: undefined;
|
|
if (conflictingHostName) {
|
|
diagnostics.push({
|
|
code: "host-conflict",
|
|
name: "PORTAL_APP_HOST",
|
|
classification: getEnvVariableDefinition("PORTAL_APP_HOST")?.classification,
|
|
message: `PORTAL_APP_HOST must be distinct from ${conflictingHostName}.`,
|
|
});
|
|
}
|
|
return diagnostics;
|
|
}
|
|
|
|
function isLoopbackHost(value: string | undefined) {
|
|
const host = normalizeHostForProtocol(value, "http");
|
|
if (!host) {
|
|
return false;
|
|
}
|
|
|
|
const hostname = new URL(`http://${host}`).hostname.toLowerCase();
|
|
const ipv4Parts = hostname.split(".");
|
|
const isIpv4Loopback =
|
|
ipv4Parts.length === 4 && ipv4Parts[0] === "127" && ipv4Parts.every((part) => /^\d{1,3}$/u.test(part) && Number(part) >= 0 && Number(part) <= 255);
|
|
return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "::1" || hostname === "[::1]" || isIpv4Loopback;
|
|
}
|
|
|
|
function validatePortalAuthDependencies(env: EnvRecord, nodeEnv: string, runtimeSurface: WebRuntimeSurface): WebConfigDiagnostic[] {
|
|
if (nodeEnv !== "production" || runtimeSurface !== "portal") {
|
|
return [];
|
|
}
|
|
|
|
const diagnostics: WebConfigDiagnostic[] = [];
|
|
const provider = present(env.CAPTCHA_PROVIDER)?.toLowerCase();
|
|
if (!provider) {
|
|
diagnostics.push(
|
|
missingPortalDependency("CAPTCHA_PROVIDER", "CAPTCHA_PROVIDER must be explicitly set to cap or mcaptcha for the production portal runtime.")
|
|
);
|
|
} else if (provider !== "cap" && provider !== "mcaptcha") {
|
|
diagnostics.push({
|
|
code: "invalid-enum",
|
|
name: "CAPTCHA_PROVIDER",
|
|
classification: getEnvVariableDefinition("CAPTCHA_PROVIDER")?.classification,
|
|
message: "CAPTCHA_PROVIDER must be cap or mcaptcha for the production portal runtime.",
|
|
});
|
|
} else if (provider === "cap") {
|
|
diagnostics.push(...validatePortalCaptchaInstanceUrl(env.CAP_INSTANCE_URL, "CAP_INSTANCE_URL"));
|
|
if (!present(env.CAP_SITEKEY_LOGIN)) {
|
|
diagnostics.push(missingPortalDependency("CAP_SITEKEY_LOGIN", "CAP_SITEKEY_LOGIN is required for portal login challenges when CAPTCHA_PROVIDER=cap."));
|
|
}
|
|
if (!present(env.CAP_SITE_SECRET_LOGIN) && !present(env.CAP_SITE_SECRET)) {
|
|
diagnostics.push(
|
|
missingPortalDependency(
|
|
"CAP_SITE_SECRET_LOGIN",
|
|
"CAP_SITE_SECRET_LOGIN or CAP_SITE_SECRET is required for portal login verification when CAPTCHA_PROVIDER=cap."
|
|
)
|
|
);
|
|
}
|
|
} else {
|
|
diagnostics.push(...validatePortalCaptchaInstanceUrl(env.MCAPTCHA_INSTANCE_URL, "MCAPTCHA_INSTANCE_URL"));
|
|
if (!present(env.MCAPTCHA_SITEKEY_LOGIN)) {
|
|
diagnostics.push(
|
|
missingPortalDependency("MCAPTCHA_SITEKEY_LOGIN", "MCAPTCHA_SITEKEY_LOGIN is required for portal login challenges when CAPTCHA_PROVIDER=mcaptcha.")
|
|
);
|
|
}
|
|
if (!present(env.MCAPTCHA_ACCOUNT_SECRET)) {
|
|
diagnostics.push(
|
|
missingPortalDependency("MCAPTCHA_ACCOUNT_SECRET", "MCAPTCHA_ACCOUNT_SECRET is required for portal login verification when CAPTCHA_PROVIDER=mcaptcha.")
|
|
);
|
|
}
|
|
}
|
|
|
|
const bullmqRedisUrl = present(env.BULLMQ_REDIS_URL);
|
|
if (bullmqRedisUrl) {
|
|
diagnostics.push(...validateRedisConnectionUrl(bullmqRedisUrl, "BULLMQ_REDIS_URL"));
|
|
}
|
|
|
|
return diagnostics;
|
|
}
|
|
|
|
function validateWebRedisDependency(env: EnvRecord, nodeEnv: string): WebConfigDiagnostic[] {
|
|
if (nodeEnv !== "production") return [];
|
|
const redisUrl = present(env.REDIS_URL);
|
|
if (!redisUrl) {
|
|
return [
|
|
{
|
|
code: "missing-required",
|
|
name: "REDIS_URL",
|
|
classification: getEnvVariableDefinition("REDIS_URL")?.classification,
|
|
message: "REDIS_URL is required for distributed GDPR export download gates in production.",
|
|
},
|
|
];
|
|
}
|
|
return validateRedisConnectionUrl(redisUrl, "REDIS_URL");
|
|
}
|
|
|
|
function missingPortalDependency(name: string, message: string): WebConfigDiagnostic {
|
|
return {
|
|
code: "missing-required",
|
|
name,
|
|
classification: getEnvVariableDefinition(name)?.classification,
|
|
message,
|
|
};
|
|
}
|
|
|
|
function validatePortalCaptchaInstanceUrl(value: string | undefined, name: "CAP_INSTANCE_URL" | "MCAPTCHA_INSTANCE_URL"): WebConfigDiagnostic[] {
|
|
const normalized = present(value);
|
|
if (!normalized) {
|
|
return [missingPortalDependency(name, `${name} is required for the selected production portal CAPTCHA provider.`)];
|
|
}
|
|
|
|
try {
|
|
const url = new URL(normalized);
|
|
const isLoopback = url.hostname === "localhost" || url.hostname === "::1" || url.hostname === "[::1]" || url.hostname.startsWith("127.");
|
|
const allowedProtocol = url.protocol === "https:" || (url.protocol === "http:" && isLoopback);
|
|
if (!allowedProtocol || !url.hostname || url.username || url.password || url.search || url.hash) {
|
|
throw new Error("invalid captcha instance URL");
|
|
}
|
|
return [];
|
|
} catch {
|
|
return [
|
|
{
|
|
code: "invalid-url",
|
|
name,
|
|
classification: getEnvVariableDefinition(name)?.classification,
|
|
message: `${name} must be an allowed CAPTCHA instance URL without credentials, query parameters, or fragments.`,
|
|
},
|
|
];
|
|
}
|
|
}
|
|
|
|
function validateRedisConnectionUrl(value: string, name: "REDIS_URL" | "BULLMQ_REDIS_URL"): WebConfigDiagnostic[] {
|
|
try {
|
|
const url = new URL(value);
|
|
const database = url.pathname.replace(/^\//u, "");
|
|
if ((url.protocol !== "redis:" && url.protocol !== "rediss:") || !url.hostname || (database && !/^\d+$/u.test(database))) {
|
|
throw new Error("invalid Redis URL");
|
|
}
|
|
return [];
|
|
} catch {
|
|
return [
|
|
{
|
|
code: "invalid-url",
|
|
name,
|
|
classification: getEnvVariableDefinition(name)?.classification,
|
|
message: `${name} must be a valid redis:// or rediss:// connection URL with an optional numeric database index.`,
|
|
},
|
|
];
|
|
}
|
|
}
|
|
|
|
function validateReleaseRevision(value: string | undefined, nodeEnv: string): WebConfigDiagnostic[] {
|
|
if (nodeEnv !== "production") {
|
|
return [];
|
|
}
|
|
const revision = present(value);
|
|
if (!revision) {
|
|
return [
|
|
{
|
|
code: "missing-required",
|
|
name: "APP_REVISION",
|
|
classification: getEnvVariableDefinition("APP_REVISION")?.classification,
|
|
message: "APP_REVISION must be the full Git SHA baked into the production image.",
|
|
},
|
|
];
|
|
}
|
|
if (!FULL_GIT_SHA_PATTERN.test(revision)) {
|
|
return [
|
|
{
|
|
code: "invalid-revision",
|
|
name: "APP_REVISION",
|
|
classification: getEnvVariableDefinition("APP_REVISION")?.classification,
|
|
message: "APP_REVISION must be a 40-character lowercase Git SHA baked into the production image.",
|
|
},
|
|
];
|
|
}
|
|
return [];
|
|
}
|
|
|
|
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;
|
|
}
|