Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): make config writes section-scoped, mode-aware, and strictly coerced (#946)
Yudhi Armyndharis277637275782
diff --git a/src/modules/infra/dto/save-config.dto.spec.ts b/src/modules/infra/dto/save-config.dto.spec.tsnew file mode 100644index 000000000..db5c59add--- /dev/null+++ b/src/modules/infra/dto/save-config.dto.spec.ts@@ -0,0 +1,90 @@+import 'reflect-metadata';+import { plainToInstance } from 'class-transformer';+import { validate } from 'class-validator';+import { SaveConfigDto } from './save-config.dto';++// Mirrors the real pipe: whitelist + forbidNonWhitelisted, and the enableImplicitConversion+// transform option from src/config/app-validation.ts. A form-encoded (urlencoded) body delivers+// every scalar as a string; without the strict transforms the implicit cast turns ANY non-empty+// string — including 'false' — into `true`, so an unchecked Infrastructure toggle would persist+// 'true' into data/.env.generated and be applied on the next boot.+const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };+const PIPE_VALIDATOR_OPTS = { whitelist: true, forbidNonWhitelisted: true };++async function run(payload: unknown) {+ const instance = plainToInstance(SaveConfigDto, payload as object, PIPE_TRANSFORM_OPTS);+ const errors = await validate(instance, PIPE_VALIDATOR_OPTS);+ return { instance, errors };+}++// Every boolean field on the save-config DTO, with the section keys its parent requires.+const BOOLEAN_FIELDS: Array<{ section: 'database' | 'redis' | 'queue' | 'storage' | 'engine'; field: string }> = [+ { section: 'database', field: 'builtIn' },+ { section: 'database', field: 'sslEnabled' },+ { section: 'database', field: 'sslRejectUnauthorized' },+ { section: 'redis', field: 'enabled' },+ { section: 'redis', field: 'builtIn' },+ { section: 'queue', field: 'enabled' },+ { section: 'storage', field: 'builtIn' },+ { section: 'engine', field: 'headless' },+];++const SECTION_BASE: Record<string, Record<string, unknown>> = {+ database: { type: 'postgres' },+ redis: {},+ queue: {},+ storage: { type: 'local' },+ engine: {},+};++describe('SaveConfigDto strict coercion', () => {+ it.each(BOOLEAN_FIELDS.map(f => [`${f.section}.${f.field}`, f] as const))(+ "%s maps a form-encoded 'false' to a real false",+ async (_label, { section, field }) => {+ const { instance, errors } = await run({ [section]: { ...SECTION_BASE[section], [field]: 'false' } });+ expect(errors).toHaveLength(0);+ const sectionValue = instance[section] as unknown as Record<string, unknown>;+ expect(sectionValue[field]).toBe(false);+ },+ );++ it.each(BOOLEAN_FIELDS.map(f => [`${f.section}.${f.field}`, f] as const))(+ "%s maps a form-encoded 'true' to a real true",+ async (_label, { section, field }) => {+ const { instance, errors } = await run({ [section]: { ...SECTION_BASE[section], [field]: 'true' } });+ expect(errors).toHaveLength(0);+ const sectionValue = instance[section] as unknown as Record<string, unknown>;+ expect(sectionValue[field]).toBe(true);+ },+ );++ it.each(+ BOOLEAN_FIELDS.flatMap(f =>+ ['yes', '0'].map(spelling => [`${f.section}.${f.field} (${JSON.stringify(spelling)})`, f, spelling] as const),+ ),+ )('%s is rejected instead of being guessed', async (_label, { section, field }, spelling) => {+ const { errors } = await run({ [section]: { ...SECTION_BASE[section], [field]: spelling } });+ expect(errors.length).toBeGreaterThan(0);+ });++ it('accepts real booleans untouched', async () => {+ const { instance, errors } = await run({+ queue: { enabled: false },+ engine: { headless: true },+ });+ expect(errors).toHaveLength(0);+ expect(instance.queue?.enabled).toBe(false);+ expect(instance.engine?.headless).toBe(true);+ });++ it("rejects a blank poolSize (Number('') is 0 — a real value the caller never sent)", async () => {+ const { errors } = await run({ database: { type: 'postgres', poolSize: '' } });+ expect(errors.length).toBeGreaterThan(0);+ });++ it('maps a numeric poolSize string to a number', async () => {+ const { instance, errors } = await run({ database: { type: 'postgres', poolSize: '25' } });+ expect(errors).toHaveLength(0);+ expect(instance.database?.poolSize).toBe(25);+ });+});diff --git a/src/modules/infra/dto/save-config.dto.ts b/src/modules/infra/dto/save-config.dto.tsnew file mode 100644index 000000000..767e0e1b5--- /dev/null+++ b/src/modules/infra/dto/save-config.dto.ts@@ -0,0 +1,210 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { Type } from 'class-transformer';+import { IsBoolean, IsIn, IsNumber, IsOptional, IsString, ValidateNested } from 'class-validator';+import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';++/**+ * Body for PUT /infra/config (saveConfig). Every section is optional: an absent section leaves the+ * stored keys for that section untouched, and within a section an absent field leaves its stored+ * key untouched — a partial payload only changes what it explicitly carries.+ *+ * Booleans use @ToStrictBoolean (and poolSize @ToStrictNumber) because the global ValidationPipe+ * runs with enableImplicitConversion: a form-encoded body delivers scalars as strings, and+ * class-transformer's implicit cast turns ANY non-empty string — including 'false' — into `true`+ * before @IsBoolean() ever runs. Without the strict transform, saving the Infrastructure form+ * URL-encoded would persist 'true' for every unchecked toggle. Only 'true'/'false'/real booleans+ * are accepted; any other spelling is rejected 400.+ */+export class DatabaseConfigDto {+ @ApiProperty({ enum: ['sqlite', 'postgres'] })+ @IsIn(['sqlite', 'postgres'])+ type!: 'sqlite' | 'postgres';++ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ builtIn?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ host?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ port?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ username?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ password?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ database?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ schema?: string;++ @ApiPropertyOptional()+ @ToStrictNumber()+ @IsOptional()+ @IsNumber()+ poolSize?: number;++ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ sslEnabled?: boolean;++ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ sslRejectUnauthorized?: boolean;+}++export class RedisConfigDto {+ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ enabled?: boolean;++ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ builtIn?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ host?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ port?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ password?: string;+}++export class QueueConfigDto {+ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ enabled?: boolean;+}++export class StorageConfigDto {+ @ApiProperty({ enum: ['local', 's3'] })+ @IsIn(['local', 's3'])+ type!: 'local' | 's3';++ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ builtIn?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ localPath?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3Bucket?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3Region?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3AccessKey?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3SecretKey?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3Endpoint?: string;+}++export class EngineConfigDto {+ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ type?: string;++ @ApiPropertyOptional()+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ headless?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ sessionDataPath?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ browserArgs?: string;+}++export class SaveConfigDto {+ @ApiPropertyOptional({ type: () => DatabaseConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => DatabaseConfigDto)+ database?: DatabaseConfigDto;++ @ApiPropertyOptional({ type: () => RedisConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => RedisConfigDto)+ redis?: RedisConfigDto;++ @ApiPropertyOptional({ type: () => QueueConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => QueueConfigDto)+ queue?: QueueConfigDto;++ @ApiPropertyOptional({ type: () => StorageConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => StorageConfigDto)+ storage?: StorageConfigDto;++ @ApiPropertyOptional({ type: () => EngineConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => EngineConfigDto)+ engine?: EngineConfigDto;+}diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex a7fecc2b7..f7ca89c84 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -29,7 +29,10 @@ jest.mock('fs', () => {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';@@ -220,18 +223,20 @@ describe('InfraController.saveConfig SSL reject-unauthorized', () => {}it('writes DATABASE_SSL_REJECT_UNAUTHORIZED=false for self-signed managed Postgres', () => {- const env = writtenEnv({ database: { type: 'postgres', sslEnabled: true, sslRejectUnauthorized: false } });+ 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 } });+ 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 } });+ const env = writtenEnv({ database: { type: 'postgres', sslEnabled: false, password: 'unit-test-pw' } });expect(env).not.toContain('DATABASE_SSL_REJECT_UNAUTHORIZED');});});@@ -261,13 +266,22 @@ describe('InfraController PostgreSQL schema (POSTGRES_SCHEMA)', () => {}it('writes POSTGRES_SCHEMA for external Postgres', () => {- const env = written({ database: { type: 'postgres', builtIn: false, host: 'db', schema: 'openwa' } });+ const env = written({+ database: { type: 'postgres', builtIn: false, host: 'db', schema: 'openwa', password: 'unit-test-pw' },+ });expect(env).toContain('POSTGRES_SCHEMA=openwa');});- it('defaults POSTGRES_SCHEMA to public for external Postgres when no schema is provided', () => {- const env = written({ database: { type: 'postgres', builtIn: false, host: 'db' } });- expect(env).toContain('POSTGRES_SCHEMA=public');+ 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', () => {@@ -494,6 +508,599 @@ describe('InfraController.saveConfig engine selection (persist ENGINE_TYPE — I});});+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');+ });+});++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;diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex b2b3fe0a2..f366909f6 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -11,9 +11,8 @@ import {HttpStatus,Optional,} from '@nestjs/common';-import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { Type } from 'class-transformer';-import { IsArray, IsBoolean, IsIn, IsNumber, IsOptional, IsString, ValidateNested } from 'class-validator';+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';@@ -37,6 +36,8 @@ 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 * as fs from 'fs';import * as path from 'path';import { randomUUID } from 'crypto';@@ -65,190 +66,10 @@ interface InfraStatus {};}-class DatabaseConfigDto {- @ApiProperty({ enum: ['sqlite', 'postgres'] })- @IsIn(['sqlite', 'postgres'])- type!: 'sqlite' | 'postgres';-- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- builtIn?: boolean;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- host?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- port?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- username?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- password?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- database?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- schema?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsNumber()- poolSize?: number;-- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- sslEnabled?: boolean;-- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- sslRejectUnauthorized?: boolean;-}--class RedisConfigDto {- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- enabled?: boolean;-- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- builtIn?: boolean;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- host?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- port?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- password?: string;-}--class QueueConfigDto {- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- enabled?: boolean;-}--class StorageConfigDto {- @ApiProperty({ enum: ['local', 's3'] })- @IsIn(['local', 's3'])- type!: 'local' | 's3';-- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- builtIn?: boolean;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- localPath?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- s3Bucket?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- s3Region?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- s3AccessKey?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- s3SecretKey?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- s3Endpoint?: string;-}--class EngineConfigDto {- @ApiPropertyOptional()- @IsOptional()- @IsString()- type?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsBoolean()- headless?: boolean;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- sessionDataPath?: string;-- @ApiPropertyOptional()- @IsOptional()- @IsString()- browserArgs?: string;-}--class SaveConfigDto {- @ApiPropertyOptional({ type: () => DatabaseConfigDto })- @IsOptional()- @ValidateNested()- @Type(() => DatabaseConfigDto)- database?: DatabaseConfigDto;-- @ApiPropertyOptional({ type: () => RedisConfigDto })- @IsOptional()- @ValidateNested()- @Type(() => RedisConfigDto)- redis?: RedisConfigDto;-- @ApiPropertyOptional({ type: () => QueueConfigDto })- @IsOptional()- @ValidateNested()- @Type(() => QueueConfigDto)- queue?: QueueConfigDto;-- @ApiPropertyOptional({ type: () => StorageConfigDto })- @IsOptional()- @ValidateNested()- @Type(() => StorageConfigDto)- storage?: StorageConfigDto;-- @ApiPropertyOptional({ type: () => EngineConfigDto })- @IsOptional()- @ValidateNested()- @Type(() => EngineConfigDto)- engine?: EngineConfigDto;-}+// 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] })@@ -778,15 +599,19 @@ export class InfraController {// 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).+ // 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 = path.resolve(process.cwd(), 'data', '.env.generated');const existing: Record<string, string> = fs.existsSync(envPath)? dotenv.parse(fs.readFileSync(envPath, 'utf8')): {};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) so a reload never sees the new- // mode alongside leftover keys from the old one.+ // 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@@ -798,9 +623,15 @@ export class InfraController {// Database. NOTE: these keys must match what src/config/configuration.ts reads.if (config.database) {updates.DATABASE_TYPE = config.database.type || 'sqlite';- updates.POSTGRES_BUILTIN = config.database.builtIn ? 'true' : 'false';+ 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 (config.database.builtIn) {+ if (dbBuiltIn) {// Built-in PostgreSQL - use container name as hostupdates.DATABASE_HOST = 'postgres';updates.DATABASE_PORT = '5432';@@ -813,24 +644,40 @@ export class InfraController {updates.POSTGRES_SCHEMA = 'public';profiles.push('postgres');} else {- // External PostgreSQL- updates.DATABASE_HOST = config.database.host || 'localhost';- updates.DATABASE_PORT = config.database.port || '5432';- updates.DATABASE_USERNAME = config.database.username || 'postgres';+ // 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);- updates.DATABASE_NAME = config.database.database || 'openwa';- updates.POSTGRES_SCHEMA = config.database.schema || 'public';+ 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);}- updates.DATABASE_POOL_SIZE = String(config.database.poolSize || 10);- 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';+ 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.+ // 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',@@ -847,24 +694,32 @@ export class InfraController {}}- // Redis / Queue- if (config.redis || config.queue) {- updates.REDIS_ENABLED = config.redis?.enabled ? 'true' : 'false';- updates.REDIS_BUILTIN = config.redis?.builtIn ? 'true' : 'false';- updates.QUEUE_ENABLED = config.queue?.enabled ? 'true' : 'false';- if (config.redis?.enabled) {- if (config.redis.builtIn) {- // Built-in Redis - use container name as host- updates.REDIS_HOST = 'redis';- updates.REDIS_PORT = '6379';- profiles.push('redis');- } else {- // External Redis- updates.REDIS_HOST = config.redis.host || 'localhost';- updates.REDIS_PORT = config.redis.port || '6379';- setSecret('REDIS_PASSWORD', config.redis.password);- }+ // 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@@ -872,16 +727,23 @@ export class InfraController {// silently ignored — #226).if (config.storage) {updates.STORAGE_TYPE = config.storage.type || 'local';- updates.MINIO_BUILTIN = config.storage.builtIn ? 'true' : 'false';+ if (config.storage.builtIn !== undefined) {+ updates.MINIO_BUILTIN = config.storage.builtIn ? 'true' : 'false';+ }if (config.storage.type === 'local') {- updates.STORAGE_LOCAL_PATH = config.storage.localPath || './data/media';+ // 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) {+ if (config.storage.builtIn === true) {// Built-in MinIO - use container name as endpointupdates.S3_ENDPOINT = 'http://minio:9000';updates.S3_ACCESS_KEY_ID = 'minioadmin';@@ -890,13 +752,30 @@ export class InfraController {updates.S3_REGION = 'us-east-1';profiles.push('minio');} else {- // External S3/MinIO- updates.S3_BUCKET = config.storage.s3Bucket || '';- updates.S3_REGION = config.storage.s3Region || 'ap-southeast-1';+ // 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) {- updates.S3_ENDPOINT = config.storage.s3Endpoint;+ 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');+ }}}}@@ -914,13 +793,19 @@ export class InfraController {}updates.ENGINE_TYPE = config.engine.type;}- updates.PUPPETEER_HEADLESS = config.engine.headless !== false ? 'true' : 'false';- updates.SESSION_DATA_PATH = config.engine.sessionDataPath || './data/sessions';- // 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';+ 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@@ -934,10 +819,36 @@ export class InfraController {// 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).+ // 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.+ try {+ assertNoDefaultSecretsInProduction({+ nodeEnv: 'production',+ databaseType: merged.DATABASE_TYPE,+ databasePassword: merged.DATABASE_PASSWORD,+ postgresBuiltIn: merged.POSTGRES_BUILTIN,+ databaseHost: merged.DATABASE_HOST,+ storageType: merged.STORAGE_TYPE,+ s3AccessKey: merged.S3_ACCESS_KEY_ID,+ s3SecretKey: merged.S3_SECRET_ACCESS_KEY,+ s3Endpoint: merged.S3_ENDPOINT,+ minioBuiltIn: merged.MINIO_BUILTIN,+ redisPassword: merged.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]}`);