Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra,config): sweep stale export archives and tighten bootstrap config guards (#960)
Yudhi Armyndharisa40ee9736c16
diff --git a/.env.example b/.env.exampleindex 7f03ec90e..04b4295e8 100644--- a/.env.example+++ b/.env.example@@ -314,6 +314,7 @@ WEBHOOK_SSRF_PROTECT=true# How often an S3-configured service re-probes a bucket that was unreachable at boot (media storage is# degraded to the local fallback dir until it recovers; writes return to S3 automatically).# S3_REPROBE_INTERVAL_MS=60000 # default 60s+# STORAGE_EXPORT_SWEEP_MAX_AGE_MS=86400000 # boot sweep deletes export archives orphaned by a restart, older than this (default 24h)# =============================================================================# RATE LIMITING (all TTLs are in MILLISECONDS)diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex 54f630f98..62804ec25 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -125,6 +125,20 @@ describe('validateEnv', () => {expect(() => validateEnv({})).not.toThrow();});+ it('rejects a REDIS_ENABLED typo instead of silently downgrading throttler+cache to in-memory', () => {+ // REDIS_ENABLED is read at boot with `=== 'true'` (throttler storage in app.module.ts,+ // CacheService), so a typo flips rate limiting + caching to per-process in-memory with zero+ // diagnostics — a silent behavior/security downgrade on a multi-replica deployment.+ expect(() => validateEnv({ REDIS_ENABLED: 'ture' })).toThrow(/REDIS_ENABLED/);+ expect(() => validateEnv({ REDIS_ENABLED: 'True' })).toThrow(/REDIS_ENABLED/);+ expect(() => validateEnv({ REDIS_ENABLED: '1' })).toThrow(/REDIS_ENABLED/);+ // Canonical values, blank (compose `${KEY:-}` forward), and unset all pass.+ expect(() => validateEnv({ REDIS_ENABLED: 'true' })).not.toThrow();+ expect(() => validateEnv({ REDIS_ENABLED: 'false' })).not.toThrow();+ expect(() => validateEnv({ REDIS_ENABLED: '' })).not.toThrow();+ expect(() => validateEnv({})).not.toThrow();+ });+it('rejects a SEARCH_PROVIDER typo instead of silently falling back to auto', () => {// A bogus / typo value must fail fast at boot rather than silently selecting the default provider.expect(() => validateEnv({ SEARCH_PROVIDER: 'bogus' })).toThrow(/SEARCH_PROVIDER/);@@ -160,6 +174,44 @@ describe('validateEnv', () => {).not.toThrow();});+ it('resolves the main DB path from MAIN_DATABASE_NAME like the runtime (no false-negative/-positive)', () => {+ // The runtime main path is MAIN_DATABASE_NAME || ./data/main.sqlite (configuration.ts). When it+ // is overridden, a DATABASE_NAME following it to the same file must still be caught — comparing+ // against the hardcoded default alone would miss this.+ expect(() =>+ validateEnv({+ DATABASE_TYPE: 'sqlite',+ MAIN_DATABASE_NAME: '/srv/openwa/main.sqlite',+ DATABASE_NAME: '/srv/openwa/main.sqlite',+ }),+ ).toThrow(/DATABASE_NAME/);+ // Same collision via a non-normalized spelling (relative/absolute forms of one file).+ expect(() =>+ validateEnv({+ DATABASE_TYPE: 'sqlite',+ MAIN_DATABASE_NAME: './custom/main.sqlite',+ DATABASE_NAME: './custom/../custom/main.sqlite',+ }),+ ).toThrow(/DATABASE_NAME/);+ // And the reverse: when MAIN_DATABASE_NAME moves the main DB elsewhere, the DEFAULT main file+ // is no longer the runtime main DB, so using it for data must NOT be rejected.+ expect(() =>+ validateEnv({+ DATABASE_TYPE: 'sqlite',+ MAIN_DATABASE_NAME: '/srv/openwa/main.sqlite',+ DATABASE_NAME: './data/main.sqlite',+ }),+ ).not.toThrow();+ // Distinct overridden paths pass.+ expect(() =>+ validateEnv({+ DATABASE_TYPE: 'sqlite',+ MAIN_DATABASE_NAME: './data/auth.sqlite',+ DATABASE_NAME: './data/openwa.sqlite',+ }),+ ).not.toThrow();+ });+it('rejects DATABASE_SYNCHRONIZE=true with DATABASE_TYPE=postgres (drops body_ts → /search 501)', () => {// The Postgres data connection hardcodes migrationsRun=true; an opted-in synchronize=true makes// TypeORM re-sync from entities on every boot, dropping the migration-created `body_ts` generateddiff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 613a4bdad..6ac86b784 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -2,8 +2,40 @@ import { resolve } from 'path';type EnvConfig = Record<string, unknown>;-// The 'main' (auth/audit) connection is always this fixed SQLite file (not env-overridable).-const MAIN_DB_PATH = './data/main.sqlite';+// Default SQLite file of the 'main' (auth/audit) connection. The runtime path is env-overridable via+// MAIN_DATABASE_NAME (configuration.ts), so the collision guard below must resolve the EFFECTIVE+// path — comparing against this constant alone would false-negative when MAIN_DATABASE_NAME moves+// the main DB and DATABASE_NAME follows it, and false-positive when the main DB moved away but+// DATABASE_NAME still points at the (now unused) default file.+const MAIN_DB_DEFAULT_PATH = './data/main.sqlite';++/**+ * Collision guard shared by boot validation (validateEnv below) and the migration CLI+ * (src/database/data-source.ts / data-source-main.ts — the TypeORM CLI never runs ConfigModule's+ * validate(), so both entry points apply this guard themselves). When the 'data' connection is+ * SQLite (explicit or defaulted), its file must not BE the 'main' connection's file: two TypeORM+ * connections on one SQLite file run separate migration ledgers + synchronize policies against the+ * same tables. Both paths are resolved exactly like the runtime (MAIN_DATABASE_NAME / DATABASE_NAME+ * overriding the defaults in configuration.ts) and normalized to absolute, so a relative spelling+ * ('./data/../data/main.sqlite') or an absolute path naming the same file is caught. Returns the+ * error message on collision, null otherwise.+ */+export function sqliteDataMainPathCollision(config: EnvConfig): string | null {+ const read = (key: string): string | undefined => {+ const value = config[key];+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;+ };+ // Postgres uses a bare database NAME, never a file path — no collision is possible there.+ const dbType = read('DATABASE_TYPE');+ if (dbType !== undefined && dbType !== 'sqlite') return null;+ const dataDbName = read('DATABASE_NAME');+ if (!dataDbName) return null;+ const mainDbPath = read('MAIN_DATABASE_NAME') || MAIN_DB_DEFAULT_PATH;+ if (resolve(dataDbName) === resolve(mainDbPath)) {+ return `DATABASE_NAME must not point at the main database file (${mainDbPath}); use a separate file`;+ }+ return null;+}/*** Fail-fast environment validation. Wired as ConfigModule's `validate`@@ -74,11 +106,14 @@ export function validateEnv(config: EnvConfig): EnvConfig {// SQLite (explicit or default): DATABASE_NAME is a file path for the 'data' connection. It must// not resolve to the 'main' DB file — two TypeORM connections on one SQLite file run separate// migration ledgers + synchronize policies against the same tables, risking schema divergence and- // lock contention. (Postgres DATABASE_NAME is a bare db name, so this never applies there.)- const dataDbName = str('DATABASE_NAME');- if (dataDbName && resolve(dataDbName) === resolve(MAIN_DB_PATH)) {- errors.push(`DATABASE_NAME must not point at the main database file (${MAIN_DB_PATH}); use a separate file`);+ // lock contention. The main path is resolved like the runtime (MAIN_DATABASE_NAME || default),+ // not assumed to be the default file. (Postgres DATABASE_NAME is a bare db name, so this never+ // applies there.)+ const collision = sqliteDataMainPathCollision(config);+ if (collision) {+ errors.push(collision);}+ const dataDbName = str('DATABASE_NAME');// Reject a bare name with no path separator and no .sqlite/.db suffix — the exact signature of a// PostgreSQL DATABASE_NAME (e.g. 'openwa') leaking into a SQLite run (#677). That bare name becomes// the SQLite file PATH, opening a file named 'openwa' under the read-only app rootfs →@@ -194,6 +229,9 @@ export function validateEnv(config: EnvConfig): EnvConfig {'RESOLVE_LID_TO_PHONE','SIMULATE_TYPING','SEARCH_ENABLED',+ // Read at boot by the throttler factory (app.module.ts) and CacheService with `=== 'true'`: a+ // typo like `ture` silently downgrades rate-limit storage + cache to per-process in-memory.+ 'REDIS_ENABLED',]) {checkBool(key);}diff --git a/src/database/data-source-main.spec.ts b/src/database/data-source-main.spec.tsindex 9d14ef706..ffd0bccee 100644--- a/src/database/data-source-main.spec.ts+++ b/src/database/data-source-main.spec.ts@@ -52,4 +52,27 @@ describe('main CLI DataSource', () => {else delete process.env.MAIN_DATABASE_NAME;}});++ it('refuses to load when DATABASE_NAME resolves to the main DB file (CLI collision guard)', () => {+ // The migration CLI never runs ConfigModule's validate(), so the SQLite main/data collision+ // guard is applied at module load instead — a shared broken env must fail the CLI too, before+ // any migration runs against the wrong file.+ const prevMain = process.env.MAIN_DATABASE_NAME;+ const prevData = process.env.DATABASE_NAME;+ process.env.MAIN_DATABASE_NAME = '/tmp/cli-guard-main.sqlite';+ process.env.DATABASE_NAME = '/tmp/cli-guard-main.sqlite';+ jest.resetModules();+ try {+ expect(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ require('./data-source-main');+ }).toThrow(/DATABASE_NAME/);+ } finally {+ if (prevMain !== undefined) process.env.MAIN_DATABASE_NAME = prevMain;+ else delete process.env.MAIN_DATABASE_NAME;+ if (prevData !== undefined) process.env.DATABASE_NAME = prevData;+ else delete process.env.DATABASE_NAME;+ jest.resetModules();+ }+ });});diff --git a/src/database/data-source-main.ts b/src/database/data-source-main.tsindex 28753e051..f1b16fa7c 100644--- a/src/database/data-source-main.ts+++ b/src/database/data-source-main.ts@@ -1,9 +1,19 @@import { DataSource } from 'typeorm';import { loadCliEnv } from './load-cli-env';+import { sqliteDataMainPathCollision } from '../config/env.validation';// Load environment variables with the app's precedence (mirrors data-source.ts / main.ts).loadCliEnv();+// Same guard as data-source.ts: the TypeORM CLI never runs ConfigModule's validate(), so the+// SQLite main/data file collision check from env.validation is re-applied here — a shared broken+// env (DATABASE_NAME resolving to the main file) must refuse BOTH migration entry points, not just+// the data one.+const sqlitePathCollision = sqliteDataMainPathCollision(process.env);+if (sqlitePathCollision) {+ throw new Error(sqlitePathCollision);+}+/*** Standalone TypeORM CLI DataSource for the MAIN connection (auth + audit).*diff --git a/src/database/data-source.spec.ts b/src/database/data-source.spec.tsindex 2dafb12ce..6f579a8f7 100644--- a/src/database/data-source.spec.ts+++ b/src/database/data-source.spec.ts@@ -31,6 +31,30 @@ describe('data CLI DataSource', () => {expect(pattern).not.toMatch(/\/\.\.\/\*\*\/\*\.entity/);}});++ it('refuses to load when DATABASE_NAME resolves to the main DB file (CLI collision guard)', () => {+ // The migration CLI never runs ConfigModule's validate(), so the SQLite main/data collision+ // guard is applied at module load instead — data migrations must never run against the main+ // (auth/audit) file.+ const prevMain = process.env.MAIN_DATABASE_NAME;+ const prevData = process.env.DATABASE_NAME;+ process.env.MAIN_DATABASE_NAME = '/tmp/cli-guard-main.sqlite';+ // A non-normalized relative spelling of the same file must be caught too.+ process.env.DATABASE_NAME = '/tmp/../tmp/cli-guard-main.sqlite';+ jest.resetModules();+ try {+ expect(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ require('./data-source');+ }).toThrow(/DATABASE_NAME/);+ } finally {+ if (prevMain !== undefined) process.env.MAIN_DATABASE_NAME = prevMain;+ else delete process.env.MAIN_DATABASE_NAME;+ if (prevData !== undefined) process.env.DATABASE_NAME = prevData;+ else delete process.env.DATABASE_NAME;+ jest.resetModules();+ }+ });});// The migration CLI connection runs DDL (CREATE INDEX, unique backfills) that can legitimately takediff --git a/src/database/data-source.ts b/src/database/data-source.tsindex b4ce9c7ba..a917e2cbd 100644--- a/src/database/data-source.ts+++ b/src/database/data-source.ts@@ -1,11 +1,22 @@import { DataSource, DataSourceOptions } from 'typeorm';import * as path from 'path';import { loadCliEnv } from './load-cli-env';+import { sqliteDataMainPathCollision } from '../config/env.validation';// Load env with the same precedence as the app (process.env > .env > data/.env.generated), so the// migration CLI targets the SAME database the dashboard configured — not the default SQLite DB.loadCliEnv();+// The TypeORM CLI never runs ConfigModule's validate(), so the boot-time guards in env.validation+// don't apply here. The one that matters for a DDL-issuing connection is re-applied explicitly:+// DATABASE_NAME must not resolve to the main (auth/audit) SQLite file, or data migrations would+// run against the wrong database. Resolved exactly like the runtime (env → default), so the CLI+// and the app make the same call.+const sqlitePathCollision = sqliteDataMainPathCollision(process.env);+if (sqlitePathCollision) {+ throw new Error(sqlitePathCollision);+}+const dbType = process.env.DATABASE_TYPE || 'sqlite';const sourceGlob = (...segments: string[]): string => path.join(__dirname, ...segments).replace(/\\/g, '/');diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex f7ca89c84..8eb1c3ac3 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -1721,6 +1721,103 @@ describe('InfraController.exportStorage keeps the export import-able and sweeps});});+describe('InfraController.sweepStaleExportArchives (boot orphan sweep)', () => {+ function buildController() {+ return new InfraController(+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ );+ }++ // A name in exactly the shape exportStorage writes: storage-export-<epochMs>-<uuid>.tar.gz.+ const archiveName = (epochMs: number): string =>+ `storage-export-${epochMs}-3b241101-e2bb-4255-8caf-4136c566a962.tar.gz`;++ const exists = (p: string): Promise<boolean> =>+ fs.promises+ .access(p)+ .then(() => true)+ .catch(() => false);++ let dir: string | undefined;+ let cwdSpy: jest.SpyInstance | undefined;++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-exports-'));+ });++ afterEach(() => {+ cwdSpy?.mockRestore();+ cwdSpy = undefined;+ if (dir) fs.rmSync(dir, { recursive: true, force: true });+ dir = undefined;+ delete process.env.STORAGE_EXPORT_SWEEP_MAX_AGE_MS;+ });++ const touch = async (name: string): Promise<string> => {+ const p = path.join(dir!, name);+ await fs.promises.writeFile(p, 'archive-bytes');+ return p;+ };++ it('deletes export archives older than the default 24h but keeps young archives and non-export files', async () => {+ const stale = await touch(archiveName(Date.now() - 25 * 60 * 60 * 1000));+ const young = await touch(archiveName(Date.now() - 60 * 1000));+ const operatorImportCandidate = await touch('to-import.tar.gz');+ // Near-miss names are NOT ours: no uuid / wrong extension / different prefix.+ const noUuid = await touch(`storage-export-${Date.now() - 48 * 60 * 60 * 1000}.tar.gz`);+ const wrongExt = await touch(archiveName(Date.now() - 48 * 60 * 60 * 1000).replace(/\.tar\.gz$/, '.zip'));+ const otherPrefix = await touch(`backup-${Date.now() - 48 * 60 * 60 * 1000}.tar.gz`);++ await buildController().sweepStaleExportArchives(dir);++ expect(await exists(stale)).toBe(false);+ expect(await exists(young)).toBe(true);+ expect(await exists(operatorImportCandidate)).toBe(true);+ expect(await exists(noUuid)).toBe(true);+ expect(await exists(wrongExt)).toBe(true);+ expect(await exists(otherPrefix)).toBe(true);+ });++ it('takes the max age from STORAGE_EXPORT_SWEEP_MAX_AGE_MS', async () => {+ const oneHourOld = archiveName(Date.now() - 60 * 60 * 1000);++ // A 30-minute cap sweeps a 1-hour-old archive...+ process.env.STORAGE_EXPORT_SWEEP_MAX_AGE_MS = '1800000';+ const swept = await touch(oneHourOld);+ await buildController().sweepStaleExportArchives(dir);+ expect(await exists(swept)).toBe(false);++ // ...while a 2-hour cap keeps it.+ process.env.STORAGE_EXPORT_SWEEP_MAX_AGE_MS = '7200000';+ const kept = await touch(oneHourOld);+ await buildController().sweepStaleExportArchives(dir);+ expect(await exists(kept)).toBe(true);+ });++ it('resolves quietly when the exports directory does not exist yet', async () => {+ await expect(buildController().sweepStaleExportArchives(path.join(dir!, 'never-created'))).resolves.toBeUndefined();+ });++ it('runs the sweep against <cwd>/data/exports at application bootstrap', async () => {+ cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(dir!);+ const exportDir = path.join(dir!, 'data', 'exports');+ await fs.promises.mkdir(exportDir, { recursive: true });+ const stale = path.join(exportDir, archiveName(Date.now() - 25 * 60 * 60 * 1000));+ await fs.promises.writeFile(stale, 'archive-bytes');++ await buildController().onApplicationBootstrap();++ expect(await exists(stale)).toBe(false);+ });+});+describe('InfraController.requestRestart constrains teardown to managed profiles', () => {const buildController = (dockerService: Record<string, unknown>) =>new InfraController(diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex f366909f6..d4e1bf689 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -9,6 +9,7 @@ import {HttpException,HttpCode,HttpStatus,+ OnApplicationBootstrap,Optional,} from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiPropertyOptional } from '@nestjs/swagger';@@ -329,7 +330,7 @@ interface SavedConfigResponse {@ApiTags('infrastructure')@Controller('infra')-export class InfraController {+export class InfraController implements OnApplicationBootstrap {private readonly logger = createLogger('InfraController');constructor(@@ -388,6 +389,62 @@ export class InfraController {}}+ // Matches exactly the filename exportStorage writes: storage-export-<Date.now()>-<randomUUID()>.tar.gz.+ // The captured group is the creation epoch-ms, so the sweep reads the age from the name — anything+ // not in this exact shape (an operator's import candidate, any other file) is never touched.+ private static readonly EXPORT_ARCHIVE_PATTERN =+ /^storage-export-(\d+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tar\.gz$/;++ /**+ * Boot sweep for orphaned storage-export archives. exportStorage deletes each archive on a TTL+ * timer, but that timer dies with the process — an archive whose process restarted or crashed+ * before the timer fired would accumulate on the data volume forever. At bootstrap, delete the+ * archives WE created whose embedded creation timestamp is older than+ * STORAGE_EXPORT_SWEEP_MAX_AGE_MS (default 24h; kept generous so the documented+ * export→restart→import migration flow still finds its file). Young archives and any+ * non-export file in data/exports/ are left untouched.+ */+ async onApplicationBootstrap(): Promise<void> {+ await this.sweepStaleExportArchives();+ }++ /**+ * Delete export archives older than STORAGE_EXPORT_SWEEP_MAX_AGE_MS from exportDir. Sweep+ * failures are logged, never thrown: a leftover archive must not block boot.+ */+ async sweepStaleExportArchives(exportDir = path.join(process.cwd(), 'data', 'exports')): Promise<void> {+ const maxAgeRaw = Number.parseInt(process.env.STORAGE_EXPORT_SWEEP_MAX_AGE_MS ?? '', 10);+ const maxAgeMs = Number.isInteger(maxAgeRaw) && maxAgeRaw > 0 ? maxAgeRaw : 24 * 60 * 60 * 1000; // default 24h++ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(exportDir, { withFileTypes: true });+ } catch (error) {+ // ENOENT just means no export has ever run on this deployment — nothing to sweep.+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {+ this.logger.warn('Storage export sweep could not read the exports directory', {+ exportDir,+ error: String(error),+ });+ }+ return;+ }++ const now = Date.now();+ for (const entry of entries) {+ if (!entry.isFile()) continue;+ const match = InfraController.EXPORT_ARCHIVE_PATTERN.exec(entry.name);+ if (!match) continue;+ if (now - Number(match[1]) < maxAgeMs) continue;+ try {+ await fs.promises.unlink(path.join(exportDir, entry.name));+ this.logger.log('Swept stale storage export archive', { file: entry.name });+ } catch (error) {+ this.logger.warn('Failed to sweep stale storage export archive', { file: entry.name, error: String(error) });+ }+ }+ }+@Get('status')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get infrastructure status' })