Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(status): harden ingest error handling, SSRF settle, and the Docker image
Yudhi Armyndharis19c6676aa9ca
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 905bbb983..56d749f1a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -69,6 +69,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0blocked until the engine type has loaded, so a Baileys post can no longer go out withoutrecipients.+- **A failed status ingest only resolves idempotently on a genuine unique-constraint violation.**+ Previously any save error coinciding with an already-persisted row was swallowed into returning+ that row; other persistence failures (e.g. a locked database) now propagate to the caller.++- **The production Docker image no longer ships the TypeScript build cache.** The incremental+ `tsbuildinfo` pinned inside `dist/` (needed so the dev server's `deleteOutDir` wipes it with the+ output) is deleted at the end of the builder stage instead of being copied into every published+ image.+- **`npm run dev` no longer crashes on the second launch with `Cannot find module '.../dist/main'`.**The TypeScript 6 upgrade moved the incremental build cache (`tsbuildinfo`) out of `dist/` to theproject root, where the dev server's `deleteOutDir` wipe could no longer remove it. On every startdiff --git a/Dockerfile b/Dockerfileindex 98f35606b..1a8e89967 100644--- a/Dockerfile+++ b/Dockerfile@@ -40,7 +40,10 @@ COPY . .# deps - install them explicitly here (npm ci, reproducible from dashboard/package-lock.json).# `--include=dev` for the same reason as above: the dashboard build needs vite/typescript# (devDependencies), which a NODE_ENV=production build env would otherwise omit.-RUN npm run build && npm run dashboard:ci -- --include=dev && npm run dashboard:build+# Drop the incremental-build cache afterwards: it is pinned inside dist/ (so nest's deleteOutDir+# wipes it with the output), and the production stage copies dist/ wholesale — it would otherwise+# ship dead compiler metadata in every image.+RUN npm run build && npm run dashboard:ci -- --include=dev && npm run dashboard:build && rm -f dist/*.tsbuildinfo# ===== Stage 2: Production =====FROM docker.io/node:22-slim AS productiondiff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex 8a735b4b4..e7b63f4a7 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -398,6 +398,48 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {expect(cancel).toHaveBeenCalledTimes(1);});+ it('cancels the unread body BEFORE destroying the dispatcher — the ordering is the fix (#887)', async () => {+ // A refactor swapping the two `finally` steps would re-open the crash path while keeping every+ // call-count assertion green; pin the order explicitly.+ const cancel = jest.fn().mockResolvedValue(undefined);+ const destroy = jest.spyOn(Agent.prototype, 'destroy').mockResolvedValue(undefined);+ try {+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);+ (undiciFetch as jest.Mock).mockResolvedValue({ status: 200, type: 'basic', bodyUsed: false, body: { cancel } });++ await withSafeFetch('https://example.com/hook', {}, () => 'ok', { guard: true });++ expect(cancel).toHaveBeenCalledTimes(1);+ expect(destroy).toHaveBeenCalledTimes(1);+ expect(cancel.mock.invocationCallOrder[0]).toBeLessThan(destroy.mock.invocationCallOrder[0]);+ } finally {+ destroy.mockRestore();+ }+ });++ it('leaves a locked body stream to its reader (cancel on a locked stream would reject)', async () => {+ // A caller that acquired a reader but never read has bodyUsed === false yet a locked stream;+ // the settle must skip it — cancelling someone else's locked stream is not safe.+ const cancel = jest.fn().mockResolvedValue(undefined);+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);+ (undiciFetch as jest.Mock).mockResolvedValue({+ status: 200,+ type: 'basic',+ bodyUsed: false,+ body: { cancel, locked: true },+ });++ await withSafeFetch('https://example.com/hook', {}, () => 'ok', { guard: true });+ expect(cancel).not.toHaveBeenCalled();+ });++ it('tolerates a duck-typed body without a cancel method instead of throwing from the finally', async () => {+ (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);+ (undiciFetch as jest.Mock).mockResolvedValue({ status: 200, type: 'basic', bodyUsed: false, body: {} });++ await expect(withSafeFetch('https://example.com/hook', {}, () => 'ok', { guard: true })).resolves.toBe('ok');+ });+it('swallows a rejection from the dispatcher teardown on the pinned path', async () => {const destroy = jest.spyOn(Agent.prototype, 'destroy').mockRejectedValue(new Error('destroy failed'));try {diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex 8e9f08f16..546ebc576 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -387,7 +387,13 @@ export function validatingLookup(): LookupFunction {* bodies (`bodyUsed`) are left alone so streaming readers (media / plugin downloads) are unaffected.*/async function settleUnreadResponseBody(response: Response): Promise<void> {- if (response.bodyUsed || !response.body) return;+ // bodyUsed only covers *disturbed* streams. A stream the caller locked with getReader() but never+ // read from is not disturbed, and cancel() on a locked stream rejects — such callers must cancel+ // their own reader on error paths, so locked streams are left to them.+ if (response.bodyUsed || !response.body || response.body.locked) return;+ // Guard the call itself: a duck-typed response (e.g. a test mock without cancel) must not throw+ // synchronously from a `finally` and mask the original error.+ if (typeof response.body.cancel !== 'function') return;await response.body.cancel().catch(() => undefined);}diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsindex 1932285c8..c12649246 100644--- a/src/modules/status-store/status-store.service.spec.ts+++ b/src/modules/status-store/status-store.service.spec.ts@@ -273,7 +273,7 @@ describe('StatusStoreService ingest race (unique-constraint loser)', () => {expect(mediaDir()).toHaveLength(0);});- it('keeps the file when the re-read row is this very insert (driver errored on a commit that landed)', async () => {+ it('keeps the file but still rethrows when the re-read row is this very insert (driver errored on a commit that landed)', async () => {const repo = {findOne: jest.fn()@@ -288,16 +288,46 @@ describe('StatusStoreService ingest race (unique-constraint loser)', () => {} as unknown as Repository<StatusUpdate>;const service = new StatusStoreService(repo, storageService, fakeConfigService());- await service.ingest('sess', {- waStatusId: 'raced',- contactJid: '[email protected]',- type: 'image',- media: { mimetype: 'image/jpeg', data: Buffer.from('self').toString('base64') },- postedAt: 1000,- });+ // Not a unique-constraint error, so the failure surfaces even though a row exists — but the+ // file is kept: the re-read row IS this insert, so its media is still referenced.+ await expect(+ service.ingest('sess', {+ waStatusId: 'raced',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', data: Buffer.from('self').toString('base64') },+ postedAt: 1000,+ }),+ ).rejects.toThrow('driver reported failure after commit');expect(mediaDir()).toHaveLength(1);});++ it('rethrows a non-unique save error even when a coincidental winner row exists', async () => {+ fs.mkdirSync(path.join(baseDir, 'media', 'statuses', 'sess'), { recursive: true });+ fs.writeFileSync(path.join(baseDir, 'media', 'statuses', 'sess', 'winner.jpg'), 'winner');+ const winner = new StatusUpdate();+ winner.mediaPath = 'statuses/sess/winner.jpg';+ const repo = {+ findOne: jest.fn().mockResolvedValueOnce(null).mockResolvedValue(winner),+ save: jest.fn().mockRejectedValue(new Error('database is locked')),+ } as unknown as Repository<StatusUpdate>;+ const service = new StatusStoreService(repo, storageService, fakeConfigService());++ // A genuine persistence failure must not be swallowed into an idempotent return just because+ // a matching row happens to exist — and this call's own file is still reaped.+ await expect(+ service.ingest('sess', {+ waStatusId: 'raced',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', data: Buffer.from('loser').toString('base64') },+ postedAt: 1000,+ }),+ ).rejects.toThrow('database is locked');++ expect(mediaDir()).toEqual(['winner.jpg']);+ });});describe('StatusStoreService.purgeExpired', () => {diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.tsindex c277173a5..dde578fd4 100644--- a/src/modules/status-store/status-store.service.ts+++ b/src/modules/status-store/status-store.service.ts@@ -7,6 +7,7 @@ import { StatusUpdate } from './entities/status-update.entity';import type { IncomingStatus } from './incoming-status';import type { Status } from '../../engine/interfaces/whatsapp-engine.interface';import { StorageService } from '../../common/storage/storage.service';+import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';import { createLogger } from '../../common/services/logger.service';/** A status/story lives for 24h from posting, matching WhatsApp's own expiry. Exported for the@@ -86,19 +87,21 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {return { row: await this.repository.save(row), created: true };} catch (error) {// The unique (sessionId, waStatusId) index is the idempotency backstop for a concurrent ingest- // of the same status racing past the findOne check above; the loser re-reads and returns the- // row the winner just inserted instead of surfacing a constraint violation to the caller.+ // of the same status racing past the findOne check above; on a unique-constraint violation the+ // loser re-reads and returns the row the winner just inserted instead of surfacing the+ // constraint error to the caller. Any OTHER save error is a genuine persistence failure and+ // must propagate — never be masked by a coincidentally matching row.const winner = await this.repository.findOne({ where: { sessionId, waStatusId: s.waStatusId } });// This call's row was never saved, so the file attachMedia wrote for it (its own random key)// is referenced by no row, and purgeExpired — which only sweeps expired rows' files — could- // never reap it. Delete it here or a lost race leaks one orphan per race. The guard skips the- // pathological case where the re-read row is this very insert (driver errored on a commit- // that landed): there the file IS the persisted row's media. deleteFile treats an+ // never reap it. Delete it here or a failed ingest leaks one orphan per failure. The guard+ // skips the pathological case where the re-read row is this very insert (driver errored on a+ // commit that landed): there the file IS the persisted row's media. deleteFile treats an// already-missing file as success.if (row.mediaPath && row.mediaPath !== winner?.mediaPath) {await this.storageService.deleteFile(row.mediaPath).catch(() => undefined);}- if (winner) return { row: winner, created: false };+ if (winner && isUniqueConstraintError(error)) return { row: winner, created: false };throw error;}}