export const CUSTOMER_PORTAL_UAT_TENANT_SLUG = "demo-pro-crm" as const; export const CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG = "demo-starter-crm" as const; export const CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG = "demo-enterprise-crm" as const; export const CUSTOMER_PORTAL_UAT_COMMERCIAL_CONFIRMATION = "demo-starter-crm+demo-pro-crm+demo-enterprise-crm" as const; export const CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN = "https://staging-portal.hivegrid.de" as const; export const CUSTOMER_PORTAL_UAT_ADMIN_EMAIL = "customer-portal-admin-uat@saas-ctrl.com" as const; export const CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL = "customer-portal-uat@saas-ctrl.com" as const; export const CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL = "customer-portal-subcontractor-uat@saas-ctrl.com" as const; export const CUSTOMER_PORTAL_UAT_PROJECT_ID = "rheinmain-shk-v1-project-0001" as const; export const CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID = "rheinmain-shk-v1-project-0002" as const; export type CustomerPortalUatMode = "plan" | "verify" | "apply"; export type CustomerPortalUatTarget = "catalog" | "fixture" | "commercial-fixture"; export type CustomerPortalUatEnvironment = Readonly>; export type CustomerPortalUatDatabaseBinding = { readonly databaseUrl: string; readonly expectedDatabaseHost: string; readonly expectedDatabasePort: string; readonly expectedDatabaseName: string; readonly operatorUserId: string; readonly auditChainSecret: string; }; export type CustomerPortalCatalogCommand = CustomerPortalUatDatabaseBinding & { readonly target: "catalog"; readonly mode: CustomerPortalUatMode; readonly lagoApiUrl: string; readonly lagoApiKey: string; }; export type CustomerPortalFixtureCommand = CustomerPortalUatDatabaseBinding & { readonly target: "fixture"; readonly mode: CustomerPortalUatMode; readonly expectedTenantId: string; readonly password: string; }; export type CustomerPortalCommercialFixtureCommand = CustomerPortalUatDatabaseBinding & { readonly target: "commercial-fixture"; readonly mode: CustomerPortalUatMode; readonly expectedStarterTenantId: string; readonly expectedProTenantId: string; readonly expectedEnterpriseTenantId: string; readonly password: string; }; export type CustomerPortalUatCommand = CustomerPortalCatalogCommand | CustomerPortalFixtureCommand | CustomerPortalCommercialFixtureCommand; const modeArguments = new Map([ ["--plan", "plan"], ["--verify", "verify"], ["--apply", "apply"], ]); const forbiddenEnvironmentKeys = new Set(["DIRECT_URL", "MIGRATE_ON_BOOT", "SEED_ON_BOOT"]); const allowedStagingLagoApiUrls = new Set(["http://127.0.0.1:3108", "http://10.42.0.4:3108"]); export class CustomerPortalUatError extends Error { constructor(message: string) { super(message); this.name = "CustomerPortalUatError"; } } function requiredEnvironmentValue(env: CustomerPortalUatEnvironment, name: string): string { const value = env[name]?.trim(); if (!value) throw new CustomerPortalUatError(`customer-portal UAT: ${name} is required`); return value; } function parseSingleValueArgument(argv: readonly string[], name: string): string | undefined { const prefix = `${name}=`; const values = argv.filter((argument) => argument.startsWith(prefix)).map((argument) => argument.slice(prefix.length)); if (values.length > 1) throw new CustomerPortalUatError(`customer-portal UAT: ${name} may only be provided once`); return values[0]; } function parseMode(argv: readonly string[]): CustomerPortalUatMode { const modes = argv.flatMap((argument) => { const mode = modeArguments.get(argument); return mode ? [mode] : []; }); if (modes.length > 1) throw new CustomerPortalUatError("customer-portal UAT: provide exactly one mode"); return modes[0] ?? "plan"; } function assertKnownArguments(argv: readonly string[]): void { for (const argument of argv) { if (modeArguments.has(argument) || argument.startsWith("--confirm=")) continue; throw new CustomerPortalUatError("customer-portal UAT: unknown argument"); } } function assertOperatorEnvironment(env: CustomerPortalUatEnvironment): void { if (env.NODE_ENV?.trim() !== "production") { throw new CustomerPortalUatError("customer-portal UAT: NODE_ENV must be production so production audit guarantees stay active"); } if (env.SENTRY_ENVIRONMENT?.trim() !== "staging") { throw new CustomerPortalUatError("customer-portal UAT: SENTRY_ENVIRONMENT must be staging"); } if (env.RLS_RUNTIME_MODE?.trim() !== "required") { throw new CustomerPortalUatError("customer-portal UAT: RLS_RUNTIME_MODE must be required"); } if (env.DATABASE_RUNTIME_ROLE?.trim() !== "hivegrid_app") { throw new CustomerPortalUatError("customer-portal UAT: DATABASE_RUNTIME_ROLE must be hivegrid_app"); } const auditChainSecret = env.AUDIT_CHAIN_SECRET; if (!auditChainSecret || Buffer.byteLength(auditChainSecret, "utf8") < 32) { throw new CustomerPortalUatError("customer-portal UAT: AUDIT_CHAIN_SECRET must contain the canonical staging audit secret"); } for (const [name, value] of Object.entries(env)) { if (!value) continue; if (forbiddenEnvironmentKeys.has(name) || name.startsWith("SEED_") || name.startsWith("MIGRATOR_") || name.toUpperCase().startsWith("PG")) { throw new CustomerPortalUatError(`customer-portal UAT: forbidden operator environment key ${name}`); } } } export function normalizeCustomerPortalStagingLagoApiUrl(value: string): string { let parsed: URL; try { parsed = new URL(value); } catch { throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL must be the canonical staging endpoint"); } if (parsed.username || parsed.password || parsed.search || parsed.hash || (parsed.pathname !== "" && parsed.pathname !== "/")) { throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL must be the canonical staging endpoint"); } const normalized = parsed.origin; if (!allowedStagingLagoApiUrls.has(normalized)) { throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL must be the canonical staging endpoint"); } return normalized; } function requireStagingLagoApiUrl(env: CustomerPortalUatEnvironment): string { return normalizeCustomerPortalStagingLagoApiUrl(requiredEnvironmentValue(env, "LAGO_API_URL")); } function parseDatabaseBinding(env: CustomerPortalUatEnvironment): CustomerPortalUatDatabaseBinding { const databaseUrl = requiredEnvironmentValue(env, "DATABASE_URL"); const expectedDatabaseHost = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE_HOST"); const expectedDatabasePort = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE_PORT"); const expectedDatabaseName = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_DATABASE"); const operatorUserId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_OPERATOR_USER_ID"); const auditChainSecret = requiredEnvironmentValue(env, "AUDIT_CHAIN_SECRET"); let parsed: URL; try { parsed = new URL(databaseUrl); } catch { throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must be a valid PostgreSQL URL"); } const databaseName = decodeURIComponent(parsed.pathname.replace(/^\//u, "")); if (!new Set(["postgres:", "postgresql:"]).has(parsed.protocol)) { throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must use PostgreSQL"); } if (parsed.username !== "hivegrid_app" || !parsed.password) { throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must authenticate as hivegrid_app"); } // pg-connection-string treats URI query parameters such as host, user, // port, database, service and options as connection-setting overrides. // Reject the entire query/fragment surface instead of trying to maintain a // partial deny-list that can silently grow behind this staging mutation // boundary. if (parsed.search || parsed.hash) { throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL must not contain PostgreSQL connection overrides"); } if (parsed.hostname !== expectedDatabaseHost || parsed.port !== expectedDatabasePort || databaseName !== expectedDatabaseName) { throw new CustomerPortalUatError("customer-portal UAT: DATABASE_URL does not match the explicit staging database binding"); } return { databaseUrl, expectedDatabaseHost, expectedDatabasePort, expectedDatabaseName, operatorUserId, auditChainSecret }; } function assertMutationConfirmation(argv: readonly string[], mode: CustomerPortalUatMode, target: CustomerPortalUatTarget): void { const confirmation = parseSingleValueArgument(argv, "--confirm"); const expectedConfirmation = target === "commercial-fixture" ? CUSTOMER_PORTAL_UAT_COMMERCIAL_CONFIRMATION : CUSTOMER_PORTAL_UAT_TENANT_SLUG; if (mode === "apply") { if (confirmation !== expectedConfirmation) { throw new CustomerPortalUatError(`customer-portal UAT: apply requires --confirm=${expectedConfirmation}`); } return; } if (confirmation !== undefined) { throw new CustomerPortalUatError("customer-portal UAT: --confirm is valid only with --apply"); } } function requireStrongUatPassword(env: CustomerPortalUatEnvironment): string { const password = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_PASSWORD"); if (password.length < 20 || new Set(password).size < 10 || /^(?:password|passwort|demo|hivegrid)/iu.test(password)) { throw new CustomerPortalUatError("customer-portal UAT: CUSTOMER_PORTAL_UAT_PASSWORD must be a strong random secret of at least 20 characters"); } return password; } export function parseCustomerPortalUatCommand( target: CustomerPortalUatTarget, argv: readonly string[], env: CustomerPortalUatEnvironment ): CustomerPortalUatCommand { assertKnownArguments(argv); const mode = parseMode(argv); assertMutationConfirmation(argv, mode, target); assertOperatorEnvironment(env); const database = parseDatabaseBinding(env); if (target === "catalog") { return { ...database, target, mode, lagoApiUrl: requireStagingLagoApiUrl(env), lagoApiKey: requiredEnvironmentValue(env, "LAGO_API_KEY"), }; } if (target === "fixture") { return { ...database, target, mode, expectedTenantId: requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_TENANT_ID"), password: requireStrongUatPassword(env), }; } const expectedStarterTenantId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_STARTER_TENANT_ID"); const expectedProTenantId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_PRO_TENANT_ID"); const expectedEnterpriseTenantId = requiredEnvironmentValue(env, "CUSTOMER_PORTAL_UAT_EXPECTED_ENTERPRISE_TENANT_ID"); if (new Set([expectedStarterTenantId, expectedProTenantId, expectedEnterpriseTenantId]).size !== 3) { throw new CustomerPortalUatError("customer-portal UAT: starter, pro, and Enterprise tenant bindings must be distinct"); } return { ...database, target, mode, expectedStarterTenantId, expectedProTenantId, expectedEnterpriseTenantId, password: requireStrongUatPassword(env), }; } export function safeCustomerPortalUatError(error: unknown): string { if (error instanceof CustomerPortalUatError) return error.message; return "customer-portal UAT: operator command failed; inspect redacted service logs"; }