Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -1,6 +1,17 @@
|
||||
import { EnabledLocalesConfigError, parseEnabledLocales } from "@hivegrid/i18n/locales";
|
||||
import { getEnvVariableDefinition, validateEnv } from "./index.js";
|
||||
import { getDomainRoutingConfig } from "./routing.js";
|
||||
import type { EnvRecord, RequiredWebConfigOptions, WebConfig, WebConfigDiagnostic, WebConfigErrorDetails, WebConfigOptions, WebConfigResult } from "./types.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";
|
||||
@@ -11,6 +22,20 @@ 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[];
|
||||
@@ -39,32 +64,52 @@ export function loadRequiredWebConfig(env: EnvRecord = process.env, options: Req
|
||||
|
||||
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(
|
||||
validateEnv(env, {
|
||||
target: "web",
|
||||
nodeEnv,
|
||||
includeOptionalProviders: options.includeOptionalProviders,
|
||||
extraRequired: options.extraRequired,
|
||||
}).missing
|
||||
),
|
||||
...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);
|
||||
}
|
||||
diagnostics.push(...validateSecretStrength(env, nodeEnv));
|
||||
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,
|
||||
sessionSecret: present(env.SESSION_SECRET),
|
||||
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,
|
||||
@@ -86,12 +131,26 @@ export function loadWebConfig(env: EnvRecord = process.env, options: WebConfigOp
|
||||
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),
|
||||
@@ -100,10 +159,6 @@ export function loadWebConfig(env: EnvRecord = process.env, options: WebConfigOp
|
||||
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),
|
||||
},
|
||||
lago: {
|
||||
apiUrl: present(env.LAGO_API_URL),
|
||||
apiKey: present(env.LAGO_API_KEY),
|
||||
@@ -115,6 +170,24 @@ export function loadWebConfig(env: EnvRecord = process.env, options: WebConfigOp
|
||||
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),
|
||||
@@ -124,6 +197,7 @@ export function loadWebConfig(env: EnvRecord = process.env, options: WebConfigOp
|
||||
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),
|
||||
@@ -147,6 +221,24 @@ export function loadWebConfig(env: EnvRecord = process.env, options: WebConfigOp
|
||||
};
|
||||
}
|
||||
|
||||
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") {
|
||||
@@ -253,31 +345,49 @@ function normalizeMagicLinkTokenTtlMinutes(value: string | undefined): { tokenTt
|
||||
}
|
||||
|
||||
const MIN_SECRET_LENGTH = 32;
|
||||
const STRENGTH_CHECKED_SECRETS = ["SESSION_SECRET", "CRYPTO_SECRET", "JWT_SECRET", "API_ACCESS_TOKEN"] as const;
|
||||
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 chars) or when SESSION_SECRET and CRYPTO_SECRET are
|
||||
// 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): WebConfigDiagnostic[] {
|
||||
function validateSecretStrength(env: EnvRecord, nodeEnv: string, runtimeSurface: WebRuntimeSurface): WebConfigDiagnostic[] {
|
||||
if (nodeEnv !== "production") {
|
||||
return [];
|
||||
}
|
||||
const diagnostics: WebConfigDiagnostic[] = [];
|
||||
for (const name of STRENGTH_CHECKED_SECRETS) {
|
||||
const checkedSecrets = runtimeSurface === "portal" ? ["PORTAL_SESSION_SECRET"] : STRENGTH_CHECKED_SECRETS;
|
||||
for (const name of checkedSecrets) {
|
||||
const value = present(env[name]);
|
||||
if (value && value.length < MIN_SECRET_LENGTH) {
|
||||
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} must be at least ${MIN_SECRET_LENGTH} characters in production (generate with \`openssl rand -hex 32\`).`,
|
||||
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 = present(env.SESSION_SECRET);
|
||||
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",
|
||||
@@ -286,9 +396,323 @@ function validateSecretStrength(env: EnvRecord, nodeEnv: string): WebConfigDiagn
|
||||
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",
|
||||
|
||||
Reference in new issue
Block a user