Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): stop the call-link create answering a replayable 503

Yudhi Armyndharis84460c0ee8ed
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 0887a316c..2cd3896b2 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -155,7 +155,7 @@ A document sent without a `filename` is delivered under the default name `file`
### Size Limit
-There is a **single shared media byte cap**, not a per-type table. A base64 (or downloaded) media blob whose **decoded** size exceeds the cap is rejected with `413 Payload Too Large`. The cap is `MEDIA_DOWNLOAD_MAX_BYTES`, default **50 MiB (52,428,800 bytes)**; the same value bounds outbound base64 sends, remote-URL downloads, and inbound media. A non-positive or garbage override falls back to the default.
+There is a **single shared media byte cap**, not a per-type table. A base64 (or downloaded) media blob whose **decoded** size exceeds the cap is rejected with `413 Payload Too Large`. The cap is `MEDIA_DOWNLOAD_MAX_BYTES`, default **50 MiB (52,428,800 bytes)**; the same value bounds outbound base64 sends, remote-URL downloads, and inbound media. It takes a raw byte count, not a unit string, and the gateway refuses to boot on a non-positive or non-numeric value rather than falling back silently (`50mb` would parse to 50 bytes).
### Text Limit
@@ -6304,7 +6304,7 @@ Generate a shareable WhatsApp call link.
> caller handed `{ "link": "" }` — or a bare prefix with nothing after it — would pass it to a user
> before discovering it is dead.
-**Errors:** `400` session not ready, or an invalid `type`/`startTime` · `401` missing/invalid API key · `403` WhatsApp generated no link · `409` conflict or engine not ready (retryable) · `503` WhatsApp did not answer within the request budget
+**Errors:** `400` session not ready, or an invalid `type`/`startTime` · `401` missing/invalid API key · `403` WhatsApp generated no link · `409` conflict or engine not ready (retryable) · `500` the whatsapp-web.js page died mid-request (deliberately not `503`: each call mints a new link, so a client replaying a `503` would create a second one)
#### POST /api/sessions/:sessionId/calls/:callId/reject
diff --git a/openapi.json b/openapi.json
index fe31a86c5..719a788f6 100644
--- a/openapi.json
+++ b/openapi.json
@@ -6326,9 +6326,6 @@
},
"409": {
"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."
- },
- "503": {
- "description": "WhatsApp did not answer within the request budget. The link may or may not have been created — the gateway stopped waiting for a reply that never came."
}
},
"summary": "Generate a shareable WhatsApp call link",
diff --git a/src/engine/adapters/create-call-link.spec.ts b/src/engine/adapters/create-call-link.spec.ts
index dc115f91d..12a419459 100644
--- a/src/engine/adapters/create-call-link.spec.ts
+++ b/src/engine/adapters/create-call-link.spec.ts
@@ -89,18 +89,27 @@ describe('BaileysMessaging.createCallLink', () => {
});
describe('WwebjsProfile.createCallLink', () => {
- function makeProfile(client: Record<string, jest.Mock>): WwebjsProfile {
+ const PAGE_DEATH = /protocol error|target closed|session closed|connection closed/i;
+
+ function makeProfile(client: Record<string, jest.Mock>): { profile: WwebjsProfile; reported: string[] } {
+ const reported: string[] = [];
+ const isPageTransportError = (error: unknown): boolean =>
+ PAGE_DEATH.test(error instanceof Error ? error.message : String(error));
const host = {
ensureReady: jest.fn(),
getClient: () => client as unknown as Client,
logger,
+ isPageTransportError,
+ reportIfPageTransportError: (error: unknown, context: string) => {
+ if (isPageTransportError(error)) reported.push(context);
+ },
} as unknown as WwebjsEngineHost;
- return new WwebjsProfile(host);
+ return { profile: new WwebjsProfile(host), reported };
}
it('returns the finished link the client resolves', async () => {
const createCallLink = jest.fn().mockResolvedValue('https://call.whatsapp.com/video/TOKEN789');
- const link = await makeProfile({ createCallLink }).createCallLink('video', START_MS);
+ const link = await makeProfile({ createCallLink }).profile.createCallLink('video', START_MS);
expect(link).toBe('https://call.whatsapp.com/video/TOKEN789');
const [startDate, callType] = createCallLink.mock.calls[0] as [Date, string];
@@ -111,15 +120,29 @@ describe('WwebjsProfile.createCallLink', () => {
// whatsapp-web.js rejects anything but 'voice' | 'video', so the neutral 'audio' must be mapped.
it("maps the neutral 'audio' onto the library's 'voice'", async () => {
const createCallLink = jest.fn().mockResolvedValue('https://call.whatsapp.com/voice/TOKENABC');
- await makeProfile({ createCallLink }).createCallLink('audio', START_MS);
+ await makeProfile({ createCallLink }).profile.createCallLink('audio', START_MS);
expect((createCallLink.mock.calls[0] as [Date, string])[1]).toBe('voice');
});
it('treats the empty string as a failure rather than returning it', async () => {
const createCallLink = jest.fn().mockResolvedValue('');
- await expect(makeProfile({ createCallLink }).createCallLink('video', START_MS)).rejects.toThrow(
+ await expect(makeProfile({ createCallLink }).profile.createCallLink('video', START_MS)).rejects.toThrow(
/did not return a call link/i,
);
});
+
+ // Non-idempotent: each call mints a new server-side link, so a dead page must NOT surface as the
+ // 503 the clients replay, or a retry creates a second link. Report the death, rethrow untouched.
+ it('reports a dead page but keeps its own error, so a replay cannot mint a second link', async () => {
+ const createCallLink = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));
+ const { profile, reported } = makeProfile({ createCallLink });
+
+ const thrown = await profile.createCallLink('video', START_MS).catch((e: unknown) => e);
+
+ expect(thrown).toBeInstanceOf(Error);
+ expect(thrown).not.toBeInstanceOf(EngineTransportError);
+ expect((thrown as Error).message).toContain('Target closed');
+ expect(reported).toEqual(['createCallLink']);
+ });
});
diff --git a/src/engine/adapters/wwebjs-profile.ts b/src/engine/adapters/wwebjs-profile.ts
index 858eaaf6b..45e69242a 100644
--- a/src/engine/adapters/wwebjs-profile.ts
+++ b/src/engine/adapters/wwebjs-profile.ts
@@ -2,7 +2,7 @@ import { type Client } from 'whatsapp-web.js';
import { CallLinkType, MediaInput } from '../interfaces/whatsapp-engine.interface';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { toMessageMedia } from './wwebjs-messaging';
-import { type WwebjsEngineHost, withPage } from './wwebjs-host';
+import { type WwebjsEngineHost, withPage, reportPageDeath } from './wwebjs-host';
/**
* Own-account profile operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public
@@ -27,7 +27,10 @@ export class WwebjsProfile {
// whatsapp-web.js rejects any callType outside 'voice' | 'video', so the neutral 'audio' maps
// here. It floors the Date to seconds itself, so the epoch-milliseconds the contract takes goes
// straight into the Date.
- const link = await this.withPage('createCallLink', () =>
+ // Non-idempotent: each call mints a NEW server-side link, so a client replaying a 503 would
+ // create a second one. Report a dead page, keep the error as thrown (500). Same rule as
+ // createChannel; see reportPageDeath.
+ const link = await reportPageDeath(this.host, 'createCallLink', () =>
this.client().createCallLink(new Date(startTime), type === 'video' ? 'video' : 'voice'),
);
if (!link) {
diff --git a/src/modules/call/call.controller.ts b/src/modules/call/call.controller.ts
index 5b0cde2cc..9abc6a507 100644
--- a/src/modules/call/call.controller.ts
+++ b/src/modules/call/call.controller.ts
@@ -21,12 +21,6 @@ export class CallController {
@ApiResponse({ status: 200, description: 'The generated link', type: CallLinkResponseDto })
@ApiResponse({ status: 400, description: 'Session is not started, or an invalid type / startTime' })
@ApiResponse({ status: 403, description: 'WhatsApp generated no link for this request' })
- @ApiResponse({
- status: 503,
- description:
- 'WhatsApp did not answer within the request budget. The link may or may not have been created — ' +
- 'the gateway stopped waiting for a reply that never came.',
- })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
async createLink(
@Param('sessionId') sessionId: string,