If you find this project helpful, consider following me on GitHub.
toxic-baileys™

Hey! 👋 This is toxic-baileys — a souped-up, feature-packed fork of the Baileys WhatsApp Web API. If you want rock-solid WhatsApp automation with LID identity mapping, AI group support, cross-platform interoperability, extended message types, and much better connection handling, you are in the right place 🙂
Maintainer: 𝐱𝐡_𝐜𝐥𝐢𝐧𝐭𝐨𝐧
[!IMPORTANT]
LID Mapping — Critical Feature in This Fork
WhatsApp has rolled out Linked Identity (LID) JIDs as part of its cross-platform interoperability initiative. Group messages and status updates now arrive with @lid domain JIDs instead of standard @s.whatsapp.net phone-number JIDs. Without LID resolution, you cannot identify who sent a message in many groups.
This fork ships a complete LIDMappingStore (bidirectional LRU cache + persistent key store) and UsyncLIDProtocol so your bot always knows the real phone number behind every @lid JID. See the LID Mapping System section for full integration details.
- 🚀 What's New
- ✨ Features
- 📦 Installation
- ⚡ Quick Start
- 🔌 Connection & Configuration
- 🔑 Authentication State Management
- 🧠 LID Mapping System
- 🤖 AI Groups
- 🔗 Interoperability API
- 📡 USync Protocol
- 💬 Sending Messages
- Basic Messages
- Media Messages
- Interactive Messages
- Album Messages
- Event Messages
- Poll & Poll Result Messages
- Group Status Messages
- Payment Request Messages
- Product Messages
- Button & Template Messages
- 🛠️ Rich Message Builders
- 💭 Chat & Message Management
- 👥 Group Management
- 👤 User & Profile Management
- ✏️ Username Management
- 📢 Newsletter / Channel Management
- 🔒 Privacy & Block Management
- 💾 Data Store Implementation
- 🧰 Utility Functions
- 💡 Best Practices & Tips
- ⚠️ Important Legal Notice
- 🆘 Getting Help
- 📜 License
🚀 What's New
This update pulls in a batch of fixes and improvements from upstream Baileys and merges them into the existing feature set without touching any of the custom stuff (ToxicHandler, AI groups, interop, LID mapping, group status).
New in 1.6.0:
-
Pairing codes work again — and fail loudly when they should. The pairing key derivation now matches WhatsApp's protocol (PBKDF2), fixing codes that were always rejected while QR worked. On top of that, pairing requests wait for the server's readiness stanza, surface real server errors instead of dying silently, and can't be double-fired.
-
Retries actually recover sessions now. When a contact asks for a resend, the session bundle inside their retry receipt is used to rebuild the session, stale sessions are detected via registration-id/base-key checks, and group resends carry the sender-key distribution so people can actually decrypt.
-
Sessions stop dying for silly reasons. Auth files are written atomically (no more corrupted creds.json after a crash), undecryptable echoes from your own other devices no longer trigger stream-killing retry loops, and <status> stanzas are acked so the server doesn't end the stream.
-
Browsers.android is available for sessions that need to present as Android, and pre-key uploads are deduplicated the way WhatsApp Web does it.
-
LID lookups are faster and less wasteful. The LID mapping store now batches and coalesces concurrent lookups instead of firing off duplicate requests, and it has a proper close() for shutting it down cleanly.
-
A real username API. checkUsername, setUsername, getMyUsername, findUserByUsername, fetchContactUsernames, and a couple more — see Username Management. Also added USyncPictureProtocol and USyncTextStatusProtocol for fetching profile pictures and text statuses via USync directly.
-
New AIRich, Button, ButtonV2, Carousel, and Toolkit builders. See the Rich Message Builders section — chainable APIs for buttons, carousels, and Meta AI-style rich responses with inline citations, LaTeX, code blocks, and tables. Each one also has a couple of shorter alias names if you'd rather import it as something else.
-
sendInteractive (aka inappsignup / inapp_signup). Sends interactive buttons, and automatically falls back to a plain text message if the bot's own paired device is iOS, since buttons don't reliably show up there.
-
Profile pictures no longer crop lopsided. generateProfilePicture was cropping non-square photos from the top-left corner instead of the center — fixed, so the whole subject stays in frame instead of getting cut off to one side.
-
App state sync no longer gives up on the first bad patch. If a single patch fails to decode or a hash check comes back wrong, it logs a warning and keeps syncing instead of throwing and killing the whole sync.
-
Event buffer actually cleans up after itself now. destroy() clears pending timers and listeners when the socket closes, instead of just being a name with nothing behind it.
-
Spoofed protocol messages get dropped. This covers the message-spoofing/app-state-corruption issue reported in GHSA-qvv5-jq5g-4cgg (CVE-2026-48063) — history sync notifications, app state key shares, and placeholder-resend responses that don't actually come from your own account (fromMe) are now rejected instead of processed.
-
Media downloads fall back to the right host. Instead of always assuming mmg.whatsapp.net, downloads now use the host from the message itself when one is present.
-
getChatId fails loudly instead of quietly. Missing remoteJid/participant now throws a clear error instead of silently working with undefined.
-
Profile picture fetching cleaned up to match the newer, simpler query-building approach upstream uses.
-
Group presence updates now carry groupOnlineCount when WhatsApp sends it.
-
Dependency versions and resolutions bumped to match what upstream is currently shipping.
Compared to upstream Baileys, this fork adds:
| Feature |
Description |
| LID Mapping System |
Full LIDMappingStore with LRU cache, persistent key store, bidirectional lookups, and UsyncLIDProtocol |
| AI Groups |
makeAIGroupsSocket — create, manage, and receive events for WhatsApp AI-powered groups |
| Interoperability API |
makeInteropSocket — fetch third-party integrators, accept Interop TOS, opt in/out |
| USync Protocol Layer |
Full WAUSync module: LID, Contact, Device, Disappearing Mode, Status, Text Status, Picture, Username, Bot Profile protocols |
| MEX / GraphQL Queries |
executeWMexQuery for structured WhatsApp server queries via the w:mex IQ namespace |
me.lid Credential |
Bot's own LID identity stored in credentials on pairing via configureSuccessfulPairing |
lidDbMigrated Login Flag |
Signals to WhatsApp to push down LID mappings on connect |
| Group Status V2 |
ToxicHandler exposed on socket for rich group story/status management |
SignalRepositoryWithLIDStore |
Extended signal repository type that exposes lidMapping directly on the socket |
newsletterId() Helper |
Utility to extract a clean newsletter/channel ID from any JID format |
✨ Features
A quick tour of what you get out of the box 🙂
- Modern & Fast — Latest WA version
[2,3000,1035194821], optimised pre-key upload (812 keys)
- Full LID Identity Resolution — Bidirectional LIDPN mapping with LRU cache, USync lookup, and persistent storage
- AI Groups Support — Create and manage WhatsApp's AI-powered group type
- Cross-Platform Interop — Third-party integrator management (BirdyChat, Haiket, and more)
- Enhanced Stability — Improved connection handling, socket end handlers,
ev.destroy() on close, cleaner pre-key retry logic
- Multi-Device Support — Full WhatsApp multi-device protocol with improved
historySyncConfig
- End-to-End Encryption — Signal Protocol,
inlineInitialPayloadInE2EeMsg: true
- Extended Message Types — Interactive, album, event, poll result, group status, payment, product
- Advanced Group Management — Group controls, group status V2, communities support
- Flexible Auth — Multi-file auth state with
makeCacheableSignalKeyStore
- Full Newsletter/Channel API — Follow, create, metadata,
newsletterId() helper, fixed join/leave v2 endpoints
- Developer Friendly —
toxicHandler and ToxicHandler exposed on socket, fetchAccountReachoutTimelock, fetchNewChatMessageCap, registerSocketEndHandler, clean API
- WebSocket Improvements —
perMessageDeflate: false, 100 MB max payload
📦 Installation
Pick whichever one suits you 🙂
Via npm
npm install toxic-baileys
Via Yarn
yarn add toxic-baileys
From GitHub (edge)
npm install github:xhclintohn/Baileys
Drop-in replacement for @whiskeysockets/baileys
{
"dependencies": {
"@whiskeysockets/baileys": "npm:toxic-baileys@latest"
}
}
⚡ Quick Start
Get connected in under a minute 🙂
import makeWASocket, { useMultiFileAuthState, DisconnectReason } from 'toxic-baileys';
import { Boom } from '@hapi/boom';
async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
const sock = makeWASocket({ auth: state, printQRInTerminal: true });
sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
if (connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) connectToWhatsApp();
} else if (connection === 'open') {
console.log('Connected! Bot LID:', sock.user?.lid);
}
});
sock.ev.on('messages.upsert', async ({ messages }) => {
for (const m of messages) {
if (!m.message) continue;
console.log('Message:', JSON.stringify(m, undefined, 2));
}
});
sock.ev.on('creds.update', saveCreds);
}
connectToWhatsApp().catch(console.error);
import makeWASocket, { useMultiFileAuthState } from 'toxic-baileys';
async function connectWithPairing() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
const sock = makeWASocket({ auth: state, printQRInTerminal: false });
sock.ev.on('creds.update', saveCreds);
if (!sock.authState.creds.registered) {
const phoneNumber = '254712345678'; // no + or spaces
const code = await sock.requestPairingCode(phoneNumber);
console.log('Pairing Code:', code);
}
}
connectWithPairing().catch(console.error);
🔌 Connection & Configuration
Tune how your bot connects to WhatsApp 🙂
import makeWASocket, { Browsers, makeCacheableSignalKeyStore } from 'toxic-baileys';
import NodeCache from '@cacheable/node-cache';
const groupCache = new NodeCache({ stdTTL: 300, useClones: false });
const sock = makeWASocket({
browser: Browsers.macOS('Chrome'),
syncFullHistory: true,
markOnlineOnConnect: false,
connectTimeoutMs: 60_000,
defaultQueryTimeoutMs: 60_000,
keepAliveIntervalMs: 30_000,
generateHighQualityLinkPreview: true,
cachedGroupMetadata: async (jid) => groupCache.get(jid),
getMessage: async (key) => await yourStore.getMessage(key),
});
sock.ev.on('groups.update', async ([event]) => {
const metadata = await sock.groupMetadata(event.id);
groupCache.set(event.id, metadata);
});
🔑 Authentication State Management
How your bot remembers who it is between restarts 🙂
import makeWASocket, { useMultiFileAuthState } from 'toxic-baileys';
const { state, saveCreds } = await useMultiFileAuthState('./auth_info');
const sock = makeWASocket({ auth: state });
sock.ev.on('creds.update', saveCreds);
import makeWASocket, { makeCacheableSignalKeyStore } from 'toxic-baileys';
const myAuthState = {
creds: await db.getAuthCreds(),
keys: makeCacheableSignalKeyStore(await db.getSignalKeys(), console)
};
const sock = makeWASocket({ auth: myAuthState });
sock.ev.on('creds.update', async (creds) => await db.saveAuthCreds(creds));
🧠 LID Mapping System
[!IMPORTANT]
This is one of the most critical new features in this fork. WhatsApp is migrating groups to use Linked Identity (LID) JIDs — identifiers in the @lid domain that replace @s.whatsapp.net phone-number JIDs for privacy and cross-platform reasons. If you receive a message from 1234567890:0@lid and don't have a mapping, you cannot identify the sender.
A Linked Identity (LID) is an opaque numeric identifier assigned to each WhatsApp account in the @lid domain. WhatsApp uses LIDs in groups to decouple a person's phone number from their group identity. The LID is stable across phone number changes and is used for the Signal encryption protocol in newer group types.
Standard JID: 254712345678@s.whatsapp.net phone number visible
LID JID: 9876543210:0@lid opaque — phone number hidden
This fork implements LIDMappingStore in src/Signal/lid-mapping.ts:
┌─────────────────────────────────────────────────────┐
│ LIDMappingStore │
│ │
│ LRU Cache (3-day TTL, auto-purge) │
│ pn:{pnUser} lidUser │
│ lid:{lidUser} pnUser │
│ │
│ SignalKeyStoreWithTransaction │
│ lid-mapping/{pnUser} lidUser │
│ lid-mapping/{lidUser}_reverse pnUser │
│ │
│ USync Lookup (UsyncLIDProtocol) │
│ Query WhatsApp servers via w:sync IQ │
└─────────────────────────────────────────────────────┘
Persistent file naming (with useMultiFileAuthState):
Session/
lid-mapping-{pnUser}.json pnUser lidUser
lid-mapping-{lidUser}_reverse.json lidUser pnUser (reverse lookup)
When your bot pairs with WhatsApp, its own LID is stored in the session credentials:
// Stored automatically by configureSuccessfulPairing()
// Access it any time after connecting:
const myLid = sock.user?.lid;
console.log('My LID:', myLid); // e.g. "9876543210@lid"