Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs(api): describe the changed request and event behavior
Yudhi Armyndharis14392e6de99e
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 57c1d1052..c39a5e02d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -675,7 +675,7 @@ A session stopped with `POST /stop` or `POST /force-kill` is marked to run againOn multiple nodes, an explicit start may clear a peer's stop recorded before it successfully claimed ownership. It checks ownership and the stop record again after the start hook, before creating an engine; a lost claim or failed renewal answers `409` with no engine launched. A stop or claim loss during engine initialization retires that engine when initialization finishes.-**Errors:** `400` session already started / already starting, or this node already holds `MAX_CONCURRENT_SESSIONS` slots, counting running and starting engines and sessions waiting to relaunch after a failed reconnect (`Maximum concurrent sessions reached (N)`, answered only after the `404` and the `409` for a session running on another node; the session is not started, so retry once a slot frees or on a node with room) · `401` · `403` · `404` not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; no destructive side effect runs before the refusal — a retry after cleanup settles proceeds), or another node currently holds this session's engine (refused before any engine is launched), or, with no `code`, a `POST /stop`, a `POST /force-kill` that found a running engine to kill, or a data import (`stopOrphans`) of this session that began or finished while the start was waiting, or a delete of it still running or sent while the start was waiting and failed once it began removing (the start yields and launches nothing; after a stop, a force-kill or a delete that failed part-way a new `POST /start` clears it and starts the session, after a delete or an import that removed the session the retry answers `404`) · `503` the gateway is shutting down, or the engine's browser or socket connection died during launch and the one automatic retry failed too; no engine is left running, so the start can be retried · `504` the engine did not finish starting within its timeout (WhatsApp Web or the network unreachable, a stalled browser or resource limit, or, on whatsapp-web.js, an unreachable `proxyUrl`); the engine is torn down, so the start can be retried once the cause is addressed+**Errors:** `400` session already started / already starting, or this node already holds `MAX_CONCURRENT_SESSIONS` slots, counting running and starting engines and sessions waiting to relaunch after a failed reconnect (`Maximum concurrent sessions reached (N)`, answered only after the `404` and the `409` for a session running on another node; the session is not started, so retry once a slot frees or on a node with room) · `401` · `403` · `404` not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; no destructive side effect runs before the refusal — a retry after cleanup settles proceeds), or another node currently holds this session's engine (refused before any engine is launched), or, with no `code`, a `POST /stop`, a `POST /logout` or `POST /force-kill` that found a running engine, or a data import (`stopOrphans`) of this session that began or finished while the start was waiting, or a delete of it still running or sent while the start was waiting and failed once it began removing (the start yields and launches nothing; after a stop, a force-kill or a delete that failed part-way a new `POST /start` clears it and starts the session, after a delete or an import that removed the session the retry answers `404`) · `503` the gateway is shutting down, or the engine's browser or socket connection died during launch and the one automatic retry failed too; no engine is left running, so the start can be retried · `504` the engine did not finish starting within its timeout (WhatsApp Web or the network unreachable, a stalled browser or resource limit, or, on whatsapp-web.js, an unreachable `proxyUrl`); the engine is torn down, so the start can be retried once the cause is addressed#### POST /api/sessions/:sessionId/stop@@ -832,7 +832,7 @@ Like `stop`, a force-killed session stays down across restarts and takeover untiRequest an 8-char pairing code to link via phone number (alternative to QR).-> ⚠️ **On the whatsapp-web.js engine, only request a code for a number you are prepared to re-link.** A request for a number that already has a linked session has been observed to end with WhatsApp revoking that device: the linked session logs a LOGOUT, its credentials are deleted, and it falls back to `qr_ready` with no phone. Nothing here refuses such a request: the guards check the session's state, never the number. The request runs inside the shared WhatsApp Web page and resets its linking mode before asking for a code, so the blast radius is the account rather than the session. Baileys was not affected in the same tests. Link by QR when a session of that number must stay up.+> ⚠️ **On the whatsapp-web.js engine, only request a code for a number you are prepared to re-link.** A request for a number that already has a linked session has been observed to end with WhatsApp revoking that device: the linked session logs a LOGOUT, its credentials are deleted, and it falls back to `qr_ready` with no phone. The gateway refuses with `409` a number that is the stored phone of another of its sessions (a Brazilian, Mexican or Argentine mobile number counts under either spelling of its marker digit), but it cannot see a link made on another gateway or only on the phone, and refuses nothing there. The request runs inside the shared WhatsApp Web page and resets its linking mode before asking for a code, so the blast radius is the account rather than the session. Baileys was not affected in the same tests and is not refused: sessions of one number may coexist there. Link by QR when a session of that number must stay up.**Auth:** API key (OPERATOR) · **Scope:** session-scoped@@ -860,7 +860,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. · `503` whatsapp-web.js only: the gateway stopped waiting after its attempt budget, usually because WhatsApp Web kept reloading its QR page; retryable, and the last attempt's reason rides in the message. An attempt that timed out may still have reached WhatsApp, and a retry starts the linking flow again, so the unlink warning above applies to the retry too.+**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. On whatsapp-web.js a `409` also answers a number that is the stored phone of another session; log that session out or delete it before pairing this one. · `503` whatsapp-web.js only: the gateway stopped waiting after its attempt budget, usually because WhatsApp Web kept reloading its QR page; retryable, and the last attempt's reason rides in the message. An attempt that timed out may still have reached WhatsApp, and a retry starts the linking flow again, so the unlink warning above applies to the retry too.#### POST /api/sessions/:sessionId/presence/subscribe@@ -2415,7 +2415,7 @@ Send messages to multiple recipients as an async batch — returns immediately a| messages | BulkMessageItemDto[] | Yes | array, max 100, nested-validated | The batch items (see below); exact duplicate entries (same `chatId`, `type`, `content` and `variables`) are collapsed before processing, first occurrence wins, order preserved; distinct messages to the same `chatId` are all sent || options | BulkMessageOptionsDto | No | nested-validated | Pacing/error options (see below) |-Each `BulkMessageItemDto`: `{ chatId: string, type: 'text'|'image'|'video'|'audio'|'document', content: BulkMessageContentDto, variables?: Record<string,string> }`. `content` (all fields optional, nested-validated): `text?: string`, `image?`/`video?`/`audio?`/`document?`: `{ url?, base64?, mimetype?, filename?, ptt? }` (`ptt` applies to `audio` only), `caption?: string`, `mentions?: string[]` (per item; a batch fans out to many chats, and a WID is only taggable in a chat the participant is in).+Each `BulkMessageItemDto`: `{ chatId: string, type: 'text'|'image'|'video'|'audio'|'document', content: BulkMessageContentDto, variables?: Record<string,string> }`. `content` (all fields optional, nested-validated): `text?: string`, `image?`/`video?`/`audio?`/`document?`: `{ url?, base64?, mimetype?, filename?, ptt? }` (`ptt` applies to `audio` only), `caption?: string`, `mentions?: string[]` (per item; a batch fans out to many chats, and a WID is only taggable in a chat the participant is in). An entry may hold a placeholder such as `{{phone}}@c.us` that the item's `variables` fill in, so one batch can tag a different participant per item; the request accepts it unchecked, and a rendered list that is not made of individual WIDs fails that item.`BulkMessageOptionsDto`: `{ delayBetweenMessages?: number (1000–60000, default 3000), randomizeDelay?: boolean (default true), stopOnError?: boolean (default false) }`.@@ -2683,7 +2683,7 @@ Batch-resolve profile picture URLs for many contacts in one request (a chat side}```-`pictures` is keyed by the requested id. A per-id failure — or a lookup that exceeds the 8 s per-id deadline — yields `null` for that id rather than failing the batch. An omitted or empty `ids` returns `{ "pictures": {} }`.+`pictures` is keyed by the requested id. Lookups run five at a time. A per-id failure yields `null` for that id rather than failing the batch. A lookup that exceeds its 8 s deadline also yields `null` for its id and ends the request there: the ids of the later chunks are absent from `pictures`, as are the ids past the 50th, so ask for them again instead of reading them as having no picture. Completed pictures are kept. An omitted or empty `ids` returns `{ "pictures": {} }`.An engine that is not ready is the exception: it describes the session rather than one id, so the whole request answers `409` and no partial result is returned.@@ -3480,14 +3480,14 @@ for every **named** requester is a `403`.}```-**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the engine refused (admin rights / every named requester failed) · `404` no such group · `409` engine not ready · `503` WhatsApp did not answer within the request budget; on Baileys, also when WhatsApp rate-limits or times out the request (code 429 or 408): retry after a pause+**Errors:** `400` validation / session not started / a body that is a JSON list, or one sent in a content type other than `application/json` or `application/x-www-form-urlencoded`, which would otherwise act on every pending request · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the engine refused (admin rights / every named requester failed) · `404` no such group · `409` engine not ready · `503` WhatsApp did not answer within the request budget; on Baileys, also when WhatsApp rate-limits or times out the request (code 429 or 408): retry after a pause#### POST /api/sessions/:sessionId/groups/:groupId/membership-requests/rejectReject pending join requests. Same body, response shape, batch-guard contract and error map as`.../membership-requests/approve`; rejecting an empty queue is likewise a no-op.-**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the engine refused (admin rights / every named requester failed) · `404` no such group · `409` engine not ready · `503` WhatsApp did not answer within the request budget; on Baileys, also when WhatsApp rate-limits or times out the request (code 429 or 408): retry after a pause+**Errors:** `400` validation / session not started / a body that is a JSON list, or one sent in a content type other than `application/json` or `application/x-www-form-urlencoded`, which would otherwise act on every pending request · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the engine refused (admin rights / every named requester failed) · `404` no such group · `409` engine not ready · `503` WhatsApp did not answer within the request budget; on Baileys, also when WhatsApp rate-limits or times out the request (code 429 or 408): retry after a pause```json{@@ -4808,7 +4808,7 @@ timeout does not cancel the batch; inspect the failure log before retrying it.}```-`redriven` equals `delivered`; `enqueued` is retained for response compatibility and is always `0`. A row is excluded before applying the limit when it has `attempts: 0`, holds no event data, is past the retention window or out of scope, or its webhook is removed, disabled, unsubscribed from the event or no longer in the row's session. `skipped` counts selected rows cancelled by a hook or invalidated during the call. `remaining` counts eligible rows in the same requested session, webhook and IDs after the call. Retry another batch only after resolving persistent failures or hook cancellations; `remaining > 0` alone does not mean another call will succeed.+`redriven` equals `delivered`; `enqueued` is retained for response compatibility and is always `0`. A row is excluded before applying the limit when it has `attempts: 0`, holds no event data, is past the retention window or out of scope, or its webhook is removed, disabled, unsubscribed from the event or no longer in the row's session. `skipped` counts selected rows cancelled by a hook or invalidated during the call. `remaining` counts eligible rows in the same requested session, webhook and IDs after the call. A replay a hook cancels counts as an attempt on its row, like a failed one, and keeps its payload, so cancelled rows move behind rows with fewer attempts instead of leading every batch. Retry another batch only after resolving persistent failures or hook cancellations; `remaining > 0` alone does not mean another call will succeed.**Errors:** `400` body fails validation · `401` missing/invalid API key · `403` key role below ADMIN@@ -5283,7 +5283,9 @@ Content-Type `text/plain` with the parameters `version=0.0.4` and `charset=utf-8When the data database cannot be read the database-derived series (`openwa_sessions*`,`openwa_messages*`) are OMITTED rather than reported as zero — a zero would fire an alertclaiming every session had dropped. `openwa_stats_available` is what tells the two cases apart,-so alert on it rather than reading a missing series as zero. `docs/10` lists every series.+so alert on it rather than reading a missing series as zero. A scrape waits at most 2 seconds for+that read and omits the series when it is late, so a database that stalls costs those series and not the+rest of the scrape. `docs/10` lists every series.```# HELP openwa_up 1 if the OpenWA process is running@@ -5439,7 +5441,7 @@ Notes: raw return of an in-memory `Settings` object built once in the controller#### GET /api/audit-List audit-log entries, newest first. API-key lifecycle changes, session lifecycle events, send-pacing and rate-limit enforcement, queue-dashboard mutations, webhook delivery redrives, integration-instance changes, plugin management (install, update, uninstall, enable, disable, configuration, session activation) and ADMIN infra operations land here. **The eight actions below are never emitted**, so filtering for any of them returns zero rows by design: `message_sent` and `message_failed` (every send and its outcome is in the `messages` table), `webhook_triggered` and `webhook_failed` (tracked in `webhook_delivery_failures` and the `openwa_webhook_delivery_failures_total` counter), `webhook_created` and `webhook_deleted` (not wired yet), `api_key_used` (it would fire on every authenticated request; failed authentication is audited as `api_key_auth_failed`), and `session_connected` (an engine-level transition already reflected in `sessions.status`; the user-initiated `session_started` and `session_stopped` are audited).+List audit-log entries, newest first. API-key lifecycle changes, session lifecycle events, send-pacing and rate-limit enforcement, queue-dashboard mutations, webhook delivery redrives, integration-instance changes, plugin management (install, update, uninstall, enable, disable, configuration, session activation) and ADMIN infra operations land here. **The eight actions below are never emitted**, so filtering for any of them returns zero rows by design: `message_sent` and `message_failed` (every send and its outcome is in the `messages` table), `webhook_triggered` and `webhook_failed` (tracked in `webhook_delivery_failures` and the `openwa_webhook_delivery_failures_total` counter), `webhook_created` and `webhook_deleted` (not wired yet), `api_key_used` (it would fire on every authenticated request; failed authentication is audited as `api_key_auth_failed`), and `session_connected` (an engine-level transition already reflected in `sessions.status`; the user-initiated `session_started` and `session_stopped` are audited, and `session_stopped` is also written, with `via: infra_import_data` in its metadata, for each session a data import with `stopOrphans` stops, whether or not the import then commits).**Auth:** API key (ADMIN) · **Scope:** rows are confined to the calling key's `allowedSessions` — the `sessionId` query may only narrow within that list, never widen it@@ -5549,7 +5551,7 @@ The `queue.webhooks` counters are live BullMQ job counts (`pending` = waiting +`builtIn` (on `database`/`redis`/`storage`) reports whether OpenWA's own bundled container is actually running _and_ backing this service, detected live from the labelled container (on a daemon another OpenWA instance shares, its container counts too while this instance's host is spelled like the bundled one, see [13 - Horizontal Scaling](./13-horizontal-scaling.md)); when Docker is unreachable it falls back to the saved `*_BUILTIN` flag (one pinned by the environment first, else the one in `data/.env.generated`) beside a host that reaches the bundled container: a host name alone counts for nothing there, since an external server may be called `postgres`, and neither does the flag beside another host, which the process dials. `running` (on the same three) reports whether a bundled container OpenWA itself created is up, whether or not the service uses it: one Docker Compose created (it carries Compose's project label) reads `false`, so does one beside a configuration whose `POSTGRES_BUILTIN`, `REDIS_BUILTIN` or `MINIO_BUILTIN` (the environment's first, else the saved one) is not `true` (the container names are fixed per Docker daemon, so another OpenWA instance on the same daemon sees the same containers), and the key is absent while Docker is unreachable, since nothing can be seen or stopped then. In S3 mode `storage` additionally carries `bucket` and `endpoint` (each when one is configured; a bundled MinIO that is stopped still reports `http://minio:9000` here, with `builtIn` false) and `s3Available` (re-probed, throttled, while false; once true it stays true until a restart, so a later outage does not clear it); in local mode neither key is present. `engine.webVersion`/`engine.webVersionSource` (`pinned` / `auto` / `native`) appear only on `whatsapp-web.js`; `webVersion` is `null` until the auto-resolve first succeeds. `engine.browserArgs` is the effective launch argument list: `PUPPETEER_ARGS` (or the four defaults shown) with `--lang=en-US` appended unless a `--lang` flag is already present.-`envPinned` lists which of the keys `PUT /api/infra/config` writes the host environment or the project `.env` sets, by name only: `DATABASE_TYPE`, `POSTGRES_BUILTIN`, `DATABASE_HOST`, `DATABASE_PORT`, `DATABASE_USERNAME`, `DATABASE_PASSWORD`, `DATABASE_NAME`, `DATABASE_POOL_SIZE`, `POSTGRES_SCHEMA`, `DATABASE_SSL`, `DATABASE_SSL_REJECT_UNAUTHORIZED`, `REDIS_ENABLED`, `REDIS_BUILTIN`, `REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD`, `QUEUE_ENABLED`, `STORAGE_TYPE`, `MINIO_BUILTIN`, `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `STORAGE_LOCAL_PATH`, `ENGINE_TYPE`, `PUPPETEER_HEADLESS`, `SESSION_DATA_PATH` and `PUPPETEER_ARGS`. Those layers win over `data/.env.generated`, so a value saved for one of these keys through `PUT /api/infra/config` cannot take effect until that layer is changed. A pinned host also decides whether the bundled container backs its service, whatever `builtIn` is saved. A pinned `POSTGRES_BUILTIN`, `REDIS_BUILTIN` or `MINIO_BUILTIN` participates in container startup: `true` starts the container only while its datastore is in use and the environment does not pin its host to another server. The service uses the container only when its effective host reaches it.+`envPinned` lists which of the keys `PUT /api/infra/config` writes the host environment or the project `.env` sets, by name only: `DATABASE_TYPE`, `POSTGRES_BUILTIN`, `DATABASE_HOST`, `DATABASE_PORT`, `DATABASE_USERNAME`, `DATABASE_PASSWORD`, `DATABASE_NAME`, `DATABASE_POOL_SIZE`, `POSTGRES_SCHEMA`, `DATABASE_SSL`, `DATABASE_SSL_REJECT_UNAUTHORIZED`, `REDIS_ENABLED`, `REDIS_BUILTIN`, `REDIS_TLS`, `REDIS_USERNAME`, `REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD`, `QUEUE_ENABLED`, `STORAGE_TYPE`, `MINIO_BUILTIN`, `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `STORAGE_LOCAL_PATH`, `ENGINE_TYPE`, `PUPPETEER_HEADLESS`, `SESSION_DATA_PATH` and `PUPPETEER_ARGS`. Those layers win over `data/.env.generated`, so a value saved for one of these keys through `PUT /api/infra/config` cannot take effect until that layer is changed. A pinned host also decides whether the bundled container backs its service, whatever `builtIn` is saved. A pinned `POSTGRES_BUILTIN`, `REDIS_BUILTIN` or `MINIO_BUILTIN` participates in container startup: `true` starts the container only while its datastore is in use and the environment does not pin its host to another server. The service uses the container only when its effective host reaches it.**Errors:** `401` missing/invalid key · `403` key role < ADMIN, or key is session-scoped@@ -5765,11 +5767,11 @@ Built-in flags: a section sent without `builtIn` follows its stored host or endp}```-Write/IO errors are caught and returned as HTTP `200` with `{ "saved": false, "envPath": "", "profiles": [], "message": "Failed to save configuration: …" }`. DTO validation, an unknown engine type, an invalid `database.schema`, CR/LF injection, a value that cannot be stored so that it reads back unchanged, and a merged config the production boot guard would reject (an empty or default `DATABASE_PASSWORD` or S3 key on an external datastore, or a placeholder `REDIS_PASSWORD`; message starts `Refusing to save a configuration that would be rejected at production boot.`), and a local `storage.localPath` the app cannot create or write (message starts `Refusing to save the storage path`; the next start would refuse to boot on it, and a path pinned by the host environment or the project `.env` is not judged, as the boot never reads the submitted one) are real HTTP `400` responses, and nothing is written. `profiles` lists newly-required Docker profiles.+Write/IO errors are caught and returned as HTTP `200` with `{ "saved": false, "envPath": "", "profiles": [], "message": "Failed to save configuration: …" }`. DTO validation, an unknown engine type, an invalid `database.schema`, CR/LF injection, a value that cannot be stored so that it reads back unchanged, and a merged config the production boot guard would reject (an empty or default `DATABASE_PASSWORD` or S3 key on an external datastore, or a placeholder `REDIS_PASSWORD`; message starts `Refusing to save a configuration that would be rejected at production boot.`), and a merged config the boot environment validation rejects, such as a PostgreSQL selection without a host, a pool size that is not an integer or `REDIS_TLS=true` beside the built-in Redis (message starts `Refusing to save a configuration that fails boot validation.` and carries the boot message), and a local `storage.localPath` the app cannot create or write (message starts `Refusing to save the storage path`; the next start would refuse to boot on it, and a path pinned by the host environment or the project `.env` is not judged, as the boot never reads the submitted one) are real HTTP `400` responses, and nothing is written. `profiles` lists newly-required Docker profiles.**Errors:** `400` unknown/mistyped body field, a `database.type`/`storage.type` left out with none stored or pinned, unknown`engine.type`, invalid `database.schema`, CR-LF in a value, a value that cannot round-trip through the-env file, a config the production boot secret guard would reject, or a local+env file, a config the production boot secret guard or the boot environment validation would reject, or a local`storage.localPath` the app cannot create or write · `401` · `403`---@@ -7167,7 +7169,7 @@ Live events are pushed as a **nested** envelope (note: `data` is under `payload`}```-Error `code` values include `UNAUTHORIZED`, `INVALID_MESSAGE`, `INVALID_SESSION`, `INVALID_EVENTS`, `FORBIDDEN_SESSION`, `FORBIDDEN_EVENTS`, `TOO_MANY_SUBSCRIPTIONS`, and `RATE_LIMITED`. `RATE_LIMITED` is followed by a disconnect when a handshake exceeds the per-IP connection-attempt window or the key's concurrent-socket cap; a frame over the per-key frame budget gets `RATE_LIMITED` and is dropped undispatched, and the socket stays open. A subscribe answers `INVALID_SESSION` when `sessionId` is missing, or is neither `"*"` nor a session id of at most 128 letters, digits and hyphens. An unsubscribe answers `INVALID_SESSION` when `sessionId` is missing, empty, not a string, or neither `"*"` nor such a session id. A subscribe answers `TOO_MANY_SUBSCRIPTIONS` when it would take the connection past 4096 rooms; chat-restricted subscriptions count every literal chat address form for each session and event. When the rooms already held are the cause, unsubscribe before subscribing to more. A chat-restricted frame can also need more than 4096 on its own (its address forms times the events it names); unsubscribing cannot help there: name fewer events or subscribe with `"*"`, and a list stored before the 2000-entry bound whose address forms alone exceed 4096 has to be shortened.+Error `code` values include `UNAUTHORIZED`, `INVALID_MESSAGE`, `INVALID_SESSION`, `INVALID_EVENTS`, `FORBIDDEN_SESSION`, `FORBIDDEN_EVENTS`, `TOO_MANY_SUBSCRIPTIONS`, `SUBSCRIPTION_CANCELLED`, and `RATE_LIMITED`. `RATE_LIMITED` is followed by a disconnect when a handshake exceeds the per-IP connection-attempt window or the key's concurrent-socket cap; a frame over the per-key frame budget gets `RATE_LIMITED` and is dropped undispatched, and the socket stays open. A subscribe answers `INVALID_SESSION` when `sessionId` is missing, or is neither `"*"` nor a session id of at most 128 letters, digits and hyphens. An unsubscribe answers `INVALID_SESSION` when `sessionId` is missing, empty, not a string, or neither `"*"` nor such a session id. A subscribe still checking the API key when an unsubscribe for the same session, or for `"*"`, arrives answers `SUBSCRIPTION_CANCELLED` and joins no rooms. A subscribe answers `TOO_MANY_SUBSCRIPTIONS` when it would take the connection past 4096 rooms; chat-restricted subscriptions count every literal chat address form for each session and event. When the rooms already held are the cause, unsubscribe before subscribing to more. A chat-restricted frame can also need more than 4096 on its own (its address forms times the events it names); unsubscribing cannot help there: name fewer events or subscribe with `"*"`, and a list stored before the 2000-entry bound whose address forms alone exceed 4096 has to be shortened.### Subscribable events@@ -7296,7 +7298,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eveCached answers are checked again on the first message at least five minutes later and are discarded when the session engine stops or is replaced. Both engines can answer from local cache, so rechecking does not guarantee a fresh network identity check. Cache-only mappings remain available for display but cannot authorize phone/LID aliases or expand chat filters. A conflicting cached lookup disables alias matching until an engine mapping report confirms the phone. Baileys learns those reports from message identity fields and contact updates carrying a phone; its signal-key and send-time cache lookups remain display data. A cached Baileys answer can revoke a contradictory reported alias but cannot grant either phone. whatsapp-web.js can also confirm a mapping through its send-time number query. After a failed mapping write, another actual report retries it; a message without a new mapping does not re-report a cached Baileys answer.-Baileys preserves raw LIDs in message, contact and chat identities, with phone numbers kept separately for display. Older phone-keyed message rows keep their original ids. Cross-form edits and deletes require a reported pairing; explicit API actions that need such a pairing can confirm it through the public WhatsApp LID query before acting. A cached phone alone cannot redirect an operation to an older row or attach another chat's preview. A successful shared-table lookup with no mapping does not reuse a resident alias, including after a data import removes that row.+Baileys preserves raw LIDs in message, contact and chat identities, with phone numbers kept separately for display. Older phone-keyed message rows keep their original ids. Cross-form edits and deletes require a reported pairing; explicit API actions that need such a pairing can confirm it through the public WhatsApp LID query before acting. A cached phone alone cannot redirect an operation to an older row or attach another chat's preview. A successful shared-table lookup with no mapping does not reuse a resident alias, including after a data import removes that row. While the shared table cannot be read, no alias is granted: the API-key chat fence and the message, status, webhook and automation chat filters match only the id as granted, and the in-memory mapping is not consulted.Existing stored mappings from older releases have mixed origins, so an upgrade retains their display data but requires a new mapping report before phone/LID alias matching resumes. Exact phone or LID grants still match the chat id explicitly named. Upgrade every process sharing the database together: older readers do not enforce this distinction. Backups preserve mapping origin; older backups without it restore conservatively as display data.@@ -7349,7 +7351,7 @@ Webhook delivery is **at-least-once**. A consumer can legitimately receive the sOutbox creation is best effort, and message persistence and outbox insertion are separate transactions. A write failure or crash between them can still lose the webhook delivery. Failure records with zero attempts are excluded from operator redrive. Capacity and shutdown rejections can still be recovered from an unsettled outbox record; shutdown during retry backoff may follow earlier POSTs. The direct dispatcher leaves its local in-flight work alone during reconciliation. Graceful shutdown drains current queue jobs for at most 10 s; direct sends, an operator redrive replay in flight, and an outbox replay in flight with its plugin hooks, get up to `WEBHOOK_SHUTDOWN_DRAIN_MS` (default 5s). That replay sends at most one more POST, bounded by `WEBHOOK_TIMEOUT`, and no further row is replayed; the next start replays what it left pending.-**Opt-in events are bounded, not replayed.** `message.receipt` fires once per recipient and status, so one flush of buffered receipts can be thousands of events in a tick. Each webhook that names it has a queue of its own before the shared dispatch pool: a quarter of `WEBHOOK_DISPATCH_CONCURRENCY` deliveries run at once, divided among the session's webhooks that name `message.receipt` and never fewer than one running delivery per webhook, and up to three quarters of `WEBHOOK_DISPATCH_MAX_QUEUED` more receipts wait their turn. With the defaults a flush of 500 is delivered in full and at least 750 of a flush of 2000 (754 with one webhook, 751 with four). A flush drains at that quarter of the pool: 750 receipts to a receiver that takes 30 ms each take about 6 s, or about 24 s when four webhooks share the quarter. Any further receipt is dropped for that webhook: it leaves no outbox or failure row, is not replayed, and is counted in `openwa_webhook_delivery_failures_total` once for each webhook it is dropped for. It is logged once per burst and webhook (`webhook_opt_in_dropping` when the webhook starts dropping, then `webhook_opt_in_dropped` with the count). A webhook's queue is its own, so a receiver of it that never answers holds only that webhook's places: the session's other webhooks and its other events are not slowed. Between sessions the isolation has a limit, because the dispatch pool is shared. A receiver that never answers holds its places for a `WEBHOOK_TIMEOUT`; a session holds up to four at once, or one per webhook when it has more than four. That share is fixed when a webhook's queue is created and kept while the queue has events, so a session that adds receipt webhooks while a queue is busy can briefly hold more places than this. An event of another session waits for a slot once such sessions together hold all `WEBHOOK_DISPATCH_CONCURRENCY` of them, which at the defaults is four sessions: it then waits one `WEBHOOK_TIMEOUT` with four or five, two with eight. The receipts waiting in all queues together are not capped. Receipts still waiting at shutdown are dropped without being counted.+**Opt-in events are bounded, not replayed.** `message.receipt` fires once per recipient and status, so one flush of buffered receipts can be thousands of events in a tick. Each webhook that names it has a queue of its own before the shared dispatch pool: a quarter of `WEBHOOK_DISPATCH_CONCURRENCY` deliveries run at once, divided among the session's webhooks that name `message.receipt` (each keeps at least one place, and the session as a whole never runs more than that quarter at once, however many webhooks name it), and up to three quarters of `WEBHOOK_DISPATCH_MAX_QUEUED` more receipts wait their turn. With the defaults a flush of 500 is delivered in full and at least 750 of a flush of 2000 (754 with one webhook, 751 with four). A flush drains at that quarter of the pool: 750 receipts to a receiver that takes 30 ms each take about 6 s, or about 24 s when four webhooks share the quarter. Any further receipt is dropped for that webhook: it leaves no outbox or failure row, is not replayed, and is counted in `openwa_webhook_delivery_failures_total` once for each webhook it is dropped for. It is logged once per burst and webhook (`webhook_opt_in_dropping` when the webhook starts dropping, then `webhook_opt_in_dropped` with the count). A webhook's queue is its own, so a receiver of it that never answers holds only that webhook's places: the session's other webhooks and its other events are not slowed. Between sessions the isolation has a limit, because the dispatch pool is shared. A receiver that never answers holds its places for a `WEBHOOK_TIMEOUT`; a session holds at most a quarter of the pool at once, four at the defaults, however many webhooks name `message.receipt` and whenever they were added. An event of another session waits for a slot once such sessions together hold all `WEBHOOK_DISPATCH_CONCURRENCY` of them, which at the defaults is four sessions: it then waits one `WEBHOOK_TIMEOUT` with four or five, two with eight. The receipts waiting in all queues together are not capped. Receipts still waiting at shutdown are dropped without being counted.Before downgrading to a version that does not recognize the `queued` outbox state, drain or recover those records and take a backup. Its cleanup may otherwise treat an unsettled queued record as settled. Reverting the terminal-identity migration removes its index but does not restore historical duplicates.@@ -7401,24 +7403,24 @@ Every delivery includes:- `message.receipt`: `receipt_{sessionId}_{messageId}_{participant}_{status}`- `message.failed`: `failed_{sessionId}_{messageId}_{status}`- `message.revoked`: `rev_{sessionId}_{messageId}`-- `message.edited`: `edit_{sessionId}_{messageId}_{occurredAt}`-- `message.reaction`: `react_{sessionId}_{messageId}_{senderId}_{occurredAt}`+- `message.edited`: `edit_{sessionId}_{messageId}_{occurrenceId}`+- `message.reaction`: `react_{sessionId}_{messageId}_{senderId}_{occurrenceId}`- `session.qr`: `qr_{sessionId}_{hash(qr)}`-- `session.status`: `sess_{sessionId}_{status}_{occurredAt}`-- `session.authenticated`: `auth_{sessionId}_{hash(data)}_{occurredAt}`-- `session.disconnected`: `disc_{sessionId}_{hash(reason)}_{occurredAt}`-- `session.reconnect_loop`: `loop_{sessionId}_{attempts}_{occurredAt}`-- `group.join` / `group.leave`: `grp_{groupId}_{hash(participantIds)}_{join|leave}_{occurredAt}`-- `group.update`: `grp_{groupId}_update_{hash(changes)}_{occurredAt}`-- `group.join_request`: `grp_{groupId}_{hash(participantIds)}_join_request_{occurredAt}` (salted like `group.join` — a rejected user can legitimately ask again)-- `call.received`: `call_{sessionId}_{callId}` (a call id is unique per call, so no `occurredAt` salt)-- `call.accepted` / `call.rejected` / `call.missed`: `call_{sessionId}_{callId}_{outcome}` (each call ends once, so no `occurredAt` salt)-- `session.restriction`: `restr_{sessionId}_{kind}_{active}_{occurredAt}`-- `presence.update`: `pres_{sessionId}_{chatId}_{hash(participants)}_{occurredAt}`-- `event.response`: `rsvp_{sessionId}_{responseMessageId}` (every answer is its own message with its own id, so no `occurredAt` salt)+- `session.status`: `sess_{sessionId}_{status}_{occurrenceId}`+- `session.authenticated`: `auth_{sessionId}_{hash(data)}_{occurrenceId}`+- `session.disconnected`: `disc_{sessionId}_{hash(reason)}_{occurrenceId}`+- `session.reconnect_loop`: `loop_{sessionId}_{attempts}_{occurrenceId}`+- `group.join` / `group.leave`: `grp_{groupId}_{hash(participantIds)}_{join|leave}_{occurrenceId}`+- `group.update`: `grp_{groupId}_update_{hash(changes)}_{occurrenceId}`+- `group.join_request`: `grp_{groupId}_{hash(participantIds)}_join_request_{occurrenceId}` (salted like `group.join` — a rejected user can legitimately ask again)+- `call.received`: `call_{sessionId}_{callId}` (a call id is unique per call, so no `occurrenceId` salt)+- `call.accepted` / `call.rejected` / `call.missed`: `call_{sessionId}_{callId}_{outcome}` (each call ends once, so no `occurrenceId` salt)+- `session.restriction`: `restr_{sessionId}_{kind}_{active}_{occurrenceId}`+- `presence.update`: `pres_{sessionId}_{chatId}_{hash(participants)}_{occurrenceId}`+- `event.response`: `rsvp_{sessionId}_{responseMessageId}` (every answer is its own message with its own id, so no `occurrenceId` salt)- any other event (for example `status.received`): `evt_{event with . replaced by _}_{hash(data)}`-Recurring lifecycle events (and `message.reaction` / `message.edited` / `presence.update`) carry the same content across occurrences — the same phone on every reconnect, a constant disconnect reason, a re-applied emoji, or editing the same message multiple times — so they are salted with an `occurredAt` timestamp captured **once per dispatch and reused across that dispatch's retries**. This gives distinct occurrences distinct keys while keeping retries of one occurrence stable. Message keys are scoped by `sessionId` because WhatsApp message ids are unique per account, not globally.+Recurring lifecycle events (and `message.reaction` / `message.edited` / `presence.update`) carry the same content across occurrences — the same phone on every reconnect, a constant disconnect reason, a re-applied emoji, or editing the same message multiple times — so they are salted with an `occurrenceId`, a random id minted **once per dispatch and reused across that dispatch's retries**; it is not a timestamp, so two occurrences within the same millisecond still get distinct keys. This gives distinct occurrences distinct keys while keeping retries of one occurrence stable. Message keys are scoped by `sessionId` because WhatsApp message ids are unique per account, not globally.### Retries with exponential backoffdiff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 6ade767ac..9fd6abb53 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -185,7 +185,7 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/force-kill#### POST /api/sessions/:sessionId/pairing-code-Request an 8-char pairing code via phone number (OPERATOR). On whatsapp-web.js, request a code only for a number you are prepared to re-link: a request for a number that already has a linked session has been observed to end with WhatsApp revoking that device. Baileys was not affected in the same tests; link by QR when a session of that number must stay up.+Request an 8-char pairing code via phone number (OPERATOR). On whatsapp-web.js, request a code only for a number you are prepared to re-link: a request for a number that already has a linked session has been observed to end with WhatsApp revoking that device. The gateway answers `409` for a number that is the stored phone of another of its sessions, and cannot see a link made elsewhere. Baileys was not affected in the same tests and is not refused; link by QR when a session of that number must stay up.```bashcurl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/pairing-code" \diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex 277274afe..5fabf0882 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -148,7 +148,7 @@ The top-level client also exposes:| `logout` | `logout(id)` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** || `forceKill` | `forceKill(id)` | Force-kill a stuck session (SIGKILL + teardown). A `502` (`SESSION_FORCE_KILL_INCOMPLETE`) stops locally but the engine process may still be running; a retry answers `400`, so restart the node to reap it. **OPERATOR** || `getQrCode` | `getQrCode(id)` | Get the current QR code for authentication (live from the engine). **OPERATOR** |-| `requestPairingCode` | `requestPairingCode(id, body)` | Request an 8-character pairing code for phone-based login. On whatsapp-web.js, not for a number that already has a linked session (WhatsApp can revoke that device); link it by QR instead. **OPERATOR** |+| `requestPairingCode` | `requestPairingCode(id, body)` | Request an 8-character pairing code for phone-based login. On whatsapp-web.js, not for a number that already has a linked session (WhatsApp can revoke that device; the gateway answers 409 for the stored phone of another of its sessions but cannot see a link made elsewhere); link it by QR instead. **OPERATOR** || `setOnlinePresence` | `setOnlinePresence(id, body)` | Set the account's own global presence (appear online or offline). **OPERATOR** || `stats` | `stats()` | Aggregate statistics across the key's sessions. |@@ -194,7 +194,7 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime| `get` | `get(sessionId, contactId)` | Get details for a single contact by JID. || `check` | `check(sessionId, number)` | Check whether a phone number is registered on WhatsApp. **OPERATOR** || `profilePicture` | `profilePicture(sessionId, contactId)` | Get the contact's profile picture URL (or null). |-| `profilePictures` | `profilePictures(sessionId, ids)` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |+| `profilePictures` | `profilePictures(sessionId, ids)` | Profile picture URLs for up to 50 contacts; ids skipped after a timeout are absent. || `phone` | `phone(sessionId, contactId)` | Resolve a contact id (e.g. a `@lid`) to a phone number. || `block` | `block(sessionId, contactId)` | Block a contact. **OPERATOR** || `upsert` | `upsert(sessionId, contactId, body)` | Save a contact to the account's addressbook, or edit an existing entry. **OPERATOR** |@@ -528,7 +528,7 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All| `logout` | `logout(session_id) -> SessionResponse` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** || `force_kill` | `force_kill(session_id) -> SessionResponse` | Force-terminate a session. A `502` (`SESSION_FORCE_KILL_INCOMPLETE`) stops locally but the engine process may still be running; a retry answers `400`, so restart the node to reap it. **OPERATOR** || `get_qr_code` | `get_qr_code(session_id) -> QrCodeResponse` | Fetch the login QR code. **OPERATOR** |-| `request_pairing_code` | `request_pairing_code(session_id, body) -> PairingCodeResponse` | Request a phone-number pairing code. On whatsapp-web.js, not for a number that already has a linked session (WhatsApp can revoke that device); link it by QR instead. **OPERATOR** |+| `request_pairing_code` | `request_pairing_code(session_id, body) -> PairingCodeResponse` | Request a phone-number pairing code. On whatsapp-web.js, not for a number that already has a linked session (WhatsApp can revoke that device; the gateway answers 409 for the stored phone of another of its sessions but cannot see a link made elsewhere); link it by QR instead. **OPERATOR** || `set_online_presence` | `set_online_presence(session_id, body) -> SuccessResult` | Set the account's own global presence (appear online or offline). **OPERATOR** || `stats` | `stats() -> SessionStatsOverview` | Session statistics overview. |@@ -572,7 +572,7 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All| `get` | `get(session_id, contact_id) -> ContactRecord` | Get one contact. || `check` | `check(session_id, number) -> CheckNumberResponse` | Check whether a number is on WhatsApp. **OPERATOR** || `profile_picture` | `profile_picture(session_id, contact_id) -> ProfilePictureResponse` | Get a contact's profile picture. |-| `profile_pictures` | `profile_pictures(session_id, ids) -> ProfilePicturesResponse` | Batch-resolve profile picture URLs for up to 50 contacts. |+| `profile_pictures` | `profile_pictures(session_id, ids) -> ProfilePicturesResponse` | Profile picture URLs for up to 50 contacts; ids skipped after a timeout are absent. || `phone` | `phone(session_id, contact_id) -> ContactPhoneResponse` | Resolve a contact's phone number. || `block` | `block(session_id, contact_id) -> SuccessResult` | Block a contact. **OPERATOR** || `upsert` | `upsert(session_id, contact_id, body) -> SuccessResult` | Save a contact to the account's addressbook, or edit an existing entry. **OPERATOR** |@@ -881,7 +881,7 @@ All payloads are associative arrays; all listed methods are synchronous and retu| `logout` | `logout(string $id): array` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** || `forceKill` | `forceKill(string $id): array` | Force-kill a session. A `502` (`SESSION_FORCE_KILL_INCOMPLETE`) stops locally but the engine process may still be running; a retry answers `400`, so restart the node to reap it. **OPERATOR** || `getQrCode` | `getQrCode(string $id): array` | Fetch the current QR code. **OPERATOR** |-| `requestPairingCode` | `requestPairingCode(string $id, array $body): array` | Request a phone-pairing code. On whatsapp-web.js, not for a number that already has a linked session (WhatsApp can revoke that device); link it by QR instead. **OPERATOR** |+| `requestPairingCode` | `requestPairingCode(string $id, array $body): array` | Request a phone-pairing code. On whatsapp-web.js, not for a number that already has a linked session (WhatsApp can revoke that device; the gateway answers 409 for the stored phone of another of its sessions but cannot see a link made elsewhere); link it by QR instead. **OPERATOR** || `setOnlinePresence` | `setOnlinePresence(string $id, array $body): array` | Set the account's own global presence (appear online or offline). **OPERATOR** || `stats` | `stats(): array` | `GET /api/sessions/stats/overview`. |@@ -925,7 +925,7 @@ All payloads are associative arrays; all listed methods are synchronous and retu| `get` | `get(string $sessionId, string $contactId): array` | Get one contact. || `check` | `check(string $sessionId, string $number): array` | Check whether a number is on WhatsApp. **OPERATOR** || `profilePicture` | `profilePicture(string $sessionId, string $contactId): array` | Get a contact's profile picture. |-| `profilePictures` | `profilePictures(string $sessionId, array $ids): array` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |+| `profilePictures` | `profilePictures(string $sessionId, array $ids): array` | Profile picture URLs for up to 50 contacts; ids skipped after a timeout are absent. || `phone` | `phone(string $sessionId, string $contactId): array` | Resolve a contact's phone number. || `block` | `block(string $sessionId, string $contactId): array` | Block a contact. **OPERATOR** || `upsert` | `upsert(string $sessionId, string $contactId, array $body): array` | Save a contact to the account's addressbook, or edit an existing entry. **OPERATOR** |diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 44cc9e98c..07cd8265c 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -964,8 +964,11 @@ adapter boundary — none silently stubs.return a code, but on whatsapp-web.js the request runs in the shared WhatsApp Web page and checksno precondition: measured twice, a request for a number that already had a linked session wasfollowed within about a minute by WhatsApp revoking that device, whatsapp-web.js deleting its- credentials and the session returning to `qr_ready`. Baileys writes only its own credentials and- showed no such effect. Link by QR when the session of that number must stay up.+ credentials and the session returning to `qr_ready`. The gateway now answers `409` on whatsapp-web.js+ for a number that is the stored phone of another of its sessions (the mobile-marker spellings of a+ Brazilian, Mexican or Argentine number count as one), but it cannot see a link made on another gateway+ or only on the phone. Baileys writes only its own credentials, showed no such effect and is not+ refused. Link by QR when the session of that number must stay up.- **`archiveChat` / `clearChatMessages` / `deleteChat` / `sendSeen` / `markUnread` (baileys).** Thefour `chatModify` actions (archive, clear, delete, unread) need the chat's last known message, whichthe patch carries. `sendSeen` without message ids is `readMessages([key])` for the newest _received_diff --git a/docs/examples/session-phone-number-pairing.md b/docs/examples/session-phone-number-pairing.mdindex 45af2dee2..1488ab666 100644--- a/docs/examples/session-phone-number-pairing.md+++ b/docs/examples/session-phone-number-pairing.md@@ -6,7 +6,7 @@ This flow returns an 8-character pairing code that the user enters in WhatsApp o> This does **not** create or register a new WhatsApp account. It only links an existing WhatsApp account as a companion device for an OpenWA session.-> **On the whatsapp-web.js engine, request a code only for a number you are prepared to re-link.** A pairing request for a number that already has a linked session has been observed to end with WhatsApp revoking that device: within about a minute the linked session logs `WhatsApp unlinked this device (LOGOUT)`, its stored credentials are deleted, and it returns to `qr_ready` with no phone. The request runs inside the shared WhatsApp Web page and resets its linking mode before it asks for a code, so the blast radius is the account, not the session. Baileys has no such page and was not affected in the same tests. If a session of that number must stay up, link the new one by QR.+> **On the whatsapp-web.js engine, request a code only for a number you are prepared to re-link.** A pairing request for a number that already has a linked session has been observed to end with WhatsApp revoking that device: within about a minute the linked session logs `WhatsApp unlinked this device (LOGOUT)`, its stored credentials are deleted, and it returns to `qr_ready` with no phone. The request runs inside the shared WhatsApp Web page and resets its linking mode before it asks for a code, so the blast radius is the account, not the session. The gateway answers `409` for a number that is the stored phone of another of its sessions, but it cannot see a link made on another gateway or only on the phone. Baileys has no such page, was not affected in the same tests and is not refused. If a session of that number must stay up, link the new one by QR.## Flow@@ -96,7 +96,7 @@ After the code is accepted, the OpenWA session should move to a connected/ready## Troubleshooting- If OpenWA returns `Session is not started`, call `POST /api/sessions/{sessionId}/start` first.-- If OpenWA returns `Session is already authenticated`, the account is already linked and no pairing code is needed. Nothing refuses a request whose number is linked to a DIFFERENT session, or to a device outside this gateway, and on whatsapp-web.js that is the request that can unlink it; see the warning at the top.+- If OpenWA returns `Session is already authenticated`, the account is already linked and no pairing code is needed. On whatsapp-web.js a request whose number is the stored phone of a DIFFERENT session of this gateway answers `409`: log that session out or delete it first. Nothing refuses a number linked to a device outside this gateway, or only on the phone, and on whatsapp-web.js that is the request that can unlink it; see the warning at the top.- If OpenWA returns 409 `Session is not waiting to be linked`, the engine is still connecting (or reconnecting after a drop). Wait for `status` to read `qr_ready` and request again. After a code was accepted the same 409 is answered until the session is `ready`; do not request another code then. On Baileys the same 409 can also answer while `status` already reads `qr_ready`, for as long as the WebSocket takes to finish closing (up to 30 s on a silently dropped connection); retry rather than treating it as a bad state.- If the phone number is rejected, send digits only in international format, without `+`, spaces, or punctuation.- On the Baileys engine, if pairing keeps failing with a generic "check the phone number" rejection even though the number is correct and in the right format, WhatsApp is refusing the linked-device identity for that account rather than the number itself. The device name is carried into the pairing request, and some accounts reject a non-standard one. The default is `Ubuntu`; if `BAILEYS_BROWSER_NAME` was set to a custom brand, set it back to `Ubuntu` (or another standard OS name), restart OpenWA itself (the name is read at boot, so stopping and starting the session is not enough), and request a fresh code. whatsapp-web.js does not send this device name and never reads `BAILEYS_BROWSER_NAME`, so the variable has no effect there.diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex 8c98244d0..f5c6a04c6 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -318,6 +318,8 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {'phone on every tick. The interval lives in the page, so it dies with the next WhatsApp Web ' +'reload (roughly every 20s while UNPAIRED) and with the session; the library does expose ' +'cancelPairingCode, but it returns the page to QR mode, which is not what a retry wants. ' ++ 'The gateway answers 409 before asking, on whatsapp-web.js only, for a number that is the stored ' ++ 'phone of another of its sessions; it cannot see a link made on another gateway or only on the phone. ' +'baileys requestPairingCode ' +'(Socket/socket.js:596-650) writes only its own creds and sends one link_code_companion_reg IQ, ' +'with no shared page; no side effect was observed there.',