Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs: describe the SDK header checks, fix the 409 and media notes
Yudhi Armyndharisf5f987bae9ec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fc41ad67d..762a29ec9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -52,7 +52,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Bound each webhook and ingress queue command at 2 s once Redis has connected, so a Redis that stops answering falls back to direct delivery and inline dispatch instead of holding every dispatch and ingress request.- Keep the dashboard chat's scroll-to-bottom button in view while the reader is scrolled up, where it moved with the thread and was off screen.-- Keep the dashboard chat reader's own scroll while an older page loads, where a scroll made in the meantime was undone and the scroll-to-bottom button could end far above the bottom.+- Land the dashboard chat's scroll-to-bottom button at the bottom when an older page arrives meanwhile, where the animated jump could end far above it.- Refuse to save a local `storage.localPath` the app cannot create or write, where the next start refused to boot and the dashboard that could undo the save was down.- Answer `400` for a send route's or a product send's `chatId`, or a bulk `batchId`, over 255 characters, where PostgreSQL answered `500` once the value passed its index entry limit.- Answer `400` for a `chatId` over 255 characters in the request body of a chat action, as the send routes do, instead of handing it to the engine.@@ -159,10 +159,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Parse a dashboard message made of many code spans or code blocks in linear time, so one long message no longer freezes the tab for seconds.- Render a dashboard message body over 4096 characters without links, so link detection no longer freezes the tab on a very long body.- Python SDK (next SDK release after 0.5.1): an error with an empty body names the response's status text instead of `None`.-- Python SDK (next SDK release after 0.5.1): a `timeout` of `None`, 0 or infinity means no timeout, an `httpx.Timeout` or a four-value tuple is passed through with a 0 or infinite element leaving that operation without a limit, and a negative, NaN or non-number raises `ValueError`.+- Python SDK (next SDK release after 0.5.1): a `timeout` of `None`, 0 or infinity means no timeout, a four-value tuple takes the same for each element, an `httpx.Timeout` is passed to httpx as given, and a negative, NaN or non-number raises `ValueError`.- Python SDK (next SDK release after 0.5.1): `WebhookFilterCondition` and `CustomLinkPreview` require the keys the gateway requires.- JavaScript and PHP SDKs (next SDK release after 0.5.1): printing or dumping a client no longer shows its API key, and the PHP client keeps its default header values out of a dump, an export and a cast as well.- Python and PHP SDKs (next SDK release after 0.5.1): the API key is trimmed, and one with a control or non-ASCII character is refused when the client is built, without repeating it.+- JavaScript SDK (next SDK release after 0.5.1): the API key is trimmed, and a key or default header value with a control or non-Latin-1 character is refused when the client is built, naming the header and never repeating the value.+- Go SDK (next SDK release after 0.5.1): the API key is trimmed, and one with a control character is refused when the client is built, without repeating it.- Python and PHP SDKs (next SDK release after 0.5.1): a default header value with a control or non-ASCII character is refused when the client is built, naming the header and never repeating the value.- Java SDK (next SDK release after 0.5.1): a connection failure names its exception class and keeps it as the cause instead of ending in `null`.- Java SDK (next SDK release after 0.5.1): a key or default header value with a control or non-ASCII character is refused when the client is built, naming the header and never repeating the value.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 261de0ad0..3a4939f10 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1633,8 +1633,9 @@ content on the API origin.**Errors:** `401` missing/invalid API key · `403` key not scoped to this session · `404``No media stored for this message` — the message carries no media, `MEDIA_DOWNLOAD_ENABLED=false`or the media was above `MEDIA_DOWNLOAD_MAX_BYTES` when it was stored (the row holds a size-only-marker), it was a URL-based API send (the gateway fetches those bytes at send time and never stores-them), or the message is not in this gateway's history (e.g. history backfill, which is media-free)+marker), it was a URL-based API send (the gateway stores none of those bytes, though on+whatsapp-web.js the own-send echo may), or the message is not in this gateway's history (e.g. history+backfill, which is media-free)Note: this is a three-path-segment route, so it never collides with the two-segment`GET /messages/:chatId/history` regardless of declaration order.diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex e5ff9396b..360ed28ef 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -112,13 +112,13 @@ const { OpenWAClient } = require('@rmyndharis/openwa');The constructor takes a single `OpenWAClientOptions` object. `baseUrl` and `apiKey` are required (the constructor throws synchronously if either is missing).-| Option | Type | Required | Default | Description |-| ---------------- | ------------------------ | -------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `baseUrl` | `string` | yes | — | Base URL of the OpenWA API, e.g. `http://localhost:2785`. A trailing slash is trimmed; a path prefix (e.g. `https://host/v1`) is preserved. |-| `apiKey` | `string` | yes | — | API key sent as the `X-API-Key` header on every request. |-| `timeoutMs` | `number` | no | `30000` | Per-request timeout in milliseconds; `0` or `Infinity` turns it off, and a value that is not a non-negative number throws a `TypeError`. Overridable per call via `RequestOptions.timeoutMs` on the raw `request()` method. |-| `defaultHeaders` | `Record<string, string>` | no | `{}` | Headers merged onto every request. The `Content-Type: application/json` and `X-API-Key` headers always take precedence. |-| `fetch` | `FetchLike` | no | `globalThis.fetch` | Injectable transport (the WHATWG `fetch` signature). Use this to wrap requests with retry/observability middleware, or to supply a `fetch` on runtimes that lack a global one. |+| Option | Type | Required | Default | Description |+| ---------------- | ------------------------ | -------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `baseUrl` | `string` | yes | — | Base URL of the OpenWA API, e.g. `http://localhost:2785`. A trailing slash is trimmed; a path prefix (e.g. `https://host/v1`) is preserved. |+| `apiKey` | `string` | yes | — | API key sent as the `X-API-Key` header on every request. Surrounding whitespace is trimmed; a control or non-Latin-1 character is refused when the client is built. |+| `timeoutMs` | `number` | no | `30000` | Per-request timeout in milliseconds; `0` or `Infinity` turns it off, and a value that is not a non-negative number throws a `TypeError`. Overridable per call via `RequestOptions.timeoutMs` on the raw `request()` method. |+| `defaultHeaders` | `Record<string, string>` | no | `{}` | Headers merged onto every request. The `Content-Type: application/json` and `X-API-Key` headers always take precedence. A value with a control or non-Latin-1 character is refused when the client is built, naming the header. |+| `fetch` | `FetchLike` | no | `globalThis.fetch` | Injectable transport (the WHATWG `fetch` signature). Use this to wrap requests with retry/observability middleware, or to supply a `fetch` on runtimes that lack a global one. |### Resources & Methods@@ -491,13 +491,13 @@ OpenWAClient()```-| Parameter | Type | Default | Description |-| ----------------- | ----------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `base_url` | `str` | _(required)_ | Gateway base URL, e.g. `http://localhost:2785`. Raises `ValueError` if empty. A trailing `/` is stripped; any path prefix is preserved. |-| `api_key` | `str` | _(required)_ | API key sent as the `X-API-Key` header. Surrounding whitespace is trimmed; raises `ValueError` if empty or if it holds a control or non-ASCII character. |-| `timeout` | `float \| httpx.Timeout \| tuple \| None` | `30.0` | Seconds per network operation, not per call; `0`, `inf` or `None` turns it off. An `httpx.Timeout` or a `(connect, read, write, pool)` tuple sets the operations apart. A breach raises `OpenWATimeoutError`. |-| `default_headers` | `Mapping[str, str] \| None` | `None` | Extra headers applied to every request. Applied **first**, so the SDK's `X-API-Key` and `Content-Type: application/json` always win. |-| `transport` | `httpx.BaseTransport \| None` | `None` | Optional `httpx` transport override (e.g. `httpx.MockTransport`) sharing the one connection pool. Useful for testing. |+| Parameter | Type | Default | Description |+| ----------------- | ----------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `base_url` | `str` | _(required)_ | Gateway base URL, e.g. `http://localhost:2785`. Raises `ValueError` if empty. A trailing `/` is stripped; any path prefix is preserved. |+| `api_key` | `str` | _(required)_ | API key sent as the `X-API-Key` header. Surrounding whitespace is trimmed; raises `ValueError` if empty or if it holds a control or non-ASCII character. |+| `timeout` | `float \| httpx.Timeout \| tuple \| None` | `30.0` | Seconds per network operation, not per call; `0`, `inf` or `None` turns it off. An `httpx.Timeout` or a `(connect, read, write, pool)` tuple sets the operations apart. A breach raises `OpenWATimeoutError`. |+| `default_headers` | `Mapping[str, str] \| None` | `None` | Extra headers applied to every request. Applied **first**, so the SDK's `X-API-Key` and `Content-Type: application/json` always win. A name must be an HTTP token and a value text without a control or non-ASCII character (surrounding spaces are trimmed); `ValueError` names the header, never the value. |+| `transport` | `httpx.BaseTransport \| None` | `None` | Optional `httpx` transport override (e.g. `httpx.MockTransport`) sharing the one connection pool. Useful for testing. |The client also exposes a few non-resource members:@@ -768,8 +768,8 @@ try:"chatId": "[email protected]","text": "Hi!",})-except OpenWAConflictError:- print("Conflict: typically the session is not ready yet (start it first); see error.code.")+except OpenWAConflictError as e:+ print(f"Conflict: typically the session is not ready yet (start it first); see e.code ({e.code}).")except OpenWANotFoundError:print("Session does not exist.")except OpenWARateLimitError:@@ -849,16 +849,16 @@ Two escape hatches sit on the client itself:The constructor takes a single associative `$config` array:-| Key | Type | Default | Description |-| ------------------- | ------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `baseUrl` | `string` | — (**required**) | API base URL, e.g. `http://localhost:2785`. A trailing `/` is stripped; any path prefix (e.g. `/v1` behind a proxy) is preserved. |-| `apiKey` | `string` | — (**required**) | Sent as the `X-API-Key` header on every request. |-| `timeout` | `float` | `30.0` | Per-request timeout in seconds. |-| `httpClient` | `?\GuzzleHttp\ClientInterface` | `null` | Inject a Guzzle client (e.g. one built on a `MockHandler`) for testing or middleware. When `null`, a default Guzzle client is created with the configured timeout. |-| `defaultHeaders` | `array<string,string>` | `[]` | Extra headers applied on every request, **under** the SDK's auth/JSON headers (which always win). |-| `allowInsecureHttp` | `bool` | `false` | Skip the `error_log()` warning written for an `http://` `baseUrl` whose host is not localhost (e.g. a private Docker network or a TLS-terminating proxy). |+| Key | Type | Default | Description |+| ------------------- | ------------------------------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `baseUrl` | `string` | — (**required**) | API base URL, e.g. `http://localhost:2785`. A trailing `/` is stripped; any path prefix (e.g. `/v1` behind a proxy) is preserved. |+| `apiKey` | `string` | — (**required**) | Sent as the `X-API-Key` header on every request. Surrounding whitespace is trimmed; a control or non-ASCII character is refused. |+| `timeout` | `float` | `30.0` | Per-request timeout in seconds. |+| `httpClient` | `?\GuzzleHttp\ClientInterface` | `null` | Inject a Guzzle client (e.g. one built on a `MockHandler`) for testing or middleware. When `null`, a default Guzzle client is created with the configured timeout. |+| `defaultHeaders` | `array<string,string>` | `[]` | Extra headers applied on every request, **under** the SDK's auth/JSON headers (which always win). A name must be an HTTP token; a value is text (a number is sent as its text) without a control or non-ASCII character, or an exception names the header. |+| `allowInsecureHttp` | `bool` | `false` | Skip the `error_log()` warning written for an `http://` `baseUrl` whose host is not localhost (e.g. a private Docker network or a TLS-terminating proxy). |-Missing `baseUrl` or `apiKey` throws `OpenWA\Exceptions\OpenWAException` from the constructor.+Missing `baseUrl` or `apiKey`, a key or default header value with a control or non-ASCII character, or a default header name that is not an HTTP token throws `OpenWA\Exceptions\OpenWAException` from the constructor.### Resources & Methods@@ -1094,7 +1094,7 @@ All exceptions the SDK raises itself live in `OpenWA\Exceptions` and descend fro| Exception | Extends | Trigger || ----------------------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `OpenWAException` | `\Exception` | Base for the SDK's own errors (also thrown for missing `baseUrl`/`apiKey`); a transport failure other than a timeout is Guzzle's own (`TransferException`). |+| `OpenWAException` | `\Exception` | Base for the SDK's own errors (also thrown for missing `baseUrl`/`apiKey` and for a key or default header the HTTP layer would refuse); a transport failure other than a timeout is Guzzle's own (`TransferException`). || `OpenWAApiException` | `OpenWAException` | Any non-2xx (including unfollowed 3xx and other 4xx/5xx). || `OpenWAAuthException` | `OpenWAApiException` | `401` — missing/invalid API key. || `OpenWAForbiddenException` | `OpenWAApiException` | `403` — the key's role or scope refuses the call (e.g. operator-only endpoint, or a session, IP or chat outside its allow-lists), or WhatsApp itself refused the operation (for example, missing group admin rights). |diff --git a/sdk/go/README.md b/sdk/go/README.mdindex 5da3edb6c..f9e9b4eee 100644--- a/sdk/go/README.md+++ b/sdk/go/README.md@@ -96,9 +96,10 @@ func main() {res, err := client.Messages.SendText(ctx, sessionID, req)switch {case errors.Is(err, openwa.ErrConflict):- // 409 — engine not ready; retry once the session is "ready".- // A keyed send can also answer 409 for a pending or uncertain outcome;- // APIError.Code tells them apart ("Send idempotency" below says what to do).+ // 409 — a conflicting state, typically a session that is not "ready" yet:+ // retry once it is. A keyed send can also answer 409 for a pending or+ // uncertain outcome; APIError.Code tells them apart ("Send idempotency"+ // below says what to do).case errors.Is(err, openwa.ErrNotFound):// 404 — unknown session/resource.case err != nil:diff --git a/sdk/go/messages.go b/sdk/go/messages.goindex f9823239c..606f357fb 100644--- a/sdk/go/messages.go+++ b/sdk/go/messages.go@@ -181,7 +181,8 @@ func (s *MessagesService) Unpin(ctx context.Context, sessionID string, body Unpi// Media fetches a message's stored media bytes: the archived file when one// exists, else the inline copy on the message row — which covers media sent by// this account. The server answers 404 when neither holds bytes (no media, a-// size-only marker, or a URL-based send whose bytes were never stored).+// size-only marker, or a URL-based send, whose bytes the gateway does not store+// though on whatsapp-web.js the own-send echo may).func (s *MessagesService) Media(ctx context.Context, sessionID, chatID, messageID string) (*MessageMedia, error) {path := s.base(sessionID) + "/" + pathEscape(chatID) + "/" + pathEscape(messageID) + "/media"data, contentType, err := s.client.doRaw(ctx, "GET", path, nil, nil, false)diff --git a/sdk/java/README.md b/sdk/java/README.mdindex 88cf481aa..3de21b25f 100644--- a/sdk/java/README.md+++ b/sdk/java/README.md@@ -115,17 +115,17 @@ try {}```-| Class | HTTP | Meaning |-| ------------------------------- | ---- | ----------------------------------------------------------- |-| `OpenWAAuthError` | 401 | Missing or invalid API key |-| `OpenWAForbiddenError` | 403 | API key role or scope, or WhatsApp itself, refuses the call |-| `OpenWANotFoundError` | 404 | Resource not found |-| `OpenWAConflictError` | 409 | Engine not ready, or an idempotency outcome (see `code()`) |-| `OpenWARateLimitError` | 429 | Rate limited |-| `OpenWANotImplementedError` | 501 | Active engine does not support the call |-| `OpenWAServiceUnavailableError` | 503 | Engine did not confirm in time |-| `OpenWAApiError` | — | Any other non-2xx (carries `.status()`) |-| `OpenWATimeoutError` | — | Request exceeded the configured timeout |+| Class | HTTP | Meaning |+| ------------------------------- | ---- | --------------------------------------------------------------------------------------- |+| `OpenWAAuthError` | 401 | Missing or invalid API key |+| `OpenWAForbiddenError` | 403 | API key role or scope, or WhatsApp itself, refuses the call |+| `OpenWANotFoundError` | 404 | Resource not found |+| `OpenWAConflictError` | 409 | Conflicting state, typically engine not ready, or an idempotency outcome (see `code()`) |+| `OpenWARateLimitError` | 429 | Rate limited |+| `OpenWANotImplementedError` | 501 | Active engine does not support the call |+| `OpenWAServiceUnavailableError` | 503 | Engine did not confirm in time |+| `OpenWAApiError` | — | Any other non-2xx (carries `.status()`) |+| `OpenWATimeoutError` | — | Request exceeded the configured timeout |All extend `OpenWAError` (a `RuntimeException`). 503 is transient, but a catalog 503 can persist because WhatsApp may never answer that query, so bound any retry. A 429 from the global rate limiter lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default), and `retryAfterSeconds()` carries its `Retry-After` header. A 429 whose `code()` is `"SEND_PACING_LIMITED"` is usually not transient: do not retry it before `retryAfterSeconds()`, which then comes from the body: a few seconds when only sends still in flight caused it, the rest of the failure breaker's cooldown (`SEND_PACING_BREAKER_COOLDOWN_MS`, 15 minutes by default) after a run of send failures, otherwise up to the next UTC day. `headers()` returns the response headers. A 503 does not prove a write was never carried out: the engine answers it when WhatsApp did not confirm in time, and the change may still have been applied, so re-read the state before repeating it. In a routed deployment a forward that fails before reaching the owner node answers 503, one that fails after the request reached it answers 502 or 504, and a 503 from the owner itself is relayed unchanged.