Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: small correctness + housekeeping cleanups (#434)
Yudhi Armyndharis8b133d70abb5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 33442a9c7..478215ab9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Webhook delivery no longer POSTs an empty (`undefined`) body when a `webhook:before` plugin hook returns a result without a `payload` key — it now falls back to the original payload. (#434)+- The `session.qr` WebSocket event is now actually emitted from the QR callback, so the dashboard can render the QR live instead of only polling `GET /qr`. (#434)+- Storage usage now reports real S3 object sizes instead of a 100KB-per-file estimate, and local file writes no longer block the event loop during an import. (#434)- A sandboxed plugin whose `load`/`onEnable`/`onDisable` hangs no longer blocks the enable/disable request (and the request behind it) indefinitely — plugin lifecycle calls are now time-bounded, and a disable always tears the worker down even if `onDisable` fails, so a misbehaving plugin can't leak its worker thread. (#431)- Sandboxed plugins now receive `onConfigChange` (config updates reach the worker instead of being silently ignored until disable + re-enable) and have their real `healthCheck` run — `GET /plugins/:id/health` previously always returned the default "healthy" for sandboxed plugins. (#430)- Plugin `onDisable` now runs on graceful shutdown (`OnModuleDestroy`), so stateful plugins can flush buffers / close connections / persist state instead of losing in-flight work on every restart or deploy. (#430)diff --git a/src/common/storage/storage.service.spec.ts b/src/common/storage/storage.service.spec.tsindex 89349b786..3d72d6b11 100644--- a/src/common/storage/storage.service.spec.ts+++ b/src/common/storage/storage.service.spec.ts@@ -131,6 +131,35 @@ describe('StorageService put/getFile containment is backend-agnostic', () => {});});+describe('StorageService getFileCount (S3 size)', () => {+ it('sums the real Size of each S3 object instead of estimating', async () => {+ const { service, baseDir } = makeLocalService();+ const sendMock = jest.fn().mockResolvedValue({+ Contents: [+ { Key: 'media/a.jpg', Size: 1000 },+ { Key: 'media/b.jpg', Size: 2500 },+ ],+ });+ const internal = service as unknown as {+ storageType: string;+ s3Client: unknown;+ s3Bucket: string;+ s3Available: boolean;+ };+ internal.storageType = 's3';+ internal.s3Client = { send: sendMock };+ internal.s3Bucket = 'test-bucket';+ internal.s3Available = true;++ const result = await service.getFileCount();++ expect(result.count).toBe(2);+ expect(result.sizeBytes).toBe(3500); // real object sizes, not files.length * 100000++ fs.rmSync(baseDir, { recursive: true, force: true });+ });+});+describe('StorageService import resource caps (decompression-bomb defense)', () => {let baseDir: string;let localPath: string;diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex fda78d595..516bbff21 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -148,27 +148,52 @@ export class StorageService {}async getFileCount(): Promise<{ count: number; sizeBytes: number }> {+ if (this.storageType === 's3' && this.s3Client && this.s3Available) {+ // ListObjectsV2 already returns each object's Size, so report the real total instead of a+ // 100KB-per-file estimate — no extra API calls beyond the listing we'd do anyway.+ return this.getS3CountAndSize();+ }+const files = await this.listFiles();let sizeBytes = 0;-- if (this.storageType === 's3' && this.s3Client && this.s3Available) {- // S3 size would require additional API calls, estimate- sizeBytes = files.length * 100000; // Estimate 100KB per file- } else {- for (const file of files) {- try {- const fullPath = path.join(this.localPath, file);- const stats = fs.statSync(fullPath);- sizeBytes += stats.size;- } catch (error) {- this.logger.debug(`Failed to stat file: ${file}`, { error: String(error) });- }+ for (const file of files) {+ try {+ const fullPath = path.join(this.localPath, file);+ const stats = fs.statSync(fullPath);+ sizeBytes += stats.size;+ } catch (error) {+ this.logger.debug(`Failed to stat file: ${file}`, { error: String(error) });}}return { count: files.length, sizeBytes };}+ private async getS3CountAndSize(): Promise<{ count: number; sizeBytes: number }> {+ let count = 0;+ let sizeBytes = 0;+ let continuationToken: string | undefined;++ do {+ const response = await this.s3Client!.send(+ new ListObjectsV2Command({+ Bucket: this.s3Bucket,+ Prefix: 'media/',+ ContinuationToken: continuationToken,+ }),+ );++ for (const obj of response.Contents ?? []) {+ count += 1;+ sizeBytes += obj.Size ?? 0;+ }++ continuationToken = response.NextContinuationToken;+ } while (continuationToken);++ return { count, sizeBytes };+ }+// ============================================================================// Export - Create tar.gz stream from current storage// ============================================================================@@ -332,19 +357,16 @@ export class StorageService {return fs.promises.readFile(fullPath);}- private putLocalFile(filePath: string, data: Buffer): Promise<void> {+ private async putLocalFile(filePath: string, data: Buffer): Promise<void> {if (!isPathWithin(this.localPath, filePath)) {throw new Error(`Refusing to write outside storage root: ${filePath}`);}const fullPath = path.join(this.localPath, filePath);- const dir = path.dirname(fullPath);-- if (!fs.existsSync(dir)) {- fs.mkdirSync(dir, { recursive: true });- }- fs.writeFileSync(fullPath, data);- return Promise.resolve();+ // Async, non-blocking: a synchronous write here stalls the event loop during an import.+ // mkdir recursive is idempotent, so it doubles as the existsSync check.+ await fs.promises.mkdir(path.dirname(fullPath), { recursive: true });+ await fs.promises.writeFile(fullPath, data);}// ============================================================================diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex 93cd591f1..9989c4776 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -423,7 +423,9 @@ export class DockerService implements OnModuleInit {await container.stop();this.logger.log(`Stopped container: ${profile}`);}- await container.remove({ v: true }); // v: true removes volumes too+ // v: true removes only the container's ANONYMOUS volumes; named datastore volumes+ // (redis/postgres/minio data) are preserved, so disable + re-enable keeps the data.+ await container.remove({ v: true });this.logger.log(`Removed container: ${profile}`);return true;} catch (error) {diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex a2822937f..6878fb474 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -94,6 +94,7 @@ describe('SessionService', () => {emitMessageAck: jest.fn(),emitMessageRevoked: jest.fn(),emitMessageReaction: jest.fn(),+ emitQRCode: jest.fn(),};webhookService = {@@ -1359,6 +1360,21 @@ describe('SessionService', () => {});});+ // ── onQRCode WebSocket emit ───────────────────────────────────────++ describe('onQRCode', () => {+ it('emits the QR over the WebSocket so subscribed clients get it without polling', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const callbacks = (mockEngine.initialize.mock.calls as [EngineEventCallbacks][])[0][0];++ callbacks.onQRCode?.('qr-data-123');++ expect(eventsGateway.emitQRCode).toHaveBeenCalledWith('sess-uuid-1', 'qr-data-123');+ });+ });+// ── deleteChat ────────────────────────────────────────────────────describe('deleteChat', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 0ce514b7f..7fd7433fa 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -463,6 +463,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatvoid this.webhookService.dispatch(id, 'session.qr', { sessionId: id, qr });+ // Push the QR to subscribed dashboard clients over the WebSocket (the `session.qr` event is+ // advertised + consumed there, so clients can render it live instead of polling GET /qr).+ this.eventsGateway.emitQRCode(id, qr);+// Execute hook for QR eventvoid this.hookManager.execute('session:qr',diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 6cbef2ea9..800f72217 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -298,6 +298,27 @@ describe('WebhookService', () => {timeoutSpy.mockRestore();});+ it('falls back to the original payload when a before-hook omits payload (no undefined body)', async () => {+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ // A misbehaving plugin returns continue:true but no `payload` key on the result.+ (hookManager.execute as jest.Mock).mockResolvedValue({+ continue: true,+ data: { sessionId: 'sess-1', event: 'message.received' },+ });++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ expect(mockFetch).toHaveBeenCalled();+ const callArgs = mockFetch.mock.calls[0] as [unknown, { body: string }];+ const body = JSON.parse(callArgs[1].body) as WebhookPayload;+ expect(body).not.toBeUndefined();+ expect(body.event).toBe('message.received');+ expect(body.data).toEqual({ from: '[email protected]' });+ });+it('test() probes the receiver using the configured WEBHOOK_TIMEOUT', async () => {const webhook = createMockWebhook({ events: ['message.received'] });(repository.findOne as jest.Mock).mockResolvedValue(webhook);diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 6a76f4baa..2bd8ca740 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -254,8 +254,9 @@ export class WebhookService {continue;}- // Use potentially modified payload- const finalPayload = (hookResult as { payload: WebhookPayload }).payload;+ // Use the plugin-modified payload, falling back to the original if a before-hook returned a+ // result without a `payload` key — otherwise we'd POST an `undefined` body.+ const finalPayload = (hookResult as { payload?: WebhookPayload }).payload ?? payload;// Build headers — custom headers FIRST so the system headers below always win.const headers: Record<string, string> = {diff --git a/src/plugins/extensions/translation/manifest.json b/src/plugins/extensions/translation/manifest.jsonindex 1542ebc65..f070a3d34 100644--- a/src/plugins/extensions/translation/manifest.json+++ b/src/plugins/extensions/translation/manifest.json@@ -5,7 +5,7 @@"type": "extension","description": "Auto-translates group messages between participants' languages via LibreTranslate. Configure in-group with /tr commands. Disabled by default.","main": "index.ts",- "permissions": ["messages:send"],+ "permissions": ["messages:send", "engine:read"],"sessions": ["*"],"configSchema": {"type": "object",