Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: close the gaps a second review found in this branch's own commits
Yudhi Armyndharisfe7e5db96ff8
diff --git a/.env.minimal b/.env.minimalindex d3747fa02..18416d10c 100644--- a/.env.minimal+++ b/.env.minimal@@ -33,13 +33,13 @@ STORAGE_LOCAL_PATH=./data/media# Redis & Queue (disabled for minimal setup)REDIS_ENABLED=false-REDIS_BUILTIN=false+# REDIS_BUILTIN=falseQUEUE_ENABLED=falseCACHE_ENABLED=false# Built-in Docker services (all disabled for minimal setup)-POSTGRES_BUILTIN=false-MINIO_BUILTIN=false+# POSTGRES_BUILTIN=false+# MINIO_BUILTIN=false# API Security (optional for development)# API_MASTER_KEY=your-master-api-key-herediff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex fa74a9e7f..f76737e16 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -507,6 +507,15 @@ jobs:REPO: ${{ github.repository }}run: echo "ref=ghcr.io/${REPO,,}:smoke-${{ github.run_id }}" >> "$GITHUB_OUTPUT"+ # The tag path is the one that promotes to `latest`, so it must not be laxer than the PR gate —+ # the same rule this workflow's own audit step states. ci.yml verifies the root→openwa drop on+ # the built image; without it here, a change leaving Node on uid 0 reaches `latest` through the+ # only path that publishes it.+ - name: Verify the image drops from root to the openwa user+ env:+ IMAGE: ${{ steps.image.outputs.ref }}+ run: OPENWA_SMOKE_IMAGE="$IMAGE" ./scripts/smoke-test-non-root.sh+- name: Boot + liveness check on each architectureenv:IMAGE: ${{ steps.image.outputs.ref }}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b0e19fd85..8e0c8d1e4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The addressbook write guard now checks the id, not just its domain. `parseWaId('NOT A [email protected]').kind` is `'user'`, so free text, letters and an empty user-part cleared the guard, reached the engine and were reported to the caller as a saved contact — for an entry keyed by something that is not a phone number. It now applies `isIndividualWid`, the same predicate the group-participant, channel-admin and message-mention surfaces already use on these very shapes.-- `POST /api/infra/import-data` now answers 400 for a malformed archive instead of 500. A table value that is not an array — a hand-edited or truncated backup — was dereferenced with `.map()` before anything checked it, so the operator was told the server had broken when their file was simply wrong. Checked for every table, not only `sessions`: the rest are read inside the transaction, where the same mistake would fail mid-restore rather than before it opens.+- `POST /api/infra/import-data` now answers 400 for a malformed archive instead of 500. A table value that is not an array — a hand-edited or truncated backup — was dereferenced with `.map()` before anything checked it, so the operator was told the server had broken when their file was simply wrong. Checked for every table, not only `sessions`: the rest are read inside the transaction, where the same mistake would fail mid-restore rather than before it opens. A row that is not an object — `[null]`, a bare string, a nested array — is rejected the same way, instead of passing the array check and dying on its first property read.- README no longer inverts the shipped MCP posture. It described `MCP_ENABLED=true` as exposing 51 tools including messaging, when the surface is read-only unless `MCP_READONLY=false` — a secure default the code chose deliberately — so an operator wired a client, saw no send or group tools, and had nothing in README pointing at the knob. It now states the 25 read-only tools mounted by default and names the opt-in for all 51. A gate derives both counts from the tool sources, so a tier change fails instead of making the prose wrong again.- README's Ports table no longer publishes Swagger unconditionally. The documented production command produces a deployment where `/api/docs` returns 404, and SECURITY.md separately tells operators to review `ENABLE_SWAGGER`, so the two published documents disagreed. The row now states the condition.@@ -34,7 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The cross-node takeover sweep no longer adopts sessions while the process is shutting down. `onModuleDestroy` cleared the interval, which stops the next sweep but does nothing about one already running — it is neither aborted nor awaited, and nothing on the start path consulted a shutting-down signal. On a rolling restart a sweep mid-flight could construct and register an engine after the shutdown path had emptied the registry, and claim the ownership lease for a process about to exit, pinning that session to a dead node until the lease lapsed. The signal is re-checked per adoption, because each one costs a browser launch and the loop spans much of the sweep interval.-- `GET /infra/storage/export` now enumerates the whole store. It listed with `listFiles()`, which stops at `STORAGE_LIST_MAX_FILES` and returns without logging or throwing, so an operator following the documented local→S3 migration — export, repoint `STORAGE_TYPE`, import — silently left media behind on the backend they were about to decommission, and the `files/count` pre-check was truncated by the same code path, so their own consistency check could not reveal it. The export now walks the uncapped `iterateFiles()`, which exists for exactly this: the cap is a per-call guard, not a completeness contract.+- `GET /infra/storage/export` now enumerates the whole store. It listed with `listFiles()`, which stops at `STORAGE_LIST_MAX_FILES` and returns without logging or throwing, so an operator following the documented local→S3 migration — export, repoint `STORAGE_TYPE`, import — silently left media behind on the backend they were about to decommission, and the `files/count` pre-check was truncated by the same code path, so their own consistency check could not reveal it. The export now walks the uncapped `iterateFiles()`, which exists for exactly this: the cap is a per-call guard, not a completeness contract. The `files/count` pre-check an operator runs before that migration walks the same uncapped list, so it can no longer hide the gap it exists to reveal.- An ingress route whose manifest omits `maxBodyBytes` is no longer unbounded by its own cap. The check compared a byte length against `undefined`, which is always false, so the per-route 413 the published contract promises was silently inert — and every accepted delivery is persisted with the body stored twice and carried into the queue, turning one forgotten manifest field into a write amplifier with no load-time error and no runtime signal. A route with no usable value now falls back to the process-wide body limit (what it was already bounded by in practice, so nothing accepted today starts failing) and the gap is logged once per route instead of passing in silence.@@ -54,11 +54,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Bulk send now caps its rendered result at `TEMPLATE_RENDER_MAX_CHARS` (default 64 KiB), the same limit the single-send template path already enforced. `content.text` is length-validated before substitution, so caller-supplied variables inflated each item without bound while the request body stayed far below the in-flight body budget — a few hundred KiB of variables became hundreds of megabytes of heap per item, then went to the engine and the `messages.body` column. An over-cap render now fails that item with a message naming the limit, exactly as a pacing refusal does, rather than being truncated silently or sent.-- The published image's drop from root to the `openwa` user is now verified in CI. The Dockerfile carries no `USER` directive by design — `docker-entrypoint.sh` starts as root to fix named-volume ownership and then runs `exec gosu openwa` — and `scripts/smoke-test-non-root.sh` was the only check of that drop, but no workflow ran it: its sole appearance in `ci.yml` was inside a comment. A change leaving the Node process on uid 0 passed lint, every test job, the multi-arch build and the image scan, and was promoted to `latest`. The Docker job now loads a single-arch image from the cache the multi-arch build already populated and runs the smoke test against it.+- The published image's drop from root to the `openwa` user is now verified in CI. The Dockerfile carries no `USER` directive by design — `docker-entrypoint.sh` starts as root to fix named-volume ownership and then runs `exec gosu openwa` — and `scripts/smoke-test-non-root.sh` was the only check of that drop, but no workflow ran it: its sole appearance in `ci.yml` was inside a comment. A change leaving the Node process on uid 0 passed lint, every test job, the multi-arch build and the image scan, and was promoted to `latest`. The Docker job now loads a single-arch image from the cache the multi-arch build already populated and runs the smoke test against it. The release path checks it too, since that is the path that promotes to `latest`.- The dashboard's dependency tree is now audited on both the PR and the tag path. It went unscanned by every job: `npm audit` ran against the root tree only, and the image scan sees OS packages and the built bundle rather than the npm graph behind it — so a HIGH advisory in a dependency that reaches an operator's browser could ride a release undetected. Two were present at this baseline: `socket.io-parser` (bundled into `dashboard/dist` via `socket.io-client`) and `brace-expansion` (dev-only, via ESLint), the latter pinned to a vulnerable version by an override that had not been bumped. Both are now overridden to patched releases.-- `.env.example` shipped five keys the Infrastructure dashboard owns — `POSTGRES_BUILTIN`, `DATABASE_SSL`, `DATABASE_SSL_REJECT_UNAUTHORIZED`, `REDIS_BUILTIN` and `MINIO_BUILTIN` — uncommented, so an operator who followed the documented `cp .env.example .env` pinned them: the dashboard control still saved and reported success while the running value never changed, most consequentially leaving a Postgres connection unencrypted after the operator enabled SSL. The file's own header already promised a gate against this, but that gate only reached keys docker-compose forwards blank; it now covers every key the dashboard writes.+- `.env.example` shipped five keys the Infrastructure dashboard owns — `POSTGRES_BUILTIN`, `DATABASE_SSL`, `DATABASE_SSL_REJECT_UNAUTHORIZED`, `REDIS_BUILTIN` and `MINIO_BUILTIN` — uncommented, so an operator who followed the documented `cp .env.example .env` pinned them: the dashboard control still saved and reported success while the running value never changed, most consequentially leaving a Postgres connection unencrypted after the operator enabled SSL. The file's own header already promised a gate against this, but that gate only reached keys docker-compose forwards blank; it now covers every key the dashboard writes. `.env.minimal`, the other documented starting point, no longer pins the three built-in datastore toggles either; its deliberate development pins are left alone.- Two enabled instances of one integration plugin that share a session scope no longer collapse onto a single config, so an ingress delivery authenticated with one instance's secret is no longer handled with the credentials of whichever instance was provisioned last. Dispatch now layers the instance's own config over the base config and any per-session override.diff --git a/src/common/ci-privilege-gate.spec.ts b/src/common/ci-privilege-gate.spec.tsindex e67c2d3d1..6158e022e 100644--- a/src/common/ci-privilege-gate.spec.ts+++ b/src/common/ci-privilege-gate.spec.ts@@ -30,8 +30,10 @@ describe('the non-root drop is enforced, not merely documented', () => {expect(runCommandsOf('ci.yml').join('\n')).toContain('smoke-test-backup-restore.sh');});- it('invokes the non-root smoke test from ci.yml', () => {- const invocations = runCommandsOf('ci.yml').filter(run => run.includes('smoke-test-non-root.sh'));+ // BOTH paths. The tag path is the one that promotes to `latest`, so a check present only on the PR+ // path leaves the publishing route unguarded — the asymmetry this workflow's own audit step forbids.+ it.each(['ci.yml', 'release.yml'])('invokes the non-root smoke test from %s', file => {+ const invocations = runCommandsOf(file).filter(run => run.includes('smoke-test-non-root.sh'));expect(invocations.length).toBeGreaterThan(0);});diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex 4bce02636..e87894d63 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -319,7 +319,10 @@ export class StorageService implements OnModuleDestroy {return { count, sizeBytes };}- const files = await this.listFiles();+ // The uncapped walk, for the same reason createExportStream uses it: this is the pre-check an+ // operator runs BEFORE the export/import migration, so a count truncated at STORAGE_LIST_MAX_FILES+ // would hide exactly the gap they are checking for.+ const files = await this.listAllFiles();let sizeBytes = 0;for (const file of files) {try {diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.tsindex 793c9a527..8f30ec748 100644--- a/src/config/bootstrap-security.ts+++ b/src/config/bootstrap-security.ts@@ -173,9 +173,13 @@ export function assertNoDefaultSecretsInProduction(env: SecretCheckEnv): void {// been through boot validation yet and is still an arbitrary string here. Recognising only// 'production' meant every unrecognised value — a `prod` typo, a `staging` deployment — skipped the// guard silently, including the ALLOW_DEV_API_KEY rejection below. Only the two values that are- // deliberately not production (and an unset variable, the standard Node default for local runs)- // skip it; everything else is treated as production. Mirrors shutdown.service.ts's drain window,- // which already fails toward the production behaviour the same way.+ // deliberately not production (and an unset or blank variable, the standard Node default for local+ // runs) skip it; everything else is treated as production.+ //+ // NOTE: unset skips the guard. That is the pre-existing behaviour and is deliberate — a plain+ // `docker run` sets no NODE_ENV, and refusing to start there would break local use — but it does+ // mean a production deployment must set it. shutdown.service.ts makes the OPPOSITE choice for the+ // same variable (unset keeps the production drain window), so this is not a mirror of it.// A blank value means the same here as it does to boot validation, which treats '' as unset:// otherwise `NODE_ENV=` boots clean and then gets production-grade secret enforcement, and the// two halves of this guard disagree about the same string.diff --git a/src/config/env-precedence.spec.ts b/src/config/env-precedence.spec.tsindex 885eb9e05..2ee291e77 100644--- a/src/config/env-precedence.spec.ts+++ b/src/config/env-precedence.spec.ts@@ -289,15 +289,34 @@ describe('every key the dashboard writes is commented out in .env.example', () =expect(viaSecretHelper()).toContain('REDIS_PASSWORD');});- it('ships none of them uncommented', () => {- const example = fs.readFileSync(path.join(__dirname, '../../.env.example'), 'utf8');- const uncommented = example+ const uncommentedKeys = (file: string): string[] =>+ fs+ .readFileSync(path.join(__dirname, '../..', file), 'utf8').split('\n').map(line => /^([A-Z0-9_]+)=/.exec(line)?.[1]).filter((key): key is string => key !== undefined);++ it('ships none of them uncommented in .env.example', () => {+ const uncommented = uncommentedKeys('.env.example');expect(uncommented).toContain('NODE_ENV'); // the file really does ship some keys uncommentedexpect(uncommented.filter(key => dashboardOwned().includes(key))).toEqual([]);});++ /**+ * `.env.minimal` is also copied to `.env` by the docs (docs/README.md), but its rule is NARROWER on+ * purpose: it describes itself as a development/personal config and deliberately pins the choices an+ * operator makes by hand there — DATABASE_TYPE, ENGINE_TYPE, the puppeteer flags. Those pins are the+ * file's reason to exist.+ *+ * The built-in datastore toggles are different: they are pure Dashboard > Infrastructure switches, so+ * pinning them makes the UI control move, save, report success and change nothing — the same trap the+ * .env.example rule exists for.+ */+ it('ships the built-in datastore toggles commented out in .env.minimal', () => {+ const toggles = ['POSTGRES_BUILTIN', 'REDIS_BUILTIN', 'MINIO_BUILTIN'];+ expect(toggles.every(t => dashboardOwned().includes(t))).toBe(true); // control: they ARE dashboard-owned+ expect(uncommentedKeys('.env.minimal').filter(key => toggles.includes(key))).toEqual([]);+ });});/**diff --git a/src/engine/adapters/baileys-contact-blocked.spec.ts b/src/engine/adapters/baileys-contact-blocked.spec.tsindex 0d23779c0..0f81c4620 100644--- a/src/engine/adapters/baileys-contact-blocked.spec.ts+++ b/src/engine/adapters/baileys-contact-blocked.spec.ts@@ -31,7 +31,8 @@ describe('Baileys contact reads report real blocklist state', () => {: jest.fn().mockResolvedValue(opts.blocklist ?? []);const host = {ensureReady: jest.fn(),- getSocket: () => ({ fetchBlocklist }) as unknown as WASocket,+ getSocket: () =>+ ({ fetchBlocklist, updateBlockStatus: jest.fn().mockResolvedValue(undefined) }) as unknown as WASocket,logger: { ...logger, warn },listContacts: () => [contact('[email protected]'), contact('[email protected]')],findContact: (id: string) => contact(id),@@ -72,6 +73,28 @@ describe('Baileys contact reads report real blocklist state', () => {expect(fetchBlocklist).toHaveBeenCalledTimes(1);});+ // The memo must not outlive a change made through this same API: block() and unblock() clear it,+ // and without that a contact just blocked still reads isBlocked=false for the memo window.+ it('re-queries after a block, so a just-changed state is not read stale', async () => {+ const { contacts, fetchBlocklist } = make({ blocklist: [] });+ await contacts.getContactById('[email protected]');+ expect(fetchBlocklist).toHaveBeenCalledTimes(1);++ await contacts.blockContact('[email protected]');+ await contacts.getContactById('[email protected]');++ expect(fetchBlocklist).toHaveBeenCalledTimes(2);+ });++ it('re-queries after an unblock for the same reason', async () => {+ const { contacts, fetchBlocklist } = make({ blocklist: ['[email protected]'] });+ await contacts.getContactById('[email protected]');+ await contacts.unblockContact('[email protected]');+ await contacts.getContactById('[email protected]');++ expect(fetchBlocklist).toHaveBeenCalledTimes(2);+ });+it('does not fail the contact read when the blocklist query does, and says so', async () => {const { contacts, warn } = make({blocklistError: new Error('WhatsApp did not answer the blocklist query in time'),diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex 400d2ca61..49498c93e 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -2019,6 +2019,17 @@ describe('InfraDataController.importData rejects a malformed table value', () =>);});+ // Array.isArray alone let `[null]` through, and the RED comment above claimed this case was+ // covered when it was not — the row then died on its first property read, the same 500 with a+ // longer fuse.+ it.each([+ ['a null row', [null]],+ ['a string row', ['nope']],+ ['a nested array', [[]]],+ ])('answers 400 for %s rather than dying on the first property read', async (_label, rows) => {+ await expect(controller().importData({ tables: { sessions: rows } } as never)).rejects.toThrow(BadRequestException);+ });+it('names the offending table so the operator can fix the file', async () => {await expect(controller().importData({ tables: { messages: 'nope' } } as never)).rejects.toThrow(/messages/);});diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex e71892bda..51ccda99d 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -571,9 +571,16 @@ export class InfraDataController {// archive is simply malformed. Checked for all tables, not just `sessions`: the rest are read// inside the transaction, where the same mistake would fail mid-restore instead of before it.for (const [table, rows] of Object.entries(data.tables ?? {})) {- if (rows !== undefined && !Array.isArray(rows)) {+ if (rows === undefined) continue;+ if (!Array.isArray(rows)) {throw new BadRequestException(`tables.${table} must be an array of rows`);}+ // Array.isArray alone is not enough: `[null]` passes it and then dies on the first property+ // read, which is the same 500 with a longer fuse. Every element must be a row object.+ const badRow = rows.findIndex(row => typeof row !== 'object' || row === null || Array.isArray(row));+ if (badRow !== -1) {+ throw new BadRequestException(`tables.${table}[${badRow}] must be a row object`);+ }}const importedSessionIds = new Set((data.tables.sessions ?? []).map(s => s.id));