Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): report effective config values from GET /infra/config
Yudhi Armyndharis690c089725d7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8e6d1fd99..d785eb999 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- `GET /infra/config` now resolves each field with the boot precedence (host environment, then project `.env`, then `data/.env.generated`) instead of reporting only the dashboard-saved file: a deployment setting `ENGINE_TYPE`/`DATABASE_TYPE`/`REDIS_ENABLED` via Compose `environment:` no longer reads back `whatsapp-web.js`/`sqlite`/disabled defaults that contradict the running process (#1313). Values that only ever lived in the saved file still hydrate the form as before, so the "saved, pending restart" state is unchanged, and the dashboard now omits `engine.type` from a save when the seeded value is an environment pin the operator never chose — the stored engine selection survives until the variable is unset (#1082).+### Security- `GET /sessions/:sessionId/status/:statusId/media` now serves `image/svg+xml` status media as an inert download (`application/octet-stream` plus `Content-Disposition: attachment`), matching the chat-media route: SVG is scriptable despite the `image/` prefix, and serving it with its declared Content-Type made the endpoint stored-XSS material on the API origin.diff --git a/dashboard/src/hooks/useInfraConfigForm.ts b/dashboard/src/hooks/useInfraConfigForm.tsindex 4d4e5152e..f595ca663 100644--- a/dashboard/src/hooks/useInfraConfigForm.ts+++ b/dashboard/src/hooks/useInfraConfigForm.ts@@ -207,17 +207,15 @@ export function useInfraConfigForm(if (infraStatus && savedConfig) formHydrated.current = true;}, [infraStatus, savedConfig]);- // Seed the radio from the SAVED engine, once, and never after the operator has touched it (#735).+ // Seed the radio once from /config, and never after the operator has touched it (#735).//- // Not from the running engine, which this used to do: the gateway resolves ENGINE_TYPE once at boot,- // so the running value is stale from the moment a change is saved until the server restarts, and it- // is the pinned value outright when an environment variable supplies one. Either way it is a value- // nobody chose here, and because `buildSavePayload` always sends `type` once the radio has seeded,- // the next save of ANY field on this page wrote it back over the operator's saved engine — losing a- // choice that unsetting the variable, or restarting, was supposed to reveal (#1082).- //- // The saved file is the intent; what is actually running is reported by the card badge and, when the- // two differ, named by the card's own notice.+ // /config reports the EFFECTIVE engine: the saved file value while nothing pins ENGINE_TYPE, the+ // pinned value outright when an environment variable supplies one (#1313). Either way the seeded+ // value may be one nobody chose here — the running one is stale from the moment a change is saved+ // until the server restarts — so the seed is display-only: buildSavePayload omits `type` for an+ // untouched seed under a pin, and only an operator click (engineTouched) persists a selection. What+ // is actually running is reported by the card badge and, when the two differ, named by the card's+ // own notice.useEffect(() => {const seed = savedConfig?.engine.type;if (!seed || engineHydrated.current || engineTouched.current) return;@@ -257,11 +255,21 @@ export function useInfraConfigForm(},queue: { enabled: queueEnabled },storage: { ...storageConfig },- // Only send `type` once we actually know it — either the radio seeded from the running engine- // or the operator picked one. If /engines/current never resolved (endpoint down), engineConfig.type- // still holds its useState default, and sending that would persist ENGINE_TYPE and silently flip- // the engine on the next restart. The backend treats an absent `type` as "leave ENGINE_TYPE alone".- engine: engineTypeKnown() ? { ...engineConfig } : { ...engineConfig, type: undefined },+ // Only send `type` once we actually know it — either the radio seeded from /config or the+ // operator picked one. If /config never resolved, engineConfig.type still holds its useState+ // default, and sending that would persist ENGINE_TYPE and silently flip the engine on the next+ // restart. The backend treats an absent `type` as "leave ENGINE_TYPE alone".+ //+ // An untouched seed under a PINNED ENGINE_TYPE counts as unknown too: /config reports the+ // effective (pinned) engine, so the seeded value is the pin, not a choice made here — sending+ // it would bake the pin into data/.env.generated over the operator's stored choice, which+ // unsetting the variable was supposed to reveal (#1082). Pin-ness is read HERE, at save time,+ // not at seed time: the two queries settle independently and the save click always sees the+ // latest /status. An operator click (engineTouched) is a deliberate choice and always sends.+ engine:+ engineTypeKnown() && !(engineHydrated.current && !engineTouched.current && infraStatus?.envPinned?.includes('ENGINE_TYPE'))+ ? { ...engineConfig }+ : { ...engineConfig, type: undefined },});return {diff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.tsindex de6c2cc94..72da8a8fa 100644--- a/dashboard/src/pages/Infrastructure.test.ts+++ b/dashboard/src/pages/Infrastructure.test.ts@@ -406,26 +406,35 @@ test('the pending-restart note survives a successful save', async () => {assert.ok(screen.queryByText(PENDING_RESTART_NOTE), 'the pending-restart note must not vanish once a save succeeds');});-test('the engine radio seeds from the saved engine when ENGINE_TYPE is pinned', async () => {+test('the engine radio seeds from the effective engine when ENGINE_TYPE is pinned', async () => {const { screen, waitFor } = rtl;resetFetchCalls();- overrides = { status: PINNED_STATUS, saved: SAVED_BAILEYS };+ // Under a pin, /config reports the pinned (effective) engine — the value /status also reports —+ // so the stock fixtures (both whatsapp-web.js) model the honest pinned response. The radio must+ // show what actually runs, with the pin note explaining why a save here cannot change it (#1313).+ overrides = { status: PINNED_STATUS };const { container } = renderInfrastructure();await screen.findByText('Database Configuration');await awaitConfigHydrated(container);- // The running engine is the PINNED value, not a choice the operator made, so showing it would- // present the pin as their selection.await waitFor(() =>- assert.equal(engineRadios(container)[1].checked, true, 'expected the saved engine (baileys) to be selected'),+ assert.equal(engineRadios(container)[0].checked, true, 'expected the pinned engine (whatsapp-web.js) to be selected'),+ );+ assert.ok(+ screen.getByText(/Pinned by the environment variable ENGINE_TYPE/, { exact: false }),+ 'the pin note must explain why the radio cannot take effect',);});-test('saving while ENGINE_TYPE is pinned does not write the running engine over the saved one', async () => {+test('saving while ENGINE_TYPE is pinned omits engine.type so the stored choice survives', async () => {const { screen, waitFor, fireEvent } = rtl;resetFetchCalls();- overrides = { status: PINNED_STATUS, saved: SAVED_BAILEYS };+ // The stored ENGINE_TYPE in data/.env.generated is invisible to the dashboard while the pin+ // holds (/config reports the effective engine). The operator never touched the radio here, so+ // the payload must OMIT type: sending the pinned seed would bake the pin over the stored choice,+ // and unsetting the variable later could not restore it (#1082).+ overrides = { status: PINNED_STATUS };const { container } = renderInfrastructure();await screen.findByText('Database Configuration');@@ -433,8 +442,29 @@ test('saving while ENGINE_TYPE is pinned does not write the running engine overfireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));- // The operator never touched the engine here. Persisting the pinned value would destroy the choice- // held in data/.env.generated, so unsetting the variable later could not restore it.+ await waitFor(() => {+ const call = findFetchCall('PUT', '/api/infra/config');+ assert.ok(call, 'expected a PUT to /infra/config');+ const body = call!.body as { engine?: { type?: string } };+ assert.equal(body.engine?.type, undefined, 'an untouched pinned seed must not be persisted');+ });+});++test('an operator engine pick under a pin is deliberate and still saved', async () => {+ const { screen, waitFor, fireEvent } = rtl;+ resetFetchCalls();+ // The pin note says dashboard changes won't APPLY until the variable is unset — it does not say+ // the choice cannot be stored. Clicking a radio is an explicit selection (engineTouched), so it+ // must reach the payload and replace the stored intent for the post-unpin boot.+ overrides = { status: PINNED_STATUS };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitConfigHydrated(container);++ fireEvent.click(engineRadios(container)[1]);+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));+await waitFor(() => {const call = findFetchCall('PUT', '/api/infra/config');assert.ok(call, 'expected a PUT to /infra/config');diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex e1cd9d58b..973164ef4 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5189,7 +5189,7 @@ Get the currently active engine type.#### GET /api/infra/config-Read the saved infrastructure config from `data/.env.generated` (used to hydrate the dashboard form). **Secrets are never returned** — only `*Set`/`*CredentialsSet` booleans indicate that a secret is stored.+Read the effective infrastructure config used to hydrate the dashboard form. Each field resolves with the boot precedence: a value pinned by the host environment (e.g. Compose `environment:`) or the project `.env` wins over `data/.env.generated`, while a key that only ever lived in the saved file reports the freshly-saved value even before a restart applies it ("saved, pending restart"). **Secrets are never returned** — only `*Set`/`*CredentialsSet` booleans indicate that a secret is stored.**Auth:** API key (ADMIN)@@ -5230,7 +5230,7 @@ Read the saved infrastructure config from `data/.env.generated` (used to hydrate}```-When `data/.env.generated` does not exist, empty-string/default values are returned (`schema='public'`, `poolSize=10`, `sslRejectUnauthorized=true`, `engine.type='whatsapp-web.js'`, `headless=true`).+When nothing supplies a key — no pinned environment value and the file absent or silent about it — empty-string/default values are returned (`schema='public'`, `poolSize=10`, `sslRejectUnauthorized=true`, `engine.type='whatsapp-web.js'`, `headless=true`).**Errors:** `401` · `403`diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex dde1c6de9..0f047c9e5 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -1385,7 +1385,7 @@ curl "$BASE/api/infra/engines/current" \#### GET /api/infra/config-Read saved infrastructure config (secrets omitted).+Read effective infrastructure config (secrets omitted) — each field resolves with the boot precedence (environment / `.env` over `data/.env.generated`).```bashcurl "$BASE/api/infra/config" \diff --git a/openapi.json b/openapi.jsonindex b20c627b2..d3e7b4702 100644--- a/openapi.json+++ b/openapi.json@@ -4048,7 +4048,7 @@"parameters": [],"responses": {"200": {- "description": "Saved configuration (secrets omitted)",+ "description": "Effective configuration (secrets omitted)","content": {"application/json": {"schema": {@@ -4058,7 +4058,7 @@}}},- "summary": "Read the saved infrastructure configuration for the dashboard form",+ "summary": "Read the effective infrastructure configuration for the dashboard form","tags": ["infrastructure"]diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.tsindex 97f6f786c..339e16b93 100644--- a/src/modules/infra/infra-config.controller.spec.ts+++ b/src/modules/infra/infra-config.controller.spec.ts@@ -28,7 +28,7 @@ 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';+import { recordOsEnvKeys, recordPinnedEnvKeys } from '../../config/env-precedence';describe('InfraConfigController.saveConfig SSL reject-unauthorized', () => {function writtenEnv(config: unknown): string {@@ -1007,6 +1007,92 @@ describe('InfraConfigController.getConfig (#226)', () => {});});+describe('InfraConfigController.getConfig reflects environment-pinned values (#1313)', () => {+ // A compose `environment:` value outranks data/.env.generated at every boot, so the form must+ // read it back instead of the first-run defaults the file still holds.+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);+ const PINNED_KEYS = ['ENGINE_TYPE', 'DATABASE_TYPE', 'REDIS_ENABLED', 'QUEUE_ENABLED'];+ let savedEnv: Array<[string, string | undefined]>;++ beforeEach(() => {+ savedEnv = PINNED_KEYS.map(k => [k, process.env[k]]);+ for (const k of PINNED_KEYS) delete process.env[k];+ });+ afterEach(() => {+ for (const [k, v] of savedEnv) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ // Restore the permissive snapshot the rest of the file assumes (no snapshot = isEnvPinned+ // false everywhere, which is what the other describes rely on).+ recordPinnedEnvKeys(process.env);+ });++ it('reports host-provided engine/database/redis values over the first-run file defaults', () => {+ // The exact #1313 deployment: everything set via compose environment:, no .env, and the+ // first-run data/.env.generated holding sqlite/false with no ENGINE_TYPE line at all.+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=sqlite\nREDIS_ENABLED=false\n');++ process.env.ENGINE_TYPE = 'baileys';+ process.env.DATABASE_TYPE = 'postgres';+ process.env.REDIS_ENABLED = 'true';+ recordPinnedEnvKeys(process.env);++ const cfg = newController().getConfig();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');++ expect(cfg.engine.type).toBe('baileys');+ expect(cfg.database.type).toBe('postgres');+ expect(cfg.redis.enabled).toBe(true);+ });++ it('a saved-but-not-yet-restarted file value wins over the stale process.env copy', () => {+ // Boot loaded the OLD file value into process.env (override:false), then the dashboard saved a+ // new one. The key is not pinned (it never came from the host or .env), so the freshly saved+ // file must hydrate the form — otherwise it flips back to the pre-save value (#226/#1082).+ recordPinnedEnvKeys({}); // the host supplied nothing; ENGINE_TYPE below came from the file+ process.env.ENGINE_TYPE = 'whatsapp-web.js';+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue('ENGINE_TYPE=baileys\n');++ expect(newController().getConfig().engine.type).toBe('baileys');++ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ });++ it('a blank pinned forward counts as unset, so the file value applies', () => {+ // Compose renders `- KEY=${KEY:-}` as an empty value when the operator set nothing; boot's+ // clearBlankEnv treats it as unset, and the read must agree or the blank would shadow the file.+ recordPinnedEnvKeys({ ENGINE_TYPE: '' });+ process.env.ENGINE_TYPE = '';+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue('ENGINE_TYPE=baileys\n');++ expect(newController().getConfig().engine.type).toBe('baileys');++ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ });++ it('a blank pinned value on a key boot does NOT clear still wins as blank, mirroring the runtime read', () => {+ // QUEUE_ENABLED is not blank-forwarded by compose, so clearBlankEnv leaves a blank host/.env+ // value in place: configuration.ts's `process.env.QUEUE_ENABLED === 'true'` then reads false,+ // and the form must agree instead of falling through to a contradicting file value.+ recordPinnedEnvKeys({ QUEUE_ENABLED: '' });+ process.env.QUEUE_ENABLED = '';+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue('QUEUE_ENABLED=true\n');++ expect(newController().getConfig().queue.enabled).toBe(false);++ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ });+});+describe('InfraConfigController.requestRestart constrains teardown to managed profiles', () => {const buildController = (dockerService: Record<string, unknown>) =>new InfraConfigController(diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.tsindex 9a6bdac8b..b2c482d0c 100644--- a/src/modules/infra/infra-config.controller.ts+++ b/src/modules/infra/infra-config.controller.ts@@ -24,7 +24,7 @@ import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { SaveConfigDto } from './dto/save-config.dto';import { assertNoDefaultSecretsInProduction } from '../../config/bootstrap-security';-import { BLANK_SHADOWED_ENV_KEYS, isOsProvidedEnv } from '../../config/env-precedence';+import { BLANK_SHADOWED_ENV_KEYS, isEnvPinned, isOsProvidedEnv } from '../../config/env-precedence';import * as fs from 'fs';import * as path from 'path';import { generatedEnvPath, readGeneratedEnv } from './generated-env';@@ -109,50 +109,68 @@ export class InfraConfigController {@Get('config')@RequireRole(ApiKeyRole.ADMIN)- @ApiOperation({ summary: 'Read the saved infrastructure configuration for the dashboard form' })- @ApiResponse({ status: 200, description: 'Saved configuration (secrets omitted)', type: InfraConfigResponseDto })+ @ApiOperation({ summary: 'Read the effective infrastructure configuration for the dashboard form' })+ @ApiResponse({ status: 200, description: 'Effective configuration (secrets omitted)', type: InfraConfigResponseDto })getConfig(): SavedConfigResponse {const saved = readGeneratedEnv();+ // A value supplied by the host environment or the project .env outranks data/.env.generated at+ // every boot (load-env's override:false order), so the form must read it back instead of the+ // first-run defaults — otherwise a compose `environment:` deployment shows whatsapp-web.js/sqlite+ // while the process actually runs baileys/postgres (#1313). isEnvPinned's boot snapshot excludes+ // file-sourced keys, so a value that only ever lived in data/.env.generated is NOT pinned and the+ // freshly-saved file still wins over process.env's stale boot-time copy — keeping the+ // "saved, pending restart" form state intact until the reboot applies it (#226/#1082). The blank+ // rule is the same one the save guard's bootValue applies: a blank counts as unset only for the+ // blank-forwarded keys boot's clearBlankEnv clears; elsewhere the runtime reads the blank as-is+ // (configuration.ts's `=== 'true'` checks), so the read must not fall through to the file there.+ const effective = (key: string): string | undefined => {+ const envValue = isEnvPinned(key) ? process.env[key] : undefined;+ if (envValue !== undefined && (envValue.trim() !== '' || !BLANK_SHADOWED_ENV_KEYS.includes(key))) {+ return envValue;+ }+ return saved[key];+ };+// 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).+ // 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),+ type: effective('DATABASE_TYPE') === 'postgres' ? 'postgres' : 'sqlite',+ builtIn: effective('POSTGRES_BUILTIN') === 'true',+ host: effective('DATABASE_HOST') || '',+ port: effective('DATABASE_PORT') || '',+ username: effective('DATABASE_USERNAME') || '',+ database: effective('DATABASE_NAME') || '',+ schema: effective('POSTGRES_SCHEMA') || 'public',+ poolSize: Number(effective('DATABASE_POOL_SIZE')) || 10,+ sslEnabled: effective('DATABASE_SSL') === 'true',+ sslRejectUnauthorized: effective('DATABASE_SSL_REJECT_UNAUTHORIZED') !== 'false',+ passwordSet: Boolean(effective('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),+ enabled: effective('REDIS_ENABLED') === 'true',+ builtIn: effective('REDIS_BUILTIN') === 'true',+ host: effective('REDIS_HOST') || '',+ port: effective('REDIS_PORT') || '',+ passwordSet: Boolean(effective('REDIS_PASSWORD')),},- queue: { enabled: saved.QUEUE_ENABLED === 'true' },+ queue: { enabled: effective('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),+ type: effective('STORAGE_TYPE') === 's3' ? 's3' : 'local',+ builtIn: effective('MINIO_BUILTIN') === 'true',+ localPath: effective('STORAGE_LOCAL_PATH') || '',+ s3Bucket: effective('S3_BUCKET') || '',+ s3Region: effective('S3_REGION') || '',+ s3Endpoint: effective('S3_ENDPOINT') || '',+ s3CredentialsSet: Boolean(effective('S3_ACCESS_KEY_ID') && effective('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 || '',+ type: effective('ENGINE_TYPE') || 'whatsapp-web.js',+ headless: effective('PUPPETEER_HEADLESS') !== 'false',+ sessionDataPath: effective('SESSION_DATA_PATH') || '',+ browserArgs: effective('PUPPETEER_ARGS') || '',},};}