Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): stop claiming inbound ids, and cap only the peer contacts
Yudhi Armyndharis1004686c8c78
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d2522a662..bda67f308 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,17 +26,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- A WebSocket client that emits without an ack callback receives command replies again. The gateway answered by returning a frame, which Socket.IO delivers through the ack callback and nowhere else, so a client written to the documented `message` event saw no subscribe confirmation, no pong, and none of the refusals, including the session-scope denial. Replies now go out on `message` as well as through the ack.-- A Baileys message the account sent from its phone is no longer lost when the message store cannot be read. The repeat-delivery check threw on a locked database or an unparseable row and the message was dropped with it, and WhatsApp does not re-deliver one it has already acked; the check now fails open. Two deliveries of one such message landing before the store commits are also reported once rather than twice.+- A Baileys message the account sent from its phone is no longer lost when the message store cannot be read. The repeat-delivery check threw on a locked database or an unparseable row and the message was dropped with it, and WhatsApp does not re-deliver one it has already acked; the check now fails open, so at worst such a message is reported twice rather than never.- Baileys `editMessage` returns the edited message's id instead of the edit envelope's, which named a message no route could address and disagreed with the whatsapp-web.js engine.-- The Baileys address book survives a partial loss, not only an empty store. During the initial sync WhatsApp folds saved contacts into the history batch, where their names are stripped as chat titles, so the store kept plenty of contacts with the saved ones missing and the previous repair, which triggered only on an empty store, never ran. The app-state snapshot is now re-pulled once per process.-- Saved Baileys contacts are no longer evicted by peers seen once in a group or a broadcast. Both populations shared one capped map, so a busy session answered `GET /api/sessions/:sessionId/contacts` with fewer and fewer of the contacts the account actually saved.+- Saved Baileys contacts are no longer evicted by peers seen once in a group or a broadcast. Both populations shared one capped map, so a busy session answered `GET /api/sessions/:sessionId/contacts` with fewer and fewer of the contacts the account actually saved. `BAILEYS_SESSION_STORE_MAX_ENTRIES` now bounds the peer side of that map; the saved side is bounded by the account's own address book.- A Baileys business prompt no longer offers a call-to-action as a clickable choice. A button that opens a URL or dials a number reached `buttons[]` on `message.received` and was accepted by `POST /api/sessions/:sessionId/messages/click-button`, although WhatsApp has no reply form for it.- A webhook or automation filter written against an `@lid` chat or sender keeps matching once the gateway learns that identity's phone number. Only the event side was resolved through the lid mapping, so an exclusion started delivering the chat it was meant to keep off the wire, and an inclusion stopped delivering, with the rule still reading correctly in the dashboard.- An ingress delivery whose dedup header is present but blank is keyed on the body hash instead of on the empty string. Every such delivery shared one key, so all but the first were dropped with no job enqueued and no dead-letter row, while each provider was answered with the route's success ack.- `POST /api/sessions/:sessionId/automation-rules` answers `404` for a session that does not exist, instead of letting the foreign key surface as `500`.-- A session proxy whose credentials contain a bare `%` is refused when it is set, naming the escape, instead of failing every later start and every proxied URL fetch with an opaque `URI malformed`.+- A session proxy whose credentials contain a bare `%` is refused by `POST /api/sessions` and `PATCH /api/sessions/:sessionId/proxy` when it is set, instead of being stored and then failing every later start and every proxied URL fetch with an opaque `URI malformed`.- A WebSocket handshake whose transport closes while the key is being validated no longer burns a slot of the per-key connection cap for the life of the process.-- Baileys sessions list the saved address book again after a process restart. WhatsApp sends neither history nor an app-state snapshot to a device that has synced once, and the contact store is in memory, so a restarted gateway answered `GET /api/sessions/:sessionId/contacts` with only the peers it had seen since. A reconnect that finds the store empty now re-pulls the snapshot of the app-state collection that carries saved contacts. The list is also the address book only: a peer known by pushname alone is no longer listed, while `GET .../contacts/:contactId` still resolves it with `isMyContact: false`, and a chat title from history sync no longer overwrites a saved name. Thanks @gabrielmmoraes1999.+- Baileys sessions list the saved address book again after a process restart. WhatsApp sends neither history nor an app-state snapshot to a device that has synced once, and the contact store is in memory, so a restarted gateway answered `GET /api/sessions/:sessionId/contacts` with only the peers it had seen since. Each session now re-pulls the snapshot of the app-state collection that carries saved contacts, once per engine start. That also repairs a PARTIAL address book, which is the usual shape: during the initial sync WhatsApp folds saved contacts into the history batch, where their names are stripped as chat titles, so the store keeps plenty of contacts with the saved ones missing. The list is also the address book only: a peer known by pushname alone is no longer listed, while `GET .../contacts/:contactId` still resolves it with `isMyContact: false`, and a chat title from history sync no longer overwrites a saved name. Thanks @gabrielmmoraes1999.- whatsapp-web.js sessions send media again on the WhatsApp Web builds rolled out on 2026-09-17: the library spread the media model into the outgoing message after its id, and the model's private `__x_id` clobbered it, so every image, video, audio, document, sticker and status media send failed with `Data passed to getter must include an id property` while text kept working. An install-time patch carries upstream's one-line fix until a whatsapp-web.js release ships it ([#1643](https://github.com/rmyndharis/OpenWA/issues/1643), [#1636](https://github.com/rmyndharis/OpenWA/issues/1636)). Thanks @15874611923 and @Magnarks for the reports.- An ingress route can declare `dedupOn: "body"` to key provider retries on the raw body instead of the delivery-id header. A provider that mints a fresh delivery id on every retry attempt, as supabase/auth does inside its hook retry loop, was never deduplicated when an ack was lost, so the contact received the message twice; routes that do not declare it keep the header ([#1641](https://github.com/rmyndharis/OpenWA/issues/1641)).- Baileys sessions record a message the account sent from its phone while the gateway was down, and dispatch `message.sent` for it, as they already did for one sent while the gateway was online. The offline replay carried the same `append` tag as the library's echo of an API send, which the upsert handler dropped wholesale; it now skips only the ids this session sent itself, and the phone's reactions, edits and revokes from that window are replayed the same way ([#1667](https://github.com/rmyndharis/OpenWA/issues/1667)).diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 09c0511d3..2680c4631 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2204,7 +2204,9 @@ Edit the text of a message sent by this account; also updates the stored record'**Response** `200`-The edited message keeps its original id.+The edited message keeps its original id, on both engines, so the id you passed is the id you get back.++`timestamp` is the one field the two engines report differently: Baileys answers with the time the edit was sent, whatsapp-web.js re-reads the message and answers with the time the ORIGINAL message was sent. Read the stored message if you need one of the two specifically.```json{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1760000000 }diff --git a/openapi.json b/openapi.jsonindex 0fa582d9f..9c8b1cee0 100644--- a/openapi.json+++ b/openapi.json@@ -913,7 +913,7 @@"description": "The session is not waiting to be linked: the engine is still connecting, or reconnecting after a drop, so the request never reached WhatsApp. Wait for `status` to read `qr_ready` and retry. Once a code has been accepted the session moves through `authenticating` and `initializing` to `ready` and answers this until then; wait for `ready` in that case. A session that reads `ready` is already linked and answers `400` instead. One window answers this while the session still reads `qr_ready`: on the Baileys engine a socket that has begun closing stops accepting a pairing request before the status catches up, which on a silently dropped connection takes until the WebSocket's close timeout (30 s); retry, and the status follows shortly."},"503": {- "description": "The pairing code could not be generated: the gateway stopped waiting after its attempt budget, usually because WhatsApp Web kept reloading its QR page. The condition is transient and the request is worth retrying; the last attempt's reason is carried 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 on this route applies to the retry too. The Baileys engine does not answer this, having no page to reload."+ "description": "The pairing code could not be generated: the gateway stopped waiting after its attempt budget, usually because WhatsApp Web kept reloading its QR page. The condition is transient and the request is worth retrying; the last attempt's reason is carried in the message. An attempt that timed out may still have reached WhatsApp, and a retry starts the linking flow again, with the same risk of unlinking an already-linked device that this route carries generally. The Baileys engine does not answer this, having no page to reload."}},"summary": "Request an 8-char pairing code to link via phone number (alternative to QR)",diff --git a/src/common/openapi/engine-status-responses.ts b/src/common/openapi/engine-status-responses.tsindex 1f8b4eb81..7eac40b7d 100644--- a/src/common/openapi/engine-status-responses.ts+++ b/src/common/openapi/engine-status-responses.ts@@ -46,17 +46,18 @@ export const PAIRING_NOT_READY_409 =/*** `EngineTransportError` (503) on `POST /sessions/:sessionId/pairing-code`, where the whatsapp-web.js* engine bounds each attempt and retries the navigation shapes: WhatsApp Web reloads its QR page every- * few seconds while unpaired, so a request can land mid-navigation. Only an exhausted retry budget is- * reported here. A refusal WhatsApp itself sends is not navigation-shaped and propagates on the first- * attempt instead.+ * few seconds while unpaired, so a request can land mid-navigation. Only an exhausted budget is+ * reported here, and an attempt can exhaust it on a bare timeout with no navigation behind it, so the+ * description says what the gateway knows rather than naming a cause. A refusal WhatsApp itself sends+ * is not navigation-shaped and propagates on the first attempt instead.*/export const PAIRING_TRANSPORT_503 ='The pairing code could not be generated: the gateway stopped waiting after its attempt budget, ' +'usually because WhatsApp Web kept reloading its QR page. The condition is transient and the ' +"request is worth retrying; the last attempt's reason is carried 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 on this route applies to the retry too. The Baileys engine does not answer this, ' +- 'having no page to reload.';+ 'timed out may still have reached WhatsApp, and a retry starts the linking flow again, with the ' ++ 'same risk of unlinking an already-linked device that this route carries generally. The Baileys ' ++ 'engine does not answer this, having no page to reload.';/*** The catalog and status services pass a `NotFoundException` factory to `EngineRegistry.require()`diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.tsindex a9abd1b10..b83b21701 100644--- a/src/engine/adapters/baileys-events.spec.ts+++ b/src/engine/adapters/baileys-events.spec.ts@@ -100,7 +100,6 @@ function makeHost(overrides: Partial<BaileysEventsHost> = {}): BaileysEventsHostrecordMessage: noop,recordMessageEdit: noop,consumeOwnSend: () => false,- rememberOwnSend: noop,getStoredMessage: () => undefined,putStoredMessage: () => undefined,getOnMessage: () => undefined,diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 71b1e2838..ef6cead4a 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -119,8 +119,6 @@ export interface BaileysEventsHost {* is arriving; false for anything the session did not send (see OwnSendRegistry).*/consumeOwnSend(id: string | null | undefined): boolean;- /** Claim an id for {@link consumeOwnSend}, so the next delivery carrying it is taken as a repeat. */- rememberOwnSend(id: string | null | undefined): void;/** A message this session already delivered or sent, from the persistent store; undefined without a store. */getStoredMessage(messageId: string): Promise<WAMessage | null> | undefined;/** The currently-registered onMessage callback, if any (assigned at initialize()). */@@ -179,22 +177,20 @@ export class BaileysEvents {// why the echo has to be caught here, and why a fromMe message the store already holds is// dropped in processInboundMessage before it can be reported a second time.//- // One gate catches both repeats. `consume` is true for the echo of a send this session made- // through the API, whose id the send path recorded, and for a second delivery of a fromMe- // message this handler has already taken, because it claims the id below. Claiming is what- // makes the second case work: the store check in processInboundMessage sits behind an await- // and can only see ids the store has committed, so two deliveries landing inside that window- // would both be reported. This runs before any await, so they cannot.- if (msg.key.fromMe === true) {- const alreadyTaken = this.host.consumeOwnSend(msg.key.id);- this.host.rememberOwnSend(msg.key.id);- if (alreadyTaken) {- this.host.logger.debug('Skipping a message this session has already reported', {- msgId: msg.key.id ?? 'unknown',- type: event.type,- });- continue;- }+ // Only ids this session SENT are consumed here. Claiming every inbound fromMe id instead, to+ // close the window where two deliveries of one id arrive before the store write commits, costs+ // more than it buys: a first delivery that reports nothing (a partial decrypt arrives as+ // protocol noise and is dropped below) would claim the id, and the decryption-retry delivery+ // that carries the real body would then be swallowed as a repeat and the message lost. A+ // repeat inside that narrow window is a duplicate, which the webhook idempotency key and the+ // insert oracle both absorb; a loss is not recoverable, because Baileys acks the node before+ // it emits the upsert.+ if (msg.key.fromMe === true && this.host.consumeOwnSend(msg.key.id)) {+ this.host.logger.debug('Skipping the echo of a message this session sent', {+ msgId: msg.key.id ?? 'unknown',+ type: event.type,+ });+ continue;}// Throttle through the limiter so a burst of media messages can't run unbounded parallel// downloads (each a full decrypted buffer in heap). Ordering stays correct — the message store@@ -403,9 +399,10 @@ export class BaileysEvents {* Deliberately fail-open: a locked database or a row whose JSON no longer parses must not be read* as "this was never sent". The caller's only other outcome is the catch above, which drops the* message outright, and Baileys acks the node before it emits the upsert, so WhatsApp does not- * send it again. A repeat is recoverable downstream (same idempotency key on the webhook, and the- * insert oracle holds the row to one); a message nobody ever hears about is not. The persist side- * of the same store is already written this way.+ * send it again. A repeat is absorbed where it matters: the webhook carries the same idempotency+ * key and the insert oracle holds the row to one. A WebSocket subscriber does see the frame twice,+ * which is the price paid here deliberately, because a message nobody ever hears about cannot be+ * recovered at all. The persist side of the same store is already written this way.*/private async readStoredMessage(messageId: string): Promise<WAMessage | null> {try {diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.tsindex 8af9ac958..d92d1f6ca 100644--- a/src/engine/adapters/baileys-history.ts+++ b/src/engine/adapters/baileys-history.ts@@ -31,9 +31,9 @@ export interface BaileysHistoryHost {upsertContacts(records: Partial<BaileysContact>[]): void;upsertChats(records: Partial<Chat>[]): void;/**- * How many contacts the in-memory session store currently holds. Used to decide whether a- * reconnect must re-pull the address-book snapshot (Baileys skips history + app-state snapshot- * once `accountSyncCounter > 0`, and this store does not survive a process restart).+ * How many saved contacts the in-memory session store currently holds. Reported alongside the+ * address-book restore so a log line says what the pull was worth; it does not decide whether the+ * pull happens, because a partial address book counts as plenty (see restoreAddressbookSnapshot).*/contactCount(): number;/** The chat's cached disappearing-messages timer extraction (`msg.ephemeralDuration` primary). */@@ -111,13 +111,13 @@ export class BaileysHistory {** On a reconnect (`accountSyncCounter > 0`) Baileys skips history sync and the address-book snapshot* entirely: WhatsApp assumes the linked device kept its local copy. This gateway's contact store is- * in-memory, so a process restart leaves GET /contacts empty. Once per connection we therefore drop+ * in-memory, so a process restart leaves GET /contacts empty. Once per engine instance we therefore drop* the stored version of the contact collection (so the next resync asks for a snapshot, not an* incremental patch) and process its mutations as an initial sync, which is what emits* `contacts.upsert` for the saved address book. The other collections keep the incremental resync* below.*- * Once per connection, not "only when no saved contact is held": during the initial sync the event+ * Once per engine instance, not "only when no saved contact is held": during the initial sync the event* buffer folds an app-state `contacts.upsert` into a `messaging-history.set` record it is already* holding for that id (`absorbed contact upsert in contact set` in Baileys' event-buffer), and the* whole initial sync is buffered as one batch, so those saved names arrive only inside the history@@ -155,8 +155,15 @@ export class BaileysHistory {}const alreadySynced = (this.sock().authState?.creds?.accountSyncCounter ?? 0) > 0;if (alreadySynced && !this.addressbookRestored) {+ // Set before the await so a second connect cannot start a concurrent pull, and cleared again+ // if it fails, so one bad attempt does not count as the one pull this instance gets.this.addressbookRestored = true;- await this.restoreAddressbookSnapshot();+ try {+ await this.restoreAddressbookSnapshot();+ } catch (err) {+ this.addressbookRestored = false;+ throw err;+ }}await this.sock().resyncAppState(collections, false);this.host.logger.debug('Re-synced app state for contact names', { action: 'baileys_resync_appstate' });diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 6ef0959ae..7b4574cf1 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -601,6 +601,23 @@ describe('BaileysSessionStore', () => {expect(s.findContact('[email protected]')).toBeNull();});+ it('still caches peers once the saved contacts alone fill the cap', () => {+ // The cap governs the peer population. Measuring the whole map instead made a full address+ // book evict each new peer in the very call that inserted it, so `GET /contacts/:id` stopped+ // resolving anyone who is not saved, and chat titles fell back to the raw number.+ const s = storeWithCap('2');+ s.upsertContacts([{ id: '[email protected]', name: 'Alice' }]);+ s.upsertContacts([{ id: '[email protected]', name: 'Bob' }]);++ s.upsertContacts([{ id: '[email protected]', notify: 'peer one' }]);+ s.upsertContacts([{ id: '[email protected]', notify: 'peer two' }]);++ expect(s.findContact('[email protected]')?.pushName).toBe('peer one');+ expect(s.findContact('[email protected]')?.pushName).toBe('peer two');+ expect(s.findContact('[email protected]')?.name).toBe('Alice');+ expect(s.findContact('[email protected]')?.name).toBe('Bob');+ });+it('keeps the saved address book when unsaved peers overflow the cap', () => {// The two populations share one map: a handful of contacts the account saved, and every peer// seen once in a group or a broadcast. Only the second grows without limit, and it used to@@ -693,6 +710,8 @@ describe('BaileysSessionStore', () => {// Unsaved peers: the cap governs exactly this population (a saved contact is pinned).s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net`, notify: 'x' })));expect(s.findContact('[email protected]')).toBeNull(); // the oldest went first+ // Only the oldest: one entry over a 5000 cap evicts exactly one, which is what pins the default.+ expect(s.findContact('[email protected]')).not.toBeNull();expect(s.findContact('[email protected]')).not.toBeNull();});@@ -700,6 +719,7 @@ describe('BaileysSessionStore', () => {const s = storeWithCap('');s.upsertContacts(Array.from({ length: 5001 }, (_, i) => ({ id: `62${100000 + i}@s.whatsapp.net`, notify: 'x' })));expect(s.findContact('[email protected]')).toBeNull();+ expect(s.findContact('[email protected]')).not.toBeNull();expect(s.findContact('[email protected]')).not.toBeNull();});});diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 83730687d..07eea6d08 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -21,19 +21,42 @@ export const SESSION_STORE_MAP_CAP_DEFAULT = 5000;* write re-inserts the key at the most-recent end, and a set evicts the least-recently-used entry* while over `max`. `max = 0` means unbounded.*- * `pinned` marks entries an eviction must skip while any unpinned entry is older. It exists for the- * contacts map, where two populations share one cap: the account's own address book, which the- * operator curated and which the API reports, and a much larger stream of peers seen once in a group- * or a broadcast. Without it the second evicts the first.+ * `pinned` marks entries eviction may never take. It exists for the contacts map, where two+ * populations share one structure: the account's own address book, which the operator curated and+ * which the API reports, and a much larger stream of peers seen once in a group or a broadcast.+ * Without it the second evicts the first.+ *+ * The cap then governs the UNPINNED population alone, which is the one that grows from peer traffic.+ * Counting the whole map instead would make a full address book evict each new peer in the same call+ * that inserted it, so peers would stop being cached at all once the saved set reached the cap. The+ * pinned side is bounded by the account's own contact list rather than by this number.*/class LruMap<K, V> {private readonly map = new Map<K, V>();+ /** Entries the predicate does not protect. The cap is measured against exactly these. */+ private unpinned = 0;+constructor(private readonly max: number,private readonly pinned?: (value: V) => boolean,) {}+ private isPinned(value: V): boolean {+ return this.pinned ? this.pinned(value) : false;+ }++ /** Remove a key while keeping {@link unpinned} honest. No-op for a key that is not held. */+ private drop(key: K): void {+ if (!this.map.has(key)) {+ return;+ }+ if (!this.isPinned(this.map.get(key) as V)) {+ this.unpinned--;+ }+ this.map.delete(key);+ }+has(key: K): boolean {return this.map.has(key);}@@ -49,17 +72,20 @@ class LruMap<K, V> {}set(key: K, value: V): void {- this.map.delete(key);+ this.drop(key);this.map.set(key, value);+ if (!this.isPinned(value)) {+ this.unpinned++;+ }if (!this.max) {return;}- while (this.map.size > this.max) {+ while (this.unpinned > this.max) {const victim = this.oldestEvictable();if (victim === undefined) {- break; // every entry is pinned: keep them all rather than drop curated data+ break; // unreachable while unpinned > 0, and a safe stop if it ever is not}- this.map.delete(victim);+ this.drop(victim);}}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 7cfa3d9c4..bb007d8e0 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2419,28 +2419,6 @@ describe('BaileysAdapter inbound fan-out', () => {expect(onMessageCreate).toHaveBeenCalledTimes(1);});- // The store write is fire-and-forget and only issued after the dispatch, so two deliveries of one- // id landing before it commits both read an empty store. The id is claimed synchronously when the- // batch is taken, which is the only point early enough to catch them.- it('does not dispatch a phone-sent message twice when both deliveries land before the store commits', async () => {- const replayed = {- key: { remoteJid: '[email protected]', fromMe: true, id: 'TYPED_ON_PHONE' },- message: { conversation: 'replied from the phone during the outage' },- messageTimestamp: Math.floor(Date.now() / 1000) - 3600,- };- const onMessageCreate = jest.fn();- const adapter = newAdapter();- await adapter.initialize({ onMessageCreate });- fakeSock.fire('connection.update', { connection: 'open' });-- // Both in the same tick: nothing has been written to the store in between.- fakeSock.fire('messages.upsert', { type: 'append', messages: [replayed] });- fakeSock.fire('messages.upsert', { type: 'append', messages: [replayed] });- await new Promise(r => setImmediate(r));-- expect(onMessageCreate).toHaveBeenCalledTimes(1);- });-// A store that cannot answer must not be read as "this was never sent": the only other outcome is// the handler's catch, which drops the message, and Baileys acks the node before emitting it, so// WhatsApp never sends it again. Fail open, and take the duplicate risk instead of the loss.diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex b5012893c..b2090cefb 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -235,6 +235,19 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {sock.emit.mockClear();const pong = await gateway.handleMessage(asSocket(sock), { type: 'ping' } as unknown as WSClientMessage);expect(sock.emit).toHaveBeenCalledWith('message', pong);++ sock.emit.mockClear();+ const unsubscribed = await gateway.handleMessage(asSocket(sock), {+ type: 'unsubscribe',+ sessionId: 'sess-1',+ events: ['message.received'],+ } as unknown as WSClientMessage);+ expect(sock.emit).toHaveBeenCalledWith('message', unsubscribed);++ sock.emit.mockClear();+ const unknown = await gateway.handleMessage(asSocket(sock), { type: 'nonsense' } as unknown as WSClientMessage);+ expect((unknown as WSErrorResponse).code).toBe('INVALID_MESSAGE');+ expect(sock.emit).toHaveBeenCalledWith('message', unknown);});it('forbids a session-scoped key from subscribing to the * wildcard', async () => {diff --git a/src/modules/session/dto/session-proxy-credentials.spec.ts b/src/modules/session/dto/session-proxy-credentials.spec.tsindex 2566ee953..2183007ae 100644--- a/src/modules/session/dto/session-proxy-credentials.spec.ts+++ b/src/modules/session/dto/session-proxy-credentials.spec.ts@@ -1,23 +1,55 @@-import { validate } from 'class-validator';-import { plainToInstance } from 'class-transformer';+import { BadRequestException, ValidationPipe } from '@nestjs/common';+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';import { UpdateSessionProxyDto } from './session-proxy.dto';+import { CreateSessionDto } from './create-session.dto';-describe('UpdateSessionProxyDto proxy credential escapes', () => {- const errorsFor = async (proxyUrl: string): Promise<string[]> => {- const dto = plainToInstance(UpdateSessionProxyDto, { proxyUrl });- const errors = await validate(dto);- return errors.flatMap(e => Object.values(e.constraints ?? {}));+/**+ * A proxy URL whose credentials carry a percent that begins no escape passes `@IsUrl` and `new URL()`,+ * and only throws later, inside whichever library decodes it. Both routes that accept one must refuse+ * it at the boundary, so this drives the real global pipe rather than the validator alone.+ */+describe('proxy credential escapes on both routes that accept a proxy URL', () => {+ const pipe = new ValidationPipe(GLOBAL_VALIDATION_OPTIONS);+ const through = (metatype: unknown, value: object): Promise<unknown> =>+ pipe.transform(value, { type: 'body', metatype: metatype as never });++ const BAD = 'http://u:pa%[email protected]:8080';++ /** The per-field messages the pipe collects, which is where a constraint's own wording lands. */+ const messagesFrom = async (metatype: unknown, value: object): Promise<string[]> => {+ try {+ await through(metatype, value);+ } catch (error) {+ expect(error).toBeInstanceOf(BadRequestException);+ const body = (error as BadRequestException).getResponse() as { message?: string[] };+ return body.message ?? [];+ }+ throw new Error('expected the pipe to reject');};- it('rejects credentials carrying a percent that begins no escape', async () => {- expect(await errorsFor('http://u:pa%[email protected]:8080')).toEqual([- expect.stringContaining('invalid percent-escape'),+ it('refuses it on the proxy update route, naming the escape', async () => {+ expect(await messagesFrom(UpdateSessionProxyDto, { proxyUrl: BAD })).toEqual([+ expect.stringContaining('percent-escape'),]);});- it('accepts a properly escaped percent and an ordinary credentialed URL', async () => {- expect(await errorsFor('http://u:pa%[email protected]:8080')).toEqual([]);- expect(await errorsFor('socks5://user:p%[email protected]:1080')).toEqual([]);- expect(await errorsFor('http://proxy.local:8080')).toEqual([]);+ it('refuses it on the session create route', async () => {+ expect(await messagesFrom(CreateSessionDto, { name: 'sess', proxyUrl: BAD })).toEqual([+ expect.stringContaining('percent-escape'),+ ]);+ });++ it('accepts an escaped percent, an encoded credential and no credentials at all', async () => {+ await expect(+ through(UpdateSessionProxyDto, { proxyUrl: 'http://u:pa%[email protected]:8080' }),+ ).resolves.toBeDefined();+ await expect(+ through(UpdateSessionProxyDto, { proxyUrl: 'socks5://user:p%[email protected]:1080' }),+ ).resolves.toBeDefined();+ await expect(through(UpdateSessionProxyDto, { proxyUrl: 'http://proxy.local:8080' })).resolves.toBeDefined();+ });++ it('leaves clearing the proxy with null alone', async () => {+ await expect(through(UpdateSessionProxyDto, { proxyUrl: null })).resolves.toBeDefined();});});