Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): say why an inbound media download left only the marker
Yudhi Armyndharis49728e9793c5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e5623613f..60921acfa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- JavaScript SDK CI and release jobs install with `--engine-strict` wherever they run the tests, so an unsupported Node fails at install.- The JavaScript SDK smoke check sends requests through both built clients, so the Node 18 CI lane covers the request path.- Retire the whatsapp-web.js download-mimetype install patch; inbound media downloads now pass the mimetype themselves.+- A whatsapp-web.js inbound media download the page answers with nothing logs a warning, and one WhatsApp Web rejects is logged with the rejection's name, message and WhatsApp Web build instead of the minified `t: t`.- Storage import abort messages name the `STORAGE_IMPORT_MAX_BYTES` or `STORAGE_IMPORT_MAX_ENTRIES` setting that stopped them.- CI and the weekly security scan run `npm audit` over the JavaScript SDK, and Dependabot watches its lockfile.- The Baileys linked-device name defaults to `Ubuntu` instead of `OpenWA`, so phone-number pairing works without setting `BAILEYS_BROWSER_NAME`.diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex a7b5f816b..6d4a8f138 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5832,6 +5832,21 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {expect(toBase64).not.toHaveBeenCalled();});+ it.each<[string, { stage?: string; resolvedStage?: string }, string]>([+ ['a page that does not offer the media yet', { stage: 'REUPLOADING' }, 'null'],+ ['media whose resolve step fails', { stage: 'INIT', resolvedStage: 'ERROR_MISSING' }, 'undefined'],+ ])('says why %s leaves the omitted marker', async (_case, page, answer) => {+ pageServing(3, page);+ const warn = jest.spyOn(LoggerService.prototype, 'warn').mockImplementation(() => undefined);++ await expect(cap(understated(runInPage))).resolves.toEqual(expect.objectContaining({ omitted: true }));+ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalledWith(+ 'Inbound media download returned nothing; emitting the omitted marker',+ expect.objectContaining({ msgId: 'M1', answer }),+ );+ });+it('looks the message up by an id the WhatsApp Web build stores under $1', async () => {// A bare `_serialized` read sends the page an empty id, which finds no message and comes back null.pageServing(3);@@ -5889,11 +5904,16 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {});});- it('rethrows any other download error', async () => {- const failure = Object.assign(new Error('boom'), { status: 500 });+ // puppeteer rebuilds a page exception from its class name alone, and WhatsApp Web's classes are minified+ // (`t: t`), so the page names the rejection itself, with the build it came from.+ it('names any other download error with its WhatsApp Web build', async () => {+ const failure = Object.assign(new Error('bad type'), { name: 'InvalidMediaFileType', status: 500 });pageServing(5, { decrypt: () => Promise.reject(failure) });+ (g.window as { Debug?: unknown }).Debug = { VERSION: '2.3000.1' };- await expect(downloadMediaInPage({ msgId: 'M1', maxBytes: 1000 })).rejects.toBe(failure);+ await expect(downloadMediaInPage({ msgId: 'M1', maxBytes: 1000 })).rejects.toThrow(+ 'InvalidMediaFileType: bad type (WhatsApp Web 2.3000.1)',+ );});// puppeteer ships downloadMediaInPage into the page as Function#toString(), so it can reach nothing of this@@ -5940,8 +5960,11 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {it('reaches nothing outside the page when a download fails with any other error', async () => {const failure = Object.assign(new Error('boom'), { status: 500 });pageServing(3, { decrypt: () => Promise.reject(failure) });+ (g.window as { Debug?: unknown }).Debug = { VERSION: '2.3000.1' };- await expect(shippedToPage()({ msgId: 'M1', maxBytes: 1000 })).rejects.toBe(failure);+ await expect(shippedToPage()({ msgId: 'M1', maxBytes: 1000 })).rejects.toThrow(+ 'Error: boom (WhatsApp Web 2.3000.1)',+ );});// downloadMediaInPage copies the page side of Message#downloadMedia. The fingerprint pins the whole@@ -5975,9 +5998,20 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {'f70f7cd8393bc60149745b7901bb96eece28a2940eaee4725e71ce615cf9ec73',);expect(literals(own)).toEqual(literals(upstream));- // The copy measures the decrypted length instead of reporting the declared `size`.+ // The copy measures the decrypted length instead of reporting the declared `size`, and names a+ // rejection from its `name`, `message` and the page's `Debug.VERSION`.expect(members(own)).toEqual(- [...members(upstream).filter(m => m !== 'size'), 'byteLength', 'maxBytes', 'msgId', 'sizeBytes'].sort(),+ [+ ...members(upstream).filter(m => m !== 'size'),+ 'byteLength',+ 'maxBytes',+ 'msgId',+ 'sizeBytes',+ 'name',+ 'message',+ 'Debug',+ 'VERSION',+ ].sort(),);expect(call(own, 'downloadMedia')).toBe(call(upstream, 'downloadMedia'));expect(call(own, 'downloadAndMaybeDecrypt')).toBe(diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex a9af2c6d8..8caa7ebe7 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -351,13 +351,25 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// as a rejection, which boundedReady adopts and rethrows past the only exit that builds the marker,// leaving every call site to emit with no media field at all. It is the same "no usable media"// outcome as the timeout below, so it takes the same null sentinel.- const download = downloadCappedMedia(msg, maxBytes).catch((error: unknown) => {- this.logger.warn('Inbound media download failed; emitting the omitted marker', {- msgId,- error: String(error),+ const download = downloadCappedMedia(msg, maxBytes)+ .then(result => {+ // The page answers null or undefined for media it cannot serve (re-uploading, a failed resolve, a+ // 404), and the omitted marker alone gives nobody a line to post.+ if (!result) {+ this.logger.warn('Inbound media download returned nothing; emitting the omitted marker', {+ msgId,+ answer: String(result),+ });+ }+ return result;+ })+ .catch((error: unknown) => {+ this.logger.warn('Inbound media download failed; emitting the omitted marker', {+ msgId,+ error: String(error),+ });+ return null;});- return null;- });resolveBounded(withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () =>this.logger.warn(diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 92976bc1d..db570515c 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -159,7 +159,13 @@ export async function downloadMediaInPage(args: {return { ...meta, data: await w.WWebJS.arrayBufferToBase64Async(decrypted) };} catch (e) {if ((e as { status?: number } | null)?.status === 404) return undefined;- throw e;+ // WhatsApp Web's rejection classes are minified, and puppeteer rebuilds a page exception from the class+ // name alone (`t: t`). Name the rejection here, with the build it came from.+ const thrown = e as { name?: unknown; message?: unknown } | null;+ const build = (window as unknown as { Debug?: { VERSION?: unknown } }).Debug?.VERSION;+ throw new Error(`${String(thrown?.name)}: ${String(thrown?.message)} (WhatsApp Web ${String(build)})`, {+ cause: e,+ });}}