Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(config): write the env loader's boot lines through the logger
Yudhi Armyndharisaf3c08dd341e
diff --git a/src/config/load-env.spec.ts b/src/config/load-env.spec.tsindex 3c2a88474..050bf3942 100644--- a/src/config/load-env.spec.ts+++ b/src/config/load-env.spec.ts@@ -89,6 +89,30 @@ describe('loadEnvironment', () => {expect(log.mock.calls.map(args => args.join(' '))).not.toContainEqual(expect.stringContaining('injected env'));});+ // The image runs with NODE_ENV=production, where the logger emits JSON. A raw console line from the+ // loader would land in that stream as plain text, with no level for an aggregator to filter on.+ it.each<[string, Record<string, string>]>([+ ['a saved configuration', { '.env': 'DATABASE_SSL=false\n', 'data/.env.generated': 'DATABASE_SSL=true\n' }],+ ['a first run', { '.env': 'REDIS_HOST=redis.internal\n' }],+ ])('writes its boot lines through the structured logger on %s', (_case, files) => {+ delete process.env.DATABASE_SSL;+ process.env.LOG_FORMAT = 'json';+ makeTempCwd(files);+ const lines: string[] = [];+ const capture = (line: unknown): void => void lines.push(String(line));+ jest.spyOn(console, 'log').mockImplementation(capture);+ jest.spyOn(console, 'warn').mockImplementation(capture);++ runLoader();++ expect(lines.length).toBeGreaterThan(0);+ for (const line of lines) {+ const entry = JSON.parse(line) as { context?: string; level?: string };+ expect(entry.context).toBe('Bootstrap');+ expect(['info', 'warn']).toContain(entry.level);+ }+ });+// Older .env templates shipped DATABASE_SSL=false, and compose forwards it, so it silently outranks// TLS turned on in the dashboard. The override stands, but the boot log names both values.it('warns when a pinned database TLS setting differs from the one saved in the dashboard', () => {diff --git a/src/config/load-env.ts b/src/config/load-env.tsindex 1372524df..9ce443b04 100644--- a/src/config/load-env.ts+++ b/src/config/load-env.ts@@ -1,9 +1,14 @@import * as dotenv from 'dotenv';import * as fs from 'fs';import * as path from 'path';+import { createLogger } from '../common/services/logger.service';import { writeSecretFile } from '../common/utils/secret-file';import { clearBlankEnv, recordOsEnvKeys, recordPinnedEnvKeys, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';+// LoggerService reads its format and level per write and nothing at import, so it is safe to use+// before the env files below are merged in.+const logger = createLogger('Bootstrap');+/*** Load configuration into process.env BEFORE any application module is imported.*@@ -56,7 +61,7 @@ export function loadEnvironment(): void {// 2. User-managed .env (does not override real process env)if (fs.existsSync(userEnvPath)) {- console.log('[Bootstrap] Loading .env from:', userEnvPath);+ logger.log(`Loading .env from: ${userEnvPath}`);dotenv.config({ path: userEnvPath, override: false, quiet: true });}@@ -68,20 +73,20 @@ export function loadEnvironment(): void {// 3. Dashboard-saved config (does not override .env or process env)if (fs.existsSync(generatedEnvPath)) {- console.log('[Bootstrap] Loading saved configuration from:', generatedEnvPath);+ logger.log(`Loading saved configuration from: ${generatedEnvPath}`);const { parsed = {} } = dotenv.config({ path: generatedEnvPath, override: false, quiet: true });// Compose forwards DATABASE_SSL*, and templates older than 0.18 set DATABASE_SSL=false in .env, so// a stale line can outrank TLS turned on in the dashboard. The override stands; the log names it.for (const key of ['DATABASE_SSL', 'DATABASE_SSL_REJECT_UNAUTHORIZED']) {if (parsed[key] !== undefined && process.env[key] !== parsed[key]) {- console.warn(- `[Bootstrap] ${key}=${process.env[key]} from the environment or .env overrides ${key}=${parsed[key]} ` ++ logger.warn(+ `${key}=${process.env[key]} from the environment or .env overrides ${key}=${parsed[key]} ` +'saved in data/.env.generated (Dashboard > Infrastructure)',);}}} else {- console.log('[Bootstrap] First run detected, creating default configuration...');+ logger.log('First run detected, creating default configuration...');// Create minimal .env.generated with sensible defaultsconst minimalConfig = `# OpenWA Configuration# Generated automatically on first run@@ -105,7 +110,7 @@ STORAGE_LOCAL_PATH=./data/media# Docker Profiles: none (minimal setup)`;writeSecretFile(generatedEnvPath, minimalConfig);- console.log('[Bootstrap] Created default configuration at:', generatedEnvPath);+ logger.log(`Created default configuration at: ${generatedEnvPath}`);dotenv.config({ path: generatedEnvPath, override: false, quiet: true });}}