Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(infra): split InfraController into four cohesive controllers
Yudhi Armyndharis77e315edded3
diff --git a/openapi.json b/openapi.jsonindex 6ad301d6d..bd280c058 100644--- a/openapi.json+++ b/openapi.json@@ -2559,7 +2559,7 @@},"/api/infra/status": {"get": {- "operationId": "InfraController_getStatus",+ "operationId": "InfraStatusController_getStatus","parameters": [],"responses": {"200": {@@ -2574,7 +2574,7 @@},"/api/infra/engines": {"get": {- "operationId": "InfraController_getEngines",+ "operationId": "InfraStatusController_getEngines","parameters": [],"responses": {"200": {@@ -2589,7 +2589,7 @@},"/api/infra/engines/current": {"get": {- "operationId": "InfraController_getCurrentEngine",+ "operationId": "InfraStatusController_getCurrentEngine","parameters": [],"responses": {"200": {@@ -2602,9 +2602,25 @@]}},+ "/api/infra/health": {+ "get": {+ "operationId": "InfraStatusController_healthCheck",+ "parameters": [],+ "responses": {+ "200": {+ "description": "Server is healthy"+ }+ },+ "summary": "Health check endpoint",+ "tags": [+ "infrastructure"+ ],+ "security": []+ }+ },"/api/infra/config": {"get": {- "operationId": "InfraController_getConfig",+ "operationId": "InfraConfigController_getConfig","parameters": [],"responses": {"200": {@@ -2617,7 +2633,7 @@]},"put": {- "operationId": "InfraController_saveConfig",+ "operationId": "InfraConfigController_saveConfig","parameters": [],"requestBody": {"required": true,@@ -2643,7 +2659,7 @@},"/api/infra/restart": {"post": {- "operationId": "InfraController_requestRestart",+ "operationId": "InfraConfigController_requestRestart","parameters": [],"requestBody": {"required": false,@@ -2666,25 +2682,9 @@]}},- "/api/infra/health": {- "get": {- "operationId": "InfraController_healthCheck",- "parameters": [],- "responses": {- "200": {- "description": "Server is healthy"- }- },- "summary": "Health check endpoint",- "tags": [- "infrastructure"- ],- "security": []- }- },"/api/infra/export-data": {"get": {- "operationId": "InfraController_exportData",+ "operationId": "InfraDataController_exportData","parameters": [],"responses": {"200": {@@ -2699,7 +2699,7 @@},"/api/infra/import-data": {"post": {- "operationId": "InfraController_importData",+ "operationId": "InfraDataController_importData","parameters": [],"requestBody": {"required": true,@@ -2758,7 +2758,7 @@},"/api/infra/storage/files/count": {"get": {- "operationId": "InfraController_getStorageFileCount",+ "operationId": "InfraStorageController_getStorageFileCount","parameters": [],"responses": {"200": {@@ -2773,7 +2773,7 @@},"/api/infra/storage/export": {"get": {- "operationId": "InfraController_exportStorage",+ "operationId": "InfraStorageController_exportStorage","parameters": [],"responses": {"200": {@@ -2788,7 +2788,7 @@},"/api/infra/storage/import": {"post": {- "operationId": "InfraController_importStorage",+ "operationId": "InfraStorageController_importStorage","parameters": [],"requestBody": {"required": true,diff --git a/src/modules/infra/generated-env.ts b/src/modules/infra/generated-env.tsindex 655306bd6..6f4135b5e 100644--- a/src/modules/infra/generated-env.ts+++ b/src/modules/infra/generated-env.ts@@ -17,11 +17,12 @@ export const generatedEnvPath = (): string => path.resolve(process.cwd(), 'data'/*** Parsed contents, or `{}` when the file has never been written.*- * Three `InfraController` reads share this — the built-in-flag fallback behind the Docker probe, the- * config form's hydrate, and the merge base the save path writes back over. Re-deriving the location- * at each of them made the file an undeclared dependency shared between reading infrastructure- * status, rendering the form, and persisting credentials: three concerns that otherwise touch none of- * the same state.+ * Three reads share this — the built-in-flag fallback behind the Docker probe+ * (InfraStatusController.readSavedBuiltinFlags), the config form's hydrate+ * (InfraConfigController.getConfig), and the merge base the save path writes back over+ * (InfraConfigController.saveConfig). Re-deriving the location at each of them made the file an+ * undeclared dependency shared between reading infrastructure status, rendering the form, and+ * persisting credentials: three concerns that otherwise touch none of the same state.*/export function readGeneratedEnv(): Record<string, string> {const envPath = generatedEnvPath();diff --git a/src/modules/infra/infra-access-control.spec.ts b/src/modules/infra/infra-access-control.spec.tsnew file mode 100644index 000000000..3d0e2ca5c--- /dev/null+++ b/src/modules/infra/infra-access-control.spec.ts@@ -0,0 +1,69 @@+// StorageService (imported transitively by the infra controllers) pulls in `archiver`+// v8, which is ESM-only and cannot be parsed by ts-jest. The controller logic+// under test never touches archiver, so a lightweight stub is sufficient.+jest.mock('archiver', () => ({ default: jest.fn() }));++// saveConfig writes the generated env via fs.writeFileSync and reads the existing file+// via fs.existsSync/readFileSync; mock those so tests assert produced content without+// touching the filesystem. existsSync defaults to false (no prior config).+jest.mock('fs', () => {+ const actual = jest.requireActual<typeof import('fs')>('fs');+ return {+ ...actual,+ writeFileSync: jest.fn(),+ // saveConfig now writes the generated env via writeSecretFile, which chmods 0600 — mock it+ // so the secret-hygiene path never touches the real filesystem.+ chmodSync: jest.fn(),+ existsSync: jest.fn().mockReturnValue(false),+ readFileSync: jest.fn().mockReturnValue(''),+ createReadStream: jest.fn(() => jest.requireActual<typeof import('stream')>('stream').Readable.from([])),+ };+});++import { Reflector } from '@nestjs/core';+import { InfraStatusController } from './infra-status.controller';+import { InfraConfigController } from './infra-config.controller';+import { InfraDataController } from './infra-data.controller';+import { InfraStorageController } from './infra-storage.controller';+import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';++describe('Infra controllers access control (Vuln 2)', () => {+ const reflector = new Reflector();++ // Every mutating, data-exfiltration, and operational-read endpoint must require+ // the ADMIN role so that a low-privilege (VIEWER/OPERATOR) API key cannot wipe+ // data, read secrets, change config, restart, trigger storage import, or read+ // infrastructure status / engine / storage details (#221 tightened the reads).+ const adminOnly = [+ [InfraConfigController, 'getConfig'], // GET /infra/config (returns saved config; secrets omitted but still ADMIN-only)+ [InfraConfigController, 'saveConfig'], // PUT /infra/config+ [InfraConfigController, 'requestRestart'], // POST /infra/restart+ [InfraDataController, 'exportData'], // GET /infra/export-data (exposes webhook secrets)+ [InfraDataController, 'importData'], // POST /infra/import-data (DELETEs all rows)+ [InfraStorageController, 'exportStorage'], // GET /infra/storage/export+ [InfraStorageController, 'importStorage'], // POST /infra/storage/import+ [InfraStatusController, 'getStatus'], // GET /infra/status+ [InfraStatusController, 'getEngines'], // GET /infra/engines+ [InfraStatusController, 'getCurrentEngine'], // GET /infra/engines/current+ [InfraStorageController, 'getStorageFileCount'], // GET /infra/storage/files/count+ ] as const;++ it.each(+ adminOnly.map(([ControllerClass, method]) => ({+ label: `${ControllerClass.name}.${method}`,+ ControllerClass,+ method,+ })),+ )('$label requires the ADMIN role', ({ ControllerClass, method }) => {+ // The handler is only ever a lookup key for reflector metadata — it is never invoked, so there is+ // no `this` to lose. unbound-method (tightened in typescript-eslint 8.65) cannot tell the two+ // apart, and the cast below does not satisfy it either.++ const handler = ControllerClass.prototype[method as keyof typeof ControllerClass.prototype] as unknown as (+ ...args: unknown[]+ ) => unknown;+ const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);+ expect(role).toBe(ApiKeyRole.ADMIN);+ });+});diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.tsnew file mode 100644index 000000000..d446b295b--- /dev/null+++ b/src/modules/infra/infra-config.controller.spec.ts@@ -0,0 +1,1143 @@+import * as fs from 'fs';++// StorageService (imported transitively by the infra controllers) pulls in `archiver`+// v8, which is ESM-only and cannot be parsed by ts-jest. The controller logic+// under test never touches archiver, so a lightweight stub is sufficient.+jest.mock('archiver', () => ({ default: jest.fn() }));++// saveConfig writes the generated env via fs.writeFileSync and reads the existing file+// via fs.existsSync/readFileSync; mock those so tests assert produced content without+// touching the filesystem. existsSync defaults to false (no prior config).+jest.mock('fs', () => {+ const actual = jest.requireActual<typeof import('fs')>('fs');+ return {+ ...actual,+ writeFileSync: jest.fn(),+ // saveConfig now writes the generated env via writeSecretFile, which chmods 0600 — mock it+ // so the secret-hygiene path never touches the real filesystem.+ chmodSync: jest.fn(),+ existsSync: jest.fn().mockReturnValue(false),+ readFileSync: jest.fn().mockReturnValue(''),+ createReadStream: jest.fn(() => jest.requireActual<typeof import('stream')>('stream').Readable.from([])),+ };+});++import { BadRequestException } from '@nestjs/common';+import { plainToInstance } from 'class-transformer';+import { validate } from 'class-validator';+import { InfraConfigController } from './infra-config.controller';+import { SaveConfigDto } from './dto/save-config.dto';+import { AuditAction } from '../audit/entities/audit-log.entity';+import { recordOsEnvKeys } from '../../config/env-precedence';++describe('InfraConfigController.saveConfig SSL reject-unauthorized', () => {+ function writtenEnv(config: unknown): string {+ const spy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);+ const controller = new InfraConfigController({} as never, {} as never, {} as never);+ controller.saveConfig(config as never);+ const content = spy.mock.calls[0][1] as string;+ spy.mockRestore();+ return content;+ }++ it('writes DATABASE_SSL_REJECT_UNAUTHORIZED=false for self-signed managed Postgres', () => {+ const env = writtenEnv({+ database: { type: 'postgres', sslEnabled: true, sslRejectUnauthorized: false, password: 'unit-test-pw' },+ });+ expect(env).toContain('DATABASE_SSL=true');+ expect(env).toContain('DATABASE_SSL_REJECT_UNAUTHORIZED=false');+ });++ it('defaults DATABASE_SSL_REJECT_UNAUTHORIZED=true when SSL is enabled without an explicit flag', () => {+ const env = writtenEnv({ database: { type: 'postgres', sslEnabled: true, password: 'unit-test-pw' } });+ expect(env).toContain('DATABASE_SSL_REJECT_UNAUTHORIZED=true');+ });++ it('omits DATABASE_SSL_REJECT_UNAUTHORIZED when SSL is disabled', () => {+ const env = writtenEnv({ database: { type: 'postgres', sslEnabled: false, password: 'unit-test-pw' } });+ expect(env).not.toContain('DATABASE_SSL_REJECT_UNAUTHORIZED');+ });+});++describe('InfraConfigController PostgreSQL schema (POSTGRES_SCHEMA)', () => {+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);++ function written(config: unknown, existing?: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(config as never);+ const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ return content;+ }++ it('writes POSTGRES_SCHEMA for external Postgres', () => {+ const env = written({+ database: { type: 'postgres', builtIn: false, host: 'db', schema: 'openwa', password: 'unit-test-pw' },+ });+ expect(env).toContain('POSTGRES_SCHEMA=openwa');+ });++ it('leaves POSTGRES_SCHEMA untouched when the payload omits it (the runtime default is public)', () => {+ // Per-key merge: an absent field must not reset the stored value. With nothing stored, the+ // key stays out of the file and configuration.ts's own 'public' default applies at boot.+ const fresh = written({ database: { type: 'postgres', builtIn: false, host: 'db', password: 'unit-test-pw' } });+ expect(fresh).not.toContain('POSTGRES_SCHEMA=');+ const preserved = written(+ { database: { type: 'postgres', builtIn: false, host: 'db', password: 'unit-test-pw' } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_SCHEMA=openwa\n',+ );+ expect(preserved).toContain('POSTGRES_SCHEMA=openwa');+ });++ it('pins POSTGRES_SCHEMA=public for the built-in Postgres container', () => {+ const env = written({ database: { type: 'postgres', builtIn: true } });+ expect(env).toContain('POSTGRES_SCHEMA=public');+ });++ it('does not write POSTGRES_SCHEMA for sqlite', () => {+ const env = written({ database: { type: 'sqlite' } });+ expect(env).not.toContain('POSTGRES_SCHEMA=');+ });++ it('getConfig surfaces the saved POSTGRES_SCHEMA, defaulting to public', () => {+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=postgres\nPOSTGRES_SCHEMA=openwa\n');+ expect(newController().getConfig().database.schema).toBe('openwa');+ (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=postgres\n');+ expect(newController().getConfig().database.schema).toBe('public');+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ });+});++describe('InfraConfigController.saveConfig writes the generated env owner-only', () => {+ // data/.env.generated holds DB/S3/Redis credentials, so it must be written 0600 — not the+ // default 0644 (world-readable). The write must go through the same owner-only path the+ // first-run boot uses, closing the gap between a dashboard save and the next restart.+ it('persists data/.env.generated with mode 0600, not world-readable', () => {+ const writeSpy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);+ const controller = new InfraConfigController({} as never, {} as never, {} as never);+ controller.saveConfig({ database: { type: 'postgres', sslEnabled: true, password: 'pw' } } as never);+ const opts = writeSpy.mock.calls[0][2];+ expect(opts).toEqual({ mode: 0o600 });+ writeSpy.mockRestore();+ });+});++describe('InfraConfigController.saveConfig env-name correctness and merge (#226)', () => {+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);++ function written(config: unknown, existing?: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(config as never);+ const calls = (fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>;+ const content = calls[0][1];+ // Reset to defaults so later tests start from "no prior config".+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ return content;+ }++ it('writes the env names the backend actually reads (not the old ignored names)', () => {+ const env = written({+ engine: { headless: false, sessionDataPath: './sess', browserArgs: '--flag' },+ storage: { type: 's3', s3Bucket: 'b', s3AccessKey: 'ak', s3SecretKey: 'sk' },+ });+ // Correct names (configuration.ts reads these)+ expect(env).toContain('PUPPETEER_HEADLESS=false');+ expect(env).toContain('SESSION_DATA_PATH=./sess');+ expect(env).toContain('PUPPETEER_ARGS=--flag');+ expect(env).toContain('S3_ACCESS_KEY_ID=ak');+ expect(env).toContain('S3_SECRET_ACCESS_KEY=sk');+ // Old, silently-ignored names must be gone+ expect(env).not.toContain('ENGINE_HEADLESS=');+ expect(env).not.toContain('ENGINE_SESSION_PATH=');+ expect(env).not.toContain('ENGINE_BROWSER_ARGS=');+ expect(env).not.toContain('S3_ACCESS_KEY=');+ expect(env).not.toContain('S3_SECRET_KEY=');+ });++ it('defaults PUPPETEER_ARGS to the full Docker sandbox flag set when browserArgs is empty', () => {+ // Once compose blank-forwards PUPPETEER_ARGS this saved value wins at runtime, so the default must+ // keep --disable-dev-shm-usage (the Docker /dev/shm tab-crash guard) — NOT the old 2-flag set.+ const env = written({ engine: { headless: true, sessionDataPath: './data/sessions', browserArgs: '' } });+ expect(env).toContain('PUPPETEER_ARGS=--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu');+ expect(env).not.toContain('PUPPETEER_ARGS=--no-sandbox --disable-gpu');+ });++ it('writes STORAGE_LOCAL_PATH (the name the backend reads) for local storage', () => {+ const env = written({ storage: { type: 'local', localPath: './data/media' } });+ expect(env).toContain('STORAGE_LOCAL_PATH=./data/media');+ expect(env).not.toContain('STORAGE_PATH=');+ });++ it('preserves existing keys that are not in the current payload', () => {+ const env = written({ engine: { headless: true } }, 'WEBHOOK_TIMEOUT=5000\nSESSION_DATA_PATH=./old\n');+ expect(env).toContain('WEBHOOK_TIMEOUT=5000'); // untouched key survives+ expect(env).toContain('PUPPETEER_HEADLESS=true'); // payload applied+ });++ it('does not blank a stored secret when the form submits an empty value', () => {+ const env = written({ database: { type: 'postgres', host: 'db', password: '' } }, 'DATABASE_PASSWORD=keepme\n');+ expect(env).toContain('DATABASE_PASSWORD=keepme');+ expect(env).toContain('DATABASE_HOST=db');+ });++ it('drops stale postgres keys (including POSTGRES_SCHEMA) when switching to sqlite', () => {+ const existing =+ 'DATABASE_TYPE=postgres\nDATABASE_HOST=oldhost\nDATABASE_PASSWORD=secret\nDATABASE_PORT=5432\nPOSTGRES_SCHEMA=openwa\n';+ const env = written({ database: { type: 'sqlite' } }, existing);+ expect(env).toContain('DATABASE_TYPE=sqlite');+ expect(env).not.toContain('DATABASE_HOST=');+ expect(env).not.toContain('DATABASE_PASSWORD=');+ expect(env).not.toContain('DATABASE_PORT=');+ expect(env).not.toContain('POSTGRES_SCHEMA=');+ });++ it('drops stale S3 keys when switching storage to local', () => {+ const existing =+ 'STORAGE_TYPE=s3\nS3_BUCKET=old\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\nS3_ENDPOINT=http://x\n';+ const env = written({ storage: { type: 'local', localPath: './data/media' } }, existing);+ expect(env).toContain('STORAGE_TYPE=local');+ expect(env).toContain('STORAGE_LOCAL_PATH=./data/media');+ expect(env).not.toContain('S3_BUCKET=');+ expect(env).not.toContain('S3_ACCESS_KEY_ID=');+ expect(env).not.toContain('S3_SECRET_ACCESS_KEY=');+ });+});++describe('InfraConfigController.saveConfig rejects values that would inject extra env vars', () => {+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);++ // .env.generated is one KEY=value per line and is loaded on the next boot. A value carrying a+ // newline would write a second `KEY=value` line — injecting an arbitrary env var (e.g. an admin+ // key) the operator never set. Such a value must be refused outright, with nothing written.+ it.each([+ ['linefeed', '--no-sandbox\nADMIN_MASTER_KEY=attacker'],+ ['carriage return', '--no-sandbox\rADMIN_MASTER_KEY=attacker'],+ ])('does not persist a config value containing a %s', (_label, malicious) => {+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.writeFileSync as jest.Mock).mockClear();++ // A newline-injected value is rejected outright with a 4xx (BadRequestException), not masked as a+ // {saved:false} 200 — and nothing is written.+ expect(() => newController().saveConfig({ engine: { browserArgs: malicious } })).toThrow(BadRequestException);+ expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();+ });++ it('still persists a normal value with the same key', () => {+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.writeFileSync as jest.Mock).mockClear();++ const result = newController().saveConfig({ engine: { browserArgs: '--no-sandbox --disable-gpu' } });++ expect(result.saved).toBe(true);+ expect(fs.writeFileSync as jest.Mock).toHaveBeenCalled();+ });+});++describe('InfraConfigController.saveConfig engine selection (persist ENGINE_TYPE — Infrastructure tile)', () => {+ const engineFactory = {+ getAvailableEngines: () => [{ id: 'whatsapp-web.js' }, { id: 'baileys' }],+ };+ const newController = () => new InfraConfigController(engineFactory as never, {} as never, {} as never);++ function written(config: unknown, existing?: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(config as never);+ const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ return content;+ }++ it('persists ENGINE_TYPE when a valid engine is selected', () => {+ const env = written({ engine: { type: 'baileys', headless: true } });+ expect(env).toContain('ENGINE_TYPE=baileys');+ });++ it('does not write ENGINE_TYPE when no engine type is provided (avoids clobbering)', () => {+ const env = written({ engine: { headless: false } });+ expect(env).not.toContain('ENGINE_TYPE=');+ expect(env).toContain('PUPPETEER_HEADLESS=false');+ });++ it('rejects an unknown engine type and writes nothing', () => {+ (fs.writeFileSync as jest.Mock).mockClear();+ // Rejected as a 4xx (BadRequestException naming the bad engine), not a {saved:false} 200.+ expect(() => newController().saveConfig({ engine: { type: 'bogus' } })).toThrow(/unknown engine/i);+ expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();+ });+});++describe('InfraConfigController.saveConfig byte-identical regression (full dashboard payload)', () => {+ // Pins the legitimate behavior: a FULL dashboard save (every section, every field — the exact+ // shape Infrastructure.tsx posts) must produce exactly the same .env.generated bytes as before+ // the per-key merge change. The literal key maps below were derived from the previous+ // implementation's output; any drift in written keys or values fails this gate.+ const engineFactory = {+ getAvailableEngines: () => [{ id: 'whatsapp-web.js' }, { id: 'baileys' }],+ };+ const newController = () => new InfraConfigController(engineFactory as never, {} as never, {} as never);++ const NOW = '2026-01-02T03:04:05.000Z';++ beforeEach(() => {+ jest.useFakeTimers();+ jest.setSystemTime(new Date(NOW));+ });+ afterEach(() => {+ jest.useRealTimers();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ });++ function expectedEnv(keys: Record<string, string>): string {+ const body = Object.keys(keys)+ .sort()+ .map(k => `${k}=${keys[k]}`);+ return [+ '# OpenWA Configuration',+ `# Generated at ${NOW}`,+ '# Managed via Dashboard > Infrastructure. Values in process env or project .env take precedence.',+ '',+ ...body,+ '',+ ].join('\n');+ }++ function saveAndGetContent(config: unknown, existing: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing);+ (fs.writeFileSync as jest.Mock).mockClear();+ const result = newController().saveConfig(config as never);+ expect(result.saved).toBe(true);+ return ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];+ }++ it('all-built-in full save is byte-identical', () => {+ const existing = [+ 'DATABASE_TYPE=postgres',+ 'POSTGRES_BUILTIN=true',+ 'DATABASE_HOST=postgres',+ 'DATABASE_PORT=5432',+ 'DATABASE_USERNAME=openwa',+ 'DATABASE_PASSWORD=openwa',+ 'DATABASE_NAME=openwa',+ 'POSTGRES_SCHEMA=public',+ 'DATABASE_POOL_SIZE=10',+ 'DATABASE_SSL=false',+ 'REDIS_ENABLED=true',+ 'REDIS_BUILTIN=true',+ 'REDIS_HOST=redis',+ 'REDIS_PORT=6379',+ 'QUEUE_ENABLED=true',+ 'STORAGE_TYPE=s3',+ 'MINIO_BUILTIN=true',+ 'S3_ENDPOINT=http://minio:9000',+ 'S3_ACCESS_KEY_ID=minioadmin',+ 'S3_SECRET_ACCESS_KEY=minioadmin',+ 'S3_BUCKET=openwa',+ 'S3_REGION=us-east-1',+ 'ENGINE_TYPE=whatsapp-web.js',+ 'PUPPETEER_HEADLESS=true',+ 'SESSION_DATA_PATH=./data/sessions',+ 'PUPPETEER_ARGS=--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',+ 'WEBHOOK_TIMEOUT=5000',+ '',+ ].join('\n');+ // The exact payload the dashboard posts for that saved state (secrets come back empty:+ // "unchanged"). The built-in credentials are exempt from the production secret guard.+ const payload = {+ database: {+ type: 'postgres',+ builtIn: true,+ host: 'postgres',+ port: '5432',+ username: 'openwa',+ password: '',+ database: 'openwa',+ schema: 'public',+ poolSize: 10,+ sslEnabled: false,+ sslRejectUnauthorized: true,+ },+ redis: { enabled: true, builtIn: true, host: 'redis', port: '6379', password: '' },+ queue: { enabled: true },+ storage: {+ type: 's3',+ builtIn: true,+ localPath: '',+ s3Bucket: 'openwa',+ s3Region: 'us-east-1',+ s3AccessKey: '',+ s3SecretKey: '',+ s3Endpoint: 'http://minio:9000',+ },+ engine: {+ type: 'whatsapp-web.js',+ headless: true,+ sessionDataPath: './data/sessions',+ browserArgs: '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',+ },+ };++ const content = saveAndGetContent(payload, existing);++ expect(content).toBe(+ expectedEnv({+ DATABASE_HOST: 'postgres',+ DATABASE_NAME: 'openwa',+ DATABASE_PASSWORD: 'openwa',+ DATABASE_POOL_SIZE: '10',+ DATABASE_PORT: '5432',+ DATABASE_SSL: 'false',+ DATABASE_TYPE: 'postgres',+ DATABASE_USERNAME: 'openwa',+ ENGINE_TYPE: 'whatsapp-web.js',+ MINIO_BUILTIN: 'true',+ POSTGRES_BUILTIN: 'true',+ POSTGRES_SCHEMA: 'public',+ PUPPETEER_ARGS: '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',+ PUPPETEER_HEADLESS: 'true',+ QUEUE_ENABLED: 'true',+ REDIS_BUILTIN: 'true',+ REDIS_ENABLED: 'true',+ REDIS_HOST: 'redis',+ REDIS_PORT: '6379',+ S3_ACCESS_KEY_ID: 'minioadmin',+ S3_BUCKET: 'openwa',+ S3_ENDPOINT: 'http://minio:9000',+ S3_REGION: 'us-east-1',+ S3_SECRET_ACCESS_KEY: 'minioadmin',+ SESSION_DATA_PATH: './data/sessions',+ STORAGE_TYPE: 's3',+ WEBHOOK_TIMEOUT: '5000',+ }),+ );+ });++ it('all-external full save is byte-identical (secrets preserved on empty submission)', () => {+ const existing = [+ 'DATABASE_TYPE=postgres',+ 'POSTGRES_BUILTIN=false',+ 'DATABASE_HOST=db.example.com',+ 'DATABASE_PORT=5433',+ 'DATABASE_USERNAME=openwauser',+ 'DATABASE_PASSWORD=Str0ng!Passw0rd',+ 'DATABASE_NAME=openwa',+ 'POSTGRES_SCHEMA=openwa',+ 'DATABASE_POOL_SIZE=20',+ 'DATABASE_SSL=true',+ 'DATABASE_SSL_REJECT_UNAUTHORIZED=false',+ 'REDIS_ENABLED=true',+ 'REDIS_BUILTIN=false',+ 'REDIS_HOST=redis.example.com',+ 'REDIS_PORT=6380',+ 'REDIS_PASSWORD=r3dis-secret',+ 'QUEUE_ENABLED=false',+ 'STORAGE_TYPE=s3',+ 'MINIO_BUILTIN=false',+ 'S3_ENDPOINT=https://s3.eu-west-1.amazonaws.com',+ 'S3_ACCESS_KEY_ID=AKIAEXAMPLE123',+ 'S3_SECRET_ACCESS_KEY=s3-super-secret',+ 'S3_BUCKET=mybucket',+ 'S3_REGION=eu-west-1',+ 'ENGINE_TYPE=baileys',+ 'PUPPETEER_HEADLESS=false',+ 'SESSION_DATA_PATH=/var/lib/openwa/sessions',+ 'PUPPETEER_ARGS=--no-sandbox',+ '',+ ].join('\n');+ const payload = {+ database: {+ type: 'postgres',+ builtIn: false,+ host: 'db.example.com',+ port: '5433',+ username: 'openwauser',+ password: '',+ database: 'openwa',+ schema: 'openwa',+ poolSize: 20,+ sslEnabled: true,+ sslRejectUnauthorized: false,+ },+ redis: { enabled: true, builtIn: false, host: 'redis.example.com', port: '6380', password: '' },+ queue: { enabled: false },+ storage: {+ type: 's3',+ builtIn: false,+ localPath: '',+ s3Bucket: 'mybucket',+ s3Region: 'eu-west-1',+ s3AccessKey: '',+ s3SecretKey: '',+ s3Endpoint: 'https://s3.eu-west-1.amazonaws.com',+ },+ engine: {+ type: 'baileys',+ headless: false,+ sessionDataPath: '/var/lib/openwa/sessions',+ browserArgs: '--no-sandbox',+ },+ };++ const content = saveAndGetContent(payload, existing);++ expect(content).toBe(+ expectedEnv({+ DATABASE_HOST: 'db.example.com',+ DATABASE_NAME: 'openwa',+ DATABASE_PASSWORD: 'Str0ng!Passw0rd',+ DATABASE_POOL_SIZE: '20',+ DATABASE_PORT: '5433',+ DATABASE_SSL: 'true',+ DATABASE_SSL_REJECT_UNAUTHORIZED: 'false',+ DATABASE_TYPE: 'postgres',+ DATABASE_USERNAME: 'openwauser',+ ENGINE_TYPE: 'baileys',+ MINIO_BUILTIN: 'false',+ POSTGRES_BUILTIN: 'false',+ POSTGRES_SCHEMA: 'openwa',+ PUPPETEER_ARGS: '--no-sandbox',+ PUPPETEER_HEADLESS: 'false',+ QUEUE_ENABLED: 'false',+ REDIS_BUILTIN: 'false',+ REDIS_ENABLED: 'true',+ REDIS_HOST: 'redis.example.com',+ REDIS_PASSWORD: 'r3dis-secret',+ REDIS_PORT: '6380',+ S3_ACCESS_KEY_ID: 'AKIAEXAMPLE123',+ S3_BUCKET: 'mybucket',+ S3_ENDPOINT: 'https://s3.eu-west-1.amazonaws.com',+ S3_REGION: 'eu-west-1',+ S3_SECRET_ACCESS_KEY: 's3-super-secret',+ SESSION_DATA_PATH: '/var/lib/openwa/sessions',+ STORAGE_TYPE: 's3',+ }),+ );+ });+});++describe('InfraConfigController.saveConfig per-key merge (partial payloads)', () => {+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);++ function written(config: unknown, existing?: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(config as never);+ const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ return content;+ }++ it('a queue-only save does not touch the redis section', () => {+ const env = written(+ { queue: { enabled: true } },+ 'REDIS_ENABLED=true\nREDIS_BUILTIN=true\nREDIS_HOST=redis\nREDIS_PORT=6379\nQUEUE_ENABLED=false\n',+ );+ expect(env).toContain('QUEUE_ENABLED=true');+ expect(env).toContain('REDIS_ENABLED=true');+ expect(env).toContain('REDIS_BUILTIN=true');+ expect(env).toContain('REDIS_HOST=redis');+ expect(env).toContain('REDIS_PORT=6379');+ });++ it('a redis-only save does not touch the queue section or force the redis flags', () => {+ const env = written(+ { redis: { host: 'redis2.example.com' } },+ 'REDIS_ENABLED=true\nREDIS_BUILTIN=false\nREDIS_HOST=redis1.example.com\nQUEUE_ENABLED=true\n',+ );+ expect(env).toContain('REDIS_HOST=redis2.example.com');+ expect(env).toContain('REDIS_ENABLED=true');+ expect(env).toContain('REDIS_BUILTIN=false');+ expect(env).toContain('QUEUE_ENABLED=true');+ });++ it('a partial database save keeps unmentioned keys (pool size, schema, stored password)', () => {+ const existing =+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=old.example.com\nDATABASE_PASSWORD=keepme\nDATABASE_POOL_SIZE=25\nPOSTGRES_SCHEMA=openwa\n';+ const env = written({ database: { type: 'postgres', host: 'new.example.com' } }, existing);+ expect(env).toContain('DATABASE_HOST=new.example.com');+ expect(env).toContain('DATABASE_POOL_SIZE=25');+ expect(env).toContain('POSTGRES_SCHEMA=openwa');+ expect(env).toContain('DATABASE_PASSWORD=keepme');+ });++ it('a partial storage save keeps the stored S3 region instead of resetting it to the default', () => {+ const existing =+ 'STORAGE_TYPE=s3\nMINIO_BUILTIN=false\nS3_BUCKET=old-bucket\nS3_REGION=eu-west-1\nS3_ACCESS_KEY_ID=ak-strong\nS3_SECRET_ACCESS_KEY=sk-strong\n';+ const env = written({ storage: { type: 's3', s3Bucket: 'new-bucket' } }, existing);+ expect(env).toContain('S3_BUCKET=new-bucket');+ expect(env).toContain('S3_REGION=eu-west-1');+ expect(env).toContain('S3_ACCESS_KEY_ID=ak-strong');+ });++ it('a partial engine save keeps the stored session path and browser args', () => {+ const env = written(+ { engine: { headless: false } },+ 'SESSION_DATA_PATH=./old-path\nPUPPETEER_ARGS=--custom-flag\n',+ );+ expect(env).toContain('PUPPETEER_HEADLESS=false');+ expect(env).toContain('SESSION_DATA_PATH=./old-path');+ expect(env).toContain('PUPPETEER_ARGS=--custom-flag');+ });+});++describe('InfraConfigController.saveConfig built-in/external mode flips and the save-time secret guard', () => {+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);++ function written(config: unknown, existing?: string): string {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(config as never);+ const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ return content;+ }++ function expectRejected(config: unknown, existing: string | undefined, match: RegExp): void {+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');+ (fs.writeFileSync as jest.Mock).mockClear();+ expect(() => newController().saveConfig(config as never)).toThrow(match);+ // A rejected save must leave the previous file untouched.+ expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ }++ const BUILTIN_POSTGRES_ENV =+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PORT=5432\nDATABASE_USERNAME=openwa\nDATABASE_PASSWORD=openwa\nDATABASE_NAME=openwa\nPOSTGRES_SCHEMA=public\n';+ const BUILTIN_MINIO_ENV =+ 'STORAGE_TYPE=s3\nMINIO_BUILTIN=true\nS3_ENDPOINT=http://minio:9000\nS3_ACCESS_KEY_ID=minioadmin\nS3_SECRET_ACCESS_KEY=minioadmin\nS3_BUCKET=openwa\nS3_REGION=us-east-1\n';++ it('flipping Postgres built-in -> external with a fresh password drops the bundled password', () => {+ const env = written(+ {+ database: {+ type: 'postgres',+ builtIn: false,+ host: 'db.example.com',+ username: 'app',+ password: 'Sup3rSecret!',+ database: 'appdb',+ },+ },+ BUILTIN_POSTGRES_ENV,+ );+ expect(env).toContain('POSTGRES_BUILTIN=false');+ expect(env).toContain('DATABASE_HOST=db.example.com');+ expect(env).toContain('DATABASE_PASSWORD=Sup3rSecret!');+ // No trace of the bundled 'openwa' credential may survive the flip.+ expect(env).not.toContain('openwa');+ });++ it('rejects flipping Postgres built-in -> external without a fresh password instead of crash-looping', () => {+ // Without the mode-flip drop + save-time guard this saved the bundled 'openwa' password into+ // the external config; the production boot guard then refused to start and the dashboard died+ // with it. The save itself must now fail with a 400 naming the variable.+ expectRejected(+ { database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' } },+ BUILTIN_POSTGRES_ENV,+ /DATABASE_PASSWORD/,+ );+ });++ it('rejects a blank-password external Postgres on a fresh setup (the sibling blank-password case)', () => {+ expectRejected(+ { database: { type: 'postgres', builtIn: false, host: 'db.example.com', password: '' } },+ undefined,+ /DATABASE_PASSWORD/,+ );+ });++ it('rejects an external Postgres using a known-default password', () => {+ expectRejected(+ { database: { type: 'postgres', builtIn: false, host: 'db.example.com', password: 'password' } },+ undefined,+ /DATABASE_PASSWORD/,+ );+ });++ it('the rejection is a 400 BadRequestException, not a masked {saved:false} 200', () => {+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.writeFileSync as jest.Mock).mockClear();+ expect(() =>+ newController().saveConfig({ database: { type: 'postgres', builtIn: false, host: 'db' } } as never),+ ).toThrow(BadRequestException);+ });++ it('flipping storage built-in -> external with fresh credentials drops the bundled ones', () => {+ const env = written(+ {+ storage: {+ type: 's3',+ builtIn: false,+ s3Bucket: 'prod-bucket',+ s3Region: 'ap-southeast-1',+ s3AccessKey: 'AKIANEWEXAMPLE',+ s3SecretKey: 'brand-new-secret',+ s3Endpoint: 'https://s3.ap-southeast-1.amazonaws.com',+ },+ },+ BUILTIN_MINIO_ENV,+ );+ expect(env).toContain('MINIO_BUILTIN=false');+ expect(env).toContain('S3_ACCESS_KEY_ID=AKIANEWEXAMPLE');+ expect(env).toContain('S3_SECRET_ACCESS_KEY=brand-new-secret');+ expect(env).toContain('S3_ENDPOINT=https://s3.ap-southeast-1.amazonaws.com');+ expect(env).not.toContain('minioadmin');+ expect(env).not.toContain('http://minio:9000');+ });++ it('flipping storage built-in -> external (AWS) with a blank endpoint drops the stale MinIO endpoint', () => {+ const env = written(+ {+ storage: {+ type: 's3',+ builtIn: false,+ s3Bucket: 'prod-bucket',+ s3AccessKey: 'AKIANEWEXAMPLE',+ s3SecretKey: 'brand-new-secret',+ s3Endpoint: '',+ },+ },+ BUILTIN_MINIO_ENV,+ );+ expect(env).not.toContain('S3_ENDPOINT=');+ expect(env).toContain('S3_ACCESS_KEY_ID=AKIANEWEXAMPLE');+ });++ it('rejects flipping storage built-in -> external without fresh credentials', () => {+ expectRejected(+ {+ storage: {+ type: 's3',+ builtIn: false,+ s3Bucket: 'prod-bucket',+ s3AccessKey: '',+ s3SecretKey: '',+ s3Endpoint: '',+ },+ },+ BUILTIN_MINIO_ENV,+ /S3_ACCESS_KEY, S3_SECRET_KEY/,+ );+ });++ it('rejects external S3 using the known-default minioadmin credentials', () => {+ expectRejected(+ {+ storage: {+ type: 's3',+ builtIn: false,+ s3Bucket: 'b',+ s3AccessKey: 'minioadmin',+ s3SecretKey: 'minioadmin',+ s3Endpoint: 'https://minio.example.com',+ },+ },+ undefined,+ /S3_ACCESS_KEY, S3_SECRET_KEY/,+ );+ });++ it('flipping Redis external -> built-in drops the stale external password', () => {+ const env = written(+ { redis: { enabled: true, builtIn: true } },+ 'REDIS_ENABLED=true\nREDIS_BUILTIN=false\nREDIS_HOST=redis.example.com\nREDIS_PORT=6379\nREDIS_PASSWORD=hunter2\n',+ );+ expect(env).toContain('REDIS_BUILTIN=true');+ expect(env).toContain('REDIS_HOST=redis');+ // The bundled Redis runs without auth; a carried-over password would make the client AUTH+ // against a passwordless server on the next boot.+ expect(env).not.toContain('REDIS_PASSWORD=');+ });++ it('rejects a placeholder Redis password at save time', () => {+ expectRejected(+ { redis: { enabled: true, builtIn: false, host: 'redis.example.com', password: 'password' } },+ undefined,+ /REDIS_PASSWORD/,+ );+ });++ it('still saves built-in modes: the bundled credentials stay exempt from the guard', () => {+ const env = written({+ database: { type: 'postgres', builtIn: true },+ storage: { type: 's3', builtIn: true },+ });+ expect(env).toContain('DATABASE_PASSWORD=openwa');+ expect(env).toContain('POSTGRES_BUILTIN=true');+ expect(env).toContain('S3_ACCESS_KEY_ID=minioadmin');+ expect(env).toContain('MINIO_BUILTIN=true');+ });++ it('an absent builtIn field inherits built-in mode without clobbering a stored custom password', () => {+ // Secrets are never echoed back to the form, so an absent password field means "unchanged".+ // Merely inheriting the built-in mode must not re-stamp the bundled 'openwa' over a custom+ // password (e.g. an operator who re-keyed the bundled container via POSTGRES_PASSWORD).+ const env = written(+ { database: { type: 'postgres', poolSize: 25 } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PORT=5432\nDATABASE_USERNAME=openwa\nDATABASE_PASSWORD=CustomPw123!\nDATABASE_NAME=openwa\nPOSTGRES_SCHEMA=public\n',+ );+ expect(env).toContain('POSTGRES_BUILTIN=true');+ expect(env).toContain('DATABASE_PASSWORD=CustomPw123!');+ expect(env).toContain('DATABASE_POOL_SIZE=25');+ });++ it('an explicit password wins while the built-in mode is only inherited', () => {+ const env = written(+ { database: { type: 'postgres', password: 'NewPw456!' } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PASSWORD=openwa\nDATABASE_NAME=openwa\n',+ );+ expect(env).toContain('DATABASE_PASSWORD=NewPw456!');+ expect(env).not.toContain('DATABASE_PASSWORD=openwa');+ });++ it('an explicit builtIn:true keeps a re-keyed bundled password (the dashboard always sends builtIn)', () => {+ // Infrastructure.tsx sends `database.builtIn` on every save and never echoes the password back,+ // so treating "explicit builtIn:true + no password" as a reset re-wrote a re-keyed container's+ // credential on each save, breaking the next boot's DB auth.+ const env = written(+ { database: { type: 'postgres', builtIn: true } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PASSWORD=CustomPw123!\nDATABASE_NAME=openwa\n',+ );+ expect(env).toContain('DATABASE_PASSWORD=CustomPw123!');+ });++ it('does not carry an EXTERNAL password into the bundled container when switching to built-in', () => {+ // The stored secret belongs to the external DB; the bundled container is seeded with 'openwa'+ // unless the operator re-keys it, so switching modes must reset rather than inherit.+ const env = written(+ { database: { type: 'postgres', builtIn: true } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.example.com\nDATABASE_PASSWORD=ExternalPw!\nDATABASE_NAME=appdb\n',+ );+ expect(env).toContain('DATABASE_PASSWORD=openwa');+ expect(env).not.toContain('ExternalPw!');+ });++ // The guard must evaluate what the next boot would SEE: load-env.ts loads with dotenv+ // override:false, so a value in the container environment (compose `environment:`) wins over the+ // saved file. Snapshot + clear every guard-relevant key so these tests are hermetic.+ describe('process-environment precedence', () => {+ const GUARD_ENV_KEYS = [+ 'DATABASE_TYPE',+ 'DATABASE_PASSWORD',+ 'POSTGRES_BUILTIN',+ 'DATABASE_HOST',+ 'STORAGE_TYPE',+ 'S3_ACCESS_KEY_ID',+ 'S3_SECRET_ACCESS_KEY',+ 'S3_ENDPOINT',+ 'MINIO_BUILTIN',+ 'REDIS_PASSWORD',+ ];+ let savedEnv: Array<[string, string | undefined]>;+ beforeEach(() => {+ savedEnv = GUARD_ENV_KEYS.map(k => [k, process.env[k]]);+ for (const k of GUARD_ENV_KEYS) delete process.env[k];+ });+ afterEach(() => {+ for (const [k, v] of savedEnv) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ });++ it('accepts an external Postgres whose strong password comes from the process environment', () => {+ // The compose deployment the guard used to refuse on EVERY save: the file still holds the+ // bundled built-in credentials, but boot would see the env password, not the file's.+ process.env.DATABASE_PASSWORD = 'Sup3rSecret!';+ const env = written(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ );+ expect(env).toContain('POSTGRES_BUILTIN=false');+ expect(env).toContain('DATABASE_HOST=db.example.com');+ // The stale bundled password is still dropped from the file — the environment supplies it.+ expect(env).not.toContain('DATABASE_PASSWORD');+ });++ it('a blank process-env forward counts as unset, so a weak merged config is still rejected', () => {+ // Compose renders `- DATABASE_PASSWORD=${DATABASE_PASSWORD:-}` as an empty value when the+ // operator sets nothing; boot clears that blank (clearBlankEnv) and falls to the file. The+ // guard does the same — a blank forward can neither mask a weak file value nor supply one.+ process.env.DATABASE_PASSWORD = '';+ expectRejected(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ /DATABASE_PASSWORD/,+ );+ });++ it('a weak process-env value wins over a strong saved one and is still rejected', () => {+ // Precedence cuts both ways: boot would see the env value, so a weak env password must not be+ // rescued by a strong one sitting in the file.+ process.env.DATABASE_PASSWORD = 'password';+ expectRejected(+ { queue: { enabled: true } },+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.example.com\nDATABASE_PASSWORD=Str0ngSaved!\n',+ /DATABASE_PASSWORD/,+ );+ });++ // The cases above delete every guard key from process.env, which cannot happen in production:+ // load-env merges data/.env.generated INTO process.env at boot, so the file's own values are+ // sitting there while this save runs. Reading them back as if they were an orchestrator+ // override makes the guard validate the config being REPLACED.+ describe('saved-file values echoed in process.env are not mistaken for host overrides', () => {+ afterEach(() => {+ // Restore the permissive snapshot the rest of the file assumes.+ recordOsEnvKeys(process.env);+ });++ it('refuses a built-in -> external flip that keeps the bundled password (boot would crash-loop)', () => {+ recordOsEnvKeys({}); // the host supplied nothing; everything below came from the file+ process.env.DATABASE_TYPE = 'postgres';+ process.env.POSTGRES_BUILTIN = 'true';+ process.env.DATABASE_HOST = 'postgres';+ process.env.DATABASE_PASSWORD = 'openwa';+ expectRejected(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ /DATABASE_PASSWORD/,+ );+ });++ it('still honors a genuine host override of the same key', () => {+ recordOsEnvKeys({ DATABASE_PASSWORD: 'Sup3rSecret!' });+ process.env.DATABASE_PASSWORD = 'Sup3rSecret!';+ const env = written(+ {+ database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },+ },+ BUILTIN_POSTGRES_ENV,+ );+ expect(env).toContain('DATABASE_HOST=db.example.com');+ });+ });+ });+});++describe('InfraConfigController.saveConfig persists strictly-coerced form booleans', () => {+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);++ it("persists 'false' for every boolean field when the body arrives form-encoded", async () => {+ // The global urlencoded parser delivers scalars as strings and the ValidationPipe runs with+ // enableImplicitConversion, which used to turn every non-empty string — including 'false' —+ // into `true`. SaveConfigDto's @ToStrictBoolean fields must map 'false' to a real false so the+ // file gets 'false', not a silently-enabled feature on the next boot.+ const formPayload = {+ database: {+ type: 'postgres',+ builtIn: 'false',+ host: 'db.example.com',+ password: 'unit-test-pw',+ sslEnabled: 'true',+ sslRejectUnauthorized: 'false',+ },+ redis: { enabled: 'false', builtIn: 'false' },+ queue: { enabled: 'false' },+ storage: { type: 's3', builtIn: 'false', s3Bucket: 'b', s3AccessKey: 'ak-strong', s3SecretKey: 'sk-strong' },+ engine: { headless: 'false' },+ };+ // Mirror the real pipe: implicit conversion on, whitelist validation (src/config/app-validation.ts).+ const instance = plainToInstance(SaveConfigDto, formPayload, { enableImplicitConversion: true });+ const errors = await validate(instance, { whitelist: true, forbidNonWhitelisted: true });+ expect(errors).toHaveLength(0);++ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.writeFileSync as jest.Mock).mockClear();+ newController().saveConfig(instance);+ const env = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];++ expect(env).toContain('POSTGRES_BUILTIN=false');+ expect(env).toContain('DATABASE_SSL=true');+ expect(env).toContain('DATABASE_SSL_REJECT_UNAUTHORIZED=false');+ expect(env).toContain('REDIS_ENABLED=false');+ expect(env).toContain('REDIS_BUILTIN=false');+ expect(env).toContain('QUEUE_ENABLED=false');+ expect(env).toContain('MINIO_BUILTIN=false');+ expect(env).toContain('PUPPETEER_HEADLESS=false');+ });+});++describe('InfraConfigController.getConfig (#226)', () => {+ it('returns the saved config shape without echoing secrets', () => {+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue(+ 'DATABASE_TYPE=postgres\nDATABASE_HOST=db\nDATABASE_PASSWORD=secret\nSESSION_DATA_PATH=./sess\nENGINE_TYPE=baileys\nSTORAGE_TYPE=s3\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\n',+ );+ const controller = new InfraConfigController({} as never, {} as never, {} as never);++ const cfg = controller.getConfig();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');++ expect(cfg.database.type).toBe('postgres');+ expect(cfg.database.host).toBe('db');+ expect(cfg.database.passwordSet).toBe(true);+ expect(cfg.engine.sessionDataPath).toBe('./sess');+ expect(cfg.engine.type).toBe('baileys');+ expect(cfg.storage.type).toBe('s3');+ expect(cfg.storage.s3CredentialsSet).toBe(true);+ // Secrets are never present on the returned object.+ expect(JSON.stringify(cfg)).not.toContain('secret');+ expect(JSON.stringify(cfg)).not.toContain('"ak"');+ });+});++describe('InfraConfigController.requestRestart constrains teardown to managed profiles', () => {+ const buildController = (dockerService: Record<string, unknown>) =>+ new InfraConfigController(+ {} as never, // engineFactory+ dockerService as never,+ { shutdown: jest.fn() } as never, // shutdownService+ );++ it('tears down only allowlisted profiles, never an unknown or empty entry', async () => {+ const stopManagedService = jest.fn().mockResolvedValue(true);+ const controller = buildController({+ isDockerAvailable: () => true,+ stopManagedService,+ orchestrateProfiles: jest.fn().mockResolvedValue({}),+ });++ // '' (matches any container by substring) and 'evil' must be dropped; only managed profiles act.+ await controller.requestRestart({ profilesToRemove: ['', 'evil', 'postgres', 'redis'] });++ const torn = stopManagedService.mock.calls.map(call => String((call as unknown[])[0])).sort();+ expect(torn).toEqual(['postgres', 'redis']);+ expect(torn).not.toContain('');+ expect(torn).not.toContain('evil');+ });++ it('reports teardown as stopped-not-removed, with honest per-profile errors', async () => {+ const stopManagedService = jest+ .fn()+ .mockResolvedValueOnce(true) // postgres stops cleanly+ .mockResolvedValueOnce(false); // redis fails+ const controller = buildController({+ isDockerAvailable: () => true,+ stopManagedService,+ orchestrateProfiles: jest.fn().mockResolvedValue({}),+ });++ const result = await controller.requestRestart({ profilesToRemove: ['postgres', 'redis'] });++ // Teardown is stop-only (containers are retained, never deleted) — the payload must say so.+ expect(result.removal).toEqual({+ stopped: ['postgres'],+ errors: ['Failed to stop redis'],+ });+ expect(JSON.stringify(result.removal)).not.toContain('removed');+ });++ it('starts only allowlisted profiles, never an unknown entry (symmetry with teardown)', async () => {+ const orchestrateProfiles = jest.fn().mockResolvedValue({});+ const controller = buildController({+ isDockerAvailable: () => true,+ stopManagedService: jest.fn().mockResolvedValue(true),+ orchestrateProfiles,+ });++ // A non-managed name must be dropped before reaching orchestrateProfiles, exactly as teardown+ // drops it before reaching stopManagedService — so start cannot select an unrelated container.+ await controller.requestRestart({ profiles: ['postgres', 'not-managed'] });++ expect(orchestrateProfiles).toHaveBeenCalledTimes(1);+ expect(orchestrateProfiles).toHaveBeenCalledWith(['postgres']);+ });++ it('writes only allowlisted profiles to the no-Docker signal file (symmetry with the Docker path)', async () => {+ const writeFileSync = fs.writeFileSync as jest.Mock;+ writeFileSync.mockClear();+ const controller = buildController({ isDockerAvailable: () => false });++ // The signal file is consumed by an external host script — it must never be handed a name the+ // in-process Docker path would have refused.+ await controller.requestRestart({ profiles: ['postgres', 'not-managed'], profilesToRemove: ['evil', 'redis'] });++ const written = (writeFileSync.mock.calls as Array<[unknown, unknown]>).find(call =>+ String(call[0]).endsWith('.orchestration-request.json'),+ );+ expect(written).toBeDefined();+ const payload = JSON.parse(String(written![1])) as { profiles: string[]; profilesToRemove: string[] };+ expect(payload.profiles).toEqual(['postgres']);+ expect(payload.profilesToRemove).toEqual(['redis']);+ });+});++// C002: the infra module exposed sensitive ADMIN operations (credential config write, restart/Docker+// orchestration, full-DB + storage export/import) with no audit trail. Each now emits an AuditAction.+describe('InfraConfigController C002 audit trail (light-dependency handlers)', () => {+ const makeAudit = (): { logInfo: jest.Mock } => ({ logInfo: jest.fn().mockResolvedValue(null) });++ // Positional constructor: (engineFactory, dockerService, shutdownService, auditService?).+ // auditService is the last @Optional arg.+ const build = (+ audit: { logInfo: jest.Mock },+ overrides: Partial<{+ engineFactory: unknown;+ dockerService: unknown;+ shutdownService: unknown;+ }> = {},+ ): InfraConfigController =>+ new InfraConfigController(+ (overrides.engineFactory ?? {}) as never,+ (overrides.dockerService ?? {}) as never,+ (overrides.shutdownService ?? {}) as never,+ audit as never,+ );++ it('saveConfig emits INFRA_CONFIG_SAVED without leaking secret values into the metadata', () => {+ const audit = makeAudit();+ build(audit).saveConfig({ database: { type: 'postgres', host: 'db', password: 'topsecret' } } as never);+ expect(audit.logInfo).toHaveBeenCalledTimes(1);+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { sections: string[] } }]>;+ const [action, ctx] = calls[0];+ expect(action).toBe(AuditAction.INFRA_CONFIG_SAVED);+ expect(ctx.metadata.sections).toContain('database');+ // Only section names + profiles are recorded — never a secret value.+ expect(JSON.stringify(ctx)).not.toContain('topsecret');+ });++ it('saveConfig does NOT emit when the payload is rejected (unknown engine)', () => {+ const audit = makeAudit();+ const controller = build(audit, { engineFactory: { getAvailableEngines: () => [{ id: 'baileys' }] } });+ expect(() => controller.saveConfig({ engine: { type: 'bogus' } })).toThrow(BadRequestException);+ expect(audit.logInfo).not.toHaveBeenCalled();+ });++ it('requestRestart emits INFRA_RESTART_REQUESTED with the requested profiles', async () => {+ const audit = makeAudit();+ const controller = build(audit, {+ dockerService: { isDockerAvailable: () => false },+ shutdownService: { shutdown: jest.fn() },+ });+ await controller.requestRestart({ profiles: ['postgres'], profilesToRemove: [] });+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { profiles: string[] } }]>;+ expect(calls[0][0]).toBe(AuditAction.INFRA_RESTART_REQUESTED);+ expect(calls[0][1].metadata.profiles).toEqual(['postgres']);+ });+});diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.tsnew file mode 100644index 000000000..1042b7346--- /dev/null+++ b/src/modules/infra/infra-config.controller.ts@@ -0,0 +1,668 @@+import {+ Controller,+ Get,+ Put,+ Post,+ Body,+ BadRequestException,+ HttpException,+ HttpCode,+ HttpStatus,+ Optional,+} from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiPropertyOptional } from '@nestjs/swagger';+import { IsArray, IsOptional, IsString } from 'class-validator';+import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { writeSecretFile } from '../../common/utils/secret-file';+import { EngineFactory } from '../../engine/engine.factory';+import { DockerService, MANAGED_DOCKER_PROFILES } from '../docker';+import { ShutdownService } from '../../common/services/shutdown.service';+import { createLogger } from '../../common/services/logger.service';+import { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';+import {+ DatabaseConfigDto,+ EngineConfigDto,+ RedisConfigDto,+ SaveConfigDto,+ StorageConfigDto,+} from './dto/save-config.dto';+import { assertNoDefaultSecretsInProduction } from '../../config/bootstrap-security';+import { BLANK_SHADOWED_ENV_KEYS, isOsProvidedEnv } from '../../config/env-precedence';+import * as fs from 'fs';+import * as path from 'path';+import { generatedEnvPath, readGeneratedEnv } from './generated-env';++// The PUT /infra/config body DTOs live in ./dto/save-config.dto.ts: as *.dto.ts classes they are+// covered by the input-coercion drift gate (src/common/utils/dto-strict-coercion.spec.ts), which+// controller-local classes escape, and their boolean/numeric fields carry the @ToStrictBoolean /+// @ToStrictNumber transforms that keep a form-encoded 'false' from being coerced to `true`.++class RestartDto {+ @ApiPropertyOptional({ type: [String] })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ profiles?: string[];++ @ApiPropertyOptional({ type: [String] })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ profilesToRemove?: string[];+}++// Saved infrastructure config returned to the dashboard form for hydration. Secret+// values are never echoed back — a `*Set` boolean indicates whether one is stored.+interface SavedConfigResponse {+ database: {+ type: 'sqlite' | 'postgres';+ builtIn: boolean;+ host: string;+ port: string;+ username: string;+ database: string;+ schema: string;+ poolSize: number;+ sslEnabled: boolean;+ sslRejectUnauthorized: boolean;+ passwordSet: boolean;+ };+ redis: { enabled: boolean; builtIn: boolean; host: string; port: string; passwordSet: boolean };+ queue: { enabled: boolean };+ storage: {+ type: 'local' | 's3';+ builtIn: boolean;+ localPath: string;+ s3Bucket: string;+ s3Region: string;+ s3Endpoint: string;+ s3CredentialsSet: boolean;+ };+ engine: { type: string; headless: boolean; sessionDataPath: string; browserArgs: string };+}++// Mutable accumulator threaded through the per-section appliers extracted from saveConfig:+// `updates` collects the values this payload writes, `staleKeys` the keys a mode switch makes+// obsolete (dropped from the merged result), and `profiles` the Docker profiles the new config+// requires.+interface ConfigSectionContext {+ updates: Record<string, string>;+ staleKeys: Set<string>;+ profiles: string[];+}++// Secret values are never echoed back to the form, so an empty submission means+// "unchanged" — keep whatever is already stored instead of blanking it.+function setSecret(updates: Record<string, string>, key: string, value: string | undefined): void {+ if (value) updates[key] = value;+}++@ApiTags('infrastructure')+@Controller('infra')+// Every route here is deployment-global (data export/import, infra config, service orchestration),+// so the guard's route-param session fence can never bite. Reject session-scoped keys outright at+// class level, which also covers routes added later. @Public routes are unaffected: the guard+// returns before it reads this metadata.+@RequireUnscopedKey()+export class InfraConfigController {+ private readonly logger = createLogger('InfraConfigController');++ constructor(+ private readonly engineFactory: EngineFactory,+ private readonly dockerService: DockerService,+ private readonly shutdownService: ShutdownService,+ // Best-effort audit emission for the sensitive infra operations below. Injected @Optional and+ // appended last so it never shifts the existing positional args: the running app always provides+ // the @Global AuditService, while the direct-construction unit tests omit it — the `?.` at each+ // call site then makes emission a no-op there instead of forcing every test to wire a mock.+ @Optional()+ private readonly auditService?: AuditService,+ ) {}++ @Get('config')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Read the saved infrastructure configuration for the dashboard form' })+ @ApiResponse({ status: 200, description: 'Saved configuration (secrets omitted)' })+ getConfig(): SavedConfigResponse {+ const saved = readGeneratedEnv();++ // Secrets (passwords, S3 keys) are never returned; the form shows a "set" indicator+ // and an empty submission preserves the stored value (see saveConfig). This lets the+ // dashboard hydrate the form so a save no longer overwrites unseen fields (#226).+ return {+ database: {+ type: saved.DATABASE_TYPE === 'postgres' ? 'postgres' : 'sqlite',+ builtIn: saved.POSTGRES_BUILTIN === 'true',+ host: saved.DATABASE_HOST || '',+ port: saved.DATABASE_PORT || '',+ username: saved.DATABASE_USERNAME || '',+ database: saved.DATABASE_NAME || '',+ schema: saved.POSTGRES_SCHEMA || 'public',+ poolSize: Number(saved.DATABASE_POOL_SIZE) || 10,+ sslEnabled: saved.DATABASE_SSL === 'true',+ sslRejectUnauthorized: saved.DATABASE_SSL_REJECT_UNAUTHORIZED !== 'false',+ passwordSet: Boolean(saved.DATABASE_PASSWORD),+ },+ redis: {+ enabled: saved.REDIS_ENABLED === 'true',+ builtIn: saved.REDIS_BUILTIN === 'true',+ host: saved.REDIS_HOST || '',+ port: saved.REDIS_PORT || '',+ passwordSet: Boolean(saved.REDIS_PASSWORD),+ },+ queue: { enabled: saved.QUEUE_ENABLED === 'true' },+ storage: {+ type: saved.STORAGE_TYPE === 's3' ? 's3' : 'local',+ builtIn: saved.MINIO_BUILTIN === 'true',+ localPath: saved.STORAGE_LOCAL_PATH || '',+ s3Bucket: saved.S3_BUCKET || '',+ s3Region: saved.S3_REGION || '',+ s3Endpoint: saved.S3_ENDPOINT || '',+ s3CredentialsSet: Boolean(saved.S3_ACCESS_KEY_ID && saved.S3_SECRET_ACCESS_KEY),+ },+ engine: {+ type: saved.ENGINE_TYPE || 'whatsapp-web.js',+ headless: saved.PUPPETEER_HEADLESS !== 'false',+ sessionDataPath: saved.SESSION_DATA_PATH || '',+ browserArgs: saved.PUPPETEER_ARGS || '',+ },+ };+ }++ @Put('config')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Save infrastructure configuration to .env file' })+ @ApiResponse({ status: 200, description: 'Configuration saved' })+ @ApiBody({ description: 'Configuration to save', type: SaveConfigDto })+ saveConfig(@Body() config: SaveConfigDto): { message: string; saved: boolean; envPath: string; profiles: string[] } {+ try {+ const profiles: string[] = [];++ // Merge into the existing saved config rather than rebuilding from scratch, so a+ // partial payload (the dashboard only sends the sections it renders) cannot wipe+ // keys it didn't include (#226). The merge is per-section AND per-key: an absent+ // section leaves that section's keys alone, and within a present section an absent+ // field (`undefined`) leaves its stored key alone — only values actually submitted+ // are written. `existing` below is therefore the base for every key the payload+ // does not mention.+ const envPath = generatedEnvPath();+ const existing = readGeneratedEnv();+ const updates: Record<string, string> = {};+ // Keys to remove from the merged result — used to drop stale settings when the+ // user switches mode (postgres->sqlite, s3->local, built-in->external) so a reload+ // never sees the new mode alongside leftover keys from the old one.+ const staleKeys = new Set<string>();++ const ctx: ConfigSectionContext = { updates, staleKeys, profiles };++ if (config.database) {+ this.applyDatabaseSection(config.database, existing, ctx);+ }++ // Redis and queue are independent sections: a payload carrying only one of them must+ // not rewrite (or disable) the other's saved keys.+ if (config.redis) {+ this.applyRedisSection(config.redis, existing, ctx);+ }+ if (config.queue) {+ if (config.queue.enabled !== undefined) updates.QUEUE_ENABLED = config.queue.enabled ? 'true' : 'false';+ }++ if (config.storage) {+ this.applyStorageSection(config.storage, existing, ctx);+ }++ if (config.engine) {+ this.applyEngineSection(config.engine, existing, ctx);+ }++ // .env.generated is one KEY=value per line, loaded on the next boot. A value carrying a+ // line break would write a second line and inject an arbitrary env var the operator never+ // set, so refuse any such value before writing anything.+ for (const [key, value] of Object.entries(updates)) {+ if (/[\r\n]/.test(value)) {+ throw new BadRequestException(`Invalid configuration value for ${key}: line breaks are not allowed`);+ }+ }++ // Existing values are the base; this payload's values win (secrets handled above).+ const merged: Record<string, string> = { ...existing, ...updates };+ // Drop keys made obsolete by a mode switch (postgres->sqlite, s3->local, built-in->external).+ for (const k of staleKeys) {+ delete merged[k];+ }++ // Save-time production guard. The file is loaded on the NEXT boot, which may run with+ // NODE_ENV=production regardless of this process's environment — so evaluate the merged+ // result with the very same boot guard (as production) and refuse the save when that boot+ // would refuse to start. This is what stops a built-in->external flip with no fresh+ // credentials from persisting a config that crash-loops the next production boot.+ // Evaluate what that boot would actually SEE, not just what the file holds: load-env.ts+ // loads with dotenv override:false, so a value supplied via the container environment+ // (compose `environment:`) wins over this file — the precedence the file header documents.+ // Without that, a deployment providing DATABASE_PASSWORD & co. through the environment is+ // refused on EVERY save even though its boot passes the guard. A blank compose-forwarded+ // value counts as unset exactly like clearBlankEnv treats it at boot.+ //+ // Only a HOST-supplied key may win. load-env also merges .env and data/.env.generated into+ // process.env, so reading process.env alone would hand back the very file this save is+ // replacing — the guard would then bless a flip by validating the OLD config (a built-in ->+ // external switch keeping the bundled 'openwa' password would save cleanly and crash-loop the+ // next production boot, the exact case this guard exists for). isOsProvidedEnv separates the+ // two using the snapshot load-env takes before either file is loaded.+ const bootValue = (key: string): string | undefined => {+ const envValue = isOsProvidedEnv(key) ? process.env[key] : undefined;+ if (envValue !== undefined && (envValue.trim() !== '' || !BLANK_SHADOWED_ENV_KEYS.includes(key))) {+ return envValue;+ }+ return merged[key];+ };+ try {+ assertNoDefaultSecretsInProduction({+ nodeEnv: 'production',+ databaseType: bootValue('DATABASE_TYPE'),+ databasePassword: bootValue('DATABASE_PASSWORD'),+ postgresBuiltIn: bootValue('POSTGRES_BUILTIN'),+ databaseHost: bootValue('DATABASE_HOST'),+ storageType: bootValue('STORAGE_TYPE'),+ s3AccessKey: bootValue('S3_ACCESS_KEY_ID'),+ s3SecretKey: bootValue('S3_SECRET_ACCESS_KEY'),+ s3Endpoint: bootValue('S3_ENDPOINT'),+ minioBuiltIn: bootValue('MINIO_BUILTIN'),+ redisPassword: bootValue('REDIS_PASSWORD'),+ });+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error);+ throw new BadRequestException(+ `Refusing to save a configuration that would be rejected at production boot. ${detail}`,+ );+ }+ const body = Object.keys(merged)+ .sort()+ .map(key => `${key}=${merged[key]}`);+ const contents = [+ '# OpenWA Configuration',+ `# Generated at ${new Date().toISOString()}`,+ '# Managed via Dashboard > Infrastructure. Values in process env or project .env take precedence.',+ '',+ ...body,+ '',+ ].join('\n');++ // Write to data/ so it persists across container restarts. Owner-only (0600): this file holds+ // the DB/S3/Redis credentials, so it must not be world-readable between save and next restart.+ writeSecretFile(envPath, contents);+ this.logger.log('Configuration saved', { envPath });++ // Audit the credential-bearing env mutation. Fire-and-forget (not awaited) so saveConfig stays+ // synchronous — its validation rejections must remain synchronous throws the tests assert via+ // `.toThrow`. Only section names + Docker profiles are recorded; secret values are never logged.+ void this.auditService?.logInfo(AuditAction.INFRA_CONFIG_SAVED, {+ metadata: { sections: Object.keys(config ?? {}), profiles },+ });++ const profileMsg = profiles.length > 0 ? ` Docker profiles required: ${profiles.join(', ')}.` : '';++ return {+ message: `Configuration saved successfully.${profileMsg} Server restart required to apply changes.`,+ saved: true,+ // Return a cwd-relative path so the response doesn't disclose the absolute host filesystem layout.+ envPath: path.relative(process.cwd(), envPath),+ profiles,+ };+ } catch (error) {+ // A validation rejection (unknown engine type, or a newline-injected value) is a BadRequestException+ // and MUST surface as its real 4xx status, not be masked as an HTTP 200 {saved:false} — a client+ // branching on HTTP status alone would otherwise treat rejected input as success. Re-throw any+ // HttpException so the Nest layer maps it. A non-HTTP failure (e.g. a writeSecretFile disk/permission+ // error) stays a {saved:false} 200, preserving the dashboard's body.saved handling for I/O faults.+ if (error instanceof HttpException) {+ throw error;+ }+ return {+ message: `Failed to save configuration: ${error instanceof Error ? error.message : 'Unknown error'}`,+ saved: false,+ envPath: '',+ profiles: [],+ };+ }+ }++ // Database. NOTE: these keys must match what src/config/configuration.ts reads.+ private applyDatabaseSection(+ database: DatabaseConfigDto,+ existing: Record<string, string>,+ ctx: ConfigSectionContext,+ ): void {+ const { updates, staleKeys, profiles } = ctx;+ updates.DATABASE_TYPE = database.type || 'sqlite';+ if (database.builtIn !== undefined) {+ updates.POSTGRES_BUILTIN = database.builtIn ? 'true' : 'false';+ }+ // The effective mode: an explicit builtIn wins; when it is absent the saved mode+ // is inherited so a partial payload stays in the current mode instead of silently+ // flipping to external.+ const dbBuiltIn = database.builtIn ?? existing.POSTGRES_BUILTIN === 'true';+ if (database.type === 'postgres') {+ if (dbBuiltIn) {+ // Built-in PostgreSQL - use container name as host+ updates.DATABASE_HOST = 'postgres';+ updates.DATABASE_PORT = '5432';+ updates.DATABASE_USERNAME = 'openwa';+ // The bundled credential is only the DEFAULT. Secrets are never echoed back to the form,+ // so an absent password field means "unchanged", not "reset to 'openwa'" — and the+ // dashboard ALWAYS sends builtIn, so keying the reset on "explicit builtIn:true" reset a+ // re-keyed container on every save from the Infrastructure page.+ // What decides it is whether the stored password belongs to this same bundled container:+ // it does when the previous mode was already built-in. Coming from external, the stored+ // value is the external DB's credential and must not be carried into the container.+ const storedPassword = existing.POSTGRES_BUILTIN === 'true' ? existing.DATABASE_PASSWORD : undefined;+ updates.DATABASE_PASSWORD = database.password || storedPassword || 'openwa';+ updates.DATABASE_NAME = 'openwa';+ // Built-in Postgres is initialized with the default 'public' schema (see+ // scripts/postgres-init-schema.sh). Pin it so a later switch from a custom-schema+ // external DB to built-in doesn't carry a stale POSTGRES_SCHEMA forward.+ updates.POSTGRES_SCHEMA = 'public';+ profiles.push('postgres');+ } else {+ // External PostgreSQL. Flipping built-in -> external must not carry the bundled+ // 'openwa' password into the external config: the production boot guard rejects+ // it, so the next boot would crash-loop. A password in the same payload wins.+ if (database.builtIn === false && existing.POSTGRES_BUILTIN === 'true' && !database.password) {+ staleKeys.add('DATABASE_PASSWORD');+ }+ if (database.host !== undefined) updates.DATABASE_HOST = database.host || 'localhost';+ if (database.port !== undefined) updates.DATABASE_PORT = database.port || '5432';+ if (database.username !== undefined) updates.DATABASE_USERNAME = database.username || 'postgres';+ setSecret(updates, 'DATABASE_PASSWORD', database.password);+ if (database.database !== undefined) updates.DATABASE_NAME = database.database || 'openwa';+ if (database.schema !== undefined) updates.POSTGRES_SCHEMA = database.schema || 'public';+ }+ if (database.poolSize !== undefined) {+ updates.DATABASE_POOL_SIZE = String(database.poolSize || 10);+ }+ if (database.sslEnabled !== undefined) {+ updates.DATABASE_SSL = database.sslEnabled ? 'true' : 'false';+ if (database.sslEnabled) {+ // Default to certificate verification; only relax it when the operator opts out+ // (managed Postgres with self-signed certs: Supabase, Heroku, Render, Railway).+ updates.DATABASE_SSL_REJECT_UNAUTHORIZED = database.sslRejectUnauthorized === false ? 'false' : 'true';+ }+ }+ } else {+ // Switching to sqlite: drop stale postgres connection keys, and reset the built-in+ // flag with them — there is no bundled Postgres backing a SQLite database.+ updates.POSTGRES_BUILTIN = 'false';+ for (const k of [+ 'DATABASE_HOST',+ 'DATABASE_PORT',+ 'DATABASE_USERNAME',+ 'DATABASE_PASSWORD',+ 'DATABASE_NAME',+ 'DATABASE_POOL_SIZE',+ 'DATABASE_SSL',+ 'DATABASE_SSL_REJECT_UNAUTHORIZED',+ 'POSTGRES_SCHEMA',+ ]) {+ staleKeys.add(k);+ }+ }+ }++ private applyRedisSection(redis: RedisConfigDto, existing: Record<string, string>, ctx: ConfigSectionContext): void {+ const { updates, staleKeys, profiles } = ctx;+ if (redis.enabled !== undefined) updates.REDIS_ENABLED = redis.enabled ? 'true' : 'false';+ if (redis.builtIn !== undefined) updates.REDIS_BUILTIN = redis.builtIn ? 'true' : 'false';+ if (redis.builtIn === true) {+ // Built-in Redis - use container name as host. The bundled container runs without+ // auth, so a password saved by an earlier external setup is stale: leaving it+ // would make the client AUTH against a passwordless server on the next boot.+ updates.REDIS_HOST = 'redis';+ updates.REDIS_PORT = '6379';+ if (!redis.password) staleKeys.add('REDIS_PASSWORD');+ } else {+ // External Redis (explicit, or inherited when builtIn is absent)+ if (redis.host !== undefined) updates.REDIS_HOST = redis.host || 'localhost';+ if (redis.port !== undefined) updates.REDIS_PORT = redis.port || '6379';+ }+ setSecret(updates, 'REDIS_PASSWORD', redis.password);+ const redisEnabled = redis.enabled ?? existing.REDIS_ENABLED === 'true';+ const redisBuiltIn = redis.builtIn ?? existing.REDIS_BUILTIN === 'true';+ if (redisEnabled && redisBuiltIn) {+ profiles.push('redis');+ }+ }++ // Storage. NOTE: STORAGE_LOCAL_PATH / S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY are+ // the names configuration.ts reads (previously saved as STORAGE_PATH / S3_*_KEY and+ // silently ignored — #226).+ private applyStorageSection(+ storage: StorageConfigDto,+ existing: Record<string, string>,+ ctx: ConfigSectionContext,+ ): void {+ const { updates, staleKeys, profiles } = ctx;+ updates.STORAGE_TYPE = storage.type || 'local';+ if (storage.builtIn !== undefined) {+ updates.MINIO_BUILTIN = storage.builtIn ? 'true' : 'false';+ }+ if (storage.type === 'local') {+ // Switching to local: drop stale S3 keys, and reset the built-in flag with them —+ // there is no bundled MinIO backing a local storage path.+ updates.MINIO_BUILTIN = 'false';+ if (storage.localPath !== undefined) {+ updates.STORAGE_LOCAL_PATH = storage.localPath || './data/media';+ }+ // Switching to local: drop stale S3 keys.+ for (const k of ['S3_ENDPOINT', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'S3_BUCKET', 'S3_REGION']) {+ staleKeys.add(k);+ }+ } else if (storage.type === 's3') {+ staleKeys.add('STORAGE_LOCAL_PATH');+ if (storage.builtIn === true) {+ // Built-in MinIO - use container name as endpoint+ updates.S3_ENDPOINT = 'http://minio:9000';+ updates.S3_ACCESS_KEY_ID = 'minioadmin';+ updates.S3_SECRET_ACCESS_KEY = 'minioadmin';+ updates.S3_BUCKET = 'openwa';+ updates.S3_REGION = 'us-east-1';+ profiles.push('minio');+ } else {+ // External S3/MinIO. Flipping built-in -> external must not carry the bundled+ // 'minioadmin' credentials or the internal endpoint into the external config:+ // the production boot guard rejects those credentials (crash-loop), and a stale+ // MinIO endpoint would send AWS-bound traffic to the wrong host. Values in the+ // same payload win.+ if (storage.builtIn === false && existing.MINIO_BUILTIN === 'true') {+ if (!storage.s3AccessKey) staleKeys.add('S3_ACCESS_KEY_ID');+ if (!storage.s3SecretKey) staleKeys.add('S3_SECRET_ACCESS_KEY');+ if (!storage.s3Endpoint) staleKeys.add('S3_ENDPOINT');+ }+ if (storage.s3Bucket !== undefined) updates.S3_BUCKET = storage.s3Bucket;+ if (storage.s3Region !== undefined) updates.S3_REGION = storage.s3Region || 'ap-southeast-1';+ setSecret(updates, 'S3_ACCESS_KEY_ID', storage.s3AccessKey);+ setSecret(updates, 'S3_SECRET_ACCESS_KEY', storage.s3SecretKey);+ if (storage.s3Endpoint !== undefined) {+ // Unlike the credentials, the endpoint IS echoed back to the form, so an empty+ // submission is a real "clear it" (moving to the default AWS endpoint), not+ // "unchanged" — leaving a stale MinIO endpoint behind would silently keep+ // pointing S3 traffic at the old host.+ if (storage.s3Endpoint) {+ updates.S3_ENDPOINT = storage.s3Endpoint;+ } else {+ staleKeys.add('S3_ENDPOINT');+ }+ }+ }+ }+ }++ // Engine. NOTE: PUPPETEER_HEADLESS / SESSION_DATA_PATH / PUPPETEER_ARGS are the names+ // configuration.ts reads (previously saved as ENGINE_* and silently ignored — #226).+ private applyEngineSection(+ engine: EngineConfigDto,+ existing: Record<string, string>,+ ctx: ConfigSectionContext,+ ): void {+ const { updates } = ctx;+ // Persist the selected engine so the Infrastructure tile can actually switch engines (the+ // active engine was previously only settable via the ENGINE_TYPE env, never from the UI).+ if (engine.type) {+ const validEngineIds = this.engineFactory.getAvailableEngines().map(e => e.id);+ if (!validEngineIds.includes(engine.type)) {+ throw new BadRequestException(`Unknown engine type: ${engine.type}`);+ }+ updates.ENGINE_TYPE = engine.type;+ }+ if (engine.headless !== undefined) {+ updates.PUPPETEER_HEADLESS = engine.headless ? 'true' : 'false';+ }+ if (engine.sessionDataPath !== undefined) {+ updates.SESSION_DATA_PATH = engine.sessionDataPath || './data/sessions';+ }+ if (engine.browserArgs !== undefined) {+ // Must match configuration.ts's PUPPETEER_ARGS default (4 flags). Once compose blank-forwards+ // PUPPETEER_ARGS, this saved value wins at runtime — a 2-flag default here would silently drop+ // --disable-dev-shm-usage (the Docker /dev/shm tab-crash guard) after any Infrastructure save.+ updates.PUPPETEER_ARGS =+ engine.browserArgs || '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu';+ }+ }++ @Post('restart')+ @HttpCode(HttpStatus.OK)+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Request server restart with Docker orchestration' })+ @ApiResponse({ status: 200, description: 'Server will restart with new profiles' })+ @ApiBody({ required: false, type: RestartDto })+ async requestRestart(@Body() body?: RestartDto): Promise<{+ message: string;+ restarting: boolean;+ profiles: string[];+ profilesToRemove: string[];+ estimatedTime: number;+ orchestration?: object;+ removal?: object;+ }> {+ const profiles = body?.profiles || [];+ const profilesToRemove = body?.profilesToRemove || [];+ let orchestrationResult: object | undefined;+ // Teardown is stop-only (see DockerService.stopManagedService): containers are stopped and+ // retained for re-enable, never deleted — the result below reports exactly that.+ let removalResult: { stopped: string[]; errors: string[] } | undefined;++ this.logger.log('Restart requested', { profiles });+ this.logger.log('Profiles to remove', { profilesToRemove });++ // If profiles are specified, orchestrate Docker containers+ if (this.dockerService.isDockerAvailable()) {+ // Remove only the profiles the Save flow explicitly asked to remove, and never one we're about to+ // (re)start. We deliberately do NOT infer teardown from the saved *_BUILTIN flag: the default+ // data/.env.generated carries POSTGRES_BUILTIN=false, so a bare compose-profile restart would+ // otherwise tear down the very backend the app is running on. (Known minor limitation: switching+ // away from a built-in backend and then reloading the page before restarting can leave the old+ // container running until the next explicit change.)+ // Only ever tear down OpenWA-managed services. An arbitrary profile name (or the empty string)+ // would otherwise reach stopManagedService and, via container-name matching, could stop an unrelated+ // container — so constrain teardown to the managed allowlist and drop anything else.+ const requested = profilesToRemove.filter(p => !profiles.includes(p));+ const toRemove = requested.filter(p => MANAGED_DOCKER_PROFILES.includes(p));+ const ignored = requested.filter(p => !MANAGED_DOCKER_PROFILES.includes(p));+ if (ignored.length > 0) {+ this.logger.warn('Ignoring non-managed profiles in profilesToRemove', { ignored });+ }++ // First, stop containers for disabled services (stop-only: retained, never deleted)+ if (toRemove.length > 0) {+ this.logger.log('Stopping disabled profiles (containers retained)...', { toRemove });+ removalResult = { stopped: [], errors: [] };++ for (const profile of toRemove) {+ try {+ const success = await this.dockerService.stopManagedService(profile);+ if (success) {+ removalResult.stopped.push(profile);+ } else {+ removalResult.errors.push(`Failed to stop ${profile}`);+ }+ } catch (err) {+ removalResult.errors.push(`Error stopping ${profile}: ${err}`);+ }+ }+ this.logger.log('Teardown result', { removalResult });+ }++ // Then, start containers for enabled services. Start shares the SAME managed allowlist as+ // teardown above: a non-managed name reaching orchestrateProfiles could, via container-name+ // matching, select an unrelated host container, so constrain start to the managed profiles too+ // and drop anything else. (DockerService already hard-prefixes openwa-<service> and filters on+ // the com.openwa.service label, so this is defense-in-depth, not the sole control.)+ const toStart = profiles.filter(p => MANAGED_DOCKER_PROFILES.includes(p));+ const ignoredStart = profiles.filter(p => !MANAGED_DOCKER_PROFILES.includes(p));+ if (ignoredStart.length > 0) {+ this.logger.warn('Ignoring non-managed profiles in profiles', { ignoredStart });+ }+ if (toStart.length > 0) {+ this.logger.log('Orchestrating enabled profiles...');+ orchestrationResult = await this.dockerService.orchestrateProfiles(toStart);+ this.logger.log('Orchestration result', { orchestrationResult });+ }+ } else {+ this.logger.warn('Docker not available, writing signal file instead');+ // Fallback: write signal file for host script — but apply the SAME managed-profile+ // constraint as the Docker path above: the external consumer of this file must never be+ // handed a profile name the in-process path would have refused.+ try {+ const signalFile = path.resolve(process.cwd(), 'data', '.orchestration-request.json');+ const toStart = profiles.filter(p => MANAGED_DOCKER_PROFILES.includes(p));+ const toRemove = profilesToRemove.filter(p => !profiles.includes(p) && MANAGED_DOCKER_PROFILES.includes(p));+ const ignored = [...profiles, ...profilesToRemove].filter(p => !MANAGED_DOCKER_PROFILES.includes(p));+ if (ignored.length > 0) {+ this.logger.warn('Ignoring non-managed profiles in the signal-file request', { ignored });+ }+ const orchestrationRequest = {+ timestamp: new Date().toISOString(),+ profiles: toStart,+ profilesToRemove: toRemove,+ action: 'restart-with-profiles',+ };+ fs.writeFileSync(signalFile, JSON.stringify(orchestrationRequest, null, 2), 'utf8');+ this.logger.log('Orchestration request written', { signalFile });+ } catch (err) {+ this.logger.error('Failed to write orchestration request', err instanceof Error ? err.message : String(err));+ }+ }++ // Record the operational action (Docker orchestration + scheduled restart) BEFORE starting the+ // shutdown, awaited so the row is persisted even as the process goes down.+ await this.auditService?.logInfo(AuditAction.INFRA_RESTART_REQUESTED, {+ metadata: { profiles, profilesToRemove },+ });++ // Schedule graceful shutdown after the configurable bounded grace (SHUTDOWN_DELAY_MS,+ // default 3s) — readiness reports 503 during the window so traffic drains first.+ void this.shutdownService.shutdown();++ // Calculate estimated time - base 15s + additional for each service (increased for reliability)+ let estimatedTime = 15;+ if (profiles.includes('postgres')) estimatedTime += 20;+ if (profiles.includes('redis')) estimatedTime += 13;+ if (profiles.includes('minio')) estimatedTime += 15;+ if (profilesToRemove.length > 0) estimatedTime += profilesToRemove.length * 5; // +5s per removal++ return {+ message:+ profiles.length > 0 || profilesToRemove.length > 0+ ? `Server is restarting. Enabling: ${profiles.join(', ') || 'none'}. Disabling: ${profilesToRemove.join(', ') || 'none'}.`+ : 'Server is restarting. Please wait...',+ restarting: true,+ profiles,+ profilesToRemove,+ estimatedTime,+ orchestration: orchestrationResult,+ removal: removalResult,+ };+ }+}diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsnew file mode 100644index 000000000..13b4fe5c4--- /dev/null+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -0,0 +1,1023 @@+// StorageService (imported transitively by the infra controllers) pulls in `archiver`+// v8, which is ESM-only and cannot be parsed by ts-jest. The controller logic+// under test never touches archiver, so a lightweight stub is sufficient.+jest.mock('archiver', () => ({ default: jest.fn() }));++// saveConfig writes the generated env via fs.writeFileSync and reads the existing file+// via fs.existsSync/readFileSync; mock those so tests assert produced content without+// touching the filesystem. existsSync defaults to false (no prior config).+jest.mock('fs', () => {+ const actual = jest.requireActual<typeof import('fs')>('fs');+ return {+ ...actual,+ writeFileSync: jest.fn(),+ // saveConfig now writes the generated env via writeSecretFile, which chmods 0600 — mock it+ // so the secret-hygiene path never touches the real filesystem.+ chmodSync: jest.fn(),+ existsSync: jest.fn().mockReturnValue(false),+ readFileSync: jest.fn().mockReturnValue(''),+ createReadStream: jest.fn(() => jest.requireActual<typeof import('stream')>('stream').Readable.from([])),+ };+});++import { DataSource, QueryFailedError } from 'typeorm';+import { ConflictException } from '@nestjs/common';+import { InfraDataController } from './infra-data.controller';+import { Session, SessionStatus } from '../session/entities/session.entity';+import { Webhook } from '../webhook/entities/webhook.entity';+import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';+import { MessageBatch, BatchStatus } from '../message/entities/message-batch.entity';+import { Template } from '../template/entities/template.entity';+import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';+import { LidMapping } from '../../engine/identity/lid-mapping.entity';+import { PluginInstance } from '../integration/entities/plugin-instance.entity';+import { ConversationMapping } from '../integration/entities/conversation-mapping.entity';+import { IngressEvent } from '../integration/entities/ingress-event.entity';+import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';+import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';+import { StatusUpdate } from '../status-store/entities/status-update.entity';+import { AuditAction } from '../audit/entities/audit-log.entity';++describe('InfraDataController.importData round-trips export-data (no silent message/batch loss)', () => {+ let ds: DataSource;+ let controller: InfraDataController;+ // exportData only reads dataDatabase.type off the config; everything else is unused here.+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };++ const newController = () => new InfraDataController(cfg as never, ds);++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [+ Session,+ Webhook,+ Message,+ MessageBatch,+ PluginInstance,+ ConversationMapping,+ IngressEvent,+ WebhookDeliveryFailure,+ IntegrationDeliveryFailure,+ ],+ synchronize: true,+ });+ await ds.initialize();+ controller = newController();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const seedSession = (id: string) =>+ ds.getRepository(Session).save(+ ds.getRepository(Session).create({+ id,+ name: `session-${id}`,+ status: SessionStatus.READY,+ phone: null,+ pushName: null,+ config: {},+ proxyUrl: null,+ proxyType: null,+ connectedAt: null,+ lastActiveAt: null,+ }),+ );++ it('restores messages and message_batches faithfully — not silently to zero', async () => {+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ chatId: '[email protected]',+ chatName: 'Support Chat',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello',+ type: 'text',+ direction: MessageDirection.INCOMING,+ timestamp: 1700000000,+ metadata: { ack: 2 },+ status: MessageStatus.DELIVERED,+ }),+ );+ await ds.getRepository(MessageBatch).save(+ ds.getRepository(MessageBatch).create({+ id: 'b1',+ batchId: 'BATCH1',+ sessionId: 's1',+ status: BatchStatus.COMPLETED,+ messages: [{ chatId: 'c1', type: 'text', content: {} }],+ options: null as never,+ progress: null as never,+ results: null as never,+ currentIndex: 0,+ startedAt: null,+ completedAt: null,+ }),+ );++ const dump = await controller.exportData();+ expect(dump.counts.messages).toBe(1);+ expect(dump.counts.messageBatches).toBe(1);++ const res = await controller.importData({ tables: dump.tables });++ // The whole point of the bug: a valid backup must restore with no warnings and imported:true.+ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(res.counts.messages).toBe(1);+ expect(res.counts.messageBatches).toBe(1);++ // ...and the rows must actually be present after the DELETE+reinsert, with fields intact.+ expect(await ds.getRepository(Message).count()).toBe(1);+ expect(await ds.getRepository(MessageBatch).count()).toBe(1);+ const m = await ds.getRepository(Message).findOneByOrFail({ id: 'm1' });+ expect(m.body).toBe('hello');+ expect(m.waMessageId).toBe('WA1');+ expect(m.chatName).toBe('Support Chat');+ expect(m.from).toBe('[email protected]');+ expect(m.to).toBe('[email protected]');+ expect(m.metadata).toEqual({ ack: 2 });+ const b = await ds.getRepository(MessageBatch).findOneByOrFail({ id: 'b1' });+ expect(b.batchId).toBe('BATCH1');+ expect(b.status).toBe(BatchStatus.COMPLETED);+ });++ it('round-trips plugin instances + integration delivery failures (Integration Fabric + DLQ)', async () => {+ await seedSession('s1');+ await ds.getRepository(PluginInstance).save(+ ds.getRepository(PluginInstance).create({+ id: 'chatwoot:acct1',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ sessionScope: 's1',+ secret: 'hmac-secret',+ verifyToken: null,+ config: { baseUrl: 'https://x' },+ enabled: true,+ }),+ );+ await ds.getRepository(IntegrationDeliveryFailure).save(+ ds.getRepository(IntegrationDeliveryFailure).create({+ direction: 'outbound',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ sessionId: 's1',+ deliveryId: 'd1',+ attempts: 3,+ lastError: 'boom',+ payload: { foo: 'bar' },+ redriven: false,+ }),+ );++ const dump = await controller.exportData();+ expect(dump.counts.pluginInstances).toBe(1);+ expect(dump.counts.integrationDeliveryFailures).toBe(1);++ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(res.counts.pluginInstances).toBe(1);+ expect(res.counts.integrationDeliveryFailures).toBe(1);++ expect(await ds.getRepository(PluginInstance).count()).toBe(1);+ expect(await ds.getRepository(IntegrationDeliveryFailure).count()).toBe(1);+ const pi = await ds.getRepository(PluginInstance).findOneByOrFail({ id: 'chatwoot:acct1' });+ expect(pi.secret).toBe('hmac-secret'); // ingress HMAC secret survives a SQLite→Postgres migration+ expect(pi.config).toEqual({ baseUrl: 'https://x' });+ const dlf = await ds.getRepository(IntegrationDeliveryFailure).findOneByOrFail({ deliveryId: 'd1' });+ expect(dlf.lastError).toBe('boom');+ expect(dlf.payload).toEqual({ foo: 'bar' });+ });++ it('round-trips the ingress dispatch-lifecycle columns so a restored pending event still replays', async () => {+ await seedSession('s1');+ const ingressRepo = ds.getRepository(IngressEvent);+ // A pending event (still carrying its payload, awaiting reconciler replay) and a retired one+ // (dispatch outcome recorded, payload slimmed to NULL).+ await ingressRepo.save(+ ingressRepo.create({+ id: 'ie-pending',+ instanceId: 'acct1',+ pluginId: 'chatwoot',+ providerDeliveryId: 'dlv-1',+ route: 'chatwoot/acct1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ payloadHash: 'abc123',+ sessionId: 's1',+ dispatchState: 'pending',+ dispatchAttempts: 2,+ lastDispatchAt: new Date('2026-01-02T03:04:05.000Z'),+ }),+ );+ await ingressRepo.save(+ ingressRepo.create({+ id: 'ie-retired',+ instanceId: 'acct1',+ pluginId: 'chatwoot',+ providerDeliveryId: 'dlv-2',+ route: 'chatwoot/acct1',+ payload: null,+ payloadHash: 'def456',+ sessionId: 's1',+ dispatchState: 'dispatched',+ dispatchAttempts: 1,+ lastDispatchAt: new Date('2026-01-02T03:04:05.000Z'),+ }),+ );++ const dump = await controller.exportData();+ expect(dump.counts.ingressEvents).toBe(2);++ await ingressRepo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(res.counts.ingressEvents).toBe(2);++ // A restored 'pending' row that lost its dispatchState would read as NULL ("not watched"): the+ // reconciler would never replay it while the dedup key still blocked the provider's retry.+ const pending = await ingressRepo.findOneByOrFail({ id: 'ie-pending' });+ expect(pending.dispatchState).toBe('pending');+ expect(pending.dispatchAttempts).toBe(2);+ expect(pending.lastDispatchAt).toEqual(new Date('2026-01-02T03:04:05.000Z'));+ expect(pending.payloadHash).toBe('abc123');+ expect(pending.payload).toEqual({ headers: {}, query: {}, body: '{}', rawBody: '{}' });++ const retired = await ingressRepo.findOneByOrFail({ id: 'ie-retired' });+ expect(retired.dispatchState).toBe('dispatched');+ expect(retired.payloadHash).toBe('def456');+ // A retired payload must stay NULL — re-materializing it as '{}' would make the slimmed dedup+ // row read as a pending event with an empty body.+ expect(retired.payload).toBeNull();+ });++ it('imports a pre-lifecycle backup (no dispatch columns) as not-watched legacy rows', async () => {+ await seedSession('s1');+ const res = await controller.importData({+ tables: {+ ingressEvents: [+ {+ id: 'ie-legacy',+ instanceId: 'acct1',+ pluginId: 'chatwoot',+ providerDeliveryId: 'dlv-9',+ route: 'chatwoot/acct1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ sessionId: 's1',+ createdAt: '2026-01-01T00:00:00.000Z',+ },+ ] as never,+ },+ });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ // Columns absent from an older backup import as NULL/0 — the same "not watched" reading legacy+ // rows have by design (the reconciler never sweeps them, so an upgrade can't mass-replay history).+ const legacy = await ds.getRepository(IngressEvent).findOneByOrFail({ id: 'ie-legacy' });+ expect(legacy.dispatchState).toBeNull();+ expect(legacy.dispatchAttempts).toBe(0);+ expect(legacy.lastDispatchAt).toBeNull();+ expect(legacy.payloadHash).toBeNull();+ });++ it('rolls back and reports imported:false when a row fails — existing data is preserved', async () => {+ // Pre-existing data that must survive a failed import.+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ chatId: 'c1',+ from: 'a',+ to: 'b',+ body: 'keep me',+ type: 'text',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ }),+ );++ // A backup whose message row is malformed (missing the non-null from/to) must fail the whole import.+ const res = await controller.importData({+ tables: {+ sessions: [{ id: 's2', name: 'imported', status: 'ready' }] as never,+ messages: [+ { id: 'mX', sessionId: 's2', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },+ ] as never,+ },+ });++ expect(res.imported).toBe(false);+ expect(res.warnings.length).toBeGreaterThan(0);++ // The destructive DELETE must have been rolled back — original data intact, nothing from the bad import.+ expect(await ds.getRepository(Message).count()).toBe(1);+ expect((await ds.getRepository(Message).findOneByOrFail({ id: 'm1' })).body).toBe('keep me');+ expect(await ds.getRepository(Session).findOneBy({ id: 's2' })).toBeNull();+ });++ it('refuses an empty/garbage backup — does not wipe existing data (#488 review must-fix)', async () => {+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm1',+ sessionId: 's1',+ chatId: 'c1',+ from: 'a',+ to: 'b',+ body: 'keep me',+ type: 'text',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ }),+ );++ // A wrong/empty file (no rows to restore) must NOT commit the all-rows DELETE and report success.+ const res = await controller.importData({ tables: {} });++ expect(res.imported).toBe(false);+ expect(res.warnings.length).toBeGreaterThan(0);+ expect(await ds.getRepository(Session).count()).toBe(1);+ expect(await ds.getRepository(Message).count()).toBe(1);+ });++ it('propagates a genuine clear-table failure (lock/IO) instead of committing a merged restore', async () => {+ // Pre-existing data that must survive if a clear step fails.+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm1',+ sessionId: 's1',+ chatId: 'c1',+ from: 'a',+ to: 'b',+ body: 'keep me',+ type: 'text',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ }),+ );++ expect(await ds.getRepository(Message).count()).toBe(1); // sanity: seeded++ // Make ONLY `DELETE FROM messages` fail with a genuine (non-missing-table) error. Previously a+ // blind `.catch(() => {})` swallowed this and let a disjoint-id backup COMMIT a merged (not+ // replaced) restore on SQLite; scoping the swallow to missing-table means the failure must now+ // SURFACE (reaching the existing rollback-and-rethrow catch). A Proxy over the runner the+ // controller creates intercepts just that one statement — no spy on `query`, so TypeORM's own+ // internal `this.query` transaction control (BEGIN/ROLLBACK) is untouched.+ const lockErr = new QueryFailedError(+ 'DELETE FROM messages',+ [],+ Object.assign(new Error('SQLITE_BUSY: database is locked'), { code: 'SQLITE_BUSY' }),+ );+ let rolledBack = false;+ const origCreate = ds.createQueryRunner.bind(ds);+ jest.spyOn(ds, 'createQueryRunner').mockImplementation(() => {+ const real = origCreate();+ return new Proxy(real, {+ get(target, prop) {+ if (prop === 'query') {+ return (sql: string, params?: unknown[]) =>+ sql === 'DELETE FROM messages'+ ? Promise.reject(lockErr)+ : (target.query as (q: string, p?: unknown[]) => Promise<unknown>).call(target, sql, params);+ }+ if (prop === 'rollbackTransaction') {+ return async () => {+ rolledBack = true;+ return target.rollbackTransaction.call(target);+ };+ }+ const val = (target as unknown as Record<string, unknown>)[prop as string];+ return typeof val === 'function' ? (val as (...a: unknown[]) => unknown).bind(target) : val;+ },+ });+ });++ await expect(controller.importData({ tables: { messages: [] } })).rejects.toThrow(/database is locked/);+ expect(rolledBack).toBe(true);++ jest.restoreAllMocks();+ });+});++describe('InfraDataController.import/export preserves every data-DB table', () => {+ let ds: DataSource;+ let controller: InfraDataController;+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };+ const newController = () => new InfraDataController(cfg as never, ds);++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Session, Webhook, Message, MessageBatch, Template, BaileysStoredMessage, LidMapping],+ synchronize: true,+ });+ await ds.initialize();+ controller = newController();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const seedSession = (id: string) =>+ ds.getRepository(Session).save(+ ds.getRepository(Session).create({+ id,+ name: `session-${id}`,+ status: SessionStatus.READY,+ phone: null,+ pushName: null,+ config: {},+ proxyUrl: null,+ proxyType: null,+ connectedAt: null,+ lastActiveAt: null,+ }),+ );++ // lid_mappings is the persisted lid->phone cache; it is NOT a FK to sessions, so the sessions DELETE+ // never touches it — but export omitted it, so a backup→restore into a fresh DB dropped it entirely.+ it('restores lid_mappings instead of dropping them on a backup→restore', async () => {+ await seedSession('s1');+ const lidRepo = ds.getRepository(LidMapping);+ await lidRepo.save(lidRepo.create({ lid: '111', phone: '628111', sessionId: 's1' }));+ await lidRepo.save(lidRepo.create({ lid: '222', phone: null, sessionId: 's1' })); // negative cache++ const dump = await controller.exportData();+ expect((dump.tables as unknown as { lidMappings?: unknown[] }).lidMappings).toHaveLength(2);++ // Simulate restoring into a fresh data DB (the documented backend-migration flow).+ await lidRepo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(await lidRepo.count()).toBe(2);+ expect((await lidRepo.findOneByOrFail({ lid: '111' })).phone).toBe('628111');+ expect((await lidRepo.findOneByOrFail({ lid: '222' })).phone).toBeNull();+ });++ // The messages import column list must carry every later-added column; `author` (the group+ // sender identity) was the one that drifted — a restored backup silently lost all attribution.+ it('restores the group-sender author column on a backup→restore', async () => {+ await seedSession('s1');+ const msgRepo = ds.getRepository(Message);+ await msgRepo.save(+ msgRepo.create({+ sessionId: 's1',+ waMessageId: 'WA-A1',+ chatId: '[email protected]',+ chatName: 'Alice',+ author: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello',+ type: 'text',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ timestamp: 1700000000,+ }),+ );++ const dump = await controller.exportData();+ await msgRepo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ const restored = await msgRepo.findOneByOrFail({ waMessageId: 'WA-A1' });+ expect(restored.author).toBe('[email protected]');+ });++ // DELETE FROM sessions cascades to templates + baileys_stored_messages (both FK ON DELETE CASCADE),+ // so an import that never re-inserts them permanently wipes both on the documented backup flow.+ it('restores templates and baileys_stored_messages instead of cascade-wiping them', async () => {+ await seedSession('s1');+ await ds+ .getRepository(Template)+ .save(ds.getRepository(Template).create({ id: 't1', sessionId: 's1', name: 'greet', body: 'Hi {{name}}' }));+ await ds.getRepository(BaileysStoredMessage).save(+ ds.getRepository(BaileysStoredMessage).create({+ id: 'bsm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ serializedMessage: '{"k":"v"}',+ }),+ );++ const dump = await controller.exportData();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(await ds.getRepository(Template).count()).toBe(1);+ expect(await ds.getRepository(BaileysStoredMessage).count()).toBe(1);+ expect((await ds.getRepository(Template).findOneByOrFail({ id: 't1' })).body).toBe('Hi {{name}}');+ expect((await ds.getRepository(BaileysStoredMessage).findOneByOrFail({ id: 'bsm1' })).serializedMessage).toBe(+ '{"k":"v"}',+ );+ });++ // The webhooks INSERT omitted the `filters` column, so a filtered webhook came back firing on+ // every event after a restore (over-delivery / PII fan-out).+ it('preserves webhook filters across a round-trip', async () => {+ await seedSession('s1');+ await ds.getRepository(Webhook).save(+ ds.getRepository(Webhook).create({+ id: 'w1',+ sessionId: 's1',+ url: 'https://example.com/hook',+ events: ['message'],+ secret: null,+ headers: {},+ active: true,+ retryCount: 3,+ filters: { conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }] },+ }),+ );++ const dump = await controller.exportData();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.imported).toBe(true);+ expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).filters).toEqual({+ conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }],+ });+ // The active flag (exported as integer 1 from SQLite) must round-trip as a real boolean.+ expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).active).toBe(true);+ });+});++describe('InfraDataController C002 audit trail — import emits only on a committed restore', () => {+ let ds: DataSource;+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };+ const build = (audit: { logInfo: jest.Mock }): InfraDataController =>+ new InfraDataController(cfg as never, ds, audit as never);++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [+ Session,+ Webhook,+ Message,+ MessageBatch,+ PluginInstance,+ ConversationMapping,+ IngressEvent,+ WebhookDeliveryFailure,+ IntegrationDeliveryFailure,+ ],+ synchronize: true,+ });+ await ds.initialize();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const seedSession = (id: string) =>+ ds.getRepository(Session).save(+ ds.getRepository(Session).create({+ id,+ name: `session-${id}`,+ status: SessionStatus.READY,+ phone: null,+ pushName: null,+ config: {},+ proxyUrl: null,+ proxyType: null,+ connectedAt: null,+ lastActiveAt: null,+ }),+ );++ it('emits INFRA_DATA_EXPORTED then INFRA_DATA_IMPORTED across a successful round-trip', async () => {+ await seedSession('s1');+ const audit = { logInfo: jest.fn().mockResolvedValue(null) };+ const controller = build(audit);+ const dump = await controller.exportData();+ const res = await controller.importData({ tables: dump.tables });+ expect(res.imported).toBe(true);+ const actions = (audit.logInfo.mock.calls as Array<[AuditAction, unknown]>).map(c => c[0]);+ expect(actions).toContain(AuditAction.INFRA_DATA_EXPORTED);+ expect(actions).toContain(AuditAction.INFRA_DATA_IMPORTED);+ });++ it('does NOT emit INFRA_DATA_IMPORTED when an empty backup is refused (no data changed)', async () => {+ await seedSession('s1');+ const audit = { logInfo: jest.fn().mockResolvedValue(null) };+ const res = await build(audit).importData({ tables: {} });+ expect(res.imported).toBe(false);+ const actions = (audit.logInfo.mock.calls as Array<[AuditAction, unknown]>).map(c => c[0]);+ expect(actions).not.toContain(AuditAction.INFRA_DATA_IMPORTED);+ });+});++describe('InfraDataController.exportData optional-table strictness', () => {+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };+ const build = (query: jest.Mock) => new InfraDataController(cfg as never, { query } as never);++ it('rethrows a non-missing-table error (lock/IO/timeout) instead of reporting a partial export as complete', async () => {+ // A lock on ONE optional table must fail the whole export: silently exporting without that table+ // produces a backup the import then treats as authoritative, DELETing the table's existing rows.+ const query = jest.fn((sql: string) =>+ sql === 'SELECT * FROM messages'+ ? Promise.reject(new Error('SQLITE_BUSY: database is locked'))+ : Promise.resolve([]),+ );+ await expect(build(query).exportData()).rejects.toThrow(/database is locked/);+ });++ it('tolerates a genuinely absent optional table — and marks it in skippedTables', async () => {+ const missing = Object.assign(new Error('no such table: messages'), { name: 'SqliteError' });+ const query = jest.fn((sql: string) =>+ sql === 'SELECT * FROM messages' ? Promise.reject(missing) : Promise.resolve([]),+ );+ const dump = await build(query).exportData();+ expect(dump.counts.messages).toBe(0);+ expect(dump.tables.messages).toEqual([]);+ expect(dump.skippedTables).toContain('messages');+ // Every other table still exported (all empty here, none skipped).+ expect(dump.skippedTables).toEqual(['messages']);+ });++ it('strips the Postgres generated body_ts tsvector from exported message rows', async () => {+ // Postgres' STORED generated FTS column rides along in `SELECT *`; it is an index artifact, not+ // payload, and must not be serialized into a (dialect-neutral) backup.+ const messageRow = {+ id: 'm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ chatId: 'c1',+ chatName: null,+ author: null,+ from: 'a',+ to: 'b',+ body: 'hello',+ type: 'text',+ direction: 'incoming',+ timestamp: 1700000000,+ metadata: null,+ status: 'delivered',+ createdAt: '2026-01-01T00:00:00.000Z',+ body_ts: "'hello'",+ };+ const query = jest.fn((sql: string) => Promise.resolve(sql === 'SELECT * FROM messages' ? [messageRow] : []));+ const dump = await build(query).exportData();+ expect(dump.tables.messages).toHaveLength(1);+ expect(dump.tables.messages[0]).not.toHaveProperty('body_ts');+ expect(dump.tables.messages[0].body).toBe('hello');+ });+});++describe('InfraDataController.importData status_updates + runtime reconciliation', () => {+ let ds: DataSource;+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };++ // Positional constructor: (config, dataDs, auditService?, sessionService?, lidMappingStore?).+ // The @Optional args trail the required ones; auditService is unused in these tests, so its slot+ // stays undefined.+ const build = (opts: { sessionService?: unknown; lidMappingStore?: unknown } = {}) =>+ new InfraDataController(cfg as never, ds, undefined, opts.sessionService as never, opts.lidMappingStore as never);++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [+ Session,+ Webhook,+ Message,+ MessageBatch,+ Template,+ BaileysStoredMessage,+ LidMapping,+ PluginInstance,+ ConversationMapping,+ IngressEvent,+ WebhookDeliveryFailure,+ IntegrationDeliveryFailure,+ StatusUpdate,+ ],+ synchronize: true,+ });+ await ds.initialize();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const seedSession = (id: string) =>+ ds.getRepository(Session).save(+ ds.getRepository(Session).create({+ id,+ name: `session-${id}`,+ status: SessionStatus.READY,+ phone: null,+ pushName: null,+ config: {},+ proxyUrl: null,+ proxyType: null,+ connectedAt: null,+ lastActiveAt: null,+ }),+ );++ it('exports and restores status_updates (the table the docs promise is covered)', async () => {+ await seedSession('s1');+ const statusRepo = ds.getRepository(StatusUpdate);+ await statusRepo.save(+ statusRepo.create({+ id: 'su1',+ sessionId: 's1',+ contactJid: '[email protected]',+ contactName: 'Alice',+ contactPushName: 'alice',+ waStatusId: 'false_status@broadcast_ABC',+ type: 'text',+ caption: 'on vacation',+ mediaOmitted: true,+ omitReason: 'over_cap',+ backgroundColor: '#FF0000',+ font: 2,+ postedAt: 1750000000000,+ expiresAt: 1750086400000,+ }),+ );++ const controller = build();+ const dump = await controller.exportData();+ expect(dump.counts.statusUpdates).toBe(1);+ expect(dump.skippedTables).toEqual([]);++ await statusRepo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(res.counts.statusUpdates).toBe(1);+ const restored = await statusRepo.findOneByOrFail({ id: 'su1' });+ expect(restored.waStatusId).toBe('false_status@broadcast_ABC');+ expect(restored.caption).toBe('on vacation');+ expect(restored.mediaOmitted).toBe(true); // boolean survives the 0/1 round-trip+ expect(restored.omitReason).toBe('over_cap');+ expect(restored.font).toBe(2);+ expect(restored.postedAt).toBe(1750000000000);+ expect(restored.expiresAt).toBe(1750086400000);+ });++ it('tolerates body_ts on imported message rows (backup made before the strip)', async () => {+ await seedSession('s1');+ const res = await build().importData({+ tables: {+ sessions: [+ {+ id: 's1',+ name: 'session-s1',+ status: 'ready',+ config: '{}',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ },+ ] as never,+ messages: [+ {+ id: 'm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ chatId: 'c1',+ from: 'a',+ to: 'b',+ body: 'hello',+ type: 'text',+ direction: 'incoming',+ status: 'delivered',+ createdAt: '2026-01-01T00:00:00.000Z',+ body_ts: "'hello'", // legacy Postgres export artifact — must be ignored, not fail+ },+ ] as never,+ },+ });+ expect(res.imported).toBe(true);+ expect(res.warnings).toEqual([]);+ expect((await ds.getRepository(Message).findOneByOrFail({ id: 'm1' })).body).toBe('hello');+ });++ it('reloads the in-memory lid mappings after a committed restore', async () => {+ await seedSession('s1');+ const lidMappingStore = { reload: jest.fn().mockResolvedValue(undefined) };+ const controller = build({ lidMappingStore });+ const dump = await controller.exportData();+ const res = await controller.importData({ tables: dump.tables });+ expect(res.imported).toBe(true);+ expect(lidMappingStore.reload).toHaveBeenCalledTimes(1);+ });++ it('does NOT reload lid mappings when the import is refused (nothing committed)', async () => {+ await seedSession('s1');+ const lidMappingStore = { reload: jest.fn().mockResolvedValue(undefined) };+ const res = await build({ lidMappingStore }).importData({ tables: {} });+ expect(res.imported).toBe(false);+ expect(lidMappingStore.reload).not.toHaveBeenCalled();+ });++ it('409s when a live engine would be orphaned by the replace — unless force=true', async () => {+ await seedSession('s1');+ const controller = build({ sessionService: { getActiveSessionIds: () => ['ghost'] } });+ const dump = await controller.exportData(); // backup contains only s1, not the running 'ghost'++ // Without force: 409 Conflict, and the destructive replace never started.+ const err = await controller.importData({ tables: dump.tables }).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ConflictException);+ expect((err as ConflictException).getStatus()).toBe(409);+ expect((err as ConflictException).message).toContain('ghost');+ expect(await ds.getRepository(Session).count()).toBe(1); // nothing deleted++ // With force: the restore proceeds and the response tells the operator a restart is required+ // to stop the orphaned engine.+ const res = await controller.importData({ tables: dump.tables, force: true });+ expect(res.imported).toBe(true);+ expect(res.restartRequired).toBe(true);+ expect(res.orphanedEngines).toEqual(['ghost']);+ });++ it('reports restartRequired:false when no live engine is orphaned', async () => {+ await seedSession('s1');+ const controller = build({ sessionService: { getActiveSessionIds: () => ['s1'] } });+ const dump = await controller.exportData();+ const res = await controller.importData({ tables: dump.tables });+ expect(res.imported).toBe(true);+ expect(res.restartRequired).toBe(false);+ expect(res.orphanedEngines).toEqual([]);+ });++ it('stopOrphans=true stops the orphan engines inside the request and keeps restartRequired:false', async () => {+ await seedSession('s1');+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['ghost'], notRunning: [], failed: [] });+ const controller = build({+ sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },+ });+ const dump = await controller.exportData(); // backup contains only s1, not 'ghost'++ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });++ // The orphan engines were stopped (called once with exactly the orphan ids) and the import+ // proceeded without requiring a restart — the whole point of stopOrphans vs force.+ expect(stopOrphanEngines).toHaveBeenCalledWith(['ghost']);+ expect(stopOrphanEngines).toHaveBeenCalledTimes(1);+ expect(res.imported).toBe(true);+ expect(res.restartRequired).toBe(false);+ expect(res.stoppedOrphanEngines).toEqual(['ghost']);+ expect(res.failedOrphanEngines).toEqual([]);+ expect(res.orphanedEngines).toEqual(['ghost']);+ });++ it('still reports the engines it already stopped when the import rolls back', async () => {+ // The pre-flight teardown runs BEFORE the transaction opens and cannot be rolled back with it.+ // An operator reading imported:false plus empty orphan arrays would conclude nothing happened,+ // while their sessions are actually down.+ await seedSession('s1');+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['ghost'], notRunning: [], failed: [] });+ const controller = build({+ sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },+ });+ const dump = await controller.exportData();++ // A message row missing the non-null from/to fails mid-import and forces the all-or-nothing rollback.+ const res = await controller.importData({+ tables: {+ ...dump.tables,+ messages: [+ { id: 'mX', sessionId: 's1', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },+ ] as never,+ },+ stopOrphans: true,+ });++ expect(res.imported).toBe(false); // the DB really did roll back+ expect(stopOrphanEngines).toHaveBeenCalledWith(['ghost']); // ...but the teardown really did happen+ expect(res.stoppedOrphanEngines).toEqual(['ghost']);+ expect(res.orphanedEngines).toEqual(['ghost']);+ expect(res.restartRequired).toBe(false); // sessions survive the rollback; restart them via the API+ });++ it('flags restartRequired on a rolled-back import whose orphan teardown failed', async () => {+ // The failed teardown is the one irreversible thing a rollback cannot undo: the Chromium/socket+ // may still be alive, so this must stay true even though no data changed.+ await seedSession('s1');+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: [], notRunning: [], failed: ['ghost'] });+ const controller = build({+ sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },+ });+ const dump = await controller.exportData();++ const res = await controller.importData({+ tables: {+ ...dump.tables,+ messages: [+ { id: 'mX', sessionId: 's1', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },+ ] as never,+ },+ stopOrphans: true,+ });++ expect(res.imported).toBe(false);+ expect(res.restartRequired).toBe(true);+ expect(res.failedOrphanEngines).toEqual(['ghost']);+ });++ it('stopOrphans=true surfaces a teardown failure as restartRequired:true + a warning (Map reconciled regardless)', async () => {+ await seedSession('s1');+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['g1'], notRunning: [], failed: ['g2'] });+ const controller = build({+ sessionService: { getActiveSessionIds: () => ['g1', 'g2'], stopOrphanEngines },+ });+ const dump = await controller.exportData();++ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });++ expect(res.imported).toBe(true);+ expect(res.restartRequired).toBe(true);+ expect(res.failedOrphanEngines).toEqual(['g2']);+ expect(res.stoppedOrphanEngines).toEqual(['g1']);+ expect(res.notices.some(w => w.includes('g2') && w.includes('restart'))).toBe(true);+ });++ it('stopOrphans=true reports notRunning orphans (still initializing) as a warning', async () => {+ await seedSession('s1');+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['g1'], notRunning: ['g-init'], failed: [] });+ const controller = build({+ sessionService: { getActiveSessionIds: () => ['g1', 'g-init'], stopOrphanEngines },+ });+ const dump = await controller.exportData();++ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });++ expect(res.imported).toBe(true);+ expect(res.restartRequired).toBe(false);+ expect(res.notices.some(w => w.includes('g-init') && w.includes('initializing'))).toBe(true);+ });++ it('stopOrphans=true is a no-op when there is no sessionService wired', async () => {+ // Some stripped-down module shapes may not import SessionModule; the controller must not throw+ // when stopOrphans is requested but the service is unavailable — it falls back to refuse/force.+ await seedSession('s1');+ const controller = build({}); // no sessionService+ const dump = await controller.exportData();++ // Without sessionService there are no active ids to detect, so no orphan, no 409 — the import+ // proceeds normally. (This matches the @Optional() wiring; the gate only engages when the+ // service is present.)+ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });+ expect(res.imported).toBe(true);+ expect(res.stoppedOrphanEngines).toEqual([]);+ });+});++// C002: the infra module exposed sensitive ADMIN operations (credential config write, restart/Docker+// orchestration, full-DB + storage export/import) with no audit trail. Each now emits an AuditAction.+describe('InfraDataController C002 audit trail (light-dependency handlers)', () => {+ const makeAudit = (): { logInfo: jest.Mock } => ({ logInfo: jest.fn().mockResolvedValue(null) });++ // Positional constructor: (config, dataDs, auditService?, sessionService?, lidMappingStore?).+ // auditService is the first trailing @Optional arg.+ const build = (+ audit: { logInfo: jest.Mock },+ overrides: Partial<{+ config: unknown;+ dataDs: unknown;+ }> = {},+ ): InfraDataController =>+ new InfraDataController((overrides.config ?? {}) as never, (overrides.dataDs ?? {}) as never, audit as never);++ it('exportData emits INFRA_DATA_EXPORTED with per-table counts', async () => {+ const audit = makeAudit();+ const controller = build(audit, {+ config: { get: (k: string, d?: unknown) => (k === 'dataDatabase.type' ? 'sqlite' : d) },+ dataDs: { query: jest.fn().mockResolvedValue([]) },+ });+ await controller.exportData();+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { counts: { sessions: number } } }]>;+ expect(calls[0][0]).toBe(AuditAction.INFRA_DATA_EXPORTED);+ expect(calls[0][1].metadata.counts.sessions).toBe(0);+ });+});diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsnew file mode 100644index 000000000..c8d853acd--- /dev/null+++ b/src/modules/infra/infra-data.controller.ts@@ -0,0 +1,997 @@+import { Controller, Get, Post, Body, ConflictException, HttpCode, HttpStatus, Optional } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';+import { ConfigService } from '@nestjs/config';+import { DataSource } from 'typeorm';+import { InjectDataSource } from '@nestjs/typeorm';+import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { isSafeSessionName } from '../../common/utils/path-safety';+import { createLogger } from '../../common/services/logger.service';+import { isMissingTableError } from '../../common/utils/db-errors';+import { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';+import { SessionService } from '../session/session.service';+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';++// Database migration types for export/import+interface SessionRow {+ id: string;+ name: string;+ status: string;+ phone: string | null;+ pushName: string | null;+ config: string | Record<string, unknown>;+ proxyUrl: string | null;+ proxyType: string | null;+ connectedAt: string | null;+ lastActiveAt: string | null;+ createdAt: string;+ updatedAt: string;+}++interface WebhookRow {+ id: string;+ sessionId: string;+ url: string;+ events: string | string[];+ secret: string | null;+ headers: string | Record<string, string>;+ filters: string | Record<string, unknown> | null;+ active: boolean | number;+ retryCount: number;+ lastTriggeredAt: string | null;+ createdAt: string;+ updatedAt: string;+}++// Shapes mirror the REAL table columns as returned by `SELECT *` (export-data), not the+// camelCase TypeORM entity properties. `messages` columns are the property names; `message_batches`+// columns are snake_case (the entity maps them via `name:`). Keeping these accurate is what keeps+// the import column lists below from drifting back into "no such column" failures.+interface MessageRow {+ id: string;+ sessionId: string;+ waMessageId: string | null;+ chatId: string;+ chatName: string | null;+ /** Group participant JID (nullable; added to messages after chatName — keep the import list in sync). */+ author: string | null;+ from: string;+ to: string;+ body: string | null;+ type: string;+ direction: string;+ timestamp: number | string | null;+ metadata: string | Record<string, unknown> | null;+ status: string;+ createdAt: string;+ /**+ * Postgres-only STORED generated tsvector (FTS). Present in `SELECT *` rows read from a Postgres+ * source (and in backups made before it was stripped) but never a real payload column: export drops+ * it, and the import's explicit column list ignores it. Declared so both directions type-check.+ */+ body_ts?: unknown;+}++interface MessageBatchRow {+ id: string;+ batch_id: string;+ session_id: string;+ status: string;+ messages: string | unknown[];+ options: string | Record<string, unknown> | null;+ progress: string | Record<string, unknown> | null;+ results: string | unknown[] | null;+ current_index: number;+ created_at: string;+ updated_at: string;+ started_at: string | null;+ completed_at: string | null;+}++// templates + baileys_stored_messages both FK sessions ON DELETE CASCADE, so import's+// `DELETE FROM sessions` wipes them; they must be exported and re-inserted or the documented+// backup flow loses them permanently.+interface TemplateRow {+ id: string;+ sessionId: string;+ name: string;+ body: string;+ header: string | null;+ footer: string | null;+ createdAt: string;+ updatedAt: string;+}++interface BaileysStoredMessageRow {+ id: string;+ sessionId: string;+ waMessageId: string;+ serializedMessage: string;+ createdAt: string;+}++// The persisted lid->phone resolution cache. Not a FK to sessions (provenance only), so the import's+// `DELETE FROM sessions` never clears it — it must be exported + re-inserted explicitly or a+// backup→restore into a fresh DB loses the whole cache (it self-heals via re-lookup, but lossily).+interface LidMappingRow {+ lid: string;+ phone: string | null;+ sessionId: string | null;+ updatedAt: string;+}++interface PluginInstanceRow {+ id: string;+ pluginId: string;+ instanceId: string;+ sessionScope: string | null;+ secret: string;+ verifyToken: string | null;+ config: string | Record<string, unknown> | null;+ enabled: boolean | number;+ createdAt: string;+ updatedAt: string;+}++interface ConversationMappingRow {+ id: string;+ sessionId: string;+ chatId: string;+ pluginId: string;+ instanceId: string;+ providerConversationId: string;+ handoverState: string;+ metadata: string | Record<string, unknown> | null;+ updatedAt: string;+}++interface IngressEventRow {+ id: string;+ instanceId: string;+ pluginId: string;+ providerDeliveryId: string;+ route: string;+ // Retired to NULL once the dispatch outcome is recorded; only 'pending' rows still carry one.+ payload: string | Record<string, unknown> | null;+ payloadHash?: string | null;+ // Dispatch lifecycle (the AddIngressEventDispatchState migration). A restored 'pending' row must+ // keep these or the reconciler never replays it while the dedup row still blocks the provider's+ // retry. Optional because backups exported before the columns existed don't carry them.+ dispatchState?: 'pending' | 'dispatched' | 'failed' | null;+ dispatchAttempts?: number;+ lastDispatchAt?: string | null;+ sessionId: string | null;+ createdAt: string;+}++interface WebhookDeliveryFailureRow {+ id: string;+ webhookId: string;+ sessionId: string;+ event: string;+ url: string;+ idempotencyKey: string | null;+ deliveryId: string | null;+ attempts: number;+ lastStatusCode: number | null;+ lastError: string;+ createdAt: string;+}++interface IntegrationDeliveryFailureRow {+ id: string;+ direction: string;+ pluginId: string;+ instanceId: string;+ sessionId: string | null;+ deliveryId: string | null;+ attempts: number;+ lastError: string;+ payload: string | Record<string, unknown> | null;+ redriven: boolean | number;+ createdAt: string;+}++// status_updates has no FK to sessions (plain columns), so the import's `DELETE FROM sessions` never+// clears it — it must be exported + re-inserted explicitly like lid_mappings. postedAt/expiresAt are+// bigint epoch-ms: raw queries bypass the entity transformer, so Postgres returns them as strings.+interface StatusUpdateRow {+ id: string;+ sessionId: string;+ contactJid: string;+ contactName: string | null;+ contactPushName: string | null;+ waStatusId: string;+ type: string;+ caption: string | null;+ mediaPath: string | null;+ mediaMimetype: string | null;+ mediaOmitted: boolean | number;+ omitReason: string | null;+ backgroundColor: string | null;+ font: number | null;+ postedAt: number | string;+ expiresAt: number | string;+}++interface MigrationTables {+ sessions: SessionRow[];+ webhooks: WebhookRow[];+ messages: MessageRow[];+ messageBatches: MessageBatchRow[];+ templates: TemplateRow[];+ baileysStoredMessages: BaileysStoredMessageRow[];+ lidMappings: LidMappingRow[];+ pluginInstances: PluginInstanceRow[];+ conversationMappings: ConversationMappingRow[];+ ingressEvents: IngressEventRow[];+ webhookDeliveryFailures: WebhookDeliveryFailureRow[];+ integrationDeliveryFailures: IntegrationDeliveryFailureRow[];+ statusUpdates: StatusUpdateRow[];+}++type TableCounts = { [K in keyof MigrationTables]: number };++// A per-table restore step for importData: which backup key to read, the exact INSERT text (kept in+// Postgres' `$N` placeholder form; the insert() helper rewrites it for SQLite), the param mapping,+// and an optional per-row skip guard. key/label/id also drive the counts object and the failure+// warnings, so the import loop below stays table-agnostic.+interface TableImporter<K extends keyof MigrationTables = keyof MigrationTables> {+ key: K;+ /** Singular noun used in the per-row failure warning: `Failed to import <label> <id>: <err>`. */+ label: string;+ /** Full INSERT ... VALUES ($1, ...) text, verbatim per table. */+ sql: string;+ /** The id interpolated into the failure warning (lid_mappings rows key on lid, not id). */+ id: (row: MigrationTables[K][number]) => string;+ map: (row: MigrationTables[K][number]) => unknown[];+ /** Per-row veto: returns the warning to record (the row is skipped) or null to import the row. */+ skip?: (row: MigrationTables[K][number]) => string | null;+}++// Registers one concrete descriptor into the union-keyed TABLE_IMPORTERS array. The return type+// widens the row-specific id/map/skip to the union of all row types; sound because the import loop+// only ever feeds a descriptor rows read from data.tables[its own key].+function defineTableImporter<K extends keyof MigrationTables>(importer: TableImporter<K>): TableImporter {+ return importer;+}++// Restore order is FK order: sessions first (webhooks/messages/templates/etc. reference it), the+// standalone cache/DLQ tables after. The per-block comments from the former inline import blocks+// live on their descriptor entries.+const TABLE_IMPORTERS: TableImporter[] = [+ // Import sessions first+ defineTableImporter({+ key: 'sessions',+ label: 'session',+ sql: `INSERT INTO sessions (id, name, status, phone, "pushName", config, "proxyUrl", "proxyType", "connectedAt", "lastActiveAt", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,+ id: (session: SessionRow) => session.id,+ // A session name becomes the engine auth-directory key, so an unvalidated imported name (this+ // path bypasses CreateSessionDto) could traverse the filesystem. Skip + warn instead of+ // throwing, so one bad row doesn't 500 the whole restore.+ skip: (session: SessionRow) => {+ if (isSafeSessionName(session.name)) return null;+ return `Skipped session ${session.id}: unsafe name ${JSON.stringify(session.name)}`;+ },+ map: (session: SessionRow) => [+ session.id,+ session.name,+ session.status,+ session.phone,+ session.pushName,+ typeof session.config === 'string' ? session.config : JSON.stringify(session.config || {}),+ session.proxyUrl,+ session.proxyType,+ session.connectedAt,+ session.lastActiveAt,+ session.createdAt,+ session.updatedAt,+ ],+ }),++ // Import webhooks+ defineTableImporter({+ key: 'webhooks',+ label: 'webhook',+ sql: `INSERT INTO webhooks (id, "sessionId", url, events, secret, headers, filters, active, "retryCount", "lastTriggeredAt", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,+ id: (webhook: WebhookRow) => webhook.id,+ map: (webhook: WebhookRow) => [+ webhook.id,+ webhook.sessionId,+ webhook.url,+ typeof webhook.events === 'string' ? webhook.events : JSON.stringify(webhook.events || []),+ webhook.secret,+ typeof webhook.headers === 'string' ? webhook.headers : JSON.stringify(webhook.headers || {}),+ webhook.filters == null+ ? null+ : typeof webhook.filters === 'string'+ ? webhook.filters+ : JSON.stringify(webhook.filters),+ webhook.active,+ webhook.retryCount,+ webhook.lastTriggeredAt,+ webhook.createdAt,+ webhook.updatedAt,+ ],+ }),++ // Import messages (optional)+ defineTableImporter({+ key: 'messages',+ label: 'message',+ sql: `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", author, "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,+ id: (msg: MessageRow) => msg.id,+ map: (msg: MessageRow) => [+ msg.id,+ msg.sessionId,+ msg.waMessageId ?? null,+ msg.chatId,+ msg.chatName ?? null,+ // Rows exported before the author column existed simply restore to NULL (legacy+ // behavior) instead of failing the whole import on an unknown key.+ msg.author ?? null,+ msg.from,+ msg.to,+ msg.body ?? null,+ msg.type,+ msg.direction,+ msg.timestamp ?? null,+ msg.metadata == null ? null : typeof msg.metadata === 'string' ? msg.metadata : JSON.stringify(msg.metadata),+ msg.status,+ msg.createdAt,+ ],+ }),++ // Import message batches (optional)+ defineTableImporter({+ key: 'messageBatches',+ label: 'message batch',+ sql: `INSERT INTO message_batches (id, batch_id, session_id, status, messages, options, progress, results, current_index, created_at, updated_at, started_at, completed_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,+ id: (batch: MessageBatchRow) => batch.id,+ map: (batch: MessageBatchRow) => [+ batch.id,+ batch.batch_id,+ batch.session_id,+ batch.status,+ typeof batch.messages === 'string' ? batch.messages : JSON.stringify(batch.messages ?? []),+ batch.options == null ? null : typeof batch.options === 'string' ? batch.options : JSON.stringify(batch.options),+ batch.progress == null+ ? null+ : typeof batch.progress === 'string'+ ? batch.progress+ : JSON.stringify(batch.progress),+ batch.results == null ? null : typeof batch.results === 'string' ? batch.results : JSON.stringify(batch.results),+ batch.current_index,+ batch.created_at,+ batch.updated_at,+ batch.started_at,+ batch.completed_at,+ ],+ }),++ // Import templates (optional; FK -> sessions, restored above)+ defineTableImporter({+ key: 'templates',+ label: 'template',+ sql: `INSERT INTO templates (id, "sessionId", name, body, header, footer, "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ id: (tpl: TemplateRow) => tpl.id,+ map: (tpl: TemplateRow) => [+ tpl.id,+ tpl.sessionId,+ tpl.name,+ tpl.body,+ tpl.header ?? null,+ tpl.footer ?? null,+ tpl.createdAt,+ tpl.updatedAt,+ ],+ }),++ // Import baileys stored messages (optional; FK -> sessions, restored above)+ defineTableImporter({+ key: 'baileysStoredMessages',+ label: 'baileys stored message',+ sql: `INSERT INTO baileys_stored_messages (id, "sessionId", "waMessageId", "serializedMessage", "createdAt")+ VALUES ($1, $2, $3, $4, $5)`,+ id: (bsm: BaileysStoredMessageRow) => bsm.id,+ map: (bsm: BaileysStoredMessageRow) => [+ bsm.id,+ bsm.sessionId,+ bsm.waMessageId,+ bsm.serializedMessage,+ bsm.createdAt,+ ],+ }),++ // Import lid mappings (optional; not a FK, restored as a standalone cache table)+ defineTableImporter({+ key: 'lidMappings',+ label: 'lid mapping',+ sql: `INSERT INTO lid_mappings (lid, phone, "sessionId", "updatedAt") VALUES ($1, $2, $3, $4)`,+ id: (lm: LidMappingRow) => lm.lid,+ map: (lm: LidMappingRow) => [lm.lid, lm.phone ?? null, lm.sessionId ?? null, lm.updatedAt],+ }),++ // Import plugin instances (Integration Fabric config + ingress HMAC secret)+ defineTableImporter({+ key: 'pluginInstances',+ label: 'plugin instance',+ sql: `INSERT INTO plugin_instances (id, "pluginId", "instanceId", "sessionScope", secret, "verifyToken", config, enabled, "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,+ id: (pi: PluginInstanceRow) => pi.id,+ map: (pi: PluginInstanceRow) => [+ pi.id,+ pi.pluginId,+ pi.instanceId,+ pi.sessionScope,+ pi.secret,+ pi.verifyToken,+ pi.config == null ? null : typeof pi.config === 'string' ? pi.config : JSON.stringify(pi.config),+ pi.enabled,+ pi.createdAt,+ pi.updatedAt,+ ],+ }),++ // Import conversation mappings (handover state; sessionId is non-FK provenance)+ defineTableImporter({+ key: 'conversationMappings',+ label: 'conversation mapping',+ sql: `INSERT INTO conversation_mappings (id, "sessionId", "chatId", "pluginId", "instanceId", "providerConversationId", "handoverState", metadata, "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,+ id: (cm: ConversationMappingRow) => cm.id,+ map: (cm: ConversationMappingRow) => [+ cm.id,+ cm.sessionId,+ cm.chatId,+ cm.pluginId,+ cm.instanceId,+ cm.providerConversationId,+ cm.handoverState,+ cm.metadata == null ? null : typeof cm.metadata === 'string' ? cm.metadata : JSON.stringify(cm.metadata),+ cm.updatedAt,+ ],+ }),++ // Import ingress events (durable inbound dedup oracle; payload is JSON). The dispatch-lifecycle+ // columns ride along: dropping them would strand a restored 'pending' row (NULL dispatchState is+ // never swept by the reconciler) while its dedup key still blocks the provider's retry. Columns+ // absent from a pre-lifecycle backup import as NULL/0 — the same "not watched" reading legacy+ // rows have by design. dispatchAttempts is NOT NULL, so it coalesces to 0 rather than NULL.+ defineTableImporter({+ key: 'ingressEvents',+ label: 'ingress event',+ sql: `INSERT INTO ingress_events (id, "instanceId", "pluginId", "providerDeliveryId", route, payload, "payloadHash", "sessionId", "dispatchState", "dispatchAttempts", "lastDispatchAt", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,+ id: (ie: IngressEventRow) => ie.id,+ map: (ie: IngressEventRow) => [+ ie.id,+ ie.instanceId,+ ie.pluginId,+ ie.providerDeliveryId,+ ie.route,+ // A retired (NULL) payload must stay NULL — re-materializing it as '{}' would make a+ // slimmed dedup row read as a pending event with an empty body.+ ie.payload == null ? null : typeof ie.payload === 'string' ? ie.payload : JSON.stringify(ie.payload),+ ie.payloadHash ?? null,+ ie.sessionId,+ ie.dispatchState ?? null,+ ie.dispatchAttempts ?? 0,+ ie.lastDispatchAt ?? null,+ ie.createdAt,+ ],+ }),++ // Import webhook delivery failures (webhook DLQ)+ defineTableImporter({+ key: 'webhookDeliveryFailures',+ label: 'webhook delivery failure',+ sql: `INSERT INTO webhook_delivery_failures (id, "webhookId", "sessionId", event, url, "idempotencyKey", "deliveryId", attempts, "lastStatusCode", "lastError", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ id: (wf: WebhookDeliveryFailureRow) => wf.id,+ map: (wf: WebhookDeliveryFailureRow) => [+ wf.id,+ wf.webhookId,+ wf.sessionId,+ wf.event,+ wf.url,+ wf.idempotencyKey,+ wf.deliveryId,+ wf.attempts,+ wf.lastStatusCode,+ wf.lastError,+ wf.createdAt,+ ],+ }),++ // Import integration delivery failures (inbound + outbound DLQ)+ defineTableImporter({+ key: 'integrationDeliveryFailures',+ label: 'integration delivery failure',+ sql: `INSERT INTO integration_delivery_failures (id, direction, "pluginId", "instanceId", "sessionId", "deliveryId", attempts, "lastError", payload, redriven, "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ id: (df: IntegrationDeliveryFailureRow) => df.id,+ map: (df: IntegrationDeliveryFailureRow) => [+ df.id,+ df.direction,+ df.pluginId,+ df.instanceId,+ df.sessionId,+ df.deliveryId,+ df.attempts,+ df.lastError,+ df.payload == null ? null : typeof df.payload === 'string' ? df.payload : JSON.stringify(df.payload),+ df.redriven,+ df.createdAt,+ ],+ }),++ // Import status updates (24h-TTL status/story store; sessionId is non-FK provenance)+ defineTableImporter({+ key: 'statusUpdates',+ label: 'status update',+ sql: `INSERT INTO status_updates (id, "sessionId", "contactJid", "contactName", "contactPushName", "waStatusId", type, caption, "mediaPath", "mediaMimetype", "mediaOmitted", "omitReason", "backgroundColor", font, "postedAt", "expiresAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)`,+ id: (su: StatusUpdateRow) => su.id,+ map: (su: StatusUpdateRow) => [+ su.id,+ su.sessionId,+ su.contactJid,+ su.contactName ?? null,+ su.contactPushName ?? null,+ su.waStatusId,+ su.type,+ su.caption ?? null,+ su.mediaPath ?? null,+ su.mediaMimetype ?? null,+ su.mediaOmitted ?? false,+ su.omitReason ?? null,+ su.backgroundColor ?? null,+ su.font ?? null,+ su.postedAt,+ su.expiresAt,+ ],+ }),+];++@ApiTags('infrastructure')+@Controller('infra')+// Every route here is deployment-global (data export/import, infra config, service orchestration),+// so the guard's route-param session fence can never bite. Reject session-scoped keys outright at+// class level, which also covers routes added later. @Public routes are unaffected: the guard+// returns before it reads this metadata.+@RequireUnscopedKey()+export class InfraDataController {+ private readonly logger = createLogger('InfraDataController');++ constructor(+ private readonly configService: ConfigService,+ @InjectDataSource('data')+ private readonly dataDataSource: DataSource,+ // Best-effort audit emission for the sensitive infra operations below. Injected @Optional and+ // grouped with the trailing @Optional args so it never shifts the required positional args: the+ // running app always provides the @Global AuditService, while the direct-construction unit tests+ // omit it — the `?.` at each call site then makes emission a no-op there instead of forcing+ // every test to wire a mock.+ @Optional()+ private readonly auditService?: AuditService,+ // Post-import runtime reconciliation (see importData). Same trailing-@Optional convention as+ // auditService: provided by the app (InfraModule imports SessionModule; EngineModule is @Global),+ // omitted by direct-construction unit tests, and every use is `?.`-guarded.+ @Optional()+ private readonly sessionService?: SessionService,+ @Optional()+ private readonly lidMappingStore?: LidMappingStoreService,+ ) {}++ @Get('export-data')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Export all data from Data DB for migration' })+ @ApiResponse({ status: 200, description: 'Exported data as JSON' })+ async exportData(): Promise<{+ exportedAt: string;+ dataDbType: string;+ tables: MigrationTables;+ counts: {+ sessions: number;+ webhooks: number;+ messages: number;+ messageBatches: number;+ templates: number;+ baileysStoredMessages: number;+ lidMappings: number;+ pluginInstances: number;+ conversationMappings: number;+ ingressEvents: number;+ webhookDeliveryFailures: number;+ integrationDeliveryFailures: number;+ statusUpdates: number;+ };+ /** Optional tables that were skipped because they genuinely do not exist in this DB (older schema). */+ skippedTables: string[];+ }> {+ // Get all entities from Data DB+ const sessions = await this.dataDataSource.query<SessionRow[]>('SELECT * FROM sessions');+ const webhooks = await this.dataDataSource.query<WebhookRow[]>('SELECT * FROM webhooks');++ // The tables below may legitimately not exist yet (created by migrations an older DB has not run).+ // Only a GENUINE missing-table error (isMissingTableError) may be tolerated — anything else (lock,+ // I/O, timeout, aborted connection) must FAIL the export. The old blind `catch { debug-log }`+ // pattern reported those as "table is empty", producing a 200 "complete" backup that was actually+ // partial — which the import then treated as authoritative and DELETEd the missing tables' rows.+ // A skipped table is surfaced in `skippedTables` (and logged as a warning) so an operator can tell+ // "not migrated yet" apart from "exported empty".+ const skippedTables: string[] = [];+ const queryOptionalTable = async <T>(table: string): Promise<T[]> => {+ try {+ return await this.dataDataSource.query<T[]>(`SELECT * FROM ${table}`);+ } catch (error) {+ if (!isMissingTableError(error)) throw error;+ skippedTables.push(table);+ this.logger.warn('Optional table does not exist in this DB; exporting without it', { table });+ return [];+ }+ };++ const messages = await queryOptionalTable<MessageRow>('messages');+ // Postgres carries a STORED generated tsvector column `body_ts` (FTS) that `SELECT *` picks up.+ // It is a server-maintained index artifact, not payload: strip it so backups stay dialect-neutral+ // (and small). The import's explicit column list already ignores it in older archives.+ for (const row of messages) {+ delete row.body_ts;+ }+ const messageBatches = await queryOptionalTable<MessageBatchRow>('message_batches');+ const templates = await queryOptionalTable<TemplateRow>('templates');+ const baileysStoredMessages = await queryOptionalTable<BaileysStoredMessageRow>('baileys_stored_messages');+ const lidMappings = await queryOptionalTable<LidMappingRow>('lid_mappings');+ // Integration Fabric + both DLQs were added after the original migration set; tolerate a genuinely+ // absent table (older DB) like the tables above rather than 500-ing the whole export.+ const pluginInstances = await queryOptionalTable<PluginInstanceRow>('plugin_instances');+ const conversationMappings = await queryOptionalTable<ConversationMappingRow>('conversation_mappings');+ const ingressEvents = await queryOptionalTable<IngressEventRow>('ingress_events');+ const webhookDeliveryFailures = await queryOptionalTable<WebhookDeliveryFailureRow>('webhook_delivery_failures');+ const integrationDeliveryFailures = await queryOptionalTable<IntegrationDeliveryFailureRow>(+ 'integration_delivery_failures',+ );+ const statusUpdates = await queryOptionalTable<StatusUpdateRow>('status_updates');++ const counts = {+ sessions: sessions.length,+ webhooks: webhooks.length,+ messages: messages.length,+ messageBatches: messageBatches.length,+ templates: templates.length,+ baileysStoredMessages: baileysStoredMessages.length,+ lidMappings: lidMappings.length,+ pluginInstances: pluginInstances.length,+ conversationMappings: conversationMappings.length,+ ingressEvents: ingressEvents.length,+ webhookDeliveryFailures: webhookDeliveryFailures.length,+ integrationDeliveryFailures: integrationDeliveryFailures.length,+ statusUpdates: statusUpdates.length,+ };++ // Audit the full-DB export: this payload carries webhook + plugin-instance secrets, so WHO pulled+ // a dump (and the per-table row counts) is exactly the trail C002 was missing. Data itself is never+ // logged — only counts.+ await this.auditService?.logInfo(AuditAction.INFRA_DATA_EXPORTED, { metadata: { counts } });++ return {+ exportedAt: new Date().toISOString(),+ dataDbType: this.configService.get<string>('dataDatabase.type', 'sqlite'),+ tables: {+ sessions,+ webhooks,+ messages,+ messageBatches,+ templates,+ baileysStoredMessages,+ lidMappings,+ pluginInstances,+ conversationMappings,+ ingressEvents,+ webhookDeliveryFailures,+ integrationDeliveryFailures,+ statusUpdates,+ },+ counts,+ skippedTables,+ };+ }++ @Post('import-data')+ @HttpCode(HttpStatus.OK)+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Import data to Data DB (replaces existing data)' })+ @ApiBody({+ description: 'Exported data from export-data endpoint',+ schema: {+ type: 'object',+ properties: {+ force: {+ type: 'boolean',+ description:+ 'Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead.',+ },+ stopOrphans: {+ type: 'boolean',+ description:+ 'Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path.',+ },+ tables: {+ type: 'object',+ properties: {+ sessions: { type: 'array' },+ webhooks: { type: 'array' },+ messages: { type: 'array' },+ messageBatches: { type: 'array' },+ statusUpdates: { type: 'array' },+ },+ },+ },+ },+ })+ @ApiResponse({ status: 200, description: 'Data imported successfully' })+ @ApiResponse({+ status: 409,+ description:+ 'Refused: live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)',+ })+ async importData(+ @Body()+ data: {+ tables: Partial<MigrationTables>;+ force?: boolean;+ /**+ * Stop the running engines for sessions the backup does not contain, inside this request and+ * before the replace runs (best-effort, time-bounded per engine). Supersedes force=true for the+ * orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so+ * restartRequired stays false on the success path. Without it the pre-existing behavior holds —+ * refuse with 409, or proceed with force=true and leave the engines running until restart.+ */+ stopOrphans?: boolean;+ },+ ): Promise<{+ imported: boolean;+ counts: TableCounts;+ warnings: string[];+ /**+ * Non-fatal operator-facing messages (e.g. orphan-engine reconciliation details). Distinct from+ * warnings: notices never cause a rollback, while warnings make the replace-rollback gate fire.+ */+ notices: string[];+ /** True when live engines were left pointing at sessions this restore removed — restart to stop them. */+ restartRequired: boolean;+ /** Session ids with a running engine that the restored data no longer contains. */+ orphanedEngines: string[];+ /** Orphan engines stopped inside this request (only populated when stopOrphans=true was passed). */+ stoppedOrphanEngines: string[];+ /** Orphan engines whose teardown threw or timed out (Map reconciled regardless; investigate). */+ failedOrphanEngines: string[];+ }> {+ const warnings: string[] = [];++ // Runtime reconciliation, part 1 (pre-flight): the replace below DELETES every session not in the+ // backup, but an engine started for such a session keeps running as an unstoppable zombie (the+ // session service keys engines by session id, and every stop path goes through the now-missing DB+ // row) whose inbound messages land in tables that were just replaced. Three operator-chosen paths:+ // - default: refuse with 409 listing the orphan ids;+ // - force=true: proceed and leave the engines running until process restart (restartRequired=true);+ // - stopOrphans=true: stop each orphan engine inside this request (best-effort, time-bounded,+ // isolated per engine) and then proceed — restartRequired stays false on the success path.+ // stopOrphans is preferred over force for the orphan case: a force restore that silently leaves+ // engines writing into the freshly replaced tables for an unbounded time is the corruption this+ // gate exists to prevent, so the explicit-stop path closes that window instead of relying on the+ // operator to restart promptly.+ const importedSessionIds = new Set((data.tables.sessions ?? []).map(s => s.id));+ const orphanedEngines = (this.sessionService?.getActiveSessionIds() ?? []).filter(+ id => !importedSessionIds.has(id),+ );++ let stoppedOrphanEngines: string[] = [];+ let failedOrphanEngines: string[] = [];+ let restartRequired = false;++ // notices collect non-fatal operator-facing messages (orphan-engine reconciliation details) that+ // must NOT trip the warnings→rollback gate further down. warnings is reserved for per-row import+ // failures that make the replace partial and therefore require a rollback.+ const notices: string[] = [];++ if (orphanedEngines.length > 0 && data.stopOrphans && this.sessionService) {+ // Stop the orphans inside this request, BEFORE the transaction opens. destroyEngineSafely's+ // per-engine 10s deadline bounds the worst case (a stuck Chromium cannot wedge the import); the+ // engines are reconciled from the Map regardless of teardown outcome.+ const result = await this.sessionService.stopOrphanEngines(orphanedEngines);+ stoppedOrphanEngines = result.stopped;+ failedOrphanEngines = result.failed;+ if (failedOrphanEngines.length > 0) {+ // Teardown failed for at least one orphan. The Map entry is removed regardless (see+ // stopOrphanEngines), so the engine no longer holds a concurrency slot — but its underlying+ // Chromium/socket may still be alive and writing into restored tables. Surface the ids and+ // flag restartRequired so the operator does not read a clean response as "engines stopped".+ restartRequired = true;+ notices.push(+ `Teardown failed for ${failedOrphanEngines.length} orphan engine(s): ${failedOrphanEngines.join(', ')} ` ++ `(removed from the engine registry; a process restart guarantees cleanup).`,+ );+ }+ // Engines still mid-initialization (no Map entry yet) are reported in notRunning: their start()+ // self-aborts via the stop mark, but they are not counted as stopped here.+ if (result.notRunning.length > 0) {+ notices.push(+ `${result.notRunning.length} orphan session(s) had no live engine yet (still initializing): ` ++ `${result.notRunning.join(', ')} — their start() will self-abort.`,+ );+ }+ } else if (orphanedEngines.length > 0 && !data.force) {+ throw new ConflictException(+ `Import would orphan ${orphanedEngines.length} running engine(s) for session(s) ` ++ `${orphanedEngines.join(', ')} that the backup does not contain. Stop them first, retry with ` ++ `stopOrphans=true (stops them inside this request), or retry with force=true ` ++ `(a server restart is then required to stop the orphaned engines).`,+ );+ } else if (orphanedEngines.length > 0 && data.force) {+ // Legacy escape hatch: proceed and leave the engines running until restart.+ restartRequired = true;+ }++ // What the rollback branches below must report about the engines. The transaction can be rolled+ // back; the orphan teardown above CANNOT — it ran before the transaction opened and those engines+ // are already destroyed. Reporting empty arrays there would tell an operator nothing happened+ // while their sessions are down.+ //+ // restartRequired narrows to the one thing a rollback cannot undo: a FAILED teardown may have left+ // a Chromium/socket alive. The two other pre-flight outcomes do not survive the rollback as+ // restart-worthy — a cleanly stopped orphan leaves its session row intact (restart it through+ // POST /sessions/:id/start), and an engine the force path left running was never orphaned after+ // all, because the data it would have been orphaned by is gone.+ const engineStateAfterRollback = {+ restartRequired: failedOrphanEngines.length > 0,+ orphanedEngines,+ stoppedOrphanEngines,+ failedOrphanEngines,+ };++ const queryRunner = this.dataDataSource.createQueryRunner();+ await queryRunner.connect();+ await queryRunner.startTransaction();++ try {+ // Clear existing data (in correct order due to foreign keys). templates and+ // baileys_stored_messages FK sessions ON DELETE CASCADE, so the sessions DELETE would clear+ // them too; clearing them explicitly first keeps the order correct on engines where the+ // cascade is not enforced. Tolerate a genuinely-absent table (isMissingTableError) but let any+ // OTHER failure (lock, I/O, aborted tx) propagate to the transaction rollback below — a blind+ // `.catch(() => {})` here could otherwise silently commit a MERGED (not replaced) restore on+ // SQLite, violating the endpoint's "replaces existing data" contract.+ const clearTable = async (table: string): Promise<void> => {+ try {+ await queryRunner.query(`DELETE FROM ${table}`);+ } catch (err) {+ if (!isMissingTableError(err)) throw err;+ this.logger.debug('Skipped clearing a table that does not exist during import', { table });+ }+ };+ // The INSERTs below are written once, in Postgres' `$N` placeholder form. better-sqlite3 differs+ // from the legacy sqlite3 driver on raw queries in two ways: SQLite parses `$N` as a NAMED+ // parameter, which cannot be bound from the positional array TypeORM passes through (RangeError),+ // and strict binding rejects booleans/undefined — which a Postgres-made backup carries (real+ // booleans survive the JSON round-trip). Postgres needs `$N` and binds booleans natively, so both+ // rewrites apply only on the SQLite path. Safe: every `$N` below occurs once, in ascending order.+ const isPostgres = this.dataDataSource.options.type === 'postgres';+ const insert = (text: string, params: unknown[]): Promise<unknown> =>+ queryRunner.query(+ isPostgres ? text : text.replace(/\$\d+/g, '?'),+ isPostgres ? params : params.map(v => (typeof v === 'boolean' ? Number(v) : (v ?? null))),+ );+ await queryRunner.query('DELETE FROM webhooks');+ await clearTable('messages');+ await clearTable('message_batches');+ await clearTable('templates');+ await clearTable('baileys_stored_messages');+ // lid_mappings is not a FK to sessions, so the sessions DELETE below won't clear it; clear it+ // explicitly so a restore replaces the cache rather than colliding on existing lid PKs.+ await clearTable('lid_mappings');+ // Integration Fabric + both DLQs: none carry an FK constraint to sessions (sessionId is provenance),+ // so clearing them here before the sessions DELETE keeps the replace-semantics complete.+ await clearTable('plugin_instances');+ await clearTable('conversation_mappings');+ await clearTable('ingress_events');+ await clearTable('webhook_delivery_failures');+ await clearTable('integration_delivery_failures');+ // status_updates has no FK to sessions; clear it explicitly so the replace is complete.+ await clearTable('status_updates');+ await queryRunner.query('DELETE FROM sessions');++ // Restore table by table in TABLE_IMPORTERS order (FK-safe: sessions first). The descriptors+ // carry each table's INSERT text, param mapping, and per-row skip guard; a missing or empty+ // table keeps its 0 count and contributes no warnings.+ const counts = Object.fromEntries(TABLE_IMPORTERS.map(importer => [importer.key, 0] as const)) as TableCounts;+ for (const importer of TABLE_IMPORTERS) {+ const rows = data.tables[importer.key];+ if (!rows?.length) continue;+ for (const row of rows) {+ const skipWarning = importer.skip?.(row);+ if (skipWarning != null) {+ warnings.push(skipWarning);+ continue;+ }+ try {+ await insert(importer.sql, importer.map(row));+ counts[importer.key]++;+ } catch (err) {+ warnings.push(`Failed to import ${importer.label} ${importer.id(row)}: ${err}`);+ }+ }+ }++ // "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if any+ // INSERT failed we must roll back (restoring the pre-import data) rather than commit a+ // half-wiped DB and report success. A partial restore reported as imported:true was how+ // message history could silently vanish on a SQLite->Postgres migration.+ if (warnings.length > 0) {+ await queryRunner.rollbackTransaction();+ return {+ imported: false,+ counts,+ warnings,+ notices,+ ...engineStateAfterRollback,+ };+ }++ // A wrong/empty/garbage backup file restores zero rows but the DELETE already ran — committing+ // would silently WIPE the database and report success. Refuse it and roll back instead. (#488 review)+ const totalRestored = Object.values(counts).reduce((sum, n) => sum + n, 0);+ if (totalRestored === 0) {+ await queryRunner.rollbackTransaction();+ return {+ imported: false,+ counts,+ warnings: ['Backup contained no rows to restore; refused to replace existing data. Check the file.'],+ notices,+ ...engineStateAfterRollback,+ };+ }++ await queryRunner.commitTransaction();++ // Runtime reconciliation, part 2 (post-commit): the in-memory lid->phone mirror was warmed from+ // the OLD lid_mappings rows and is write-through only, so the just-restored table would never+ // reach it — resolution would keep serving stale entries (and miss restored ones) until the next+ // process start. Reload from the new DB contents. Best-effort: a miss falls back to engine+ // re-resolution, so a reload failure degrades instead of failing the (already committed) import.+ await this.lidMappingStore?.reload();++ // Audit the destructive replace-all restore, only on the committed-success path (the rollback /+ // refused-empty branches above return without emitting, since no data actually changed). Any+ // warnings would have taken the rollback branch, so warnings.length is always 0 here — record+ // only the per-table counts.+ await this.auditService?.logInfo(AuditAction.INFRA_DATA_IMPORTED, { metadata: { counts } });++ // restartRequired was computed in the pre-flight: true only when orphans were left running+ // (force=true legacy path) or when stopOrphans teardown failed for at least one engine.+ return {+ imported: true,+ counts,+ warnings,+ notices,+ restartRequired,+ orphanedEngines,+ stoppedOrphanEngines,+ failedOrphanEngines,+ };+ } catch (error) {+ await queryRunner.rollbackTransaction();+ throw error;+ } finally {+ await queryRunner.release();+ }+ }+}diff --git a/src/modules/infra/infra-status.controller.spec.ts b/src/modules/infra/infra-status.controller.spec.tsnew file mode 100644index 000000000..4531fb0f9--- /dev/null+++ b/src/modules/infra/infra-status.controller.spec.ts@@ -0,0 +1,182 @@+// StorageService (imported transitively by the infra controllers) pulls in `archiver`+// v8, which is ESM-only and cannot be parsed by ts-jest. The controller logic+// under test never touches archiver, so a lightweight stub is sufficient.+jest.mock('archiver', () => ({ default: jest.fn() }));++// saveConfig writes the generated env via fs.writeFileSync and reads the existing file+// via fs.existsSync/readFileSync; mock those so tests assert produced content without+// touching the filesystem. existsSync defaults to false (no prior config).+jest.mock('fs', () => {+ const actual = jest.requireActual<typeof import('fs')>('fs');+ return {+ ...actual,+ writeFileSync: jest.fn(),+ // saveConfig now writes the generated env via writeSecretFile, which chmods 0600 — mock it+ // so the secret-hygiene path never touches the real filesystem.+ chmodSync: jest.fn(),+ existsSync: jest.fn().mockReturnValue(false),+ readFileSync: jest.fn().mockReturnValue(''),+ createReadStream: jest.fn(() => jest.requireActual<typeof import('stream')>('stream').Readable.from([])),+ };+});++import { InfraStatusController } from './infra-status.controller';++describe('InfraStatusController.getStatus DB health (active SELECT 1 probe, not just isInitialized)', () => {+ const build = (query: jest.Mock) => {+ // engine.type=baileys skips the wa-web-version registry fetch (no network in unit tests).+ const config = { get: (k: string, def?: unknown) => (k === 'engine.type' ? 'baileys' : def) };+ const ds = { isInitialized: true, query };+ const cache = { isAvailable: jest.fn().mockResolvedValue(false), refreshS3Availability: jest.fn() };+ return new InfraStatusController(+ config as never,+ ds as never,+ ds as never,+ { create: jest.fn() } as never,+ { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() } as never,+ cache as never,+ { refreshS3Availability: jest.fn() } as never,+ undefined as never,+ );+ };++ it('reports connected:true when SELECT 1 succeeds', async () => {+ const status = await build(jest.fn().mockResolvedValue([{ '1': 1 }])).getStatus();+ expect(status.database.connected).toBe(true);+ });++ it('reports connected:false when the DB is initialized but SELECT 1 fails (backend died post-init)', async () => {+ const status = await build(jest.fn().mockRejectedValue(new Error('ECONNRESET'))).getStatus();+ expect(status.database.connected).toBe(false);+ });+});++describe('InfraStatusController.getStatus queue job counts', () => {+ function buildStatusController(opts: { queueEnabled: boolean; queue?: { getJobCounts: jest.Mock } }) {+ const configService = {+ get: (key: string, def?: unknown) => (key === 'queue.enabled' ? opts.queueEnabled : def),+ };+ const dataSource = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) } as unknown;+ const engineFactory = { create: jest.fn() };+ const dockerService = { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() };+ const cacheService = { isAvailable: jest.fn().mockResolvedValue(false), refreshS3Availability: jest.fn() };+ const storageService = { refreshS3Availability: jest.fn() };+ return new InfraStatusController(+ configService as never,+ dataSource as never,+ dataSource as never,+ engineFactory as never,+ dockerService as never,+ cacheService as never,+ storageService as never,+ opts.queue as never,+ );+ }++ it('reports live webhook job counts when the queue is enabled (pending = wait+active+delayed)', async () => {+ const getJobCounts = jest.fn().mockResolvedValue({ wait: 2, active: 1, delayed: 3, completed: 10, failed: 1 });+ const controller = buildStatusController({ queueEnabled: true, queue: { getJobCounts } });++ const status = await controller.getStatus();++ expect(getJobCounts).toHaveBeenCalledWith('wait', 'active', 'delayed', 'completed', 'failed');+ expect(status.queue).toEqual({ enabled: true, webhooks: { pending: 6, completed: 10, failed: 1 } });+ });++ it('reports zeros (and does not touch the queue) when the queue is disabled', async () => {+ const getJobCounts = jest.fn();+ const controller = buildStatusController({ queueEnabled: false, queue: { getJobCounts } });++ const status = await controller.getStatus();++ expect(getJobCounts).not.toHaveBeenCalled();+ expect(status.queue).toEqual({ enabled: false, webhooks: { pending: 0, completed: 0, failed: 0 } });+ });+});++describe('InfraStatusController.getStatus engine (reads the real engine.puppeteer.* keys)', () => {+ // Pin the WA-Web version so getStatus does not fire the wa-version registry fetch (no network in tests).+ const savedWebVer = process.env.WWEBJS_WEB_VERSION;+ beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));+ afterAll(() => {+ if (savedWebVer === undefined) delete process.env.WWEBJS_WEB_VERSION;+ else process.env.WWEBJS_WEB_VERSION = savedWebVer;+ });++ it('reports the saved headless/browserArgs instead of stale defaults from non-existent flat keys', async () => {+ const map: Record<string, unknown> = {+ 'engine.type': 'whatsapp-web.js',+ 'engine.puppeteer.headless': false,+ 'engine.puppeteer.args': ['--foo', '--bar'],+ 'engine.sessionDataPath': './sess',+ };+ const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };+ const cache = { isAvailable: () => Promise.resolve(false) };+ const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };+ const controller = new InfraStatusController(+ config as never,+ ds as never,+ ds as never,+ {} as never, // engineFactory+ { isDockerAvailable: () => false } as never, // dockerService — no Docker in unit tests+ cache as never,+ { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never, // storageService+ );++ const status = await controller.getStatus();+ expect(status.engine.headless).toBe(false);+ expect(status.engine.browserArgs).toBe('--foo --bar');+ expect(status.engine.sessionDataPath).toBe('./sess');+ });+});++describe('InfraStatusController.getStatus storage (reads the real storage.localPath key)', () => {+ // Pin the WA-Web version so getStatus does not fire the wa-version registry fetch (no network in tests).+ const savedWebVer = process.env.WWEBJS_WEB_VERSION;+ beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));+ afterAll(() => {+ if (savedWebVer === undefined) delete process.env.WWEBJS_WEB_VERSION;+ else process.env.WWEBJS_WEB_VERSION = savedWebVer;+ });++ const buildController = (map: Record<string, unknown>) => {+ const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };+ const cache = { isAvailable: () => Promise.resolve(false) };+ const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };+ return new InfraStatusController(+ config as never,+ ds as never,+ ds as never,+ {} as never, // engineFactory+ { isDockerAvailable: () => false } as never, // dockerService — no Docker in unit tests+ cache as never,+ { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never, // storageService+ );+ };++ it('reports the configured storage.localPath, not the ./uploads fallback', async () => {+ // The bug: status read the non-existent `storage.path` key, so it always reported the+ // `./uploads` fallback instead of the real path StorageService uses (`storage.localPath`).+ const status = await buildController({+ 'storage.type': 'local',+ 'storage.localPath': '/srv/openwa/media',+ }).getStatus();+ expect(status.storage.path).toBe('/srv/openwa/media');+ });++ it('falls back to ./data/media (matching StorageService) when storage.localPath is unset', async () => {+ const status = await buildController({ 'storage.type': 'local' }).getStatus();+ expect(status.storage.path).toBe('./data/media');+ });++ it('reports the bucket in S3 mode so the active backend is visible', async () => {+ const status = await buildController({ 'storage.type': 's3', 'storage.s3.bucket': 'my-openwa-bucket' }).getStatus();+ expect(status.storage.type).toBe('s3');+ expect(status.storage.bucket).toBe('my-openwa-bucket');+ });++ it('omits bucket in local mode (no fabricated field)', async () => {+ const status = await buildController({ 'storage.type': 'local' }).getStatus();+ expect(status.storage.bucket).toBeUndefined();+ });+});diff --git a/src/modules/infra/infra-status.controller.ts b/src/modules/infra/infra-status.controller.tsnew file mode 100644index 000000000..03288efa1--- /dev/null+++ b/src/modules/infra/infra-status.controller.ts@@ -0,0 +1,250 @@+import { Controller, Get, Optional } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';+import { InjectQueue } from '@nestjs/bullmq';+import { Queue } from 'bullmq';+import { QUEUE_NAMES } from '../queue/queue-names';+import { ConfigService } from '@nestjs/config';+import { DataSource } from 'typeorm';+import { InjectDataSource } from '@nestjs/typeorm';+import { Public, RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { EngineFactory } from '../../engine/engine.factory';+import { getEffectiveWebVersionInfo, resolveCurrentWebVersion } from '../../engine/wa-web-version';+import { DockerService } from '../docker';+import { CacheService } from '../../common/cache/cache.service';+import { StorageService } from '../../common/storage/storage.service';+import { createLogger } from '../../common/services/logger.service';+import { readGeneratedEnv } from './generated-env';++interface InfraStatus {+ // `builtIn` reflects whether OpenWA's own bundled container is actually running and backing this+ // service (detected live from the labeled container), not merely the saved intent. Falls back to the+ // saved flag when Docker is unavailable. (#488)+ database: { connected: boolean; type: string; host: string; builtIn: boolean };+ redis: { enabled: boolean; connected: boolean; host: string; port: number; builtIn: boolean };+ queue: {+ enabled: boolean;+ webhooks: { pending: number; completed: number; failed: number };+ };+ storage: { type: 'local' | 's3'; path?: string; bucket?: string; builtIn: boolean; s3Available?: boolean };+ engine: {+ type: string;+ headless: boolean;+ sessionDataPath: string;+ browserArgs: string;+ // whatsapp-web.js only: the actual WhatsApp Web build in use (distinct from the library version),+ // and how it was chosen. Omitted for other engines (e.g. baileys). (#488)+ webVersion?: string | null;+ webVersionSource?: 'pinned' | 'auto' | 'native';+ };+}++@ApiTags('infrastructure')+@Controller('infra')+// Every route here is deployment-global (data export/import, infra config, service orchestration),+// so the guard's route-param session fence can never bite. Reject session-scoped keys outright at+// class level, which also covers routes added later. @Public routes are unaffected: the guard+// returns before it reads this metadata.+@RequireUnscopedKey()+export class InfraStatusController {+ private readonly logger = createLogger('InfraStatusController');++ constructor(+ private readonly configService: ConfigService,+ @InjectDataSource('main')+ private readonly mainDataSource: DataSource,+ @InjectDataSource('data')+ private readonly dataDataSource: DataSource,+ private readonly engineFactory: EngineFactory,+ private readonly dockerService: DockerService,+ private readonly cacheService: CacheService,+ private readonly storageService: StorageService,+ @Optional()+ @InjectQueue(QUEUE_NAMES.WEBHOOK)+ private readonly webhookQueue?: Queue,+ ) {}++ /** Bound the DB liveness probe so a hung connection can't stall the status read. */+ private static readonly DB_PROBE_TIMEOUT_MS = 3000;++ /**+ * Active DB liveness probe: run `SELECT 1`, not just read `DataSource.isInitialized`. A backend+ * (notably Postgres) that dies AFTER init keeps `isInitialized` true until an explicit `.destroy()`,+ * so the old check reported the tile green while the DB was actually down. Bounded by a short+ * timeout; any error or timeout resolves to `false`. Mirrors `/health/ready`'s authoritative probe.+ */+ private async probeDbConnected(ds: DataSource): Promise<boolean> {+ if (!ds.isInitialized) return false;+ let timer: NodeJS.Timeout | undefined;+ try {+ await Promise.race([+ ds.query('SELECT 1'),+ new Promise((_resolve, reject) => {+ timer = setTimeout(() => reject(new Error('db probe timeout')), InfraStatusController.DB_PROBE_TIMEOUT_MS);+ }),+ ]);+ return true;+ } catch {+ return false;+ } finally {+ if (timer) clearTimeout(timer);+ }+ }++ @Get('status')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Get infrastructure status' })+ @ApiResponse({ status: 200, description: 'Infrastructure status' })+ async getStatus(): Promise<InfraStatus> {+ // Active DB liveness probe (SELECT 1) on both connections in parallel — not just isInitialized,+ // which stays true after a Postgres backend dies until an explicit .destroy() (see probeDbConnected).+ const [mainDbConnected, dataDbConnected] = await Promise.all([+ this.probeDbConnected(this.mainDataSource),+ this.probeDbConnected(this.dataDataSource),+ ]);+ const dbConnected = mainDbConnected && dataDbConnected;+ const dbType = this.configService.get<string>('dataDatabase.type', 'sqlite');+ const dbHost = this.configService.get<string>('dataDatabase.host', 'localhost');++ const redisHost = process.env.REDIS_HOST || this.configService.get<string>('redis.host', 'localhost');+ const redisPort = parseInt(process.env.REDIS_PORT || '', 10) || this.configService.get<number>('redis.port', 6379);+ const redisEnabled = process.env.REDIS_ENABLED === 'true';+ const queueEnabled = this.configService.get<boolean>('queue.enabled', false);++ // Check actual Redis connectivity via CacheService+ const redisConnected = await this.cacheService.isAvailable();++ const storageType = this.configService.get<'local' | 's3'>('storage.type', 'local');+ // Read the key StorageService actually uses (`storage.localPath`, default `./data/media`).+ // The old `storage.path` key never existed, so status always reported the `./uploads` fallback.+ const storagePath = this.configService.get<string>('storage.localPath', './data/media');+ // In S3 mode the local path is unused; surface the bucket so the status panel shows the real+ // backend. `path` is kept (additive) so the dashboard's local-mode rendering is unchanged.+ const storageBucket = this.configService.get<string>('storage.s3.bucket');++ const engineType = this.configService.get<string>('engine.type', 'whatsapp-web.js');+ // whatsapp-web.js only: surface the actual WhatsApp Web build (not the library version) so the+ // dashboard shows which build is running. Trigger the auto-resolve so the panel is populated even+ // before a session starts; the result is cached, so this is a one-time fetch. (#488)+ let webVersion: string | null | undefined;+ let webVersionSource: 'pinned' | 'auto' | 'native' | undefined;+ if (engineType === 'whatsapp-web.js') {+ // Kick the auto-resolve but DON'T await it — /infra/status is polled frequently and the registry+ // fetch can take up to 5s on a firewalled host. Read whatever's cached now (null until the first+ // success); a later poll reflects the resolved build. (#488 review)+ if (getEffectiveWebVersionInfo().source === 'auto') {+ void resolveCurrentWebVersion().catch(() => undefined);+ }+ const info = getEffectiveWebVersionInfo();+ webVersion = info.version;+ webVersionSource = info.source;+ }+ // configuration.ts nests these under engine.puppeteer.{headless,args}; the old flat+ // engine.headless / engine.browserArgs keys never existed, so status always reported defaults.+ const engineHeadless = this.configService.get<boolean>('engine.puppeteer.headless', true) ?? true;+ const sessionDataPath = this.configService.get<string>('engine.sessionDataPath', './data/sessions');+ const browserArgs =+ this.configService.get<string[]>('engine.puppeteer.args')?.join(' ') || '--no-sandbox --disable-gpu';++ // Built-in detection: prefer the actually-running bundled container as truth (so a stopped/missing+ // container, or a host-pinned external host, reads as NOT built-in), and require the app to be+ // pointed at the bundled service. Fall back to the saved *_BUILTIN intent when Docker is+ // unreachable (bare-npm / socket-less) so the toggles don't spuriously flip off. (#488)+ const s3Endpoint = this.configService.get<string>('storage.s3.endpoint');+ const running = this.dockerService.isDockerAvailable()+ ? await this.dockerService.getRunningBuiltinServices()+ : null;+ const savedBuiltin = this.readSavedBuiltinFlags();+ const dbBuiltIn = running ? running.database && dbHost === 'postgres' : savedBuiltin.database;+ const redisBuiltIn = running ? running.cache && redisHost === 'redis' : savedBuiltin.cache;+ const storageBuiltIn = running ? running.storage && s3Endpoint === 'http://minio:9000' : savedBuiltin.storage;+ // Re-probe (throttled) so a MinIO/S3 that came up after boot is reflected, not latched unreachable.+ const s3Available = storageType === 's3' ? await this.storageService.refreshS3Availability() : undefined;++ // Live webhook-queue depth (the only real queue). pending = waiting + active + delayed. Degrades to+ // zeros when the queue is disabled or Redis is unreachable, so the panel never errors the status read.+ let webhooks = { pending: 0, completed: 0, failed: 0 };+ if (queueEnabled && this.webhookQueue) {+ try {+ const counts = await this.webhookQueue.getJobCounts('wait', 'active', 'delayed', 'completed', 'failed');+ webhooks = {+ pending: (counts.wait ?? 0) + (counts.active ?? 0) + (counts.delayed ?? 0),+ completed: counts.completed ?? 0,+ failed: counts.failed ?? 0,+ };+ } catch (error) {+ this.logger.warn('Failed to read webhook queue job counts', { error: String(error) });+ }+ }++ return {+ database: { connected: dbConnected, type: dbType, host: dbHost, builtIn: dbBuiltIn },+ redis: {+ enabled: redisEnabled,+ connected: redisConnected,+ host: redisHost,+ port: redisPort,+ builtIn: redisBuiltIn,+ },+ queue: {+ enabled: queueEnabled,+ webhooks,+ },+ storage: {+ type: storageType,+ path: storagePath,+ ...(storageType === 's3' && storageBucket ? { bucket: storageBucket } : {}),+ builtIn: storageBuiltIn,+ ...(storageType === 's3' ? { s3Available } : {}),+ },+ engine: {+ type: engineType,+ headless: engineHeadless,+ sessionDataPath,+ browserArgs,+ ...(engineType === 'whatsapp-web.js' ? { webVersion, webVersionSource } : {}),+ },+ };+ }++ /** Saved built-in intent flags from data/.env.generated — the fallback when Docker isn't reachable. */+ private readSavedBuiltinFlags(): { database: boolean; cache: boolean; storage: boolean } {+ try {+ const saved = readGeneratedEnv();+ return {+ database: saved.POSTGRES_BUILTIN === 'true',+ cache: saved.REDIS_BUILTIN === 'true',+ storage: saved.MINIO_BUILTIN === 'true',+ };+ } catch {+ return { database: false, cache: false, storage: false };+ }+ }++ @Get('engines')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Get available WhatsApp engines' })+ @ApiResponse({ status: 200, description: 'List of available engines' })+ getEngines(): Array<{ id: string; name: string; enabled: boolean; features: string[] }> {+ return this.engineFactory.getAvailableEngines();+ }++ @Get('engines/current')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Get current active engine' })+ @ApiResponse({ status: 200, description: 'Current engine info' })+ getCurrentEngine(): { engineType: string } {+ return { engineType: this.engineFactory.getCurrentEngine() };+ }++ @Get('health')+ @Public()+ @ApiOperation({ summary: 'Health check endpoint' })+ @ApiResponse({ status: 200, description: 'Server is healthy' })+ healthCheck(): { status: string; timestamp: string } {+ return {+ status: 'ok',+ timestamp: new Date().toISOString(),+ };+ }+}diff --git a/src/modules/infra/infra-storage.controller.spec.ts b/src/modules/infra/infra-storage.controller.spec.tsnew file mode 100644index 000000000..a41822d67--- /dev/null+++ b/src/modules/infra/infra-storage.controller.spec.ts@@ -0,0 +1,297 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { Readable } from 'stream';++// StorageService (imported transitively by the infra controllers) pulls in `archiver`+// v8, which is ESM-only and cannot be parsed by ts-jest. The controller logic+// under test never touches archiver, so a lightweight stub is sufficient.+jest.mock('archiver', () => ({ default: jest.fn() }));++// saveConfig writes the generated env via fs.writeFileSync and reads the existing file+// via fs.existsSync/readFileSync; mock those so tests assert produced content without+// touching the filesystem. existsSync defaults to false (no prior config).+jest.mock('fs', () => {+ const actual = jest.requireActual<typeof import('fs')>('fs');+ return {+ ...actual,+ writeFileSync: jest.fn(),+ // saveConfig now writes the generated env via writeSecretFile, which chmods 0600 — mock it+ // so the secret-hygiene path never touches the real filesystem.+ chmodSync: jest.fn(),+ existsSync: jest.fn().mockReturnValue(false),+ readFileSync: jest.fn().mockReturnValue(''),+ createReadStream: jest.fn(() => jest.requireActual<typeof import('stream')>('stream').Readable.from([])),+ };+});++import { BadRequestException } from '@nestjs/common';+import { InfraStorageController } from './infra-storage.controller';+import { AuditAction } from '../audit/entities/audit-log.entity';++describe('InfraStorageController.importStorage filePath validation (Vuln 3)', () => {+ function buildController(storage: Partial<{ importFromStream: jest.Mock; getCurrentStorageType: jest.Mock }>) {+ return new InfraStorageController(storage as never);+ }++ it('rejects a filePath that escapes the data directory before touching the filesystem', async () => {+ const storage = { importFromStream: jest.fn(), getCurrentStorageType: jest.fn(() => 'local') };+ const controller = buildController(storage);++ await expect(controller.importStorage({ filePath: '../../../../etc/passwd' })).rejects.toBeInstanceOf(+ BadRequestException,+ );+ expect(storage.importFromStream).not.toHaveBeenCalled();+ });++ it('guards and opens the same cwd-resolved path returned by storage export', async () => {+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');+ (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/export.tar.gz');+ (fs.createReadStream as jest.Mock).mockClear();+ const storage = {+ importFromStream: jest.fn().mockResolvedValue(3),+ getCurrentStorageType: jest.fn(() => 'local'),+ };+ try {+ const result = await buildController(storage).importStorage({ filePath: 'data/exports/export.tar.gz' });+ expect(fs.createReadStream).toHaveBeenCalledWith('/srv/openwa/data/exports/export.tar.gz');+ expect(storage.importFromStream).toHaveBeenCalledTimes(1);+ expect(result).toEqual({ imported: true, count: 3, storageType: 'local' });+ } finally {+ cwdSpy.mockRestore();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ }+ });+});++describe('InfraStorageController.exportStorage keeps the export import-able and sweeps it', () => {+ function buildController(storage: Partial<{ createExportStream: jest.Mock }>) {+ return new InfraStorageController(storage as never);+ }++ // fs.existsSync is globally mocked in this file, so probe the real filesystem via fs.promises.access.+ const exists = (p: string): Promise<boolean> =>+ fs.promises+ .access(p)+ .then(() => true)+ .catch(() => false);++ // Poll (don't sleep a fixed time) so the sweep assertion isn't flaky under CI load.+ const waitForGone = async (p: string, timeoutMs = 3000): Promise<void> => {+ const start = Date.now();+ while (await exists(p)) {+ if (Date.now() - start > timeoutMs) throw new Error(`file was not swept in time: ${p}`);+ await new Promise(resolve => setTimeout(resolve, 10));+ }+ };++ let cwdSpy: jest.SpyInstance | undefined;+ let cwd: string | undefined;++ afterEach(() => {+ cwdSpy?.mockRestore();+ if (cwd) fs.rmSync(cwd, { recursive: true, force: true });+ cwdSpy = undefined;+ cwd = undefined;+ delete process.env.STORAGE_EXPORT_TTL_MS;+ });++ it('writes under data/exports (so it stays import-able + survives restart) and TTL-sweeps it', async () => {+ cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-cwd-'));+ cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);+ process.env.STORAGE_EXPORT_TTL_MS = '30';+ const createExportStream = jest.fn().mockResolvedValue(Readable.from([Buffer.from('archive-bytes')]));+ const controller = buildController({ createExportStream });++ const result = await controller.exportStorage();++ // download is cwd-relative (no absolute host path leak) and stays under data/exports so the import+ // handler — which only accepts paths inside data/ — can still consume it.+ expect(path.isAbsolute(result.download)).toBe(false);+ expect(result.download.startsWith(path.join('data', 'exports'))).toBe(true);+ // Resolve against the (mocked) cwd to check on-disk existence; fs itself uses the real cwd.+ const abs = path.join(cwd, result.download);+ expect(await exists(abs)).toBe(true);++ await waitForGone(abs);+ expect(await exists(abs)).toBe(false);+ });+});++describe('InfraStorageController.sweepStaleExportArchives (boot orphan sweep)', () => {+ function buildController() {+ return new InfraStorageController({} 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('InfraStorageController storage stream failures surface as request errors, not process crashes', () => {+ it('importStorage maps an archive/stream failure to a 400 with the real reason', async () => {+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');+ (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/bad.tar.gz');+ try {+ const storage = {+ importFromStream: jest.fn().mockRejectedValue(new Error('incorrect header check')),+ getCurrentStorageType: () => 'local',+ };+ const controller = new InfraStorageController(storage as never);+ const err = await controller.importStorage({ filePath: 'data/exports/bad.tar.gz' }).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(BadRequestException);+ expect((err as BadRequestException).message).toContain('incorrect header check');+ } finally {+ cwdSpy.mockRestore();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ }+ });++ it('exportStorage rejects (and the process lives) when the export source stream errors', async () => {+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-export-err-'));+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);+ try {+ // pipe() never forwards source errors: without a listener on the source this would be an+ // unhandled 'error' event and kill the process instead of failing the request.+ const errStream = new Readable({+ read() {+ this.destroy(new Error('archive boom'));+ },+ });+ const storage = { createExportStream: jest.fn().mockResolvedValue(errStream) };+ const controller = new InfraStorageController(storage as never);+ await expect(controller.exportStorage()).rejects.toThrow(/archive boom/);+ } finally {+ cwdSpy.mockRestore();+ fs.rmSync(cwd, { recursive: true, force: true });+ }+ });+});++// C002: the infra module exposed sensitive ADMIN operations (credential config write, restart/Docker+// orchestration, full-DB + storage export/import) with no audit trail. Each now emits an AuditAction.+describe('InfraStorageController C002 audit trail (light-dependency handlers)', () => {+ const makeAudit = (): { logInfo: jest.Mock } => ({ logInfo: jest.fn().mockResolvedValue(null) });++ // Positional constructor: (storageService, auditService?). auditService is the last @Optional arg.+ const build = (+ audit: { logInfo: jest.Mock },+ overrides: Partial<{+ storageService: unknown;+ }> = {},+ ): InfraStorageController => new InfraStorageController((overrides.storageService ?? {}) as never, audit as never);++ it('importStorage emits INFRA_STORAGE_IMPORTED with the imported file count', async () => {+ const audit = makeAudit();+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');+ (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/x.tar.gz');+ try {+ const storageService = { importFromStream: jest.fn().mockResolvedValue(5), getCurrentStorageType: () => 'local' };+ await build(audit, { storageService }).importStorage({ filePath: 'data/exports/x.tar.gz' });+ const calls = audit.logInfo.mock.calls as Array<+ [AuditAction, { metadata: { count: number; storageType: string } }]+ >;+ expect(calls[0][0]).toBe(AuditAction.INFRA_STORAGE_IMPORTED);+ expect(calls[0][1].metadata).toEqual({ count: 5, storageType: 'local' });+ } finally {+ cwdSpy.mockRestore();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ }+ });++ it('exportStorage emits INFRA_STORAGE_EXPORTED', async () => {+ const audit = makeAudit();+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-audit-'));+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);+ process.env.STORAGE_EXPORT_TTL_MS = '30';+ try {+ const storageService = { createExportStream: jest.fn().mockResolvedValue(Readable.from([Buffer.from('x')])) };+ await build(audit, { storageService }).exportStorage();+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { download: string } }]>;+ expect(calls[0][0]).toBe(AuditAction.INFRA_STORAGE_EXPORTED);+ expect(typeof calls[0][1].metadata.download).toBe('string');+ } finally {+ cwdSpy.mockRestore();+ fs.rmSync(cwd, { recursive: true, force: true });+ delete process.env.STORAGE_EXPORT_TTL_MS;+ }+ });+});diff --git a/src/modules/infra/infra-storage.controller.ts b/src/modules/infra/infra-storage.controller.tsnew file mode 100644index 000000000..80e4af3af--- /dev/null+++ b/src/modules/infra/infra-storage.controller.ts@@ -0,0 +1,229 @@+import {+ Controller,+ Get,+ Post,+ Body,+ BadRequestException,+ HttpCode,+ HttpStatus,+ OnApplicationBootstrap,+ Optional,+} from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';+import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { isPathWithin } from '../../common/utils/path-safety';+import { StorageService } from '../../common/storage/storage.service';+import { createLogger } from '../../common/services/logger.service';+import { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';+import { ImportStorageDto } from './dto/import-storage.dto';+import * as fs from 'fs';+import * as path from 'path';+import { randomUUID } from 'crypto';++@ApiTags('infrastructure')+@Controller('infra')+// Every route here is deployment-global (data export/import, infra config, service orchestration),+// so the guard's route-param session fence can never bite. Reject session-scoped keys outright at+// class level, which also covers routes added later. @Public routes are unaffected: the guard+// returns before it reads this metadata.+@RequireUnscopedKey()+export class InfraStorageController implements OnApplicationBootstrap {+ private readonly logger = createLogger('InfraStorageController');++ constructor(+ private readonly storageService: StorageService,+ // Best-effort audit emission for the sensitive infra operations below. Injected @Optional and+ // appended last so it never shifts the existing positional args: the running app always provides+ // the @Global AuditService, while the direct-construction unit tests omit it — the `?.` at each+ // call site then makes emission a no-op there instead of forcing every test to wire a mock.+ @Optional()+ private readonly auditService?: AuditService,+ ) {}++ // 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 = InfraStorageController.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) });+ }+ }+ }++ // ============================================================================+ // STORAGE MIGRATION API+ // ============================================================================++ @Get('storage/files/count')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Get file count in current storage' })+ @ApiResponse({ status: 200, description: 'File count and size' })+ async getStorageFileCount(): Promise<{+ storageType: string;+ count: number;+ sizeBytes: number;+ sizeMB: string;+ }> {+ const { count, sizeBytes } = await this.storageService.getFileCount();+ return {+ storageType: this.storageService.getCurrentStorageType(),+ count,+ sizeBytes,+ sizeMB: (sizeBytes / 1024 / 1024).toFixed(2),+ };+ }++ @Get('storage/export')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Export all storage files as tar.gz' })+ @ApiResponse({ status: 200, description: 'Tar.gz archive stream' })+ async exportStorage(): Promise<{ message: string; download: string }> {+ // Note: In production, this would return a StreamableFile+ // For simplicity, we'll save to a temp file and return the path+ const stream = await this.storageService.createExportStream();+ // Keep the export INSIDE data/ (under data/exports/): the import handler only accepts paths under+ // data/, and the documented backend-migration flow re-imports this file AFTER a container restart,+ // so it must live on the persistent volume — the OS temp dir is wiped on restart. The original+ // unbounded-accumulation leak is addressed by the TTL sweep below + a collision-proof filename+ // (a per-call UUID), not by relocating off the volume.+ const exportDir = path.join(process.cwd(), 'data', 'exports');+ if (!fs.existsSync(exportDir)) {+ fs.mkdirSync(exportDir, { recursive: true });+ }+ const exportPath = path.join(exportDir, `storage-export-${Date.now()}-${randomUUID()}.tar.gz`);++ const writeStream = fs.createWriteStream(exportPath);+ stream.pipe(writeStream);++ await new Promise<void>((resolve, reject) => {+ writeStream.on('finish', resolve);+ writeStream.on('error', reject);+ // pipe() does NOT forward source errors: an archiver/gzip failure surfaces as an 'error' event on+ // the source stream, which without a listener crashes the process. Fail the request instead and+ // tear down the sink so its fd isn't held open waiting for a 'finish' that never comes.+ stream.on('error', (err: Error) => {+ writeStream.destroy();+ reject(err);+ });+ });++ // Sweep the throwaway archive so repeated exports don't accumulate on the data volume.+ const ttlRaw = Number.parseInt(process.env.STORAGE_EXPORT_TTL_MS ?? '', 10);+ const ttlMs = Number.isInteger(ttlRaw) && ttlRaw > 0 ? ttlRaw : 60 * 60 * 1000; // default 1h+ setTimeout(() => {+ fs.promises.unlink(exportPath).catch(() => undefined);+ }, ttlMs).unref();++ // cwd-relative rather than an absolute host path: doesn't leak the filesystem layout, and the+ // import round-trip still works because importStorage's existsSync/createReadStream resolve a+ // relative filePath against the same cwd this was made relative to.+ const download = path.relative(process.cwd(), exportPath);++ // Audit the bulk media-export (all stored files leave the box as one archive).+ await this.auditService?.logInfo(AuditAction.INFRA_STORAGE_EXPORTED, { metadata: { download } });++ return {+ message: 'Storage export completed',+ download,+ };+ }++ @Post('storage/import')+ @HttpCode(HttpStatus.OK)+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Import storage files from tar.gz' })+ @ApiBody({ description: 'Path to tar.gz file to import' })+ @ApiResponse({ status: 200, description: 'Import result' })+ async importStorage(+ @Body() body: ImportStorageDto,+ ): Promise<{ imported: boolean; count: number; storageType: string }> {+ const { filePath } = body;++ // `filePath` is fully caller-controlled. Restrict it to the app's data+ // directory so it cannot point at arbitrary files on the host. Resolve once against the+ // same cwd-relative base used by exportStorage, then use that exact path for both the guard+ // and the file sink.+ const dataDir = path.join(process.cwd(), 'data');+ const resolved = path.resolve(process.cwd(), filePath || '');+ if (!filePath || !isPathWithin(dataDir, resolved)) {+ throw new BadRequestException('filePath must reference a file inside the data directory');+ }++ if (!fs.existsSync(resolved)) {+ throw new BadRequestException(`File not found: ${filePath}`);+ }++ const readStream = fs.createReadStream(resolved);+ // importFromStream rejects on archive/gzip/read failures (its streams carry error listeners, so a+ // bad file fails the request instead of crashing the process on an unhandled 'error' event). The+ // failures that reach here are almost always a problem with the caller-supplied file (not a gzip,+ // not a tar, unreadable, over the resource caps), so surface them as a 400 with the real reason+ // rather than an opaque 500.+ let count: number;+ try {+ count = await this.storageService.importFromStream(readStream);+ } catch (error) {+ throw new BadRequestException(`Storage import failed: ${error instanceof Error ? error.message : String(error)}`);+ }+ const storageType = this.storageService.getCurrentStorageType();++ // Audit the bulk media-import (files written into the active storage backend).+ await this.auditService?.logInfo(AuditAction.INFRA_STORAGE_IMPORTED, {+ metadata: { count, storageType },+ });++ return {+ imported: true,+ count,+ storageType,+ };+ }+}diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsdeleted file mode 100644index 57404ca92..000000000--- a/src/modules/infra/infra.controller.spec.ts+++ /dev/null@@ -1,2784 +0,0 @@-import * as fs from 'fs';-import * as os from 'os';-import * as path from 'path';-import { Readable } from 'stream';-import { Reflector } from '@nestjs/core';-import { BadRequestException } from '@nestjs/common';--// StorageService (imported transitively by InfraController) pulls in `archiver`-// v8, which is ESM-only and cannot be parsed by ts-jest. The controller logic-// under test never touches archiver, so a lightweight stub is sufficient.-jest.mock('archiver', () => ({ default: jest.fn() }));--// saveConfig writes the generated env via fs.writeFileSync and reads the existing file-// via fs.existsSync/readFileSync; mock those so tests assert produced content without-// touching the filesystem. existsSync defaults to false (no prior config).-jest.mock('fs', () => {- const actual = jest.requireActual<typeof import('fs')>('fs');- return {- ...actual,- writeFileSync: jest.fn(),- // saveConfig now writes the generated env via writeSecretFile, which chmods 0600 — mock it- // so the secret-hygiene path never touches the real filesystem.- chmodSync: jest.fn(),- existsSync: jest.fn().mockReturnValue(false),- readFileSync: jest.fn().mockReturnValue(''),- createReadStream: jest.fn(() => jest.requireActual<typeof import('stream')>('stream').Readable.from([])),- };-});--import { DataSource, QueryFailedError } from 'typeorm';-import { ConflictException } from '@nestjs/common';-import { plainToInstance } from 'class-transformer';-import { validate } from 'class-validator';-import { InfraController } from './infra.controller';-import { SaveConfigDto } from './dto/save-config.dto';-import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';-import { Session, SessionStatus } from '../session/entities/session.entity';-import { Webhook } from '../webhook/entities/webhook.entity';-import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';-import { MessageBatch, BatchStatus } from '../message/entities/message-batch.entity';-import { Template } from '../template/entities/template.entity';-import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';-import { LidMapping } from '../../engine/identity/lid-mapping.entity';-import { PluginInstance } from '../integration/entities/plugin-instance.entity';-import { ConversationMapping } from '../integration/entities/conversation-mapping.entity';-import { IngressEvent } from '../integration/entities/ingress-event.entity';-import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';-import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';-import { StatusUpdate } from '../status-store/entities/status-update.entity';-import { AuditAction } from '../audit/entities/audit-log.entity';-import { recordOsEnvKeys } from '../../config/env-precedence';--describe('InfraController access control (Vuln 2)', () => {- const reflector = new Reflector();-- // Every mutating, data-exfiltration, and operational-read endpoint must require- // the ADMIN role so that a low-privilege (VIEWER/OPERATOR) API key cannot wipe- // data, read secrets, change config, restart, trigger storage import, or read- // infrastructure status / engine / storage details (#221 tightened the reads).- const adminOnly = [- 'getConfig', // GET /infra/config (returns saved config; secrets omitted but still ADMIN-only)- 'saveConfig', // PUT /infra/config- 'requestRestart', // POST /infra/restart- 'exportData', // GET /infra/export-data (exposes webhook secrets)- 'importData', // POST /infra/import-data (DELETEs all rows)- 'exportStorage', // GET /infra/storage/export- 'importStorage', // POST /infra/storage/import- 'getStatus', // GET /infra/status- 'getEngines', // GET /infra/engines- 'getCurrentEngine', // GET /infra/engines/current- 'getStorageFileCount', // GET /infra/storage/files/count- ] as const;-- it.each(adminOnly)('%s requires the ADMIN role', method => {- // The handler is only ever a lookup key for reflector metadata — it is never invoked, so there is- // no `this` to lose. unbound-method (tightened in typescript-eslint 8.65) cannot tell the two- // apart, and the cast below does not satisfy it either.- // eslint-disable-next-line @typescript-eslint/unbound-method- const handler = InfraController.prototype[method as keyof InfraController] as unknown as (- ...args: unknown[]- ) => unknown;- const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);- expect(role).toBe(ApiKeyRole.ADMIN);- });-});--describe('InfraController.importStorage filePath validation (Vuln 3)', () => {- function buildController(storage: Partial<{ importFromStream: jest.Mock; getCurrentStorageType: jest.Mock }>) {- return new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- storage as never,- {} as never,- );- }-- it('rejects a filePath that escapes the data directory before touching the filesystem', async () => {- const storage = { importFromStream: jest.fn(), getCurrentStorageType: jest.fn(() => 'local') };- const controller = buildController(storage);-- await expect(controller.importStorage({ filePath: '../../../../etc/passwd' })).rejects.toBeInstanceOf(- BadRequestException,- );- expect(storage.importFromStream).not.toHaveBeenCalled();- });-- it('guards and opens the same cwd-resolved path returned by storage export', async () => {- const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');- (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/export.tar.gz');- (fs.createReadStream as jest.Mock).mockClear();- const storage = {- importFromStream: jest.fn().mockResolvedValue(3),- getCurrentStorageType: jest.fn(() => 'local'),- };- try {- const result = await buildController(storage).importStorage({ filePath: 'data/exports/export.tar.gz' });- expect(fs.createReadStream).toHaveBeenCalledWith('/srv/openwa/data/exports/export.tar.gz');- expect(storage.importFromStream).toHaveBeenCalledTimes(1);- expect(result).toEqual({ imported: true, count: 3, storageType: 'local' });- } finally {- cwdSpy.mockRestore();- (fs.existsSync as jest.Mock).mockReturnValue(false);- }- });-});--describe('InfraController.getStatus DB health (active SELECT 1 probe, not just isInitialized)', () => {- const build = (query: jest.Mock) => {- // engine.type=baileys skips the wa-web-version registry fetch (no network in unit tests).- const config = { get: (k: string, def?: unknown) => (k === 'engine.type' ? 'baileys' : def) };- const ds = { isInitialized: true, query };- const cache = { isAvailable: jest.fn().mockResolvedValue(false), refreshS3Availability: jest.fn() };- return new InfraController(- config as never,- ds as never,- ds as never,- { create: jest.fn() } as never,- { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() } as never,- cache as never,- { refreshS3Availability: jest.fn() } as never,- {} as never,- undefined as never,- );- };-- it('reports connected:true when SELECT 1 succeeds', async () => {- const status = await build(jest.fn().mockResolvedValue([{ '1': 1 }])).getStatus();- expect(status.database.connected).toBe(true);- });-- it('reports connected:false when the DB is initialized but SELECT 1 fails (backend died post-init)', async () => {- const status = await build(jest.fn().mockRejectedValue(new Error('ECONNRESET'))).getStatus();- expect(status.database.connected).toBe(false);- });-});--describe('InfraController.getStatus queue job counts', () => {- function buildStatusController(opts: { queueEnabled: boolean; queue?: { getJobCounts: jest.Mock } }) {- const configService = {- get: (key: string, def?: unknown) => (key === 'queue.enabled' ? opts.queueEnabled : def),- };- const dataSource = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) } as unknown;- const engineFactory = { create: jest.fn() };- const dockerService = { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() };- const cacheService = { isAvailable: jest.fn().mockResolvedValue(false), refreshS3Availability: jest.fn() };- const storageService = { refreshS3Availability: jest.fn() };- const shutdownService = {};- return new InfraController(- configService as never,- dataSource as never,- dataSource as never,- engineFactory as never,- dockerService as never,- cacheService as never,- storageService as never,- shutdownService as never,- opts.queue as never,- );- }-- it('reports live webhook job counts when the queue is enabled (pending = wait+active+delayed)', async () => {- const getJobCounts = jest.fn().mockResolvedValue({ wait: 2, active: 1, delayed: 3, completed: 10, failed: 1 });- const controller = buildStatusController({ queueEnabled: true, queue: { getJobCounts } });-- const status = await controller.getStatus();-- expect(getJobCounts).toHaveBeenCalledWith('wait', 'active', 'delayed', 'completed', 'failed');- expect(status.queue).toEqual({ enabled: true, webhooks: { pending: 6, completed: 10, failed: 1 } });- });-- it('reports zeros (and does not touch the queue) when the queue is disabled', async () => {- const getJobCounts = jest.fn();- const controller = buildStatusController({ queueEnabled: false, queue: { getJobCounts } });-- const status = await controller.getStatus();-- expect(getJobCounts).not.toHaveBeenCalled();- expect(status.queue).toEqual({ enabled: false, webhooks: { pending: 0, completed: 0, failed: 0 } });- });-});--describe('InfraController.saveConfig SSL reject-unauthorized', () => {- function writtenEnv(config: unknown): string {- const spy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);- const controller = new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );- controller.saveConfig(config as never);- const content = spy.mock.calls[0][1] as string;- spy.mockRestore();- return content;- }-- it('writes DATABASE_SSL_REJECT_UNAUTHORIZED=false for self-signed managed Postgres', () => {- const env = writtenEnv({- database: { type: 'postgres', sslEnabled: true, sslRejectUnauthorized: false, password: 'unit-test-pw' },- });- expect(env).toContain('DATABASE_SSL=true');- expect(env).toContain('DATABASE_SSL_REJECT_UNAUTHORIZED=false');- });-- it('defaults DATABASE_SSL_REJECT_UNAUTHORIZED=true when SSL is enabled without an explicit flag', () => {- const env = writtenEnv({ database: { type: 'postgres', sslEnabled: true, password: 'unit-test-pw' } });- expect(env).toContain('DATABASE_SSL_REJECT_UNAUTHORIZED=true');- });-- it('omits DATABASE_SSL_REJECT_UNAUTHORIZED when SSL is disabled', () => {- const env = writtenEnv({ database: { type: 'postgres', sslEnabled: false, password: 'unit-test-pw' } });- expect(env).not.toContain('DATABASE_SSL_REJECT_UNAUTHORIZED');- });-});--describe('InfraController PostgreSQL schema (POSTGRES_SCHEMA)', () => {- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- function written(config: unknown, existing?: string): string {- (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);- (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');- (fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);- const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- return content;- }-- it('writes POSTGRES_SCHEMA for external Postgres', () => {- const env = written({- database: { type: 'postgres', builtIn: false, host: 'db', schema: 'openwa', password: 'unit-test-pw' },- });- expect(env).toContain('POSTGRES_SCHEMA=openwa');- });-- it('leaves POSTGRES_SCHEMA untouched when the payload omits it (the runtime default is public)', () => {- // Per-key merge: an absent field must not reset the stored value. With nothing stored, the- // key stays out of the file and configuration.ts's own 'public' default applies at boot.- const fresh = written({ database: { type: 'postgres', builtIn: false, host: 'db', password: 'unit-test-pw' } });- expect(fresh).not.toContain('POSTGRES_SCHEMA=');- const preserved = written(- { database: { type: 'postgres', builtIn: false, host: 'db', password: 'unit-test-pw' } },- 'DATABASE_TYPE=postgres\nPOSTGRES_SCHEMA=openwa\n',- );- expect(preserved).toContain('POSTGRES_SCHEMA=openwa');- });-- it('pins POSTGRES_SCHEMA=public for the built-in Postgres container', () => {- const env = written({ database: { type: 'postgres', builtIn: true } });- expect(env).toContain('POSTGRES_SCHEMA=public');- });-- it('does not write POSTGRES_SCHEMA for sqlite', () => {- const env = written({ database: { type: 'sqlite' } });- expect(env).not.toContain('POSTGRES_SCHEMA=');- });-- it('getConfig surfaces the saved POSTGRES_SCHEMA, defaulting to public', () => {- (fs.existsSync as jest.Mock).mockReturnValue(true);- (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=postgres\nPOSTGRES_SCHEMA=openwa\n');- expect(newController().getConfig().database.schema).toBe('openwa');- (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=postgres\n');- expect(newController().getConfig().database.schema).toBe('public');- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- });-});--describe('InfraController.saveConfig writes the generated env owner-only', () => {- // data/.env.generated holds DB/S3/Redis credentials, so it must be written 0600 — not the- // default 0644 (world-readable). The write must go through the same owner-only path the- // first-run boot uses, closing the gap between a dashboard save and the next restart.- it('persists data/.env.generated with mode 0600, not world-readable', () => {- const writeSpy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);- const controller = new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );- controller.saveConfig({ database: { type: 'postgres', sslEnabled: true, password: 'pw' } } as never);- const opts = writeSpy.mock.calls[0][2];- expect(opts).toEqual({ mode: 0o600 });- writeSpy.mockRestore();- });-});--describe('InfraController.saveConfig env-name correctness and merge (#226)', () => {- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- function written(config: unknown, existing?: string): string {- (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);- (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');- (fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);- const calls = (fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>;- const content = calls[0][1];- // Reset to defaults so later tests start from "no prior config".- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- return content;- }-- it('writes the env names the backend actually reads (not the old ignored names)', () => {- const env = written({- engine: { headless: false, sessionDataPath: './sess', browserArgs: '--flag' },- storage: { type: 's3', s3Bucket: 'b', s3AccessKey: 'ak', s3SecretKey: 'sk' },- });- // Correct names (configuration.ts reads these)- expect(env).toContain('PUPPETEER_HEADLESS=false');- expect(env).toContain('SESSION_DATA_PATH=./sess');- expect(env).toContain('PUPPETEER_ARGS=--flag');- expect(env).toContain('S3_ACCESS_KEY_ID=ak');- expect(env).toContain('S3_SECRET_ACCESS_KEY=sk');- // Old, silently-ignored names must be gone- expect(env).not.toContain('ENGINE_HEADLESS=');- expect(env).not.toContain('ENGINE_SESSION_PATH=');- expect(env).not.toContain('ENGINE_BROWSER_ARGS=');- expect(env).not.toContain('S3_ACCESS_KEY=');- expect(env).not.toContain('S3_SECRET_KEY=');- });-- it('defaults PUPPETEER_ARGS to the full Docker sandbox flag set when browserArgs is empty', () => {- // Once compose blank-forwards PUPPETEER_ARGS this saved value wins at runtime, so the default must- // keep --disable-dev-shm-usage (the Docker /dev/shm tab-crash guard) — NOT the old 2-flag set.- const env = written({ engine: { headless: true, sessionDataPath: './data/sessions', browserArgs: '' } });- expect(env).toContain('PUPPETEER_ARGS=--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu');- expect(env).not.toContain('PUPPETEER_ARGS=--no-sandbox --disable-gpu');- });-- it('writes STORAGE_LOCAL_PATH (the name the backend reads) for local storage', () => {- const env = written({ storage: { type: 'local', localPath: './data/media' } });- expect(env).toContain('STORAGE_LOCAL_PATH=./data/media');- expect(env).not.toContain('STORAGE_PATH=');- });-- it('preserves existing keys that are not in the current payload', () => {- const env = written({ engine: { headless: true } }, 'WEBHOOK_TIMEOUT=5000\nSESSION_DATA_PATH=./old\n');- expect(env).toContain('WEBHOOK_TIMEOUT=5000'); // untouched key survives- expect(env).toContain('PUPPETEER_HEADLESS=true'); // payload applied- });-- it('does not blank a stored secret when the form submits an empty value', () => {- const env = written({ database: { type: 'postgres', host: 'db', password: '' } }, 'DATABASE_PASSWORD=keepme\n');- expect(env).toContain('DATABASE_PASSWORD=keepme');- expect(env).toContain('DATABASE_HOST=db');- });-- it('drops stale postgres keys (including POSTGRES_SCHEMA) when switching to sqlite', () => {- const existing =- 'DATABASE_TYPE=postgres\nDATABASE_HOST=oldhost\nDATABASE_PASSWORD=secret\nDATABASE_PORT=5432\nPOSTGRES_SCHEMA=openwa\n';- const env = written({ database: { type: 'sqlite' } }, existing);- expect(env).toContain('DATABASE_TYPE=sqlite');- expect(env).not.toContain('DATABASE_HOST=');- expect(env).not.toContain('DATABASE_PASSWORD=');- expect(env).not.toContain('DATABASE_PORT=');- expect(env).not.toContain('POSTGRES_SCHEMA=');- });-- it('drops stale S3 keys when switching storage to local', () => {- const existing =- 'STORAGE_TYPE=s3\nS3_BUCKET=old\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\nS3_ENDPOINT=http://x\n';- const env = written({ storage: { type: 'local', localPath: './data/media' } }, existing);- expect(env).toContain('STORAGE_TYPE=local');- expect(env).toContain('STORAGE_LOCAL_PATH=./data/media');- expect(env).not.toContain('S3_BUCKET=');- expect(env).not.toContain('S3_ACCESS_KEY_ID=');- expect(env).not.toContain('S3_SECRET_ACCESS_KEY=');- });-});--describe('InfraController.saveConfig rejects values that would inject extra env vars', () => {- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- // .env.generated is one KEY=value per line and is loaded on the next boot. A value carrying a- // newline would write a second `KEY=value` line — injecting an arbitrary env var (e.g. an admin- // key) the operator never set. Such a value must be refused outright, with nothing written.- it.each([- ['linefeed', '--no-sandbox\nADMIN_MASTER_KEY=attacker'],- ['carriage return', '--no-sandbox\rADMIN_MASTER_KEY=attacker'],- ])('does not persist a config value containing a %s', (_label, malicious) => {- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.writeFileSync as jest.Mock).mockClear();-- // A newline-injected value is rejected outright with a 4xx (BadRequestException), not masked as a- // {saved:false} 200 — and nothing is written.- expect(() => newController().saveConfig({ engine: { browserArgs: malicious } })).toThrow(BadRequestException);- expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();- });-- it('still persists a normal value with the same key', () => {- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.writeFileSync as jest.Mock).mockClear();-- const result = newController().saveConfig({ engine: { browserArgs: '--no-sandbox --disable-gpu' } });-- expect(result.saved).toBe(true);- expect(fs.writeFileSync as jest.Mock).toHaveBeenCalled();- });-});--describe('InfraController.saveConfig engine selection (persist ENGINE_TYPE — Infrastructure tile)', () => {- const engineFactory = {- getAvailableEngines: () => [{ id: 'whatsapp-web.js' }, { id: 'baileys' }],- };- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- engineFactory as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- function written(config: unknown, existing?: string): string {- (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);- (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');- (fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);- const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- return content;- }-- it('persists ENGINE_TYPE when a valid engine is selected', () => {- const env = written({ engine: { type: 'baileys', headless: true } });- expect(env).toContain('ENGINE_TYPE=baileys');- });-- it('does not write ENGINE_TYPE when no engine type is provided (avoids clobbering)', () => {- const env = written({ engine: { headless: false } });- expect(env).not.toContain('ENGINE_TYPE=');- expect(env).toContain('PUPPETEER_HEADLESS=false');- });-- it('rejects an unknown engine type and writes nothing', () => {- (fs.writeFileSync as jest.Mock).mockClear();- // Rejected as a 4xx (BadRequestException naming the bad engine), not a {saved:false} 200.- expect(() => newController().saveConfig({ engine: { type: 'bogus' } })).toThrow(/unknown engine/i);- expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();- });-});--describe('InfraController.saveConfig byte-identical regression (full dashboard payload)', () => {- // Pins the legitimate behavior: a FULL dashboard save (every section, every field — the exact- // shape Infrastructure.tsx posts) must produce exactly the same .env.generated bytes as before- // the per-key merge change. The literal key maps below were derived from the previous- // implementation's output; any drift in written keys or values fails this gate.- const engineFactory = {- getAvailableEngines: () => [{ id: 'whatsapp-web.js' }, { id: 'baileys' }],- };- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- engineFactory as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- const NOW = '2026-01-02T03:04:05.000Z';-- beforeEach(() => {- jest.useFakeTimers();- jest.setSystemTime(new Date(NOW));- });- afterEach(() => {- jest.useRealTimers();- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- });-- function expectedEnv(keys: Record<string, string>): string {- const body = Object.keys(keys)- .sort()- .map(k => `${k}=${keys[k]}`);- return [- '# OpenWA Configuration',- `# Generated at ${NOW}`,- '# Managed via Dashboard > Infrastructure. Values in process env or project .env take precedence.',- '',- ...body,- '',- ].join('\n');- }-- function saveAndGetContent(config: unknown, existing: string): string {- (fs.existsSync as jest.Mock).mockReturnValue(true);- (fs.readFileSync as jest.Mock).mockReturnValue(existing);- (fs.writeFileSync as jest.Mock).mockClear();- const result = newController().saveConfig(config as never);- expect(result.saved).toBe(true);- return ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];- }-- it('all-built-in full save is byte-identical', () => {- const existing = [- 'DATABASE_TYPE=postgres',- 'POSTGRES_BUILTIN=true',- 'DATABASE_HOST=postgres',- 'DATABASE_PORT=5432',- 'DATABASE_USERNAME=openwa',- 'DATABASE_PASSWORD=openwa',- 'DATABASE_NAME=openwa',- 'POSTGRES_SCHEMA=public',- 'DATABASE_POOL_SIZE=10',- 'DATABASE_SSL=false',- 'REDIS_ENABLED=true',- 'REDIS_BUILTIN=true',- 'REDIS_HOST=redis',- 'REDIS_PORT=6379',- 'QUEUE_ENABLED=true',- 'STORAGE_TYPE=s3',- 'MINIO_BUILTIN=true',- 'S3_ENDPOINT=http://minio:9000',- 'S3_ACCESS_KEY_ID=minioadmin',- 'S3_SECRET_ACCESS_KEY=minioadmin',- 'S3_BUCKET=openwa',- 'S3_REGION=us-east-1',- 'ENGINE_TYPE=whatsapp-web.js',- 'PUPPETEER_HEADLESS=true',- 'SESSION_DATA_PATH=./data/sessions',- 'PUPPETEER_ARGS=--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',- 'WEBHOOK_TIMEOUT=5000',- '',- ].join('\n');- // The exact payload the dashboard posts for that saved state (secrets come back empty:- // "unchanged"). The built-in credentials are exempt from the production secret guard.- const payload = {- database: {- type: 'postgres',- builtIn: true,- host: 'postgres',- port: '5432',- username: 'openwa',- password: '',- database: 'openwa',- schema: 'public',- poolSize: 10,- sslEnabled: false,- sslRejectUnauthorized: true,- },- redis: { enabled: true, builtIn: true, host: 'redis', port: '6379', password: '' },- queue: { enabled: true },- storage: {- type: 's3',- builtIn: true,- localPath: '',- s3Bucket: 'openwa',- s3Region: 'us-east-1',- s3AccessKey: '',- s3SecretKey: '',- s3Endpoint: 'http://minio:9000',- },- engine: {- type: 'whatsapp-web.js',- headless: true,- sessionDataPath: './data/sessions',- browserArgs: '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',- },- };-- const content = saveAndGetContent(payload, existing);-- expect(content).toBe(- expectedEnv({- DATABASE_HOST: 'postgres',- DATABASE_NAME: 'openwa',- DATABASE_PASSWORD: 'openwa',- DATABASE_POOL_SIZE: '10',- DATABASE_PORT: '5432',- DATABASE_SSL: 'false',- DATABASE_TYPE: 'postgres',- DATABASE_USERNAME: 'openwa',- ENGINE_TYPE: 'whatsapp-web.js',- MINIO_BUILTIN: 'true',- POSTGRES_BUILTIN: 'true',- POSTGRES_SCHEMA: 'public',- PUPPETEER_ARGS: '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',- PUPPETEER_HEADLESS: 'true',- QUEUE_ENABLED: 'true',- REDIS_BUILTIN: 'true',- REDIS_ENABLED: 'true',- REDIS_HOST: 'redis',- REDIS_PORT: '6379',- S3_ACCESS_KEY_ID: 'minioadmin',- S3_BUCKET: 'openwa',- S3_ENDPOINT: 'http://minio:9000',- S3_REGION: 'us-east-1',- S3_SECRET_ACCESS_KEY: 'minioadmin',- SESSION_DATA_PATH: './data/sessions',- STORAGE_TYPE: 's3',- WEBHOOK_TIMEOUT: '5000',- }),- );- });-- it('all-external full save is byte-identical (secrets preserved on empty submission)', () => {- const existing = [- 'DATABASE_TYPE=postgres',- 'POSTGRES_BUILTIN=false',- 'DATABASE_HOST=db.example.com',- 'DATABASE_PORT=5433',- 'DATABASE_USERNAME=openwauser',- 'DATABASE_PASSWORD=Str0ng!Passw0rd',- 'DATABASE_NAME=openwa',- 'POSTGRES_SCHEMA=openwa',- 'DATABASE_POOL_SIZE=20',- 'DATABASE_SSL=true',- 'DATABASE_SSL_REJECT_UNAUTHORIZED=false',- 'REDIS_ENABLED=true',- 'REDIS_BUILTIN=false',- 'REDIS_HOST=redis.example.com',- 'REDIS_PORT=6380',- 'REDIS_PASSWORD=r3dis-secret',- 'QUEUE_ENABLED=false',- 'STORAGE_TYPE=s3',- 'MINIO_BUILTIN=false',- 'S3_ENDPOINT=https://s3.eu-west-1.amazonaws.com',- 'S3_ACCESS_KEY_ID=AKIAEXAMPLE123',- 'S3_SECRET_ACCESS_KEY=s3-super-secret',- 'S3_BUCKET=mybucket',- 'S3_REGION=eu-west-1',- 'ENGINE_TYPE=baileys',- 'PUPPETEER_HEADLESS=false',- 'SESSION_DATA_PATH=/var/lib/openwa/sessions',- 'PUPPETEER_ARGS=--no-sandbox',- '',- ].join('\n');- const payload = {- database: {- type: 'postgres',- builtIn: false,- host: 'db.example.com',- port: '5433',- username: 'openwauser',- password: '',- database: 'openwa',- schema: 'openwa',- poolSize: 20,- sslEnabled: true,- sslRejectUnauthorized: false,- },- redis: { enabled: true, builtIn: false, host: 'redis.example.com', port: '6380', password: '' },- queue: { enabled: false },- storage: {- type: 's3',- builtIn: false,- localPath: '',- s3Bucket: 'mybucket',- s3Region: 'eu-west-1',- s3AccessKey: '',- s3SecretKey: '',- s3Endpoint: 'https://s3.eu-west-1.amazonaws.com',- },- engine: {- type: 'baileys',- headless: false,- sessionDataPath: '/var/lib/openwa/sessions',- browserArgs: '--no-sandbox',- },- };-- const content = saveAndGetContent(payload, existing);-- expect(content).toBe(- expectedEnv({- DATABASE_HOST: 'db.example.com',- DATABASE_NAME: 'openwa',- DATABASE_PASSWORD: 'Str0ng!Passw0rd',- DATABASE_POOL_SIZE: '20',- DATABASE_PORT: '5433',- DATABASE_SSL: 'true',- DATABASE_SSL_REJECT_UNAUTHORIZED: 'false',- DATABASE_TYPE: 'postgres',- DATABASE_USERNAME: 'openwauser',- ENGINE_TYPE: 'baileys',- MINIO_BUILTIN: 'false',- POSTGRES_BUILTIN: 'false',- POSTGRES_SCHEMA: 'openwa',- PUPPETEER_ARGS: '--no-sandbox',- PUPPETEER_HEADLESS: 'false',- QUEUE_ENABLED: 'false',- REDIS_BUILTIN: 'false',- REDIS_ENABLED: 'true',- REDIS_HOST: 'redis.example.com',- REDIS_PASSWORD: 'r3dis-secret',- REDIS_PORT: '6380',- S3_ACCESS_KEY_ID: 'AKIAEXAMPLE123',- S3_BUCKET: 'mybucket',- S3_ENDPOINT: 'https://s3.eu-west-1.amazonaws.com',- S3_REGION: 'eu-west-1',- S3_SECRET_ACCESS_KEY: 's3-super-secret',- SESSION_DATA_PATH: '/var/lib/openwa/sessions',- STORAGE_TYPE: 's3',- }),- );- });-});--describe('InfraController.saveConfig per-key merge (partial payloads)', () => {- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- function written(config: unknown, existing?: string): string {- (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);- (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');- (fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);- const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- return content;- }-- it('a queue-only save does not touch the redis section', () => {- const env = written(- { queue: { enabled: true } },- 'REDIS_ENABLED=true\nREDIS_BUILTIN=true\nREDIS_HOST=redis\nREDIS_PORT=6379\nQUEUE_ENABLED=false\n',- );- expect(env).toContain('QUEUE_ENABLED=true');- expect(env).toContain('REDIS_ENABLED=true');- expect(env).toContain('REDIS_BUILTIN=true');- expect(env).toContain('REDIS_HOST=redis');- expect(env).toContain('REDIS_PORT=6379');- });-- it('a redis-only save does not touch the queue section or force the redis flags', () => {- const env = written(- { redis: { host: 'redis2.example.com' } },- 'REDIS_ENABLED=true\nREDIS_BUILTIN=false\nREDIS_HOST=redis1.example.com\nQUEUE_ENABLED=true\n',- );- expect(env).toContain('REDIS_HOST=redis2.example.com');- expect(env).toContain('REDIS_ENABLED=true');- expect(env).toContain('REDIS_BUILTIN=false');- expect(env).toContain('QUEUE_ENABLED=true');- });-- it('a partial database save keeps unmentioned keys (pool size, schema, stored password)', () => {- const existing =- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=old.example.com\nDATABASE_PASSWORD=keepme\nDATABASE_POOL_SIZE=25\nPOSTGRES_SCHEMA=openwa\n';- const env = written({ database: { type: 'postgres', host: 'new.example.com' } }, existing);- expect(env).toContain('DATABASE_HOST=new.example.com');- expect(env).toContain('DATABASE_POOL_SIZE=25');- expect(env).toContain('POSTGRES_SCHEMA=openwa');- expect(env).toContain('DATABASE_PASSWORD=keepme');- });-- it('a partial storage save keeps the stored S3 region instead of resetting it to the default', () => {- const existing =- 'STORAGE_TYPE=s3\nMINIO_BUILTIN=false\nS3_BUCKET=old-bucket\nS3_REGION=eu-west-1\nS3_ACCESS_KEY_ID=ak-strong\nS3_SECRET_ACCESS_KEY=sk-strong\n';- const env = written({ storage: { type: 's3', s3Bucket: 'new-bucket' } }, existing);- expect(env).toContain('S3_BUCKET=new-bucket');- expect(env).toContain('S3_REGION=eu-west-1');- expect(env).toContain('S3_ACCESS_KEY_ID=ak-strong');- });-- it('a partial engine save keeps the stored session path and browser args', () => {- const env = written(- { engine: { headless: false } },- 'SESSION_DATA_PATH=./old-path\nPUPPETEER_ARGS=--custom-flag\n',- );- expect(env).toContain('PUPPETEER_HEADLESS=false');- expect(env).toContain('SESSION_DATA_PATH=./old-path');- expect(env).toContain('PUPPETEER_ARGS=--custom-flag');- });-});--describe('InfraController.saveConfig built-in/external mode flips and the save-time secret guard', () => {- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- function written(config: unknown, existing?: string): string {- (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);- (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');- (fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);- const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- return content;- }-- function expectRejected(config: unknown, existing: string | undefined, match: RegExp): void {- (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);- (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');- (fs.writeFileSync as jest.Mock).mockClear();- expect(() => newController().saveConfig(config as never)).toThrow(match);- // A rejected save must leave the previous file untouched.- expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');- }-- const BUILTIN_POSTGRES_ENV =- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PORT=5432\nDATABASE_USERNAME=openwa\nDATABASE_PASSWORD=openwa\nDATABASE_NAME=openwa\nPOSTGRES_SCHEMA=public\n';- const BUILTIN_MINIO_ENV =- 'STORAGE_TYPE=s3\nMINIO_BUILTIN=true\nS3_ENDPOINT=http://minio:9000\nS3_ACCESS_KEY_ID=minioadmin\nS3_SECRET_ACCESS_KEY=minioadmin\nS3_BUCKET=openwa\nS3_REGION=us-east-1\n';-- it('flipping Postgres built-in -> external with a fresh password drops the bundled password', () => {- const env = written(- {- database: {- type: 'postgres',- builtIn: false,- host: 'db.example.com',- username: 'app',- password: 'Sup3rSecret!',- database: 'appdb',- },- },- BUILTIN_POSTGRES_ENV,- );- expect(env).toContain('POSTGRES_BUILTIN=false');- expect(env).toContain('DATABASE_HOST=db.example.com');- expect(env).toContain('DATABASE_PASSWORD=Sup3rSecret!');- // No trace of the bundled 'openwa' credential may survive the flip.- expect(env).not.toContain('openwa');- });-- it('rejects flipping Postgres built-in -> external without a fresh password instead of crash-looping', () => {- // Without the mode-flip drop + save-time guard this saved the bundled 'openwa' password into- // the external config; the production boot guard then refused to start and the dashboard died- // with it. The save itself must now fail with a 400 naming the variable.- expectRejected(- { database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' } },- BUILTIN_POSTGRES_ENV,- /DATABASE_PASSWORD/,- );- });-- it('rejects a blank-password external Postgres on a fresh setup (the sibling blank-password case)', () => {- expectRejected(- { database: { type: 'postgres', builtIn: false, host: 'db.example.com', password: '' } },- undefined,- /DATABASE_PASSWORD/,- );- });-- it('rejects an external Postgres using a known-default password', () => {- expectRejected(- { database: { type: 'postgres', builtIn: false, host: 'db.example.com', password: 'password' } },- undefined,- /DATABASE_PASSWORD/,- );- });-- it('the rejection is a 400 BadRequestException, not a masked {saved:false} 200', () => {- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.writeFileSync as jest.Mock).mockClear();- expect(() =>- newController().saveConfig({ database: { type: 'postgres', builtIn: false, host: 'db' } } as never),- ).toThrow(BadRequestException);- });-- it('flipping storage built-in -> external with fresh credentials drops the bundled ones', () => {- const env = written(- {- storage: {- type: 's3',- builtIn: false,- s3Bucket: 'prod-bucket',- s3Region: 'ap-southeast-1',- s3AccessKey: 'AKIANEWEXAMPLE',- s3SecretKey: 'brand-new-secret',- s3Endpoint: 'https://s3.ap-southeast-1.amazonaws.com',- },- },- BUILTIN_MINIO_ENV,- );- expect(env).toContain('MINIO_BUILTIN=false');- expect(env).toContain('S3_ACCESS_KEY_ID=AKIANEWEXAMPLE');- expect(env).toContain('S3_SECRET_ACCESS_KEY=brand-new-secret');- expect(env).toContain('S3_ENDPOINT=https://s3.ap-southeast-1.amazonaws.com');- expect(env).not.toContain('minioadmin');- expect(env).not.toContain('http://minio:9000');- });-- it('flipping storage built-in -> external (AWS) with a blank endpoint drops the stale MinIO endpoint', () => {- const env = written(- {- storage: {- type: 's3',- builtIn: false,- s3Bucket: 'prod-bucket',- s3AccessKey: 'AKIANEWEXAMPLE',- s3SecretKey: 'brand-new-secret',- s3Endpoint: '',- },- },- BUILTIN_MINIO_ENV,- );- expect(env).not.toContain('S3_ENDPOINT=');- expect(env).toContain('S3_ACCESS_KEY_ID=AKIANEWEXAMPLE');- });-- it('rejects flipping storage built-in -> external without fresh credentials', () => {- expectRejected(- {- storage: {- type: 's3',- builtIn: false,- s3Bucket: 'prod-bucket',- s3AccessKey: '',- s3SecretKey: '',- s3Endpoint: '',- },- },- BUILTIN_MINIO_ENV,- /S3_ACCESS_KEY, S3_SECRET_KEY/,- );- });-- it('rejects external S3 using the known-default minioadmin credentials', () => {- expectRejected(- {- storage: {- type: 's3',- builtIn: false,- s3Bucket: 'b',- s3AccessKey: 'minioadmin',- s3SecretKey: 'minioadmin',- s3Endpoint: 'https://minio.example.com',- },- },- undefined,- /S3_ACCESS_KEY, S3_SECRET_KEY/,- );- });-- it('flipping Redis external -> built-in drops the stale external password', () => {- const env = written(- { redis: { enabled: true, builtIn: true } },- 'REDIS_ENABLED=true\nREDIS_BUILTIN=false\nREDIS_HOST=redis.example.com\nREDIS_PORT=6379\nREDIS_PASSWORD=hunter2\n',- );- expect(env).toContain('REDIS_BUILTIN=true');- expect(env).toContain('REDIS_HOST=redis');- // The bundled Redis runs without auth; a carried-over password would make the client AUTH- // against a passwordless server on the next boot.- expect(env).not.toContain('REDIS_PASSWORD=');- });-- it('rejects a placeholder Redis password at save time', () => {- expectRejected(- { redis: { enabled: true, builtIn: false, host: 'redis.example.com', password: 'password' } },- undefined,- /REDIS_PASSWORD/,- );- });-- it('still saves built-in modes: the bundled credentials stay exempt from the guard', () => {- const env = written({- database: { type: 'postgres', builtIn: true },- storage: { type: 's3', builtIn: true },- });- expect(env).toContain('DATABASE_PASSWORD=openwa');- expect(env).toContain('POSTGRES_BUILTIN=true');- expect(env).toContain('S3_ACCESS_KEY_ID=minioadmin');- expect(env).toContain('MINIO_BUILTIN=true');- });-- it('an absent builtIn field inherits built-in mode without clobbering a stored custom password', () => {- // Secrets are never echoed back to the form, so an absent password field means "unchanged".- // Merely inheriting the built-in mode must not re-stamp the bundled 'openwa' over a custom- // password (e.g. an operator who re-keyed the bundled container via POSTGRES_PASSWORD).- const env = written(- { database: { type: 'postgres', poolSize: 25 } },- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PORT=5432\nDATABASE_USERNAME=openwa\nDATABASE_PASSWORD=CustomPw123!\nDATABASE_NAME=openwa\nPOSTGRES_SCHEMA=public\n',- );- expect(env).toContain('POSTGRES_BUILTIN=true');- expect(env).toContain('DATABASE_PASSWORD=CustomPw123!');- expect(env).toContain('DATABASE_POOL_SIZE=25');- });-- it('an explicit password wins while the built-in mode is only inherited', () => {- const env = written(- { database: { type: 'postgres', password: 'NewPw456!' } },- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PASSWORD=openwa\nDATABASE_NAME=openwa\n',- );- expect(env).toContain('DATABASE_PASSWORD=NewPw456!');- expect(env).not.toContain('DATABASE_PASSWORD=openwa');- });-- it('an explicit builtIn:true keeps a re-keyed bundled password (the dashboard always sends builtIn)', () => {- // Infrastructure.tsx sends `database.builtIn` on every save and never echoes the password back,- // so treating "explicit builtIn:true + no password" as a reset re-wrote a re-keyed container's- // credential on each save, breaking the next boot's DB auth.- const env = written(- { database: { type: 'postgres', builtIn: true } },- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PASSWORD=CustomPw123!\nDATABASE_NAME=openwa\n',- );- expect(env).toContain('DATABASE_PASSWORD=CustomPw123!');- });-- it('does not carry an EXTERNAL password into the bundled container when switching to built-in', () => {- // The stored secret belongs to the external DB; the bundled container is seeded with 'openwa'- // unless the operator re-keys it, so switching modes must reset rather than inherit.- const env = written(- { database: { type: 'postgres', builtIn: true } },- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.example.com\nDATABASE_PASSWORD=ExternalPw!\nDATABASE_NAME=appdb\n',- );- expect(env).toContain('DATABASE_PASSWORD=openwa');- expect(env).not.toContain('ExternalPw!');- });-- // The guard must evaluate what the next boot would SEE: load-env.ts loads with dotenv- // override:false, so a value in the container environment (compose `environment:`) wins over the- // saved file. Snapshot + clear every guard-relevant key so these tests are hermetic.- describe('process-environment precedence', () => {- const GUARD_ENV_KEYS = [- 'DATABASE_TYPE',- 'DATABASE_PASSWORD',- 'POSTGRES_BUILTIN',- 'DATABASE_HOST',- 'STORAGE_TYPE',- 'S3_ACCESS_KEY_ID',- 'S3_SECRET_ACCESS_KEY',- 'S3_ENDPOINT',- 'MINIO_BUILTIN',- 'REDIS_PASSWORD',- ];- let savedEnv: Array<[string, string | undefined]>;- beforeEach(() => {- savedEnv = GUARD_ENV_KEYS.map(k => [k, process.env[k]]);- for (const k of GUARD_ENV_KEYS) delete process.env[k];- });- afterEach(() => {- for (const [k, v] of savedEnv) {- if (v === undefined) delete process.env[k];- else process.env[k] = v;- }- });-- it('accepts an external Postgres whose strong password comes from the process environment', () => {- // The compose deployment the guard used to refuse on EVERY save: the file still holds the- // bundled built-in credentials, but boot would see the env password, not the file's.- process.env.DATABASE_PASSWORD = 'Sup3rSecret!';- const env = written(- {- database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },- },- BUILTIN_POSTGRES_ENV,- );- expect(env).toContain('POSTGRES_BUILTIN=false');- expect(env).toContain('DATABASE_HOST=db.example.com');- // The stale bundled password is still dropped from the file — the environment supplies it.- expect(env).not.toContain('DATABASE_PASSWORD');- });-- it('a blank process-env forward counts as unset, so a weak merged config is still rejected', () => {- // Compose renders `- DATABASE_PASSWORD=${DATABASE_PASSWORD:-}` as an empty value when the- // operator sets nothing; boot clears that blank (clearBlankEnv) and falls to the file. The- // guard does the same — a blank forward can neither mask a weak file value nor supply one.- process.env.DATABASE_PASSWORD = '';- expectRejected(- {- database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },- },- BUILTIN_POSTGRES_ENV,- /DATABASE_PASSWORD/,- );- });-- it('a weak process-env value wins over a strong saved one and is still rejected', () => {- // Precedence cuts both ways: boot would see the env value, so a weak env password must not be- // rescued by a strong one sitting in the file.- process.env.DATABASE_PASSWORD = 'password';- expectRejected(- { queue: { enabled: true } },- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.example.com\nDATABASE_PASSWORD=Str0ngSaved!\n',- /DATABASE_PASSWORD/,- );- });-- // The cases above delete every guard key from process.env, which cannot happen in production:- // load-env merges data/.env.generated INTO process.env at boot, so the file's own values are- // sitting there while this save runs. Reading them back as if they were an orchestrator- // override makes the guard validate the config being REPLACED.- describe('saved-file values echoed in process.env are not mistaken for host overrides', () => {- afterEach(() => {- // Restore the permissive snapshot the rest of the file assumes.- recordOsEnvKeys(process.env);- });-- it('refuses a built-in -> external flip that keeps the bundled password (boot would crash-loop)', () => {- recordOsEnvKeys({}); // the host supplied nothing; everything below came from the file- process.env.DATABASE_TYPE = 'postgres';- process.env.POSTGRES_BUILTIN = 'true';- process.env.DATABASE_HOST = 'postgres';- process.env.DATABASE_PASSWORD = 'openwa';- expectRejected(- {- database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },- },- BUILTIN_POSTGRES_ENV,- /DATABASE_PASSWORD/,- );- });-- it('still honors a genuine host override of the same key', () => {- recordOsEnvKeys({ DATABASE_PASSWORD: 'Sup3rSecret!' });- process.env.DATABASE_PASSWORD = 'Sup3rSecret!';- const env = written(- {- database: { type: 'postgres', builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },- },- BUILTIN_POSTGRES_ENV,- );- expect(env).toContain('DATABASE_HOST=db.example.com');- });- });- });-});--describe('InfraController.saveConfig persists strictly-coerced form booleans', () => {- const newController = () =>- new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- it("persists 'false' for every boolean field when the body arrives form-encoded", async () => {- // The global urlencoded parser delivers scalars as strings and the ValidationPipe runs with- // enableImplicitConversion, which used to turn every non-empty string — including 'false' —- // into `true`. SaveConfigDto's @ToStrictBoolean fields must map 'false' to a real false so the- // file gets 'false', not a silently-enabled feature on the next boot.- const formPayload = {- database: {- type: 'postgres',- builtIn: 'false',- host: 'db.example.com',- password: 'unit-test-pw',- sslEnabled: 'true',- sslRejectUnauthorized: 'false',- },- redis: { enabled: 'false', builtIn: 'false' },- queue: { enabled: 'false' },- storage: { type: 's3', builtIn: 'false', s3Bucket: 'b', s3AccessKey: 'ak-strong', s3SecretKey: 'sk-strong' },- engine: { headless: 'false' },- };- // Mirror the real pipe: implicit conversion on, whitelist validation (src/config/app-validation.ts).- const instance = plainToInstance(SaveConfigDto, formPayload, { enableImplicitConversion: true });- const errors = await validate(instance, { whitelist: true, forbidNonWhitelisted: true });- expect(errors).toHaveLength(0);-- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(instance);- const env = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];-- expect(env).toContain('POSTGRES_BUILTIN=false');- expect(env).toContain('DATABASE_SSL=true');- expect(env).toContain('DATABASE_SSL_REJECT_UNAUTHORIZED=false');- expect(env).toContain('REDIS_ENABLED=false');- expect(env).toContain('REDIS_BUILTIN=false');- expect(env).toContain('QUEUE_ENABLED=false');- expect(env).toContain('MINIO_BUILTIN=false');- expect(env).toContain('PUPPETEER_HEADLESS=false');- });-});--describe('InfraController.importData round-trips export-data (no silent message/batch loss)', () => {- let ds: DataSource;- let controller: InfraController;- // exportData only reads dataDatabase.type off the config; everything else is unused here.- const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };-- const newController = () =>- new InfraController(cfg as never, {} as never, ds, {} as never, {} as never, {} as never, {} as never, {} as never);-- beforeEach(async () => {- ds = new DataSource({- type: 'better-sqlite3',- database: ':memory:',- entities: [- Session,- Webhook,- Message,- MessageBatch,- PluginInstance,- ConversationMapping,- IngressEvent,- WebhookDeliveryFailure,- IntegrationDeliveryFailure,- ],- synchronize: true,- });- await ds.initialize();- controller = newController();- });-- afterEach(async () => {- await ds.destroy();- });-- const seedSession = (id: string) =>- ds.getRepository(Session).save(- ds.getRepository(Session).create({- id,- name: `session-${id}`,- status: SessionStatus.READY,- phone: null,- pushName: null,- config: {},- proxyUrl: null,- proxyType: null,- connectedAt: null,- lastActiveAt: null,- }),- );-- it('restores messages and message_batches faithfully — not silently to zero', async () => {- await seedSession('s1');- await ds.getRepository(Message).save(- ds.getRepository(Message).create({- id: 'm1',- sessionId: 's1',- waMessageId: 'WA1',- chatId: '[email protected]',- chatName: 'Support Chat',- from: '[email protected]',- to: '[email protected]',- body: 'hello',- type: 'text',- direction: MessageDirection.INCOMING,- timestamp: 1700000000,- metadata: { ack: 2 },- status: MessageStatus.DELIVERED,- }),- );- await ds.getRepository(MessageBatch).save(- ds.getRepository(MessageBatch).create({- id: 'b1',- batchId: 'BATCH1',- sessionId: 's1',- status: BatchStatus.COMPLETED,- messages: [{ chatId: 'c1', type: 'text', content: {} }],- options: null as never,- progress: null as never,- results: null as never,- currentIndex: 0,- startedAt: null,- completedAt: null,- }),- );-- const dump = await controller.exportData();- expect(dump.counts.messages).toBe(1);- expect(dump.counts.messageBatches).toBe(1);-- const res = await controller.importData({ tables: dump.tables });-- // The whole point of the bug: a valid backup must restore with no warnings and imported:true.- expect(res.warnings).toEqual([]);- expect(res.imported).toBe(true);- expect(res.counts.messages).toBe(1);- expect(res.counts.messageBatches).toBe(1);-- // ...and the rows must actually be present after the DELETE+reinsert, with fields intact.- expect(await ds.getRepository(Message).count()).toBe(1);- expect(await ds.getRepository(MessageBatch).count()).toBe(1);- const m = await ds.getRepository(Message).findOneByOrFail({ id: 'm1' });- expect(m.body).toBe('hello');- expect(m.waMessageId).toBe('WA1');- expect(m.chatName).toBe('Support Chat');- expect(m.from).toBe('[email protected]');- expect(m.to).toBe('[email protected]');- expect(m.metadata).toEqual({ ack: 2 });- const b = await ds.getRepository(MessageBatch).findOneByOrFail({ id: 'b1' });- expect(b.batchId).toBe('BATCH1');- expect(b.status).toBe(BatchStatus.COMPLETED);- });-- it('round-trips plugin instances + integration delivery failures (Integration Fabric + DLQ)', async () => {- await seedSession('s1');- await ds.getRepository(PluginInstance).save(- ds.getRepository(PluginInstance).create({- id: 'chatwoot:acct1',- pluginId: 'chatwoot',- instanceId: 'acct1',- sessionScope: 's1',- secret: 'hmac-secret',- verifyToken: null,- config: { baseUrl: 'https://x' },- enabled: true,- }),- );- await ds.getRepository(IntegrationDeliveryFailure).save(- ds.getRepository(IntegrationDeliveryFailure).create({- direction: 'outbound',- pluginId: 'chatwoot',- instanceId: 'acct1',- sessionId: 's1',- deliveryId: 'd1',- attempts: 3,- lastError: 'boom',- payload: { foo: 'bar' },- redriven: false,- }),- );-- const dump = await controller.exportData();- expect(dump.counts.pluginInstances).toBe(1);- expect(dump.counts.integrationDeliveryFailures).toBe(1);-- const res = await controller.importData({ tables: dump.tables });-- expect(res.warnings).toEqual([]);- expect(res.imported).toBe(true);- expect(res.counts.pluginInstances).toBe(1);- expect(res.counts.integrationDeliveryFailures).toBe(1);-- expect(await ds.getRepository(PluginInstance).count()).toBe(1);- expect(await ds.getRepository(IntegrationDeliveryFailure).count()).toBe(1);- const pi = await ds.getRepository(PluginInstance).findOneByOrFail({ id: 'chatwoot:acct1' });- expect(pi.secret).toBe('hmac-secret'); // ingress HMAC secret survives a SQLite→Postgres migration- expect(pi.config).toEqual({ baseUrl: 'https://x' });- const dlf = await ds.getRepository(IntegrationDeliveryFailure).findOneByOrFail({ deliveryId: 'd1' });- expect(dlf.lastError).toBe('boom');- expect(dlf.payload).toEqual({ foo: 'bar' });- });-- it('round-trips the ingress dispatch-lifecycle columns so a restored pending event still replays', async () => {- await seedSession('s1');- const ingressRepo = ds.getRepository(IngressEvent);- // A pending event (still carrying its payload, awaiting reconciler replay) and a retired one- // (dispatch outcome recorded, payload slimmed to NULL).- await ingressRepo.save(- ingressRepo.create({- id: 'ie-pending',- instanceId: 'acct1',- pluginId: 'chatwoot',- providerDeliveryId: 'dlv-1',- route: 'chatwoot/acct1',- payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },- payloadHash: 'abc123',- sessionId: 's1',- dispatchState: 'pending',- dispatchAttempts: 2,- lastDispatchAt: new Date('2026-01-02T03:04:05.000Z'),- }),- );- await ingressRepo.save(- ingressRepo.create({- id: 'ie-retired',- instanceId: 'acct1',- pluginId: 'chatwoot',- providerDeliveryId: 'dlv-2',- route: 'chatwoot/acct1',- payload: null,- payloadHash: 'def456',- sessionId: 's1',- dispatchState: 'dispatched',- dispatchAttempts: 1,- lastDispatchAt: new Date('2026-01-02T03:04:05.000Z'),- }),- );-- const dump = await controller.exportData();- expect(dump.counts.ingressEvents).toBe(2);-- await ingressRepo.clear();- const res = await controller.importData({ tables: dump.tables });-- expect(res.warnings).toEqual([]);- expect(res.imported).toBe(true);- expect(res.counts.ingressEvents).toBe(2);-- // A restored 'pending' row that lost its dispatchState would read as NULL ("not watched"): the- // reconciler would never replay it while the dedup key still blocked the provider's retry.- const pending = await ingressRepo.findOneByOrFail({ id: 'ie-pending' });- expect(pending.dispatchState).toBe('pending');- expect(pending.dispatchAttempts).toBe(2);- expect(pending.lastDispatchAt).toEqual(new Date('2026-01-02T03:04:05.000Z'));- expect(pending.payloadHash).toBe('abc123');- expect(pending.payload).toEqual({ headers: {}, query: {}, body: '{}', rawBody: '{}' });-- const retired = await ingressRepo.findOneByOrFail({ id: 'ie-retired' });- expect(retired.dispatchState).toBe('dispatched');- expect(retired.payloadHash).toBe('def456');- // A retired payload must stay NULL — re-materializing it as '{}' would make the slimmed dedup- // row read as a pending event with an empty body.- expect(retired.payload).toBeNull();- });-- it('imports a pre-lifecycle backup (no dispatch columns) as not-watched legacy rows', async () => {- await seedSession('s1');- const res = await controller.importData({- tables: {- ingressEvents: [- {- id: 'ie-legacy',- instanceId: 'acct1',- pluginId: 'chatwoot',- providerDeliveryId: 'dlv-9',- route: 'chatwoot/acct1',- payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },- sessionId: 's1',- createdAt: '2026-01-01T00:00:00.000Z',- },- ] as never,- },- });-- expect(res.warnings).toEqual([]);- expect(res.imported).toBe(true);- // Columns absent from an older backup import as NULL/0 — the same "not watched" reading legacy- // rows have by design (the reconciler never sweeps them, so an upgrade can't mass-replay history).- const legacy = await ds.getRepository(IngressEvent).findOneByOrFail({ id: 'ie-legacy' });- expect(legacy.dispatchState).toBeNull();- expect(legacy.dispatchAttempts).toBe(0);- expect(legacy.lastDispatchAt).toBeNull();- expect(legacy.payloadHash).toBeNull();- });-- it('rolls back and reports imported:false when a row fails — existing data is preserved', async () => {- // Pre-existing data that must survive a failed import.- await seedSession('s1');- await ds.getRepository(Message).save(- ds.getRepository(Message).create({- id: 'm1',- sessionId: 's1',- waMessageId: 'WA1',- chatId: 'c1',- from: 'a',- to: 'b',- body: 'keep me',- type: 'text',- direction: MessageDirection.INCOMING,- status: MessageStatus.DELIVERED,- }),- );-- // A backup whose message row is malformed (missing the non-null from/to) must fail the whole import.- const res = await controller.importData({- tables: {- sessions: [{ id: 's2', name: 'imported', status: 'ready' }] as never,- messages: [- { id: 'mX', sessionId: 's2', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },- ] as never,- },- });-- expect(res.imported).toBe(false);- expect(res.warnings.length).toBeGreaterThan(0);-- // The destructive DELETE must have been rolled back — original data intact, nothing from the bad import.- expect(await ds.getRepository(Message).count()).toBe(1);- expect((await ds.getRepository(Message).findOneByOrFail({ id: 'm1' })).body).toBe('keep me');- expect(await ds.getRepository(Session).findOneBy({ id: 's2' })).toBeNull();- });-- it('refuses an empty/garbage backup — does not wipe existing data (#488 review must-fix)', async () => {- await seedSession('s1');- await ds.getRepository(Message).save(- ds.getRepository(Message).create({- id: 'm1',- sessionId: 's1',- chatId: 'c1',- from: 'a',- to: 'b',- body: 'keep me',- type: 'text',- direction: MessageDirection.INCOMING,- status: MessageStatus.DELIVERED,- }),- );-- // A wrong/empty file (no rows to restore) must NOT commit the all-rows DELETE and report success.- const res = await controller.importData({ tables: {} });-- expect(res.imported).toBe(false);- expect(res.warnings.length).toBeGreaterThan(0);- expect(await ds.getRepository(Session).count()).toBe(1);- expect(await ds.getRepository(Message).count()).toBe(1);- });-- it('propagates a genuine clear-table failure (lock/IO) instead of committing a merged restore', async () => {- // Pre-existing data that must survive if a clear step fails.- await seedSession('s1');- await ds.getRepository(Message).save(- ds.getRepository(Message).create({- id: 'm1',- sessionId: 's1',- chatId: 'c1',- from: 'a',- to: 'b',- body: 'keep me',- type: 'text',- direction: MessageDirection.INCOMING,- status: MessageStatus.DELIVERED,- }),- );-- expect(await ds.getRepository(Message).count()).toBe(1); // sanity: seeded-- // Make ONLY `DELETE FROM messages` fail with a genuine (non-missing-table) error. Previously a- // blind `.catch(() => {})` swallowed this and let a disjoint-id backup COMMIT a merged (not- // replaced) restore on SQLite; scoping the swallow to missing-table means the failure must now- // SURFACE (reaching the existing rollback-and-rethrow catch). A Proxy over the runner the- // controller creates intercepts just that one statement — no spy on `query`, so TypeORM's own- // internal `this.query` transaction control (BEGIN/ROLLBACK) is untouched.- const lockErr = new QueryFailedError(- 'DELETE FROM messages',- [],- Object.assign(new Error('SQLITE_BUSY: database is locked'), { code: 'SQLITE_BUSY' }),- );- let rolledBack = false;- const origCreate = ds.createQueryRunner.bind(ds);- jest.spyOn(ds, 'createQueryRunner').mockImplementation(() => {- const real = origCreate();- return new Proxy(real, {- get(target, prop) {- if (prop === 'query') {- return (sql: string, params?: unknown[]) =>- sql === 'DELETE FROM messages'- ? Promise.reject(lockErr)- : (target.query as (q: string, p?: unknown[]) => Promise<unknown>).call(target, sql, params);- }- if (prop === 'rollbackTransaction') {- return async () => {- rolledBack = true;- return target.rollbackTransaction.call(target);- };- }- const val = (target as unknown as Record<string, unknown>)[prop as string];- return typeof val === 'function' ? (val as (...a: unknown[]) => unknown).bind(target) : val;- },- });- });-- await expect(controller.importData({ tables: { messages: [] } })).rejects.toThrow(/database is locked/);- expect(rolledBack).toBe(true);-- jest.restoreAllMocks();- });-});--describe('InfraController.import/export preserves every data-DB table', () => {- let ds: DataSource;- let controller: InfraController;- const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };- const newController = () =>- new InfraController(cfg as never, {} as never, ds, {} as never, {} as never, {} as never, {} as never, {} as never);-- beforeEach(async () => {- ds = new DataSource({- type: 'better-sqlite3',- database: ':memory:',- entities: [Session, Webhook, Message, MessageBatch, Template, BaileysStoredMessage, LidMapping],- synchronize: true,- });- await ds.initialize();- controller = newController();- });-- afterEach(async () => {- await ds.destroy();- });-- const seedSession = (id: string) =>- ds.getRepository(Session).save(- ds.getRepository(Session).create({- id,- name: `session-${id}`,- status: SessionStatus.READY,- phone: null,- pushName: null,- config: {},- proxyUrl: null,- proxyType: null,- connectedAt: null,- lastActiveAt: null,- }),- );-- // lid_mappings is the persisted lid->phone cache; it is NOT a FK to sessions, so the sessions DELETE- // never touches it — but export omitted it, so a backup→restore into a fresh DB dropped it entirely.- it('restores lid_mappings instead of dropping them on a backup→restore', async () => {- await seedSession('s1');- const lidRepo = ds.getRepository(LidMapping);- await lidRepo.save(lidRepo.create({ lid: '111', phone: '628111', sessionId: 's1' }));- await lidRepo.save(lidRepo.create({ lid: '222', phone: null, sessionId: 's1' })); // negative cache-- const dump = await controller.exportData();- expect((dump.tables as unknown as { lidMappings?: unknown[] }).lidMappings).toHaveLength(2);-- // Simulate restoring into a fresh data DB (the documented backend-migration flow).- await lidRepo.clear();- const res = await controller.importData({ tables: dump.tables });-- expect(res.warnings).toEqual([]);- expect(res.imported).toBe(true);- expect(await lidRepo.count()).toBe(2);- expect((await lidRepo.findOneByOrFail({ lid: '111' })).phone).toBe('628111');- expect((await lidRepo.findOneByOrFail({ lid: '222' })).phone).toBeNull();- });-- // The messages import column list must carry every later-added column; `author` (the group- // sender identity) was the one that drifted — a restored backup silently lost all attribution.- it('restores the group-sender author column on a backup→restore', async () => {- await seedSession('s1');- const msgRepo = ds.getRepository(Message);- await msgRepo.save(- msgRepo.create({- sessionId: 's1',- waMessageId: 'WA-A1',- chatId: '[email protected]',- chatName: 'Alice',- author: '[email protected]',- from: '[email protected]',- to: '[email protected]',- body: 'hello',- type: 'text',- direction: MessageDirection.INCOMING,- status: MessageStatus.DELIVERED,- timestamp: 1700000000,- }),- );-- const dump = await controller.exportData();- await msgRepo.clear();- const res = await controller.importData({ tables: dump.tables });-- expect(res.warnings).toEqual([]);- const restored = await msgRepo.findOneByOrFail({ waMessageId: 'WA-A1' });- expect(restored.author).toBe('[email protected]');- });-- // DELETE FROM sessions cascades to templates + baileys_stored_messages (both FK ON DELETE CASCADE),- // so an import that never re-inserts them permanently wipes both on the documented backup flow.- it('restores templates and baileys_stored_messages instead of cascade-wiping them', async () => {- await seedSession('s1');- await ds- .getRepository(Template)- .save(ds.getRepository(Template).create({ id: 't1', sessionId: 's1', name: 'greet', body: 'Hi {{name}}' }));- await ds.getRepository(BaileysStoredMessage).save(- ds.getRepository(BaileysStoredMessage).create({- id: 'bsm1',- sessionId: 's1',- waMessageId: 'WA1',- serializedMessage: '{"k":"v"}',- }),- );-- const dump = await controller.exportData();- const res = await controller.importData({ tables: dump.tables });-- expect(res.warnings).toEqual([]);- expect(res.imported).toBe(true);- expect(await ds.getRepository(Template).count()).toBe(1);- expect(await ds.getRepository(BaileysStoredMessage).count()).toBe(1);- expect((await ds.getRepository(Template).findOneByOrFail({ id: 't1' })).body).toBe('Hi {{name}}');- expect((await ds.getRepository(BaileysStoredMessage).findOneByOrFail({ id: 'bsm1' })).serializedMessage).toBe(- '{"k":"v"}',- );- });-- // The webhooks INSERT omitted the `filters` column, so a filtered webhook came back firing on- // every event after a restore (over-delivery / PII fan-out).- it('preserves webhook filters across a round-trip', async () => {- await seedSession('s1');- await ds.getRepository(Webhook).save(- ds.getRepository(Webhook).create({- id: 'w1',- sessionId: 's1',- url: 'https://example.com/hook',- events: ['message'],- secret: null,- headers: {},- active: true,- retryCount: 3,- filters: { conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }] },- }),- );-- const dump = await controller.exportData();- const res = await controller.importData({ tables: dump.tables });-- expect(res.imported).toBe(true);- expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).filters).toEqual({- conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }],- });- // The active flag (exported as integer 1 from SQLite) must round-trip as a real boolean.- expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).active).toBe(true);- });-});--describe('InfraController.getConfig (#226)', () => {- it('returns the saved config shape without echoing secrets', () => {- (fs.existsSync as jest.Mock).mockReturnValue(true);- (fs.readFileSync as jest.Mock).mockReturnValue(- 'DATABASE_TYPE=postgres\nDATABASE_HOST=db\nDATABASE_PASSWORD=secret\nSESSION_DATA_PATH=./sess\nENGINE_TYPE=baileys\nSTORAGE_TYPE=s3\nS3_ACCESS_KEY_ID=ak\nS3_SECRET_ACCESS_KEY=sk\n',- );- const controller = new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- const cfg = controller.getConfig();- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');-- expect(cfg.database.type).toBe('postgres');- expect(cfg.database.host).toBe('db');- expect(cfg.database.passwordSet).toBe(true);- expect(cfg.engine.sessionDataPath).toBe('./sess');- expect(cfg.engine.type).toBe('baileys');- expect(cfg.storage.type).toBe('s3');- expect(cfg.storage.s3CredentialsSet).toBe(true);- // Secrets are never present on the returned object.- expect(JSON.stringify(cfg)).not.toContain('secret');- expect(JSON.stringify(cfg)).not.toContain('"ak"');- });-});--describe('InfraController.getStatus engine (reads the real engine.puppeteer.* keys)', () => {- // Pin the WA-Web version so getStatus does not fire the wa-version registry fetch (no network in tests).- const savedWebVer = process.env.WWEBJS_WEB_VERSION;- beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));- afterAll(() => {- if (savedWebVer === undefined) delete process.env.WWEBJS_WEB_VERSION;- else process.env.WWEBJS_WEB_VERSION = savedWebVer;- });-- it('reports the saved headless/browserArgs instead of stale defaults from non-existent flat keys', async () => {- const map: Record<string, unknown> = {- 'engine.type': 'whatsapp-web.js',- 'engine.puppeteer.headless': false,- 'engine.puppeteer.args': ['--foo', '--bar'],- 'engine.sessionDataPath': './sess',- };- const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };- const cache = { isAvailable: () => Promise.resolve(false) };- const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };- const controller = new InfraController(- config as never,- ds as never,- ds as never,- {} as never, // engineFactory- { isDockerAvailable: () => false } as never, // dockerService — no Docker in unit tests- cache as never,- { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never, // storageService- {} as never, // shutdownService- );-- const status = await controller.getStatus();- expect(status.engine.headless).toBe(false);- expect(status.engine.browserArgs).toBe('--foo --bar');- expect(status.engine.sessionDataPath).toBe('./sess');- });-});--describe('InfraController.getStatus storage (reads the real storage.localPath key)', () => {- // Pin the WA-Web version so getStatus does not fire the wa-version registry fetch (no network in tests).- const savedWebVer = process.env.WWEBJS_WEB_VERSION;- beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));- afterAll(() => {- if (savedWebVer === undefined) delete process.env.WWEBJS_WEB_VERSION;- else process.env.WWEBJS_WEB_VERSION = savedWebVer;- });-- const buildController = (map: Record<string, unknown>) => {- const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };- const cache = { isAvailable: () => Promise.resolve(false) };- const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };- return new InfraController(- config as never,- ds as never,- ds as never,- {} as never, // engineFactory- { isDockerAvailable: () => false } as never, // dockerService — no Docker in unit tests- cache as never,- { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never, // storageService- {} as never, // shutdownService- );- };-- it('reports the configured storage.localPath, not the ./uploads fallback', async () => {- // The bug: status read the non-existent `storage.path` key, so it always reported the- // `./uploads` fallback instead of the real path StorageService uses (`storage.localPath`).- const status = await buildController({- 'storage.type': 'local',- 'storage.localPath': '/srv/openwa/media',- }).getStatus();- expect(status.storage.path).toBe('/srv/openwa/media');- });-- it('falls back to ./data/media (matching StorageService) when storage.localPath is unset', async () => {- const status = await buildController({ 'storage.type': 'local' }).getStatus();- expect(status.storage.path).toBe('./data/media');- });-- it('reports the bucket in S3 mode so the active backend is visible', async () => {- const status = await buildController({ 'storage.type': 's3', 'storage.s3.bucket': 'my-openwa-bucket' }).getStatus();- expect(status.storage.type).toBe('s3');- expect(status.storage.bucket).toBe('my-openwa-bucket');- });-- it('omits bucket in local mode (no fabricated field)', async () => {- const status = await buildController({ 'storage.type': 'local' }).getStatus();- expect(status.storage.bucket).toBeUndefined();- });-});--describe('InfraController.exportStorage keeps the export import-able and sweeps it', () => {- function buildController(storage: Partial<{ createExportStream: jest.Mock }>) {- return new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- storage as never,- {} as never,- );- }-- // fs.existsSync is globally mocked in this file, so probe the real filesystem via fs.promises.access.- const exists = (p: string): Promise<boolean> =>- fs.promises- .access(p)- .then(() => true)- .catch(() => false);-- // Poll (don't sleep a fixed time) so the sweep assertion isn't flaky under CI load.- const waitForGone = async (p: string, timeoutMs = 3000): Promise<void> => {- const start = Date.now();- while (await exists(p)) {- if (Date.now() - start > timeoutMs) throw new Error(`file was not swept in time: ${p}`);- await new Promise(resolve => setTimeout(resolve, 10));- }- };-- let cwdSpy: jest.SpyInstance | undefined;- let cwd: string | undefined;-- afterEach(() => {- cwdSpy?.mockRestore();- if (cwd) fs.rmSync(cwd, { recursive: true, force: true });- cwdSpy = undefined;- cwd = undefined;- delete process.env.STORAGE_EXPORT_TTL_MS;- });-- it('writes under data/exports (so it stays import-able + survives restart) and TTL-sweeps it', async () => {- cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-cwd-'));- cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);- process.env.STORAGE_EXPORT_TTL_MS = '30';- const createExportStream = jest.fn().mockResolvedValue(Readable.from([Buffer.from('archive-bytes')]));- const controller = buildController({ createExportStream });-- const result = await controller.exportStorage();-- // download is cwd-relative (no absolute host path leak) and stays under data/exports so the import- // handler — which only accepts paths inside data/ — can still consume it.- expect(path.isAbsolute(result.download)).toBe(false);- expect(result.download.startsWith(path.join('data', 'exports'))).toBe(true);- // Resolve against the (mocked) cwd to check on-disk existence; fs itself uses the real cwd.- const abs = path.join(cwd, result.download);- expect(await exists(abs)).toBe(true);-- await waitForGone(abs);- expect(await exists(abs)).toBe(false);- });-});--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(- { get: () => undefined } as never,- { isInitialized: true } as never,- { isInitialized: true } as never,- {} as never, // engineFactory- dockerService as never,- { isAvailable: () => Promise.resolve(false) } as never, // cacheService- { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never, // storageService- { shutdown: jest.fn() } as never, // shutdownService- );-- it('tears down only allowlisted profiles, never an unknown or empty entry', async () => {- const stopManagedService = jest.fn().mockResolvedValue(true);- const controller = buildController({- isDockerAvailable: () => true,- stopManagedService,- orchestrateProfiles: jest.fn().mockResolvedValue({}),- });-- // '' (matches any container by substring) and 'evil' must be dropped; only managed profiles act.- await controller.requestRestart({ profilesToRemove: ['', 'evil', 'postgres', 'redis'] });-- const torn = stopManagedService.mock.calls.map(call => String((call as unknown[])[0])).sort();- expect(torn).toEqual(['postgres', 'redis']);- expect(torn).not.toContain('');- expect(torn).not.toContain('evil');- });-- it('reports teardown as stopped-not-removed, with honest per-profile errors', async () => {- const stopManagedService = jest- .fn()- .mockResolvedValueOnce(true) // postgres stops cleanly- .mockResolvedValueOnce(false); // redis fails- const controller = buildController({- isDockerAvailable: () => true,- stopManagedService,- orchestrateProfiles: jest.fn().mockResolvedValue({}),- });-- const result = await controller.requestRestart({ profilesToRemove: ['postgres', 'redis'] });-- // Teardown is stop-only (containers are retained, never deleted) — the payload must say so.- expect(result.removal).toEqual({- stopped: ['postgres'],- errors: ['Failed to stop redis'],- });- expect(JSON.stringify(result.removal)).not.toContain('removed');- });-- it('starts only allowlisted profiles, never an unknown entry (symmetry with teardown)', async () => {- const orchestrateProfiles = jest.fn().mockResolvedValue({});- const controller = buildController({- isDockerAvailable: () => true,- stopManagedService: jest.fn().mockResolvedValue(true),- orchestrateProfiles,- });-- // A non-managed name must be dropped before reaching orchestrateProfiles, exactly as teardown- // drops it before reaching stopManagedService — so start cannot select an unrelated container.- await controller.requestRestart({ profiles: ['postgres', 'not-managed'] });-- expect(orchestrateProfiles).toHaveBeenCalledTimes(1);- expect(orchestrateProfiles).toHaveBeenCalledWith(['postgres']);- });-- it('writes only allowlisted profiles to the no-Docker signal file (symmetry with the Docker path)', async () => {- const writeFileSync = fs.writeFileSync as jest.Mock;- writeFileSync.mockClear();- const controller = buildController({ isDockerAvailable: () => false });-- // The signal file is consumed by an external host script — it must never be handed a name the- // in-process Docker path would have refused.- await controller.requestRestart({ profiles: ['postgres', 'not-managed'], profilesToRemove: ['evil', 'redis'] });-- const written = (writeFileSync.mock.calls as Array<[unknown, unknown]>).find(call =>- String(call[0]).endsWith('.orchestration-request.json'),- );- expect(written).toBeDefined();- const payload = JSON.parse(String(written![1])) as { profiles: string[]; profilesToRemove: string[] };- expect(payload.profiles).toEqual(['postgres']);- expect(payload.profilesToRemove).toEqual(['redis']);- });-});--// C002: the infra module exposed sensitive ADMIN operations (credential config write, restart/Docker-// orchestration, full-DB + storage export/import) with no audit trail. Each now emits an AuditAction.-describe('InfraController C002 audit trail (light-dependency handlers)', () => {- const makeAudit = (): { logInfo: jest.Mock } => ({ logInfo: jest.fn().mockResolvedValue(null) });-- // Positional constructor: (config, mainDs, dataDs, engineFactory, dockerService, cacheService,- // storageService, shutdownService, webhookQueue?, auditService?). auditService is the last @Optional arg.- const build = (- audit: { logInfo: jest.Mock },- overrides: Partial<{- config: unknown;- dataDs: unknown;- engineFactory: unknown;- dockerService: unknown;- storageService: unknown;- shutdownService: unknown;- }> = {},- ): InfraController =>- new InfraController(- (overrides.config ?? {}) as never,- {} as never,- (overrides.dataDs ?? {}) as never,- (overrides.engineFactory ?? {}) as never,- (overrides.dockerService ?? {}) as never,- {} as never,- (overrides.storageService ?? {}) as never,- (overrides.shutdownService ?? {}) as never,- undefined as never,- audit as never,- );-- it('saveConfig emits INFRA_CONFIG_SAVED without leaking secret values into the metadata', () => {- const audit = makeAudit();- build(audit).saveConfig({ database: { type: 'postgres', host: 'db', password: 'topsecret' } } as never);- expect(audit.logInfo).toHaveBeenCalledTimes(1);- const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { sections: string[] } }]>;- const [action, ctx] = calls[0];- expect(action).toBe(AuditAction.INFRA_CONFIG_SAVED);- expect(ctx.metadata.sections).toContain('database');- // Only section names + profiles are recorded — never a secret value.- expect(JSON.stringify(ctx)).not.toContain('topsecret');- });-- it('saveConfig does NOT emit when the payload is rejected (unknown engine)', () => {- const audit = makeAudit();- const controller = build(audit, { engineFactory: { getAvailableEngines: () => [{ id: 'baileys' }] } });- expect(() => controller.saveConfig({ engine: { type: 'bogus' } })).toThrow(BadRequestException);- expect(audit.logInfo).not.toHaveBeenCalled();- });-- it('requestRestart emits INFRA_RESTART_REQUESTED with the requested profiles', async () => {- const audit = makeAudit();- const controller = build(audit, {- config: { get: () => undefined },- dockerService: { isDockerAvailable: () => false },- shutdownService: { shutdown: jest.fn() },- });- await controller.requestRestart({ profiles: ['postgres'], profilesToRemove: [] });- const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { profiles: string[] } }]>;- expect(calls[0][0]).toBe(AuditAction.INFRA_RESTART_REQUESTED);- expect(calls[0][1].metadata.profiles).toEqual(['postgres']);- });-- it('exportData emits INFRA_DATA_EXPORTED with per-table counts', async () => {- const audit = makeAudit();- const controller = build(audit, {- config: { get: (k: string, d?: unknown) => (k === 'dataDatabase.type' ? 'sqlite' : d) },- dataDs: { query: jest.fn().mockResolvedValue([]) },- });- await controller.exportData();- const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { counts: { sessions: number } } }]>;- expect(calls[0][0]).toBe(AuditAction.INFRA_DATA_EXPORTED);- expect(calls[0][1].metadata.counts.sessions).toBe(0);- });-- it('importStorage emits INFRA_STORAGE_IMPORTED with the imported file count', async () => {- const audit = makeAudit();- const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');- (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/x.tar.gz');- try {- const storageService = { importFromStream: jest.fn().mockResolvedValue(5), getCurrentStorageType: () => 'local' };- await build(audit, { storageService }).importStorage({ filePath: 'data/exports/x.tar.gz' });- const calls = audit.logInfo.mock.calls as Array<- [AuditAction, { metadata: { count: number; storageType: string } }]- >;- expect(calls[0][0]).toBe(AuditAction.INFRA_STORAGE_IMPORTED);- expect(calls[0][1].metadata).toEqual({ count: 5, storageType: 'local' });- } finally {- cwdSpy.mockRestore();- (fs.existsSync as jest.Mock).mockReturnValue(false);- }- });-- it('exportStorage emits INFRA_STORAGE_EXPORTED', async () => {- const audit = makeAudit();- const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-audit-'));- const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);- process.env.STORAGE_EXPORT_TTL_MS = '30';- try {- const storageService = { createExportStream: jest.fn().mockResolvedValue(Readable.from([Buffer.from('x')])) };- await build(audit, { storageService }).exportStorage();- const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { download: string } }]>;- expect(calls[0][0]).toBe(AuditAction.INFRA_STORAGE_EXPORTED);- expect(typeof calls[0][1].metadata.download).toBe('string');- } finally {- cwdSpy.mockRestore();- fs.rmSync(cwd, { recursive: true, force: true });- delete process.env.STORAGE_EXPORT_TTL_MS;- }- });-});--describe('InfraController C002 audit trail — import emits only on a committed restore', () => {- let ds: DataSource;- const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };- const build = (audit: { logInfo: jest.Mock }): InfraController =>- new InfraController(- cfg as never,- {} as never,- ds,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- undefined as never,- audit as never,- );-- beforeEach(async () => {- ds = new DataSource({- type: 'better-sqlite3',- database: ':memory:',- entities: [- Session,- Webhook,- Message,- MessageBatch,- PluginInstance,- ConversationMapping,- IngressEvent,- WebhookDeliveryFailure,- IntegrationDeliveryFailure,- ],- synchronize: true,- });- await ds.initialize();- });-- afterEach(async () => {- await ds.destroy();- });-- const seedSession = (id: string) =>- ds.getRepository(Session).save(- ds.getRepository(Session).create({- id,- name: `session-${id}`,- status: SessionStatus.READY,- phone: null,- pushName: null,- config: {},- proxyUrl: null,- proxyType: null,- connectedAt: null,- lastActiveAt: null,- }),- );-- it('emits INFRA_DATA_EXPORTED then INFRA_DATA_IMPORTED across a successful round-trip', async () => {- await seedSession('s1');- const audit = { logInfo: jest.fn().mockResolvedValue(null) };- const controller = build(audit);- const dump = await controller.exportData();- const res = await controller.importData({ tables: dump.tables });- expect(res.imported).toBe(true);- const actions = (audit.logInfo.mock.calls as Array<[AuditAction, unknown]>).map(c => c[0]);- expect(actions).toContain(AuditAction.INFRA_DATA_EXPORTED);- expect(actions).toContain(AuditAction.INFRA_DATA_IMPORTED);- });-- it('does NOT emit INFRA_DATA_IMPORTED when an empty backup is refused (no data changed)', async () => {- await seedSession('s1');- const audit = { logInfo: jest.fn().mockResolvedValue(null) };- const res = await build(audit).importData({ tables: {} });- expect(res.imported).toBe(false);- const actions = (audit.logInfo.mock.calls as Array<[AuditAction, unknown]>).map(c => c[0]);- expect(actions).not.toContain(AuditAction.INFRA_DATA_IMPORTED);- });-});--describe('InfraController.exportData optional-table strictness', () => {- const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };- const build = (query: jest.Mock) =>- new InfraController(- cfg as never,- {} as never,- { query } as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- );-- it('rethrows a non-missing-table error (lock/IO/timeout) instead of reporting a partial export as complete', async () => {- // A lock on ONE optional table must fail the whole export: silently exporting without that table- // produces a backup the import then treats as authoritative, DELETing the table's existing rows.- const query = jest.fn((sql: string) =>- sql === 'SELECT * FROM messages'- ? Promise.reject(new Error('SQLITE_BUSY: database is locked'))- : Promise.resolve([]),- );- await expect(build(query).exportData()).rejects.toThrow(/database is locked/);- });-- it('tolerates a genuinely absent optional table — and marks it in skippedTables', async () => {- const missing = Object.assign(new Error('no such table: messages'), { name: 'SqliteError' });- const query = jest.fn((sql: string) =>- sql === 'SELECT * FROM messages' ? Promise.reject(missing) : Promise.resolve([]),- );- const dump = await build(query).exportData();- expect(dump.counts.messages).toBe(0);- expect(dump.tables.messages).toEqual([]);- expect(dump.skippedTables).toContain('messages');- // Every other table still exported (all empty here, none skipped).- expect(dump.skippedTables).toEqual(['messages']);- });-- it('strips the Postgres generated body_ts tsvector from exported message rows', async () => {- // Postgres' STORED generated FTS column rides along in `SELECT *`; it is an index artifact, not- // payload, and must not be serialized into a (dialect-neutral) backup.- const messageRow = {- id: 'm1',- sessionId: 's1',- waMessageId: 'WA1',- chatId: 'c1',- chatName: null,- author: null,- from: 'a',- to: 'b',- body: 'hello',- type: 'text',- direction: 'incoming',- timestamp: 1700000000,- metadata: null,- status: 'delivered',- createdAt: '2026-01-01T00:00:00.000Z',- body_ts: "'hello'",- };- const query = jest.fn((sql: string) => Promise.resolve(sql === 'SELECT * FROM messages' ? [messageRow] : []));- const dump = await build(query).exportData();- expect(dump.tables.messages).toHaveLength(1);- expect(dump.tables.messages[0]).not.toHaveProperty('body_ts');- expect(dump.tables.messages[0].body).toBe('hello');- });-});--describe('InfraController.importData status_updates + runtime reconciliation', () => {- let ds: DataSource;- const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };-- // Positional constructor: (config, mainDs, dataDs, engineFactory, dockerService, cacheService,- // storageService, shutdownService, webhookQueue?, auditService?, sessionService?, lidMappingStore?).- const build = (opts: { sessionService?: unknown; lidMappingStore?: unknown } = {}) =>- new InfraController(- cfg as never,- {} as never,- ds,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- undefined as never,- undefined,- opts.sessionService as never,- opts.lidMappingStore as never,- );-- beforeEach(async () => {- ds = new DataSource({- type: 'better-sqlite3',- database: ':memory:',- entities: [- Session,- Webhook,- Message,- MessageBatch,- Template,- BaileysStoredMessage,- LidMapping,- PluginInstance,- ConversationMapping,- IngressEvent,- WebhookDeliveryFailure,- IntegrationDeliveryFailure,- StatusUpdate,- ],- synchronize: true,- });- await ds.initialize();- });-- afterEach(async () => {- await ds.destroy();- });-- const seedSession = (id: string) =>- ds.getRepository(Session).save(- ds.getRepository(Session).create({- id,- name: `session-${id}`,- status: SessionStatus.READY,- phone: null,- pushName: null,- config: {},- proxyUrl: null,- proxyType: null,- connectedAt: null,- lastActiveAt: null,- }),- );-- it('exports and restores status_updates (the table the docs promise is covered)', async () => {- await seedSession('s1');- const statusRepo = ds.getRepository(StatusUpdate);- await statusRepo.save(- statusRepo.create({- id: 'su1',- sessionId: 's1',- contactJid: '[email protected]',- contactName: 'Alice',- contactPushName: 'alice',- waStatusId: 'false_status@broadcast_ABC',- type: 'text',- caption: 'on vacation',- mediaOmitted: true,- omitReason: 'over_cap',- backgroundColor: '#FF0000',- font: 2,- postedAt: 1750000000000,- expiresAt: 1750086400000,- }),- );-- const controller = build();- const dump = await controller.exportData();- expect(dump.counts.statusUpdates).toBe(1);- expect(dump.skippedTables).toEqual([]);-- await statusRepo.clear();- const res = await controller.importData({ tables: dump.tables });-- expect(res.warnings).toEqual([]);- expect(res.imported).toBe(true);- expect(res.counts.statusUpdates).toBe(1);- const restored = await statusRepo.findOneByOrFail({ id: 'su1' });- expect(restored.waStatusId).toBe('false_status@broadcast_ABC');- expect(restored.caption).toBe('on vacation');- expect(restored.mediaOmitted).toBe(true); // boolean survives the 0/1 round-trip- expect(restored.omitReason).toBe('over_cap');- expect(restored.font).toBe(2);- expect(restored.postedAt).toBe(1750000000000);- expect(restored.expiresAt).toBe(1750086400000);- });-- it('tolerates body_ts on imported message rows (backup made before the strip)', async () => {- await seedSession('s1');- const res = await build().importData({- tables: {- sessions: [- {- id: 's1',- name: 'session-s1',- status: 'ready',- config: '{}',- createdAt: '2026-01-01T00:00:00.000Z',- updatedAt: '2026-01-01T00:00:00.000Z',- },- ] as never,- messages: [- {- id: 'm1',- sessionId: 's1',- waMessageId: 'WA1',- chatId: 'c1',- from: 'a',- to: 'b',- body: 'hello',- type: 'text',- direction: 'incoming',- status: 'delivered',- createdAt: '2026-01-01T00:00:00.000Z',- body_ts: "'hello'", // legacy Postgres export artifact — must be ignored, not fail- },- ] as never,- },- });- expect(res.imported).toBe(true);- expect(res.warnings).toEqual([]);- expect((await ds.getRepository(Message).findOneByOrFail({ id: 'm1' })).body).toBe('hello');- });-- it('reloads the in-memory lid mappings after a committed restore', async () => {- await seedSession('s1');- const lidMappingStore = { reload: jest.fn().mockResolvedValue(undefined) };- const controller = build({ lidMappingStore });- const dump = await controller.exportData();- const res = await controller.importData({ tables: dump.tables });- expect(res.imported).toBe(true);- expect(lidMappingStore.reload).toHaveBeenCalledTimes(1);- });-- it('does NOT reload lid mappings when the import is refused (nothing committed)', async () => {- await seedSession('s1');- const lidMappingStore = { reload: jest.fn().mockResolvedValue(undefined) };- const res = await build({ lidMappingStore }).importData({ tables: {} });- expect(res.imported).toBe(false);- expect(lidMappingStore.reload).not.toHaveBeenCalled();- });-- it('409s when a live engine would be orphaned by the replace — unless force=true', async () => {- await seedSession('s1');- const controller = build({ sessionService: { getActiveSessionIds: () => ['ghost'] } });- const dump = await controller.exportData(); // backup contains only s1, not the running 'ghost'-- // Without force: 409 Conflict, and the destructive replace never started.- const err = await controller.importData({ tables: dump.tables }).catch((e: unknown) => e);- expect(err).toBeInstanceOf(ConflictException);- expect((err as ConflictException).getStatus()).toBe(409);- expect((err as ConflictException).message).toContain('ghost');- expect(await ds.getRepository(Session).count()).toBe(1); // nothing deleted-- // With force: the restore proceeds and the response tells the operator a restart is required- // to stop the orphaned engine.- const res = await controller.importData({ tables: dump.tables, force: true });- expect(res.imported).toBe(true);- expect(res.restartRequired).toBe(true);- expect(res.orphanedEngines).toEqual(['ghost']);- });-- it('reports restartRequired:false when no live engine is orphaned', async () => {- await seedSession('s1');- const controller = build({ sessionService: { getActiveSessionIds: () => ['s1'] } });- const dump = await controller.exportData();- const res = await controller.importData({ tables: dump.tables });- expect(res.imported).toBe(true);- expect(res.restartRequired).toBe(false);- expect(res.orphanedEngines).toEqual([]);- });-- it('stopOrphans=true stops the orphan engines inside the request and keeps restartRequired:false', async () => {- await seedSession('s1');- const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['ghost'], notRunning: [], failed: [] });- const controller = build({- sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },- });- const dump = await controller.exportData(); // backup contains only s1, not 'ghost'-- const res = await controller.importData({ tables: dump.tables, stopOrphans: true });-- // The orphan engines were stopped (called once with exactly the orphan ids) and the import- // proceeded without requiring a restart — the whole point of stopOrphans vs force.- expect(stopOrphanEngines).toHaveBeenCalledWith(['ghost']);- expect(stopOrphanEngines).toHaveBeenCalledTimes(1);- expect(res.imported).toBe(true);- expect(res.restartRequired).toBe(false);- expect(res.stoppedOrphanEngines).toEqual(['ghost']);- expect(res.failedOrphanEngines).toEqual([]);- expect(res.orphanedEngines).toEqual(['ghost']);- });-- it('still reports the engines it already stopped when the import rolls back', async () => {- // The pre-flight teardown runs BEFORE the transaction opens and cannot be rolled back with it.- // An operator reading imported:false plus empty orphan arrays would conclude nothing happened,- // while their sessions are actually down.- await seedSession('s1');- const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['ghost'], notRunning: [], failed: [] });- const controller = build({- sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },- });- const dump = await controller.exportData();-- // A message row missing the non-null from/to fails mid-import and forces the all-or-nothing rollback.- const res = await controller.importData({- tables: {- ...dump.tables,- messages: [- { id: 'mX', sessionId: 's1', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },- ] as never,- },- stopOrphans: true,- });-- expect(res.imported).toBe(false); // the DB really did roll back- expect(stopOrphanEngines).toHaveBeenCalledWith(['ghost']); // ...but the teardown really did happen- expect(res.stoppedOrphanEngines).toEqual(['ghost']);- expect(res.orphanedEngines).toEqual(['ghost']);- expect(res.restartRequired).toBe(false); // sessions survive the rollback; restart them via the API- });-- it('flags restartRequired on a rolled-back import whose orphan teardown failed', async () => {- // The failed teardown is the one irreversible thing a rollback cannot undo: the Chromium/socket- // may still be alive, so this must stay true even though no data changed.- await seedSession('s1');- const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: [], notRunning: [], failed: ['ghost'] });- const controller = build({- sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },- });- const dump = await controller.exportData();-- const res = await controller.importData({- tables: {- ...dump.tables,- messages: [- { id: 'mX', sessionId: 's1', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },- ] as never,- },- stopOrphans: true,- });-- expect(res.imported).toBe(false);- expect(res.restartRequired).toBe(true);- expect(res.failedOrphanEngines).toEqual(['ghost']);- });-- it('stopOrphans=true surfaces a teardown failure as restartRequired:true + a warning (Map reconciled regardless)', async () => {- await seedSession('s1');- const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['g1'], notRunning: [], failed: ['g2'] });- const controller = build({- sessionService: { getActiveSessionIds: () => ['g1', 'g2'], stopOrphanEngines },- });- const dump = await controller.exportData();-- const res = await controller.importData({ tables: dump.tables, stopOrphans: true });-- expect(res.imported).toBe(true);- expect(res.restartRequired).toBe(true);- expect(res.failedOrphanEngines).toEqual(['g2']);- expect(res.stoppedOrphanEngines).toEqual(['g1']);- expect(res.notices.some(w => w.includes('g2') && w.includes('restart'))).toBe(true);- });-- it('stopOrphans=true reports notRunning orphans (still initializing) as a warning', async () => {- await seedSession('s1');- const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['g1'], notRunning: ['g-init'], failed: [] });- const controller = build({- sessionService: { getActiveSessionIds: () => ['g1', 'g-init'], stopOrphanEngines },- });- const dump = await controller.exportData();-- const res = await controller.importData({ tables: dump.tables, stopOrphans: true });-- expect(res.imported).toBe(true);- expect(res.restartRequired).toBe(false);- expect(res.notices.some(w => w.includes('g-init') && w.includes('initializing'))).toBe(true);- });-- it('stopOrphans=true is a no-op when there is no sessionService wired', async () => {- // Some stripped-down module shapes may not import SessionModule; the controller must not throw- // when stopOrphans is requested but the service is unavailable — it falls back to refuse/force.- await seedSession('s1');- const controller = build({}); // no sessionService- const dump = await controller.exportData();-- // Without sessionService there are no active ids to detect, so no orphan, no 409 — the import- // proceeds normally. (This matches the @Optional() wiring; the gate only engages when the- // service is present.)- const res = await controller.importData({ tables: dump.tables, stopOrphans: true });- expect(res.imported).toBe(true);- expect(res.stoppedOrphanEngines).toEqual([]);- });-});--describe('InfraController storage stream failures surface as request errors, not process crashes', () => {- it('importStorage maps an archive/stream failure to a 400 with the real reason', async () => {- const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');- (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/bad.tar.gz');- try {- const storage = {- importFromStream: jest.fn().mockRejectedValue(new Error('incorrect header check')),- getCurrentStorageType: () => 'local',- };- const controller = new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- storage as never,- {} as never,- );- const err = await controller.importStorage({ filePath: 'data/exports/bad.tar.gz' }).catch((e: unknown) => e);- expect(err).toBeInstanceOf(BadRequestException);- expect((err as BadRequestException).message).toContain('incorrect header check');- } finally {- cwdSpy.mockRestore();- (fs.existsSync as jest.Mock).mockReturnValue(false);- }- });-- it('exportStorage rejects (and the process lives) when the export source stream errors', async () => {- const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-export-err-'));- const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);- try {- // pipe() never forwards source errors: without a listener on the source this would be an- // unhandled 'error' event and kill the process instead of failing the request.- const errStream = new Readable({- read() {- this.destroy(new Error('archive boom'));- },- });- const storage = { createExportStream: jest.fn().mockResolvedValue(errStream) };- const controller = new InfraController(- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- {} as never,- storage as never,- {} as never,- );- await expect(controller.exportStorage()).rejects.toThrow(/archive boom/);- } finally {- cwdSpy.mockRestore();- fs.rmSync(cwd, { recursive: true, force: true });- }- });-});diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsdeleted file mode 100644index 958ef76ae..000000000--- a/src/modules/infra/infra.controller.ts+++ /dev/null@@ -1,2081 +0,0 @@-import {- Controller,- Get,- Put,- Post,- Body,- BadRequestException,- ConflictException,- HttpException,- HttpCode,- HttpStatus,- OnApplicationBootstrap,- Optional,-} from '@nestjs/common';-import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiPropertyOptional } from '@nestjs/swagger';-import { IsArray, IsOptional, IsString } from 'class-validator';-import { InjectQueue } from '@nestjs/bullmq';-import { Queue } from 'bullmq';-import { QUEUE_NAMES } from '../queue/queue-names';-import { ConfigService } from '@nestjs/config';-import { DataSource } from 'typeorm';-import { InjectDataSource } from '@nestjs/typeorm';-import { Public, RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';-import { isPathWithin, isSafeSessionName } from '../../common/utils/path-safety';-import { writeSecretFile } from '../../common/utils/secret-file';-import { EngineFactory } from '../../engine/engine.factory';-import { getEffectiveWebVersionInfo, resolveCurrentWebVersion } from '../../engine/wa-web-version';-import { DockerService, MANAGED_DOCKER_PROFILES } from '../docker';-import { CacheService } from '../../common/cache/cache.service';-import { StorageService } from '../../common/storage/storage.service';-import { ShutdownService } from '../../common/services/shutdown.service';-import { createLogger } from '../../common/services/logger.service';-import { isMissingTableError } from '../../common/utils/db-errors';-import { AuditService } from '../audit/audit.service';-import { AuditAction } from '../audit/entities/audit-log.entity';-import { SessionService } from '../session/session.service';-import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';-import { ImportStorageDto } from './dto/import-storage.dto';-import { SaveConfigDto } from './dto/save-config.dto';-import { assertNoDefaultSecretsInProduction } from '../../config/bootstrap-security';-import { BLANK_SHADOWED_ENV_KEYS, isOsProvidedEnv } from '../../config/env-precedence';-import * as fs from 'fs';-import * as path from 'path';-import { randomUUID } from 'crypto';-import { generatedEnvPath, readGeneratedEnv } from './generated-env';--interface InfraStatus {- // `builtIn` reflects whether OpenWA's own bundled container is actually running and backing this- // service (detected live from the labeled container), not merely the saved intent. Falls back to the- // saved flag when Docker is unavailable. (#488)- database: { connected: boolean; type: string; host: string; builtIn: boolean };- redis: { enabled: boolean; connected: boolean; host: string; port: number; builtIn: boolean };- queue: {- enabled: boolean;- webhooks: { pending: number; completed: number; failed: number };- };- storage: { type: 'local' | 's3'; path?: string; bucket?: string; builtIn: boolean; s3Available?: boolean };- engine: {- type: string;- headless: boolean;- sessionDataPath: string;- browserArgs: string;- // whatsapp-web.js only: the actual WhatsApp Web build in use (distinct from the library version),- // and how it was chosen. Omitted for other engines (e.g. baileys). (#488)- webVersion?: string | null;- webVersionSource?: 'pinned' | 'auto' | 'native';- };-}--// The PUT /infra/config body DTOs live in ./dto/save-config.dto.ts: as *.dto.ts classes they are-// covered by the input-coercion drift gate (src/common/utils/dto-strict-coercion.spec.ts), which-// controller-local classes escape, and their boolean/numeric fields carry the @ToStrictBoolean /-// @ToStrictNumber transforms that keep a form-encoded 'false' from being coerced to `true`.--class RestartDto {- @ApiPropertyOptional({ type: [String] })- @IsOptional()- @IsArray()- @IsString({ each: true })- profiles?: string[];-- @ApiPropertyOptional({ type: [String] })- @IsOptional()- @IsArray()- @IsString({ each: true })- profilesToRemove?: string[];-}--// Database migration types for export/import-interface SessionRow {- id: string;- name: string;- status: string;- phone: string | null;- pushName: string | null;- config: string | Record<string, unknown>;- proxyUrl: string | null;- proxyType: string | null;- connectedAt: string | null;- lastActiveAt: string | null;- createdAt: string;- updatedAt: string;-}--interface WebhookRow {- id: string;- sessionId: string;- url: string;- events: string | string[];- secret: string | null;- headers: string | Record<string, string>;- filters: string | Record<string, unknown> | null;- active: boolean | number;- retryCount: number;- lastTriggeredAt: string | null;- createdAt: string;- updatedAt: string;-}--// Shapes mirror the REAL table columns as returned by `SELECT *` (export-data), not the-// camelCase TypeORM entity properties. `messages` columns are the property names; `message_batches`-// columns are snake_case (the entity maps them via `name:`). Keeping these accurate is what keeps-// the import column lists below from drifting back into "no such column" failures.-interface MessageRow {- id: string;- sessionId: string;- waMessageId: string | null;- chatId: string;- chatName: string | null;- /** Group participant JID (nullable; added to messages after chatName — keep the import list in sync). */- author: string | null;- from: string;- to: string;- body: string | null;- type: string;- direction: string;- timestamp: number | string | null;- metadata: string | Record<string, unknown> | null;- status: string;- createdAt: string;- /**- * Postgres-only STORED generated tsvector (FTS). Present in `SELECT *` rows read from a Postgres- * source (and in backups made before it was stripped) but never a real payload column: export drops- * it, and the import's explicit column list ignores it. Declared so both directions type-check.- */- body_ts?: unknown;-}--interface MessageBatchRow {- id: string;- batch_id: string;- session_id: string;- status: string;- messages: string | unknown[];- options: string | Record<string, unknown> | null;- progress: string | Record<string, unknown> | null;- results: string | unknown[] | null;- current_index: number;- created_at: string;- updated_at: string;- started_at: string | null;- completed_at: string | null;-}--// templates + baileys_stored_messages both FK sessions ON DELETE CASCADE, so import's-// `DELETE FROM sessions` wipes them; they must be exported and re-inserted or the documented-// backup flow loses them permanently.-interface TemplateRow {- id: string;- sessionId: string;- name: string;- body: string;- header: string | null;- footer: string | null;- createdAt: string;- updatedAt: string;-}--interface BaileysStoredMessageRow {- id: string;- sessionId: string;- waMessageId: string;- serializedMessage: string;- createdAt: string;-}--// The persisted lid->phone resolution cache. Not a FK to sessions (provenance only), so the import's-// `DELETE FROM sessions` never clears it — it must be exported + re-inserted explicitly or a-// backup→restore into a fresh DB loses the whole cache (it self-heals via re-lookup, but lossily).-interface LidMappingRow {- lid: string;- phone: string | null;- sessionId: string | null;- updatedAt: string;-}--interface PluginInstanceRow {- id: string;- pluginId: string;- instanceId: string;- sessionScope: string | null;- secret: string;- verifyToken: string | null;- config: string | Record<string, unknown> | null;- enabled: boolean | number;- createdAt: string;- updatedAt: string;-}--interface ConversationMappingRow {- id: string;- sessionId: string;- chatId: string;- pluginId: string;- instanceId: string;- providerConversationId: string;- handoverState: string;- metadata: string | Record<string, unknown> | null;- updatedAt: string;-}--interface IngressEventRow {- id: string;- instanceId: string;- pluginId: string;- providerDeliveryId: string;- route: string;- // Retired to NULL once the dispatch outcome is recorded; only 'pending' rows still carry one.- payload: string | Record<string, unknown> | null;- payloadHash?: string | null;- // Dispatch lifecycle (the AddIngressEventDispatchState migration). A restored 'pending' row must- // keep these or the reconciler never replays it while the dedup row still blocks the provider's- // retry. Optional because backups exported before the columns existed don't carry them.- dispatchState?: 'pending' | 'dispatched' | 'failed' | null;- dispatchAttempts?: number;- lastDispatchAt?: string | null;- sessionId: string | null;- createdAt: string;-}--interface WebhookDeliveryFailureRow {- id: string;- webhookId: string;- sessionId: string;- event: string;- url: string;- idempotencyKey: string | null;- deliveryId: string | null;- attempts: number;- lastStatusCode: number | null;- lastError: string;- createdAt: string;-}--interface IntegrationDeliveryFailureRow {- id: string;- direction: string;- pluginId: string;- instanceId: string;- sessionId: string | null;- deliveryId: string | null;- attempts: number;- lastError: string;- payload: string | Record<string, unknown> | null;- redriven: boolean | number;- createdAt: string;-}--// status_updates has no FK to sessions (plain columns), so the import's `DELETE FROM sessions` never-// clears it — it must be exported + re-inserted explicitly like lid_mappings. postedAt/expiresAt are-// bigint epoch-ms: raw queries bypass the entity transformer, so Postgres returns them as strings.-interface StatusUpdateRow {- id: string;- sessionId: string;- contactJid: string;- contactName: string | null;- contactPushName: string | null;- waStatusId: string;- type: string;- caption: string | null;- mediaPath: string | null;- mediaMimetype: string | null;- mediaOmitted: boolean | number;- omitReason: string | null;- backgroundColor: string | null;- font: number | null;- postedAt: number | string;- expiresAt: number | string;-}--interface MigrationTables {- sessions: SessionRow[];- webhooks: WebhookRow[];- messages: MessageRow[];- messageBatches: MessageBatchRow[];- templates: TemplateRow[];- baileysStoredMessages: BaileysStoredMessageRow[];- lidMappings: LidMappingRow[];- pluginInstances: PluginInstanceRow[];- conversationMappings: ConversationMappingRow[];- ingressEvents: IngressEventRow[];- webhookDeliveryFailures: WebhookDeliveryFailureRow[];- integrationDeliveryFailures: IntegrationDeliveryFailureRow[];- statusUpdates: StatusUpdateRow[];-}--// Saved infrastructure config returned to the dashboard form for hydration. Secret-// values are never echoed back — a `*Set` boolean indicates whether one is stored.-interface SavedConfigResponse {- database: {- type: 'sqlite' | 'postgres';- builtIn: boolean;- host: string;- port: string;- username: string;- database: string;- schema: string;- poolSize: number;- sslEnabled: boolean;- sslRejectUnauthorized: boolean;- passwordSet: boolean;- };- redis: { enabled: boolean; builtIn: boolean; host: string; port: string; passwordSet: boolean };- queue: { enabled: boolean };- storage: {- type: 'local' | 's3';- builtIn: boolean;- localPath: string;- s3Bucket: string;- s3Region: string;- s3Endpoint: string;- s3CredentialsSet: boolean;- };- engine: { type: string; headless: boolean; sessionDataPath: string; browserArgs: string };-}--@ApiTags('infrastructure')-@Controller('infra')-// Every route here is deployment-global (data export/import, infra config, service orchestration),-// so the guard's route-param session fence can never bite. Reject session-scoped keys outright at-// class level, which also covers routes added later. @Public routes are unaffected: the guard-// returns before it reads this metadata.-@RequireUnscopedKey()-export class InfraController implements OnApplicationBootstrap {- private readonly logger = createLogger('InfraController');-- constructor(- private readonly configService: ConfigService,- @InjectDataSource('main')- private readonly mainDataSource: DataSource,- @InjectDataSource('data')- private readonly dataDataSource: DataSource,- private readonly engineFactory: EngineFactory,- private readonly dockerService: DockerService,- private readonly cacheService: CacheService,- private readonly storageService: StorageService,- private readonly shutdownService: ShutdownService,- @Optional()- @InjectQueue(QUEUE_NAMES.WEBHOOK)- private readonly webhookQueue?: Queue,- // Best-effort audit emission for the sensitive infra operations below. Injected @Optional and- // appended last so it never shifts the existing positional args: the running app always provides- // the @Global AuditService, while the direct-construction unit tests omit it — the `?.` at each- // call site then makes emission a no-op there instead of forcing every test to wire a mock.- @Optional()- private readonly auditService?: AuditService,- // Post-import runtime reconciliation (see importData). Same trailing-@Optional convention as- // auditService: provided by the app (InfraModule imports SessionModule; EngineModule is @Global),- // omitted by direct-construction unit tests, and every use is `?.`-guarded.- @Optional()- private readonly sessionService?: SessionService,- @Optional()- private readonly lidMappingStore?: LidMappingStoreService,- ) {}-- /** Bound the DB liveness probe so a hung connection can't stall the status read. */- private static readonly DB_PROBE_TIMEOUT_MS = 3000;-- /**- * Active DB liveness probe: run `SELECT 1`, not just read `DataSource.isInitialized`. A backend- * (notably Postgres) that dies AFTER init keeps `isInitialized` true until an explicit `.destroy()`,- * so the old check reported the tile green while the DB was actually down. Bounded by a short- * timeout; any error or timeout resolves to `false`. Mirrors `/health/ready`'s authoritative probe.- */- private async probeDbConnected(ds: DataSource): Promise<boolean> {- if (!ds.isInitialized) return false;- let timer: NodeJS.Timeout | undefined;- try {- await Promise.race([- ds.query('SELECT 1'),- new Promise((_resolve, reject) => {- timer = setTimeout(() => reject(new Error('db probe timeout')), InfraController.DB_PROBE_TIMEOUT_MS);- }),- ]);- return true;- } catch {- return false;- } finally {- if (timer) clearTimeout(timer);- }- }-- // 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' })- @ApiResponse({ status: 200, description: 'Infrastructure status' })- async getStatus(): Promise<InfraStatus> {- // Active DB liveness probe (SELECT 1) on both connections in parallel — not just isInitialized,- // which stays true after a Postgres backend dies until an explicit .destroy() (see probeDbConnected).- const [mainDbConnected, dataDbConnected] = await Promise.all([- this.probeDbConnected(this.mainDataSource),- this.probeDbConnected(this.dataDataSource),- ]);- const dbConnected = mainDbConnected && dataDbConnected;- const dbType = this.configService.get<string>('dataDatabase.type', 'sqlite');- const dbHost = this.configService.get<string>('dataDatabase.host', 'localhost');-- const redisHost = process.env.REDIS_HOST || this.configService.get<string>('redis.host', 'localhost');- const redisPort = parseInt(process.env.REDIS_PORT || '', 10) || this.configService.get<number>('redis.port', 6379);- const redisEnabled = process.env.REDIS_ENABLED === 'true';- const queueEnabled = this.configService.get<boolean>('queue.enabled', false);-- // Check actual Redis connectivity via CacheService- const redisConnected = await this.cacheService.isAvailable();-- const storageType = this.configService.get<'local' | 's3'>('storage.type', 'local');- // Read the key StorageService actually uses (`storage.localPath`, default `./data/media`).- // The old `storage.path` key never existed, so status always reported the `./uploads` fallback.- const storagePath = this.configService.get<string>('storage.localPath', './data/media');- // In S3 mode the local path is unused; surface the bucket so the status panel shows the real- // backend. `path` is kept (additive) so the dashboard's local-mode rendering is unchanged.- const storageBucket = this.configService.get<string>('storage.s3.bucket');-- const engineType = this.configService.get<string>('engine.type', 'whatsapp-web.js');- // whatsapp-web.js only: surface the actual WhatsApp Web build (not the library version) so the- // dashboard shows which build is running. Trigger the auto-resolve so the panel is populated even- // before a session starts; the result is cached, so this is a one-time fetch. (#488)- let webVersion: string | null | undefined;- let webVersionSource: 'pinned' | 'auto' | 'native' | undefined;- if (engineType === 'whatsapp-web.js') {- // Kick the auto-resolve but DON'T await it — /infra/status is polled frequently and the registry- // fetch can take up to 5s on a firewalled host. Read whatever's cached now (null until the first- // success); a later poll reflects the resolved build. (#488 review)- if (getEffectiveWebVersionInfo().source === 'auto') {- void resolveCurrentWebVersion().catch(() => undefined);- }- const info = getEffectiveWebVersionInfo();- webVersion = info.version;- webVersionSource = info.source;- }- // configuration.ts nests these under engine.puppeteer.{headless,args}; the old flat- // engine.headless / engine.browserArgs keys never existed, so status always reported defaults.- const engineHeadless = this.configService.get<boolean>('engine.puppeteer.headless', true) ?? true;- const sessionDataPath = this.configService.get<string>('engine.sessionDataPath', './data/sessions');- const browserArgs =- this.configService.get<string[]>('engine.puppeteer.args')?.join(' ') || '--no-sandbox --disable-gpu';-- // Built-in detection: prefer the actually-running bundled container as truth (so a stopped/missing- // container, or a host-pinned external host, reads as NOT built-in), and require the app to be- // pointed at the bundled service. Fall back to the saved *_BUILTIN intent when Docker is- // unreachable (bare-npm / socket-less) so the toggles don't spuriously flip off. (#488)- const s3Endpoint = this.configService.get<string>('storage.s3.endpoint');- const running = this.dockerService.isDockerAvailable()- ? await this.dockerService.getRunningBuiltinServices()- : null;- const savedBuiltin = this.readSavedBuiltinFlags();- const dbBuiltIn = running ? running.database && dbHost === 'postgres' : savedBuiltin.database;- const redisBuiltIn = running ? running.cache && redisHost === 'redis' : savedBuiltin.cache;- const storageBuiltIn = running ? running.storage && s3Endpoint === 'http://minio:9000' : savedBuiltin.storage;- // Re-probe (throttled) so a MinIO/S3 that came up after boot is reflected, not latched unreachable.- const s3Available = storageType === 's3' ? await this.storageService.refreshS3Availability() : undefined;-- // Live webhook-queue depth (the only real queue). pending = waiting + active + delayed. Degrades to- // zeros when the queue is disabled or Redis is unreachable, so the panel never errors the status read.- let webhooks = { pending: 0, completed: 0, failed: 0 };- if (queueEnabled && this.webhookQueue) {- try {- const counts = await this.webhookQueue.getJobCounts('wait', 'active', 'delayed', 'completed', 'failed');- webhooks = {- pending: (counts.wait ?? 0) + (counts.active ?? 0) + (counts.delayed ?? 0),- completed: counts.completed ?? 0,- failed: counts.failed ?? 0,- };- } catch (error) {- this.logger.warn('Failed to read webhook queue job counts', { error: String(error) });- }- }-- return {- database: { connected: dbConnected, type: dbType, host: dbHost, builtIn: dbBuiltIn },- redis: {- enabled: redisEnabled,- connected: redisConnected,- host: redisHost,- port: redisPort,- builtIn: redisBuiltIn,- },- queue: {- enabled: queueEnabled,- webhooks,- },- storage: {- type: storageType,- path: storagePath,- ...(storageType === 's3' && storageBucket ? { bucket: storageBucket } : {}),- builtIn: storageBuiltIn,- ...(storageType === 's3' ? { s3Available } : {}),- },- engine: {- type: engineType,- headless: engineHeadless,- sessionDataPath,- browserArgs,- ...(engineType === 'whatsapp-web.js' ? { webVersion, webVersionSource } : {}),- },- };- }-- /** Saved built-in intent flags from data/.env.generated — the fallback when Docker isn't reachable. */- private readSavedBuiltinFlags(): { database: boolean; cache: boolean; storage: boolean } {- try {- const saved = readGeneratedEnv();- return {- database: saved.POSTGRES_BUILTIN === 'true',- cache: saved.REDIS_BUILTIN === 'true',- storage: saved.MINIO_BUILTIN === 'true',- };- } catch {- return { database: false, cache: false, storage: false };- }- }-- @Get('engines')- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Get available WhatsApp engines' })- @ApiResponse({ status: 200, description: 'List of available engines' })- getEngines(): Array<{ id: string; name: string; enabled: boolean; features: string[] }> {- return this.engineFactory.getAvailableEngines();- }-- @Get('engines/current')- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Get current active engine' })- @ApiResponse({ status: 200, description: 'Current engine info' })- getCurrentEngine(): { engineType: string } {- return { engineType: this.engineFactory.getCurrentEngine() };- }-- @Get('config')- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Read the saved infrastructure configuration for the dashboard form' })- @ApiResponse({ status: 200, description: 'Saved configuration (secrets omitted)' })- getConfig(): SavedConfigResponse {- const saved = readGeneratedEnv();-- // Secrets (passwords, S3 keys) are never returned; the form shows a "set" indicator- // and an empty submission preserves the stored value (see saveConfig). This lets the- // dashboard hydrate the form so a save no longer overwrites unseen fields (#226).- return {- database: {- type: saved.DATABASE_TYPE === 'postgres' ? 'postgres' : 'sqlite',- builtIn: saved.POSTGRES_BUILTIN === 'true',- host: saved.DATABASE_HOST || '',- port: saved.DATABASE_PORT || '',- username: saved.DATABASE_USERNAME || '',- database: saved.DATABASE_NAME || '',- schema: saved.POSTGRES_SCHEMA || 'public',- poolSize: Number(saved.DATABASE_POOL_SIZE) || 10,- sslEnabled: saved.DATABASE_SSL === 'true',- sslRejectUnauthorized: saved.DATABASE_SSL_REJECT_UNAUTHORIZED !== 'false',- passwordSet: Boolean(saved.DATABASE_PASSWORD),- },- redis: {- enabled: saved.REDIS_ENABLED === 'true',- builtIn: saved.REDIS_BUILTIN === 'true',- host: saved.REDIS_HOST || '',- port: saved.REDIS_PORT || '',- passwordSet: Boolean(saved.REDIS_PASSWORD),- },- queue: { enabled: saved.QUEUE_ENABLED === 'true' },- storage: {- type: saved.STORAGE_TYPE === 's3' ? 's3' : 'local',- builtIn: saved.MINIO_BUILTIN === 'true',- localPath: saved.STORAGE_LOCAL_PATH || '',- s3Bucket: saved.S3_BUCKET || '',- s3Region: saved.S3_REGION || '',- s3Endpoint: saved.S3_ENDPOINT || '',- s3CredentialsSet: Boolean(saved.S3_ACCESS_KEY_ID && saved.S3_SECRET_ACCESS_KEY),- },- engine: {- type: saved.ENGINE_TYPE || 'whatsapp-web.js',- headless: saved.PUPPETEER_HEADLESS !== 'false',- sessionDataPath: saved.SESSION_DATA_PATH || '',- browserArgs: saved.PUPPETEER_ARGS || '',- },- };- }-- @Put('config')- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Save infrastructure configuration to .env file' })- @ApiResponse({ status: 200, description: 'Configuration saved' })- @ApiBody({ description: 'Configuration to save', type: SaveConfigDto })- saveConfig(@Body() config: SaveConfigDto): { message: string; saved: boolean; envPath: string; profiles: string[] } {- try {- const profiles: string[] = [];-- // Merge into the existing saved config rather than rebuilding from scratch, so a- // partial payload (the dashboard only sends the sections it renders) cannot wipe- // keys it didn't include (#226). The merge is per-section AND per-key: an absent- // section leaves that section's keys alone, and within a present section an absent- // field (`undefined`) leaves its stored key alone — only values actually submitted- // are written. `existing` below is therefore the base for every key the payload- // does not mention.- const envPath = generatedEnvPath();- const existing = readGeneratedEnv();- const updates: Record<string, string> = {};- // Keys to remove from the merged result — used to drop stale settings when the- // user switches mode (postgres->sqlite, s3->local, built-in->external) so a reload- // never sees the new mode alongside leftover keys from the old one.- const staleKeys = new Set<string>();-- // Secret values are never echoed back to the form, so an empty submission means- // "unchanged" — keep whatever is already stored instead of blanking it.- const setSecret = (key: string, value: string | undefined): void => {- if (value) updates[key] = value;- };-- // Database. NOTE: these keys must match what src/config/configuration.ts reads.- if (config.database) {- updates.DATABASE_TYPE = config.database.type || 'sqlite';- if (config.database.builtIn !== undefined) {- updates.POSTGRES_BUILTIN = config.database.builtIn ? 'true' : 'false';- }- // The effective mode: an explicit builtIn wins; when it is absent the saved mode- // is inherited so a partial payload stays in the current mode instead of silently- // flipping to external.- const dbBuiltIn = config.database.builtIn ?? existing.POSTGRES_BUILTIN === 'true';- if (config.database.type === 'postgres') {- if (dbBuiltIn) {- // Built-in PostgreSQL - use container name as host- updates.DATABASE_HOST = 'postgres';- updates.DATABASE_PORT = '5432';- updates.DATABASE_USERNAME = 'openwa';- // The bundled credential is only the DEFAULT. Secrets are never echoed back to the form,- // so an absent password field means "unchanged", not "reset to 'openwa'" — and the- // dashboard ALWAYS sends builtIn, so keying the reset on "explicit builtIn:true" reset a- // re-keyed container on every save from the Infrastructure page.- // What decides it is whether the stored password belongs to this same bundled container:- // it does when the previous mode was already built-in. Coming from external, the stored- // value is the external DB's credential and must not be carried into the container.- const storedPassword = existing.POSTGRES_BUILTIN === 'true' ? existing.DATABASE_PASSWORD : undefined;- updates.DATABASE_PASSWORD = config.database.password || storedPassword || 'openwa';- updates.DATABASE_NAME = 'openwa';- // Built-in Postgres is initialized with the default 'public' schema (see- // scripts/postgres-init-schema.sh). Pin it so a later switch from a custom-schema- // external DB to built-in doesn't carry a stale POSTGRES_SCHEMA forward.- updates.POSTGRES_SCHEMA = 'public';- profiles.push('postgres');- } else {- // External PostgreSQL. Flipping built-in -> external must not carry the bundled- // 'openwa' password into the external config: the production boot guard rejects- // it, so the next boot would crash-loop. A password in the same payload wins.- if (- config.database.builtIn === false &&- existing.POSTGRES_BUILTIN === 'true' &&- !config.database.password- ) {- staleKeys.add('DATABASE_PASSWORD');- }- if (config.database.host !== undefined) updates.DATABASE_HOST = config.database.host || 'localhost';- if (config.database.port !== undefined) updates.DATABASE_PORT = config.database.port || '5432';- if (config.database.username !== undefined)- updates.DATABASE_USERNAME = config.database.username || 'postgres';- setSecret('DATABASE_PASSWORD', config.database.password);- if (config.database.database !== undefined) updates.DATABASE_NAME = config.database.database || 'openwa';- if (config.database.schema !== undefined) updates.POSTGRES_SCHEMA = config.database.schema || 'public';- }- if (config.database.poolSize !== undefined) {- updates.DATABASE_POOL_SIZE = String(config.database.poolSize || 10);- }- if (config.database.sslEnabled !== undefined) {- updates.DATABASE_SSL = config.database.sslEnabled ? 'true' : 'false';- if (config.database.sslEnabled) {- // Default to certificate verification; only relax it when the operator opts out- // (managed Postgres with self-signed certs: Supabase, Heroku, Render, Railway).- updates.DATABASE_SSL_REJECT_UNAUTHORIZED =- config.database.sslRejectUnauthorized === false ? 'false' : 'true';- }- }- } else {- // Switching to sqlite: drop stale postgres connection keys, and reset the built-in- // flag with them — there is no bundled Postgres backing a SQLite database.- updates.POSTGRES_BUILTIN = 'false';- for (const k of [- 'DATABASE_HOST',- 'DATABASE_PORT',- 'DATABASE_USERNAME',- 'DATABASE_PASSWORD',- 'DATABASE_NAME',- 'DATABASE_POOL_SIZE',- 'DATABASE_SSL',- 'DATABASE_SSL_REJECT_UNAUTHORIZED',- 'POSTGRES_SCHEMA',- ]) {- staleKeys.add(k);- }- }- }-- // Redis and queue are independent sections: a payload carrying only one of them must- // not rewrite (or disable) the other's saved keys.- if (config.redis) {- if (config.redis.enabled !== undefined) updates.REDIS_ENABLED = config.redis.enabled ? 'true' : 'false';- if (config.redis.builtIn !== undefined) updates.REDIS_BUILTIN = config.redis.builtIn ? 'true' : 'false';- if (config.redis.builtIn === true) {- // Built-in Redis - use container name as host. The bundled container runs without- // auth, so a password saved by an earlier external setup is stale: leaving it- // would make the client AUTH against a passwordless server on the next boot.- updates.REDIS_HOST = 'redis';- updates.REDIS_PORT = '6379';- if (!config.redis.password) staleKeys.add('REDIS_PASSWORD');- } else {- // External Redis (explicit, or inherited when builtIn is absent)- if (config.redis.host !== undefined) updates.REDIS_HOST = config.redis.host || 'localhost';- if (config.redis.port !== undefined) updates.REDIS_PORT = config.redis.port || '6379';- }- setSecret('REDIS_PASSWORD', config.redis.password);- const redisEnabled = config.redis.enabled ?? existing.REDIS_ENABLED === 'true';- const redisBuiltIn = config.redis.builtIn ?? existing.REDIS_BUILTIN === 'true';- if (redisEnabled && redisBuiltIn) {- profiles.push('redis');- }- }- if (config.queue) {- if (config.queue.enabled !== undefined) updates.QUEUE_ENABLED = config.queue.enabled ? 'true' : 'false';- }-- // Storage. NOTE: STORAGE_LOCAL_PATH / S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY are- // the names configuration.ts reads (previously saved as STORAGE_PATH / S3_*_KEY and- // silently ignored — #226).- if (config.storage) {- updates.STORAGE_TYPE = config.storage.type || 'local';- if (config.storage.builtIn !== undefined) {- updates.MINIO_BUILTIN = config.storage.builtIn ? 'true' : 'false';- }- if (config.storage.type === 'local') {- // Switching to local: drop stale S3 keys, and reset the built-in flag with them —- // there is no bundled MinIO backing a local storage path.- updates.MINIO_BUILTIN = 'false';- if (config.storage.localPath !== undefined) {- updates.STORAGE_LOCAL_PATH = config.storage.localPath || './data/media';- }- // Switching to local: drop stale S3 keys.- for (const k of ['S3_ENDPOINT', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'S3_BUCKET', 'S3_REGION']) {- staleKeys.add(k);- }- } else if (config.storage.type === 's3') {- staleKeys.add('STORAGE_LOCAL_PATH');- if (config.storage.builtIn === true) {- // Built-in MinIO - use container name as endpoint- updates.S3_ENDPOINT = 'http://minio:9000';- updates.S3_ACCESS_KEY_ID = 'minioadmin';- updates.S3_SECRET_ACCESS_KEY = 'minioadmin';- updates.S3_BUCKET = 'openwa';- updates.S3_REGION = 'us-east-1';- profiles.push('minio');- } else {- // External S3/MinIO. Flipping built-in -> external must not carry the bundled- // 'minioadmin' credentials or the internal endpoint into the external config:- // the production boot guard rejects those credentials (crash-loop), and a stale- // MinIO endpoint would send AWS-bound traffic to the wrong host. Values in the- // same payload win.- if (config.storage.builtIn === false && existing.MINIO_BUILTIN === 'true') {- if (!config.storage.s3AccessKey) staleKeys.add('S3_ACCESS_KEY_ID');- if (!config.storage.s3SecretKey) staleKeys.add('S3_SECRET_ACCESS_KEY');- if (!config.storage.s3Endpoint) staleKeys.add('S3_ENDPOINT');- }- if (config.storage.s3Bucket !== undefined) updates.S3_BUCKET = config.storage.s3Bucket;- if (config.storage.s3Region !== undefined) updates.S3_REGION = config.storage.s3Region || 'ap-southeast-1';- setSecret('S3_ACCESS_KEY_ID', config.storage.s3AccessKey);- setSecret('S3_SECRET_ACCESS_KEY', config.storage.s3SecretKey);- if (config.storage.s3Endpoint !== undefined) {- // Unlike the credentials, the endpoint IS echoed back to the form, so an empty- // submission is a real "clear it" (moving to the default AWS endpoint), not- // "unchanged" — leaving a stale MinIO endpoint behind would silently keep- // pointing S3 traffic at the old host.- if (config.storage.s3Endpoint) {- updates.S3_ENDPOINT = config.storage.s3Endpoint;- } else {- staleKeys.add('S3_ENDPOINT');- }- }- }- }- }-- // Engine. NOTE: PUPPETEER_HEADLESS / SESSION_DATA_PATH / PUPPETEER_ARGS are the names- // configuration.ts reads (previously saved as ENGINE_* and silently ignored — #226).- if (config.engine) {- // Persist the selected engine so the Infrastructure tile can actually switch engines (the- // active engine was previously only settable via the ENGINE_TYPE env, never from the UI).- if (config.engine.type) {- const validEngineIds = this.engineFactory.getAvailableEngines().map(e => e.id);- if (!validEngineIds.includes(config.engine.type)) {- throw new BadRequestException(`Unknown engine type: ${config.engine.type}`);- }- updates.ENGINE_TYPE = config.engine.type;- }- if (config.engine.headless !== undefined) {- updates.PUPPETEER_HEADLESS = config.engine.headless ? 'true' : 'false';- }- if (config.engine.sessionDataPath !== undefined) {- updates.SESSION_DATA_PATH = config.engine.sessionDataPath || './data/sessions';- }- if (config.engine.browserArgs !== undefined) {- // Must match configuration.ts's PUPPETEER_ARGS default (4 flags). Once compose blank-forwards- // PUPPETEER_ARGS, this saved value wins at runtime — a 2-flag default here would silently drop- // --disable-dev-shm-usage (the Docker /dev/shm tab-crash guard) after any Infrastructure save.- updates.PUPPETEER_ARGS =- config.engine.browserArgs || '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu';- }- }-- // .env.generated is one KEY=value per line, loaded on the next boot. A value carrying a- // line break would write a second line and inject an arbitrary env var the operator never- // set, so refuse any such value before writing anything.- for (const [key, value] of Object.entries(updates)) {- if (/[\r\n]/.test(value)) {- throw new BadRequestException(`Invalid configuration value for ${key}: line breaks are not allowed`);- }- }-- // Existing values are the base; this payload's values win (secrets handled above).- const merged: Record<string, string> = { ...existing, ...updates };- // Drop keys made obsolete by a mode switch (postgres->sqlite, s3->local, built-in->external).- for (const k of staleKeys) {- delete merged[k];- }-- // Save-time production guard. The file is loaded on the NEXT boot, which may run with- // NODE_ENV=production regardless of this process's environment — so evaluate the merged- // result with the very same boot guard (as production) and refuse the save when that boot- // would refuse to start. This is what stops a built-in->external flip with no fresh- // credentials from persisting a config that crash-loops the next production boot.- // Evaluate what that boot would actually SEE, not just what the file holds: load-env.ts- // loads with dotenv override:false, so a value supplied via the container environment- // (compose `environment:`) wins over this file — the precedence the file header documents.- // Without that, a deployment providing DATABASE_PASSWORD & co. through the environment is- // refused on EVERY save even though its boot passes the guard. A blank compose-forwarded- // value counts as unset exactly like clearBlankEnv treats it at boot.- //- // Only a HOST-supplied key may win. load-env also merges .env and data/.env.generated into- // process.env, so reading process.env alone would hand back the very file this save is- // replacing — the guard would then bless a flip by validating the OLD config (a built-in ->- // external switch keeping the bundled 'openwa' password would save cleanly and crash-loop the- // next production boot, the exact case this guard exists for). isOsProvidedEnv separates the- // two using the snapshot load-env takes before either file is loaded.- const bootValue = (key: string): string | undefined => {- const envValue = isOsProvidedEnv(key) ? process.env[key] : undefined;- if (envValue !== undefined && (envValue.trim() !== '' || !BLANK_SHADOWED_ENV_KEYS.includes(key))) {- return envValue;- }- return merged[key];- };- try {- assertNoDefaultSecretsInProduction({- nodeEnv: 'production',- databaseType: bootValue('DATABASE_TYPE'),- databasePassword: bootValue('DATABASE_PASSWORD'),- postgresBuiltIn: bootValue('POSTGRES_BUILTIN'),- databaseHost: bootValue('DATABASE_HOST'),- storageType: bootValue('STORAGE_TYPE'),- s3AccessKey: bootValue('S3_ACCESS_KEY_ID'),- s3SecretKey: bootValue('S3_SECRET_ACCESS_KEY'),- s3Endpoint: bootValue('S3_ENDPOINT'),- minioBuiltIn: bootValue('MINIO_BUILTIN'),- redisPassword: bootValue('REDIS_PASSWORD'),- });- } catch (error) {- const detail = error instanceof Error ? error.message : String(error);- throw new BadRequestException(- `Refusing to save a configuration that would be rejected at production boot. ${detail}`,- );- }- const body = Object.keys(merged)- .sort()- .map(key => `${key}=${merged[key]}`);- const contents = [- '# OpenWA Configuration',- `# Generated at ${new Date().toISOString()}`,- '# Managed via Dashboard > Infrastructure. Values in process env or project .env take precedence.',- '',- ...body,- '',- ].join('\n');-- // Write to data/ so it persists across container restarts. Owner-only (0600): this file holds- // the DB/S3/Redis credentials, so it must not be world-readable between save and next restart.- writeSecretFile(envPath, contents);- this.logger.log('Configuration saved', { envPath });-- // Audit the credential-bearing env mutation. Fire-and-forget (not awaited) so saveConfig stays- // synchronous — its validation rejections must remain synchronous throws the tests assert via- // `.toThrow`. Only section names + Docker profiles are recorded; secret values are never logged.- void this.auditService?.logInfo(AuditAction.INFRA_CONFIG_SAVED, {- metadata: { sections: Object.keys(config ?? {}), profiles },- });-- const profileMsg = profiles.length > 0 ? ` Docker profiles required: ${profiles.join(', ')}.` : '';-- return {- message: `Configuration saved successfully.${profileMsg} Server restart required to apply changes.`,- saved: true,- // Return a cwd-relative path so the response doesn't disclose the absolute host filesystem layout.- envPath: path.relative(process.cwd(), envPath),- profiles,- };- } catch (error) {- // A validation rejection (unknown engine type, or a newline-injected value) is a BadRequestException- // and MUST surface as its real 4xx status, not be masked as an HTTP 200 {saved:false} — a client- // branching on HTTP status alone would otherwise treat rejected input as success. Re-throw any- // HttpException so the Nest layer maps it. A non-HTTP failure (e.g. a writeSecretFile disk/permission- // error) stays a {saved:false} 200, preserving the dashboard's body.saved handling for I/O faults.- if (error instanceof HttpException) {- throw error;- }- return {- message: `Failed to save configuration: ${error instanceof Error ? error.message : 'Unknown error'}`,- saved: false,- envPath: '',- profiles: [],- };- }- }- @Post('restart')- @HttpCode(HttpStatus.OK)- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Request server restart with Docker orchestration' })- @ApiResponse({ status: 200, description: 'Server will restart with new profiles' })- @ApiBody({ required: false, type: RestartDto })- async requestRestart(@Body() body?: RestartDto): Promise<{- message: string;- restarting: boolean;- profiles: string[];- profilesToRemove: string[];- estimatedTime: number;- orchestration?: object;- removal?: object;- }> {- const profiles = body?.profiles || [];- const profilesToRemove = body?.profilesToRemove || [];- let orchestrationResult: object | undefined;- // Teardown is stop-only (see DockerService.stopManagedService): containers are stopped and- // retained for re-enable, never deleted — the result below reports exactly that.- let removalResult: { stopped: string[]; errors: string[] } | undefined;-- this.logger.log('Restart requested', { profiles });- this.logger.log('Profiles to remove', { profilesToRemove });-- // If profiles are specified, orchestrate Docker containers- if (this.dockerService.isDockerAvailable()) {- // Remove only the profiles the Save flow explicitly asked to remove, and never one we're about to- // (re)start. We deliberately do NOT infer teardown from the saved *_BUILTIN flag: the default- // data/.env.generated carries POSTGRES_BUILTIN=false, so a bare compose-profile restart would- // otherwise tear down the very backend the app is running on. (Known minor limitation: switching- // away from a built-in backend and then reloading the page before restarting can leave the old- // container running until the next explicit change.)- // Only ever tear down OpenWA-managed services. An arbitrary profile name (or the empty string)- // would otherwise reach stopManagedService and, via container-name matching, could stop an unrelated- // container — so constrain teardown to the managed allowlist and drop anything else.- const requested = profilesToRemove.filter(p => !profiles.includes(p));- const toRemove = requested.filter(p => MANAGED_DOCKER_PROFILES.includes(p));- const ignored = requested.filter(p => !MANAGED_DOCKER_PROFILES.includes(p));- if (ignored.length > 0) {- this.logger.warn('Ignoring non-managed profiles in profilesToRemove', { ignored });- }-- // First, stop containers for disabled services (stop-only: retained, never deleted)- if (toRemove.length > 0) {- this.logger.log('Stopping disabled profiles (containers retained)...', { toRemove });- removalResult = { stopped: [], errors: [] };-- for (const profile of toRemove) {- try {- const success = await this.dockerService.stopManagedService(profile);- if (success) {- removalResult.stopped.push(profile);- } else {- removalResult.errors.push(`Failed to stop ${profile}`);- }- } catch (err) {- removalResult.errors.push(`Error stopping ${profile}: ${err}`);- }- }- this.logger.log('Teardown result', { removalResult });- }-- // Then, start containers for enabled services. Start shares the SAME managed allowlist as- // teardown above: a non-managed name reaching orchestrateProfiles could, via container-name- // matching, select an unrelated host container, so constrain start to the managed profiles too- // and drop anything else. (DockerService already hard-prefixes openwa-<service> and filters on- // the com.openwa.service label, so this is defense-in-depth, not the sole control.)- const toStart = profiles.filter(p => MANAGED_DOCKER_PROFILES.includes(p));- const ignoredStart = profiles.filter(p => !MANAGED_DOCKER_PROFILES.includes(p));- if (ignoredStart.length > 0) {- this.logger.warn('Ignoring non-managed profiles in profiles', { ignoredStart });- }- if (toStart.length > 0) {- this.logger.log('Orchestrating enabled profiles...');- orchestrationResult = await this.dockerService.orchestrateProfiles(toStart);- this.logger.log('Orchestration result', { orchestrationResult });- }- } else {- this.logger.warn('Docker not available, writing signal file instead');- // Fallback: write signal file for host script — but apply the SAME managed-profile- // constraint as the Docker path above: the external consumer of this file must never be- // handed a profile name the in-process path would have refused.- try {- const signalFile = path.resolve(process.cwd(), 'data', '.orchestration-request.json');- const toStart = profiles.filter(p => MANAGED_DOCKER_PROFILES.includes(p));- const toRemove = profilesToRemove.filter(p => !profiles.includes(p) && MANAGED_DOCKER_PROFILES.includes(p));- const ignored = [...profiles, ...profilesToRemove].filter(p => !MANAGED_DOCKER_PROFILES.includes(p));- if (ignored.length > 0) {- this.logger.warn('Ignoring non-managed profiles in the signal-file request', { ignored });- }- const orchestrationRequest = {- timestamp: new Date().toISOString(),- profiles: toStart,- profilesToRemove: toRemove,- action: 'restart-with-profiles',- };- fs.writeFileSync(signalFile, JSON.stringify(orchestrationRequest, null, 2), 'utf8');- this.logger.log('Orchestration request written', { signalFile });- } catch (err) {- this.logger.error('Failed to write orchestration request', err instanceof Error ? err.message : String(err));- }- }-- // Record the operational action (Docker orchestration + scheduled restart) BEFORE starting the- // shutdown, awaited so the row is persisted even as the process goes down.- await this.auditService?.logInfo(AuditAction.INFRA_RESTART_REQUESTED, {- metadata: { profiles, profilesToRemove },- });-- // Schedule graceful shutdown after the configurable bounded grace (SHUTDOWN_DELAY_MS,- // default 3s) — readiness reports 503 during the window so traffic drains first.- void this.shutdownService.shutdown();-- // Calculate estimated time - base 15s + additional for each service (increased for reliability)- let estimatedTime = 15;- if (profiles.includes('postgres')) estimatedTime += 20;- if (profiles.includes('redis')) estimatedTime += 13;- if (profiles.includes('minio')) estimatedTime += 15;- if (profilesToRemove.length > 0) estimatedTime += profilesToRemove.length * 5; // +5s per removal-- return {- message:- profiles.length > 0 || profilesToRemove.length > 0- ? `Server is restarting. Enabling: ${profiles.join(', ') || 'none'}. Disabling: ${profilesToRemove.join(', ') || 'none'}.`- : 'Server is restarting. Please wait...',- restarting: true,- profiles,- profilesToRemove,- estimatedTime,- orchestration: orchestrationResult,- removal: removalResult,- };- }-- @Get('health')- @Public()- @ApiOperation({ summary: 'Health check endpoint' })- @ApiResponse({ status: 200, description: 'Server is healthy' })- healthCheck(): { status: string; timestamp: string } {- return {- status: 'ok',- timestamp: new Date().toISOString(),- };- }-- @Get('export-data')- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Export all data from Data DB for migration' })- @ApiResponse({ status: 200, description: 'Exported data as JSON' })- async exportData(): Promise<{- exportedAt: string;- dataDbType: string;- tables: MigrationTables;- counts: {- sessions: number;- webhooks: number;- messages: number;- messageBatches: number;- templates: number;- baileysStoredMessages: number;- lidMappings: number;- pluginInstances: number;- conversationMappings: number;- ingressEvents: number;- webhookDeliveryFailures: number;- integrationDeliveryFailures: number;- statusUpdates: number;- };- /** Optional tables that were skipped because they genuinely do not exist in this DB (older schema). */- skippedTables: string[];- }> {- // Get all entities from Data DB- const sessions = await this.dataDataSource.query<SessionRow[]>('SELECT * FROM sessions');- const webhooks = await this.dataDataSource.query<WebhookRow[]>('SELECT * FROM webhooks');-- // The tables below may legitimately not exist yet (created by migrations an older DB has not run).- // Only a GENUINE missing-table error (isMissingTableError) may be tolerated — anything else (lock,- // I/O, timeout, aborted connection) must FAIL the export. The old blind `catch { debug-log }`- // pattern reported those as "table is empty", producing a 200 "complete" backup that was actually- // partial — which the import then treated as authoritative and DELETEd the missing tables' rows.- // A skipped table is surfaced in `skippedTables` (and logged as a warning) so an operator can tell- // "not migrated yet" apart from "exported empty".- const skippedTables: string[] = [];- const queryOptionalTable = async <T>(table: string): Promise<T[]> => {- try {- return await this.dataDataSource.query<T[]>(`SELECT * FROM ${table}`);- } catch (error) {- if (!isMissingTableError(error)) throw error;- skippedTables.push(table);- this.logger.warn('Optional table does not exist in this DB; exporting without it', { table });- return [];- }- };-- const messages = await queryOptionalTable<MessageRow>('messages');- // Postgres carries a STORED generated tsvector column `body_ts` (FTS) that `SELECT *` picks up.- // It is a server-maintained index artifact, not payload: strip it so backups stay dialect-neutral- // (and small). The import's explicit column list already ignores it in older archives.- for (const row of messages) {- delete row.body_ts;- }- const messageBatches = await queryOptionalTable<MessageBatchRow>('message_batches');- const templates = await queryOptionalTable<TemplateRow>('templates');- const baileysStoredMessages = await queryOptionalTable<BaileysStoredMessageRow>('baileys_stored_messages');- const lidMappings = await queryOptionalTable<LidMappingRow>('lid_mappings');- // Integration Fabric + both DLQs were added after the original migration set; tolerate a genuinely- // absent table (older DB) like the tables above rather than 500-ing the whole export.- const pluginInstances = await queryOptionalTable<PluginInstanceRow>('plugin_instances');- const conversationMappings = await queryOptionalTable<ConversationMappingRow>('conversation_mappings');- const ingressEvents = await queryOptionalTable<IngressEventRow>('ingress_events');- const webhookDeliveryFailures = await queryOptionalTable<WebhookDeliveryFailureRow>('webhook_delivery_failures');- const integrationDeliveryFailures = await queryOptionalTable<IntegrationDeliveryFailureRow>(- 'integration_delivery_failures',- );- const statusUpdates = await queryOptionalTable<StatusUpdateRow>('status_updates');-- const counts = {- sessions: sessions.length,- webhooks: webhooks.length,- messages: messages.length,- messageBatches: messageBatches.length,- templates: templates.length,- baileysStoredMessages: baileysStoredMessages.length,- lidMappings: lidMappings.length,- pluginInstances: pluginInstances.length,- conversationMappings: conversationMappings.length,- ingressEvents: ingressEvents.length,- webhookDeliveryFailures: webhookDeliveryFailures.length,- integrationDeliveryFailures: integrationDeliveryFailures.length,- statusUpdates: statusUpdates.length,- };-- // Audit the full-DB export: this payload carries webhook + plugin-instance secrets, so WHO pulled- // a dump (and the per-table row counts) is exactly the trail C002 was missing. Data itself is never- // logged — only counts.- await this.auditService?.logInfo(AuditAction.INFRA_DATA_EXPORTED, { metadata: { counts } });-- return {- exportedAt: new Date().toISOString(),- dataDbType: this.configService.get<string>('dataDatabase.type', 'sqlite'),- tables: {- sessions,- webhooks,- messages,- messageBatches,- templates,- baileysStoredMessages,- lidMappings,- pluginInstances,- conversationMappings,- ingressEvents,- webhookDeliveryFailures,- integrationDeliveryFailures,- statusUpdates,- },- counts,- skippedTables,- };- }-- @Post('import-data')- @HttpCode(HttpStatus.OK)- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Import data to Data DB (replaces existing data)' })- @ApiBody({- description: 'Exported data from export-data endpoint',- schema: {- type: 'object',- properties: {- force: {- type: 'boolean',- description:- 'Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead.',- },- stopOrphans: {- type: 'boolean',- description:- 'Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path.',- },- tables: {- type: 'object',- properties: {- sessions: { type: 'array' },- webhooks: { type: 'array' },- messages: { type: 'array' },- messageBatches: { type: 'array' },- statusUpdates: { type: 'array' },- },- },- },- },- })- @ApiResponse({ status: 200, description: 'Data imported successfully' })- @ApiResponse({- status: 409,- description:- 'Refused: live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)',- })- async importData(- @Body()- data: {- tables: Partial<MigrationTables>;- force?: boolean;- /**- * Stop the running engines for sessions the backup does not contain, inside this request and- * before the replace runs (best-effort, time-bounded per engine). Supersedes force=true for the- * orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so- * restartRequired stays false on the success path. Without it the pre-existing behavior holds —- * refuse with 409, or proceed with force=true and leave the engines running until restart.- */- stopOrphans?: boolean;- },- ): Promise<{- imported: boolean;- counts: {- sessions: number;- webhooks: number;- messages: number;- messageBatches: number;- templates: number;- baileysStoredMessages: number;- lidMappings: number;- pluginInstances: number;- conversationMappings: number;- ingressEvents: number;- webhookDeliveryFailures: number;- integrationDeliveryFailures: number;- statusUpdates: number;- };- warnings: string[];- /**- * Non-fatal operator-facing messages (e.g. orphan-engine reconciliation details). Distinct from- * warnings: notices never cause a rollback, while warnings make the replace-rollback gate fire.- */- notices: string[];- /** True when live engines were left pointing at sessions this restore removed — restart to stop them. */- restartRequired: boolean;- /** Session ids with a running engine that the restored data no longer contains. */- orphanedEngines: string[];- /** Orphan engines stopped inside this request (only populated when stopOrphans=true was passed). */- stoppedOrphanEngines: string[];- /** Orphan engines whose teardown threw or timed out (Map reconciled regardless; investigate). */- failedOrphanEngines: string[];- }> {- const warnings: string[] = [];-- // Runtime reconciliation, part 1 (pre-flight): the replace below DELETES every session not in the- // backup, but an engine started for such a session keeps running as an unstoppable zombie (the- // session service keys engines by session id, and every stop path goes through the now-missing DB- // row) whose inbound messages land in tables that were just replaced. Three operator-chosen paths:- // - default: refuse with 409 listing the orphan ids;- // - force=true: proceed and leave the engines running until process restart (restartRequired=true);- // - stopOrphans=true: stop each orphan engine inside this request (best-effort, time-bounded,- // isolated per engine) and then proceed — restartRequired stays false on the success path.- // stopOrphans is preferred over force for the orphan case: a force restore that silently leaves- // engines writing into the freshly replaced tables for an unbounded time is the corruption this- // gate exists to prevent, so the explicit-stop path closes that window instead of relying on the- // operator to restart promptly.- const importedSessionIds = new Set((data.tables.sessions ?? []).map(s => s.id));- const orphanedEngines = (this.sessionService?.getActiveSessionIds() ?? []).filter(- id => !importedSessionIds.has(id),- );-- let stoppedOrphanEngines: string[] = [];- let failedOrphanEngines: string[] = [];- let restartRequired = false;-- // notices collect non-fatal operator-facing messages (orphan-engine reconciliation details) that- // must NOT trip the warnings→rollback gate further down. warnings is reserved for per-row import- // failures that make the replace partial and therefore require a rollback.- const notices: string[] = [];-- if (orphanedEngines.length > 0 && data.stopOrphans && this.sessionService) {- // Stop the orphans inside this request, BEFORE the transaction opens. destroyEngineSafely's- // per-engine 10s deadline bounds the worst case (a stuck Chromium cannot wedge the import); the- // engines are reconciled from the Map regardless of teardown outcome.- const result = await this.sessionService.stopOrphanEngines(orphanedEngines);- stoppedOrphanEngines = result.stopped;- failedOrphanEngines = result.failed;- if (failedOrphanEngines.length > 0) {- // Teardown failed for at least one orphan. The Map entry is removed regardless (see- // stopOrphanEngines), so the engine no longer holds a concurrency slot — but its underlying- // Chromium/socket may still be alive and writing into restored tables. Surface the ids and- // flag restartRequired so the operator does not read a clean response as "engines stopped".- restartRequired = true;- notices.push(- `Teardown failed for ${failedOrphanEngines.length} orphan engine(s): ${failedOrphanEngines.join(', ')} ` +- `(removed from the engine registry; a process restart guarantees cleanup).`,- );- }- // Engines still mid-initialization (no Map entry yet) are reported in notRunning: their start()- // self-aborts via the stop mark, but they are not counted as stopped here.- if (result.notRunning.length > 0) {- notices.push(- `${result.notRunning.length} orphan session(s) had no live engine yet (still initializing): ` +- `${result.notRunning.join(', ')} — their start() will self-abort.`,- );- }- } else if (orphanedEngines.length > 0 && !data.force) {- throw new ConflictException(- `Import would orphan ${orphanedEngines.length} running engine(s) for session(s) ` +- `${orphanedEngines.join(', ')} that the backup does not contain. Stop them first, retry with ` +- `stopOrphans=true (stops them inside this request), or retry with force=true ` +- `(a server restart is then required to stop the orphaned engines).`,- );- } else if (orphanedEngines.length > 0 && data.force) {- // Legacy escape hatch: proceed and leave the engines running until restart.- restartRequired = true;- }-- // What the rollback branches below must report about the engines. The transaction can be rolled- // back; the orphan teardown above CANNOT — it ran before the transaction opened and those engines- // are already destroyed. Reporting empty arrays there would tell an operator nothing happened- // while their sessions are down.- //- // restartRequired narrows to the one thing a rollback cannot undo: a FAILED teardown may have left- // a Chromium/socket alive. The two other pre-flight outcomes do not survive the rollback as- // restart-worthy — a cleanly stopped orphan leaves its session row intact (restart it through- // POST /sessions/:id/start), and an engine the force path left running was never orphaned after- // all, because the data it would have been orphaned by is gone.- const engineStateAfterRollback = {- restartRequired: failedOrphanEngines.length > 0,- orphanedEngines,- stoppedOrphanEngines,- failedOrphanEngines,- };-- const queryRunner = this.dataDataSource.createQueryRunner();- await queryRunner.connect();- await queryRunner.startTransaction();-- try {- // Clear existing data (in correct order due to foreign keys). templates and- // baileys_stored_messages FK sessions ON DELETE CASCADE, so the sessions DELETE would clear- // them too; clearing them explicitly first keeps the order correct on engines where the- // cascade is not enforced. Tolerate a genuinely-absent table (isMissingTableError) but let any- // OTHER failure (lock, I/O, aborted tx) propagate to the transaction rollback below — a blind- // `.catch(() => {})` here could otherwise silently commit a MERGED (not replaced) restore on- // SQLite, violating the endpoint's "replaces existing data" contract.- const clearTable = async (table: string): Promise<void> => {- try {- await queryRunner.query(`DELETE FROM ${table}`);- } catch (err) {- if (!isMissingTableError(err)) throw err;- this.logger.debug('Skipped clearing a table that does not exist during import', { table });- }- };- // The INSERTs below are written once, in Postgres' `$N` placeholder form. better-sqlite3 differs- // from the legacy sqlite3 driver on raw queries in two ways: SQLite parses `$N` as a NAMED- // parameter, which cannot be bound from the positional array TypeORM passes through (RangeError),- // and strict binding rejects booleans/undefined — which a Postgres-made backup carries (real- // booleans survive the JSON round-trip). Postgres needs `$N` and binds booleans natively, so both- // rewrites apply only on the SQLite path. Safe: every `$N` below occurs once, in ascending order.- const isPostgres = this.dataDataSource.options.type === 'postgres';- const insert = (text: string, params: unknown[]): Promise<unknown> =>- queryRunner.query(- isPostgres ? text : text.replace(/\$\d+/g, '?'),- isPostgres ? params : params.map(v => (typeof v === 'boolean' ? Number(v) : (v ?? null))),- );- await queryRunner.query('DELETE FROM webhooks');- await clearTable('messages');- await clearTable('message_batches');- await clearTable('templates');- await clearTable('baileys_stored_messages');- // lid_mappings is not a FK to sessions, so the sessions DELETE below won't clear it; clear it- // explicitly so a restore replaces the cache rather than colliding on existing lid PKs.- await clearTable('lid_mappings');- // Integration Fabric + both DLQs: none carry an FK constraint to sessions (sessionId is provenance),- // so clearing them here before the sessions DELETE keeps the replace-semantics complete.- await clearTable('plugin_instances');- await clearTable('conversation_mappings');- await clearTable('ingress_events');- await clearTable('webhook_delivery_failures');- await clearTable('integration_delivery_failures');- // status_updates has no FK to sessions; clear it explicitly so the replace is complete.- await clearTable('status_updates');- await queryRunner.query('DELETE FROM sessions');-- // Import sessions first- let sessionsCount = 0;- if (data.tables.sessions?.length) {- for (const session of data.tables.sessions) {- // A session name becomes the engine auth-directory key, so an unvalidated imported name (this- // path bypasses CreateSessionDto) could traverse the filesystem. Skip + warn instead of- // throwing, so one bad row doesn't 500 the whole restore.- if (!isSafeSessionName(session.name)) {- warnings.push(`Skipped session ${session.id}: unsafe name ${JSON.stringify(session.name)}`);- continue;- }- try {- await insert(- `INSERT INTO sessions (id, name, status, phone, "pushName", config, "proxyUrl", "proxyType", "connectedAt", "lastActiveAt", "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,- [- session.id,- session.name,- session.status,- session.phone,- session.pushName,- typeof session.config === 'string' ? session.config : JSON.stringify(session.config || {}),- session.proxyUrl,- session.proxyType,- session.connectedAt,- session.lastActiveAt,- session.createdAt,- session.updatedAt,- ],- );- sessionsCount++;- } catch (err) {- warnings.push(`Failed to import session ${session.id}: ${err}`);- }- }- }-- // Import webhooks- let webhooksCount = 0;- if (data.tables.webhooks?.length) {- for (const webhook of data.tables.webhooks) {- try {- await insert(- `INSERT INTO webhooks (id, "sessionId", url, events, secret, headers, filters, active, "retryCount", "lastTriggeredAt", "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,- [- webhook.id,- webhook.sessionId,- webhook.url,- typeof webhook.events === 'string' ? webhook.events : JSON.stringify(webhook.events || []),- webhook.secret,- typeof webhook.headers === 'string' ? webhook.headers : JSON.stringify(webhook.headers || {}),- webhook.filters == null- ? null- : typeof webhook.filters === 'string'- ? webhook.filters- : JSON.stringify(webhook.filters),- webhook.active,- webhook.retryCount,- webhook.lastTriggeredAt,- webhook.createdAt,- webhook.updatedAt,- ],- );- webhooksCount++;- } catch (err) {- warnings.push(`Failed to import webhook ${webhook.id}: ${err}`);- }- }- }-- // Import messages (optional)- let messagesCount = 0;- if (data.tables.messages?.length) {- for (const msg of data.tables.messages) {- try {- await insert(- `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", author, "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,- [- msg.id,- msg.sessionId,- msg.waMessageId ?? null,- msg.chatId,- msg.chatName ?? null,- // Rows exported before the author column existed simply restore to NULL (legacy- // behavior) instead of failing the whole import on an unknown key.- msg.author ?? null,- msg.from,- msg.to,- msg.body ?? null,- msg.type,- msg.direction,- msg.timestamp ?? null,- msg.metadata == null- ? null- : typeof msg.metadata === 'string'- ? msg.metadata- : JSON.stringify(msg.metadata),- msg.status,- msg.createdAt,- ],- );- messagesCount++;- } catch (err) {- warnings.push(`Failed to import message ${msg.id}: ${err}`);- }- }- }-- // Import message batches (optional)- let messageBatchesCount = 0;- if (data.tables.messageBatches?.length) {- for (const batch of data.tables.messageBatches) {- try {- await insert(- `INSERT INTO message_batches (id, batch_id, session_id, status, messages, options, progress, results, current_index, created_at, updated_at, started_at, completed_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,- [- batch.id,- batch.batch_id,- batch.session_id,- batch.status,- typeof batch.messages === 'string' ? batch.messages : JSON.stringify(batch.messages ?? []),- batch.options == null- ? null- : typeof batch.options === 'string'- ? batch.options- : JSON.stringify(batch.options),- batch.progress == null- ? null- : typeof batch.progress === 'string'- ? batch.progress- : JSON.stringify(batch.progress),- batch.results == null- ? null- : typeof batch.results === 'string'- ? batch.results- : JSON.stringify(batch.results),- batch.current_index,- batch.created_at,- batch.updated_at,- batch.started_at,- batch.completed_at,- ],- );- messageBatchesCount++;- } catch (err) {- warnings.push(`Failed to import message batch ${batch.id}: ${err}`);- }- }- }-- // Import templates (optional; FK -> sessions, restored above)- let templatesCount = 0;- if (data.tables.templates?.length) {- for (const tpl of data.tables.templates) {- try {- await insert(- `INSERT INTO templates (id, "sessionId", name, body, header, footer, "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,- [- tpl.id,- tpl.sessionId,- tpl.name,- tpl.body,- tpl.header ?? null,- tpl.footer ?? null,- tpl.createdAt,- tpl.updatedAt,- ],- );- templatesCount++;- } catch (err) {- warnings.push(`Failed to import template ${tpl.id}: ${err}`);- }- }- }-- // Import baileys stored messages (optional; FK -> sessions, restored above)- let baileysStoredMessagesCount = 0;- if (data.tables.baileysStoredMessages?.length) {- for (const bsm of data.tables.baileysStoredMessages) {- try {- await insert(- `INSERT INTO baileys_stored_messages (id, "sessionId", "waMessageId", "serializedMessage", "createdAt")- VALUES ($1, $2, $3, $4, $5)`,- [bsm.id, bsm.sessionId, bsm.waMessageId, bsm.serializedMessage, bsm.createdAt],- );- baileysStoredMessagesCount++;- } catch (err) {- warnings.push(`Failed to import baileys stored message ${bsm.id}: ${err}`);- }- }- }-- // Import lid mappings (optional; not a FK, restored as a standalone cache table)- let lidMappingsCount = 0;- if (data.tables.lidMappings?.length) {- for (const lm of data.tables.lidMappings) {- try {- await insert(`INSERT INTO lid_mappings (lid, phone, "sessionId", "updatedAt") VALUES ($1, $2, $3, $4)`, [- lm.lid,- lm.phone ?? null,- lm.sessionId ?? null,- lm.updatedAt,- ]);- lidMappingsCount++;- } catch (err) {- warnings.push(`Failed to import lid mapping ${lm.lid}: ${err}`);- }- }- }-- // Import plugin instances (Integration Fabric config + ingress HMAC secret)- let pluginInstancesCount = 0;- if (data.tables.pluginInstances?.length) {- for (const pi of data.tables.pluginInstances) {- try {- await insert(- `INSERT INTO plugin_instances (id, "pluginId", "instanceId", "sessionScope", secret, "verifyToken", config, enabled, "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,- [- pi.id,- pi.pluginId,- pi.instanceId,- pi.sessionScope,- pi.secret,- pi.verifyToken,- pi.config == null ? null : typeof pi.config === 'string' ? pi.config : JSON.stringify(pi.config),- pi.enabled,- pi.createdAt,- pi.updatedAt,- ],- );- pluginInstancesCount++;- } catch (err) {- warnings.push(`Failed to import plugin instance ${pi.id}: ${err}`);- }- }- }-- // Import conversation mappings (handover state; sessionId is non-FK provenance)- let conversationMappingsCount = 0;- if (data.tables.conversationMappings?.length) {- for (const cm of data.tables.conversationMappings) {- try {- await insert(- `INSERT INTO conversation_mappings (id, "sessionId", "chatId", "pluginId", "instanceId", "providerConversationId", "handoverState", metadata, "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,- [- cm.id,- cm.sessionId,- cm.chatId,- cm.pluginId,- cm.instanceId,- cm.providerConversationId,- cm.handoverState,- cm.metadata == null- ? null- : typeof cm.metadata === 'string'- ? cm.metadata- : JSON.stringify(cm.metadata),- cm.updatedAt,- ],- );- conversationMappingsCount++;- } catch (err) {- warnings.push(`Failed to import conversation mapping ${cm.id}: ${err}`);- }- }- }-- // Import ingress events (durable inbound dedup oracle; payload is JSON). The dispatch-lifecycle- // columns ride along: dropping them would strand a restored 'pending' row (NULL dispatchState is- // never swept by the reconciler) while its dedup key still blocks the provider's retry. Columns- // absent from a pre-lifecycle backup import as NULL/0 — the same "not watched" reading legacy- // rows have by design. dispatchAttempts is NOT NULL, so it coalesces to 0 rather than NULL.- let ingressEventsCount = 0;- if (data.tables.ingressEvents?.length) {- for (const ie of data.tables.ingressEvents) {- try {- await insert(- `INSERT INTO ingress_events (id, "instanceId", "pluginId", "providerDeliveryId", route, payload, "payloadHash", "sessionId", "dispatchState", "dispatchAttempts", "lastDispatchAt", "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,- [- ie.id,- ie.instanceId,- ie.pluginId,- ie.providerDeliveryId,- ie.route,- // A retired (NULL) payload must stay NULL — re-materializing it as '{}' would make a- // slimmed dedup row read as a pending event with an empty body.- ie.payload == null ? null : typeof ie.payload === 'string' ? ie.payload : JSON.stringify(ie.payload),- ie.payloadHash ?? null,- ie.sessionId,- ie.dispatchState ?? null,- ie.dispatchAttempts ?? 0,- ie.lastDispatchAt ?? null,- ie.createdAt,- ],- );- ingressEventsCount++;- } catch (err) {- warnings.push(`Failed to import ingress event ${ie.id}: ${err}`);- }- }- }-- // Import webhook delivery failures (webhook DLQ)- let webhookDeliveryFailuresCount = 0;- if (data.tables.webhookDeliveryFailures?.length) {- for (const wf of data.tables.webhookDeliveryFailures) {- try {- await insert(- `INSERT INTO webhook_delivery_failures (id, "webhookId", "sessionId", event, url, "idempotencyKey", "deliveryId", attempts, "lastStatusCode", "lastError", "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,- [- wf.id,- wf.webhookId,- wf.sessionId,- wf.event,- wf.url,- wf.idempotencyKey,- wf.deliveryId,- wf.attempts,- wf.lastStatusCode,- wf.lastError,- wf.createdAt,- ],- );- webhookDeliveryFailuresCount++;- } catch (err) {- warnings.push(`Failed to import webhook delivery failure ${wf.id}: ${err}`);- }- }- }-- // Import integration delivery failures (inbound + outbound DLQ)- let integrationDeliveryFailuresCount = 0;- if (data.tables.integrationDeliveryFailures?.length) {- for (const df of data.tables.integrationDeliveryFailures) {- try {- await insert(- `INSERT INTO integration_delivery_failures (id, direction, "pluginId", "instanceId", "sessionId", "deliveryId", attempts, "lastError", payload, redriven, "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,- [- df.id,- df.direction,- df.pluginId,- df.instanceId,- df.sessionId,- df.deliveryId,- df.attempts,- df.lastError,- df.payload == null ? null : typeof df.payload === 'string' ? df.payload : JSON.stringify(df.payload),- df.redriven,- df.createdAt,- ],- );- integrationDeliveryFailuresCount++;- } catch (err) {- warnings.push(`Failed to import integration delivery failure ${df.id}: ${err}`);- }- }- }-- // Import status updates (24h-TTL status/story store; sessionId is non-FK provenance)- let statusUpdatesCount = 0;- if (data.tables.statusUpdates?.length) {- for (const su of data.tables.statusUpdates) {- try {- await insert(- `INSERT INTO status_updates (id, "sessionId", "contactJid", "contactName", "contactPushName", "waStatusId", type, caption, "mediaPath", "mediaMimetype", "mediaOmitted", "omitReason", "backgroundColor", font, "postedAt", "expiresAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)`,- [- su.id,- su.sessionId,- su.contactJid,- su.contactName ?? null,- su.contactPushName ?? null,- su.waStatusId,- su.type,- su.caption ?? null,- su.mediaPath ?? null,- su.mediaMimetype ?? null,- su.mediaOmitted ?? false,- su.omitReason ?? null,- su.backgroundColor ?? null,- su.font ?? null,- su.postedAt,- su.expiresAt,- ],- );- statusUpdatesCount++;- } catch (err) {- warnings.push(`Failed to import status update ${su.id}: ${err}`);- }- }- }-- const counts = {- sessions: sessionsCount,- webhooks: webhooksCount,- messages: messagesCount,- messageBatches: messageBatchesCount,- templates: templatesCount,- baileysStoredMessages: baileysStoredMessagesCount,- lidMappings: lidMappingsCount,- pluginInstances: pluginInstancesCount,- conversationMappings: conversationMappingsCount,- ingressEvents: ingressEventsCount,- webhookDeliveryFailures: webhookDeliveryFailuresCount,- integrationDeliveryFailures: integrationDeliveryFailuresCount,- statusUpdates: statusUpdatesCount,- };-- // "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if any- // INSERT failed we must roll back (restoring the pre-import data) rather than commit a- // half-wiped DB and report success. A partial restore reported as imported:true was how- // message history could silently vanish on a SQLite->Postgres migration.- if (warnings.length > 0) {- await queryRunner.rollbackTransaction();- return {- imported: false,- counts,- warnings,- notices,- ...engineStateAfterRollback,- };- }-- // A wrong/empty/garbage backup file restores zero rows but the DELETE already ran — committing- // would silently WIPE the database and report success. Refuse it and roll back instead. (#488 review)- const totalRestored = Object.values(counts).reduce((sum, n) => sum + n, 0);- if (totalRestored === 0) {- await queryRunner.rollbackTransaction();- return {- imported: false,- counts,- warnings: ['Backup contained no rows to restore; refused to replace existing data. Check the file.'],- notices,- ...engineStateAfterRollback,- };- }-- await queryRunner.commitTransaction();-- // Runtime reconciliation, part 2 (post-commit): the in-memory lid->phone mirror was warmed from- // the OLD lid_mappings rows and is write-through only, so the just-restored table would never- // reach it — resolution would keep serving stale entries (and miss restored ones) until the next- // process start. Reload from the new DB contents. Best-effort: a miss falls back to engine- // re-resolution, so a reload failure degrades instead of failing the (already committed) import.- await this.lidMappingStore?.reload();-- // Audit the destructive replace-all restore, only on the committed-success path (the rollback /- // refused-empty branches above return without emitting, since no data actually changed). Any- // warnings would have taken the rollback branch, so warnings.length is always 0 here — record- // only the per-table counts.- await this.auditService?.logInfo(AuditAction.INFRA_DATA_IMPORTED, { metadata: { counts } });-- // restartRequired was computed in the pre-flight: true only when orphans were left running- // (force=true legacy path) or when stopOrphans teardown failed for at least one engine.- return {- imported: true,- counts,- warnings,- notices,- restartRequired,- orphanedEngines,- stoppedOrphanEngines,- failedOrphanEngines,- };- } catch (error) {- await queryRunner.rollbackTransaction();- throw error;- } finally {- await queryRunner.release();- }- }-- // ============================================================================- // STORAGE MIGRATION API- // ============================================================================-- @Get('storage/files/count')- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Get file count in current storage' })- @ApiResponse({ status: 200, description: 'File count and size' })- async getStorageFileCount(): Promise<{- storageType: string;- count: number;- sizeBytes: number;- sizeMB: string;- }> {- const { count, sizeBytes } = await this.storageService.getFileCount();- return {- storageType: this.storageService.getCurrentStorageType(),- count,- sizeBytes,- sizeMB: (sizeBytes / 1024 / 1024).toFixed(2),- };- }-- @Get('storage/export')- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Export all storage files as tar.gz' })- @ApiResponse({ status: 200, description: 'Tar.gz archive stream' })- async exportStorage(): Promise<{ message: string; download: string }> {- // Note: In production, this would return a StreamableFile- // For simplicity, we'll save to a temp file and return the path- const stream = await this.storageService.createExportStream();- // Keep the export INSIDE data/ (under data/exports/): the import handler only accepts paths under- // data/, and the documented backend-migration flow re-imports this file AFTER a container restart,- // so it must live on the persistent volume — the OS temp dir is wiped on restart. The original- // unbounded-accumulation leak is addressed by the TTL sweep below + a collision-proof filename- // (a per-call UUID), not by relocating off the volume.- const exportDir = path.join(process.cwd(), 'data', 'exports');- if (!fs.existsSync(exportDir)) {- fs.mkdirSync(exportDir, { recursive: true });- }- const exportPath = path.join(exportDir, `storage-export-${Date.now()}-${randomUUID()}.tar.gz`);-- const writeStream = fs.createWriteStream(exportPath);- stream.pipe(writeStream);-- await new Promise<void>((resolve, reject) => {- writeStream.on('finish', resolve);- writeStream.on('error', reject);- // pipe() does NOT forward source errors: an archiver/gzip failure surfaces as an 'error' event on- // the source stream, which without a listener crashes the process. Fail the request instead and- // tear down the sink so its fd isn't held open waiting for a 'finish' that never comes.- stream.on('error', (err: Error) => {- writeStream.destroy();- reject(err);- });- });-- // Sweep the throwaway archive so repeated exports don't accumulate on the data volume.- const ttlRaw = Number.parseInt(process.env.STORAGE_EXPORT_TTL_MS ?? '', 10);- const ttlMs = Number.isInteger(ttlRaw) && ttlRaw > 0 ? ttlRaw : 60 * 60 * 1000; // default 1h- setTimeout(() => {- fs.promises.unlink(exportPath).catch(() => undefined);- }, ttlMs).unref();-- // cwd-relative rather than an absolute host path: doesn't leak the filesystem layout, and the- // import round-trip still works because importStorage's existsSync/createReadStream resolve a- // relative filePath against the same cwd this was made relative to.- const download = path.relative(process.cwd(), exportPath);-- // Audit the bulk media-export (all stored files leave the box as one archive).- await this.auditService?.logInfo(AuditAction.INFRA_STORAGE_EXPORTED, { metadata: { download } });-- return {- message: 'Storage export completed',- download,- };- }-- @Post('storage/import')- @HttpCode(HttpStatus.OK)- @RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Import storage files from tar.gz' })- @ApiBody({ description: 'Path to tar.gz file to import' })- @ApiResponse({ status: 200, description: 'Import result' })- async importStorage(- @Body() body: ImportStorageDto,- ): Promise<{ imported: boolean; count: number; storageType: string }> {- const { filePath } = body;-- // `filePath` is fully caller-controlled. Restrict it to the app's data- // directory so it cannot point at arbitrary files on the host. Resolve once against the- // same cwd-relative base used by exportStorage, then use that exact path for both the guard- // and the file sink.- const dataDir = path.join(process.cwd(), 'data');- const resolved = path.resolve(process.cwd(), filePath || '');- if (!filePath || !isPathWithin(dataDir, resolved)) {- throw new BadRequestException('filePath must reference a file inside the data directory');- }-- if (!fs.existsSync(resolved)) {- throw new BadRequestException(`File not found: ${filePath}`);- }-- const readStream = fs.createReadStream(resolved);- // importFromStream rejects on archive/gzip/read failures (its streams carry error listeners, so a- // bad file fails the request instead of crashing the process on an unhandled 'error' event). The- // failures that reach here are almost always a problem with the caller-supplied file (not a gzip,- // not a tar, unreadable, over the resource caps), so surface them as a 400 with the real reason- // rather than an opaque 500.- let count: number;- try {- count = await this.storageService.importFromStream(readStream);- } catch (error) {- throw new BadRequestException(`Storage import failed: ${error instanceof Error ? error.message : String(error)}`);- }- const storageType = this.storageService.getCurrentStorageType();-- // Audit the bulk media-import (files written into the active storage backend).- await this.auditService?.logInfo(AuditAction.INFRA_STORAGE_IMPORTED, {- metadata: { count, storageType },- });-- return {- imported: true,- count,- storageType,- };- }-}diff --git a/src/modules/infra/infra.module.ts b/src/modules/infra/infra.module.tsindex 6f0f37b04..8678eb577 100644--- a/src/modules/infra/infra.module.ts+++ b/src/modules/infra/infra.module.ts@@ -1,11 +1,14 @@import { Module, DynamicModule, Type } from '@nestjs/common';-import { InfraController } from './infra.controller';+import { InfraStatusController } from './infra-status.controller';+import { InfraConfigController } from './infra-config.controller';+import { InfraDataController } from './infra-data.controller';+import { InfraStorageController } from './infra-storage.controller';import { EngineModule } from '../../engine/engine.module';import { DockerModule } from '../docker';import { SessionModule } from '../session/session.module';// Only import QueueModule if explicitly enabled to avoid Redis connection errors. It registers and-// exports the webhook queue, which the controller injects (@Optional) to report live job counts.+// exports the webhook queue, which InfraStatusController injects (@Optional) to report live job counts.const queueModules: Array<Type | DynamicModule> = [];if (process.env.QUEUE_ENABLED === 'true') {// eslint-disable-next-line @typescript-eslint/no-require-imports@@ -14,9 +17,9 @@ if (process.env.QUEUE_ENABLED === 'true') {}@Module({- // SessionModule gives the controller the live-engine registry for the import pre-flight orphan- // check. Its own imports (WebhookModule, StatusStoreModule) never point back here — no cycle.+ // SessionModule gives InfraDataController the live-engine registry for the import pre-flight+ // orphan check. Its own imports (WebhookModule, StatusStoreModule) never point back here — no cycle.imports: [EngineModule, DockerModule, SessionModule, ...queueModules],- controllers: [InfraController],+ controllers: [InfraStatusController, InfraConfigController, InfraDataController, InfraStorageController],})export class InfraModule {}