Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(pairing): answer 503 when the pairing-code retry budget runs out
Yudhi Armyndharis0b71a9d82ffe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5c7f9ca1..eb47c520c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- A pairing-code request whose retry budget runs out on a reloading WhatsApp Web page answers `503` instead of `500`, so a client can tell a retryable transport failure from a broken gateway ([#1654](https://github.com/rmyndharis/OpenWA/issues/1654)).- A re-delivery of an already-persisted ingress event is answered with the route's declared ack, the same response the first delivery received, instead of a hardcoded `200 duplicate` that bypassed the ack entirely. A provider that validates the ack no longer fails on the retry path dedup exists for ([#1638](https://github.com/rmyndharis/OpenWA/issues/1638)).- The `session-alive` preflight's `503` carries a `Retry-After`, so a provider that retries a 503 only when that header is present comes back instead of failing the call; the rejection writes no dedup row, so the retry is treated as a new delivery ([#1639](https://github.com/rmyndharis/OpenWA/issues/1639)).- A `429` from a rate-limit window carries a plain `Retry-After` in seconds alongside the existing `Retry-After-<window>`, which no HTTP client reads. The suffixed names stay, since they are what identify which window shed the request ([#1639](https://github.com/rmyndharis/OpenWA/issues/1639)).diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex f296079e5..90dea68f9 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -799,7 +799,7 @@ Request an 8-char pairing code to link via phone number (alternative to QR).`status` is the lowercase session status.-**Errors:** `400` validation, or session not started, or already authenticated · `401` · `403` · `404` not found · `409` session not waiting to be linked yet; wait for `status` to read `qr_ready` and retry (after a code was accepted, wait for `ready` instead). On Baileys a session that already reads `qr_ready` can still answer `409` while its socket is closing, for up to the WebSocket close timeout (30 s); that is retryable and the status follows shortly.+**Errors:** `400` validation, or session not started, or already authenticated · `401` · `403` · `404` not found · `409` session not waiting to be linked yet; wait for `status` to read `qr_ready` and retry (after a code was accepted, wait for `ready` instead). On Baileys a session that already reads `qr_ready` can still answer `409` while its socket is closing, for up to the WebSocket close timeout (30 s); that is retryable and the status follows shortly. · `503` whatsapp-web.js only: every attempt landed while WhatsApp Web was reloading its own QR page, so the request never reached WhatsApp; retryable, and the last attempt's reason rides in the message.#### POST /api/sessions/:sessionId/presence/subscribediff --git a/openapi.json b/openapi.jsonindex 1087f5cd7..106045c79 100644--- a/openapi.json+++ b/openapi.json@@ -911,6 +911,9 @@},"409": {"description": "The session is not waiting to be linked: the engine is still connecting, or reconnecting after a drop, so the request never reached WhatsApp. Wait for `status` to read `qr_ready` and retry. Once a code has been accepted the session moves through `authenticating` and `initializing` to `ready` and answers this until then; wait for `ready` in that case. A session that reads `ready` is already linked and answers `400` instead. One window answers this while the session still reads `qr_ready`: on the Baileys engine a socket that has begun closing stops accepting a pairing request before the status catches up, which on a silently dropped connection takes until the WebSocket's close timeout (30 s); retry, and the status follows shortly."+ },+ "503": {+ "description": "The pairing code could not be generated: every attempt landed while WhatsApp Web was reloading its own page, so the request never reached WhatsApp. The condition is transient and the request is worth retrying; the last attempt's reason is carried in the message. The Baileys engine does not answer this, having no page to reload."}},"summary": "Request an 8-char pairing code to link via phone number (alternative to QR)",diff --git a/src/common/openapi/engine-status-responses.ts b/src/common/openapi/engine-status-responses.tsindex 793ac2b51..46360d631 100644--- a/src/common/openapi/engine-status-responses.ts+++ b/src/common/openapi/engine-status-responses.ts@@ -43,6 +43,19 @@ export const PAIRING_NOT_READY_409 ='request before the status catches up, which on a silently dropped connection takes until the ' +"WebSocket's close timeout (30 s); retry, and the status follows shortly.";+/**+ * `EngineTransportError` (503) on `POST /sessions/:sessionId/pairing-code`, where the whatsapp-web.js+ * engine bounds each attempt and retries the navigation shapes: WhatsApp Web reloads its QR page every+ * few seconds while unpaired, so a request can land mid-navigation. Only an exhausted retry budget is+ * reported here. A refusal WhatsApp itself sends is not navigation-shaped and propagates on the first+ * attempt instead.+ */+export const PAIRING_TRANSPORT_503 =+ 'The pairing code could not be generated: every attempt landed while WhatsApp Web was reloading its ' ++ 'own page, so the request never reached WhatsApp. The condition is transient and the request is ' ++ "worth retrying; the last attempt's reason is carried in the message. The Baileys engine does not " ++ 'answer this, having no page to reload.';+/*** The catalog and status services pass a `NotFoundException` factory to `EngineRegistry.require()`* instead of taking its `BadRequestException` default, so on those routes an unstarted session is adiff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.tsindex f5cea6c14..607bd5c7e 100644--- a/src/engine/adapters/wwebjs-lifecycle.ts+++ b/src/engine/adapters/wwebjs-lifecycle.ts@@ -8,6 +8,7 @@ import {EngineStatus,} from '../interfaces/whatsapp-engine.interface';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { type createLogger } from '../../common/services/logger.service';import { MAX_TIMER_MS } from '../../config/configuration';import { resolveWebVersionPin } from '../wa-web-version';@@ -1073,7 +1074,13 @@ export class WwebjsLifecycle {}}}- // Every attempt hit a transient navigation/timeout: surface the last one rather than a hang.- throw lastError;+ // Every attempt hit a transient navigation/timeout, so the budget ran out on the transport rather+ // than on anything the caller sent. Reported as EngineTransportError (503) so a caller reads it as+ // retryable: a plain Error here surfaced as a 500, which says the gateway is broken and that+ // retrying is pointless. The last attempt's reason rides along as the detail.+ throw new EngineTransportError(+ `Pairing code could not be generated after ${PAIRING_CODE_MAX_ATTEMPTS} attempts: ` ++ `${lastError instanceof Error ? lastError.message : String(lastError)}`,+ );}}diff --git a/src/engine/adapters/wwebjs-pairing-code.spec.ts b/src/engine/adapters/wwebjs-pairing-code.spec.tsindex 1127ce3ca..b63d1c6c2 100644--- a/src/engine/adapters/wwebjs-pairing-code.spec.ts+++ b/src/engine/adapters/wwebjs-pairing-code.spec.ts@@ -7,6 +7,7 @@ import {} from './wwebjs-lifecycle';import { EngineStatus } from '../interfaces/whatsapp-engine.interface';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import type { Client } from 'whatsapp-web.js';/**@@ -52,6 +53,8 @@ describe('requestPairingCode retries a mid-navigation page', () => {expect(requestPairingCode).toHaveBeenCalledTimes(2);});+ // An exhausted budget is a transport failure, not a broken gateway: it answers 503 so a caller+ // knows the request is worth retrying, and carries the last attempt's reason as the detail.it('bounds a hanging attempt and gives up after the attempt budget', async () => {jest.useFakeTimers();const requestPairingCode = jest.fn().mockImplementation(() => new Promise<string>(() => undefined)); // never settles@@ -65,10 +68,27 @@ describe('requestPairingCode retries a mid-navigation page', () => {50;await jest.advanceTimersByTimeAsync(total);+ await expect(pending).rejects.toBeInstanceOf(EngineTransportError);await expect(pending).rejects.toThrow(/attempt timed out/i);expect(requestPairingCode).toHaveBeenCalledTimes(PAIRING_CODE_MAX_ATTEMPTS);});+ it('answers 503 for an exhausted budget', async () => {+ jest.useFakeTimers();+ const requestPairingCode = jest.fn().mockImplementation(() => new Promise<string>(() => undefined));+ const lc = makeLifecycle(requestPairingCode);++ const pending = lc.requestPairingCode('628111');+ const failure = pending.catch((err: unknown) => err);+ await jest.advanceTimersByTimeAsync(+ PAIRING_CODE_MAX_ATTEMPTS * PAIRING_CODE_ATTEMPT_TIMEOUT_MS ++ (PAIRING_CODE_MAX_ATTEMPTS - 1) * PAIRING_CODE_RETRY_DELAY_MS ++ 50,+ );++ expect(((await failure) as EngineTransportError).getStatus()).toBe(503);+ });+it('propagates a non-navigation failure on the first attempt (no wasted retries)', async () => {const requestPairingCode = jest.fn().mockRejectedValue(new Error('phone number is not registered on WhatsApp'));const lc = makeLifecycle(requestPairingCode);diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex ed46534cc..7b8355191 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -46,7 +46,11 @@ import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { RequireRole, CurrentApiKey, SessionScoped, RequireUnscopedKey } from '../auth/decorators/auth.decorators';import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';-import { ENGINE_NOT_READY_409, PAIRING_NOT_READY_409 } from '../../common/openapi/engine-status-responses';+import {+ ENGINE_NOT_READY_409,+ PAIRING_NOT_READY_409,+ PAIRING_TRANSPORT_503,+} from '../../common/openapi/engine-status-responses';@ApiTags('sessions')@Controller('sessions')@@ -440,6 +444,7 @@ export class SessionController {@ApiResponse({ status: 400, description: 'Session not started or already authenticated' })@ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({ status: 409, description: PAIRING_NOT_READY_409 })+ @ApiResponse({ status: 503, description: PAIRING_TRANSPORT_503 })async requestPairingCode(@Param('sessionId', ParseUUIDPipe) id: string,@Body() dto: RequestPairingCodeDto,