Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: three regressions found reviewing this branch
Yudhi Armyndharis276ae2d2aaf7
diff --git a/src/common/storage/storage-transfer.ts b/src/common/storage/storage-transfer.tsindex 7ac16dcca..2e19866e3 100644--- a/src/common/storage/storage-transfer.ts+++ b/src/common/storage/storage-transfer.ts@@ -24,6 +24,15 @@ export async function createExportStream(logger: LoggerService,): Promise<PassThrough> {const files = await listFiles();+ // The importer aborts a whole archive past STORAGE_IMPORT_MAX_ENTRIES. Now that the export is+ // uncapped, a large store can produce one this gateway refuses to restore — and the operator would+ // only find out at restore time, after decommissioning the source. Say it at EXPORT time instead.+ if (files.length > DEFAULT_IMPORT_MAX_ENTRIES) {+ logger.warn(+ `Export contains ${files.length} files, above the import default of ${DEFAULT_IMPORT_MAX_ENTRIES}. ` ++ 'Raise STORAGE_IMPORT_MAX_ENTRIES on the destination before restoring this archive.',+ );+ }const output = new PassThrough();const archive = new TarArchive({diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.tsindex e476ff208..8d4a3ba09 100644--- a/src/core/plugins/plugin-sandbox-bridge.ts+++ b/src/core/plugins/plugin-sandbox-bridge.ts@@ -191,6 +191,14 @@ export class PluginSandboxBridge {// projects both onto the same scope key, so the scope-keyed store alone would hand a delivery// whichever instance was provisioned last. It applies even for a non-session-scoped plugin,// whose instances are otherwise indistinguishable here.+ //+ // PRECEDENCE NOTE: this puts the instance row above the operator's per-session override from+ // PUT /plugins/:id/sessions/:sessionId/config, for the keys the instance itself defines. That is+ // deliberate and cannot be otherwise: provisioning PROJECTS each instance's config into the+ // scope-keyed store, so for two instances sharing a scope that slice holds whichever was written+ // last — applying it on top would hand a delivery the other tenant's credentials again. The+ // override still decides every key the instance does not define, and still decides everything on+ // the hook path. To change an instance's own config, use the instance route.const config = plugin? resolveInstanceConfig(resolvePluginConfig(diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex f7c13aa51..b1dc1c1ce 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -330,6 +330,56 @@ describe('BulkMessageService.processBatch', () => {messages: [{ chatId: '[email protected]', type: 'text', content: { text }, variables }],});+ // The cap must bound the MESSAGE, not the payload. `variables` is a sibling of the media fields on+ // the same DTO, so personalised media is a supported bulk request — and a 100 KB image is ~137,000+ // base64 characters, twice the 64 KiB text cap. Capping every string in the content tree failed+ // exactly the requests this endpoint exists for.+ // The gate has TWO copies (see applySendingGate's doc); the envelope check landed on one of them.+ // A handler returning a truthy object without `input` fed `undefined` into every send below.+ it('fails an item when a message:sending handler returns a payload with no usable input', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ hookManager.execute.mockResolvedValue({ continue: true, data: { notInput: 1 } });++ await runProcessBatch();++ expect(engine.sendTextMessage).not.toHaveBeenCalled();+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { results: BatchMessageResult[] }]>).at(-1)![1];+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);+ expect(finalPartial.results[0].error?.message).toMatch(/message:sending/);+ });++ // Negative twin: a chain that returns nothing is the ordinary no-plugin path.+ it('keeps the original content when the hook chain returns no data', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ hookManager.execute.mockResolvedValue({ continue: true });++ await runProcessBatch();++ expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);+ });++ it('sends a media item with variables even when its base64 exceeds the text cap', async () => {+ const bigBase64 = 'A'.repeat(137_000);+ repo.findOne.mockResolvedValue({+ ...makeBatch(1),+ messages: [+ {+ chatId: '[email protected]',+ type: 'image',+ content: { image: { base64: bigBase64, mimetype: 'image/jpeg' }, caption: 'Hi {{name}}' },+ variables: { name: 'Alice' },+ },+ ],+ });+ engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'wa1', timestamp: 1 });++ await runProcessBatch();++ expect(engine.sendImageMessage).toHaveBeenCalledTimes(1);+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { results: BatchMessageResult[] }]>).at(-1)![1];+ expect(finalPartial.results[0].status).not.toBe(BatchMessageStatus.FAILED);+ });+it('fails an item whose rendered text exceeds the cap instead of sending it', async () => {// Comfortably over the 64 KiB default the un-configured service falls back to.const huge = 'x'.repeat(70 * 1024);diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex c5189b0ed..12e6b64f5 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -467,7 +467,26 @@ export class BulkMessageService implements OnApplicationBootstrap {blockedByPlugin = true;throw new BadRequestException('Message sending blocked by plugin');}- content = (gate.data as { input: BulkMessageContent }).input;+ // Same envelope check as applySendingGate, which this is the second copy of (see its doc).+ // Reading `.input` unchecked handed `undefined` to every send below, or threw on a null — one+ // plugin authoring mistake turning a whole batch into an opaque failure. Fails CLOSED: a+ // moderation handler whose reply cannot be read may have been redacting something.+ const envelope = gate.data as { input?: unknown } | null | undefined;+ if (envelope === undefined) {+ // Nothing changed: keep the content we already had.+ } else if (+ typeof envelope !== 'object' ||+ envelope === null ||+ typeof envelope.input !== 'object' ||+ envelope.input === null+ ) {+ blockedByPlugin = true;+ throw new BadRequestException(+ 'A message:sending handler returned a payload without a usable `input`; the send was refused rather than sent unmoderated',+ );+ } else {+ content = envelope.input;+ }// Re-validate the ACTUAL outbound payload against the media cap: template variables and a// gate rewrite can grow base64 media past the limit createBatch verified on the raw input.@@ -661,15 +680,7 @@ export class BulkMessageService implements OnApplicationBootstrap {// Delegate to the shared renderer so the gateway exposes one templating syntax (#69). It// substitutes canonical `{{name}}` placeholders and still honors the legacy single-brace// `{name}` this endpoint historically used (deprecated — prefer `{{name}}`).- const replaceVars = (str: string): string => {- const rendered = renderTemplate(str, variables);- if (rendered.length > maxChars) {- throw new BadRequestException(- `Rendered content is ${rendered.length} characters, over the ${maxChars}-character limit`,- );- }- return rendered;- };+ const replaceVars = (str: string): string => renderTemplate(str, variables);const processValue = (value: unknown): unknown => {if (typeof value === 'string') {@@ -688,7 +699,23 @@ export class BulkMessageService implements OnApplicationBootstrap {return value;};- return processValue(content) as BulkMessageContent;+ const rendered = processValue(content) as BulkMessageContent;++ // Cap the MESSAGE, not the payload. Substitution runs over the whole content tree (a URL or a+ // filename may carry a placeholder too), but only the text-bearing fields are bounded: `base64`+ // holds media, which `assertBase64WithinMediaCap` governs at up to MEDIA_DOWNLOAD_MAX_BYTES —+ // three orders of magnitude above this cap. Capping every string rejected the most natural bulk+ // request there is, a personalised media send, because a 100 KB image is ~137,000 base64+ // characters.+ for (const field of ['text', 'caption'] as const) {+ const value = rendered[field];+ if (typeof value === 'string' && value.length > maxChars) {+ throw new BadRequestException(+ `Rendered ${field} is ${value.length} characters, over the ${maxChars}-character limit`,+ );+ }+ }+ return rendered;}/**