Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(boot): validate the environment before any boot side effect
Yudhi Armyndharis8a6d1b6129b0
diff --git a/src/config/boot-env-validation.spec.ts b/src/config/boot-env-validation.spec.tsnew file mode 100644index 000000000..147e387f5--- /dev/null+++ b/src/config/boot-env-validation.spec.ts@@ -0,0 +1,50 @@+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++/**+ * Boots the real entry point with an invalid environment on the built-in PostgreSQL path, the one+ * that does Docker I/O before NestFactory.create. The config must be rejected once, before any of+ * that runs, instead of starting the container and then failing inside the module graph.+ */+describe('main.ts validates the environment before any boot side effect', () => {+ const REPO = join(__dirname, '..', '..');+ let cwd: string;++ beforeAll(() => {+ cwd = mkdtempSync(join(tmpdir(), 'openwa-boot-env-'));+ });+ afterAll(() => rmSync(cwd, { recursive: true, force: true }));++ it('exits 1 with one fatal line and never reaches DockerService', () => {+ const result = spawnSync(+ join(REPO, 'node_modules', '.bin', 'ts-node-transpile-only'),+ ['--project', join(REPO, 'tsconfig.json'), join(REPO, 'src', 'main.ts')],+ {+ cwd,+ encoding: 'utf8',+ timeout: 60_000,+ env: {+ PATH: process.env.PATH,+ HOME: process.env.HOME,+ LOG_LEVEL: 'bogus',+ DATABASE_TYPE: 'postgres',+ POSTGRES_BUILTIN: 'true',+ DATABASE_HOST: 'db',+ DATABASE_USERNAME: 'u',+ DATABASE_PASSWORD: 'p',+ DOCKER_HOST: 'tcp://127.0.0.1:1',+ },+ },+ );+ const output = `${result.stdout}${result.stderr}`;++ expect(result.status).toBe(1);+ expect(output).toContain('Fatal error during bootstrap');+ expect(output).toContain('LOG_LEVEL must be one of');+ expect(output).not.toContain('Unhandled promise rejection');+ expect(output).not.toContain('DockerService');+ expect(output.match(/LOG_LEVEL must be one of/g)).toHaveLength(1);+ }, 90_000);+});diff --git a/src/main.ts b/src/main.tsindex 7010b6a29..07c01bf6b 100644--- a/src/main.ts+++ b/src/main.ts@@ -12,6 +12,7 @@ import { LoggerService, LogLevel, createLogger } from './common/services/logger.import { createSwaggerConfig, dropUnexpressibleOperations, exemptPublicOperations } from './config/swagger.config';import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './config/process-error-monitor';import { runBootstrapOrExit } from './config/bootstrap-fatal';+import { validateEnv } from './config/env.validation';import { resolveStorageRoot } from './config/storage-root';import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';import { applyGlobalValidation } from './config/app-validation';@@ -38,8 +39,7 @@ let appInstance: INestApplication | undefined;async function bootstrap() {// Apply the operator-configured log verbosity (LOG_LEVEL) before anything logs. Unset means INFO.- // A misspelling is skipped here; env.validation.ts rejects it and the boot fails inside- // NestFactory.create.+ // A misspelling is skipped here; validateEnv below rejects it before the boot has any side effect.const requestedLevel = process.env.LOG_LEVEL?.trim().toLowerCase();if (requestedLevel && (Object.values(LogLevel) as string[]).includes(requestedLevel)) {LoggerService.setLogLevel(requestedLevel as LogLevel);@@ -55,6 +55,11 @@ async function bootstrap() {// logger WITHOUT swallowing the exception, so the crash-and-restart posture is unchanged (see the helper).registerUncaughtExceptionMonitor(bootstrapLogger);+ // Validate the environment before anything acts on it. ConfigModule.forRoot runs the same check, but+ // only once NestFactory.create awaits it, which is after the storage root is created and a built-in+ // PostgreSQL container is started; an invalid config would do both and then be reported twice.+ validateEnv(process.env);+// Advisory (not enforced): an unset/blank NODE_ENV is the deliberate local-dev default, but it// silently degrades four controls to their dev posture (the default-secret guard, wildcard CORS,// Swagger UI, validation error detail) — warn so a production deployment that simply forgot the