Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(config): load environment before the module graph is evaluated (#523)

Yudhi Armyndharis63681bb492b5
diff --git a/src/config/load-env.spec.ts b/src/config/load-env.spec.ts
new file mode 100644
index 000000000..6be9227ed
--- /dev/null
+++ b/src/config/load-env.spec.ts
@@ -0,0 +1,83 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { workerConnectionOptions } from '../modules/queue/redis-connection';
+
+describe('loadEnvironment', () => {
+ let envBackup: NodeJS.ProcessEnv;
+ const tempDirs: string[] = [];
+
+ // Create an isolated working directory, write the given files into it (paths relative to the dir),
+ // and point process.cwd() at it. The loader reads `.env` / `data/.env.generated` from process.cwd(),
+ // so this drives it without touching the real project tree.
+ const makeTempCwd = (files: Record<string, string>): string => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-loadenv-'));
+ tempDirs.push(dir);
+ for (const [rel, content] of Object.entries(files)) {
+ const full = path.join(dir, rel);
+ fs.mkdirSync(path.dirname(full), { recursive: true });
+ fs.writeFileSync(full, content);
+ }
+ jest.spyOn(process, 'cwd').mockReturnValue(dir);
+ return dir;
+ };
+
+ // The loader runs as a side effect on import; resetModules forces a fresh evaluation each call so a
+ // test's mocked cwd/env is in effect when it runs (the spec never imports it statically, so it never
+ // runs against the real project tree).
+ const runLoader = async (): Promise<void> => {
+ jest.resetModules();
+ await import('./load-env');
+ };
+
+ beforeEach(() => {
+ envBackup = { ...process.env };
+ });
+
+ afterEach(() => {
+ for (const key of Object.keys(process.env)) {
+ if (!(key in envBackup)) delete process.env[key];
+ }
+ Object.assign(process.env, envBackup);
+ jest.restoreAllMocks();
+ for (const dir of tempDirs.splice(0)) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it('loads REDIS_HOST from a .env file so it reaches the webhook worker connection', async () => {
+ delete process.env.REDIS_HOST;
+ makeTempCwd({ '.env': 'REDIS_HOST=redis.internal\n', 'data/.env.generated': '' });
+
+ await runLoader();
+
+ expect(process.env.REDIS_HOST).toBe('redis.internal');
+ expect(workerConnectionOptions().host).toBe('redis.internal');
+ });
+
+ it('lets a real process env value win over the .env file (precedence preserved)', async () => {
+ process.env.REDIS_HOST = 'host-from-process-env';
+ makeTempCwd({
+ '.env': 'REDIS_HOST=host-from-dotenv\n',
+ 'data/.env.generated': 'REDIS_HOST=host-from-generated\n',
+ });
+
+ await runLoader();
+
+ expect(process.env.REDIS_HOST).toBe('host-from-process-env');
+ expect(workerConnectionOptions().host).toBe('host-from-process-env');
+ });
+});
+
+describe('main.ts bootstrap order', () => {
+ // The webhook Worker's @Processor connection/concurrency are read at module-import time. main.ts must
+ // import the env loader FIRST so .env / .env.generated are populated before the module graph (which
+ // includes that decorator) is evaluated — otherwise the worker freezes a pre-dotenv localhost Redis.
+ // ES imports are hoisted, so this is an ordering invariant that a future reorder could silently break.
+ it('imports ./config/load-env as its very first import', () => {
+ const source = fs.readFileSync(path.resolve(__dirname, '../main.ts'), 'utf8');
+ const firstImport = source.split('\n').find(line => /^\s*import\b/.test(line));
+
+ expect(firstImport).toContain('./config/load-env');
+ });
+});
diff --git a/src/config/load-env.ts b/src/config/load-env.ts
new file mode 100644
index 000000000..a5db93213
--- /dev/null
+++ b/src/config/load-env.ts
@@ -0,0 +1,93 @@
+import * as dotenv from 'dotenv';
+import * as fs from 'fs';
+import * as path from 'path';
+import { writeSecretFile } from '../common/utils/secret-file';
+import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';
+
+/**
+ * Load configuration into process.env BEFORE any application module is imported.
+ *
+ * Loading order (later sources do NOT override earlier ones):
+ * 1. Process env (Docker, shell, systemd) — highest priority
+ * 2. .env (project-level overrides committed/managed by the user)
+ * 3. data/.env.generated (Dashboard-managed config; created on first run)
+ *
+ * Rationale: explicit env vars from the host/orchestrator must always win so that operators can
+ * override the Dashboard-saved config without having to edit data/.env.generated by hand.
+ *
+ * This runs as a side effect on import (see the call at the bottom), and main.ts imports this module
+ * first — so values from .env / .env.generated are present before any module that reads process.env at
+ * import time (e.g. the webhook Worker's @Processor connection) is evaluated. A statement in main.ts's
+ * body would run too late: ES imports are hoisted and the whole module graph evaluates before the body.
+ */
+export function loadEnvironment(): void {
+ const generatedEnvPath = path.resolve(process.cwd(), 'data', '.env.generated');
+ const userEnvPath = path.resolve(process.cwd(), '.env');
+
+ // Ensure data directory exists
+ const dataDir = path.dirname(generatedEnvPath);
+ if (!fs.existsSync(dataDir)) {
+ fs.mkdirSync(dataDir, { recursive: true });
+ }
+
+ // Tighten any pre-existing secret files written before per-file 0600 perms (best-effort) — the
+ // generated .env holds S3/DB/Redis secrets and .api-key holds the raw admin key.
+ for (const secret of [generatedEnvPath, path.resolve(dataDir, '.api-key')]) {
+ if (fs.existsSync(secret)) {
+ try {
+ fs.chmodSync(secret, 0o600);
+ } catch {
+ /* best-effort */
+ }
+ }
+ }
+
+ // A compose `- KEY=${KEY:-}` line forwards a real operator value into the container but renders an
+ // empty value when none is set. An empty process.env.KEY would still block .env / .env.generated
+ // (loaded below with override:false) from supplying one, silently shadowing the dashboard's saved
+ // value — so treat a blank value as unset for every dashboard-managed, blank-forwarded key (engine
+ // selection and the external-Postgres password).
+ clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);
+
+ // 2. User-managed .env (does not override real process env)
+ if (fs.existsSync(userEnvPath)) {
+ console.log('[Bootstrap] Loading .env from:', userEnvPath);
+ dotenv.config({ path: userEnvPath, override: false });
+ }
+
+ // 3. Dashboard-saved config (does not override .env or process env)
+ if (fs.existsSync(generatedEnvPath)) {
+ console.log('[Bootstrap] Loading saved configuration from:', generatedEnvPath);
+ dotenv.config({ path: generatedEnvPath, override: false });
+ } else {
+ console.log('[Bootstrap] First run detected, creating default configuration...');
+ // Create minimal .env.generated with sensible defaults
+ const minimalConfig = `# OpenWA Configuration
+# Generated automatically on first run
+# Edit via Dashboard > Infrastructure or modify this file directly.
+# Note: values in process env or project .env take precedence over this file.
+
+# Database (SQLite - no external service required)
+DATABASE_TYPE=sqlite
+POSTGRES_BUILTIN=false
+
+# Redis & Queue (disabled by default)
+REDIS_ENABLED=false
+REDIS_BUILTIN=false
+QUEUE_ENABLED=false
+
+# Storage (Local filesystem)
+STORAGE_TYPE=local
+MINIO_BUILTIN=false
+STORAGE_LOCAL_PATH=./data/media
+
+# Docker Profiles: none (minimal setup)
+`;
+ writeSecretFile(generatedEnvPath, minimalConfig);
+ console.log('[Bootstrap] Created default configuration at:', generatedEnvPath);
+ dotenv.config({ path: generatedEnvPath, override: false });
+ }
+}
+
+// Run immediately on import so process.env is populated before any other module is evaluated.
+loadEnvironment();
diff --git a/src/main.ts b/src/main.ts
index f780968a5..59ebb4000 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -1,3 +1,7 @@
+// The env loader MUST be the first import: it populates process.env from .env / data/.env.generated
+// before any other module is evaluated, so modules that read process.env at import time (e.g. the
+// webhook Worker's @Processor connection) see the configured values rather than pre-dotenv defaults.
+import './config/load-env';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@@ -17,86 +21,6 @@ import {
import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';
import { AuthService } from './modules/auth/auth.service';
import { Request, Response, NextFunction, json, urlencoded } from 'express';
-import { writeSecretFile } from './common/utils/secret-file';
-import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS } from './config/env-precedence';
-import * as dotenv from 'dotenv';
-import * as fs from 'fs';
-import * as path from 'path';
-
-// Configuration loading order (later sources do NOT override earlier ones):
-// 1. Process env (Docker, shell, systemd) — highest priority
-// 2. .env (project-level overrides committed/managed by the user)
-// 3. data/.env.generated (Dashboard-managed config; created on first run)
-//
-// Rationale: explicit env vars from the host/orchestrator must always win
-// so that operators can override the Dashboard-saved config without having
-// to edit data/.env.generated by hand.
-const generatedEnvPath = path.resolve(process.cwd(), 'data', '.env.generated');
-const userEnvPath = path.resolve(process.cwd(), '.env');
-
-// Ensure data directory exists
-const dataDir = path.dirname(generatedEnvPath);
-if (!fs.existsSync(dataDir)) {
- fs.mkdirSync(dataDir, { recursive: true });
-}
-
-// Tighten any pre-existing secret files written before per-file 0600 perms (best-effort) — the
-// generated .env holds S3/DB/Redis secrets and .api-key holds the raw admin key.
-for (const secret of [generatedEnvPath, path.resolve(dataDir, '.api-key')]) {
- if (fs.existsSync(secret)) {
- try {
- fs.chmodSync(secret, 0o600);
- } catch {
- /* best-effort */
- }
- }
-}
-
-// A compose `- KEY=${KEY:-}` line forwards a real operator value into the container but renders an
-// empty value when none is set. An empty process.env.KEY would still block .env / .env.generated
-// (loaded below with override:false) from supplying one, silently shadowing the dashboard's saved
-// value — so treat a blank value as unset for every dashboard-managed, blank-forwarded key (engine
-// selection and the external-Postgres password).
-clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);
-
-// 2. User-managed .env (does not override real process env)
-if (fs.existsSync(userEnvPath)) {
- console.log('[Bootstrap] Loading .env from:', userEnvPath);
- dotenv.config({ path: userEnvPath, override: false });
-}
-
-// 3. Dashboard-saved config (does not override .env or process env)
-if (fs.existsSync(generatedEnvPath)) {
- console.log('[Bootstrap] Loading saved configuration from:', generatedEnvPath);
- dotenv.config({ path: generatedEnvPath, override: false });
-} else {
- console.log('[Bootstrap] First run detected, creating default configuration...');
- // Create minimal .env.generated with sensible defaults
- const minimalConfig = `# OpenWA Configuration
-# Generated automatically on first run
-# Edit via Dashboard > Infrastructure or modify this file directly.
-# Note: values in process env or project .env take precedence over this file.
-
-# Database (SQLite - no external service required)
-DATABASE_TYPE=sqlite
-POSTGRES_BUILTIN=false
-
-# Redis & Queue (disabled by default)
-REDIS_ENABLED=false
-REDIS_BUILTIN=false
-QUEUE_ENABLED=false
-
-# Storage (Local filesystem)
-STORAGE_TYPE=local
-MINIO_BUILTIN=false
-STORAGE_LOCAL_PATH=./data/media
-
-# Docker Profiles: none (minimal setup)
-`;
- writeSecretFile(generatedEnvPath, minimalConfig);
- console.log('[Bootstrap] Created default configuration at:', generatedEnvPath);
- dotenv.config({ path: generatedEnvPath, override: false });
-}
async function bootstrap() {
// Apply the operator-configured log verbosity (LOG_LEVEL) before anything logs. Unset/invalid → INFO.