Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -22,6 +22,9 @@ The catalog is verified against `.env.example`, `.env.local.example`, `.env.prod
| `APP_NAME` | required-core | shared, web, api, worker | code-and-example |
| `DATABASE_URL` | required-core | shared, web, api, worker | code-and-example |
| `SESSION_SECRET` | required-core | web, api | code-and-example |
| `WEB_RUNTIME_SURFACE` | production-only | web | code-and-example |
| `PORTAL_SESSION_SECRET` | production-only | web | code-and-example |
| `PORTAL_APP_HOST` | production-only | web, worker | code-and-example |
| `CRYPTO_SECRET` | required-per-app | web, api | code-and-example |
| `API_ACCESS_TOKEN` | required-per-app | web, api | code-and-example |
| `JWT_SECRET` | required-per-app | web, api | code-and-example |
@@ -70,8 +73,6 @@ The catalog is verified against `.env.example`, `.env.local.example`, `.env.prod
| `BROWSER_SESSION_TIMEOUT_MS` | optional-provider | api, worker | example |
| `IPSTACK_API_KEY` | optional-provider | api, worker | code |
| `IPAPIIS_API_KEY` | optional-provider | api, worker | code |
| `PORTAL_SERVER_URL` | optional-provider | web, api | code-and-example |
| `PORTAL_SERVER_FLY_TOKEN` | optional-provider | web, api, worker | code-and-example |
| `DEMO_USER` | local-development-only | web | code |
| `SEED_ADMIN_EMAIL` | production-only | web | code-and-example |
| `SEED_ADMIN_PASSWORD` | production-only | web | code-and-example |
@@ -9,5 +9,8 @@
},
"scripts": {
"test": "cd ../.. && vitest run packages/config/src"
},
"dependencies": {
"@hivegrid/i18n": "workspace:*"
}
}
@@ -1,6 +1,16 @@
import { describe, expect, test } from "vitest";
import { ApiConfigError, loadApiConfig, loadRequiredApiConfig } from "./index.js";
const PRODUCTION_SECRETS = {
session: "session-secret-value-with-at-least-32-characters",
crypto: "crypto-secret-value-with-at-least-32-characters",
adminConnection: "admin-connection-key-with-at-least-32-characters",
apiAccess: "api-access-token-value-with-at-least-32-characters",
jwt: "jwt-secret-value-with-at-least-32-characters",
analytics: "analytics-token-value-with-at-least-32-characters",
auditChain: "audit-chain-secret-value-with-at-least-32-characters",
} as const;
const REQUIRED_PRODUCTION_ENV = {
APP_NAME: "Production API",
DATABASE_URL: "postgres://example.invalid/app",
@@ -8,11 +18,13 @@ const REQUIRED_PRODUCTION_ENV = {
WEB_APP_HOST: "app.example.com",
ADMIN_APP_HOST: "admin.example.com",
API_HOST: "api.example.com",
SESSION_SECRET: "session-secret-value",
CRYPTO_SECRET: "crypto-secret-value",
API_ACCESS_TOKEN: "api-access-token-value",
JWT_SECRET: "jwt-secret-value",
ANALYTICS_TOKEN: "analytics-token-value",
SESSION_SECRET: PRODUCTION_SECRETS.session,
CRYPTO_SECRET: PRODUCTION_SECRETS.crypto,
ADMIN_CONNECTION_MASTER_KEY: PRODUCTION_SECRETS.adminConnection,
API_ACCESS_TOKEN: PRODUCTION_SECRETS.apiAccess,
JWT_SECRET: PRODUCTION_SECRETS.jwt,
ANALYTICS_TOKEN: PRODUCTION_SECRETS.analytics,
AUDIT_CHAIN_SECRET: PRODUCTION_SECRETS.auditChain,
};
describe("loadRequiredApiConfig", () => {
@@ -35,13 +47,13 @@ describe("loadRequiredApiConfig", () => {
apiHost: "api.example.com",
protocol: "https",
},
apiAccessToken: "api-access-token-value",
jwtSecret: "jwt-secret-value",
apiAccessToken: PRODUCTION_SECRETS.apiAccess,
jwtSecret: PRODUCTION_SECRETS.jwt,
});
});
test("throws redacted ApiConfigError for missing required API_ACCESS_TOKEN", () => {
const secretValues = ["session-secret-value", "crypto-secret-value", "jwt-secret-value", "analytics-token-value"];
const secretValues = [PRODUCTION_SECRETS.session, PRODUCTION_SECRETS.crypto, PRODUCTION_SECRETS.jwt, PRODUCTION_SECRETS.analytics];
expect(() =>
loadRequiredApiConfig(
@@ -79,9 +91,55 @@ describe("loadRequiredApiConfig", () => {
}
});
test("rejects weak production secrets without exposing their values", () => {
const weakSecret = "short-secret";
const result = loadApiConfig(
{
...REQUIRED_PRODUCTION_ENV,
JWT_SECRET: weakSecret,
},
{ nodeEnv: "production" }
);
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "JWT_SECRET" }));
expect(JSON.stringify(result.diagnostics)).not.toContain(weakSecret);
});
test("rejects secret reuse across independent API purposes", () => {
const result = loadApiConfig(
{
...REQUIRED_PRODUCTION_ENV,
API_ACCESS_TOKEN: PRODUCTION_SECRETS.jwt,
},
{ nodeEnv: "production" }
);
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "weak-secret",
name: "API_ACCESS_TOKEN",
message: expect.stringContaining("must not be identical to JWT_SECRET"),
})
);
expect(JSON.stringify(result.diagnostics)).not.toContain(PRODUCTION_SECRETS.jwt);
});
test("enforces metrics bounds and Mailjet webhook secret strength", () => {
const shortMetrics = loadApiConfig({ ...REQUIRED_PRODUCTION_ENV, METRICS_TOKEN: "short" }, { nodeEnv: "production" });
const longMetrics = loadApiConfig({ ...REQUIRED_PRODUCTION_ENV, METRICS_TOKEN: "x".repeat(513) }, { nodeEnv: "production" });
const shortWebhook = loadApiConfig({ ...REQUIRED_PRODUCTION_ENV, MAILJET_WEBHOOK_SECRET: "short" }, { nodeEnv: "production" });
const shortApiKeyHash = loadApiConfig({ ...REQUIRED_PRODUCTION_ENV, API_KEY_HASH_SECRET: "short" }, { nodeEnv: "production" });
expect(shortMetrics.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "METRICS_TOKEN" }));
expect(longMetrics.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "METRICS_TOKEN" }));
expect(shortWebhook.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "MAILJET_WEBHOOK_SECRET" }));
expect(shortApiKeyHash.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "API_KEY_HASH_SECRET" }));
});
test("throws redacted ApiConfigError for invalid API_PORT", () => {
const invalidPort = "secret-like-invalid-port-value";
const secretValues = ["session-secret-value", "crypto-secret-value", "api-access-token-value", "jwt-secret-value", "analytics-token-value"];
const secretValues = Object.values(PRODUCTION_SECRETS);
try {
loadRequiredApiConfig(
@@ -115,6 +173,18 @@ describe("loadRequiredApiConfig", () => {
});
describe("loadApiConfig", () => {
test("validates the shared runtime locale gate for API documentation", () => {
expect(loadApiConfig({ I18N_ENABLED_LOCALES: "de,en,pl" }).diagnostics).not.toContainEqual(
expect.objectContaining({ name: "I18N_ENABLED_LOCALES" })
);
expect(loadApiConfig({ I18N_ENABLED_LOCALES: "de,en,en" }).diagnostics).toContainEqual(
expect.objectContaining({ code: "invalid-enum", name: "I18N_ENABLED_LOCALES" })
);
expect(loadApiConfig({ ...REQUIRED_PRODUCTION_ENV, I18N_ENABLED_LOCALES: "de,en,pl" }, { nodeEnv: "production" }).diagnostics).toContainEqual(
expect.objectContaining({ code: "invalid-enum", name: "I18N_ENABLED_LOCALES" })
);
});
test("returns local defaults and API listen defaults", () => {
const result = loadApiConfig({});
@@ -156,8 +226,8 @@ describe("loadApiConfig", () => {
expect.objectContaining({ code: "missing-required", name: "ANALYTICS_TOKEN", classification: "required-per-app" }),
])
);
expect(JSON.stringify(result.diagnostics)).not.toContain("api-access-token-value");
expect(JSON.stringify(result.diagnostics)).not.toContain("analytics-token-value");
expect(JSON.stringify(result.diagnostics)).not.toContain(PRODUCTION_SECRETS.apiAccess);
expect(JSON.stringify(result.diagnostics)).not.toContain(PRODUCTION_SECRETS.analytics);
});
test("prefers API_PORT over PORT and falls back to PORT when API_PORT is empty", () => {
@@ -167,7 +237,7 @@ describe("loadApiConfig", () => {
});
test("falls back for invalid API_PORT without leaking configured secrets", () => {
const secretValues = ["api-access-token-value", "jwt-secret-value", "analytics-token-value"];
const secretValues = [PRODUCTION_SECRETS.apiAccess, PRODUCTION_SECRETS.jwt, PRODUCTION_SECRETS.analytics];
const result = loadApiConfig({
API_ACCESS_TOKEN: secretValues[0],
JWT_SECRET: secretValues[1],
@@ -199,10 +269,10 @@ describe("loadApiConfig", () => {
APP_PROTOCOL: "https",
WEB_ORIGIN: " ",
ADMIN_ORIGIN: "\t",
API_ACCESS_TOKEN: " api-access-token-value ",
JWT_SECRET: " jwt-secret-value ",
ANALYTICS_TOKEN: " analytics-token-value ",
MAILJET_WEBHOOK_SECRET: " mailjet-webhook-secret-value ",
API_ACCESS_TOKEN: ` ${PRODUCTION_SECRETS.apiAccess} `,
JWT_SECRET: ` ${PRODUCTION_SECRETS.jwt} `,
ANALYTICS_TOKEN: ` ${PRODUCTION_SECRETS.analytics} `,
MAILJET_WEBHOOK_SECRET: " mailjet-webhook-secret-value-0123456789 ",
LAGO_API_URL: " http://lago.internal:3000 ",
LAGO_API_KEY: " lago-api-key-value ",
LAGO_WEBHOOK_SECRET: " lago-webhook-secret-value ",
@@ -234,13 +304,13 @@ describe("loadApiConfig", () => {
protocol: "https",
},
origins: {},
apiAccessToken: "api-access-token-value",
jwtSecret: "jwt-secret-value",
apiAccessToken: PRODUCTION_SECRETS.apiAccess,
jwtSecret: PRODUCTION_SECRETS.jwt,
analytics: {
token: "analytics-token-value",
token: PRODUCTION_SECRETS.analytics,
},
mailjet: {
webhookSecret: "mailjet-webhook-secret-value",
webhookSecret: "mailjet-webhook-secret-value-0123456789",
},
lago: {
apiUrl: "http://lago.internal:3000",
@@ -1,3 +1,4 @@
import { EnabledLocalesConfigError, parseEnabledLocales } from "@hivegrid/i18n";
import { getEnvVariableDefinition, validateEnv } from "./index.js";
import { getDomainRoutingConfig } from "./routing.js";
import type { ApiConfig, ApiConfigDiagnostic, ApiConfigErrorDetails, ApiConfigOptions, ApiConfigResult, EnvRecord, RequiredApiConfigOptions } from "./types.js";
@@ -9,6 +10,22 @@ const DEFAULT_LAGO_TIMEOUT_MS = 10_000;
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000;
const MIN_PORT = 1;
const MAX_PORT = 65535;
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",
"ANALYTICS_TOKEN",
"AUDIT_CHAIN_SECRET",
"METRICS_TOKEN",
"MAILJET_WEBHOOK_SECRET",
"ADMIN_EMAIL_EVENT_WEBHOOK_SECRET",
"ADMIN_EMAIL_BCC_CAPABILITY_SECRET",
"API_KEY_HASH_SECRET",
] as const;
export class ApiConfigError extends Error {
readonly diagnostics: ApiConfigDiagnostic[];
@@ -53,6 +70,20 @@ export function loadApiConfig(env: EnvRecord = process.env, options: ApiConfigOp
if (portResult.diagnostic) {
diagnostics.push(portResult.diagnostic);
}
diagnostics.push(...validateApiSecretStrength(env, nodeEnv));
try {
parseEnabledLocales(env.I18N_ENABLED_LOCALES, {
allowReviewLocales: nodeEnv !== "production" || env.SENTRY_ENVIRONMENT?.trim().toLowerCase() === "staging",
});
} catch (error) {
if (!(error instanceof EnabledLocalesConfigError)) throw error;
diagnostics.push({
code: "invalid-enum",
name: "I18N_ENABLED_LOCALES",
classification: getEnvVariableDefinition("I18N_ENABLED_LOCALES")?.classification,
message: error.message,
});
}
const config: ApiConfig = {
appName: present(env.APP_NAME) ?? DEFAULT_APP_NAME,
@@ -74,6 +105,13 @@ export function loadApiConfig(env: EnvRecord = process.env, options: ApiConfigOp
mailjet: {
webhookSecret: present(env.MAILJET_WEBHOOK_SECRET),
},
adminEmail: {
eventWebhookSecret: present(env.ADMIN_EMAIL_EVENT_WEBHOOK_SECRET),
bccCapabilitySecret: present(env.ADMIN_EMAIL_BCC_CAPABILITY_SECRET),
bccInboundDomain:
present(env.ADMIN_EMAIL_BCC_INBOUND_DOMAIN) ??
`bcc.${routing.appBaseDomain.split(":")[0]}`,
},
lago: {
apiUrl: present(env.LAGO_API_URL),
apiKey: present(env.LAGO_API_KEY),
@@ -156,6 +194,45 @@ function normalizeListenPort(apiPort: string | undefined, port: string | undefin
return { port: parsed };
}
function validateApiSecretStrength(env: EnvRecord, nodeEnv: string): ApiConfigDiagnostic[] {
if (nodeEnv !== "production") {
return [];
}
const diagnostics: ApiConfigDiagnostic[] = [];
const firstPurposeByValue = new Map<string, (typeof STRENGTH_CHECKED_SECRETS)[number]>();
for (const name of STRENGTH_CHECKED_SECRETS) {
const value = present(env[name]);
if (!value) {
continue;
}
const byteLength = Buffer.byteLength(value, "utf8");
if (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.`,
});
}
const existingPurpose = firstPurposeByValue.get(value);
if (existingPurpose) {
diagnostics.push({
code: "weak-secret",
name,
classification: getEnvVariableDefinition(name)?.classification,
message: `${name} must use an independent value and must not be identical to ${existingPurpose}.`,
});
} else {
firstPurposeByValue.set(value, name);
}
}
return diagnostics;
}
function toDiagnostics(issues: ReturnType<typeof validateEnv>["missing"]): ApiConfigDiagnostic[] {
return issues.map((issue) => ({
code: "missing-required",
@@ -29,6 +29,7 @@ describe("env catalog", () => {
classification: "optional-provider",
targets: ["web", "api", "mcp", "worker"],
source: "code",
requiredInProductionTargets: ["web", "mcp"],
});
expect(getEnvVariableDefinition("EMAIL_QUEUE_NAME")).toMatchObject({
@@ -64,6 +65,25 @@ describe("env catalog", () => {
});
test("catalogs active operational runtime toggles", () => {
for (const key of ["WEB_RUNTIME_SURFACE", "PORTAL_SESSION_SECRET"]) {
expect(getEnvVariableDefinition(key)).toMatchObject({
classification: "production-only",
targets: ["web"],
source: "code-and-example",
});
}
expect(getEnvVariableDefinition("PORTAL_APP_HOST")).toMatchObject({
classification: "production-only",
targets: ["web", "worker"],
source: "code-and-example",
});
expect(getEnvVariableDefinition("CRYPTO_SECRET")).toMatchObject({
classification: "required-per-app",
targets: ["web", "api", "worker"],
source: "code-and-example",
});
expect(getEnvVariableDefinition("CRYPTO_SECRET")?.notes).toContain("worker-mail");
expect(getEnvVariableDefinition("HIVEGRID_API_MAINTENANCE_MODE")).toMatchObject({
classification: "production-only",
targets: ["api"],
@@ -75,6 +95,20 @@ describe("env catalog", () => {
targets: ["web"],
source: "code",
});
expect(getEnvVariableDefinition("SEED_DEMO_PRO_MANAGED")).toMatchObject({
classification: "production-only",
targets: ["web"],
source: "code",
defaultValue: "false",
});
expect(getEnvVariableDefinition("SEED_DEMO_USER_PASSWORD")).toMatchObject({
classification: "production-only",
targets: ["shared"],
kind: "secret",
source: "code",
});
});
test("groups required production keys without optional worker fallback keys", () => {
@@ -84,6 +118,7 @@ describe("env catalog", () => {
expect(getRequiredEnvVariableNames({ target: "worker", nodeEnv: "production" })).not.toEqual(
expect.arrayContaining(["WORKER_ENABLED", "BULLMQ_REDIS_URL", "REDIS_URL", "SITE_KEY_*"])
);
expect(getRequiredEnvVariableNames({ target: "mcp", nodeEnv: "production" })).toContain("REDIS_URL");
expect(groupEnvVariablesByClassification()["optional-provider"].map((definition) => definition.name)).toEqual(
expect.arrayContaining(["WORKER_ENABLED", "BULLMQ_REDIS_URL", "REDIS_URL", "CRISP_CHAT_WEBSITE_ID", "SITE_KEY_*"])
@@ -101,12 +136,7 @@ describe("env catalog", () => {
expect(envVarsDocument, `docs/env-vars.md missing required key ${key}`).toContain(`\`${key}\``);
}
for (const key of [
"PORTAL_SERVER_URL",
"PORTAL_SERVER_FLY_TOKEN",
"IMPORT_QUEUE_ENABLED",
"IMPORT_QUEUE_RUNTIME_READY",
]) {
for (const key of ["IMPORT_QUEUE_ENABLED", "IMPORT_QUEUE_RUNTIME_READY", "PORTAL_GDPR_EXPORT_QUEUE_ENABLED"]) {
expect(envVarsDocument, `docs/env-vars.md missing active optional key ${key}`).toContain(`\`${key}\``);
}
});
@@ -116,4 +146,59 @@ describe("env catalog", () => {
expect(getEnvVariableDefinition(key)?.targets, `${key} must include web because loadWebConfig consumes it`).toContain("web");
}
});
test("catalogs the Aircall Technology Partner OAuth boundary as web-only", () => {
for (const key of ["AIRCALL_CLIENT_ID", "AIRCALL_CLIENT_SECRET", "AIRCALL_REDIRECT_URI", "AIRCALL_WEBHOOK_URL"]) {
expect(getEnvVariableDefinition(key)).toMatchObject({
classification: "optional-provider",
targets: ["web"],
source: "code-and-example",
});
}
expect(getEnvVariableDefinition("AIRCALL_CLIENT_SECRET")?.kind).toBe("secret");
});
test("catalogs the KWP OAuth boundary and exposes only its tenant binding to the worker", () => {
for (const key of ["KWP_OAUTH_CLIENT_ID", "KWP_OAUTH_CLIENT_SECRET", "KWP_OAUTH_SCOPES", "KWP_CUSTOMER_CODE", "KWP_OIDC_ISSUER", "KWP_MANDANT"]) {
expect(getEnvVariableDefinition(key)).toMatchObject({
classification: "optional-provider",
targets: ["web"],
source: "code-and-example",
});
expect(getEnvVariableDefinition(key)?.requiredInProduction, `${key} must remain optional in production`).not.toBe(true);
}
expect(getEnvVariableDefinition("KWP_HIVEGRID_TENANT_ID")).toMatchObject({
classification: "optional-provider",
targets: ["web", "worker"],
source: "code-and-example",
});
expect(getEnvVariableDefinition("KWP_HIVEGRID_TENANT_ID")?.requiredInProduction).not.toBe(true);
expect(getEnvVariableDefinition("KWP_OAUTH_CLIENT_SECRET")?.kind).toBe("secret");
expect(getEnvVariableDefinition("KWP_OIDC_ISSUER")?.kind).toBe("url");
expect(getEnvVariableDefinition("KWP_OAUTH_REDIRECT_URI")).toBeUndefined();
});
test("catalogs the Web Push VAPID boundary without making it core-required", () => {
for (const key of ["WEB_PUSH_VAPID_SUBJECT", "WEB_PUSH_VAPID_PRIVATE_KEY"]) {
expect(getEnvVariableDefinition(key)).toMatchObject({ classification: "optional-provider", targets: ["worker"], source: "code-and-example" });
expect(getEnvVariableDefinition(key)?.requiredInProduction).not.toBe(true);
}
expect(getEnvVariableDefinition("WEB_PUSH_VAPID_PUBLIC_KEY")).toMatchObject({
classification: "optional-provider",
targets: ["web", "worker"],
source: "code-and-example",
requiredInProductionTargets: ["web"],
});
expect(getEnvVariableDefinition("WEB_PUSH_VAPID_PUBLIC_KEY")?.requiredInProduction).not.toBe(true);
expect(getEnvVariableDefinition("WEB_PUSH_VAPID_PRIVATE_KEY")?.kind).toBe("secret");
});
test("catalogs the Authentik JIT database boundary as a web-only secret", () => {
expect(getEnvVariableDefinition("AUTHENTIK_ADMIN_JIT_DATABASE_URL")).toMatchObject({
classification: "optional-provider",
targets: ["web"],
kind: "secret",
source: "code-and-example",
});
});
});
@@ -7,11 +7,21 @@ const webApiWorkerTargets = ["web", "api", "worker"] as const satisfies readonly
const webApiMcpWorkerTargets = ["web", "api", "mcp", "worker"] as const satisfies readonly RuntimeTarget[];
export const envVariableDefinitions = [
{
name: "I18N_ENABLED_LOCALES",
description: "Comma-separated product locales that may be selected at runtime.",
classification: "optional-provider",
targets: ["web", "api", "worker"],
kind: "string",
source: "code-and-example",
defaultValue: "de,en",
notes: "Must contain unique supported locale codes and always include de. Review-only locales are rejected in production until their release manifest is approved.",
},
{
name: "APP_NAME",
description: "Human-readable product name used in titles, metadata and seeded app configuration.",
classification: "required-core",
targets: allTargets,
targets: webApiWorkerTargets,
kind: "string",
source: "code-and-example",
requiredInProduction: true,
@@ -32,7 +42,66 @@ export const envVariableDefinitions = [
targets: allTargets,
kind: "database-url",
source: "code-and-example",
notes: "When unset (or empty), getReadDbClient() falls back to DATABASE_URL — single-DB dev / self-hosted setups remain functional without any code change. In staging/production point this at a streaming-replica or PgBouncer-fronted replica. See docs/architecture/rw-split.md.",
notes:
"When unset (or empty), getReadDbClient() falls back to DATABASE_URL — single-DB dev / self-hosted setups remain functional without any code change. In staging/production point this at a streaming-replica or PgBouncer-fronted replica. See docs/architecture/rw-split.md.",
},
{
name: "DATABASE_POOL_MAX",
description: "Hard maximum node-postgres connections per process and database client pool.",
classification: "optional-provider",
targets: allTargets,
kind: "string",
source: "code-and-example",
defaultValue: "10",
notes: "Applies separately to the primary and optional read-replica pools. URL connection_limit parameters are ignored by PrismaPg/node-postgres.",
},
{
name: "DATABASE_POOL_IDLE_TIMEOUT_MS",
description: "Idle timeout for primary and read-replica node-postgres connections.",
classification: "optional-provider",
targets: allTargets,
kind: "string",
source: "code-and-example",
defaultValue: "10000",
},
{
name: "DATABASE_POOL_CONNECTION_TIMEOUT_MS",
description: "Maximum time allowed to establish a primary or read-replica database connection.",
classification: "optional-provider",
targets: allTargets,
kind: "string",
source: "code-and-example",
defaultValue: "5000",
},
{
name: "RLS_RUNTIME_MODE",
description: "Postgres RLS startup enforcement mode: off, audit, or required.",
classification: "production-only",
targets: allTargets,
kind: "string",
source: "code-and-example",
notes:
"Defaults to required when NODE_ENV=production and off otherwise. Production services fail startup unless the runtime role and all expected forced policies are active.",
},
{
name: "DATABASE_RUNTIME_ROLE",
description: "Expected restricted Postgres role for application traffic.",
classification: "production-only",
targets: allTargets,
kind: "string",
source: "code-and-example",
defaultValue: "hivegrid_app",
notes:
"Must be a direct login role with NOSUPERUSER and NOBYPASSRLS. App/API/MCP use hivegrid_app; workers require a separate hivegrid_worker DATABASE_URL and set this value to hivegrid_worker. Migration credentials remain isolated in DIRECT_URL.",
},
{
name: "HIVEGRID_CLI_OPERATOR_USER_ID",
description: "Authenticated AdminUser identity bound by database-backed HiveGrid CLI commands.",
classification: "optional-provider",
targets: ["shared"],
kind: "string",
source: "code",
notes: "Required only for database-backed operator CLI commands; never replaces the restricted runtime database role.",
},
{
name: "SESSION_SECRET",
@@ -43,11 +112,38 @@ export const envVariableDefinitions = [
source: "code-and-example",
requiredInProduction: true,
},
{
name: "WEB_RUNTIME_SURFACE",
description: "Fail-closed web image runtime surface selector.",
classification: "production-only",
targets: ["web"],
kind: "string",
source: "code-and-example",
notes: "Must be core, admin, or portal. Production web runtimes require an explicit value.",
},
{
name: "PORTAL_SESSION_SECRET",
description: "Cookie/session signing secret used exclusively by the customer portal surface.",
classification: "production-only",
targets: ["web"],
kind: "secret",
source: "code-and-example",
},
{
name: "AUDIT_CHAIN_SECRET",
description: "HMAC secret for AuditEvent v2 hashes and retention checkpoints.",
classification: "production-only",
targets: webApiMcpWorkerTargets,
kind: "secret",
source: "code-and-example",
requiredInProduction: true,
notes: "Must contain at least 32 bytes and remain stable for the lifetime of retained audit evidence.",
},
{
name: "APP_BASE_DOMAIN",
description: "Root domain used to derive canonical app, admin and API hosts.",
classification: "required-core",
targets: allTargets,
targets: webApiWorkerTargets,
kind: "string",
source: "code-and-example",
requiredInProduction: true,
@@ -96,6 +192,27 @@ export const envVariableDefinitions = [
defaultValue: "api.localhost",
notes: "Local default is api.localhost.",
},
{
name: "PORTAL_APP_HOST",
description: "Canonical host for the isolated customer portal runtime surface.",
classification: "production-only",
targets: ["web", "worker"],
kind: "string",
source: "code-and-example",
defaultValue: "portal.localhost",
notes: "Required by production portal and core web runtimes so host boundaries fail closed; worker-mail uses it for customer status links.",
},
{
name: "PORTAL_CUSTOM_DOMAIN_RUNTIME_ENABLED",
description: "Explicit production runtime opt-in for customer-portal custom-domain administration and host routing.",
classification: "production-only",
targets: ["web"],
kind: "string",
source: "code",
defaultValue: "false",
notes:
"Must be exactly true on both staging web surfaces while the staging controller is active. Leave unset or false in production until its controller rollout is separately authorised.",
},
{
name: "APP_PROTOCOL",
description: "Canonical URL protocol for generated app, admin and API URLs.",
@@ -108,12 +225,25 @@ export const envVariableDefinitions = [
},
{
name: "CRYPTO_SECRET",
description: "AES secret for stored workflow credentials.",
description: "Shared AES master secret for tenant-envelope encryption across web, API and the mail worker.",
classification: "required-per-app",
targets: webApiTargets,
targets: webApiWorkerTargets,
kind: "secret",
source: "code-and-example",
requiredInProduction: true,
notes: "worker-mail must receive the exact same value as hivegrid-web so portal setup capabilities can be decrypted for delivery.",
},
{
name: "ADMIN_CONNECTION_MASTER_KEY",
description:
"Dedicated AES master secret for tenant-less platform-admin integration credentials.",
classification: "production-only",
targets: webApiWorkerTargets,
kind: "secret",
source: "code-and-example",
requiredInProduction: true,
notes:
"Use distinct staging and production values on web, API and worker; never reuse CRYPTO_SECRET or SESSION_SECRET.",
},
{
name: "API_ACCESS_TOKEN",
@@ -141,7 +271,8 @@ export const envVariableDefinitions = [
kind: "string",
source: "code-and-example",
defaultValue: "false",
notes: "Set to true only for a bounded migration window while validating pre-backfill API keys.",
notes:
"Secure default is false. Set true only for an explicitly approved, short migration window while validating pre-backfill API keys, then disable it again.",
},
{
name: "API_KEY_HASH_SECRET",
@@ -212,6 +343,16 @@ export const envVariableDefinitions = [
source: "code-and-example",
defaultValue: "10000",
},
{
name: "BILLING_MOLLIE_WEBHOOK_URL",
description: "Canonical public Mollie webhook URL used by the general worker for recurring invoice payments.",
classification: "optional-provider",
targets: ["worker"],
kind: "url",
source: "code-and-example",
notes:
"Required when billing provider side effects are enabled. Must be HTTPS and end exactly in /v1/billing/mollie/webhooks; use the environment-specific API host.",
},
{
name: "NODE_ENV",
description: "Runtime mode supplied by Node, React Router or deployment platform.",
@@ -358,7 +499,8 @@ export const envVariableDefinitions = [
targets: allTargets,
kind: "database-url",
source: "code-and-example",
notes: "Read by prisma.config.ts datasource. Required whenever DATABASE_URL points at PgBouncer (transaction pool mode breaks Migrate's prepared statements). Falls back to DATABASE_URL when unset.",
notes:
"Read by prisma.config.ts datasource. Required whenever DATABASE_URL points at PgBouncer (transaction pool mode breaks Migrate's prepared statements). Falls back to DATABASE_URL when unset.",
},
{
name: "SERVER_URL",
@@ -386,6 +528,107 @@ export const envVariableDefinitions = [
kind: "url",
source: "code-and-example",
},
{
name: "AIRCALL_CLIENT_ID",
description: "Aircall Technology Partner OAuth client identifier.",
classification: "optional-provider",
targets: ["web"],
kind: "string",
source: "code-and-example",
},
{
name: "AIRCALL_CLIENT_SECRET",
description: "Aircall Technology Partner OAuth client secret.",
classification: "optional-provider",
targets: ["web"],
kind: "secret",
source: "code-and-example",
},
{
name: "AIRCALL_REDIRECT_URI",
description: "Exact public Aircall OAuth callback URI registered for the current environment.",
classification: "optional-provider",
targets: ["web"],
kind: "url",
source: "code-and-example",
},
{
name: "AIRCALL_WEBHOOK_URL",
description: "Public Aircall webhook URL registered after a tenant authorizes the integration.",
classification: "optional-provider",
targets: ["web"],
kind: "url",
source: "code-and-example",
notes: "Must point to the API webhook route and use HTTPS outside local contract tests.",
},
{
name: "HALLOPETRA_WEBHOOK_URL",
description: "Public HiveGrid endpoint entered manually for HalloPetra post-call webhooks.",
classification: "optional-provider",
targets: ["web"],
kind: "url",
source: "code-and-example",
notes: "Must be the canonical API route and use HTTPS outside local contract tests.",
},
{
name: "KWP_OAUTH_CLIENT_ID",
description: "KWP Keycloak OAuth client identifier for the web connector.",
classification: "optional-provider",
targets: ["web"],
kind: "string",
source: "code-and-example",
notes: "The callback URI is derived from routing.protocol and routing.webAppHost; no redirect env key is used.",
},
{
name: "KWP_OAUTH_CLIENT_SECRET",
description: "KWP Keycloak OAuth client secret for the web connector.",
classification: "optional-provider",
targets: ["web"],
kind: "secret",
source: "code-and-example",
},
{
name: "KWP_OAUTH_SCOPES",
description: "Space-delimited OAuth scopes assigned to the KWP connector client.",
classification: "optional-provider",
targets: ["web"],
kind: "string",
source: "code-and-example",
},
{
name: "KWP_CUSTOMER_CODE",
description: "KWP customer code used for tenant relay discovery and authorization.",
classification: "optional-provider",
targets: ["web"],
kind: "string",
source: "code-and-example",
},
{
name: "KWP_OIDC_ISSUER",
description: "KWP Keycloak OIDC issuer URL used by the web connector.",
classification: "optional-provider",
targets: ["web"],
kind: "url",
source: "code-and-example",
},
{
name: "KWP_HIVEGRID_TENANT_ID",
description: "Exact tenant id allowed to use the environment-bound KWP pilot client.",
classification: "optional-provider",
targets: ["web", "worker"],
kind: "string",
source: "code-and-example",
notes: "Required by the KWP runtime flow and checked in addition to the kwp_integration entitlement.",
},
{
name: "KWP_MANDANT",
description: "Deprecated process-wide bnWin mandant setting; ignored by new KWP connections.",
classification: "optional-provider",
targets: ["web"],
kind: "string",
source: "code-and-example",
notes: "Leave unset. The setup flow stores an explicit selected or none binding inside each encrypted connection.",
},
{
name: "STORAGE_PROVIDER",
description: "Primary storage provider for runtime uploads.",
@@ -443,6 +686,17 @@ export const envVariableDefinitions = [
kind: "secret",
source: "code-and-example",
},
{
name: "GDPR_EXPORT_SSE_C_KEY_BASE64",
description: "Base64-encoded 32-byte SSE-C key for portal and privacy GDPR export artifacts.",
classification: "production-only",
targets: ["web", "worker"],
kind: "secret",
source: "code-and-example",
requiredInProductionTargets: ["web"],
notes:
"Required on both web runtime surfaces and conditionally on the dedicated GDPR export worker. Keep it server-only; rotation must wait until all 72-hour export artifacts have expired.",
},
{
name: "STORAGE_SESSION_TOKEN",
description: "Optional temporary session token for S3-compatible storage credentials.",
@@ -451,6 +705,87 @@ export const envVariableDefinitions = [
kind: "secret",
source: "code-and-example",
},
{
name: "WEB_STORAGE_ACCESS_KEY_ID",
description: "Host-side Compose access-key mapping for the core web storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the web container receives this value as STORAGE_ACCESS_KEY_ID.",
},
{
name: "WEB_STORAGE_SECRET_ACCESS_KEY",
description: "Host-side Compose secret-key mapping for the core web storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the web container receives this value as STORAGE_SECRET_ACCESS_KEY.",
},
{
name: "WEB_STORAGE_SESSION_TOKEN",
description: "Optional host-side Compose session-token mapping for the core web storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the web container receives this value as STORAGE_SESSION_TOKEN.",
},
{
name: "WORKER_GENERAL_STORAGE_ACCESS_KEY_ID",
description: "Host-side Compose access-key mapping for the general worker storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the general worker receives this value as STORAGE_ACCESS_KEY_ID.",
},
{
name: "WORKER_GENERAL_STORAGE_SECRET_ACCESS_KEY",
description: "Host-side Compose secret-key mapping for the general worker storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the general worker receives this value as STORAGE_SECRET_ACCESS_KEY.",
},
{
name: "WORKER_GENERAL_STORAGE_SESSION_TOKEN",
description: "Optional host-side Compose session-token mapping for the general worker storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the general worker receives this value as STORAGE_SESSION_TOKEN.",
},
{
name: "WORKER_IMPORT_STORAGE_ACCESS_KEY_ID",
description: "Host-side Compose access-key mapping for the import worker storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the import worker receives this value as STORAGE_ACCESS_KEY_ID.",
},
{
name: "WORKER_IMPORT_STORAGE_SECRET_ACCESS_KEY",
description: "Host-side Compose secret-key mapping for the import worker storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the import worker receives this value as STORAGE_SECRET_ACCESS_KEY.",
},
{
name: "WORKER_IMPORT_STORAGE_SESSION_TOKEN",
description: "Optional host-side Compose session-token mapping for the import worker storage principal.",
classification: "optional-provider",
targets: ["shared"],
kind: "secret",
source: "example",
notes: "Compose-only indirection; the import worker receives this value as STORAGE_SESSION_TOKEN.",
},
{
name: "STORAGE_PUBLIC_BASE_URL",
description: "Optional public CDN/base URL for storage object URLs.",
@@ -483,6 +818,43 @@ export const envVariableDefinitions = [
kind: "url",
source: "code-and-example",
},
{
name: "CLAMD_HOST",
description: "Mesh-only ClamAV daemon host used for synchronous and queued INSTREAM malware scans.",
classification: "optional-provider",
targets: webApiWorkerTargets,
kind: "string",
source: "code-and-example",
notes: "Required for untrusted uploads in production. Scanner failures reject uploads fail-closed.",
},
{
name: "CLAMD_PORT",
description: "ClamAV daemon TCP port used by INSTREAM scanning.",
classification: "optional-provider",
targets: webApiWorkerTargets,
kind: "string",
source: "code-and-example",
defaultValue: "3310",
},
{
name: "CLAMD_TIMEOUT_MS",
description: "Maximum time allowed for a ClamAV reachability check and malware scan.",
classification: "optional-provider",
targets: webApiWorkerTargets,
kind: "string",
source: "code-and-example",
defaultValue: "30000",
},
{
name: "SCAN_QUEUE_ENABLED",
description: "Enables the worker-backed asynchronous scan queue for stored private files.",
classification: "optional-provider",
targets: ["web", "worker"],
kind: "string",
source: "code-and-example",
defaultValue: "false",
notes: "Direct public asset uploads still require a synchronous clean ClamAV verdict.",
},
{
name: "MAILJET_WEBHOOK_SECRET",
description: "Shared secret for Basic-Auth authentication of inbound Mailjet event webhook attempts.",
@@ -490,7 +862,8 @@ export const envVariableDefinitions = [
targets: ["api"],
kind: "secret",
source: "code-and-example",
notes: "Inbound webhook secret only (used as the HTTP Basic-Auth password). Mailjet does not sign event webhooks, so the callback URL is configured as https://mailjet:SECRET@host/...; keep separate from the outbound MAILJET_API_KEY/MAILJET_SECRET_KEY pair.",
notes:
"Inbound webhook secret only (used as the HTTP Basic-Auth password). Mailjet does not sign event webhooks, so the callback URL is configured as https://mailjet:SECRET@host/...; keep separate from the outbound MAILJET_API_KEY/MAILJET_SECRET_KEY pair.",
},
{
name: "MAILJET_API_KEY",
@@ -706,11 +1079,13 @@ export const envVariableDefinitions = [
},
{
name: "CAPTCHA_FAIL_OPEN",
description: "When true (default), captcha verification fails open if the mCaptcha instance is unreachable.",
classification: "optional-provider",
description: "Local development/test escape hatch for captcha-provider outages. Deployed runtimes always fail closed.",
classification: "local-development-only",
targets: ["web"],
kind: "string",
source: "code-and-example",
defaultValue: "false",
notes: "Ignored unless NODE_ENV is development or test.",
},
{
name: "NOTIFICATIONS_NOVU_API_KEY",
@@ -720,6 +1095,34 @@ export const envVariableDefinitions = [
kind: "secret",
source: "code-and-example",
},
{
name: "WEB_PUSH_VAPID_SUBJECT",
description: "Public HTTPS or mailto contact identifier embedded in worker-generated VAPID assertions.",
classification: "optional-provider",
targets: ["worker"],
kind: "string",
source: "code-and-example",
notes: "Required together with both VAPID keys when the Web Push provider is wired; diagnostics may expose only the key name and validation state.",
},
{
name: "WEB_PUSH_VAPID_PUBLIC_KEY",
description: "URL-safe Base64 VAPID public key used by the worker provider and browser PushSubscription bootstrap.",
classification: "optional-provider",
targets: ["web", "worker"],
kind: "string",
source: "code-and-example",
requiredInProductionTargets: ["web"],
notes: "Generate once as a pair with WEB_PUSH_VAPID_PRIVATE_KEY and keep the pair stable across deployments.",
},
{
name: "WEB_PUSH_VAPID_PRIVATE_KEY",
description: "URL-safe Base64 VAPID private key used to sign worker Web Push requests.",
classification: "optional-provider",
targets: ["worker"],
kind: "secret",
source: "code-and-example",
notes: "Never log or expose this value; rotate only with an explicit PushSubscription migration plan.",
},
{
name: "WORKER_ENABLED",
description: "Opt-in flag that allows the standalone worker runtime to start queue processors.",
@@ -740,6 +1143,16 @@ export const envVariableDefinitions = [
defaultValue: "1",
notes: "Defaults to serial processing; must be a positive safe integer when provided.",
},
{
name: "WORKER_TENANT_SWEEP_CONCURRENCY",
description: "Bounded concurrency for active-tenant maintenance sweeps.",
classification: "optional-provider",
targets: ["worker"],
kind: "string",
source: "code-and-example",
defaultValue: "4",
notes: "Clamped by the worker runtime to protect Postgres and provider rate limits.",
},
{
name: "WORKER_QUEUE_GROUP",
description: "Worker queue group: one of general | mail | import | webhook | plugin. Required when WORKER_ENABLED=true.",
@@ -929,6 +1342,17 @@ export const envVariableDefinitions = [
defaultValue: "false",
notes: "Set to exactly true only with IMPORT_QUEUE_ENABLED=true after the worker runtime can process hivegrid.imports/hivegrid.exports end to end.",
},
{
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
description: "Internal opt-in for the import worker to consume only hivegrid.exports for portal and privacy GDPR artifacts.",
classification: "optional-provider",
targets: ["worker"],
kind: "string",
source: "code-and-example",
defaultValue: "false",
notes:
"Set to exactly true only on WORKER_QUEUE_GROUP=import while IMPORT_QUEUE_ENABLED and IMPORT_QUEUE_RUNTIME_READY are unset or false; requires complete STORAGE_* configuration.",
},
{
name: "OUTBOX_DISPATCHER_ENABLED",
description: "Master switch for the outbox dispatcher worker (transactional outbox pattern).",
@@ -1031,12 +1455,13 @@ export const envVariableDefinitions = [
},
{
name: "REDIS_URL",
description: "Fallback Redis connection URL for queue-backed web/API enqueue, MCP rate limits and worker processing.",
description: "Redis connection URL for MCP rate limits/readiness and fallback for queue-backed web/API/worker processing.",
classification: "optional-provider",
targets: webApiMcpWorkerTargets,
kind: "url",
source: "code",
notes: "Used when BULLMQ_REDIS_URL is absent for queue code and directly by shared-store runtimes such as MCP rate limiting.",
requiredInProductionTargets: ["web", "mcp"],
notes: "Required by web GDPR export download gates and MCP in production; used as a fallback when BULLMQ_REDIS_URL is absent for queue code.",
},
{
name: "CACHE_INVALIDATION_ENABLED",
@@ -1046,7 +1471,8 @@ export const envVariableDefinitions = [
kind: "string",
source: "code-and-example",
defaultValue: "true",
notes: "When false, two-tier caches stop publishing and subscribers are not started — replicas fall back to L1 TTL (CACHE_L1_TTL_SECONDS) as the only consistency mechanism. Use for emergency disable without redeploy. See docs/architecture/two-tier-cache.md.",
notes:
"When false, two-tier caches stop publishing and subscribers are not started — replicas fall back to L1 TTL (CACHE_L1_TTL_SECONDS) as the only consistency mechanism. Use for emergency disable without redeploy. See docs/architecture/two-tier-cache.md.",
},
{
name: "CACHE_L1_TTL_SECONDS",
@@ -1056,7 +1482,8 @@ export const envVariableDefinitions = [
kind: "string",
source: "code-and-example",
defaultValue: "300",
notes: "Acts as the safety-net when a pub/sub invalidation is missed (Redis disconnect, subscriber crash). Lower values mean fewer stale reads but more DB load.",
notes:
"Acts as the safety-net when a pub/sub invalidation is missed (Redis disconnect, subscriber crash). Lower values mean fewer stale reads but more DB load.",
},
{
name: "IDEMPOTENCY_BACKEND",
@@ -1066,7 +1493,8 @@ export const envVariableDefinitions = [
kind: "string",
source: "code-and-example",
defaultValue: "prisma",
notes: "Default 'prisma' keeps idempotency state in Postgres (already multi-replica-safe). Set 'shared-store' to back it with the SharedStore (Redis) instead — keeps the primary DB cooler, relies on Redis TTL for eviction. See apps/api/src/idempotency/shared-store-client.ts.",
notes:
"Default 'prisma' keeps idempotency state in Postgres (already multi-replica-safe). Set 'shared-store' to back it with the SharedStore (Redis) instead — keeps the primary DB cooler, relies on Redis TTL for eviction. See apps/api/src/idempotency/shared-store-client.ts.",
},
{
name: "BROWSER_RUNTIME_URL",
@@ -1135,28 +1563,13 @@ export const envVariableDefinitions = [
},
{
name: "GEOIP_DB_PATH",
description: "Filesystem path to the local DB-IP Lite Country MMDB for country-only GeoIP lookups (AD-22). Defaults to ./data/geoip/dbip-country-lite.mmdb.",
description:
"Filesystem path to the local DB-IP Lite Country MMDB for country-only GeoIP lookups (AD-22). Defaults to ./data/geoip/dbip-country-lite.mmdb.",
classification: "optional-provider",
targets: webApiWorkerTargets,
kind: "string",
source: "code",
},
{
name: "PORTAL_SERVER_URL",
description: "External portal server URL used by domain and portal integrations.",
classification: "optional-provider",
targets: webApiTargets,
kind: "url",
source: "code-and-example",
},
{
name: "PORTAL_SERVER_FLY_TOKEN",
description: "Fly token used by portal domain automation.",
classification: "optional-provider",
targets: webApiWorkerTargets,
kind: "secret",
source: "code-and-example",
},
{
name: "DEMO_USER",
description: "Local demo login hint in email:password format.",
@@ -1195,13 +1608,43 @@ export const envVariableDefinitions = [
},
{
name: "ALLOW_STAGING_DEMO_SEED",
description: "Guard that permits CRM SaaS demo seeding and demo login on the disposable staging environment.",
description: "Guard that permits CRM SaaS demo seeding on the disposable staging environment.",
classification: "production-only",
targets: ["web"],
kind: "string",
source: "code",
defaultValue: "false",
notes: "Set only on staging resources together with SEED_DEMO_DATA=true; never enable on production resources.",
notes: "Seeding only. The demo LOGIN gate is STAGING_DEMO_LOGIN_ENABLED — a SEED_*-shaped key cannot live on a runtime resource.",
},
{
name: "STAGING_DEMO_LOGIN_ENABLED",
description: "Runtime gate that lets the seeded staging demo accounts sign in. Independent of any seeding flag.",
classification: "production-only",
targets: ["web"],
kind: "string",
source: "code",
defaultValue: "false",
notes:
"Only takes effect together with SENTRY_ENVIRONMENT=staging, so it cannot unlock a demo account in production. Deliberately not SEED_*-prefixed: the RLS deploy contract rejects those keys on runtime resources.",
},
{
name: "SEED_DEMO_PRO_MANAGED",
description: "Marks demo-pro-crm as owned by the comprehensive staging seed so the legacy boot demo seed leaves that tenant untouched.",
classification: "production-only",
targets: ["web"],
kind: "string",
source: "code",
defaultValue: "false",
notes: "Set only on the staging web resource; never enable on production resources. Starter and Business boot demo tenants remain unchanged.",
},
{
name: "SEED_DEMO_USER_PASSWORD",
description: "One-off password applied to the synthetic demo-pro-crm users by the comprehensive staging seed.",
classification: "production-only",
targets: ["shared"],
kind: "secret",
source: "code",
notes: "Operator-supplied staging-only secret. The deploy workflow must never create or overwrite it; never set it on production or expose it in logs.",
},
{
name: "SITE_KEY_*",
@@ -1470,7 +1913,8 @@ export const envVariableDefinitions = [
targets: apiWorkerTargets,
kind: "string",
source: "code-and-example",
notes: "Used to attach OTLP auth tokens (e.g. `x-sentry-auth=Sentry sentry_key=<key>`). Values are sent in cleartext; supply only via deploy-secret stores.",
notes:
"Used to attach OTLP auth tokens (e.g. `x-sentry-auth=Sentry sentry_key=<key>`). Values are sent in cleartext; supply only via deploy-secret stores.",
},
{
name: "OTEL_TRACES_SAMPLER",
@@ -1479,7 +1923,8 @@ export const envVariableDefinitions = [
targets: apiWorkerTargets,
kind: "string",
source: "code-and-example",
notes: "The runtime always wraps the configured sampler in ParentBasedSampler(TraceIdRatioBasedSampler(arg)); this var is exposed only for diagnostic override.",
notes:
"The runtime always wraps the configured sampler in ParentBasedSampler(TraceIdRatioBasedSampler(arg)); this var is exposed only for diagnostic override.",
},
{
name: "OTEL_TRACES_SAMPLER_ARG",
@@ -1506,7 +1951,8 @@ export const envVariableDefinitions = [
targets: ["web"],
kind: "string",
source: "code-and-example",
notes: "When unset, apps/web/app/otel.client.ts is a no-op. Companion to OTEL_EXPORTER_OTLP_ENDPOINT (server-side). The endpoint must be CORS-reachable from the browser and rate-limited at the gateway.",
notes:
"When unset, apps/web/app/otel.client.ts is a no-op. Companion to OTEL_EXPORTER_OTLP_ENDPOINT (server-side). The endpoint must be CORS-reachable from the browser and rate-limited at the gateway.",
},
{
name: "VITE_OTEL_SERVICE_NAME",
@@ -1619,7 +2065,8 @@ export const envVariableDefinitions = [
},
{
name: "METRICS_TOKEN",
description: "Bearer token for /metrics endpoints. Must be the same string across api, worker and web in a single deployment so one Prometheus job can scrape all three.",
description:
"Bearer token for /metrics endpoints. Must be the same string across api, worker and web in a single deployment so one Prometheus job can scrape all three.",
classification: "optional-provider",
targets: ["web", "api", "worker"],
kind: "secret",
@@ -1814,7 +2261,8 @@ export const envVariableDefinitions = [
targets: webApiWorkerTargets,
kind: "url",
source: "code-and-example",
notes: "When unset the app keeps SQL fallback search semantics. Production should use an internal-only Meilisearch URL.",
notes:
"When unset the app keeps SQL fallback search semantics. Production should use an internal-only Meilisearch URL. Required on worker-general when tenant hard-delete runs in production, required-RLS, or staging/production Sentry mode.",
},
{
name: "MEILI_API_KEY",
@@ -1823,7 +2271,8 @@ export const envVariableDefinitions = [
targets: webApiWorkerTargets,
kind: "secret",
source: "code-and-example",
notes: "Never expose to browsers. Scoped to the SaaS index prefix (e.g. hivegrid-*), minted from the master key per infra STANDARDS §4. Local docker-compose may use the documented dev key.",
notes:
"Never expose to browsers. Scoped to the SaaS index prefix (e.g. hivegrid-*), minted from the master key per infra STANDARDS §4. Local docker-compose may use the documented dev key. Required on worker-general when tenant hard-delete runs in production, required-RLS, or staging/production Sentry mode.",
},
{
name: "MEILI_ENV",
@@ -1863,7 +2312,8 @@ export const envVariableDefinitions = [
kind: "string",
source: "code-and-example",
defaultValue: "false",
notes: "Set to true only after the external plugin runtime security sign-off is complete; production plugin lifecycle and worker paths fail closed otherwise.",
notes:
"Set to true only after the external plugin runtime security sign-off is complete; production plugin lifecycle and worker paths fail closed otherwise.",
},
{
name: "PLUGIN_TRUSTED_PUBLIC_KEYS",
@@ -2012,34 +2462,35 @@ export const envVariableDefinitions = [
defaultValue: "120",
},
{
name: "PLUGIN_RATE_LIMIT_FAIL_OPEN",
description: "Local-only escape hatch that allows plugin install/settings writes when rate-limit storage is unavailable outside production.",
classification: "local-development-only",
targets: ["web"],
name: "PLATFORM_LEADS_INGRESS_ENABLED",
description: "Fail-closed runtime switch for POST /v1/platform/leads.",
classification: "production-only",
targets: ["api"],
kind: "string",
source: "code-and-example",
defaultValue: "false",
notes: "Ignored in production: plugin install/settings writes always fail closed when rate-limit storage is unavailable.",
defaultValue: "true",
notes:
"Set to false, 0, or off to return a neutral 404 before source authentication or writes. This is an ingress safety switch for external lead capture; the authenticated admin Sales workspace remains available by permission.",
},
{
name: "MARKETING_ALLOWED_ORIGINS",
description: "CSV of origins (with *.host wildcards) allowed to POST to /api/leads/capture (Phase 05 #78).",
description: "Deprecated CORS allowlist for the retired /api/leads/capture 410 response.",
classification: "optional-provider",
targets: ["web"],
kind: "string",
source: "code-and-example",
notes:
"Fail-closed: empty value rejects all browser submissions. Wildcard form is 'https://*.example.com' which matches single subdomain levels only. Server-to-server bots can spoof Origin — the per-IP rate-limit + optional Turnstile cover that gap. See docs/features/marketing-funnel.md.",
"R-LEADS retired browser capture and removed marketing.js. This value no longer authorizes a write; it only lets known old origins read the structured 410 drain response. Remove it after the documented drain window.",
},
{
name: "MARKETING_RATE_LIMIT_PER_MIN",
description: "Per-IP sliding-window submission limit for /api/leads/capture (Phase 05 #78).",
description: "Deprecated, ignored rate-limit key from the retired browser lead-capture endpoint.",
classification: "optional-provider",
targets: ["web"],
kind: "string",
source: "code-and-example",
notes:
"Defaults to 5. The per-email limit is hard-coded to 1/min and acts as a second-layer dedupe to avoid LeadEvent flooding. Lower (e.g. 2) for high-spam regions; raise (e.g. 30) for shared corporate NAT environments.",
"No active runtime reads this key. Keep only while cleaning existing environment inventories; native /v1/platform/leads uses source and pre-auth ingress limits.",
},
{
name: "LEAD_CONVERSION_SECRET",
@@ -2071,6 +2522,39 @@ export const envVariableDefinitions = [
notes:
"Set to 'false' to halt outbound webhook dispatch (Slack, Discord, Mailchimp, HubSpot, Brevo, custom). Outbox rows accumulate while disabled and resume on re-enable — raise the outbox retention TTL if you plan a multi-day pause.",
},
{
name: "ADMIN_EMAIL_EVENT_WEBHOOK_SECRET",
description:
"HMAC secret for normalized Admin Sales delivery and bounce events.",
classification: "optional-provider",
targets: ["api"],
kind: "secret",
source: "code-and-example",
notes:
"Min 32 bytes. Provider adapters sign timestamp plus exact body; rotation invalidates in-flight deliveries.",
},
{
name: "ADMIN_EMAIL_BCC_CAPABILITY_SECRET",
description:
"HMAC secret for signed, rotatable Admin Sales BCC recipient capabilities.",
classification: "optional-provider",
targets: ["api", "web"],
kind: "secret",
source: "code-and-example",
notes:
"Min 32 bytes. This is independent from Mailjet webhook authentication; rotating it invalidates generated BCC addresses after their database rows are archived.",
},
{
name: "ADMIN_EMAIL_BCC_INBOUND_DOMAIN",
description:
"Dedicated inbound domain receiving signed Admin Sales BCC copies.",
classification: "optional-provider",
targets: ["api", "web"],
kind: "string",
source: "code-and-example",
notes:
"Defaults to bcc.<APP_BASE_DOMAIN>. Configure the provider catch-all and MX only for this dedicated host.",
},
{
name: "MARKETING_TOKEN_SECRET",
description: "HMAC secret signing unsubscribe tokens for sequence emails (Phase 05 #80).",
@@ -2101,6 +2585,16 @@ export const envVariableDefinitions = [
notes:
"Must match between the web app and the hocuspocus container. Min 32 bytes of entropy. When unset, the hocuspocus container refuses to boot and the web token endpoint returns 503 — single-user editor mode stays functional. See docs/features/realtime-collab.md.",
},
{
name: "CHAT_GATEWAY_AUTH_SECRET",
description: "Dedicated HS256 secret for short-lived Team Chat WebSocket identity tokens.",
classification: "optional-provider",
targets: ["web", "api"],
kind: "secret",
source: "code-and-example",
notes:
"Must match between web and API, contain at least 32 bytes of entropy, and must not be reused for Hocuspocus or another audience. Missing or weak configuration disables only the Team Chat realtime connection.",
},
{
name: "VITE_HOCUSPOCUS_URL",
description: "Browser-visible WebSocket URL for the Hocuspocus server (Phase 05 #59).",
@@ -2149,7 +2643,8 @@ export const envVariableDefinitions = [
kind: "string",
source: "code-and-example",
defaultValue: "10485760",
notes: "Defaults to 10 MiB. Acts as a guard against runaway Y.js state-bloat — the snapshot/compaction strategy (deferred follow-up) reduces real-world state size below this limit.",
notes:
"Defaults to 10 MiB. Acts as a guard against runaway Y.js state-bloat — the snapshot/compaction strategy (deferred follow-up) reduces real-world state size below this limit.",
},
// ------------------------------------------------------------------
// Admin-Panel SSO via Authentik (Phase 09 #82 — admin-oidc-login.md).
@@ -2184,6 +2679,16 @@ export const envVariableDefinitions = [
source: "code-and-example",
notes: "Fetched from the Authentik admin UI after the blueprint applies. Rotate via Authentik then redeploy the web service.",
},
{
name: "AUTHENTIK_ADMIN_JIT_DATABASE_URL",
description: "PostgreSQL URL for the execute-only Authentik Admin JIT callback capability.",
classification: "optional-provider",
targets: ["web"],
kind: "secret",
source: "code-and-example",
notes:
"Must authenticate as hivegrid_authentik_jit. Configure it together with Admin SSO only after the role provisioner has installed the dedicated login.",
},
{
name: "AUTHENTIK_ADMIN_REDIRECT_URI",
description: "Exact OAuth callback URI registered with the Authentik admin-panel provider (Phase 09 #82).",
@@ -2210,7 +2715,8 @@ export const envVariableDefinitions = [
kind: "string",
source: "code-and-example",
defaultValue: "false",
notes: "When false (default) the admin login page hides the password form entirely. Flip to true only when Authentik is unreachable; pair with a tight ADMIN_FALLBACK_LOGIN_EMAILS allowlist.",
notes:
"When false (default) the admin login page hides the password form entirely. Flip to true only when Authentik is unreachable; pair with a tight ADMIN_FALLBACK_LOGIN_EMAILS allowlist.",
},
{
name: "ADMIN_FALLBACK_LOGIN_EMAILS",
@@ -14,9 +14,11 @@ const scannedProductionFiles = [
"packages/queue/src/connection.ts",
"packages/mail/src/mailjet.ts",
"packages/config/src/api.ts",
"packages/config/src/kwp.ts",
"packages/config/src/web.ts",
"packages/config/src/worker.ts",
"packages/config/src/routing.ts",
"packages/config/src/shared-redis.ts",
] as const;
const providerBoundaryFiles = new Set<string>([
@@ -25,9 +27,11 @@ const providerBoundaryFiles = new Set<string>([
"apps/worker/src/health.ts",
"packages/queue/src/connection.ts",
"packages/config/src/api.ts",
"packages/config/src/kwp.ts",
"packages/config/src/web.ts",
"packages/config/src/worker.ts",
"packages/config/src/routing.ts",
"packages/config/src/shared-redis.ts",
]);
const packageEnvReadBaseline = new Set<string>([
@@ -36,7 +40,9 @@ const packageEnvReadBaseline = new Set<string>([
"packages/cli/src/commands/tenant/list-snapshots.ts",
"packages/cli/src/commands/tenant/restore.ts",
"packages/config/src/api.ts",
"packages/config/src/kwp.ts",
"packages/config/src/routing.ts",
"packages/config/src/shared-redis.ts",
"packages/config/src/web.ts",
"packages/config/src/worker.ts",
"packages/db/src/client.server.ts",
@@ -4,9 +4,10 @@ import { describe, expect, test } from "vitest";
import { getEnvVariableDefinition, getRequiredEnvVariableNames, listEnvVariables, validateEnv } from "./index.js";
const representativeDefinitions = {
APP_NAME: { classification: "required-core", targets: ["shared", "web", "api", "mcp", "worker"], source: "code-and-example" },
APP_NAME: { classification: "required-core", targets: ["web", "api", "worker"], source: "code-and-example" },
DATABASE_URL: { classification: "required-core", targets: ["shared", "web", "api", "mcp", "worker"], source: "code-and-example" },
SESSION_SECRET: { classification: "required-core", targets: ["web", "api"], source: "code-and-example" },
AUDIT_CHAIN_SECRET: { classification: "production-only", targets: ["web", "api", "mcp", "worker"], source: "code-and-example" },
API_ACCESS_TOKEN: { classification: "required-per-app", targets: ["web", "api"], source: "code-and-example" },
JWT_SECRET: { classification: "required-per-app", targets: ["web", "api"], source: "code-and-example" },
ANALYTICS_TOKEN: { classification: "required-per-app", targets: ["api"], source: "code" },
@@ -94,6 +95,7 @@ describe("env access inventory contract", () => {
"WORKFLOW_TRIGGER_EXECUTOR_URL",
"OUTBOX_DISPATCHER_REQUIRED",
"WORKFLOW_TRIGGER_OUTBOX_REQUIRED",
"CRYPTO_SECRET",
"BULLMQ_REDIS_URL",
"REDIS_URL",
"BROWSER_RUNTIME_URL",
@@ -115,6 +117,10 @@ describe("env access inventory contract", () => {
expect(getRequiredEnvVariableNames({ target: "worker", nodeEnv: "production" })).not.toEqual(
expect.arrayContaining(["WORKER_ENABLED", "BULLMQ_REDIS_URL", "REDIS_URL", "SITE_KEY_*"])
);
expect(getRequiredEnvVariableNames({ target: "mcp", nodeEnv: "production" })).not.toContain("APP_NAME");
expect(getRequiredEnvVariableNames({ target: "mcp", nodeEnv: "production" })).toEqual(
expect.arrayContaining(["DATABASE_URL", "REDIS_URL"])
);
});
test("validates missing required env values deterministically without reading process.env", () => {
@@ -139,10 +145,13 @@ describe("env access inventory contract", () => {
APP_BASE_DOMAIN: "example.com",
APP_NAME: "HiveGrid",
CRYPTO_SECRET: "crypto-secret",
ADMIN_CONNECTION_MASTER_KEY:
"admin-connection-master-key-value",
DATABASE_URL: "postgresql://user:pass@localhost:5432/app",
JWT_SECRET: "jwt-secret",
SESSION_SECRET: "session-secret",
ANALYTICS_TOKEN: "analytics-token",
AUDIT_CHAIN_SECRET: "audit-chain-secret-value-with-at-least-32-characters",
WEB_APP_HOST: "app.example.com",
},
{ target: "api", nodeEnv: "production" }
@@ -166,7 +175,7 @@ describe("env access inventory contract", () => {
test("locks stable inventory wording for S05/S06 owners and dynamic/fallback key semantics", () => {
expect(followUpMapping).toContain("| S05 docs | Example and documentation alignment, fallback wording, deprecated/example-only cleanup |");
expect(followUpMapping).toContain("`BULLMQ_REDIS_URL` as primary");
expect(followUpMapping).toContain("`REDIS_URL` as fallback only when `BULLMQ_REDIS_URL` is absent");
expect(followUpMapping).toContain("`REDIS_URL` as the required MCP shared-store URL and queue fallback");
expect(followUpMapping).toContain("| S06 enforcement | Future direct-read guardrails and drift tests |");
expect(followUpMapping).toContain("Prefix support for `SITE_KEY_*`");
expect(followUpMapping).toContain("CORS-origin catalog drift checks for `WEB_ORIGIN` and `ADMIN_ORIGIN`");
@@ -174,7 +183,7 @@ describe("env access inventory contract", () => {
expect(sourceAccessTable).toContain("| `BULLMQ_REDIS_URL` |");
expect(sourceAccessTable).toContain("Primary BullMQ Redis URL for web/API enqueue and worker queues");
expect(sourceAccessTable).toContain("| `REDIS_URL` |");
expect(sourceAccessTable).toContain("BullMQ fallback only when `BULLMQ_REDIS_URL` is absent");
expect(sourceAccessTable).toContain("Required by MCP in production and a BullMQ fallback elsewhere");
expect(sourceAccessTable).toContain("| `SITE_KEY_*` |");
expect(sourceAccessTable).toContain("Must be matched by prefix, not enumerated as one literal key");
expect(sourceAccessTable).toContain("| `WEB_ORIGIN` |");
@@ -99,7 +99,20 @@ describe("env example drift contract", () => {
});
test("keeps platform and runtime keys explicitly cataloged", () => {
for (const key of ["NODE_ENV", "PORT", "HOST", "WORKER_ENABLED", "BULLMQ_REDIS_URL", "REDIS_URL", "BROWSER_RUNTIME_URL", "BROWSER_RUNTIME_API_KEY", "BROWSER_SESSION_TIMEOUT_MS"]) {
for (const key of [
"NODE_ENV",
"PORT",
"HOST",
"WEB_RUNTIME_SURFACE",
"PORTAL_APP_HOST",
"PORTAL_SESSION_SECRET",
"WORKER_ENABLED",
"BULLMQ_REDIS_URL",
"REDIS_URL",
"BROWSER_RUNTIME_URL",
"BROWSER_RUNTIME_API_KEY",
"BROWSER_SESSION_TIMEOUT_MS",
]) {
expect(catalogNames.has(key), `${key} must be an explicit catalog entry, not an example-only exemption`).toBe(true);
}
});
@@ -118,6 +131,9 @@ describe("env example drift contract", () => {
"WEB_APP_HOST",
"ADMIN_APP_HOST",
"API_HOST",
"WEB_RUNTIME_SURFACE",
"PORTAL_APP_HOST",
"PORTAL_SESSION_SECRET",
"API_ACCESS_TOKEN",
"JWT_SECRET",
"MAILJET_API_KEY",
@@ -134,6 +150,31 @@ describe("env example drift contract", () => {
);
expect(keys).not.toEqual(expect.arrayContaining(["CRISP_CHAT_WEBSITE_ID"]));
expect(contents).not.toContain("CRISP_CHAT_WEBSITE_ID");
expect(contents).not.toContain("PORTAL_SERVER_URL");
expect(contents).not.toContain("PORTAL_SERVER_FLY_TOKEN");
});
test("documents the production core/portal split without enabling the portal secret globally", () => {
const path = ".env.production.example";
const contents = readProjectFile(path);
const keys = parseEnvExampleKeys(contents);
const requiredKeys = parseUncommentedEnvExampleKeys(contents);
expect(keys).toEqual(expect.arrayContaining(["WEB_RUNTIME_SURFACE", "PORTAL_APP_HOST", "PORTAL_SESSION_SECRET"]));
expect(requiredKeys).toEqual(expect.arrayContaining(["WEB_RUNTIME_SURFACE", "PORTAL_APP_HOST"]));
expect(requiredKeys, `${path} must keep the portal-only secret commented`).not.toContain("PORTAL_SESSION_SECRET");
expect(contents).not.toContain("PORTAL_SERVER_URL");
expect(contents).not.toContain("PORTAL_SERVER_FLY_TOKEN");
});
test("documents optional KWP OAuth inputs without a redirect override", () => {
const kwpKeys = ["KWP_OAUTH_CLIENT_ID", "KWP_OAUTH_CLIENT_SECRET", "KWP_OAUTH_SCOPES", "KWP_CUSTOMER_CODE", "KWP_OIDC_ISSUER", "KWP_HIVEGRID_TENANT_ID", "KWP_MANDANT"];
for (const path of [".env.example", ".env.local.example", ".env.production.example"]) {
const contents = readProjectFile(path);
expect(parseEnvExampleKeys(contents), path).toEqual(expect.arrayContaining(kwpKeys));
expect(contents, path).not.toContain("KWP_OAUTH_REDIRECT_URI");
}
});
test("documents worker runtime keys in .env.production.example without required REDIS_URL", () => {
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { normalizeGdprExportSseCKey, requireGdprExportSseCKey } from "./gdpr-export-storage.js";
const KEY = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=";
describe("GDPR export SSE-C key", () => {
it("accepts only canonical base64 encoding of exactly 32 bytes", () => {
expect(normalizeGdprExportSseCKey(` ${KEY} `)).toBe(KEY);
expect(normalizeGdprExportSseCKey(Buffer.alloc(31, 7).toString("base64"))).toBeUndefined();
expect(normalizeGdprExportSseCKey("not-base64")).toBeUndefined();
});
it("never echoes an invalid key", () => {
const invalid = "secret-that-must-not-appear";
expect(() => requireGdprExportSseCKey(invalid)).toThrow(/GDPR_EXPORT_SSE_C_KEY_BASE64/u);
try {
requireGdprExportSseCKey(invalid);
} catch (error) {
expect(String(error)).not.toContain(invalid);
}
});
});
@@ -0,0 +1,28 @@
const GDPR_EXPORT_SSE_C_KEY_BYTES = 32;
const CANONICAL_BASE64_32_BYTES = /^[A-Za-z0-9+/]{43}=$/u;
// Shared by the bounded writers and the server-side download proxy. Writers
// must never publish an artifact that its web surface cannot deliver.
export const PORTAL_GDPR_EXPORT_MAX_BYTES = 16 * 1024 * 1024;
export const PRIVACY_GDPR_EXPORT_MAX_BYTES = 32 * 1024 * 1024;
/**
* Normalize the customer-provided AES-256 key used for GDPR export objects.
* The value is intentionally opaque: diagnostics must never echo it.
*/
export function normalizeGdprExportSseCKey(value: string | undefined): string | undefined {
const normalized = value?.trim();
if (!normalized || !CANONICAL_BASE64_32_BYTES.test(normalized)) return undefined;
const decoded = Buffer.from(normalized, "base64");
if (decoded.byteLength !== GDPR_EXPORT_SSE_C_KEY_BYTES || decoded.toString("base64") !== normalized) return undefined;
return normalized;
}
export function requireGdprExportSseCKey(value: string | undefined): string {
const normalized = normalizeGdprExportSseCKey(value);
if (!normalized) {
throw new Error("GDPR_EXPORT_SSE_C_KEY_BASE64 must be canonical base64 encoding of exactly 32 random bytes.");
}
return normalized;
}
@@ -1,14 +1,19 @@
import { envVariableDefinitions } from "./catalog.js";
export { getDomainRoutingConfig, hostMatches, normalizeHost } from "./routing.js";
export { getDomainRoutingConfig, hostMatches, normalizeHost, normalizeHostForProtocol } from "./routing.js";
export { ApiConfigError, loadApiConfig, loadRequiredApiConfig } from "./api.js";
export { WebConfigError, loadRequiredWebConfig, loadWebConfig } from "./web.js";
export { resolveApiSessionCookiePolicy, resolveSessionCookiePolicy } from "./session-cookie.js";
export { normalizeGdprExportSseCKey, PORTAL_GDPR_EXPORT_MAX_BYTES, PRIVACY_GDPR_EXPORT_MAX_BYTES, requireGdprExportSseCKey } from "./gdpr-export-storage.js";
export { resolveApiSessionCookiePolicy, resolveHostOnlyCookiePolicy, resolveSessionCookiePolicy, resolveWebSessionCookiePolicy } from "./session-cookie.js";
export type { ResolveHostOnlyCookiePolicyOptions, ResolveWebSessionCookiePolicyOptions, WebSessionCookieSurface } from "./session-cookie.js";
export { WorkerConfigError, loadRequiredWorkerConfig, loadWorkerConfig } from "./worker.js";
export { resolvePluginLifecycleRuntimeEnv } from "./plugin-lifecycle.js";
export { resolveKwpRuntimeEnv } from "./kwp.js";
export { resolveSharedRedisUrl } from "./shared-redis.js";
export { validateBooleanFlag, validateOptionalSecretString, validateOptionalSecretUrl, validateRequiredSecretString } from "./secret-validator.js";
import type { EnvClassification, EnvRecord, EnvValidationOptions, EnvValidationResult, EnvVariableDefinition, RuntimeTarget } from "./types.js";
export type { DomainRoutingConfig, DomainRoutingEnv } from "./routing.js";
export type { PluginLifecycleRuntimeEnv } from "./plugin-lifecycle.js";
export type { KwpRuntimeEnv } from "./kwp.js";
export type { ResolveApiSessionCookiePolicyOptions, ResolveSessionCookiePolicyOptions, SessionCookiePolicy, SessionCookieSameSite } from "./session-cookie.js";
const definitions: readonly EnvVariableDefinition[] = envVariableDefinitions;
@@ -49,6 +54,7 @@ export type {
WebConfigResult,
WebConfigRouting,
WebConfigStorage,
WebRuntimeSurface,
EnvAuditSource,
EnvClassification,
EnvRecord,
@@ -112,12 +118,15 @@ export function getRequiredEnvVariableNames(options: EnvValidationOptions = {})
continue;
}
if ((definition.classification === "required-core" || definition.classification === "required-per-app") && !(nodeEnv !== "production" && definition.defaultValue)) {
if (
(definition.classification === "required-core" || definition.classification === "required-per-app") &&
!(nodeEnv !== "production" && definition.defaultValue)
) {
required.add(definition.name);
continue;
}
if (nodeEnv === "production" && definition.requiredInProduction) {
if (nodeEnv === "production" && (definition.requiredInProduction || definition.requiredInProductionTargets?.includes(target))) {
required.add(definition.name);
continue;
}
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { resolveKwpRuntimeEnv } from "./kwp.js";
describe("resolveKwpRuntimeEnv", () => {
it("normalizes the KWP pilot tenant id", () => {
expect(resolveKwpRuntimeEnv({ KWP_HIVEGRID_TENANT_ID: " tenant-1 " })).toEqual({
hiveGridTenantId: "tenant-1",
});
});
it("omits an empty KWP pilot tenant id", () => {
expect(resolveKwpRuntimeEnv({ KWP_HIVEGRID_TENANT_ID: " " })).toEqual({});
});
});
@@ -0,0 +1,11 @@
import type { EnvRecord } from "./types.js";
export type KwpRuntimeEnv = {
readonly hiveGridTenantId?: string;
};
/** Central env boundary for KWP runtime gates shared by web and workers. */
export function resolveKwpRuntimeEnv(env: EnvRecord = process.env): KwpRuntimeEnv {
const hiveGridTenantId = env.KWP_HIVEGRID_TENANT_ID?.trim();
return hiveGridTenantId ? { hiveGridTenantId } : {};
}
@@ -8,6 +8,7 @@ describe("getDomainRoutingConfig non-local subdomain derivation", () => {
webAppHost: "app.example.com:8443",
adminAppHost: "admin.example.com:8443",
apiHost: "api.example.com:8443",
portalAppHost: "portal.example.com:8443",
protocol: "https",
});
});
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { getDomainRoutingConfig, hostMatches, normalizeHost } from "./routing.js";
import { getDomainRoutingConfig, hostMatches, normalizeHost, normalizeHostForProtocol } from "./routing.js";
describe("routing config", () => {
test("uses local subdomain defaults", () => {
@@ -8,6 +8,7 @@ describe("routing config", () => {
webAppHost: "app.localhost",
adminAppHost: "admin.localhost",
apiHost: "api.localhost",
portalAppHost: "portal.localhost",
protocol: "http",
});
});
@@ -17,12 +18,21 @@ describe("routing config", () => {
webAppHost: "app.localhost:3000",
adminAppHost: "admin.localhost:3000",
apiHost: "api.localhost:3000",
portalAppHost: "portal.localhost:3000",
});
});
test("normalizes explicit hosts", () => {
expect(normalizeHost("https://APP.example.com/path")).toBe("app.example.com");
expect(hostMatches("https://app.example.com", "app.example.com")).toBe(true);
expect(normalizeHostForProtocol("APP.example.com:443", "https")).toBe("app.example.com");
expect(normalizeHostForProtocol("APP.example.com:80", "http")).toBe("app.example.com");
expect(normalizeHostForProtocol("APP.example.com:8443", "https")).toBe("app.example.com:8443");
});
test("fails closed for malformed hosts", () => {
expect(normalizeHost("[malformed-host")).toBeUndefined();
expect(hostMatches("[malformed-host", "app.localhost")).toBe(false);
});
test("uses explicit app, admin, api, base domain, and protocol hosts", () => {
@@ -32,6 +42,7 @@ describe("routing config", () => {
WEB_APP_HOST: "https://APP.example.com/ignored/path",
ADMIN_APP_HOST: "ADMIN.example.com:8443",
API_HOST: "https://API.example.com/v1",
PORTAL_APP_HOST: "PORTAL.example.com",
APP_PROTOCOL: "http",
})
).toEqual({
@@ -39,6 +50,7 @@ describe("routing config", () => {
webAppHost: "app.example.com",
adminAppHost: "admin.example.com:8443",
apiHost: "api.example.com",
portalAppHost: "portal.example.com",
protocol: "http",
});
});
@@ -49,6 +61,27 @@ describe("routing config", () => {
webAppHost: "app.example.com",
adminAppHost: "admin.example.com",
apiHost: "api.example.com",
portalAppHost: "portal.example.com",
protocol: "https",
});
});
test("removes protocol-default ports from routed production hosts", () => {
expect(
getDomainRoutingConfig({
APP_BASE_DOMAIN: "example.com:443",
WEB_APP_HOST: "app.example.com:443",
ADMIN_APP_HOST: "admin.example.com:443",
API_HOST: "api.example.com:443",
PORTAL_APP_HOST: "portal.example.com:443",
APP_PROTOCOL: "https",
})
).toEqual({
appBaseDomain: "example.com",
webAppHost: "app.example.com",
adminAppHost: "admin.example.com",
apiHost: "api.example.com",
portalAppHost: "portal.example.com",
protocol: "https",
});
});
@@ -3,6 +3,7 @@ export type DomainRoutingEnv = Record<string, string | undefined> & {
WEB_APP_HOST?: string;
ADMIN_APP_HOST?: string;
API_HOST?: string;
PORTAL_APP_HOST?: string;
APP_PROTOCOL?: string;
NODE_ENV?: string;
};
@@ -12,6 +13,7 @@ export type DomainRoutingConfig = {
webAppHost: string;
adminAppHost: string;
apiHost: string;
portalAppHost: string;
protocol: "http" | "https";
};
@@ -19,17 +21,21 @@ const LOCAL_BASE_DOMAIN = "localhost";
const LOCAL_WEB_APP_HOST = "app.localhost";
const LOCAL_ADMIN_APP_HOST = "admin.localhost";
const LOCAL_API_HOST = "api.localhost";
const LOCAL_PORTAL_APP_HOST = "portal.localhost";
export function getDomainRoutingConfig(env: DomainRoutingEnv = process.env): DomainRoutingConfig {
const appBaseDomain = normalizeHost(env.APP_BASE_DOMAIN) ?? LOCAL_BASE_DOMAIN;
const rawBaseDomain = normalizeHost(env.APP_BASE_DOMAIN) ?? LOCAL_BASE_DOMAIN;
const protocol = normalizeProtocol(env.APP_PROTOCOL) ?? (isLocalHost(rawBaseDomain) || env.NODE_ENV === "development" ? "http" : "https");
const appBaseDomain = normalizeHostForProtocol(rawBaseDomain, protocol) ?? rawBaseDomain;
const derivedHosts = getDerivedHosts(appBaseDomain);
return {
appBaseDomain,
webAppHost: normalizeHost(env.WEB_APP_HOST) ?? derivedHosts.webAppHost,
adminAppHost: normalizeHost(env.ADMIN_APP_HOST) ?? derivedHosts.adminAppHost,
apiHost: normalizeHost(env.API_HOST) ?? derivedHosts.apiHost,
protocol: normalizeProtocol(env.APP_PROTOCOL) ?? (isLocalHost(appBaseDomain) || env.NODE_ENV === "development" ? "http" : "https"),
webAppHost: normalizeHostForProtocol(env.WEB_APP_HOST, protocol) ?? derivedHosts.webAppHost,
adminAppHost: normalizeHostForProtocol(env.ADMIN_APP_HOST, protocol) ?? derivedHosts.adminAppHost,
apiHost: normalizeHostForProtocol(env.API_HOST, protocol) ?? derivedHosts.apiHost,
portalAppHost: normalizeHostForProtocol(env.PORTAL_APP_HOST, protocol) ?? derivedHosts.portalAppHost,
protocol,
};
}
@@ -39,9 +45,29 @@ export function normalizeHost(value: string | undefined): string | undefined {
return undefined;
}
const withProtocol = /^[a-z][a-z\d+\-.]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
const url = new URL(withProtocol);
return url.host.toLowerCase();
try {
const withProtocol = /^[a-z][a-z\d+\-.]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
const url = new URL(withProtocol);
return url.host.toLowerCase();
} catch {
return undefined;
}
}
export function normalizeHostForProtocol(
value: string | undefined,
protocol: DomainRoutingConfig["protocol"]
): string | undefined {
const host = normalizeHost(value);
if (!host) {
return undefined;
}
try {
return new URL(`${protocol}://${host}`).host.toLowerCase();
} catch {
return undefined;
}
}
export function hostMatches(actualHost: string | undefined, expectedHost: string | undefined): boolean {
@@ -82,6 +108,7 @@ function getDerivedHosts(baseDomain: string) {
webAppHost: withLocalPort(LOCAL_WEB_APP_HOST, baseDomain),
adminAppHost: withLocalPort(LOCAL_ADMIN_APP_HOST, baseDomain),
apiHost: withLocalPort(LOCAL_API_HOST, baseDomain),
portalAppHost: withLocalPort(LOCAL_PORTAL_APP_HOST, baseDomain),
};
}
@@ -89,6 +116,7 @@ function getDerivedHosts(baseDomain: string) {
webAppHost: withSubdomain("app", baseDomain),
adminAppHost: withSubdomain("admin", baseDomain),
apiHost: withSubdomain("api", baseDomain),
portalAppHost: withSubdomain("portal", baseDomain),
};
}
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { resolveApiSessionCookiePolicy, resolveSessionCookiePolicy } from "./session-cookie.js";
import { resolveApiSessionCookiePolicy, resolveHostOnlyCookiePolicy, resolveSessionCookiePolicy, resolveWebSessionCookiePolicy } from "./session-cookie.js";
const productionRouting = {
appBaseDomain: "example.com",
@@ -72,7 +72,7 @@ describe("session cookie policy", () => {
});
});
test("resolves API session cookies with the API name and shared production hardening", () => {
test("resolves API session cookies with the API name and host-only production hardening", () => {
const policy = resolveApiSessionCookiePolicy({
nodeEnv: "production",
routing: productionRouting,
@@ -82,13 +82,13 @@ describe("session cookie policy", () => {
expect(policy).toEqual({
name: "hivegrid_api_session",
maxAge: 900,
domain: "example.com",
sameSite: "lax",
secure: true,
httpOnly: true,
path: "/",
});
expect(policy.name).not.toBe("hivegrid_session");
expect(policy).not.toHaveProperty("domain");
expect(JSON.stringify(policy)).not.toContain("secret");
});
@@ -109,4 +109,67 @@ describe("session cookie policy", () => {
path: "/",
});
});
test("uses distinct secure and local names for arbitrary host-only auth cookies", () => {
expect(
resolveHostOnlyCookiePolicy({
nodeEnv: "test",
routing: productionRouting,
secureName: "__Host-hivegrid_auth_marker",
localName: "hivegrid_auth_marker",
maxAge: 60,
})
).toEqual({
name: "__Host-hivegrid_auth_marker",
maxAge: 60,
sameSite: "lax",
secure: true,
httpOnly: true,
path: "/",
});
expect(
resolveHostOnlyCookiePolicy({
nodeEnv: "development",
routing: { appBaseDomain: "localhost:3000", protocol: "http" },
secureName: "__Host-hivegrid_auth_marker",
localName: "hivegrid_auth_marker",
})
).toMatchObject({ name: "hivegrid_auth_marker", secure: false, path: "/" });
});
test.each(["app", "admin"] as const)("uses a distinct host-prefixed production cookie for the %s surface", (surface) => {
const policy = resolveWebSessionCookiePolicy({
nodeEnv: "production",
routing: productionRouting,
surface,
maxAge: 900,
});
expect(policy).toEqual({
name: `__Host-hivegrid_${surface}_session`,
maxAge: 900,
sameSite: surface === "admin" ? "strict" : "lax",
secure: true,
httpOnly: true,
path: "/",
});
expect(policy).not.toHaveProperty("domain");
});
test.each(["app", "admin"] as const)("uses a localhost-compatible host-only cookie for the %s surface", (surface) => {
const policy = resolveWebSessionCookiePolicy({
nodeEnv: "development",
routing: { appBaseDomain: "localhost:3000", protocol: "http" },
surface,
});
expect(policy).toMatchObject({
name: `hivegrid_${surface}_session`,
sameSite: surface === "admin" ? "strict" : "lax",
secure: false,
path: "/",
});
expect(policy).not.toHaveProperty("domain");
});
});
@@ -1,6 +1,6 @@
import type { DomainRoutingConfig } from "./routing.js";
export type SessionCookieSameSite = "lax";
export type SessionCookieSameSite = "lax" | "strict";
export type SessionCookiePolicy = {
name?: string;
@@ -21,6 +21,17 @@ export type ResolveSessionCookiePolicyOptions = {
export type ResolveApiSessionCookiePolicyOptions = Omit<ResolveSessionCookiePolicyOptions, "name">;
export type ResolveHostOnlyCookiePolicyOptions = Omit<ResolveSessionCookiePolicyOptions, "name"> & {
secureName: `__Host-${string}`;
localName: string;
};
export type WebSessionCookieSurface = "app" | "admin";
export type ResolveWebSessionCookiePolicyOptions = Omit<ResolveSessionCookiePolicyOptions, "name"> & {
surface: WebSessionCookieSurface;
};
const API_SESSION_COOKIE_NAME = "hivegrid_api_session";
export function resolveSessionCookiePolicy({ nodeEnv, routing, name, maxAge }: ResolveSessionCookiePolicyOptions): SessionCookiePolicy {
@@ -36,10 +47,61 @@ export function resolveSessionCookiePolicy({ nodeEnv, routing, name, maxAge }: R
}
export function resolveApiSessionCookiePolicy(options: ResolveApiSessionCookiePolicyOptions): SessionCookiePolicy {
return resolveSessionCookiePolicy({
...options,
name: API_SESSION_COOKIE_NAME,
const hostOnlyPolicy = {
...resolveSessionCookiePolicy({
...options,
name: API_SESSION_COOKIE_NAME,
}),
};
// API bearer sessions are scoped to api.*. A parent-domain cookie would be
// sent to every sibling host without enabling any supported auth flow.
delete hostOnlyPolicy.domain;
return hostOnlyPolicy;
}
/**
* Resolves an authentication-adjacent cookie that must never be accepted
* across sibling hosts. HTTPS deployments use the browser-enforced
* `__Host-` contract; local HTTP development receives a distinct name so a
* legacy or parent-domain cookie cannot shadow the production cookie.
*/
export function resolveHostOnlyCookiePolicy({
nodeEnv,
routing,
secureName,
localName,
maxAge,
}: ResolveHostOnlyCookiePolicyOptions): SessionCookiePolicy & { name: string } {
const secure = nodeEnv === "production" || routing.protocol === "https";
return {
name: secure ? secureName : localName,
...(maxAge === undefined ? {} : { maxAge }),
sameSite: "lax",
secure,
httpOnly: true,
path: "/",
};
}
/**
* Authentication cookies are deliberately host-only and use distinct names
* for the app and admin surfaces. This prevents a sibling host from planting
* a cookie that is then accepted by the more privileged admin host.
*
* The `__Host-` prefix is only valid together with Secure, Path=/ and no
* Domain attribute. Local HTTP development therefore uses an explicit,
* surface-specific fallback name.
*/
export function resolveWebSessionCookiePolicy({ nodeEnv, routing, surface, maxAge }: ResolveWebSessionCookiePolicyOptions): SessionCookiePolicy {
const policy = resolveHostOnlyCookiePolicy({
nodeEnv,
routing,
secureName: `__Host-hivegrid_${surface}_session`,
localName: `hivegrid_${surface}_session`,
maxAge,
});
return surface === "admin" ? { ...policy, sameSite: "strict" } : policy;
}
function resolveCookieDomain(appBaseDomain: string): Pick<SessionCookiePolicy, "domain"> {
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { resolveSharedRedisUrl } from "./shared-redis.js";
describe("resolveSharedRedisUrl", () => {
it("prefers the canonical shared-store endpoint", () => {
expect(resolveSharedRedisUrl({
REDIS_URL: "redis://shared.example.test:6379/1",
BULLMQ_REDIS_URL: "redis://queue.example.test:6379/2",
})).toBe("redis://shared.example.test:6379/1");
});
it("falls back to the queue endpoint and permits an unconfigured runtime", () => {
expect(resolveSharedRedisUrl({ BULLMQ_REDIS_URL: "rediss://queue.example.test:6380/2" }))
.toBe("rediss://queue.example.test:6380/2");
expect(resolveSharedRedisUrl({})).toBeUndefined();
});
});
@@ -0,0 +1,15 @@
import { validateOptionalSecretString } from "./secret-validator.js";
import type { EnvRecord } from "./types.js";
/**
* Resolves the shared Redis endpoint for cross-process coordination.
* REDIS_URL is canonical; BullMQ remains the documented fallback for
* runtimes that only configure the queue endpoint.
*/
export function resolveSharedRedisUrl(env: EnvRecord = process.env): string | undefined {
const shared = validateOptionalSecretString("REDIS_URL", env.REDIS_URL);
if (shared.configured) return shared.value;
const bullmq = validateOptionalSecretString("BULLMQ_REDIS_URL", env.BULLMQ_REDIS_URL);
return bullmq.configured ? bullmq.value : undefined;
}
@@ -19,4 +19,16 @@ describe("web config types", () => {
expectTypeOf<RequiredWebConfigOptions>().toEqualTypeOf<WebConfigOptions>();
expectTypeOf<WebConfigErrorDetails>().toHaveProperty("diagnostics").toEqualTypeOf<WebConfigDiagnostic[]>();
});
test("exposes optional typed KWP OAuth provider fields", () => {
expectTypeOf<NonNullable<WebConfig["kwp"]>>().toEqualTypeOf<{
clientId?: string;
clientSecret?: string;
scopes?: string;
customerCode?: string;
oidcIssuer?: string;
hiveGridTenantId?: string;
mandant?: string;
}>();
});
});
@@ -1,3 +1,5 @@
import type { SupportedLocale } from "@hivegrid/i18n/locales";
export type RuntimeTarget = "shared" | "web" | "api" | "mcp" | "worker";
export type EnvClassification = "required-core" | "required-per-app" | "optional-provider" | "local-development-only" | "production-only" | "deprecated-remove";
@@ -14,6 +16,7 @@ export type EnvVariableDefinition = {
kind: EnvValueKind;
source: EnvAuditSource;
requiredInProduction?: boolean;
requiredInProductionTargets?: readonly RuntimeTarget[];
dynamicPrefix?: string;
defaultValue?: string;
notes?: string;
@@ -59,7 +62,19 @@ export type SecretUrlValidationOptions = {
allowedProtocols?: readonly string[];
};
export type WebConfigDiagnosticCode = "missing-required" | "invalid-port" | "invalid-boolean" | "invalid-duration" | "invalid-number" | "weak-secret";
export type WebConfigDiagnosticCode =
| "missing-required"
| "invalid-port"
| "invalid-boolean"
| "invalid-duration"
| "invalid-number"
| "invalid-enum"
| "invalid-host"
| "invalid-url"
| "invalid-revision"
| "host-conflict"
| "forbidden"
| "weak-secret";
export type WebConfigDiagnostic = {
code: WebConfigDiagnosticCode;
@@ -78,13 +93,22 @@ export type WebConfigRouting = {
webAppHost: string;
adminAppHost: string;
apiHost: string;
portalAppHost: string;
protocol: "http" | "https";
};
export type WebRuntimeSurface = "core" | "admin" | "portal";
export type WebConfig = {
appName: string;
nodeEnv: string;
runtimeSurface: WebRuntimeSurface;
releaseRevision: string;
i18n: {
enabledLocales: readonly SupportedLocale[];
};
sessionSecret?: string;
portalSessionSecret?: string;
listen: WebConfigListen;
routing: WebConfigRouting;
webhooksUrl?: string;
@@ -103,12 +127,19 @@ export type WebConfig = {
novu: {
apiKey?: string;
};
webPush: {
vapidPublicKey?: string;
};
mailjet: {
apiKey?: string;
secretKey?: string;
fromEmail?: string;
fromName?: string;
};
adminEmail?: {
bccCapabilitySecret?: string;
bccInboundDomain?: string;
};
ipProviders: {
ipstackApiKey?: string;
ipapiIsApiKey?: string;
@@ -117,12 +148,26 @@ export type WebConfig = {
hashPepper?: string;
dbPath?: string;
};
portalServer: {
url?: string;
flyToken?: string;
};
lago: ApiConfigLago;
mollie: ApiConfigMollie;
aircall?: {
clientId?: string;
clientSecret?: string;
redirectUri?: string;
webhookUrl?: string;
};
hallopetra?: {
webhookUrl?: string;
};
kwp?: {
clientId?: string;
clientSecret?: string;
scopes?: string;
customerCode?: string;
oidcIssuer?: string;
hiveGridTenantId?: string;
mandant?: string;
};
magicLink: {
enabled: boolean;
tokenTtlMinutes?: number;
@@ -141,6 +186,7 @@ export type WebConfig = {
export type WebConfigStorage = ApiConfigStorage & {
provider?: "s3" | "local";
fallbackProvider?: "s3" | "local";
gdprExportSseCKey?: string;
localRoot?: string;
localPublicBaseUrl?: string;
};
@@ -195,6 +241,12 @@ export type ApiConfigMailjet = {
webhookSecret?: string;
};
export type ApiConfigAdminEmail = {
eventWebhookSecret?: string;
bccCapabilitySecret?: string;
bccInboundDomain?: string;
};
export type ApiConfigLago = {
apiUrl?: string;
apiKey?: string;
@@ -219,6 +271,7 @@ export type ApiConfig = {
jwtSecret?: string;
analytics: ApiConfigAnalytics;
mailjet: ApiConfigMailjet;
adminEmail?: ApiConfigAdminEmail;
lago: ApiConfigLago;
mollie: ApiConfigMollie;
storage: ApiConfigStorage;
@@ -233,7 +286,7 @@ export type ApiConfigOptions = {
export type RequiredApiConfigOptions = ApiConfigOptions;
export type ApiConfigDiagnosticCode = "missing-required" | "invalid-port";
export type ApiConfigDiagnosticCode = "missing-required" | "invalid-port" | "invalid-enum" | "weak-secret";
export type ApiConfigDiagnostic = {
code: ApiConfigDiagnosticCode;
@@ -254,6 +307,7 @@ export type ApiConfigResult = {
export type WorkerConfigDiagnosticCode =
| "missing-required"
| "weak-secret"
| "invalid-redis-url"
| "invalid-redis-protocol"
| "invalid-redis-database"
@@ -262,7 +316,9 @@ export type WorkerConfigDiagnosticCode =
| "invalid-boolean"
| "invalid-timeout"
| "invalid-concurrency"
| "invalid-worker-queue-group";
| "invalid-worker-queue-group"
| "conflicting-worker-queue-gate"
| "forbidden";
export type WorkerConfigDiagnostic = {
code: WorkerConfigDiagnosticCode;
@@ -1,6 +1,7 @@
import { describe, expect, test } from "vitest";
import { getEnvVariableDefinition, loadRequiredWebConfig, loadWebConfig, WebConfigError } from "./index.js";
const GDPR_EXPORT_SSE_C_KEY_BASE64 = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=";
const REQUIRED_PRODUCTION_ENV = {
APP_NAME: "Production App",
DATABASE_URL: "postgres://example.invalid/app",
@@ -8,15 +9,73 @@ const REQUIRED_PRODUCTION_ENV = {
WEB_APP_HOST: "app.example.com",
ADMIN_APP_HOST: "admin.example.com",
API_HOST: "api.example.com",
PORTAL_APP_HOST: "portal.example.com",
WEB_RUNTIME_SURFACE: "core",
APP_REVISION: "0123456789abcdef0123456789abcdef01234567",
SESSION_SECRET: "session-secret-value-prod-0123456789",
AUDIT_CHAIN_SECRET: "audit-chain-secret-value-prod-0123456789",
CRYPTO_SECRET: "crypto-secret-value-prod-0123456789",
ADMIN_CONNECTION_MASTER_KEY:
"admin-connection-key-prod-0123456789",
API_ACCESS_TOKEN: "api-access-token-value-prod-0123456789",
JWT_SECRET: "jwt-secret-value-prod-0123456789abcd",
MCP_RESOURCE_URL: "https://mcp.example.com",
MCP_AUTHORIZATION_SERVER_URL: "https://app.example.com",
WEB_PUSH_VAPID_PUBLIC_KEY: "web-push-public-key-prod",
STORAGE_ENDPOINT: "https://storage.example.com",
STORAGE_REGION: "eu-central-1",
STORAGE_BUCKET: "private-exports",
STORAGE_ACCESS_KEY_ID: "storage-access-key",
STORAGE_SECRET_ACCESS_KEY: "storage-secret-key",
GDPR_EXPORT_SSE_C_KEY_BASE64,
REDIS_URL: "rediss://core-redis.example.test:6380/2",
};
const PORTAL_PRODUCTION_ENV = {
...REQUIRED_PRODUCTION_ENV,
WEB_RUNTIME_SURFACE: "portal",
SESSION_SECRET: undefined,
AUDIT_CHAIN_SECRET: undefined,
WEB_APP_HOST: undefined,
ADMIN_APP_HOST: undefined,
API_HOST: undefined,
CRYPTO_SECRET: undefined,
API_ACCESS_TOKEN: undefined,
JWT_SECRET: undefined,
WEB_PUSH_VAPID_PUBLIC_KEY: undefined,
PORTAL_SESSION_SECRET: "portal-session-secret-value-prod-0123456789",
AUTH_MAGIC_LINK_ENABLED: "true",
AUTH_MAGIC_LINK_TOKEN_TTL_MINUTES: "15",
CAPTCHA_PROVIDER: "mcaptcha",
MCAPTCHA_INSTANCE_URL: "https://captcha.example.test",
MCAPTCHA_SITEKEY_LOGIN: "portal-login-sitekey",
MCAPTCHA_ACCOUNT_SECRET: "portal-mcaptcha-account-secret",
REDIS_URL: "rediss://portal-redis.example.test:6380/3",
};
describe("loadRequiredWebConfig", () => {
test("defaults enabled locales to de,en and gates catalog-ready review locales by environment", () => {
expect(loadWebConfig({}, { nodeEnv: "development" }).config.i18n.enabledLocales).toEqual(["de", "en"]);
expect(loadWebConfig({ I18N_ENABLED_LOCALES: "de,en,pl" }, { nodeEnv: "development" }).config.i18n.enabledLocales).toEqual(["de", "en", "pl"]);
const production = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, I18N_ENABLED_LOCALES: "de,en,pl" }, { nodeEnv: "production" });
expect(production.ok).toBe(false);
expect(production.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-enum", name: "I18N_ENABLED_LOCALES" }));
const staging = loadWebConfig(
{ ...REQUIRED_PRODUCTION_ENV, SENTRY_ENVIRONMENT: "staging", I18N_ENABLED_LOCALES: "de,en,pl" },
{ nodeEnv: "production" }
);
expect(staging.ok).toBe(true);
expect(staging.config.i18n.enabledLocales).toEqual(["de", "en", "pl"]);
});
test.each(["de,en,en", "de,fr", "en", "de,,en"])('rejects invalid I18N_ENABLED_LOCALES value "%s"', (value) => {
const result = loadWebConfig({ I18N_ENABLED_LOCALES: value }, { nodeEnv: "development" });
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-enum", name: "I18N_ENABLED_LOCALES" }));
});
test("returns production config when required values are valid", () => {
const config = loadRequiredWebConfig(
{
@@ -29,6 +88,8 @@ describe("loadRequiredWebConfig", () => {
expect(config).toMatchObject({
appName: "Production App",
nodeEnv: "production",
runtimeSurface: "core",
releaseRevision: "0123456789abcdef0123456789abcdef01234567",
sessionSecret: "session-secret-value-prod-0123456789",
listen: {
port: 8080,
@@ -40,6 +101,18 @@ describe("loadRequiredWebConfig", () => {
});
});
test("requires a valid distributed Redis connection for core GDPR export download gates", () => {
const missing = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, REDIS_URL: undefined }, { nodeEnv: "production" });
const invalid = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, REDIS_URL: "https://redis-secret-sentinel.example.test" }, { nodeEnv: "production" });
expect(missing.ok).toBe(false);
expect(invalid.ok).toBe(false);
if (missing.ok || invalid.ok) throw new Error("invalid production Redis fixtures unexpectedly passed");
expect(missing.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "REDIS_URL" }));
expect(invalid.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-url", name: "REDIS_URL" }));
expect(JSON.stringify([missing.diagnostics, invalid.diagnostics])).not.toContain("redis-secret-sentinel");
});
test("throws redacted WebConfigError for missing production SESSION_SECRET", () => {
const secretValues = ["crypto-secret-value", "api-access-token-value", "jwt-secret-value"];
@@ -105,6 +178,200 @@ describe("loadRequiredWebConfig", () => {
}
});
test("requires the browser VAPID public key in production", () => {
const result = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, WEB_PUSH_VAPID_PUBLIC_KEY: undefined }, { nodeEnv: "production" });
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "WEB_PUSH_VAPID_PUBLIC_KEY" }));
});
test("requires an explicit valid runtime surface in production", () => {
const missing = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, WEB_RUNTIME_SURFACE: undefined }, { nodeEnv: "production" });
const invalid = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, WEB_RUNTIME_SURFACE: "customer" }, { nodeEnv: "production" });
expect(missing.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "WEB_RUNTIME_SURFACE" }));
expect(invalid.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-enum", name: "WEB_RUNTIME_SURFACE" }));
expect(JSON.stringify(invalid.diagnostics)).not.toContain("customer");
});
test("loads a portal production surface with only its own session secret", () => {
const result = loadWebConfig(PORTAL_PRODUCTION_ENV, { nodeEnv: "production" });
expect(result.ok).toBe(true);
expect(result.config).toMatchObject({
runtimeSurface: "portal",
portalSessionSecret: "portal-session-secret-value-prod-0123456789",
routing: { portalAppHost: "portal.example.com" },
});
expect(result.config.sessionSecret).toBeUndefined();
});
test("loads the isolated admin runtime with the core session authority", () => {
const result = loadWebConfig(
{
...REQUIRED_PRODUCTION_ENV,
WEB_RUNTIME_SURFACE: "admin",
},
{ nodeEnv: "production" }
);
expect(result.ok).toBe(true);
expect(result.config).toMatchObject({
runtimeSurface: "admin",
sessionSecret: "session-secret-value-prod-0123456789",
routing: { adminAppHost: "admin.example.com" },
});
expect(result.config.portalSessionSecret).toBeUndefined();
});
test("requires HTTPS for a public production portal while allowing the loopback runtime smoke", () => {
const publicHttp = loadWebConfig({ ...PORTAL_PRODUCTION_ENV, APP_PROTOCOL: "http" }, { nodeEnv: "production" });
const lookalikeHttp = loadWebConfig({ ...PORTAL_PRODUCTION_ENV, APP_PROTOCOL: "http", PORTAL_APP_HOST: "127.evil.com" }, { nodeEnv: "production" });
const loopbackHttp = loadWebConfig(
{
...PORTAL_PRODUCTION_ENV,
APP_BASE_DOMAIN: "localhost",
PORTAL_APP_HOST: "portal.localhost",
APP_PROTOCOL: "http",
},
{ nodeEnv: "production" }
);
expect(publicHttp.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-enum", name: "APP_PROTOCOL" }));
expect(lookalikeHttp.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-enum", name: "APP_PROTOCOL" }));
expect(loopbackHttp.ok).toBe(true);
});
test("requires the selected login CAPTCHA contract for the production portal only", () => {
const missingProvider = loadWebConfig({ ...PORTAL_PRODUCTION_ENV, CAPTCHA_PROVIDER: undefined }, { nodeEnv: "production" });
const invalidProvider = loadWebConfig({ ...PORTAL_PRODUCTION_ENV, CAPTCHA_PROVIDER: "other" }, { nodeEnv: "production" });
const incompleteMcaptcha = loadWebConfig(
{
...PORTAL_PRODUCTION_ENV,
MCAPTCHA_INSTANCE_URL: undefined,
MCAPTCHA_SITEKEY_LOGIN: undefined,
MCAPTCHA_ACCOUNT_SECRET: undefined,
},
{ nodeEnv: "production" }
);
expect(missingProvider.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "CAPTCHA_PROVIDER" }));
expect(invalidProvider.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-enum", name: "CAPTCHA_PROVIDER" }));
expect(incompleteMcaptcha.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "missing-required", name: "MCAPTCHA_INSTANCE_URL" }),
expect.objectContaining({ code: "missing-required", name: "MCAPTCHA_SITEKEY_LOGIN" }),
expect.objectContaining({ code: "missing-required", name: "MCAPTCHA_ACCOUNT_SECRET" }),
])
);
expect(loadWebConfig(REQUIRED_PRODUCTION_ENV, { nodeEnv: "production" }).diagnostics).not.toEqual(
expect.arrayContaining([expect.objectContaining({ name: expect.stringMatching(/^(?:CAPTCHA_PROVIDER|MCAPTCHA_|CAP_|REDIS_URL|BULLMQ_REDIS_URL)/u) })])
);
});
test("accepts Cap portal login verification with either its login secret or the shared fallback", () => {
const capEnv = {
...PORTAL_PRODUCTION_ENV,
CAPTCHA_PROVIDER: "cap",
MCAPTCHA_INSTANCE_URL: undefined,
MCAPTCHA_SITEKEY_LOGIN: undefined,
MCAPTCHA_ACCOUNT_SECRET: undefined,
CAP_INSTANCE_URL: "https://cap.example.test",
CAP_SITEKEY_LOGIN: "portal-cap-login-sitekey",
};
const loginSecret = loadWebConfig({ ...capEnv, CAP_SITE_SECRET_LOGIN: "cap-login-secret" }, { nodeEnv: "production" });
const sharedSecret = loadWebConfig({ ...capEnv, CAP_SITE_SECRET: "cap-shared-secret" }, { nodeEnv: "production" });
expect(loginSecret.ok).toBe(true);
expect(sharedSecret.ok).toBe(true);
});
test("rejects incomplete Cap login verification without leaking provider values", () => {
const result = loadWebConfig(
{
...PORTAL_PRODUCTION_ENV,
CAPTCHA_PROVIDER: "cap",
CAP_INSTANCE_URL: "http://captcha-secret-sentinel.example.test",
CAP_SITEKEY_LOGIN: undefined,
CAP_SITE_SECRET_LOGIN: undefined,
CAP_SITE_SECRET: undefined,
},
{ nodeEnv: "production" }
);
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "invalid-url", name: "CAP_INSTANCE_URL" }),
expect.objectContaining({ code: "missing-required", name: "CAP_SITEKEY_LOGIN" }),
expect.objectContaining({ code: "missing-required", name: "CAP_SITE_SECRET_LOGIN" }),
])
);
expect(JSON.stringify(result.diagnostics)).not.toContain("captcha-secret-sentinel");
});
test("requires a valid shared Redis connection and validates a preferred BullMQ override", () => {
const missing = loadWebConfig({ ...PORTAL_PRODUCTION_ENV, REDIS_URL: undefined }, { nodeEnv: "production" });
const invalidShared = loadWebConfig({ ...PORTAL_PRODUCTION_ENV, REDIS_URL: "https://redis-secret-sentinel.example.test" }, { nodeEnv: "production" });
const invalidBullmq = loadWebConfig(
{ ...PORTAL_PRODUCTION_ENV, BULLMQ_REDIS_URL: "redis://portal-redis.example.test/not-a-database" },
{ nodeEnv: "production" }
);
expect(missing.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "REDIS_URL" }));
expect(invalidShared.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-url", name: "REDIS_URL" }));
expect(invalidBullmq.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-url", name: "BULLMQ_REDIS_URL" }));
expect(JSON.stringify(invalidShared.diagnostics)).not.toContain("redis-secret-sentinel");
});
test("requires the dedicated session secret for an explicitly selected portal surface", () => {
const result = loadWebConfig({ WEB_RUNTIME_SURFACE: "portal" }, { nodeEnv: "development" });
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "missing-required",
name: "PORTAL_SESSION_SECRET",
})
);
});
test("forbids crossing core and portal session-secret boundaries", () => {
const core = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, PORTAL_SESSION_SECRET: "portal-secret-value-prod-0123456789" }, { nodeEnv: "production" });
const portal = loadWebConfig(
{
...REQUIRED_PRODUCTION_ENV,
WEB_RUNTIME_SURFACE: "portal",
PORTAL_SESSION_SECRET: "portal-secret-value-prod-0123456789",
},
{ nodeEnv: "production" }
);
expect(core.diagnostics).toContainEqual(expect.objectContaining({ code: "forbidden", name: "PORTAL_SESSION_SECRET" }));
expect(portal.diagnostics).toContainEqual(expect.objectContaining({ code: "forbidden", name: "SESSION_SECRET" }));
});
test("requires a baked full Git SHA and the portal host in production", () => {
const result = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, APP_REVISION: "main", PORTAL_APP_HOST: undefined }, { nodeEnv: "production" });
expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-revision", name: "APP_REVISION" }));
expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "PORTAL_APP_HOST" }));
});
test("rejects malformed or shared portal hosts", () => {
const malformed = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, PORTAL_APP_HOST: "[invalid-host" }, { nodeEnv: "production" });
const shared = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, PORTAL_APP_HOST: "app.example.com" }, { nodeEnv: "production" });
const defaultPortAlias = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, PORTAL_APP_HOST: "app.example.com:443" }, { nodeEnv: "production" });
const derivedCoreHost = loadWebConfig(
{ ...REQUIRED_PRODUCTION_ENV, WEB_APP_HOST: undefined, PORTAL_APP_HOST: "app.example.com" },
{ nodeEnv: "production" }
);
expect(malformed.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-host", name: "PORTAL_APP_HOST" }));
expect(shared.diagnostics).toContainEqual(expect.objectContaining({ code: "host-conflict", name: "PORTAL_APP_HOST" }));
expect(defaultPortAlias.diagnostics).toContainEqual(expect.objectContaining({ code: "host-conflict", name: "PORTAL_APP_HOST" }));
expect(derivedCoreHost.diagnostics).toContainEqual(expect.objectContaining({ code: "host-conflict", name: "PORTAL_APP_HOST" }));
});
test("preserves default development behavior by throwing diagnostics instead of silently succeeding", () => {
expect(() => loadRequiredWebConfig({})).toThrow(WebConfigError);
});
@@ -129,6 +396,34 @@ describe("secret strength (production)", () => {
expect(JSON.stringify(result.diagnostics)).not.toContain("short-jwt-secret");
});
test("fails production web closed for missing or malformed GDPR export encryption", () => {
const missing = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, GDPR_EXPORT_SSE_C_KEY_BASE64: undefined }, { nodeEnv: "production" });
const whitespace = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, GDPR_EXPORT_SSE_C_KEY_BASE64: " " }, { nodeEnv: "production" });
const malformed = "malformed-customer-key";
const invalid = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, GDPR_EXPORT_SSE_C_KEY_BASE64: malformed }, { nodeEnv: "production" });
const insecureEndpoint = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, STORAGE_ENDPOINT: "http://storage.example.com" }, { nodeEnv: "production" });
expect(missing.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "GDPR_EXPORT_SSE_C_KEY_BASE64" }));
expect(whitespace.diagnostics).toContainEqual(expect.objectContaining({ code: "missing-required", name: "GDPR_EXPORT_SSE_C_KEY_BASE64" }));
expect(invalid.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "GDPR_EXPORT_SSE_C_KEY_BASE64" }));
expect(insecureEndpoint.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-url", name: "STORAGE_ENDPOINT" }));
expect(JSON.stringify(invalid.diagnostics)).not.toContain(malformed);
});
test("enforces the production METRICS_TOKEN byte range", () => {
const short = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, METRICS_TOKEN: "short" }, { nodeEnv: "production" });
const long = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, METRICS_TOKEN: "x".repeat(513) }, { nodeEnv: "production" });
expect(short.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "METRICS_TOKEN" }));
expect(long.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "METRICS_TOKEN" }));
});
test("rejects weak API-key and MCP token hash secrets in production", () => {
const apiKeyHash = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, API_KEY_HASH_SECRET: "short" }, { nodeEnv: "production" });
const mcpHash = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, MCP_OAUTH_TOKEN_HASH_SECRET: "short" }, { nodeEnv: "production" });
expect(apiKeyHash.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "API_KEY_HASH_SECRET" }));
expect(mcpHash.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "MCP_OAUTH_TOKEN_HASH_SECRET" }));
});
test("does not enforce secret length outside production (placeholders allowed)", () => {
const result = loadWebConfig({ ...REQUIRED_PRODUCTION_ENV, NODE_ENV: "test", SESSION_SECRET: "short" }, { nodeEnv: "test" });
expect(result.diagnostics).not.toContainEqual(expect.objectContaining({ code: "weak-secret" }));
@@ -143,6 +438,8 @@ describe("loadWebConfig", () => {
expect(result.config).toMatchObject({
appName: "HiveGrid",
nodeEnv: "development",
runtimeSurface: "core",
releaseRevision: "unknown",
listen: {
host: "0.0.0.0",
port: 3000,
@@ -152,6 +449,7 @@ describe("loadWebConfig", () => {
webAppHost: "app.localhost",
adminAppHost: "admin.localhost",
apiHost: "api.localhost",
portalAppHost: "portal.localhost",
protocol: "http",
},
});
@@ -169,14 +467,13 @@ describe("loadWebConfig", () => {
MCAPTCHA_SITEKEY_LOGIN: "login-key",
ANALYTICS_TOKEN: "analytics-token-value",
NOTIFICATIONS_NOVU_API_KEY: "novu-secret-value",
WEB_PUSH_VAPID_PUBLIC_KEY: "web-push-public-key",
MAILJET_API_KEY: "mailjet-public-value",
MAILJET_SECRET_KEY: "mailjet-secret-value",
MAILJET_FROM_EMAIL: "sender@example.com",
MAILJET_FROM_NAME: "Example Support",
IPSTACK_API_KEY: "ipstack-api-key",
IPAPIIS_API_KEY: "ipapiis-api-key",
PORTAL_SERVER_URL: "https://portals.example.com",
PORTAL_SERVER_FLY_TOKEN: "portal-fly-token-value",
LAGO_API_URL: "https://lago.example.test",
LAGO_API_KEY: "lago-secret-value",
LAGO_WEBHOOK_SECRET: "lago-webhook-secret-value",
@@ -190,6 +487,7 @@ describe("loadWebConfig", () => {
STORAGE_BUCKET: "uploads",
STORAGE_ACCESS_KEY_ID: "storage-access-key",
STORAGE_SECRET_ACCESS_KEY: "storage-secret-key",
GDPR_EXPORT_SSE_C_KEY_BASE64,
STORAGE_SESSION_TOKEN: "storage-session-token",
STORAGE_PUBLIC_BASE_URL: "https://cdn.example.com",
STORAGE_FORCE_PATH_STYLE: "true",
@@ -230,6 +528,9 @@ describe("loadWebConfig", () => {
novu: {
apiKey: "novu-secret-value",
},
webPush: {
vapidPublicKey: "web-push-public-key",
},
mailjet: {
apiKey: "mailjet-public-value",
secretKey: "mailjet-secret-value",
@@ -240,10 +541,6 @@ describe("loadWebConfig", () => {
ipstackApiKey: "ipstack-api-key",
ipapiIsApiKey: "ipapiis-api-key",
},
portalServer: {
url: "https://portals.example.com",
flyToken: "portal-fly-token-value",
},
lago: {
apiUrl: "https://lago.example.test",
apiKey: "lago-secret-value",
@@ -262,6 +559,7 @@ describe("loadWebConfig", () => {
bucket: "uploads",
accessKeyId: "storage-access-key",
secretAccessKey: "storage-secret-key",
gdprExportSseCKey: GDPR_EXPORT_SSE_C_KEY_BASE64,
sessionToken: "storage-session-token",
publicBaseUrl: "https://cdn.example.com",
forcePathStyle: "true",
@@ -275,6 +573,75 @@ describe("loadWebConfig", () => {
});
});
test("exposes Aircall provider configuration without making it a core runtime requirement", () => {
const result = loadWebConfig(
{
...REQUIRED_PRODUCTION_ENV,
AIRCALL_CLIENT_ID: "aircall-client",
AIRCALL_CLIENT_SECRET: "aircall-secret",
AIRCALL_REDIRECT_URI: "https://app.example.com/integrations/aircall/oauth/callback",
AIRCALL_WEBHOOK_URL: "https://api.example.com/v1/webhooks/telephony/aircall",
},
{ nodeEnv: "production" }
);
expect(result.ok).toBe(true);
expect(result.config.aircall).toEqual({
clientId: "aircall-client",
clientSecret: "aircall-secret",
redirectUri: "https://app.example.com/integrations/aircall/oauth/callback",
webhookUrl: "https://api.example.com/v1/webhooks/telephony/aircall",
});
expect(getEnvVariableDefinition("AIRCALL_CLIENT_SECRET")?.requiredInProduction).not.toBe(true);
});
test("exposes the optional HalloPetra webhook URL", () => {
const result = loadWebConfig(
{
...REQUIRED_PRODUCTION_ENV,
HALLOPETRA_WEBHOOK_URL: "https://api.example.com/v1/webhooks/telephony/hallopetra",
},
{ nodeEnv: "production" }
);
expect(result.ok).toBe(true);
expect(result.config.hallopetra).toEqual({
webhookUrl: "https://api.example.com/v1/webhooks/telephony/hallopetra",
});
expect(getEnvVariableDefinition("HALLOPETRA_WEBHOOK_URL")?.requiredInProduction).not.toBe(true);
});
test("exposes KWP OAuth provider configuration without a redirect override or core runtime requirement", () => {
const result = loadWebConfig(
{
...REQUIRED_PRODUCTION_ENV,
KWP_OAUTH_CLIENT_ID: " kwp-client ",
KWP_OAUTH_CLIENT_SECRET: " kwp-secret ",
KWP_OAUTH_SCOPES: " openid offline_access ",
KWP_CUSTOMER_CODE: " customer-code ",
KWP_OIDC_ISSUER: " https://id.example.test/realms/example ",
KWP_HIVEGRID_TENANT_ID: " tenant-geerkens ",
KWP_MANDANT: " mandant-code ",
},
{ nodeEnv: "production" }
);
expect(result.ok).toBe(true);
expect(result.config.kwp).toEqual({
clientId: "kwp-client",
clientSecret: "kwp-secret",
scopes: "openid offline_access",
customerCode: "customer-code",
oidcIssuer: "https://id.example.test/realms/example",
hiveGridTenantId: "tenant-geerkens",
mandant: "mandant-code",
});
for (const key of ["KWP_OAUTH_CLIENT_ID", "KWP_OAUTH_CLIENT_SECRET", "KWP_OAUTH_SCOPES", "KWP_CUSTOMER_CODE", "KWP_OIDC_ISSUER", "KWP_HIVEGRID_TENANT_ID", "KWP_MANDANT"]) {
expect(getEnvVariableDefinition(key)?.requiredInProduction, `${key} must remain optional in production`).not.toBe(true);
}
expect(getEnvVariableDefinition("KWP_OAUTH_REDIRECT_URI")).toBeUndefined();
});
test("normalizes Cap captcha provider values", () => {
const result = loadWebConfig({
...REQUIRED_PRODUCTION_ENV,
@@ -291,7 +658,6 @@ describe("loadWebConfig", () => {
});
});
test("exposes demo login hints only for development config", () => {
expect(loadWebConfig({ NODE_ENV: "development", DEMO_USER: "demo@example.com:password" }).config.demoUser).toBe("demo@example.com:password");
expect(loadWebConfig({ NODE_ENV: "test", DEMO_USER: "demo@example.com:password" }).config.demoUser).toBeUndefined();
@@ -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",
@@ -77,4 +77,11 @@ describe("loadWorkerConfig production core-env requirements", () => {
);
expect(result.diagnostics.some((diagnostic) => diagnostic.name === "APP_NAME")).toBe(false);
});
test("rejects weak audit and out-of-range metrics secrets", () => {
const weakAudit = loadWorkerConfig({ AUDIT_CHAIN_SECRET: "short" }, { nodeEnv: "production" });
const longMetrics = loadWorkerConfig({ METRICS_TOKEN: "x".repeat(513) }, { nodeEnv: "production" });
expect(weakAudit.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "AUDIT_CHAIN_SECRET" }));
expect(longMetrics.diagnostics).toContainEqual(expect.objectContaining({ code: "weak-secret", name: "METRICS_TOKEN" }));
});
});
@@ -3,6 +3,16 @@ import { loadRequiredWorkerConfig, loadWorkerConfig, WorkerConfigError } from ".
const REDIS_WITH_PASSWORD = "rediss://:super-secret-password@redis.example.com:6380/2";
const DATABASE_URL = "postgresql://user:db-secret@localhost:5432/app";
const CRYPTO_SECRET = "shared-tenant-envelope-secret-value";
const GDPR_EXPORT_SSE_C_KEY_BASE64 = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=";
const portalGdprExportStorageEnv = {
STORAGE_ACCESS_KEY_ID: "access-key",
STORAGE_BUCKET: "exports",
STORAGE_ENDPOINT: "https://storage.example.com",
STORAGE_REGION: "eu-central-1",
STORAGE_SECRET_ACCESS_KEY: "secret-key",
GDPR_EXPORT_SSE_C_KEY_BASE64,
};
describe("loadRequiredWorkerConfig", () => {
test("returns disabled local worker config without Redis", () => {
@@ -107,6 +117,50 @@ describe("loadRequiredWorkerConfig", () => {
}
}
});
test("fails mail-worker startup closed when the transactional outbox envelope key is absent", () => {
const env = {
WORKER_ENABLED: "true",
WORKER_QUEUE_GROUP: "mail",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
};
expect(() => loadRequiredWorkerConfig(env)).toThrow(WorkerConfigError);
try {
loadRequiredWorkerConfig(env);
throw new Error("Expected loadRequiredWorkerConfig to throw.");
} catch (error) {
expect(error).toBeInstanceOf(WorkerConfigError);
expect((error as WorkerConfigError).details.diagnostics).toContainEqual({
code: "missing-required",
name: "CRYPTO_SECRET",
classification: "required-per-app",
message: "CRYPTO_SECRET is required.",
});
}
});
test("allows mail-worker startup with the shared envelope key or an explicitly disabled outbox bridge", () => {
expect(
loadRequiredWorkerConfig({
WORKER_ENABLED: "true",
WORKER_QUEUE_GROUP: "mail",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
CRYPTO_SECRET,
}).enabled
).toBe(true);
expect(
loadRequiredWorkerConfig({
WORKER_ENABLED: "true",
WORKER_QUEUE_GROUP: "mail",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
TRANSACTIONAL_MAIL_OUTBOX_ENABLED: "false",
}).enabled
).toBe(true);
});
});
describe("loadWorkerConfig", () => {
@@ -278,6 +332,377 @@ describe("loadWorkerConfig", () => {
);
});
test("accepts the dedicated portal GDPR export gate only on an isolated import worker", () => {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "import",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(true);
expect(result.diagnostics).toEqual([]);
});
test("accepts dedicated mode when both full import gates are explicitly false", () => {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "import",
IMPORT_QUEUE_ENABLED: "false",
IMPORT_QUEUE_RUNTIME_READY: "false",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(true);
expect(result.diagnostics).toEqual([]);
});
test("rejects the dedicated portal GDPR export gate on another worker group", () => {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "general",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "invalid-worker-queue-group",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
});
test("enforces the dedicated worker group even when the worker is disabled", () => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "general",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "invalid-worker-queue-group",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
});
test("rejects a whitespace-padded import worker group in dedicated mode", () => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: " import ",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "invalid-worker-queue-group",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
});
test.each(["IMPORT_QUEUE_ENABLED", "IMPORT_QUEUE_RUNTIME_READY"] as const)("rejects dedicated mode when %s alone enables the full runtime", (gateName) => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "import",
IMPORT_QUEUE_ENABLED: "false",
IMPORT_QUEUE_RUNTIME_READY: "false",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
[gateName]: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "conflicting-worker-queue-gate",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
});
test.each([
["IMPORT_QUEUE_ENABLED", "TRUE"],
["IMPORT_QUEUE_ENABLED", "1"],
["IMPORT_QUEUE_ENABLED", " false "],
["IMPORT_QUEUE_RUNTIME_READY", "TRUE"],
["IMPORT_QUEUE_RUNTIME_READY", "1"],
["IMPORT_QUEUE_RUNTIME_READY", " false "],
] as const)("rejects non-canonical %s=%s while dedicated mode is enabled", (gateName, gateValue) => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "import",
IMPORT_QUEUE_ENABLED: "false",
IMPORT_QUEUE_RUNTIME_READY: "false",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
[gateName]: gateValue,
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "conflicting-worker-queue-gate",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
});
test("rejects dedicated mode when both full import gates are true", () => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "import",
IMPORT_QUEUE_ENABLED: "true",
IMPORT_QUEUE_RUNTIME_READY: "true",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "conflicting-worker-queue-gate",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
});
test("requires the complete storage contract in dedicated mode", () => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "import",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "missing-required", name: "STORAGE_ENDPOINT" }),
expect.objectContaining({ code: "missing-required", name: "STORAGE_REGION" }),
expect.objectContaining({ code: "missing-required", name: "STORAGE_BUCKET" }),
expect.objectContaining({ code: "missing-required", name: "STORAGE_ACCESS_KEY_ID" }),
expect.objectContaining({ code: "missing-required", name: "STORAGE_SECRET_ACCESS_KEY" }),
expect.objectContaining({ code: "missing-required", name: "GDPR_EXPORT_SSE_C_KEY_BASE64" }),
])
);
});
test("rejects malformed SSE-C keys and non-HTTPS storage in dedicated mode without leaking the key", () => {
const malformed = "malformed-secret-value";
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "import",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
STORAGE_ENDPOINT: "http://storage.example.com",
GDPR_EXPORT_SSE_C_KEY_BASE64: malformed,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "weak-secret", name: "GDPR_EXPORT_SSE_C_KEY_BASE64" }),
expect.objectContaining({ code: "invalid-url-protocol", name: "STORAGE_ENDPOINT" }),
])
);
expect(JSON.stringify(result.diagnostics)).not.toContain(malformed);
});
test("requires encrypted GDPR storage in the full import runtime", () => {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "import",
IMPORT_QUEUE_ENABLED: "true",
IMPORT_QUEUE_RUNTIME_READY: "true",
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "missing-required", name: "STORAGE_ENDPOINT" }),
expect.objectContaining({ code: "missing-required", name: "GDPR_EXPORT_SSE_C_KEY_BASE64" }),
])
);
});
test("accepts the full import runtime with encrypted GDPR storage", () => {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "import",
IMPORT_QUEUE_ENABLED: "true",
IMPORT_QUEUE_RUNTIME_READY: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(true);
expect(result.diagnostics).toEqual([]);
});
test("requires HTTPS storage for the general-worker GDPR retention runtime", () => {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "general",
EXPORT_RETENTION_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
STORAGE_ENDPOINT: "http://storage.example.com",
GDPR_EXPORT_SSE_C_KEY_BASE64: undefined,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "invalid-url-protocol", name: "STORAGE_ENDPOINT" }));
});
test("fails production general-worker readiness closed without tenant hard-delete storage", () => {
const result = loadWorkerConfig(
{
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "general",
},
{ nodeEnv: "production" },
);
expect(result.ok).toBe(false);
expect(result.diagnostics).toEqual(
expect.arrayContaining(
["STORAGE_ENDPOINT", "STORAGE_REGION", "STORAGE_BUCKET", "STORAGE_ACCESS_KEY_ID", "STORAGE_SECRET_ACCESS_KEY"].map(
(name) => expect.objectContaining({ code: "missing-required", name }),
),
),
);
});
test("keeps staging and required-RLS general workers fail-closed even if NODE_ENV is mislabelled", () => {
for (const boundary of [{ SENTRY_ENVIRONMENT: "staging" }, { RLS_RUNTIME_MODE: "required" }]) {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "general",
NODE_ENV: "test",
...boundary,
});
expect(result.diagnostics).toContainEqual(
expect.objectContaining({ code: "missing-required", name: "STORAGE_BUCKET" }),
);
}
});
test("accepts production general-worker tenant hard-delete storage without requiring the SSE-C read key", () => {
const result = loadWorkerConfig(
{
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "general",
EXPORT_RETENTION_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
GDPR_EXPORT_SSE_C_KEY_BASE64: undefined,
},
{ nodeEnv: "production" },
);
expect(
result.diagnostics.filter(({ name }) =>
["STORAGE_ENDPOINT", "STORAGE_REGION", "STORAGE_BUCKET", "STORAGE_ACCESS_KEY_ID", "STORAGE_SECRET_ACCESS_KEY"].includes(name),
),
).toEqual([]);
});
test("rejects the SSE-C read key on the delete-only general worker without leaking it", () => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "general",
EXPORT_RETENTION_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({ code: "forbidden", name: "GDPR_EXPORT_SSE_C_KEY_BASE64" }),
);
expect(JSON.stringify(result.diagnostics)).not.toContain(GDPR_EXPORT_SSE_C_KEY_BASE64);
});
test("requires the 15-minute export-retention runtime on every required general worker boundary", () => {
for (const boundary of [{ NODE_ENV: "production" }, { SENTRY_ENVIRONMENT: "staging" }, { RLS_RUNTIME_MODE: "required" }]) {
const result = loadWorkerConfig({
WORKER_ENABLED: "true",
BULLMQ_REDIS_URL: REDIS_WITH_PASSWORD,
DATABASE_URL,
WORKER_QUEUE_GROUP: "general",
...portalGdprExportStorageEnv,
GDPR_EXPORT_SSE_C_KEY_BASE64: undefined,
...boundary,
});
expect(result.diagnostics).toContainEqual(
expect.objectContaining({ code: "missing-required", name: "EXPORT_RETENTION_QUEUE_ENABLED" }),
);
}
});
test("rejects non-canonical or non-general export-retention gates", () => {
const invalidBoolean = loadWorkerConfig({ WORKER_QUEUE_GROUP: "general", EXPORT_RETENTION_QUEUE_ENABLED: "TRUE" });
expect(invalidBoolean.diagnostics).toContainEqual(
expect.objectContaining({ code: "invalid-boolean", name: "EXPORT_RETENTION_QUEUE_ENABLED" }),
);
const wrongGroup = loadWorkerConfig({
WORKER_QUEUE_GROUP: "mail",
EXPORT_RETENTION_QUEUE_ENABLED: "true",
...portalGdprExportStorageEnv,
GDPR_EXPORT_SSE_C_KEY_BASE64: undefined,
});
expect(wrongGroup.diagnostics).toContainEqual(
expect.objectContaining({ code: "invalid-worker-queue-group", name: "EXPORT_RETENTION_QUEUE_ENABLED" }),
);
});
test("rejects non-canonical dedicated portal GDPR export gate values", () => {
for (const value of ["TRUE", "1", "garbage"]) {
const result = loadWorkerConfig({ PORTAL_GDPR_EXPORT_QUEUE_ENABLED: value });
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "invalid-boolean",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
}
});
test("rejects whitespace-padded dedicated portal GDPR export gate values", () => {
const result = loadWorkerConfig({
WORKER_QUEUE_GROUP: "import",
PORTAL_GDPR_EXPORT_QUEUE_ENABLED: " true ",
...portalGdprExportStorageEnv,
});
expect(result.ok).toBe(false);
expect(result.diagnostics).toContainEqual(
expect.objectContaining({
code: "invalid-boolean",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
})
);
});
test("reports invalid Redis protocol without leaking URL values", () => {
const rawUrl = "https://:super-secret-password@redis.example.com/0";
const result = loadWorkerConfig({
@@ -1,4 +1,5 @@
import { getEnvVariableDefinition, validateEnv } from "./index.js";
import { normalizeGdprExportSseCKey } from "./gdpr-export-storage.js";
import { validateBooleanFlag, validateOptionalSecretString, validateOptionalSecretUrl, validateRequiredSecretString } from "./secret-validator.js";
import type {
EnvRecord,
@@ -19,6 +20,16 @@ const DEFAULT_QUEUE_NAMES = {
workflow: "workflow",
} as const;
const WORKER_QUEUE_GROUP_NAMES = ["general", "mail", "import", "webhook", "plugin"] as const;
const PORTAL_GDPR_EXPORT_STORAGE_NAMES = [
"STORAGE_ENDPOINT",
"STORAGE_REGION",
"STORAGE_BUCKET",
"STORAGE_ACCESS_KEY_ID",
"STORAGE_SECRET_ACCESS_KEY",
"GDPR_EXPORT_SSE_C_KEY_BASE64",
] as const;
const GDPR_EXPORT_RETENTION_STORAGE_NAMES = PORTAL_GDPR_EXPORT_STORAGE_NAMES.filter((name) => name !== "GDPR_EXPORT_SSE_C_KEY_BASE64");
const TENANT_HARD_DELETE_STORAGE_NAMES = GDPR_EXPORT_RETENTION_STORAGE_NAMES;
export class WorkerConfigError extends Error {
readonly diagnostics: WorkerConfigDiagnostic[];
@@ -54,6 +65,23 @@ export function loadWorkerConfig(env: EnvRecord = process.env, options: WorkerCo
const concurrency = parseWorkerConcurrency(env.WORKER_CONCURRENCY);
const mailjet = parseMailjetConfig(env);
const browserRuntime = parseBrowserRuntimeConfig(env);
const workerQueueGroup = present(env.WORKER_QUEUE_GROUP);
const portalGdprExportQueueFlag = present(env.PORTAL_GDPR_EXPORT_QUEUE_ENABLED);
const portalGdprExportQueueEnabled = env.PORTAL_GDPR_EXPORT_QUEUE_ENABLED === "true";
const exportRetentionQueueFlag = present(env.EXPORT_RETENTION_QUEUE_ENABLED);
const exportRetentionQueueEnabled = env.EXPORT_RETENTION_QUEUE_ENABLED === "true";
const fullImportRuntimeEnabled =
workerQueueGroup === "import" && env.IMPORT_QUEUE_ENABLED === "true" && env.IMPORT_QUEUE_RUNTIME_READY === "true" && !portalGdprExportQueueEnabled;
const gdprExportRuntimeEnabled = portalGdprExportQueueEnabled || fullImportRuntimeEnabled;
const tenantHardDeleteStorageRequired =
enabled &&
workerQueueGroup === "general" &&
(nodeEnv === "production" ||
env.RLS_RUNTIME_MODE === "required" ||
env.SENTRY_ENVIRONMENT === "staging" ||
env.SENTRY_ENVIRONMENT === "production");
const cryptoSecretRequired =
(enabled && workerQueueGroup === "mail" && env.TRANSACTIONAL_MAIL_OUTBOX_ENABLED !== "false") || options.extraRequired?.includes("CRYPTO_SECRET") === true;
const diagnostics: WorkerConfigDiagnostic[] = [
...toDiagnostics(
validateEnv(env, {
@@ -61,12 +89,52 @@ export function loadWorkerConfig(env: EnvRecord = process.env, options: WorkerCo
nodeEnv,
includeOptionalProviders: options.includeOptionalProviders,
extraRequired: options.extraRequired,
}).missing.filter((issue) => issue.name !== "APP_NAME" && issue.name !== "DATABASE_URL")
}).missing.filter((issue) => issue.name !== "APP_NAME" && issue.name !== "DATABASE_URL" && issue.name !== "CRYPTO_SECRET")
),
];
diagnostics.push(...toWorkerDiagnostics(enabledValidation.diagnostics));
diagnostics.push(...concurrency.diagnostics, ...mailjet.diagnostics, ...browserRuntime.diagnostics);
if (portalGdprExportQueueFlag && env.PORTAL_GDPR_EXPORT_QUEUE_ENABLED !== "true" && env.PORTAL_GDPR_EXPORT_QUEUE_ENABLED !== "false") {
diagnostics.push({
code: "invalid-boolean",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
classification: getEnvVariableDefinition("PORTAL_GDPR_EXPORT_QUEUE_ENABLED")?.classification,
message: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED must be exactly true or false.",
});
}
if (exportRetentionQueueFlag && env.EXPORT_RETENTION_QUEUE_ENABLED !== "true" && env.EXPORT_RETENTION_QUEUE_ENABLED !== "false") {
diagnostics.push({
code: "invalid-boolean",
name: "EXPORT_RETENTION_QUEUE_ENABLED",
classification: getEnvVariableDefinition("EXPORT_RETENTION_QUEUE_ENABLED")?.classification,
message: "EXPORT_RETENTION_QUEUE_ENABLED must be exactly true or false.",
});
}
if (cryptoSecretRequired) {
diagnostics.push(...toWorkerDiagnostics(validateRequiredSecretString("CRYPTO_SECRET", env.CRYPTO_SECRET).diagnostics));
}
if (nodeEnv === "production") {
for (const name of [
"AUDIT_CHAIN_SECRET",
"METRICS_TOKEN",
"ADMIN_CONNECTION_MASTER_KEY",
] as const) {
const value = present(env[name]);
const byteLength = value ? Buffer.byteLength(value, "utf8") : 0;
if (value && (byteLength < 32 || (name === "METRICS_TOKEN" && byteLength > 512))) {
diagnostics.push({
code: "weak-secret",
name,
classification: getEnvVariableDefinition(name)?.classification,
message:
name === "METRICS_TOKEN"
? "METRICS_TOKEN must contain 32..512 bytes in production."
: `${name} must contain at least 32 bytes in production.`,
});
}
}
}
if (enabled && redisSelection.source === "none") {
diagnostics.push({
@@ -85,7 +153,6 @@ export function loadWorkerConfig(env: EnvRecord = process.env, options: WorkerCo
});
}
if (enabled) {
const workerQueueGroup = present(env.WORKER_QUEUE_GROUP);
if (!workerQueueGroup) {
diagnostics.push({
code: "missing-required",
@@ -103,6 +170,101 @@ export function loadWorkerConfig(env: EnvRecord = process.env, options: WorkerCo
}
}
if (portalGdprExportQueueEnabled && env.WORKER_QUEUE_GROUP !== "import") {
diagnostics.push({
code: "invalid-worker-queue-group",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
classification: getEnvVariableDefinition("PORTAL_GDPR_EXPORT_QUEUE_ENABLED")?.classification,
message: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED=true requires WORKER_QUEUE_GROUP=import.",
});
}
if (exportRetentionQueueEnabled && workerQueueGroup !== "general") {
diagnostics.push({
code: "invalid-worker-queue-group",
name: "EXPORT_RETENTION_QUEUE_ENABLED",
classification: getEnvVariableDefinition("EXPORT_RETENTION_QUEUE_ENABLED")?.classification,
message: "EXPORT_RETENTION_QUEUE_ENABLED=true requires WORKER_QUEUE_GROUP=general.",
});
}
if (workerQueueGroup === "general" && present(env.GDPR_EXPORT_SSE_C_KEY_BASE64)) {
diagnostics.push({
code: "forbidden",
name: "GDPR_EXPORT_SSE_C_KEY_BASE64",
classification: getEnvVariableDefinition("GDPR_EXPORT_SSE_C_KEY_BASE64")?.classification,
message: "GDPR_EXPORT_SSE_C_KEY_BASE64 must not be set on the delete-only general worker.",
});
}
if (tenantHardDeleteStorageRequired && !exportRetentionQueueEnabled) {
diagnostics.push({
code: "missing-required",
name: "EXPORT_RETENTION_QUEUE_ENABLED",
classification: getEnvVariableDefinition("EXPORT_RETENTION_QUEUE_ENABLED")?.classification,
message: "EXPORT_RETENTION_QUEUE_ENABLED=true is required on the production/staging general worker.",
});
}
if (
portalGdprExportQueueEnabled &&
[env.IMPORT_QUEUE_ENABLED, env.IMPORT_QUEUE_RUNTIME_READY].some((value) => {
return present(value) !== undefined && value !== "false";
})
) {
diagnostics.push({
code: "conflicting-worker-queue-gate",
name: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED",
classification: getEnvVariableDefinition("PORTAL_GDPR_EXPORT_QUEUE_ENABLED")?.classification,
message: "PORTAL_GDPR_EXPORT_QUEUE_ENABLED=true requires IMPORT_QUEUE_ENABLED and IMPORT_QUEUE_RUNTIME_READY to be unset or exactly false.",
});
}
if (gdprExportRuntimeEnabled) {
const requirement = portalGdprExportQueueEnabled ? "PORTAL_GDPR_EXPORT_QUEUE_ENABLED=true" : "the full import runtime owns GDPR export jobs";
for (const name of PORTAL_GDPR_EXPORT_STORAGE_NAMES) {
if (!present(env[name])) {
diagnostics.push({
code: "missing-required",
name,
classification: getEnvVariableDefinition(name)?.classification,
message: `${name} is required when ${requirement}.`,
});
}
}
const sseCustomerKey = present(env.GDPR_EXPORT_SSE_C_KEY_BASE64);
if (sseCustomerKey && !normalizeGdprExportSseCKey(sseCustomerKey)) {
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.",
});
}
diagnostics.push(...toWorkerDiagnostics(validateOptionalSecretUrl("STORAGE_ENDPOINT", env.STORAGE_ENDPOINT, { allowedProtocols: ["https"] }).diagnostics));
}
if (exportRetentionQueueEnabled) {
for (const name of GDPR_EXPORT_RETENTION_STORAGE_NAMES) {
if (!present(env[name])) {
diagnostics.push({
code: "missing-required",
name,
classification: getEnvVariableDefinition(name)?.classification,
message: `${name} is required when EXPORT_RETENTION_QUEUE_ENABLED=true.`,
});
}
}
diagnostics.push(...toWorkerDiagnostics(validateOptionalSecretUrl("STORAGE_ENDPOINT", env.STORAGE_ENDPOINT, { allowedProtocols: ["https"] }).diagnostics));
}
if (tenantHardDeleteStorageRequired && !exportRetentionQueueEnabled) {
for (const name of TENANT_HARD_DELETE_STORAGE_NAMES) {
if (!present(env[name])) {
diagnostics.push({
code: "missing-required",
name,
classification: getEnvVariableDefinition(name)?.classification,
message: `${name} is required for tenant hard-delete on the production general worker.`,
});
}
}
diagnostics.push(...toWorkerDiagnostics(validateOptionalSecretUrl("STORAGE_ENDPOINT", env.STORAGE_ENDPOINT, { allowedProtocols: ["https"] }).diagnostics));
}
if (redisParse.status !== "not-provided") {
for (const issue of redisParse.diagnostics) {
diagnostics.push(issue);
@@ -317,10 +479,7 @@ function parseBrowserRuntimeConfig(env: EnvRecord): {
};
}
function parseOptionalPositiveInteger(
name: string,
value: string | undefined
): { value?: number; diagnostics: WorkerConfigDiagnostic[] } {
function parseOptionalPositiveInteger(name: string, value: string | undefined): { value?: number; diagnostics: WorkerConfigDiagnostic[] } {
const normalized = present(value);
if (!normalized) {
return { diagnostics: [] };
@@ -356,7 +515,9 @@ function parseOptionalPositiveInteger(
return { value: parsed, diagnostics: [] };
}
function toWorkerDiagnostics(diagnostics: readonly { code: string; name: string; message: string; classification?: WorkerConfigDiagnostic["classification"] }[]): WorkerConfigDiagnostic[] {
function toWorkerDiagnostics(
diagnostics: readonly { code: string; name: string; message: string; classification?: WorkerConfigDiagnostic["classification"] }[]
): WorkerConfigDiagnostic[] {
return diagnostics.map((diagnostic) => ({
code: diagnostic.code === "invalid-url-protocol" ? "invalid-url-protocol" : (diagnostic.code as WorkerConfigDiagnostic["code"]),
name: diagnostic.name,