Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(db): prevent first-boot crashes and respect operator env

rmyndharisc09fe615441b
diff --git a/package.json b/package.json
index 91aeab807..ae35b5ff0 100644
--- a/package.json
+++ b/package.json
@@ -24,11 +24,15 @@
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"typeorm": "typeorm-ts-node-commonjs",
+ "typeorm:prod": "typeorm",
"migration:create": "npm run typeorm -- migration:create src/database/migrations/$npm_config_name",
"migration:generate": "npm run typeorm -- migration:generate src/database/migrations/$npm_config_name -d src/database/data-source.ts",
"migration:run": "npm run typeorm -- migration:run -d src/database/data-source.ts",
+ "migration:run:prod": "npm run typeorm:prod -- migration:run -d dist/database/data-source.js",
"migration:revert": "npm run typeorm -- migration:revert -d src/database/data-source.ts",
- "migration:show": "npm run typeorm -- migration:show -d src/database/data-source.ts"
+ "migration:revert:prod": "npm run typeorm:prod -- migration:revert -d dist/database/data-source.js",
+ "migration:show": "npm run typeorm -- migration:show -d src/database/data-source.ts",
+ "migration:show:prod": "npm run typeorm:prod -- migration:show -d dist/database/data-source.js"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.995.0",
diff --git a/src/app.module.ts b/src/app.module.ts
index 68e4da1c9..ca4a704fb 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -72,7 +72,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
__dirname + '/modules/webhook/**/*.entity{.ts,.js}',
__dirname + '/modules/message/**/*.entity{.ts,.js}',
],
- synchronize: configService.get<boolean>('dataDatabase.synchronize', false),
+ migrations: [__dirname + '/database/migrations/*{.ts,.js}'],
logging: configService.get<boolean>('dataDatabase.logging', false),
};
@@ -85,6 +85,9 @@ if (process.env.QUEUE_ENABLED === 'true') {
username: configService.get<string>('dataDatabase.username'),
password: configService.get<string>('dataDatabase.password'),
database: 'openwa',
+ // Never auto-sync Postgres in production; rely on migrations.
+ synchronize: configService.get<boolean>('dataDatabase.synchronize', false),
+ migrationsRun: true,
retryAttempts: 10,
retryDelay: 3000,
extra: {
@@ -93,10 +96,15 @@ if (process.env.QUEUE_ENABLED === 'true') {
};
}
+ // SQLite: zero-config. Default to synchronize=true so the embedded
+ // database "just works" on first boot without a separate migration step.
+ // Users can opt out with DATABASE_SYNCHRONIZE=false to use migrations instead.
return {
...baseConfig,
type: 'sqlite' as const,
database: configService.get<string>('dataDatabase.database', './data/openwa.sqlite'),
+ synchronize: configService.get<boolean>('dataDatabase.synchronize', true),
+ migrationsRun: !configService.get<boolean>('dataDatabase.synchronize', true),
};
},
}),
diff --git a/src/main.ts b/src/main.ts
index 97230f595..64a0fc3df 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -8,11 +8,16 @@ import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as path from 'path';
-// Configuration loading:
-// 1. If data/.env.generated exists, load it (persisted config from dashboard)
-// 2. If not, create it with minimal defaults (first run)
-// 3. .env.generated is the single source of truth
+// 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);
@@ -20,15 +25,23 @@ if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
+// 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: true });
+ 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
+# 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
@@ -48,7 +61,7 @@ STORAGE_PATH=./data/media
`;
fs.writeFileSync(generatedEnvPath, minimalConfig);
console.log('[Bootstrap] Created default configuration at:', generatedEnvPath);
- dotenv.config({ path: generatedEnvPath, override: true });
+ dotenv.config({ path: generatedEnvPath, override: false });
}
async function bootstrap() {
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index 19abc7134..8eea14aab 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -1,5 +1,4 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, Index } from 'typeorm';
-import { jsonColumnType } from '../../../common/utils/column-types';
export enum AuditAction {
// API Key events
@@ -76,7 +75,9 @@ export class AuditLog {
@Column({ type: 'int', nullable: true })
statusCode: number | null;
- @Column({ type: jsonColumnType(), nullable: true })
+ // The "main" database connection is always SQLite (boot config),
+ // so we use simple-json regardless of the user's data DB choice.
+ @Column({ type: 'simple-json', nullable: true })
metadata: Record<string, unknown> | null;
@Column({ type: 'text', nullable: true })