Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(media): answer 503 when the session proxy fails a url fetch

Yudhi Armyndharis060a22a77115
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index f6617b9c1..e3efb7542 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -107,7 +107,7 @@ Validation failures (`statusCode: 400`) return `message` as an **array** of fiel
| `500` | Internal Server Error | Send failed at the WhatsApp engine or an unexpected server error |
| `501` | Not Implemented | The operation is not supported by the active engine (see the capability matrix, docs/29) |
| `502` | Bad Gateway | An engine transport failure (e.g. a dead Baileys socket; retryable), an upstream component returned something unusable (not retryable; each route section carries the exact wording), or, on a multi-node deployment, forwarding a session-scoped request to its owner node failed after the request may already have been sent, so a non-idempotent call must not be replayed blindly (see docs/13) |
-| `503` | Service Unavailable | A dependency or the session is not ready (boot draining, a datastore down, the engine reconnecting); retryable. On a multi-node deployment a forwarded request answers `503` only when the owner node was never reached, so the request was not carried out (see docs/13) |
+| `503` | Service Unavailable | A dependency or the session is not ready (boot draining, a datastore down, the engine reconnecting, a media `url` fetch through the session's egress proxy failing before any response, whether the proxy or the target is at fault); retryable. On a multi-node deployment a forwarded request answers `503` only when the owner node was never reached, so the request was not carried out (see docs/13) |
| `504` | Gateway Timeout | An upstream the gateway waits on did not answer in time: on a multi-node deployment, the owner node did not answer a forwarded session-scoped request within `SESSION_PROXY_TIMEOUT_MS`; on `POST /sessions/{sessionId}/start` (see §6.4.1), the engine did not finish starting within its timeout, either because initialization never finished at all (WhatsApp Web, the network or the session `proxyUrl` unreachable in a way that hangs the connection, or a browser stalled mid-startup, for example under a container memory or resource limit) or because the engine's own auth poll expired after the page loaded (typically an unreachable `proxyUrl`), and the message names which. On the forwarding path the request may still have been carried out on the owner node, so a non-idempotent call must not be replayed blindly (see docs/13) |
### Timestamp Conventions
@@ -1776,7 +1776,7 @@ Send an image (by URL or base64) with an optional caption.
{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
```
-**Errors:** `400` neither `url` nor `base64`, base64 without `mimetype`, SSRF-blocked URL, a `url` that answers non-2xx, times out or cannot be reached, session not active, or unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine
+**Errors:** `400` neither `url` nor `base64`, base64 without `mimetype`, SSRF-blocked URL, a `url` that answers non-2xx, times out or cannot be reached, session not active, or unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### POST /api/sessions/:sessionId/messages/send-video
@@ -1802,7 +1802,7 @@ Send a video (by URL or base64) with an optional caption. Uses the same `SendMed
{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
```
-**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine
+**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### POST /api/sessions/:sessionId/messages/send-audio
@@ -1828,7 +1828,7 @@ Send an audio message (by URL or base64). Uses `SendAudioMessageDto`. A `caption
{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
```
-**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine
+**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### POST /api/sessions/:sessionId/messages/send-document
@@ -1861,7 +1861,7 @@ Send a document/file (by URL or base64). Uses `SendMediaMessageDto`; `filename`
**Engine differences:** Baileys always sends a document as a document, while whatsapp-web.js deliberately keeps normal mimetype classification for `status@broadcast` and broadcast lists — the library returns `null` for document-mode sends to those recipients, so forcing the flag there would turn a working send into a failure. For URL-based sends without an explicit `filename`, whatsapp-web.js derives the URL basename; Baileys falls back to the literal `file`.
-**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine
+**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### POST /api/sessions/:sessionId/messages/send-location
@@ -1961,7 +1961,7 @@ Send a sticker (by URL or base64; typically webp). Reuses `SendMediaMessageDto`.
{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
```
-**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine
+**Errors:** `400` media validation failure / a `url` that answers non-2xx, times out or cannot be reached / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `413` base64 or downloaded media over the media cap (see §6.3) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### POST /api/sessions/:sessionId/messages/send-poll
@@ -2733,7 +2733,7 @@ Set the group's picture. The account must be a group admin.
**Response** `200` — `{ "success": true, "message": "Group picture updated" }`
-**Errors:** `400` the id does not name a group, the session is not active, neither `url` nor `base64` was supplied, or the `url` answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks OPERATOR role, or the engine refused (admin rights required) · `404` no such group · `409` the session is not connected (engine exists but is not `ready`) · `413` base64 or downloaded media over the media cap (see §6.3) · `503` WhatsApp did not answer within the request budget — the change may or may not have been applied
+**Errors:** `400` the id does not name a group, the session is not active, neither `url` nor `base64` was supplied, or the `url` answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks OPERATOR role, or the engine refused (admin rights required) · `404` no such group · `409` the session is not connected (engine exists but is not `ready`) · `413` base64 or downloaded media over the media cap (see §6.3) · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable), or WhatsApp did not answer within the request budget — the change may or may not have been applied
#### DELETE /api/sessions/:sessionId/groups/:groupId/picture
@@ -4312,7 +4312,7 @@ Returns the engine `StatusResult` directly. POST default status is `201`.
**Recipient JIDs:** `@c.us` (regular phone) recipients are reliable. `@lid` (privacy-id) recipients are best-effort and unverified — prefer `@c.us` where the phone number is known. **Sender-side caveat:** the posting account's own phone may show a "waiting for this status update" notice; recipients view it normally.
-**Errors:** `400` validation failure (unknown body field, an empty media wrapper, a JID not matching `@c.us`/`@lid`, more than 256 recipients, or a caption over 1024 chars), or a `url` that answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `409` conflict or engine not ready (retryable) · `413` base64 or downloaded media over the media cap (see §6.3)
+**Errors:** `400` validation failure (unknown body field, an empty media wrapper, a JID not matching `@c.us`/`@lid`, more than 256 recipients, or a caption over 1024 chars), or a `url` that answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `409` conflict or engine not ready (retryable) · `413` base64 or downloaded media over the media cap (see §6.3) · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### POST /api/sessions/:sessionId/status/send-video
@@ -4361,7 +4361,7 @@ Returns the engine `StatusResult` directly. POST default status is `201`.
**Recipient JIDs:** `@c.us` (regular phone) recipients are reliable. `@lid` (privacy-id) recipients are best-effort and unverified — prefer `@c.us` where the phone number is known. **Sender-side caveat:** the posting account's own phone may show a "waiting for this status update" notice; recipients view it normally.
-**Errors:** `400` validation failure (unknown body field, an empty media wrapper, a JID not matching `@c.us`/`@lid`, more than 256 recipients, or a caption over 1024 chars), or a `url` that answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `409` conflict or engine not ready (retryable) · `413` base64 or downloaded media over the media cap (see §6.3)
+**Errors:** `400` validation failure (unknown body field, an empty media wrapper, a JID not matching `@c.us`/`@lid`, more than 256 recipients, or a caption over 1024 chars), or a `url` that answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `409` conflict or engine not ready (retryable) · `413` base64 or downloaded media over the media cap (see §6.3) · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### POST /api/sessions/:sessionId/status/send-voice
@@ -4398,7 +4398,7 @@ There is **no `caption`**: WhatsApp has nowhere to render one on a status voice
**Read-back:** a voice status is listed with `"type": "voice"`. That member was added with this endpoint; before it, anything that was not an image or a video was reported as `text`.
-**Errors:** `400` validation failure, neither `url` nor `base64` supplied, or a `url` that answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `413` base64 or downloaded media exceeds `MEDIA_DOWNLOAD_MAX_BYTES` · `409` conflict or engine not ready (retryable)
+**Errors:** `400` validation failure, neither `url` nor `base64` supplied, or a `url` that answers non-2xx, times out or cannot be reached · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `413` base64 or downloaded media exceeds `MEDIA_DOWNLOAD_MAX_BYTES` · `409` conflict or engine not ready (retryable) · `503` a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### DELETE /api/sessions/:sessionId/status/:id
@@ -6378,7 +6378,7 @@ or
**Response** `200` — `{ "success": true, "message": "Profile picture updated" }`
-**Errors:** `400` neither `url` nor `base64` provided / base64 without `mimetype` / a `url` that answers non-2xx, times out or cannot be reached · `401` · `403` the whatsapp-web.js engine refused the change (the Baileys engine has no acceptance signal and answers `200`) · `409` conflict or engine not ready (retryable) · `413` base64 or downloaded image over the media cap (see §6.3) · `503` session not ready or dependency unavailable (retryable)
+**Errors:** `400` neither `url` nor `base64` provided / base64 without `mimetype` / a `url` that answers non-2xx, times out or cannot be reached · `401` · `403` the whatsapp-web.js engine refused the change (the Baileys engine has no acceptance signal and answers `200`) · `409` conflict or engine not ready (retryable) · `413` base64 or downloaded image over the media cap (see §6.3) · `503` session not ready, dependency unavailable, or a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault (retryable)
#### DELETE /api/sessions/:sessionId/profile/picture
@@ -6513,7 +6513,7 @@ including playlists and manifests, is refused with `400`.
{ "base64": "T2dnUwACAAAA...", "mimetype": "audio/ogg; codecs=opus", "bytes": 14970 }
```
-**Errors:** `400` neither field given, a `url` that answers non-2xx, times out or cannot be reached, or ffmpeg refused the input (its reason is included) · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `413` media above the size cap · `503` conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated
+**Errors:** `400` neither field given, a `url` that answers non-2xx, times out or cannot be reached, or ffmpeg refused the input (its reason is included) · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `413` media above the size cap · `503` conversion is disabled, the ffmpeg binary is not runnable, the conversion queue is saturated, or a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault
#### POST /api/sessions/:sessionId/media/convert/video
@@ -6521,7 +6521,7 @@ Convert video into an MP4 every WhatsApp client accepts: baseline H.264 with AAC
bounded at 1280 (never upscaled), index moved to the front so playback can start before the whole
file arrives.
-**Errors:** `400` neither field given, a `url` that answers non-2xx, times out or cannot be reached, or ffmpeg refused the input (its reason is included) · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `413` media above the size cap · `503` conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated
+**Errors:** `400` neither field given, a `url` that answers non-2xx, times out or cannot be reached, or ffmpeg refused the input (its reason is included) · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `413` media above the size cap · `503` conversion is disabled, the ffmpeg binary is not runnable, the conversion queue is saturated, or a `url` fetch through the session's egress proxy failed before any response, the proxy or the target at fault
**Response** `200`
diff --git a/openapi.json b/openapi.json
index 59a2d12db..cda621902 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2531,6 +2531,9 @@
},
"501": {
"description": "Sending media to a channel (`<id>@newsletter`) is not supported by the whatsapp-web.js engine — the page method it needs was removed by a WhatsApp Web update. Text to a channel still works."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Send an image message",
@@ -2594,6 +2597,9 @@
},
"501": {
"description": "Sending media to a channel (`<id>@newsletter`) is not supported by the whatsapp-web.js engine — the page method it needs was removed by a WhatsApp Web update. Text to a channel still works."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Send a video message",
@@ -2658,6 +2664,9 @@
},
"501": {
"description": "Sending media to a channel (`<id>@newsletter`) is not supported by the whatsapp-web.js engine — the page method it needs was removed by a WhatsApp Web update. Text to a channel still works."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Send an audio/voice message",
@@ -2722,6 +2731,9 @@
},
"501": {
"description": "Sending media to a channel (`<id>@newsletter`) is not supported by the whatsapp-web.js engine — the page method it needs was removed by a WhatsApp Web update. Text to a channel still works."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Send a document/file",
@@ -2902,6 +2914,9 @@
},
"501": {
"description": "Sending media to a channel (`<id>@newsletter`) is not supported by the whatsapp-web.js engine — the page method it needs was removed by a WhatsApp Web update. Text to a channel still works."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Send a sticker message",
@@ -6043,7 +6058,7 @@
"description": "The decoded base64 media, or the media downloaded from `url`, exceeds the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`, 50 MiB by default). A whole request is separately bounded by `BODY_SIZE_LIMIT` (25 mb by default), and base64 inflates by about a third, so a large send usually meets that coarser limit first: the body parser rejects the request before this check runs."
},
"503": {
- "description": "WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came."
+ "description": "WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came. The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Set the group's picture",
@@ -6365,7 +6380,7 @@
"description": "The decoded base64 media, or the media downloaded from `url`, exceeds the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`, 50 MiB by default). A whole request is separately bounded by `BODY_SIZE_LIMIT` (25 mb by default), and base64 inflates by about a third, so a large send usually meets that coarser limit first: the body parser rejects the request before this check runs."
},
"503": {
- "description": "WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came."
+ "description": "WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came. The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Set the account profile picture (URL or base64 image)",
@@ -7941,6 +7956,9 @@
},
"413": {
"description": "The decoded base64 media, or the media downloaded from `url`, exceeds the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`, 50 MiB by default). A whole request is separately bounded by `BODY_SIZE_LIMIT` (25 mb by default), and base64 inflates by about a third, so a large send usually meets that coarser limit first: the body parser rejects the request before this check runs."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Post an image status",
@@ -7994,6 +8012,9 @@
},
"413": {
"description": "The decoded base64 media, or the media downloaded from `url`, exceeds the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`, 50 MiB by default). A whole request is separately bounded by `BODY_SIZE_LIMIT` (25 mb by default), and base64 inflates by about a third, so a large send usually meets that coarser limit first: the body parser rejects the request before this check runs."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Post a video status",
@@ -8047,6 +8068,9 @@
},
"413": {
"description": "The decoded base64 media, or the media downloaded from `url`, exceeds the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`, 50 MiB by default). A whole request is separately bounded by `BODY_SIZE_LIMIT` (25 mb by default), and base64 inflates by about a third, so a large send usually meets that coarser limit first: the body parser rejects the request before this check runs."
+ },
+ "503": {
+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Post an audio status as a voice note",
@@ -8129,7 +8153,7 @@
"description": "The supplied media is above the media size cap."
},
"503": {
- "description": "Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly."
+ "description": "Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly. The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Convert audio into a WhatsApp voice note (Ogg/Opus)",
@@ -8180,7 +8204,7 @@
"description": "The supplied media is above the media size cap."
},
"503": {
- "description": "Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly."
+ "description": "Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly. The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`."
}
},
"summary": "Convert video into a WhatsApp-compatible MP4",
diff --git a/src/common/media/load-remote-media.spec.ts b/src/common/media/load-remote-media.spec.ts
index fb0258717..fa6ead0eb 100644
--- a/src/common/media/load-remote-media.spec.ts
+++ b/src/common/media/load-remote-media.spec.ts
@@ -1,6 +1,6 @@
import { fetch as undiciFetch } from 'undici';
import { loadRemoteMediaBuffer } from './load-remote-media';
-import { BadRequestException, PayloadTooLargeException } from '@nestjs/common';
+import { BadRequestException, PayloadTooLargeException, ServiceUnavailableException } from '@nestjs/common';
import { SsrfBlockedError } from '../security/ssrf-guard';
import { countsTowardSendBreaker } from '../../modules/message/send-pacing.service';
@@ -134,4 +134,59 @@ describe('loadRemoteMediaBuffer', () => {
expect(await failureOf()).toBe(boom);
});
});
+
+ /**
+ * undici reports a session proxy that refuses the connection, cannot be resolved or fails its
+ * handshake with the same `fetch failed` as an unreachable target. Answering 400 there blamed the
+ * caller's URL for the operator's proxy outage.
+ */
+ describe('behind a session proxy', () => {
+ const PROXY = 'http://user:[email protected]:3128';
+ const failureOf = async (): Promise<unknown> =>
+ loadRemoteMediaBuffer('http://8.8.8.8/x.png', PROXY).then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+
+ it('answers 503 for a failed connection, without the proxy or its credentials', async () => {
+ (undiciFetch as jest.Mock).mockRejectedValue(
+ new TypeError('fetch failed', { cause: new Error('connect ECONNREFUSED 10.0.0.5:3128') }),
+ );
+ const error = await failureOf();
+ expect(error).toBeInstanceOf(ServiceUnavailableException);
+ const body = JSON.stringify((error as ServiceUnavailableException).getResponse());
+ expect(body).not.toMatch(/10\.0\.0\.5|proxy\.example|secret/);
+ expect(countsTowardSendBreaker(error)).toBe(false);
+ });
+
+ it('answers 503 for a timeout before any response', async () => {
+ (undiciFetch as jest.Mock).mockRejectedValue(new DOMException('aborted', 'TimeoutError'));
+ const error = await failureOf();
+ expect(error).toBeInstanceOf(ServiceUnavailableException);
+ expect(countsTowardSendBreaker(error)).toBe(false);
+ });
+
+ it('keeps 400 once the target has answered', async () => {
+ (undiciFetch as jest.Mock).mockResolvedValue({ ...fakeResponse([], {}), ok: false, status: 404 });
+ expect(await failureOf()).toBeInstanceOf(BadRequestException);
+
+ const reader = { read: () => Promise.reject(new TypeError('terminated')), cancel: () => Promise.resolve() };
+ const response = fakeResponse([], {});
+ (undiciFetch as jest.Mock).mockResolvedValue({
+ ...response,
+ body: { ...response.body, getReader: () => reader },
+ });
+ expect(await failureOf()).toBeInstanceOf(BadRequestException);
+ });
+
+ it('keeps 400 when SESSION_PROXY_URL_FETCH=false sends the fetch direct', async () => {
+ process.env.SESSION_PROXY_URL_FETCH = 'false';
+ try {
+ (undiciFetch as jest.Mock).mockRejectedValue(new TypeError('fetch failed'));
+ expect(await failureOf()).toBeInstanceOf(BadRequestException);
+ } finally {
+ delete process.env.SESSION_PROXY_URL_FETCH;
+ }
+ });
+ });
});
diff --git a/src/common/media/load-remote-media.ts b/src/common/media/load-remote-media.ts
index 78a9456fd..0fe2205e4 100644
--- a/src/common/media/load-remote-media.ts
+++ b/src/common/media/load-remote-media.ts
@@ -1,4 +1,9 @@
-import { BadRequestException, HttpException, PayloadTooLargeException } from '@nestjs/common';
+import {
+ BadRequestException,
+ HttpException,
+ PayloadTooLargeException,
+ ServiceUnavailableException,
+} from '@nestjs/common';
import { SsrfBlockedError, withSafeFetch } from '../security/ssrf-guard';
import { urlFetchProxy } from '../security/proxy-dispatcher';
import { createLogger } from '../services/logger.service';
@@ -37,6 +42,12 @@ function positiveIntFromEnv(name: string, fallback: number): number {
* counted toward the send-pacing breaker. `SsrfBlockedError` is rethrown unchanged; each caller maps
* it to its own generic message.
*
+ * Behind a session proxy a failed connection or a timeout before any response is answered 503
+ * instead: undici reports a proxy that refuses, cannot be resolved or fails its handshake with the
+ * same `fetch failed` as an unreachable target, so the two cannot be told apart, and blaming the
+ * caller's URL for an operator's proxy outage would send the client to fix a link that works. Once a
+ * response has arrived the target was reached, and its failures stay 400/413.
+ *
* `sessionProxyUrl` is the egress proxy of the session the fetch is attributed to, or undefined for
* a direct one. It is required rather than optional so a new call site cannot leave a proxied
* session's fetch going direct by omission; `urlFetchProxy` applies the operator's opt-out.
@@ -52,10 +63,12 @@ export async function loadRemoteMediaBuffer(
// host, pins a direct or SOCKS connection to the vetted IP, and refuses redirects. The streaming cap runs inside
// the callback so the connection stays open for the body read and is torn down right after.
const proxyUrl = urlFetchProxy(sessionProxyUrl);
+ let responded = false;
return withSafeFetch(
url,
{ signal: AbortSignal.timeout(timeoutMs) },
async response => {
+ responded = true;
if (!response.ok) {
throw new BadRequestException(`Media fetch failed with status ${response.status}`);
}
@@ -93,7 +106,11 @@ export async function loadRemoteMediaBuffer(
if (error instanceof HttpException || error instanceof SsrfBlockedError) throw error;
// Matched by name: the abort reason is a DOMException, which need not share this realm's Error.
const name = (error as { name?: unknown } | null)?.name;
+ const proxyHop = proxyUrl !== undefined && !responded;
if (name === 'TimeoutError' || name === 'AbortError') {
+ if (proxyHop) {
+ throw new ServiceUnavailableException(`Media fetch through the session proxy timed out after ${timeoutMs} ms`);
+ }
throw new BadRequestException(`Media fetch timed out after ${timeoutMs} ms`);
}
// undici reports a failed connection as TypeError('fetch failed') and a body cut off mid-read
@@ -103,6 +120,7 @@ export async function loadRemoteMediaBuffer(
if (error instanceof TypeError && (error.message === 'fetch failed' || error.message === 'terminated')) {
const cause: unknown = error.cause;
logger.warn('Media fetch failed', { cause: cause instanceof Error ? cause.message : error.message });
+ if (proxyHop) throw new ServiceUnavailableException('Media fetch through the session proxy failed');
throw new BadRequestException('Media fetch failed');
}
throw error;
diff --git a/src/common/openapi/engine-status-responses.ts b/src/common/openapi/engine-status-responses.ts
index c753a847e..bde0c9e10 100644
--- a/src/common/openapi/engine-status-responses.ts
+++ b/src/common/openapi/engine-status-responses.ts
@@ -161,3 +161,14 @@ export const BULK_MEDIA_TOO_LARGE_413 =
'default). A `url` item is fetched after the `202`; one over the cap fails that item in the batch ' +
'results (`GET /messages/batch/{batchId}`) instead. The whole request is separately bounded by ' +
'`BODY_SIZE_LIMIT` (25 mb by default).';
+
+/**
+ * `ServiceUnavailableException` (503), thrown by `loadRemoteMediaBuffer` when a `url` fetched through
+ * the session's egress proxy fails before any response arrives. undici cannot tell a dead proxy from
+ * an unreachable target there, so the text names both rather than blaming either one.
+ */
+export const MEDIA_URL_PROXY_503 =
+ 'The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out ' +
+ 'before any response arrived, so the request was not carried out. The proxy or the target behind it ' +
+ 'may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy ' +
+ 'works points at the `url`. Without a session proxy the same failure answers `400`.';
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.ts
index 8e84ce2b6..808263684 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -31,6 +31,7 @@ import {
ENGINE_REFUSED_403,
GROUP_NOT_FOUND_404,
MEDIA_TOO_LARGE_413,
+ MEDIA_URL_PROXY_503,
} from '../../common/openapi/engine-status-responses';
// Reading an invite code is admin-only, but the groups list returns every group the account
@@ -486,7 +487,8 @@ export class GroupController {
status: 503,
description:
'WhatsApp did not answer within the request budget. The change may or may not have been applied — ' +
- 'the gateway stopped waiting for a confirmation that never came.',
+ 'the gateway stopped waiting for a confirmation that never came. ' +
+ MEDIA_URL_PROXY_503,
})
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 404, description: GROUP_NOT_FOUND_404 })
diff --git a/src/modules/media/media-conversion.service.ts b/src/modules/media/media-conversion.service.ts
index 10a3d0711..e5914e4db 100644
--- a/src/modules/media/media-conversion.service.ts
+++ b/src/modules/media/media-conversion.service.ts
@@ -148,7 +148,8 @@ export class MediaConversionService {
return data;
} catch (error) {
// The fetch layer already answers 400/413 for a bad status, a timeout, a failed connection
- // or a body over the cap, exactly as on the send path. An SSRF block is reported
+ // or a body over the cap (503 when the session proxy fails before any response), exactly
+ // as on the send path. An SSRF block is reported
// generically: its raw message names the resolved internal address. Anything else (a
// malformed session proxy, say) is a server fault and stays a 500, as it does on a send,
// rather than a 400 carrying a message that can name the proxy.
diff --git a/src/modules/media/media.controller.ts b/src/modules/media/media.controller.ts
index 6fe91e731..ce4bd7981 100644
--- a/src/modules/media/media.controller.ts
+++ b/src/modules/media/media.controller.ts
@@ -5,6 +5,7 @@ import { MediaConversionService } from './media-conversion.service';
import { ConvertMediaDto } from './dto/convert-media.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
+import { MEDIA_URL_PROXY_503 } from '../../common/openapi/engine-status-responses';
/**
* Server-side transcoding, scoped to a session.
@@ -60,7 +61,8 @@ export class MediaController {
@ApiResponse({
status: 503,
description:
- 'Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly.',
+ 'Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly. ' +
+ MEDIA_URL_PROXY_503,
})
async convertVoice(@Param('sessionId') sessionId: string, @Body() dto: ConvertMediaDto) {
return this.mediaConversion.convertToVoice(sessionId, dto);
@@ -87,7 +89,8 @@ export class MediaController {
@ApiResponse({
status: 503,
description:
- 'Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly.',
+ 'Conversion is disabled, the ffmpeg binary is not runnable, or the conversion queue is saturated — retry shortly. ' +
+ MEDIA_URL_PROXY_503,
})
async convertVideo(@Param('sessionId') sessionId: string, @Body() dto: ConvertMediaDto) {
return this.mediaConversion.convertToVideo(sessionId, dto);
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index a32ff2ca7..5a7af10ed 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -55,6 +55,7 @@ import {
ENGINE_NOT_SUPPORTED_501,
MEDIA_TOO_LARGE_413,
BULK_MEDIA_TOO_LARGE_413,
+ MEDIA_URL_PROXY_503,
MESSAGE_NOT_FOUND_404,
RECIPIENT_UNREACHABLE_400,
} from '../../common/openapi/engine-status-responses';
@@ -195,6 +196,7 @@ export class MessageController {
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 501, description: CHANNEL_MEDIA_501 })
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
async sendImage(
@Param('sessionId') sessionId: string,
@Body() dto: SendMediaMessageDto,
@@ -219,6 +221,7 @@ export class MessageController {
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 501, description: CHANNEL_MEDIA_501 })
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
async sendVideo(
@Param('sessionId') sessionId: string,
@Body() dto: SendMediaMessageDto,
@@ -243,6 +246,7 @@ export class MessageController {
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 501, description: CHANNEL_MEDIA_501 })
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
async sendAudio(
@Param('sessionId') sessionId: string,
@Body() dto: SendAudioMessageDto,
@@ -267,6 +271,7 @@ export class MessageController {
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 501, description: CHANNEL_MEDIA_501 })
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
async sendDocument(
@Param('sessionId') sessionId: string,
@Body() dto: SendMediaMessageDto,
@@ -322,6 +327,7 @@ export class MessageController {
@ApiResponse({ status: 400, description: RECIPIENT_UNREACHABLE_400 })
@ApiResponse({ status: 501, description: CHANNEL_MEDIA_501 })
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
async sendSticker(
@Param('sessionId') sessionId: string,
@Body() dto: SendMediaMessageDto,
diff --git a/src/modules/profile/profile.controller.ts b/src/modules/profile/profile.controller.ts
index 7097d9ee1..55e50b540 100644
--- a/src/modules/profile/profile.controller.ts
+++ b/src/modules/profile/profile.controller.ts
@@ -5,7 +5,11 @@ import { ProfileService } from './profile.service';
import { SetProfileNameDto, SetProfileStatusDto, SetProfilePictureDto } from './dto/profile.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
-import { ENGINE_NOT_READY_409, MEDIA_TOO_LARGE_413 } from '../../common/openapi/engine-status-responses';
+import {
+ ENGINE_NOT_READY_409,
+ MEDIA_TOO_LARGE_413,
+ MEDIA_URL_PROXY_503,
+} from '../../common/openapi/engine-status-responses';
@ApiTags('profile')
@Controller('sessions/:sessionId/profile')
@@ -79,7 +83,8 @@ export class ProfileController {
status: 503,
description:
'WhatsApp did not answer within the request budget. The change may or may not have been applied — ' +
- 'the gateway stopped waiting for a confirmation that never came.',
+ 'the gateway stopped waiting for a confirmation that never came. ' +
+ MEDIA_URL_PROXY_503,
})
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
async setPicture(@Param('sessionId') sessionId: string, @Body() dto: SetProfilePictureDto) {
diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.ts
index 0f10a8715..28cca480f 100644
--- a/src/modules/status/status.controller.ts
+++ b/src/modules/status/status.controller.ts
@@ -10,6 +10,7 @@ import { ApiKeyRole } from '../auth/entities/api-key.entity';
import {
ENGINE_NOT_READY_409,
MEDIA_TOO_LARGE_413,
+ MEDIA_URL_PROXY_503,
SESSION_NOT_STARTED_404,
} from '../../common/openapi/engine-status-responses';
@@ -106,6 +107,7 @@ export class StatusController {
'post was blocked by a plugin.',
})
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 404, description: SESSION_NOT_STARTED_404 })
async sendImageStatus(@Param('sessionId') sessionId: string, @Body() dto: SendImageStatusDto) {
@@ -132,6 +134,7 @@ export class StatusController {
'post was blocked by a plugin.',
})
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 404, description: SESSION_NOT_STARTED_404 })
async sendVideoStatus(@Param('sessionId') sessionId: string, @Body() dto: SendVideoStatusDto) {
@@ -159,6 +162,7 @@ export class StatusController {
'post was blocked by a plugin.',
})
@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })
+ @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 404, description: SESSION_NOT_STARTED_404 })
async sendVoiceStatus(@Param('sessionId') sessionId: string, @Body() dto: SendVoiceStatusDto) {